This tutorial is the third tutorial in a series of five Pygame tutorials:
- Pong Tutorial 1: Getting Started
- Pong Tutorial 2: Adding the Paddles
- Pong Tutorial 3: Controlling the Paddles
- Pong Tutorial 4: Adding a Bouncing Ball
- Pong Tutorial 5: Adding a Scoring system
- Extra: Pygame How To’s?
For this third tutorial we will complete the code from the previous tutorial:
Remember the aim is to create a two-player game of Pong. In the first tutorial we looked at how to create the background for our game. In the second tutorial we added our first sprites called paddleA and paddleB which are instances of the Paddle class.
In this third tutorial we will add methods to our Paddle class to move the paddles up and down when player A uses the W (up) and S (down) keys and player B uses the up and down arrow keys.
We will then add event handlers to the main program loop to respond to keystroke events. When the players use the relevant keys on the keyboard we will call our methods to move their paddle on the screen.
Step 1: Adding Methods to the Paddle class.
Open the file paddle.py and add the lines 23 to 33 as follows:
import pygame BLACK = (0,0,0) class Paddle(pygame.sprite.Sprite): #This class represents a paddle. It derives from the "Sprite" class in Pygame. def __init__(self, color, width, height): # Call the parent class (Sprite) constructor super().__init__() # Pass in the color of the paddle, its width and height. # Set the background color and set it to be transparent self.image = pygame.Surface([width, height]) self.image.fill(BLACK) self.image.set_colorkey(BLACK) # Draw the paddle (a rectangle!) pygame.draw.rect(self.image, color, [0, 0, width, height]) # Fetch the rectangle object that has the dimensions of the image. self.rect = self.image.get_rect() def moveUp(self, pixels): self.rect.y -= pixels #Check that you are not going too far (off the screen) if self.rect.y < 0: self.rect.y = 0 def moveDown(self, pixels): self.rect.y += pixels #Check that you are not going too far (off the screen) if self.rect.y > 400: self.rect.y = 400
As you can see we have added two methods to our class. In OOP (Object Orientated Programming) a method is a procedure or function associated to a class. Let’s look at the moveUp() method.
def moveUp(self, pixels): self.rect.y -= pixels #Check that you are not going too far (off the screen) if self.rect.y < 0: self.rect.y = 0
The moveUp() method takes two arguments. The first one is implicit and is called self. It refers to the current object. The second one is called pixels and refers to the number of pixels we will use to move the paddle.
Step 2: Responding to keystroke events
Let’s look at the code for our main program. You may remember that in the first tutorial we talked about the main program loop. The first section of this loop is to respond to events such as user interactions when the user uses the mouse or the keyboard.
So let’s add four event handlers, to move the paddle up or down when the players press the W or S keys (Paddle A) or the up and down arrow keys (paddle B). Each event handler will call the relevant method from the Paddle class. Check the code below with the new event handlers from line 47 to 56.
# Import the pygame library and initialise the game engine import pygame from paddle import Paddle pygame.init() # Define some colors BLACK = (0,0,0) WHITE = (255,255,255) # Open a new window size = (700, 500) screen = pygame.display.set_mode(size) pygame.display.set_caption("Pong") paddleA = Paddle(WHITE, 10, 100) paddleA.rect.x = 20 paddleA.rect.y = 200 paddleB = Paddle(WHITE, 10, 100) paddleB.rect.x = 670 paddleB.rect.y = 200 #This will be a list that will contain all the sprites we intend to use in our game. all_sprites_list = pygame.sprite.Group() # Add the paddles to the list of sprites all_sprites_list.add(paddleA) all_sprites_list.add(paddleB) # The loop will carry on until the user exits the game (e.g. clicks the close button). carryOn = True # The clock will be used to control how fast the screen updates clock = pygame.time.Clock() # -------- Main Program Loop ----------- while carryOn: # --- Main event loop for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close carryOn = False # Flag that we are done so we exit this loop elif event.type==pygame.KEYDOWN: if event.key==pygame.K_x: #Pressing the x Key will quit the game carryOn=False #Moving the paddles when the user uses the arrow keys (player A) or "W/S" keys (player B) keys = pygame.key.get_pressed() if keys[pygame.K_w]: paddleA.moveUp(5) if keys[pygame.K_s]: paddleA.moveDown(5) if keys[pygame.K_UP]: paddleB.moveUp(5) if keys[pygame.K_DOWN]: paddleB.moveDown(5) # --- Game logic should go here all_sprites_list.update() # --- Drawing code should go here # First, clear the screen to black. screen.fill(BLACK) #Draw the net pygame.draw.line(screen, WHITE, [349, 0], [349, 500], 5) #Now let's draw all the sprites in one go. (For now we only have 2 sprites!) all_sprites_list.draw(screen) # --- Go ahead and update the screen with what we've drawn. pygame.display.flip() # --- Limit to 60 frames per second clock.tick(60) #Once we have exited the main program loop we can stop the game engine: pygame.quit()
All done… Save your files and try your code. You should now be able to control each paddle using the W, S, Up arrow and Down arrow keys!
Next Step?
It’s now time to add a bouncing ball to our game:
Pong Tutorial using Pygame:Adding a Bouncing Ball