0% found this document useful (0 votes)
6 views88 pages

ch06 객체지향게임 88

The document outlines lectures on using Pygame to create object-oriented classes for animations, including a Ball class for bouncing balls and a SimpleButton class for interactive buttons. It details the implementation steps, such as importing packages, defining classes, handling events, and updating the display. The content serves as a foundational guide for developing interactive games and animations in Pygame.

Uploaded by

jom091979
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views88 pages

ch06 객체지향게임 88

The document outlines lectures on using Pygame to create object-oriented classes for animations, including a Ball class for bouncing balls and a SimpleButton class for interactive buttons. It details the implementation steps, such as importing packages, defining classes, handling events, and updating the display. The content serves as a foundational guide for developing interactive games and animations in Pygame.

Uploaded by

jom091979
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Spring 2025

OOP:
객체지향 파이게임

Seonah Lee
GNU

1
Contents

 Ball Class
 Ball Bounce Using Ball Class
 Multiple Ball Bounce

 SimpleButton Class
 SimpleButton Test
 3-Button Test

 SimpleText Class
 Ball, Text, and Button Demo
 Button Callback

2
Lecture on Defining and Animating a Ball Class Using Pygame

PYGAME BALL CLASS

3
Overview

4
1. Importing Packages

 import pygame
 from pygame.locals import *
 import random

 `pygame`:
 Library for developing games and multimedia applications.
 `pygame.locals`:
 Provides access to Pygame constants for ease of use.
 `random`:
 Generates random numbers used for initial ball placement and speed.

5
2. Defining the Ball Class

 class Ball():
 def __init__(self, window, windowWidth, windowHeight):
 self.window = window
 self.windowWidth = windowWidth
 self.windowHeight = windowHeight
 self.image = pygame.image.load('images/ball.png')

 Defines a `Ball` class that will represent a moving ball.


 The constructor (`__init__`) takes the game window and its dimensions as
parameters.
 Stores these values for use in drawing and movement calculations.
 Loads the ball image

6
3. Initializing Ball Properties

 ballRect = self.image.get_rect()
 self.width = ballRect.width
 self.height = ballRect.height
 self.maxWidth = windowWidth - self.width
 self.maxHeight = windowHeight - self.height

 - Determines its size.


 - Calculates the maximum x and y values
 the ball can reach within the window.

7
4. Randomizing Ball Position and Speed

 self.x = random.randrange(0, self.maxWidth)


 self.y = random.randrange(0, self.maxHeight)

 speedsList = [-4, -3, -2, -1, 1, 2, 3, 4]


 self.xSpeed = random.choice(speedsList)
 self.ySpeed = random.choice(speedsList)

 - Sets a random starting position within the allowed area.


 - Randomly assigns speeds in both x and y directions, ensuring that the speed is
never zero.

8
5. Updating Ball Movement

 def update(self):
 if (self.x < 0) or (self.x >= self.maxWidth):
 self.xSpeed = -self.xSpeed
 if (self.y < 0) or (self.y >= self.maxHeight):
 self.ySpeed = -self.ySpeed
 self.x = self.x + self.xSpeed
 self.y = self.y + self.ySpeed

 - Checks if the ball has hit the window edges


 Reverses the movement direction.
 - Updates the ball's position using its speed values.

9
6. Drawing the Ball on the Window

 def draw(self):
 self.window.blit(self.image, (self.x, self.y))

 - Draws the ball on the game window at its current position.


 - `blit` method places the image at the specified (x, y) coordinates.

10
Conclusion

 This `Ball` class demonstrates:


 - Object-oriented programming in Pygame.
 - Random initialization of object position and speed.
 - Continuous movement and collision detection with window edges.

 This class can serve as a foundational element for games or interactive


animations.

11
Lecture on Using a Custom Ball Class for Animation in Pygame

PYGAME BALL BOUNCE USING BALL CLASS

12
Program

13
Overview

14
1. Importing Packages

 import pygame
 from pygame.locals import *
 import sys
 import random
 from Ball import *

 - `pygame`: Main library for creating multimedia applications and games.


 - `pygame.locals`: Provides access to commonly used Pygame constants.
 - `sys`: Enables interaction with the system, including exiting the program.
 - `random`: Generates random numbers for initializing variables.
 - `Ball`: Imports the custom `Ball` class from the Ball module.

15
2. Defining Constants

 BLACK = (0, 0, 0)
 WINDOW_WIDTH = 640
 WINDOW_HEIGHT = 480
 FRAMES_PER_SECOND = 30

 - Defines the screen size, background color, and frame rate.


 - Sets the refresh rate for the game loop to 30 frames per second.

16
3. Initializing the World

 pygame.init()
 window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
 clock = pygame.time.Clock()

 - Initializes all Pygame modules for the game.


 - Creates a game window with the specified dimensions.
 - Sets up a clock object to regulate the frame rate.

17
4. Initializing the Ball Object

 oBall = Ball(window, WINDOW_WIDTH, WINDOW_HEIGHT)

 - Creates an instance of the `Ball` class.


 - Passes the game window and its dimensions as parameters for the ball's
behavior and drawing.

18
5. Event Handling Loop

 for event in pygame.event.get():


 if event.type == pygame.QUIT:
 pygame.quit()
 sys.exit()

 - Listens for user events, particularly the quit event.


 - Exits the game gracefully when the user closes the window.

19
6. Updating and Drawing the Ball

 oBall.update()
 window.fill(BLACK) Explain it
 oBall.draw()

 - Calls the `update()` method to update the ball's position.


 - Clears the screen by filling it with black before redrawing.
 - Draws the ball at its new position using the `draw()` method.

20
7. Updating the Window and Controlling
Frame Rate
 pygame.display.update()
 clock.tick(FRAMES_PER_SECOND) Explain it

 - Refreshes the display with the latest drawn frame.


 - Limits the game's frame rate to ensure smooth animation.

21
Conclusion

 This program demonstrates:


 - Using an object-oriented approach to manage game elements.
 - Integrating a custom class (`Ball`) for animation and interaction.
 - Handling events, updating objects, and refreshing the display in a game loop.

 This structure serves as a foundation for creating interactive games in Pygame.

22
Lecture on Animating Multiple Balls Using the Ball Class in Pygame

PYGAME MULTIPLE BALL BOUNCE

23
Program

24
Overview

25
1. Importing Packages

 import pygame
 from pygame.locals import *
 import sys
 import random
 from Ball import *

 - `pygame`: Main library for creating games and multimedia applications.


 - `pygame.locals`: Provides easy access to commonly used Pygame constants.
 - `sys`: Allows interaction with the operating system, including exiting the
program.
 - `random`: Generates random numbers for initialization.
 - `Ball`: Imports the custom Ball class for handling ball behavior.

26
2. Defining Constants

 BLACK = (0, 0, 0)
 WINDOW_WIDTH = 640
 WINDOW_HEIGHT = 480
 FRAMES_PER_SECOND = 30
 N_BALLS = 3

 - Defines color, window size, and frame rate.


 - `N_BALLS`: Specifies the number of ball objects to animate simultaneously.

27
3. Initializing the World

 pygame.init()
 window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
 clock = pygame.time.Clock()

 - Initializes Pygame modules for the game.


 - Sets up the display window with specified dimensions.
 - Initializes the clock to regulate the frame rate.

28
4. Creating Multiple Ball Objects

 ballList = []
Explain it
 for oBall in range(0, N_BALLS):
 oBall = Ball(window, WINDOW_WIDTH, WINDOW_HEIGHT)
 ballList.append(oBall)

 - Initializes an empty list to store multiple `Ball` objects.


 - Uses a loop to create and add each ball object to the list.

29
5. Event Handling Loop

 for event in pygame.event.get():


 if event.type == pygame.QUIT:
 pygame.quit()
 sys.exit()

 - Listens for system events.


 - Exits the program when the close button is clicked.

30
6. Updating and Drawing Each Ball

 for oBall in ballList:


 oBall.update() Explain it
 window.fill(BLACK)
 for oBall in ballList:
 oBall.draw()
 pygame.display.update()
 clock.tick(FRAMES_PER_SECOND)

 - Updates each ball's position based on its speed and direction.


 - Clears the screen before redrawing all balls in their new positions.
 - Updates the window to reflect new positions of all balls.
 - Controls the frame rate to ensure smooth animation.

31
Conclusion

 This program demonstrates:


 - Managing multiple animated objects using a list of `Ball` objects.
 - Using loops to handle multiple instances for updates and drawing.
 - Creating interactive animations with multiple moving elements.

 This technique is fundamental for games involving multiple moving objects.

32
Lecture on Creating an Interactive Button in Pygame

PYGAME SIMPLEBUTTON CLASS

33
Overview

34
1. Importing Packages

 import pygame
 from pygame.locals import *

 - `pygame`: Main library for developing games and multimedia applications.


 - `pygame.locals`: Provides access to commonly used constants in Pygame for
event handling.

35
2. Defining Button States

 class SimpleButton()
 STATE_IDLE = 'idle' # Button is up, mouse not over button
 STATE_ARMED = 'armed' # Button is down, mouse over button
 STATE_DISARMED = 'disarmed’
 # Mouse rolled off the button after being clicked

 - Uses a state machine to track the button's interaction states.


 - Helps handle different user interactions effectively.

36
3. Initializing the Button Object

 def __init__(self, window, loc, up, down):


 self.window = window
 self.loc = loc
 self.surfaceUp = pygame.image.load(up)
 self.surfaceDown = pygame.image.load(down)

 self.rect = self.surfaceUp.get_rect()
 self.rect[0] = loc[0]
 self.rect[1] = loc[1]

 self.state = SimpleButton.STATE_IDLE

 - Sets up button visuals and positioning using image assets.


 - Initializes the button's default state as `IDLE`.
 - Defines the clickable area using a rectangle.

37
4. Handling Events - Detecting Mouse Int
eraction
 def handleEvent(self, eventObj):
 if eventObj.type not in (MOUSEMOTION, MOUSEBUTTONUP, MOUSEBUTTONDOWN):
 return False
Explain it
 eventPointInButtonRect = self.rect.collidepoint(eventObj.pos)

 - Checks if the event is mouse-related.


 - Determines if the mouse event occurred inside the button's clickable area.

38
5. Handling Events –
Managing Button States
Explain it
 if self.state == SimpleButton.STATE_IDLE:
 if (eventObj.type == MOUSEBUTTONDOWN) and eventPointInButtonRect:
 self.state = SimpleButton.STATE_ARMED

 elif self.state == SimpleButton.STATE_ARMED:


 if (eventObj.type == MOUSEBUTTONUP) and eventPointInButtonRect:
 self.state = SimpleButton.STATE_IDLE
 return True # Click registered

 if (eventObj.type == MOUSEMOTION) and (not eventPointInButtonRect):


 self.state = SimpleButton.STATE_DISARMED

 - Transitions between button states based on mouse interaction.


 - Returns `True` when a click is successfully completed.

39
6. Handling Events - Disarming and Rese
tting
Explain it
 elif self.state == SimpleButton.STATE_DISARMED:
 if eventPointInButtonRect:
 self.state = SimpleButton.STATE_ARMED
 elif eventObj.type == MOUSEBUTTONUP:
 self.state = SimpleButton.STATE_IDLE

 - Handles cases where the user drags the mouse off the button mid-click.
 - Resets the state to `IDLE` when the mouse button is released.

40
7. Drawing the Button
Explain it
 def draw(self):
 if self.state == SimpleButton.STATE_ARMED:
 self.window.blit(self.surfaceDown, self.loc)
 else: # IDLE or DISARMED
 self.window.blit(self.surfaceUp, self.loc)

 - Draws the button's appearance based on its state.


 - Changes the visual representation when the button is pressed.

41
Conclusion

 This program demonstrates:


 - Implementing a simple interactive button using a state machine.
 - Handling mouse events effectively for user interaction.
 - Dynamically updating button visuals based on its state.

 This structure forms the foundation for creating interactive UI elements in


Pygame.

42
Lecture on Using the SimpleButton Class in Pygame

PYGAME SIMPLEBUTTON TEST

43
Program

44
Overview

45
1. Importing Packages

 import pygame
 from pygame.locals import *
 from SimpleButton import *
 import sys

 - `pygame`: Main library for creating games and multimedia applications.


 - `pygame.locals`: Provides access to commonly used Pygame constants.
 - `SimpleButton`: Imports the custom SimpleButton class.
 - `sys`: Allows interaction with the system for exiting the program.

46
2. Defining Constants

 GRAY = (200, 200, 200)


 WINDOW_WIDTH = 400
 WINDOW_HEIGHT = 100
 FRAMES_PER_SECOND = 30

 - Defines the background color using RGB values.


 - Sets the dimensions of the game window.
 - Controls how many frames are rendered per second.

47
3. Initializing the Game Window

 pygame.init()
 window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
 clock = pygame.time.Clock()

 - Initializes all Pygame modules.


 - Creates a display window with the specified size.
 - Sets up a clock object to manage the frame rate for smooth animations.

48
4. Initializing the SimpleButton
Explain it
 oButton = SimpleButton(window, (150, 30),
 'images/buttonUp.png',
 'images/buttonDown.png')

 - Creates an instance of the `SimpleButton` class.


 - Positions the button at coordinates (150, 30) within the game window.
 - Loads images for both button states: 'up' and 'down' appearances.

49
5. Event Handling Loop
Explain it
 for event in pygame.event.get():
 if event.type == pygame.QUIT:
 pygame.quit()
 sys.exit()
 if oButton.handleEvent(event):
 print('User has clicked the button.')

 - Listens for system events like quitting the game.


 - Passes events to the button to check for clicks.
 - Prints a message when the button is successfully clicked.

50
6. Drawing and Updating the Button
Explain it
 window.fill(GRAY)
 oButton.draw()
 pygame.display.update()
 clock.tick(FRAMES_PER_SECOND)

 - Clears the screen with a gray background.


 - Draws the button in its current state.
 - Updates the display and manages the frame rate.

51
Conclusion

 This program demonstrates:


 - Creating an interactive button using a custom class in Pygame.
 - Handling mouse events for user interaction.
 - Dynamically updating button visuals based on user input.

 This example forms a foundation for creating interactive UIs in Pygame


applications.

52
Lecture on Implementing Multiple Interactive Buttons in Pygame

PYGAME 3-BUTTON TEST

53
Program

54
Overview

55
1. Importing Packages

 import pygame
 from pygame.locals import *
 from SimpleButton import *
 import sys

 - `pygame`: Main library for creating games and multimedia applications.


 - `pygame.locals`: Provides access to commonly used Pygame constants.
 - `SimpleButton`: Imports the custom button class for handling button behavior.
 - `sys`: Allows interaction with the system, such as exiting the program.

56
2. Defining Constants

 GRAY = (200, 200, 200)


 WINDOW_WIDTH = 400
 WINDOW_HEIGHT = 100
 FRAMES_PER_SECOND = 30

 - Defines the background color using RGB values.


 - Sets the dimensions of the game window.
 - Controls how many frames are rendered per second.

57
3. Initializing the Game Window

 pygame.init()
 window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
 clock = pygame.time.Clock()

 - Initializes all Pygame modules.


 - Sets up the game window with the specified size.
 - Creates a clock object to control the frame rate for smooth animations.

58
4. Creating Multiple Button Instances

 oButtonA = SimpleButton(window, (25, 30),


 'images/buttonAUp.png', 'images/buttonADown.png')
 oButtonB = SimpleButton(window, (150, 30),
 'images/buttonBUp.png', 'images/buttonBDown.png')
 oButtonC = SimpleButton(window, (275, 30),
 'images/buttonCUp.png', 'images/buttonCDown.png')

 - Initializes three buttons at different positions on the screen.


 - Loads images for each button in both 'up' and 'down' states.

59
5. Event Handling Loop

 for event in pygame.event.get():


 if event.type == pygame.QUIT:
 pygame.quit()
 sys.exit()
 if oButtonA.handleEvent(event):
 print('User clicked button A.')
 elif oButtonB.handleEvent(event):
 print('User clicked button B.')
 elif oButtonC.handleEvent(event):
 print('User clicked button C.')

 - Listens for system events like closing the window.


 - Detects clicks on each button and prints corresponding messages.

60
6. Drawing and Updating the Buttons

 window.fill(GRAY)
 oButtonA.draw()
 oButtonB.draw()
 oButtonC.draw()
 pygame.display.update()
 clock.tick(FRAMES_PER_SECOND)

 - Clears the screen with a gray background.


 - Draws all three buttons in their respective states.
 - Updates the display and regulates the frame rate.

61
Conclusion

 This program demonstrates:


 - Managing multiple interactive buttons using a custom class.
 - Handling mouse events for each button independently.
 - Dynamically updating the display for responsive user interaction.

 This code can serve as a foundation for creating interactive menus or control
panels in Pygame.

62
Lecture on Displaying Text Dynamically in Pygame

PYGAME SIMPLETEXT CLASS

63
Overview

64
1. Importing Packages

 import pygame
 from pygame.locals import *

 - `pygame`: Main library for creating games and multimedia applications.


 - `pygame.locals`: Provides access to commonly used Pygame constants for event
handling.

65
2. Defining the SimpleText Class
Explain it
 class SimpleText():
 def __init__(self, window, loc, value, textColor):
 pygame.font.init()
 self.window = window
 self.loc = loc
 self.font = pygame.font.SysFont(None, 30)
 self.textColor = textColor
 self.text = None
 self.setValue(value)

 - Initializes Pygame's font module.


 - Sets up initial parameters for rendering text, including font style and color.
 - Calls `setValue` to set the initial text to display.

66
3. Setting the Text Value
Explain it
 def setValue(self, newText):
 if self.text == newText:
 return
 self.text = newText
 self.textSurface = self.font.render(self.text, True, self.textColor)

 - Updates the text content only if the new text is different from the current one.
 - Creates a new surface for rendering the text in the specified color.

67
4. Drawing the Text
Explain it
 def draw(self):
 self.window.blit(self.textSurface, self.loc)

 - Draws the text on the game window at the specified location.


 - Uses `blit` to render the text surface on the window.

68
Conclusion

 This program demonstrates:


 - Creating a simple class for rendering text dynamically in Pygame.
 - Managing text updates efficiently by avoiding unnecessary redraws.
 - Drawing text at specified positions in a game window.

 This class is useful for displaying scores, messages, or instructions in Pygame


applications.

69
Lecture on Integrating Ball, SimpleText, and SimpleButton in Pygame

PYGAME BALL, TEXT, AND BUTTON DEMO

70
Program

71
Overview

72
1. Importing Packages

 import pygame
 from pygame.locals import *
 import sys
 import random
 from Ball import *
 from SimpleText import *
 from SimpleButton import *

 - `pygame`: Main library for creating multimedia applications.


 - `pygame.locals`: Provides access to commonly used Pygame constants.
 - `Ball`: Custom class for creating and animating a bouncing ball.
 - `SimpleText`: Class for displaying dynamic text.
 - `SimpleButton`: Class for handling button interactions.

73
2. Defining Constants

 BLACK = (0, 0, 0)
 WHITE = (255, 255, 255)
 WINDOW_WIDTH = 640
 WINDOW_HEIGHT = 480
 FRAMES_PER_SECOND = 30

 - Sets the background and text colors using RGB values.


 - Defines the dimensions of the window.
 - Controls the frame rate for smooth animation.

74
3. Initializing the Game Window

 pygame.init()
 window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
 clock = pygame.time.Clock()

 - Initializes Pygame modules.


 - Creates a game window of specified size.
 - Sets up a clock object to regulate frame rates.

75
4. Initializing Ball, Text, and Button

 oBall = Ball(window, WINDOW_WIDTH, WINDOW_HEIGHT) Explain it


 oFrameCountLabel = SimpleText(window, (60, 20),
 'Program has run through this many loops: ', WHITE)
 oFrameCountDisplay = SimpleText(window, (500, 20), '', WHITE)
 oRestartButton = SimpleButton(window, (280, 60),
 'images/restartUp.png', 'images/restartDown.png')
 frameCounter = 0

 - Initializes a ball object for animation.


 - Displays a label for counting frames and a text display for the count value.
 - Creates a button that resets the frame counter when clicked.

76
5. Event Handling Loop

 for event in pygame.event.get():


 if event.type == pygame.QUIT:
 pygame.quit()
 sys.exit()
 if oRestartButton.handleEvent(event):
 frameCounter = 0

 - Listens for events like quitting the game.


 - Detects button clicks and resets the frame counter when clicked.

77
6. Updating Elements Per Frame
Explain it
 oBall.update()
 frameCounter += 1
 oFrameCountDisplay.setValue(str(frameCounter))

 - Updates the ball's position.


 - Increments the frame counter each frame.
 - Updates the text display with the current frame count.

78
7. Drawing Elements and
Updating Window
Explain it
 window.fill(BLACK)

 oBall.draw()
 oFrameCountLabel.draw()
 oFrameCountDisplay.draw()
 oRestartButton.draw()
 pygame.display.update()

 clock.tick(FRAMES_PER_SECOND)

 - Clears the screen and redraws all elements in their current state.
 - Refreshes the display and controls the frame rate for smooth execution.

79
Conclusion

 This program demonstrates:


 - Integrating object-oriented elements in Pygame (ball, button, text).
 - Handling interactive events, such as resetting the frame count.
 - Updating and displaying real-time information dynamically.

 This code serves as a foundation for creating interactive games and simulations
in Pygame.

80
Lecture on Implementing Callbacks with Buttons in Pygame

PYGAME BUTTON CALLBACK

81
Program

82
Overview

83
3. Defining Callback Functions

 def myCallBackFunction():
 print('User pressed Button B, called myCallBackFunction')

 class CallBackTest():
 def __init__(self):
 pass

 def myMethod(self):
 print('User pressed Button C, called myMethod of the CallBackTest object')

 - `myCallBackFunction`: Function that prints a message when Button B is clicked.


 - `CallBackTest.myMethod`: Method inside a class that prints a message when Button C is
clicked.

84
5. Creating Buttons with Callbacks

 oCallBackTest = CallBackTest()
 oButtonA = SimpleButton(window, (25, 30), 'images/buttonAUp.png',
'images/buttonADown.png')
 oButtonB = SimpleButton(window, (150, 30), 'images/buttonBUp.png',
'images/buttonBDown.png', callBack=myCallBackFunction)
 oButtonC = SimpleButton(window, (275, 30), 'images/buttonCUp.png',
'images/buttonCDown.png', callBack=oCallBackTest.myMethod)

 - Button A does not have a callback; its click is handled in the main loop.
 - Button B calls a standalone function when clicked.
 - Button C calls a method from a class instance when clicked.

85
6. Handling Events in the Main Loop

 for event in pygame.event.get():


 if event.type == pygame.QUIT:
 pygame.quit()
 sys.exit()
 if oButtonA.handleEvent(event):
 print('User pressed button A, handled in the main loop')
 oButtonB.handleEvent(event)
 oButtonC.handleEvent(event)

 - Handles quit events to exit the program safely.


 - Button A’s click is checked manually.
 - Buttons B and C handle their clicks using their callbacks.

86
7. Drawing and Updating the Screen

 window.fill(GRAY)
 oButtonA.draw()
 oButtonB.draw()
 oButtonC.draw()
 pygame.display.update()
 clock.tick(FRAMES_PER_SECOND)

 - Clears the window and redraws all buttons.


 - Updates the display and limits the frame rate.

87
Conclusion

 This program demonstrates:


 - Using callback functions to handle button clicks.
 - Handling multiple buttons efficiently in Pygame.
 - Dynamically triggering events using standalone functions and class methods.

 This approach is useful for creating interactive UI elements in Pygame


applications.

88

You might also like