Pygame Tutorial – Adding More Sprites

car-racingThis tutorial is the fourth tutorial in a serie of five Pygame tutorials:

For our car racing game we will add a few more cars.

Each car is an object that will be instantiated from the Car Class.

Looking at the code from our previous tutorial we are adding a few properties and methods to our Car class. This is to allow for the coming cars to have different sizes (width and height), colors and different speed. See the changes on the car.py file.

Then, in our main program, we are going to create four extra cars and we will add these to a list called “all_comming_cars”. Each car will be given a different color, a speed and a different starting position (x & y coordinates). This is what the code on the main.py file does on lines 34 to 62.

The four cars will be moving down (starting at the top of the screen). When they reach the bottom of the screen they will be given a new color, speed and starting position towards the top of the screen. This is what the code on the main.py file does on lines 89 to 94.

The overall speed of the game will be stored in a variable called speed initialised on line 15 of the main.py file. New event handlers will detect when the user presses the UP or DOWN keys on the keyboard. These will increment or decrement the speed variable by 0.05. See lines 82 to 85 of the main.py file.

Here is the code for our latest Car class and for our main program:

Car.pymain.py

Detecting Collision

The next addition to our game is used on most 2D arcarde games: The aim is to check when a sprite (e.g. playerCar) is colliding with other sprites (in this case cars stored in the all_coming_cars list).

You would need to add these lines of code in the “game logic” section of your main program loop. For instance you could add these lines on line 95 of the code provided above (main.py).

Share Button
Posted in Computer Science, Python - Advanced, Python Challenges Tagged with: , ,

Our Latest Book