Pygame: How to control your sprite?

arrowKeysThis tutorial is the third 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 car racing game. In the first tutorial we looked at how to create the background for our game (The road). In the second tutorial we added our first sprite called playerCar which is an instance of the Car class.

In this third tutorial we will add methods to our Car class to move the car to the left, right, forward, and backward.

We will then add event handlers to the main program loop to respond to keystroke events. When the player uses the arrow keys on the keyboard we will call our methods to move the playerCar on the screen.

Step 1: Adding Methods to the Car class.


Open the file car.py and add the lines 26 to 30 as follows:

import pygame
WHITE = (255, 255, 255)

class Car(pygame.sprite.Sprite):
    #This class represents a car. 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 car, and its x and y position, width and height.
        # Set the background color and set it to be transparent
        self.image = pygame.Surface([width, height])
        self.image.fill(WHITE)
        self.image.set_colorkey(WHITE)
 
        # Draw the car (a rectangle!)
        pygame.draw.rect(self.image, color, [0, 0, width, height])
        
        # Instead we could load a proper pciture of a car...
        # self.image = pygame.image.load("car.png").convert_alpha()
 
        # Fetch the rectangle object that has the dimensions of the image.
        self.rect = self.image.get_rect()

    def moveRight(self, pixels):
        self.rect.x += pixels

    def moveLeft(self, pixels):
        self.rect.x -= pixels

As you can see we have added two procedures to our class. In OOP (Object Orientated Programming) we call these procedures: methods. A method is a procedure or function associated to a class. Let’s look at the moveRight() method.

def moveRight(self, pixels):
   self.rect.x += pixels

The moveRight() 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 car.

The body of our method only contains one line: self.rect.x += pixels
It is basically adding pixels to the current x coordinate of the object.

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 two event handlers, one moving left and one for moving right using the left and right arrow keys of the keyboard. Each event handler will call the relevant method from the Car class. Check the code below with the new event handlers from line 37 to 45.

import pygame, random
#Let's import the Car Class
from car import Car
pygame.init()

GREEN = (20, 255, 140)
GREY = (210, 210 ,210)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
        
SCREENWIDTH=400
SCREENHEIGHT=500

size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Car Racing")

#This will be a list that will contain all the sprites we intend to use in our game.
all_sprites_list = pygame.sprite.Group()

playerCar = Car(RED, 20, 30)
playerCar.rect.x = 200
playerCar.rect.y = 300

# Add the car to the list of objects
all_sprites_list.add(playerCar)

#Allowing the user to close the window...
carryOn = True
clock=pygame.time.Clock()

while carryOn:
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                carryOn=False
            elif event.type==pygame.KEYDOWN:
                if event.key==pygame.K_x: #Pressing the x Key will quit the game
                     carryOn=False

        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            playerCar.moveLeft(5)
        if keys[pygame.K_RIGHT]:
            playerCar.moveRight(5)
        
        #Game Logic
        all_sprites_list.update()

        #Drawing on Screen
        screen.fill(GREEN)
        #Draw The Road
        pygame.draw.rect(screen, GREY, [40,0, 200,300])
        #Draw Line painting on the road
        pygame.draw.line(screen, WHITE, [140,0],[140,300],5)
        
        #Now let's draw all the sprites in one go. (For now we only have 1 sprite!)
        all_sprites_list.draw(screen)

        #Refresh Screen
        pygame.display.flip()

        #Number of frames per secong e.g. 60
        clock.tick(60)

pygame.quit() 

All done… Save your files and try your code. You should now be able to control your car using the arrow keys!

Did you like this challenge?

Click on a star to rate it!

Average rating 3.9 / 5. Vote count: 23

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

As you found this challenge interesting...

Follow us on social media!

Tagged with: , , ,