Pong Tutorial using Pygame – Adding the Paddles

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

Learning Objectives


In this second tutorial on how to create the retro arcade game Pong using PyGame we are looking at creating our first sprites.
definition-sprite

Consider a sprite as an object. An object can have different properties (e.g. width, height, colour, etc.) and methods (e.g. jump(), hide(), moveForward(), etc.). Like in the industry an object is built from a mould. In computing the mould is called a Class.

So by creating our first sprite we will implement OOP (Object Orientated Programming). We will create our first Class called Paddle and derive our first objects (paddleA and paddleB) from this class.

Pong is a two player game so playerA will be able to control the first paddle (paddleA) using the W and S keys (w for moving the paddle upwards, S for moving it downwards) while playerB will use the up and down arrow keys.

Our first Class


So let’s look at the code for our Paddle Class:
To start with the first method we will need in our class is the __init__() method. It’s called a constructor. It is used when the object is first created to initalise the main properties of the object (e.g. its x and y position, dimensions, colour, etc.)

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

Later on we will add more properties and methods to this class. But before doing so we will look at how we can use it to create our first objects: the pladdles of both players (paddleA and paddleB)

So let’s save our class as a python file called paddle.py.

Our first Object


Now that we have a Class we can create objects from this Class. (Remember a Class is like a mould. It enables you to create as many objects as you need using the same mould.)

Let’s go back to our main.py file (from previous tutorial) to edit its content.

First let’s add at the top of the code an import statement to import our Paddle class.

#Let's import the Paddle Class
from paddle import Paddle

Then we need to create and position our sprites in our main program using the following lines of code:

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

However, because we are creating a fully working game, we are going to do a few more things with these objects.

Let’s reuse the code from the first tutorial.

On line 3 notice how we are using the import command to link to our Paddle Class python file (paddle.py).

On line 25 we are declaring a list called all_sprites_list that will store all the sprites we will create in our game. (For now just two sprites, paddleA and paddleB.)

From line 22 we are creating our first sprites/objects using the Paddle Class. Notice how when declaring our first object we use the parameters from its constructor (__init__()), in this case, the colour, width and height of the paddle we want to create.

Now that we have created our first sprites we need to add them to our list of spites: all_sprites_list. This is what happens on line 28 and 29.

Finally, within the main program loop, on line 49 we are refreshing the screen and drawing all the sprites from our list: all_sprites_list.

Here is the full code:

# 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  
 
    # --- 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()

That’s it… You are now ready to move to our third tutorial to learn how to control your sprites using the arrow keys.
Pong Tutorial using PygameControlling the paddles

Did you like this challenge?

Click on a star to rate it!

Average rating 4 / 5. Vote count: 25

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

As you found this challenge interesting...

Follow us on social media!

Tagged with: