Bytes
Data Science

How to Create a Car Racing Game Using Python from Scratch

Last Updated: 13th June, 2023
icon

Harshini Bhat

Data Science Consultant at almaBetter

Are you interested in building a simple car racing game using Python and Pygame library? This article provides a step-by-step guide on how to create the game

Are you a fan of car racing games? Do you want to learn how to create your own game using Python? If so, you are fortunate. In this article, we are going to explore how to build a car racing game from scratch using Python programming language.

Top 10 Data Science Project Ideas 2023 For Beginners

Python is a popular programming language used for various purposes, from web development to data analysis. It is also a great choice for game development, all because of its simplicity and versatility. Even if you are new to programming, you need not worry as we will guide you through each and every step of the process. By the end of this, you will have a fully functional car racing game that you can play and share with your friends. So, let's get started!

image3.png

Python 2D Car Game

Requirements

Before starting to create the Python 2D car game, we need to ensure that we have the following requirements The requirements to create the Car Racing Game using Python:

  1. Python 3.x installed on our computer: Python is a widely used programming language and can be downloaded from the official website. We need to make sure to install version 3.x.
  2. IDE or Text Editor: We can choose any text editor or integrated development environment (IDE) to write and execute Python code. Some popular options include PyCharm, Visual Studio Code, Sublime Text, and Notepad++.
  3. We require images of cars, roads, enemy cars, and backgrounds to be uploaded while we build our car racing game. You can download the required images from here and save them in the same directory as your Python file.

Required Modules

Once we have these requirements set up, we can proceed to the next step by installing the necessary libraries and modules for the project. To create a car racing game using Python, you will need to import and use the following modules:

  1. Pygame: Pygame is a Python library that has different modules designed for making video games. It includes different computer graphics and sound libraries designed to be used within the Python programming language. You can install it using the pip package manager in the command prompt or terminal.
  2. Random: The random module is a built-in Python module that allows you to generate random numbers. You will use this module to create random obstacles and movements in your car racing game.
  3. Sys: The sys module is also a built-in Python module that provides access to some variables used by the interpreter and to functions that interact strongly with the interpreter. You will use it to exit the game when the player chooses to quit.

We need to make sure to install the necessary modules and import them in your Python code before we start coding our car racing game.

To install the required modules, you can use the following commands in your terminal or command prompt:

Loading...

Once the installation is complete, we can proceed with building our car racing game using Python.

Code Implementation

At First we need to import the required modules as follows:

Loading...

We will create a class called CarRacing which consists of different methods that we can use for different functions.

Loading...

Here, inside the __init__ method, Pygame is initialized, and some display variables are set, including the display width and height. It also sets some colors, black and white. The clock is set to manage the game's frames per second. gameDisplay is initialized with a value of None.

Loading...

The initialize method sets some initial values for the game. crashed is a boolean variable initialized to False. carImg is a car image that is loaded, and some initial values for the car's starting position and width are set. enemy_car is also an image loaded, and its starting position and speed are set randomly. enemy_car_width and enemy_car_height are set for the enemy car dimensions. The background image is also loaded, and its initial position and speed are set. The variable count is initialized to 0.

The __init__ method sets the initial values for the game display and Pygame, while the initialize method sets the initial values for the game elements such as the car, enemy car, and background.

Loading...

The car method is responsible for drawing the car on the game window. It takes in the x and y coordinates of the car and blits the car image onto the game display at those coordinates.

The racing_window method initializes the game display by setting the caption and size of the display. It then calls the run_car method to start the game.

Loading...

This code block contains the main game loop that runs continuously until the player either crashes into an enemy car or goes off the road.

Inside the while loop, the code checks for any user events and moves the player's car accordingly. The player can move the car left or right by pressing the corresponding arrow keys.

Then, the background road is drawn using the back_ground_raod method. Next, the enemy car is moved down the screen using the run_enemy_car method. The enemy car's position is checked, and if it has gone off the screen, it is reset to a random position at the top of the screen.

The player's car is drawn on the screen using the car method, and the player's score is updated using the highscore method.

The code then checks for collision between the player's car and the enemy car. If a collision occurs, the game is over, and a "Game Over" message is displayed using the display_message method. Similarly, if the player's car goes off the road, the game is over, and a "Game Over" message is displayed.

Finally, the screen is updated using pygame.display.update(), and the game's frame rate is set using self.clock.tick(60), which limits the game to a maximum of 60 frames per second.

Loading...

The display_message method is responsible for displaying a message on the screen when the game is over. It takes a string msg as an argument and uses the pygame.font. SysFont functions to create a font object with the specified font, size, and boldness. It then uses the render method of the font object to create a text surface with the specified message and color. The blit method of the game display surface is used to draw the text surface on the screen at the center. It also calls the display_credit method to display credits on the screen, updates the display, and waits for 1 second before calling the initialize and racing_window methods to start a new game.

The back_ground_raod method is responsible for displaying the background road image on the screen. It uses the blit method of the game display surface to draw the background road image twice, one below the other, to create a scrolling effect. It also updates the position of the background road images by incrementing their y-coordinates with the bg_speed attribute. If the y-coordinate of any background image exceeds the display height, it is reset to the top of the screen.

Loading...

The run_enemy_car method takes in thingx and thingy as arguments, which are the x and y coordinates of the enemy car, respectively. The method blits (i.e., displays) the image of the enemy car onto the game display surface (self.gameDisplay) at the specified coordinates using the blit() function from the Pygame library.

Loading...

The highscore method takes in count as an argument, which is the current score of the player. The method creates a new Pygame font object with the SysFont() function and renders the text "Score : " followed by the score as a string using the render() function. The render() function returns a new surface with the text, which is then blitted onto the game display surface at the top left corner with the blit() function.

Loading...

The display_credit method displays a small text message at the bottom right corner of the game display surface, thanking the player for playing the game. The method works similarly to the highscore method, creating a new Pygame font object, rendering the text using the render() function, and blitting the resulting surface onto the game display surface at the specified coordinates.

Loading...

The if __name__ == '__main__': block is a conditional statement that checks whether the current script is being run as the main program.

If this is true, then it creates an instance of the CarRacing class and assigns it to the car_racing variable. It then calls the racing_window() method of the CarRacing instance, which initializes the game and starts the game loop.

In short, this simple Python game code block runs the CarRacing game if the script is being run as the main program.

This finally completes our code implementation for creating a car Racing Game using Python. Note that you can find other different ways to build a car racing game by checking out the Python car racing game on Github.

Source Code

Here's the simple Python game code for building a car Racing Game using Python.

Loading...

Output:

image1.png

Car Racing Game Interface

image2.png

Car Racing Game End

Conclusion

In conclusion, creating a simple car racing game using Python and Pygame can be a fun and engaging project for both beginners and experienced programmers. The game requires the use of several programming concepts, such as object-oriented programming, event handling, and game physics. By implementing these concepts, we were able to create a game that allowed players to control a car and avoid collisions with other cars while also keeping track of their score. Through this project, we have demonstrated how Python and Pygame can be used to create an interactive game that engages users and allows them to have fun while also learning programming skills.

If you are interested in mastering Web Development from scratch, sign up for AlmaBetter’s Full Stack Web Development Program to become a Full Stack Web Developer.

Related Articles

Top Tutorials

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2024 AlmaBetter