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 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
        # 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])
        # 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
from paddle import Paddle


# Define some colors
BLACK = (0,0,0)
WHITE = (255,255,255)

# Open a new window
size = (700, 500)
screen = pygame.display.set_mode(size)

paddle = Paddle(WHITE, 10, 100)
paddle.rect.x = 20
paddle.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 paddle to the list of sprites

# 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
    #Moving the paddle when the use uses the arrow keys 
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
    if keys[pygame.K_RIGHT]:
    # --- Game logic should go here
    # --- Drawing code should go here
    # First, clear the screen to 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!)
    # --- Go ahead and update the screen with what we've drawn.
    # --- Limit to 60 frames per second
#Once we have exited the main program loop we can stop the game engine:

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.1 / 5. Vote count: 9

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

As you found this challenge interesting...

Follow us on social media!

Tagged with: