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 and add the lines 26 to 30 as follows:

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.

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.

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

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

As you found this challenge interesting...

Follow us on social media!

Tagged with: , , ,