Pygame: How to control your sprite?

arrowKeysThis tutorial is the third tutorial in a serie of three 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 and add the lines 26 to 30 as follows:

As you can see we added four 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.

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 four event handlers, one for each of the arrow key 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.

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

Share Button
Posted in Computer Science, Python - Intermediate, Python Challenges Tagged with: , , ,
One comment on “Pygame: How to control your sprite?
  1. Dolmio says:

    I couldn’t get your code to run.

    I had to change line 46 to 49 to this:

    if keys[pygame.K_UP]:
    if keys[pygame.K_DOWN]:

    *** This issue has now been solved ***

Our Latest Book