Breakout Tutorial using Pygame: Controlling the Paddle

break-out-gameThis tutorial is the second tutorial in a series of five Pygame tutorials:

For this third tutorial we will complete the code from the previous tutorial:

Remember the aim is to create a game of Breakout. In the first tutorial we looked at how to create the background for our game. In the second tutorial we added our first sprite called paddle which is an instance of the Paddle class.

In this third tutorial we will add methods to our Paddle class to move the paddle left and right when player uses the left and right 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 moveLeft(self, pixels):
        self.rect.x -= pixels
        #Check that you are not going too far (off the screen)
        if self.rect.x < 0:
          self.rect.x = 0
          
    def moveRight(self, pixels):
        self.rect.x += pixels
        #Check that you are not going too far (off the screen)
        if self.rect.x > 700:
          self.rect.x = 700

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 moveLeft() method.

def moveLeft(self, pixels):
    self.rect.x -= pixels
    #Check that you are not going too far (off the screen)
    if self.rect.x < 0:
       self.rect.x = 0

The moveLeft() 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


arrowKeysLet’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 user presses the the left and right arrow keys. 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 52.

#Import the pygame library and initialise the game engine
import pygame
#Let's import the Paddle Class
from paddle import Paddle
pygame.init()
# Define some colors
WHITE = (255,255,255)
DARKBLUE = (36,90,190)
LIGHTBLUE = (0,176,240)
RED = (255,0,0)
ORANGE = (255,100,0)
YELLOW = (255,255,0)
score = 0
lives = 3
# Open a new window
size = (800, 600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Breakout Game")
#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()
#Create the Paddle
paddle = Paddle(LIGHTBLUE, 100, 10)
paddle.rect.x = 350
paddle.rect.y = 560
# Add the paddle to the list of sprites
all_sprites_list.add(paddle)
# 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
 
    #Moving the paddle when the use uses the arrow keys 
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        paddle.moveLeft(5)
    if keys[pygame.K_RIGHT]:
        paddle.moveRight(5)  

    # --- Game logic should go here
    all_sprites_list.update()

    # --- Drawing code should go here
    # First, clear the screen to dark blue.
    screen.fill(DARKBLUE)
    pygame.draw.line(screen, WHITE, [0, 38], [800, 38], 2)
    #Display the score and the number of lives at the top of the screen
    font = pygame.font.Font(None, 34)
    text = font.render("Score: " + str(score), 1, WHITE)
    screen.blit(text, (20,10))
    text = font.render("Lives: " + str(lives), 1, WHITE)
    screen.blit(text, (650,10))
    #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 the paddle using the left arrow and right arrow keys!

Next Step?


It’s now time to add a bouncing ball to our game:
Breakout Tutorial using Pygame:Adding a Bouncing Ball

Did you like this challenge?

Click on a star to rate it!

Average rating 4 / 5. Vote count: 16

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: