VERSION 1:
# Pong Version 1
# Implements a general game template for games with animation
# You must use this template for all your graphical lab assignments
# and you are only allowed to inlclude additional modules that are part of # the Python Standard Library; no other modules are allowed
import pygame
# User-defined functions
def main():
# initialize pygame
pygame.init()
# create a pygame display window abd set caption size = (500,400)
title = Pong
pygame.display.set_mode(size) pygame.display.set_caption(title)
# get windows surface
w_surface = pygame.display.get_surface()
# create a game object
game = Game(w_surface)
game.play()
pygame.quit()
# User-defined classes
class Game:
# An object in this class represents a complete game.
def __init__(self, surface):
# Initialize a Game.
# self is the Game to initialize
# surface is the display window surface object
# === objects that are part of every game that we will discuss self.surface = surface
self.bg_color = pygame.Color(black)
self.FPS = 60
self.game_Clock = pygame.time.Clock()
self.close_clicked = False self.continue_game = True self.color = pygame.Color(white)
self.left_rect = pygame.Rect(70,165,10,40) self.right_rect = pygame.Rect(420,165,10,40)
# === game specific objects
self.ball = Ball(white, 6, [200, 150], [2,1], self.surface) #self.max_frames = 150
#self.frame_counter = 0
def play(self):
# Play the game until the player presses the close box. # self is the Game that should be continued or not.
while not self.close_clicked: # until player clicks close box # play frame
self.handle_events()
self.draw()
if self.continue_game: self.update() self.decide_continue()
self.game_Clock.tick(self.FPS) # run at most with FPS Frames Per Second
def handle_events(self):
# Handle each user event by changing the game state appropriately.
# self is the Game whose events will be handled
events = pygame.event.get() for event in events:
if event.type == pygame.QUIT: self.close_clicked = True
def draw(self):
# Draw all game objects.
# self is the Game to draw
self.surface.fill(self.bg_color) # clear the display surface first
self.ball.draw()
pygame.draw.rect(self.surface, self.color, self.left_rect) pygame.draw.rect(self.surface, self.color, self.right_rect) pygame.display.update() # make the updated surface appear on the display
def update(self):
# Update the game objects for the next frame. # self is the Game to update
self.ball.move()
#self.frame_counter = self.frame_counter + 1
def decide_continue(self): pass
class Ball:
# An object in this class represents a Dot that moves
def __init__(self, ball_color, ball_radius, ball_center, ball_velocity, surface): # initializes the instance attributes of the BAll object
self.color = pygame.Color(ball_color)
self.radius = ball_radius
self.center = ball_center self.velocity = ball_velocity self.surface = surface
def move(self):
# Change the location of the Dot by adding the corresponding # speed values to the x and y coordinate of its center
# self is the Dot
size = self.surface.get_size()
for i in range(0,2):
self.center[i] = (self.center[i] + self.velocity[i]) if self.center[i]
self.velocity[i] = -self.velocity[i]
def draw(self):
# Draw the ball on the surface
# self is the Dot
pygame.draw.circle(self.surface, self.color, self.center, self.radius)
main()
VERSION 2:
The second version should add a scoreboard that is updated based on the rules of the game and the game should end according to the rules of the game when a score reaches 11. In addition, the ball should now bounce off the front side of each paddle but go through the back side of each paddle.The game should now respond to players moving the paddles using the keyboard keys. Must use example code below!
import pygame
# User-defined functions
def main():
# initialize all pygame modules (some need initialization)
pygame.init()
# create a pygame display window
pygame.display.set_mode((500, 400))
# set the title of the display window
pygame.display.set_caption(A template for graphical games with two moving dots) # get the display surface
w_surface = pygame.display.get_surface()
# create a game object
game = Game(w_surface)
# start the main game loop by calling the play method on the game object game.play()
# quit pygame and clean up the pygame window
pygame.quit()
# User-defined classes
class Game:
# An object in this class represents a complete game.
def __init__(self, surface):
# Initialize a Game.
# self is the Game to initialize
# surface is the display window surface object
# === objects that are part of every game that we will discuss
self.surface = surface
self.bg_color = pygame.Color(black)
self.FPS = 60
self.game_Clock = pygame.time.Clock() self.close_clicked = False self.continue_game = True
# === game specific objects
self.small_dot = Dot(red, 30, [50, 50], [1, 2], self.surface) self.big_dot = Dot(blue, 40, [200, 100], [2, 1], self.surface) self.max_frames = 150
self.frame_counter = 0
def play(self):
# Play the game until the player presses the close box. # self is the Game that should be continued or not.
while not self.close_clicked: # until player clicks close box # play frame
self.handle_events()
self.draw()
if self.continue_game: self.update() self.decide_continue()
self.game_Clock.tick(self.FPS) # run at most with FPS Frames Per Second
def handle_events(self):
# Handle each user event by changing the game state appropriately.
# self is the Game whose events will be handled
events = pygame.event.get() for event in events:
if event.type == pygame.QUIT: self.close_clicked = True
def draw(self):
# Draw all game objects.
# self is the Game to draw
self.surface.fill(self.bg_color) # clear the display surface first self.small_dot.draw()
self.big_dot.draw()
pygame.display.update() # make the updated surface appear on the display
def update(self):
# Update the game objects for the next frame. # self is the Game to update
self.small_dot.move()
self.big_dot.move()
self.frame_counter = self.frame_counter + 1
def decide_continue(self):
# Check and remember if the game should continue # self is the Game to check
if self.frame_counter > self.max_frames: self.continue_game = False
class Dot:
# An object in this class represents a Dot that moves
def __init__(self, dot_color, dot_radius, dot_center, dot_velocity, surface):
# Initialize a Dot.
# self is the Dot to initialize
# color is the pygame.Color of the dot
# center is a list containing the x and y int
# coords of the center of the dot
# radius is the int pixel radius of the dot
# velocity is a list containing the x and y components
# surface is the windows pygame.Surface object
self.color = pygame.Color(dot_color) self.radius = dot_radius
self.center = dot_center
self.velocity = dot_velocity self.surface = surface
def move(self):
# Change the location of the Dot by adding the corresponding # speed values to the x and y coordinate of its center
# self is the Dot
for i in range(0,2):
self.center[i] = (self.center[i] + self.velocity[i])
def draw(self):
# Draw the dot on the surface
# self is the Dot
pygame.draw.circle(self.surface, self.color, self.center, self.radius)
main()
code_example_2.py
Displaying code_example_2.py.
Version Hints
A KEYUP or KEYDOWN event has a key attribute that can be accessed to determine which keyboard key has been pressed down. For example, if an event is a KEYDOWN event (i.e., if event.type == pygame.KEYDOWN), then you can check if this KEYDOWN event happened because the -key was pressed, by comparing the key attribute of this event with the constant for the -key (defined in pygame), e.g., as follows: if event.key == pygame.K_a: For all constants related to keys, see the documentation of the pygame key module.
To allow both players to move their paddle at the same time, you need to detect whether two keys are being pressed and held down at the same time, and compute the corresponding paddle movement accordingly. There are a number of options to achieve this:
Option 1: Listen for KEYDOWN and KEYUP events. When a KEYDOWN event for a player occurs, change the corresponding paddles velocity/speed similar to what you do with a dot or Pong ball. When a KEYUP event for a player occurs, set the corresponding paddles velocity/speed to zero. Move paddles in the games update method according to their velocities. This is probably the more elegant option for this game, given our framework.
Option 2: Use the pygame.key.get_pressed() function, which returns a sequence indicating for all keyboard keys whether they are being pressed (and held) down or not. In order to check whether a particular key is been pressed, you can use constants provided by pygame for keys. For example, assuming you have assigned the return value of pygame.key.get_pressed() to the identifier list_of_keys, as in list_of_keys = pygame.key.get_pressed(), you can then check if the -key has been pressed by using the expression list_of_keys[pygame.K_a], which evaluates to True if the key -key is being pressed and evaluates to False if the -key is not being pressed. You can check if keys that correspond to paddle movements are being pressed (and update a paddles coordinates) either in the update method of the game, or in an event handler that is triggered by a KEYDOWN event. In the latter case you will need to insert the statement pygame.key.set_repeat(20, 20) somewhere in the __init__ method of the Game class, which will cause pygame to re-insert a KEYDOWN event of a key that is being held down (without being released) into the event queue every 20 milliseconds, so that you can use a check for a KEYDOWN event to trigger the test for held down keys (and consequent paddle movement).
When moving a paddle, you will need to know the y coordinates of the top and bottom of the paddles Rect so that you dont move it out of the window. Every Rect has a set of attributes listed in the documentation for the Rect type. For example, if you had a variable called paddle that was bound to one of the paddles Rect, you could compute the y coordinate of the top of the rectangle, using the attribute reference expression: paddle.top
Reviews
There are no reviews yet.