Complete Racing Game In Python Using PyGame

Car Race Game in PyGame Python: From Scratch

So far we have learned a lot but there is not anything to end our game and now we are now going to see part 2 of our project. So, in this section, we will Create a Complete Racing Game In Python Using PyGame. So that we can use it to quit our game.

Detecting collision between the cars

Now we’ll be focusing on detecting the collision between the so that we can use it to quit and make us feel like we are really playing a game.

For collision the first thing we need to do is to find the distance between the car and using the distance we would code something to make the collision occur.

If you have read ‘coordinate geometry‘ in your school then you might know that there was a ‘distance formula’ which is used to find the distance between two points. So, we’ll be using the same formula in our game to find the distance between the cars. In case you don’t know the formula you should not worry you can google it and understand its uses and the concept behind it. The distance formula is given below.

Create Your First Racing Game: 10 Steps Complete Racing Game In Python Using PyGame So far we have learned a lot but there is not anything to end our game and now we are now going to see part 2 of our project. So, in this section, we will Create a Complete Racing Game In Python Using PyGame. So that we can use it to quit our game.

We saw that there is math involved in this so to perform the mathematical operation there is a module in Python named math so we have to import the math module this is a built-in module so you didn’t need to install it just simply type ‘import math and this will import the math module. Now, we are good to go.

assignment advertisement

Let’s look at the code below.

import pygame
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
import random
import math
screen = pygame.display.set_mode((798,600))


#changing title of the game window
pygame.display.set_caption('Racing Beast')

#changing the logo
logo = pygame.image.load('car game/logo.jpeg')
pygame.display.set_icon(logo)


#defining our gameloop function

def gameloop():

    #setting background image
    bg = pygame.image.load('car game/bg.png')

    
    # setting our player
    maincar = pygame.image.load('car game\car.png')
    maincarX = 350
    maincarY = 495
    maincarX_change = 0
    maincarY_change = 0

    #other cars
    car1 = pygame.image.load('car game\car1.jpeg')
    car1X = random.randint(178,490)
    car1Y = 100
    car1Ychange = 10

    car2 = pygame.image.load('car game\car2.png')
    car2X = random.randint(178,490)
    car2Y = 100
    car2Ychange = 10

    car3 = pygame.image.load('car game\car3.png')
    car3X = random.randint(178,490)
    car3Y = 100
    car3Ychange = 10
    
    


   
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

                #checking if any key has been pressed
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change += 5
            
                if event.key == pygame.K_LEFT:
                    maincarX_change -= 5
                
                if event.key == pygame.K_UP:
                    maincarY_change -= 5
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change += 5

                #checking if key has been lifted up
            if event.type == pygame.KEYUP: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change = 0
            
                if event.key == pygame.K_LEFT:
                    maincarX_change = 0
                
                if event.key == pygame.K_UP:
                    maincarY_change = 0
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change = 0            

        #setting boundary for our main car
        if maincarX < 178:
            maincarX = 178
        if maincarX > 490:
            maincarX = 490
        
        if maincarY < 0:
            maincarY = 0
        if maincarY > 495:
            maincarY = 495


        #CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE 
        screen.fill((0,0,0))

        #displaying the background image
        screen.blit(bg,(0,0))

        #displaying our main car
        screen.blit(maincar,(maincarX,maincarY))

        #displaing other cars
        screen.blit(car1,(car1X,car1Y))
        screen.blit(car2,(car2X,car2Y))
        screen.blit(car3,(car3X,car3Y))
        
        #updating the values
        maincarX += maincarX_change
        maincarY +=maincarY_change

        #movement of the enemies
        car1Y += car1Ychange
        car2Y += car2Ychange
        car3Y += car3Ychange
        #moving enemies infinitely
        if car1Y > 670:
            car1Y = -100
        if car2Y > 670:
            car2Y = -150
        if car3Y > 670:
            car3Y = -200

        #DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False
        
        #giving collision a variable

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY) 

        #if coll1 occur
        if coll1: 
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
        
        #if coll2 occur
        if coll2:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0

        #if coll3 occur    
        if coll3:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0



        pygame.display.update()

gameloop()

Change in the Code:-

 #DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False
        
        #giving collision a variable

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY) 

        #if coll1 occur
        if coll1: 
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
        
        #if coll2 occur
        if coll2:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0

        #if coll3 occur    
        if coll3:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0

What we did above can be divided into three parts for all the three cars separately.

#DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

In the first part, we created a function in which we obtained distance and checked if that distance is less than 50, then it will return true otherwise it will return False.

 #giving collision a variable

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY)

In the second part, we created three variables ‘coll1, coll2, coll3‘ in which we passed the collision function that we have created. We did it just for our convenience.

#if coll1 occur
        if coll1: 
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
        
        #if coll2 occur
        if coll2:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0

        #if coll3 occur    
        if coll3:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0

In the third part, we checked all the collision ‘coll1, coll2, and coll3′ one by one. And if any of them occur then we stopped our all cars including the main car. And also changed the color of our background to some color.

Let me explain how we find the distance between the cars by this code

distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(carY – maincarY,2))

We used the math module for doing this, math.sqrt means square root and math.pow means power or exponents, ‘math.pow(x,y)‘takes two things as a parameter in which the first parameter which is our x represents the base and y represents the power or the exponent.

In this case, our x is the difference between car1x and maincarx & car1y and maincary and y is 2 which we can also say square. So now you would be understanding how we used the distance formula to find the distance.

I hope you understood and if you want to learn more about the math module you can google it and go through it. Run the above code and check if everything is working.

Displaying the score in our game

Now, we’ll display the score in our game. At first, we’ll create a variable ‘score value‘ and set it to 0 (see line 30) and then we’ll update this value by 1 if the other cars’ (car1,car2, and car3) Y-axis is greater than 670 (see line 134, 137 and 140).

Now, our score is increasing but we want to display it in our game window. For doing this first we’ll create a variable font1 and will give it font and size. ‘font1= pygame.font.Font(“freesansbold.ttf”,25)’ in this ‘freesansbold.ttf’ is a font and 25 is a size of the font. After then we’ll create a function to display our score by calling this function.

We will create a function ‘show_score(x, y)‘ and will pass it two parameters x and y. In that function, we’ll first render our text and then blit our text to display on t pygame window. We’ll create a variable and render our text inside this variable.

The render method will take some values first the text we want to display which is ‘SCORE: ‘ and the string value of ‘score_value’. Since ‘score_value’ is an integer so we need to typecast it into a string to display it. The second value it took is True and the third is the color of the text in the RGB method (see line 28). After then we’ll blit it by screen.blit method in which the first value will be the ‘score’ variable and the second will be X and Y (see line 29).

Now, it’s time to call our function so let’s call it by providing some x and y values which is 570 and 280. See line 215 about how we did this.

import pygame
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
import random
import math
screen = pygame.display.set_mode((798,600))


#changing title of the game window
pygame.display.set_caption('Racing Beast')

#changing the logo
logo = pygame.image.load('car game/logo.jpeg')
pygame.display.set_icon(logo)







#defining our gameloop function

def gameloop():
    #scoring part
    font1= pygame.font.Font("freesansbold.ttf",25)
    def show_score(x,y):
        score = font1.render("SCORE: "+ str(score_value), True, (255,0,0))
        screen.blit(score, (x,y))
    score_value = 0

    #setting background image
    bg = pygame.image.load('car game/bg.png')

    
    # setting our player
    maincar = pygame.image.load('car game\car.png')
    maincarX = 350
    maincarY = 495
    maincarX_change = 0
    maincarY_change = 0

    #other cars
    car1 = pygame.image.load('car game\car1.jpeg')
    car1X = random.randint(178,490)
    car1Y = 100
    car1Ychange = 10

    car2 = pygame.image.load('car game\car2.png')
    car2X = random.randint(178,490)
    car2Y = 100
    car2Ychange = 10

    car3 = pygame.image.load('car game\car3.png')
    car3X = random.randint(178,490)
    car3Y = 100
    car3Ychange = 10
    
    


   
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

                #checking if any key has been pressed
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change += 5
            
                if event.key == pygame.K_LEFT:
                    maincarX_change -= 5
                
                if event.key == pygame.K_UP:
                    maincarY_change -= 5
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change += 5

                #checking if key has been lifted up
            if event.type == pygame.KEYUP: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change = 0
            
                if event.key == pygame.K_LEFT:
                    maincarX_change = 0
                
                if event.key == pygame.K_UP:
                    maincarY_change = 0
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change = 0            

        #setting boundary for our main car
        if maincarX < 178:
            maincarX = 178
        if maincarX > 490:
            maincarX = 490
        
        if maincarY < 0:
            maincarY = 0
        if maincarY > 495:
            maincarY = 495


        #CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE 
        screen.fill((0,0,0))

        #displaying the background image
        screen.blit(bg,(0,0))

        #displaying our main car
        screen.blit(maincar,(maincarX,maincarY))

        #displaing other cars
        screen.blit(car1,(car1X,car1Y))
        screen.blit(car2,(car2X,car2Y))
        screen.blit(car3,(car3X,car3Y))
        
        #updating the values
        maincarX += maincarX_change
        maincarY +=maincarY_change

        #movement of the enemies
        car1Y += car1Ychange
        car2Y += car2Ychange
        car3Y += car3Ychange
        #moving enemies infinitely
        if car1Y > 670:
            car1Y = -100
            score_value += 1
        if car2Y > 670:
            car2Y = -150
            score_value += 1
        if car3Y > 670:
            car3Y = -200
            score_value += 1

        #DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False
        
        #giving collision a variable

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY) 

        #if coll1 occur
        if coll1: 
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            
        
        #if coll2 occur
        if coll2:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0

        #if coll3 occur    
        if coll3:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
        
            
        show_score(570,280)


        pygame.display.update()

gameloop()

Now everything should be fine run the above code to check if everything is working or not. If you want to use another font to display our score then download it from the google with ‘.ttf‘ extension and place this file to our project folder where our all sprites are located.

We can also display the game over by this method when our car gets collide with other cars. You can try to do it by yourself because we have an image of the game over which we’ll be using later.

Now our game is almost ready but it hasn’t any sound. So in the next section, we’ll be adding music to our game.

Adding Sounds and Background Music to Our Game

In this section, we will learn to add music to our game. In this game we’ll be using two types of sound the first will be our background which will play infinitely till the end of the game. Second is the collision sound means when our car will hit another car a collision sound will play and our game will over.

For doing this we will use the mixer module of pygame. This module deals with the music means in order to play music/audio files in pygamepygame.mixer is used (pygame module for loading and playing sounds). This module contains classes for loading Sound objects and controlling playback. There are basically four steps in order to do so:

  • Starting the mixer
pygame.mixer.init()

This will initialize the mixer so that we can use it without any error.

  • Loading the song
pygame.mixer.music.load('song.mp3')

This will load the song we want to play here ‘song.mp3‘ is an example you have to give the song name with the proper extension.

  • Start playing the Song
pygame.mixer.music.play()

This will play the song which we have loaded.

  • Stop playing the Song
pygame.mixer.music.stop()

This will stop playing the song.

There are also some sound effects in the game so we will also in our this we will use pygame.mixer.sound() to perform this function. You must have been confused that why will we use pygame.mixer.sound() why we can’t use the previous method which was pygame.mixer.music().

Difference between pygame.mixer.sound() & pygame.mixer.music()

You might have been confused in pygame.mixer.sound() & pygame.mixer.music() so I should clear that.In a game, music would be a way to play background music and sound would be a way to play sound effects (ex-. jumping, firing, etc).

Now let’s code for our game. We’ll have two types of sound first will be our background music and the second will be the sound effect of a collision. Look at the following code.

import pygame
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
import random
import math
screen = pygame.display.set_mode((798,600))

#initializing pygame mixer
pygame.mixer.init()

#changing title of the game window
pygame.display.set_caption('Racing Beast')

#changing the logo
logo = pygame.image.load('car game/logo.jpeg')
pygame.display.set_icon(logo)







#defining our gameloop function

def gameloop():

      ####### music ####### 
    pygame.mixer.music.load('car game\BackgroundMusic.mp3')
    pygame.mixer.music.play()
    ###### sound effect for collision ######
    crash_sound = pygame.mixer.Sound('car game\car_crash.wav')

    ####### scoring part ######
    score_value = 0
    font1= pygame.font.Font("freesansbold.ttf",25)
    def show_score(x,y):
        score = font1.render("SCORE: "+ str(score_value), True, (255,0,0))
        screen.blit(score, (x,y))
    
    #setting background image
    bg = pygame.image.load('car game/bg.png')

    
    # setting our player
    maincar = pygame.image.load('car game\car.png')
    maincarX = 350
    maincarY = 495
    maincarX_change = 0
    maincarY_change = 0

    #other cars
    car1 = pygame.image.load('car game\car1.jpeg')
    car1X = random.randint(178,490)
    car1Y = 100
    car1Ychange = 10

    car2 = pygame.image.load('car game\car2.png')
    car2X = random.randint(178,490)
    car2Y = 100
    car2Ychange = 10

    car3 = pygame.image.load('car game\car3.png')
    car3X = random.randint(178,490)
    car3Y = 100
    car3Ychange = 10
       

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

                #checking if any key has been pressed
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change += 5
            
                if event.key == pygame.K_LEFT:
                    maincarX_change -= 5
                
                if event.key == pygame.K_UP:
                    maincarY_change -= 5
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change += 5

                #checking if key has been lifted up
            if event.type == pygame.KEYUP: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change = 0
            
                if event.key == pygame.K_LEFT:
                    maincarX_change = 0
                
                if event.key == pygame.K_UP:
                    maincarY_change = 0
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change = 0            

        #setting boundary for our main car
        if maincarX < 178:
            maincarX = 178
        if maincarX > 490:
            maincarX = 490
        
        if maincarY < 0:
            maincarY = 0
        if maincarY > 495:
            maincarY = 495


        #CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE 
        screen.fill((0,0,0))

        #displaying the background image
        screen.blit(bg,(0,0))

        #displaying our main car
        screen.blit(maincar,(maincarX,maincarY))

        #displaing other cars
        screen.blit(car1,(car1X,car1Y))
        screen.blit(car2,(car2X,car2Y))
        screen.blit(car3,(car3X,car3Y))
        
        #updating the values
        maincarX += maincarX_change
        maincarY +=maincarY_change

        #movement of the enemies
        car1Y += car1Ychange
        car2Y += car2Ychange
        car3Y += car3Ychange
        #moving enemies infinitely
        if car1Y > 670:
            car1Y = -100
            score_value += 1
        if car2Y > 670:
            car2Y = -150
            score_value += 1
        if car3Y > 670:
            car3Y = -200
            score_value += 1

        #DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False
        
        ##### giving collision a variable #####

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY) 

        #if coll1 occur
        if coll1: 
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
           
            
        
        #if coll2 occur
        if coll2:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
           

        #if coll3 occur    
        if coll3:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
           
        
            
        show_score(570,280)


        pygame.display.update()

gameloop()

Change in the Code:-

####### music ####### 
    pygame.mixer.music.load('car game\BackgroundMusic.mp3')
    pygame.mixer.music.play()
    ###### sound effect for collision ######
    crash_sound = pygame.mixer.Sound('car game\car_crash.wav')

    pygame.mixer.music.stop()
    crash_sound.play()

What we did is we first loaded our background music and then played it. Second, we loaded our sound effect which is ‘car_crash.wav’ in a variable crash_sound. After then, in coll1, coll2, and coll3 we first sopped our background music and then played our sound effect by ‘crash_sound.play()’ because our sound is stored in the variable crash_sound.

Run and check the output of the above code if our background music and crash sound is working or not.

You will notice that when you run the code our game starts quickly even if we don’t get the time to be ready for the game. So in the next section, we’ll do something that will create a countdown from 3, 2, 1, and GO.

A countdown timer for the Game.

Now we are going to add the countdown timer for our game so that our game could look better and also we can get the time to be prepared to play the game. We’ll also use the time module in this part so first import the time module by typing import time. First look at the full code.

import pygame,sys
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
import random
import math
import time
screen = pygame.display.set_mode((798,600))

#initializing pygame mixer
pygame.mixer.init()

#changing title of the game window
pygame.display.set_caption('Racing Beast')

#changing the logo
logo = pygame.image.load('car game/logo.jpeg')
pygame.display.set_icon(logo)

  ###### Countdown ######
def countdown():
    font2 = pygame.font.Font('freesansbold.ttf', 85)
    countdownBacground = pygame.image.load('car game/bg.png')
    three = font2.render('3',True, (187,30,16))
    two =   font2.render('2',True, (255,255,0))
    one =   font2.render('1',True, (51,165,50))
    go =    font2.render('GO!!!',True, (0,255,0))
    
    

               ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()

    ###### Displaying  three (3) ######
    screen.blit(three,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  two (2) ######
    screen.blit(two,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  one (1) ######
    screen.blit(one,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  Go!!! ######
    screen.blit(go,(300,250))
    pygame.display.update()
    time.sleep(1)
    gameloop() #calling the gamloop so that our game can start after the countdown
    pygame.display.update()


        

    
    

#defining our gameloop function
def gameloop():

      ####### music ####### 
    pygame.mixer.music.load('car game\BackgroundMusic.mp3')
    pygame.mixer.music.play()
    ###### sound effect for collision ######
    crash_sound = pygame.mixer.Sound('car game\car_crash.wav')

    ####### scoring part ######
    score_value = 0
    font1= pygame.font.Font("freesansbold.ttf",25)
    def show_score(x,y):
        score = font1.render("SCORE: "+ str(score_value), True, (255,0,0))
        screen.blit(score, (x,y))

    #setting background image
    bg = pygame.image.load('car game/bg.png')

    
    # setting our player
    maincar = pygame.image.load('car game\car.png')
    maincarX = 350
    maincarY = 495
    maincarX_change = 0
    maincarY_change = 0

    #other cars
    car1 = pygame.image.load('car game\car1.jpeg')
    car1X = random.randint(178,490)
    car1Y = 100
    car1Ychange = 10

    car2 = pygame.image.load('car game\car2.png')
    car2X = random.randint(178,490)
    car2Y = 100
    car2Ychange = 10

    car3 = pygame.image.load('car game\car3.png')
    car3X = random.randint(178,490)
    car3Y = 100
    car3Ychange = 10
       

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()

                #checking if any key has been pressed
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change += 5
            
                if event.key == pygame.K_LEFT:
                    maincarX_change -= 5
                
                if event.key == pygame.K_UP:
                    maincarY_change -= 5
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change += 5

                #checking if key has been lifted up
            if event.type == pygame.KEYUP: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change = 0
            
                if event.key == pygame.K_LEFT:
                    maincarX_change = 0
                
                if event.key == pygame.K_UP:
                    maincarY_change = 0
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change = 0            

        #setting boundary for our main car
        if maincarX < 178:
            maincarX = 178
        if maincarX > 490:
            maincarX = 490
        
        if maincarY < 0:
            maincarY = 0
        if maincarY > 495:
            maincarY = 495


        #CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE 
        screen.fill((0,0,0))

        #displaying the background image
        screen.blit(bg,(0,0))

        #displaying our main car
        screen.blit(maincar,(maincarX,maincarY))

        #displaing other cars
        screen.blit(car1,(car1X,car1Y))
        screen.blit(car2,(car2X,car2Y))
        screen.blit(car3,(car3X,car3Y))
        
        #updating the values
        maincarX += maincarX_change
        maincarY +=maincarY_change

        #movement of the enemies
        car1Y += car1Ychange
        car2Y += car2Ychange
        car3Y += car3Ychange
        #moving enemies infinitely
        if car1Y > 670:
            car1Y = -100
            car1X = random.randint(178,490)
            score_value += 1
        if car2Y > 670:
            car2Y = -150
            car2X = random.randint(178,490)
            score_value += 1
        if car3Y > 670:
            car3Y = -200
            car3X = random.randint(178,490)
            score_value += 1

        #DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False
        
        ##### giving collision a variable #####

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY) 

        #if coll1 occur
        if coll1: 
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
           
            
        
        #if coll2 occur
        if coll2:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
           

        #if coll3 occur    
        if coll3:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
           
        
            
        show_score(570,280)


        pygame.display.update()
countdown()

Change in the code:-

  ###### Countdown ######
def countdown():
    font2 = pygame.font.Font('freesansbold.ttf', 85)
    countdownBacground = pygame.image.load('car game/bg.png')
    three = font2.render('3',True, (187,30,16))
    two =   font2.render('2',True, (255,255,0))
    one =   font2.render('1',True, (51,165,50))
    go =    font2.render('GO!!!',True, (0,255,0))
    
    

               ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()

    ###### Displaying  three (3) ######
    screen.blit(three,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  two (2) ######
    screen.blit(two,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  one (1) ######
    screen.blit(one,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  Go!!! ######
    screen.blit(go,(300,250))
    pygame.display.update()
    time.sleep(1)
    gameloop() #calling the gamloop so that our game can start after the countdown
    pygame.display.update()

countdown()

What we did can be divided into 5 parts.

  • At first, we created the function countdown.
  • Second we created a variable font2 in which we gave font and size using pygame.font.Font. font2 = pygame.font.Font(‘freesansbold.ttf’, 85) (see line 21)
  • Third, we rendered this font and created text (3, 2, 1, and GO!!!)
  three = font2.render('3',True, (187,30,16))
  two =   font2.render('2',True, (255,255,0))
  one =   font2.render('1',True, (51,165,50))
  go =    font2.render('GO!!!',True, (0,255,0))
  • Fourth we loaded a background image using pygame.image.load(). countdownBacground = pygame.image.load(‘car game/bg.png’) (see line 30-32)
  • Fifth, we blitted all the sprites one by one with a one-second gap. And finally, we called our countdown function instead of gameloop function.

I know that you understood till 4th step clearly and there would be some confusion in step five. Don’t worry, I’ll explain it to you. Let’s first see the code of the fifth step.

##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()

    ###### Displaying  three (3) ######
    screen.blit(three,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  two (2) ######
    screen.blit(two,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  one (1) ######
    screen.blit(one,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  Go!!! ######
    screen.blit(go,(300,250))
    pygame.display.update()
    time.sleep(1)
    gameloop() #calling the gamloop so that our game can start after the countdown
    pygame.display.update()

What we did above is we first displayed our background image by using scree.blit() function and then updated the screen. And then we used time.sleep(1) which will delay the execution of the code by 1 second.

After then we displayed our text 3 updated it and took the time of 1 second and then we displayed the background image again because our previous text can overlap with another text. This process continued till the text ‘GO!!!. In a summary, we blitted our text then background then again text, and then again background till the text GO!!!.

After reaching the text ‘GO!!!‘ we called our gameloop() function so that our game can start after the countdown and it will look like an animation.

We have successfully set our countdown timer. I hope you understood this. Run the above code and check if everything is working properly. In the next, we will be displaying highscore on our game window. So, that our game can become competitive.

Adding high score to our game

For adding a high score first we will create a text document or file named as highscore.txt in which our high score will be stored. First, create it, and then we are good to go.

In python, we know that for accessing files in reading mode we use ‘with open(“filename”, ‘r’)‘ and if we want to access it in write mode we use ‘with open(“filename”, ‘w’) the only difference between reading mode and write mode is ‘r’ and ‘w’.

What are read mode and write mode?

In the read mode, we can only access the file means we can only read that file and can’t do anything with it while in write mode not only we can access the file but we can also write in it.

You already know how to display text on the screen so here is the challenge for us to update the high score which is not so tough task and then store that value in our file ‘highscore.txt’ so that if we quit our game and run again our high score shouldn’t delete or vanished.

Now, look at the first step toward it.

#highscore part
    with open ("car game\highscore.txt","r") as f:
            highscore = f.read()

We first accessed our file in reading mode as f and then we created a variable highscore in which we read the content inside it.

def show_highscore(x,y):
        Hiscore_text = font1.render('HISCORE :' + str(highscore),True,(255,0,0))
        screen.blit (Hiscore_text,(x,y))
        pygame.display.update()

Then we created a function show_highscore(x,y) in which we created a variable Hiscore_text which will be the text that we’ll be displaying on the screen. We have discussed displaying text in detail in the previous section. So I won’t go into more detail in this section.

 #checking if highscore has been created
        if score_value > int(highscore):
            highscore = score_value

Next, we checked if our score has become greater than our highscore. If yes, then we gave the value of our score to the highscore.

        show_highscore(0,0)
        # writing to our highscore.txt file
        with open ("car game\highscore.txt","w") as f:
            f.write(str(highscore))

After then, we called our show_highscore function with (0, 0) coordinates. Then we accessed our ‘highscore.txt’ file in write mode and wrote the value of highscore in it.

Now, look at the whole code below.

import pygame,sys
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
import random
import math
import time
screen = pygame.display.set_mode((798,600))

#initializing pygame mixer
pygame.mixer.init()

#changing title of the game window
pygame.display.set_caption('Racing Beast')

#changing the logo
logo = pygame.image.load('car game/logo.jpeg')
pygame.display.set_icon(logo)

  ###### Countdown ######
def countdown():
    font2 = pygame.font.Font('freesansbold.ttf', 85)
    countdownBacground = pygame.image.load('car game/bg.png')
    three = font2.render('3',True, (187,30,16))
    two =   font2.render('2',True, (255,255,0))
    one =   font2.render('1',True, (51,165,50))
    go =    font2.render('GO!!!',True, (0,255,0))
    
    

               ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()

    ###### Displaying  three (3) ######
    screen.blit(three,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  two (2) ######
    screen.blit(two,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  one (1) ######
    screen.blit(one,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  Go!!! ######
    screen.blit(go,(300,250))
    pygame.display.update()
    time.sleep(1)
    gameloop() #calling the gamloop so that our game can start after the countdown
    pygame.display.update()


#defining our gameloop function
def gameloop():

      ####### music ####### 
    pygame.mixer.music.load('car game\BackgroundMusic.mp3')
    pygame.mixer.music.play()
    ###### sound effect for collision ######
    crash_sound = pygame.mixer.Sound('car game\car_crash.wav')

    ####### scoring part ######
    score_value = 0
    font1= pygame.font.Font("freesansbold.ttf",25)
    def show_score(x,y):
        score = font1.render("SCORE: "+ str(score_value), True, (255,0,0))
        screen.blit(score, (x,y))

    #highscore part
    with open ("car game\highscore.txt","r") as f:
            highscore = f.read()
    def show_highscore(x,y):
        Hiscore_text = font1.render('HISCORE :' + str(highscore),True,(255,0,0))
        screen.blit (Hiscore_text,(x,y))
        pygame.display.update()
    
    #setting background image
    bg = pygame.image.load('car game/bg.png')

    
    # setting our player
    maincar = pygame.image.load('car game\car.png')
    maincarX = 350
    maincarY = 495
    maincarX_change = 0
    maincarY_change = 0

    #other cars
    car1 = pygame.image.load('car game\car1.jpeg')
    car1X = random.randint(178,490)
    car1Y = 100
    car1Ychange = 10

    car2 = pygame.image.load('car game\car2.png')
    car2X = random.randint(178,490)
    car2Y = 100
    car2Ychange = 10

    car3 = pygame.image.load('car game\car3.png')
    car3X = random.randint(178,490)
    car3Y = 100
    car3Ychange = 10
       

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()

                #checking if any key has been pressed
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change += 5
            
                if event.key == pygame.K_LEFT:
                    maincarX_change -= 5
                
                if event.key == pygame.K_UP:
                    maincarY_change -= 5
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change += 5

                #checking if key has been lifted up
            if event.type == pygame.KEYUP: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change = 0
            
                if event.key == pygame.K_LEFT:
                    maincarX_change = 0
                
                if event.key == pygame.K_UP:
                    maincarY_change = 0
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change = 0            

        #setting boundary for our main car
        if maincarX < 178:
            maincarX = 178
        if maincarX > 490:
            maincarX = 490
        
        if maincarY < 0:
            maincarY = 0
        if maincarY > 495:
            maincarY = 495


        #CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE 
        screen.fill((0,0,0))

        #displaying the background image
        screen.blit(bg,(0,0))

        #displaying our main car
        screen.blit(maincar,(maincarX,maincarY))

        #displaing other cars
        screen.blit(car1,(car1X,car1Y))
        screen.blit(car2,(car2X,car2Y))
        screen.blit(car3,(car3X,car3Y))

        
        
        #updating the values
        maincarX += maincarX_change
        maincarY +=maincarY_change

        #movement of the enemies
        car1Y += car1Ychange
        car2Y += car2Ychange
        car3Y += car3Ychange
        #moving enemies infinitely
        if car1Y > 670:
            car1Y = -100
            car1X = random.randint(178,490)
            score_value += 1
        if car2Y > 670:
            car2Y = -150
            car2X = random.randint(178,490)
            score_value += 1
        if car3Y > 670:
            car3Y = -200
            car3X = random.randint(178,490)
            score_value += 1

        #checking if highscore has been created
        if score_value > int(highscore):
            highscore = score_value


        #DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False
        
        ##### giving collision a variable #####

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY) 

        #if coll1 occur
        if coll1: 
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
           
            
        
        #if coll2 occur
        if coll2:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
           

        #if coll3 occur    
        if coll3:
            screen.fill((200,215,250))
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
           
        
            #calling our show_score function
        show_score(570,280)
        #calling show_hiscore function
        show_highscore(0,0)
        # writing to our highscore.txt file
        with open ("car game\highscore.txt","w") as f:
            f.write(str(highscore))

        pygame.display.update()
countdown()

I hope you all understood yet, now in the next section, we’ll be creating the game over function in which we’ll display the game over the image and will display the score and highscore in it.

Creating Game Over Function

In this section we’ll create a game-over function what we’ll be doing in this is we will display the gameover image instead of the text, we’ll be showing the score and highscore also and we’ll be also give the user option if they want to play again or want to exit the game.

The next thing we’ll do is we’ll call our gameover function after each collision. So let’s look at our gameover function.

###### creating our game over function #######

    def gameover():
        gameoverImg = pygame.image.load("car game\gameover.png")
        run = True
        while run:

            screen.blit(gameoverImg,(0,0))
            time.sleep(0.5)
            show_score(330,400)
            time.sleep(0.5)
            show_highscore(330,450)
            pygame.display.update()
            
            for event in pygame.event.get():
             if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()
             if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    countdown()
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()

At first in this function, we loaded our gameover image and then created a variable run and passed it a boolean value True, and then made a while loop. In the while loop, we displayed our gameover image, and then we called our show_score and show_highscore with 0.5 seconds of delay by using time.sleep(0.5).

After then we handled some events like the quit events which we have learned at the beginning of this tutorial. After then we checked if the space key has been pressed if yes then we called our countdown() function and our game restarted. And then we checked if the escape key has been pressed. If yes then we quit our game.

Now, run the whole code and check if everything is working properly.

import pygame,sys
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
import random
import math
import time
screen = pygame.display.set_mode((798,600))

#initializing pygame mixer
pygame.mixer.init()

#changing title of the game window
pygame.display.set_caption('Racing Beast')

#changing the logo
logo = pygame.image.load('car game/logo.jpeg')
pygame.display.set_icon(logo)



  ###### Countdown ######
def countdown():
    font2 = pygame.font.Font('freesansbold.ttf', 85)
    countdownBacground = pygame.image.load('car game/bg.png')
    three = font2.render('3',True, (187,30,16))
    two =   font2.render('2',True, (255,255,0))
    one =   font2.render('1',True, (51,165,50))
    go =    font2.render('GO!!!',True, (0,255,0))
    
    

               ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()

    ###### Displaying  three (3) ######
    screen.blit(three,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  two (2) ######
    screen.blit(two,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  one (1) ######
    screen.blit(one,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  Go!!! ######
    screen.blit(go,(300,250))
    pygame.display.update()
    time.sleep(1)
    gameloop() #calling the gamloop so that our game can start after the countdown
    pygame.display.update()


#defining our gameloop function
def gameloop():

      ####### music ####### 
    pygame.mixer.music.load('car game\BackgroundMusic.mp3')
    pygame.mixer.music.play()
    ###### sound effect for collision ######
    crash_sound = pygame.mixer.Sound('car game\car_crash.wav')

    ####### scoring part ######
    score_value = 0
    font1= pygame.font.Font("freesansbold.ttf",25)

    def show_score(x,y):
        score = font1.render("SCORE: "+ str(score_value), True, (255,0,0))
        screen.blit(score, (x,y))

    #highscore part
    with open ("car game\highscore.txt","r") as f:
            highscore = f.read()
    def show_highscore(x,y):
        Hiscore_text = font1.render('HISCORE :' + str(highscore),True,(255,0,0))
        screen.blit (Hiscore_text,(x,y))
        pygame.display.update()
    
    ###### creating our game over function #######

    def gameover(x,y):
        gameoverImg = pygame.image.load("car game\gameover.png")
        run = True
        while run:

            screen.blit(gameoverImg,(x,y))
            time.sleep(0.5)
            show_score(330,400)
            time.sleep(0.5)
            show_highscore(330,450)
            pygame.display.update()
            
            for event in pygame.event.get():
             if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()
             if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    countdown()
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
        
    
    #setting background image
    bg = pygame.image.load('car game/bg.png')
    
    
    # setting our player
    maincar = pygame.image.load('car game\car.png')
    maincarX = 350
    maincarY = 495
    maincarX_change = 0
    maincarY_change = 0

    #other cars
    car1 = pygame.image.load('car game\car1.jpeg')
    car1X = random.randint(178,490)
    car1Y = 100
    car1Ychange = 10    
    car2 = pygame.image.load('car game\car2.png')
    car2X = random.randint(178,490)
    car2Y = 100
    car2Ychange = 10

    car3 = pygame.image.load('car game\car3.png')
    car3X = random.randint(178,490)
    car3Y = 100
    car3Ychange = 10
       

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()

                #checking if any key has been pressed
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change += 5
            
                if event.key == pygame.K_LEFT:
                    maincarX_change -= 5
                
                if event.key == pygame.K_UP:
                    maincarY_change -= 5
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change += 5

                #checking if key has been lifted up
            if event.type == pygame.KEYUP: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change = 0
            
                if event.key == pygame.K_LEFT:
                    maincarX_change = 0
                
                if event.key == pygame.K_UP:
                    maincarY_change = 0
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change = 0            

        #setting boundary for our main car
        if maincarX < 178:
            maincarX = 178
        if maincarX > 490:
            maincarX = 490
        
        if maincarY < 0:
            maincarY = 0
        if maincarY > 495:
            maincarY = 495


        #CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE 
        screen.fill((0,0,0))

        #displaying the background image
        screen.blit(bg,(0,0))

        #displaying our main car
        screen.blit(maincar,(maincarX,maincarY))

        #displaing other cars
        screen.blit(car1,(car1X,car1Y))
        screen.blit(car2,(car2X,car2Y))
        screen.blit(car3,(car3X,car3Y))
          #calling our show_score function
        show_score(570,280)
        #calling show_hiscore function
        show_highscore(0,0)

        
        
        #updating the values
        maincarX += maincarX_change
        maincarY += maincarY_change

        #movement of the enemies
        car1Y += car1Ychange
        car2Y += car2Ychange
        car3Y += car3Ychange
        #moving enemies infinitely
        if car1Y > 670:
            car1Y = -100
            car1X = random.randint(178,490)
            score_value += 1
        if car2Y > 670:
            car2Y = -150
            car2X = random.randint(178,490)
            score_value += 1
        if car3Y > 670:
            car3Y = -200
            car3X = random.randint(178,490)
            score_value += 1

        #checking if highscore has been created
        if score_value > int(highscore):
            highscore = score_value

          
         


        #DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False
        
        ##### giving collision a variable #####

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY) 

        #if coll1 occur
        if coll1: 
            
            
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            car1Y = 0
            car2Y = 0
            car3Y = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
        ###### calling our game over function #######
            time.sleep(1)
            gameover(0,0)
          
           
            
        
        #if coll2 occur
        if coll2:
           
            
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            car1Y = 0
            car2Y = 0
            car3Y = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
        ###### calling our game over function #######
            time.sleep(1)
            gameover(0,0)
           

        #if coll3 occur    
        if coll3:
            
           
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            car1Y = 0
            car2Y = 0
            car3Y = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
        ###### calling our game over function #######
            time.sleep(1)
            gameover(0,0)
        
        if car1Ychange == 0 and car2Ychange == 0 and car3Ychange == 0 :
          pass
            
            
         
            
        
        # writing to our highscore.txt file
        with open ("car game\highscore.txt","w") as f:
            f.write(str(highscore))
        

        pygame.display.update()
countdown()

It was straightforward, and our game is ready, but still, there is something missing in it. We haven’t any intro screen yet. In every game, there is an intro screen in which they have some buttons like Play, Instruction, About, etc.

So, in the next and final section, we will be creating an intro screen and will add some buttons to it. We’ll also add some music to the intro screen to make our game cool and more interesting.

Making Intro Screen and Adding Some Buttons.

We have learned a lot yet using that knowledge we’ll create our intro screen the additional topic that we don’t know is to add a button so I’ll explain that and everything will be the same as previous.

Let’s first list out what actually we will be doing in this section. We’ll first display our intro image after then we’ll be creating three buttons PLAY, INSTRUCTION, and ABOUT. If the user will click on play then our game will start, if the user will click on instruction then he will get the instruction for playing this game, and last if the user will click on the about then the user will get some information about the developer of the game and his message also. We also have intro music that we’ll be using in our game.

We have images of about and instructions. So we’ll be using those images in our about and instruction button. The first thing we’ll do is we’ll create some functions for displaying our images of the intro, about, and instruction and text which is PLAY, INSTRUCTION, and ABOUT. So let’s look at the code.

############ MAKING INTRO SCREEEN ###########
IntroFont = pygame.font.Font("freesansbold.ttf", 38)
def introImg(x,y):
    intro = pygame.image.load("car game\intro.png")
    
    screen.blit(intro,(x,y))
def instructionIMG(x,y):
    instruct = pygame.image.load("car game\instruction.png")
    run = True
    while run:
        screen.blit(instruct,(x,y))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

def aboutIMG(x,y):
    aboutimg = pygame.image.load("car game\About.png")
    run = True
    while run:
        screen.blit(aboutimg,(x,y))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
def play(x,y):
    playtext = IntroFont.render("PLAY",True,(255,0,0))
    screen.blit (playtext,(x,y))
def ABOUT(x,y):
    aboutText = IntroFont.render("ABOUT",True,(255,0,0))
    screen.blit (aboutText,(x,y))
def Instruction(x,y):
    instructionText = IntroFont.render("INSTRUCTION",True,(255,0,0))
    screen.blit(instructionText,(x,y))

First, we created a font that we’ll be using to write our texts then we created some functions for displaying intro image, instruction image, about the image, play text, about the text, and instruction text. We have covered this all topic in the previous topic so there is no need to explain it again.

Now, we’ll be creating a function introscreen in which we’ll do our remaining work.

Adding Buttons in the Game

Adding buttons in the game is easy if we understand it steps by step. The button is generally some text covered by a rectangle. So, what we are going to do is we will create a rectangle and display our text inside this rectangle.

Drawing Rectangles

     ###### storing rectangle coordinates (x, y, length, height) by making variables
        button1 = pygame.Rect(60,440,175,50)
        button2 = pygame.Rect(265,440,300,50)
        button3 = pygame.Rect(600,440,165,50)

       ###### pygame.draw.rect takes these arguments (surface, color, coordinates, border) #####
        pygame.draw.rect(screen, (255,255,255), button1,6)
        pygame.draw.rect(screen, (255,255,255), button2,6)
        pygame.draw.rect(screen,(255,255,255),button3,6)

First, we are storing the coordinates of the rectangle in variables button1, button2, button3. It took four arguments first is the x-axis, second is the y-axis, third is length or width and fourth is the height. After then we used the method to draw a rectangle which is pygame.draw.rect().

pygame.draw.rect(screen, (255,255,255), button1,6) took four arguments first surface second color third coordinate, and fourth width of the border.

Adding Text to the Button

play(100,450)
Instruction(280,450)
ABOUT(615,450)

We have already created functions for displaying text so we only needed to call this by giving x and y coordinates.

Notice the x and y-axis of the button1 which will be our PLAY button are (60, 440). Since our text should be inside this rectangle so x and y-axis of our text should be a little bit greater than it so that it can fit inside this rectangle perfectly. By trial and error method the value I got is (100, 450). That’s why we displayed our PLAY text at (100, 450) by calling it to play(100,450). The same logic was applied to button2 and button3 also.

Now, look at our output.

Complete Racing Game In Python Using PyGame

Making buttons interactive.

We have made the buttons, but it is not going to do anything yet because we haven’t coded anything yet for this. For this we have to check the click event but how do we know our mouse cursor is on the PLAY or INSTRUCTION or ABOUT button? For this, we also have to know the position of the mouse cursor or coordinates of the mouse cursor.

####### getting coordinates of mouse cursor #######
        x,y = pygame.mouse.get_pos()
 #### if our cursor is on button1 which is PLAY button
        if button1.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button1,6)
        #### if we click on the PLAY button ####
            if click:
                countdown() ## CALLING COUNTDOWN FUNCTION TO START OUR GAME


        #### if our cursor is on button2 which is INSTRUCTION button
        if button2.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button2,6)
        #### if we click on the INSTRUCTION button ####
            if click:
                instructionIMG(0,0)### DISPLAYING OUR INSTRUCTION IMAGE BY CALLING IT

        
        #### if our cursor is on button3 which is ABOUT button
        if button3.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen,(155,0,0),button3,6)
        #### if we click on the ABOUT button ####
            if click:
                aboutIMG(0,0) ### DISPLAYING OUR ABOUT IMAGE BY CALLING IT
                
        ###### checking for mouse click event
        click = False
        for event in pygame.event.get():
         if event.type == pygame.QUIT:
            run = False
         if event.type == pygame.MOUSEBUTTONDOWN:
             if event.button == 1:
                 click = True
        pygame.display.update()

From the first line which is x,y = pygame.mouse.get_pos() we are getting the position of the cursor. And then we checked if our cursor collided with the button means our cursor is on the button. If yes, we changed the color of the rectangle to red from white. Look at the code below.

#### if our cursor is on button1 which is PLAY button
        if button1.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button1,6)
 

See below how our button is changing color when we move our mouse cursor to it.

Running Functions on clicking the button.

The third part of the button is to perform some functions when a user clicks on it. For this, we need to check the click event. Look at the code below.

 ###### checking for mouse click event
        click = False
        for event in pygame.event.get():
         if event.type == pygame.QUIT:
            run = False
         if event.type == pygame.MOUSEBUTTONDOWN:
             if event.button == 1:
                 click = True

We created a variable in which we stored a boolean value ‘False‘ and then we checked of quit event and then we checked if the mouse button has been pressed which we can also say left click then our click became True. Now we have the click event we can use it to perform functions by buttons.

We’ll use it when our cursor collides with any button on the screen. Suppose our cursor is on the PLAY button and we click on that then our click will become true. So, what will we do if we click on the PLAY button obviously we will call our countdown() function so that our game can start.

If we click on the INSTRUCTION button, then we’ll call our instructionIMG(0, 0) function and if we click on ABOUT button then we’ll call our aboutIMG(0,0) function.

Now, look at the lines (7-9,16-18,25-27) of code how we did that.

####### getting coordinates of mouse cursor #######
        x,y = pygame.mouse.get_pos()
 #### if our cursor is on button1 which is PLAY button
        if button1.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button1,6)
        #### if we click on the PLAY button ####
            if click:
                countdown() ## CALLING COUNTDOWN FUNCTION TO START OUR GAME


        #### if our cursor is on button2 which is INSTRUCTION button
        if button2.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button2,6)
        #### if we click on the INSTRUCTION button ####
            if click:
                instructionIMG(0,0)### DISPLAYING OUR INSTRUCTION IMAGE BY CALLING IT

        
        #### if our cursor is on button3 which is ABOUT button
        if button3.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen,(155,0,0),button3,6)
        #### if we click on the ABOUT button ####
            if click:
                aboutIMG(0,0) ### DISPLAYING OUR ABOUT IMAGE BY CALLING IT
                
        ###### checking for mouse click event
        click = False
        for event in pygame.event.get():
         if event.type == pygame.QUIT:
            run = False
         if event.type == pygame.MOUSEBUTTONDOWN:
             if event.button == 1:
                 click = True
        pygame.display.update()

Now, we have done everything we wanted to do and our ‘RACING BEAST’ game is now ready to rock. First, have a look at the whole code that we have written in this section.

############ MAKING INTRO SCREEEN ###########
IntroFont = pygame.font.Font("freesansbold.ttf", 38)
def introImg(x,y):
    intro = pygame.image.load("car game\intro.png")
    
    screen.blit(intro,(x,y))
def instructionIMG(x,y):
    instruct = pygame.image.load("car game\instruction.png")
    run = True
    while run:
        screen.blit(instruct,(x,y))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

def aboutIMG(x,y):
    aboutimg = pygame.image.load("car game\About.png")
    run = True
    while run:
        screen.blit(aboutimg,(x,y))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
def play(x,y):
    playtext = IntroFont.render("PLAY",True,(255,0,0))
    screen.blit (playtext,(x,y))
def ABOUT(x,y):
    aboutText = IntroFont.render("ABOUT",True,(255,0,0))
    screen.blit (aboutText,(x,y))
def Instruction(x,y):
    instructionText = IntroFont.render("INSTRUCTION",True,(255,0,0))
    screen.blit(instructionText,(x,y))

def introscreen():
    run = True
    pygame.mixer.music.load('car game/startingMusic.mp3')
    pygame.mixer.music.play()
    while run :
        screen.fill((0,0,0))
        ###### dispalying the intro image by calling it.
        introImg(0,0)
        play(100,450)
        Instruction(280,450)
        ABOUT(615,450)

        ####### getting coordinates of mouse cursor #######
        x,y = pygame.mouse.get_pos()

        ###### storing rectangle coordinates (x, y, length, height) by making variables
        button1 = pygame.Rect(60,440,175,50)
        button2 = pygame.Rect(265,440,300,50)
        button3 = pygame.Rect(600,440,165,50)

        ##### Drawing rectangles with stored coorditates of rectangles.######
        ###### pygame.draw.rect takes these arguments (surface, color, coordinates, border) #####
        pygame.draw.rect(screen, (255,255,255), button1,6)
        pygame.draw.rect(screen, (255,255,255), button2,6)
        pygame.draw.rect(screen,(255,255,255),button3,6)

        #### if our cursor is on button1 which is PLAY button
        if button1.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button1,6)
        #### if we click on the PLAY button ####
            if click:
                countdown() ## CALLING COUNTDOWN FUNCTION TO START OUR GAME


        #### if our cursor is on button2 which is INSTRUCTION button
        if button2.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button2,6)
        #### if we click on the INSTRUCTION button ####
            if click:
                instructionIMG(0,0)### DISPLAYING OUR INSTRUCTION IMAGE BY CALLING IT

        
        #### if our cursor is on button3 which is ABOUT button
        if button3.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen,(155,0,0),button3,6)
        #### if we click on the ABOUT button ####
            if click:
                aboutIMG(0,0) ### DISPLAYING OUR ABOUT IMAGE BY CALLING IT
                
        ###### checking for mouse click event
        click = False
        pygame.display.update()
        for event in pygame.event.get():
         if event.type == pygame.QUIT:
            run = False
         if event.type == pygame.MOUSEBUTTONDOWN:
             if event.button == 1:
                 click = True

Now our game is ready. At last look at the whole game code of our ‘RACING BEAST’.

import pygame,sys
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
import random
import math
import time
screen = pygame.display.set_mode((798,600))

#initializing pygame mixer
pygame.mixer.init()

#changing title of the game window
pygame.display.set_caption('Racing Beast')

#changing the logo
logo = pygame.image.load('car game/logo.jpeg')
pygame.display.set_icon(logo)


############ MAKING INTRO SCREEEN ###########
IntroFont = pygame.font.Font("freesansbold.ttf", 38)
def introImg(x,y):
    intro = pygame.image.load("car game\intro.png")
    
    screen.blit(intro,(x,y))
def instructionIMG(x,y):
    instruct = pygame.image.load("car game\instruction.png")
    run = True
    while run:
        screen.blit(instruct,(x,y))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

def aboutIMG(x,y):
    aboutimg = pygame.image.load("car game\About.png")
    run = True
    while run:
        screen.blit(aboutimg,(x,y))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
def play(x,y):
    playtext = IntroFont.render("PLAY",True,(255,0,0))
    screen.blit (playtext,(x,y))
def ABOUT(x,y):
    aboutText = IntroFont.render("ABOUT",True,(255,0,0))
    screen.blit (aboutText,(x,y))
def Instruction(x,y):
    instructionText = IntroFont.render("INSTRUCTION",True,(255,0,0))
    screen.blit(instructionText,(x,y))


def introscreen():
    run = True
    pygame.mixer.music.load('car game/startingMusic.mp3')
    pygame.mixer.music.play()
    while run :
        screen.fill((0,0,0))
        introImg(0,0)
        play(100,450)
        Instruction(280,450)
        ABOUT(615,450)

        ####### getting coordinates of mouse cursor #######
        x,y = pygame.mouse.get_pos()

        ###### storing rectangle coordinates (x, y, length, height) by making variables
        button1 = pygame.Rect(60,440,175,50)
        button2 = pygame.Rect(265,440,300,50)
        button3 = pygame.Rect(600,440,165,50)

        ##### Drawing rectangles with stored coorditates of rectangles.######
        ###### pygame.draw.rect takes these arguments (surface, color, coordinates, border) #####
        pygame.draw.rect(screen, (255,255,255), button1,6)
        pygame.draw.rect(screen, (255,255,255), button2,6)
        pygame.draw.rect(screen,(255,255,255),button3,6)

        #### if our cursor is on button1 which is PLAY button
        if button1.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button1,6)
        #### if we click on the PLAY button ####
            if click:
                countdown() ## CALLING COUNTDOWN FUNCTION TO START OUR GAME


        #### if our cursor is on button2 which is INSTRUCTION button
        if button2.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button2,6)
        #### if we click on the INSTRUCTION button ####
            if click:
                instructionIMG(0,0)### DISPLAYING OUR INSTRUCTION IMAGE BY CALLING IT

        
        #### if our cursor is on button3 which is ABOUT button
        if button3.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen,(155,0,0),button3,6)
        #### if we click on the ABOUT button ####
            if click:
                aboutIMG(0,0) ### DISPLAYING OUR ABOUT IMAGE BY CALLING IT
                
        ###### checking for mouse click event
        click = False
        for event in pygame.event.get():
         if event.type == pygame.QUIT:
            run = False
         if event.type == pygame.MOUSEBUTTONDOWN:
             if event.button == 1:
                 click = True
        pygame.display.update()

  ###### Countdown ######
def countdown():
    font2 = pygame.font.Font('freesansbold.ttf', 85)
    countdownBacground = pygame.image.load('car game/bg.png')
    three = font2.render('3',True, (187,30,16))
    two =   font2.render('2',True, (255,255,0))
    one =   font2.render('1',True, (51,165,50))
    go =    font2.render('GO!!!',True, (0,255,0))
    
    

               ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()

    ###### Displaying  three (3) ######
    screen.blit(three,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  two (2) ######
    screen.blit(two,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  one (1) ######
    screen.blit(one,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  Go!!! ######
    screen.blit(go,(300,250))
    pygame.display.update()
    time.sleep(1)
    gameloop() #calling the gamloop so that our game can start after the countdown
    pygame.display.update()


#defining our gameloop function
def gameloop():

      ####### music ####### 
    pygame.mixer.music.load('car game\BackgroundMusic.mp3')
    pygame.mixer.music.play()
    ###### sound effect for collision ######
    crash_sound = pygame.mixer.Sound('car game\car_crash.wav')

    ####### scoring part ######
    score_value = 0
    font1= pygame.font.Font("freesansbold.ttf",25)

    def show_score(x,y):
        score = font1.render("SCORE: "+ str(score_value), True, (255,0,0))
        screen.blit(score, (x,y))

    #highscore part
    with open ("car game\highscore.txt","r") as f:
            highscore = f.read()
    def show_highscore(x,y):
        Hiscore_text = font1.render('HISCORE :' + str(highscore),True,(255,0,0))
        screen.blit (Hiscore_text,(x,y))
        pygame.display.update()
    
    ###### creating our game over function #######

    def gameover():
        gameoverImg = pygame.image.load("car game\gameover.png")
        run = True
        while run:

            screen.blit(gameoverImg,(0,0))
            time.sleep(0.5)
            show_score(330,400)
            time.sleep(0.5)
            show_highscore(330,450)
            pygame.display.update()
            
            for event in pygame.event.get():
             if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()
             if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    countdown()
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
        
    
    #setting background image
    bg = pygame.image.load('car game/bg.png')
    
    
    # setting our player
    maincar = pygame.image.load('car game\car.png')
    maincarX = 350
    maincarY = 495
    maincarX_change = 0
    maincarY_change = 0

    #other cars
    car1 = pygame.image.load('car game\car1.jpeg')
    car1X = random.randint(178,490)
    car1Y = 100
    car1Ychange = 10    
    car2 = pygame.image.load('car game\car2.png')
    car2X = random.randint(178,490)
    car2Y = 100
    car2Ychange = 10

    car3 = pygame.image.load('car game\car3.png')
    car3X = random.randint(178,490)
    car3Y = 100
    car3Ychange = 10
       

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()

                #checking if any key has been pressed
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change += 5
            
                if event.key == pygame.K_LEFT:
                    maincarX_change -= 5
                
                if event.key == pygame.K_UP:
                    maincarY_change -= 5
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change += 5

                #checking if key has been lifted up
            if event.type == pygame.KEYUP: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change = 0
            
                if event.key == pygame.K_LEFT:
                    maincarX_change = 0
                
                if event.key == pygame.K_UP:
                    maincarY_change = 0
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change = 0            

        #setting boundary for our main car
        if maincarX < 178:
            maincarX = 178
        if maincarX > 490:
            maincarX = 490
        
        if maincarY < 0:
            maincarY = 0
        if maincarY > 495:
            maincarY = 495


        #CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE 
        screen.fill((0,0,0))

        #displaying the background image
        screen.blit(bg,(0,0))

        #displaying our main car
        screen.blit(maincar,(maincarX,maincarY))

        #displaing other cars
        screen.blit(car1,(car1X,car1Y))
        screen.blit(car2,(car2X,car2Y))
        screen.blit(car3,(car3X,car3Y))
          #calling our show_score function
        show_score(570,280)
        #calling show_hiscore function
        show_highscore(0,0)

        
        
        #updating the values
        maincarX += maincarX_change
        maincarY += maincarY_change

        #movement of the enemies
        car1Y += car1Ychange
        car2Y += car2Ychange
        car3Y += car3Ychange
        #moving enemies infinitely
        if car1Y > 670:
            car1Y = -100
            car1X = random.randint(178,490)
            score_value += 1
        if car2Y > 670:
            car2Y = -150
            car2X = random.randint(178,490)
            score_value += 1
        if car3Y > 670:
            car3Y = -200
            car3X = random.randint(178,490)
            score_value += 1

        #checking if highscore has been created
        if score_value > int(highscore):
            highscore = score_value

          
         


        #DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False
        
        ##### giving collision a variable #####

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY) 

        #if coll1 occur
        if coll1: 
            
            
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            car1Y = 0
            car2Y = 0
            car3Y = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
        ###### calling our game over function #######
            time.sleep(1)
            gameover()
          
           
            
        
        #if coll2 occur
        if coll2:
           
            
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            car1Y = 0
            car2Y = 0
            car3Y = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
        ###### calling our game over function #######
            time.sleep(1)
            gameover()
           

        #if coll3 occur    
        if coll3:
            
           
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            car1Y = 0
            car2Y = 0
            car3Y = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
        ###### calling our game over function #######
            time.sleep(1)
            gameover()
        
        if car1Ychange == 0 and car2Ychange == 0 and car3Ychange == 0 :
          pass
            
            
         
            
        
        # writing to our highscore.txt file
        with open ("car game\highscore.txt","w") as f:
            f.write(str(highscore))
        

        pygame.display.update()
introscreen()

Full SOURCE CODE, Sprites(images), and Music.

I really enjoyed a lot in this whole journey of the Game development with pygame. We get to learn a lot and we understood every topic with all our patients. Thank you for giving your precious time there is a lot to learn yet keep visiting copyassignment if you want to learn Python. There is also a Machine learning tutorial and much more you can check out if you are serious about programming.

Here is the full source code of the game ‘Racing Beast’. And below the code is the link for all sprites or images and music.

import pygame,sys
pygame.init() #initializes the Pygame
from pygame.locals import* #import all modules from Pygame
import random
import math
import time
screen = pygame.display.set_mode((798,600))

#initializing pygame mixer
pygame.mixer.init()

#changing title of the game window
pygame.display.set_caption('Racing Beast')

#changing the logo
logo = pygame.image.load('car game/logo.jpeg')
pygame.display.set_icon(logo)


############ MAKING INTRO SCREEEN ###########
IntroFont = pygame.font.Font("freesansbold.ttf", 38)
def introImg(x,y):
    intro = pygame.image.load("car game\intro.png")
    
    screen.blit(intro,(x,y))
def instructionIMG(x,y):
    instruct = pygame.image.load("car game\instruction.png")
    run = True
    while run:
        screen.blit(instruct,(x,y))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

def aboutIMG(x,y):
    aboutimg = pygame.image.load("car game\About.png")
    run = True
    while run:
        screen.blit(aboutimg,(x,y))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
def play(x,y):
    playtext = IntroFont.render("PLAY",True,(255,0,0))
    screen.blit (playtext,(x,y))
def ABOUT(x,y):
    aboutText = IntroFont.render("ABOUT",True,(255,0,0))
    screen.blit (aboutText,(x,y))
def Instruction(x,y):
    instructionText = IntroFont.render("INSTRUCTION",True,(255,0,0))
    screen.blit(instructionText,(x,y))


def introscreen():
    run = True
    pygame.mixer.music.load('car game/startingMusic.mp3')
    pygame.mixer.music.play()
    while run :
        screen.fill((0,0,0))
        introImg(0,0)
        play(100,450)
        Instruction(280,450)
        ABOUT(615,450)

        ####### getting coordinates of mouse cursor #######
        x,y = pygame.mouse.get_pos()

        ###### storing rectangle coordinates (x, y, length, height) by making variables
        button1 = pygame.Rect(60,440,175,50)
        button2 = pygame.Rect(265,440,300,50)
        button3 = pygame.Rect(600,440,165,50)

        ##### Drawing rectangles with stored coorditates of rectangles.######
        ###### pygame.draw.rect takes these arguments (surface, color, coordinates, border) #####
        pygame.draw.rect(screen, (255,255,255), button1,6)
        pygame.draw.rect(screen, (255,255,255), button2,6)
        pygame.draw.rect(screen,(255,255,255),button3,6)

        #### if our cursor is on button1 which is PLAY button
        if button1.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button1,6)
        #### if we click on the PLAY button ####
            if click:
                countdown() ## CALLING COUNTDOWN FUNCTION TO START OUR GAME


        #### if our cursor is on button2 which is INSTRUCTION button
        if button2.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen, (155,0,0), button2,6)
        #### if we click on the INSTRUCTION button ####
            if click:
                instructionIMG(0,0)### DISPLAYING OUR INSTRUCTION IMAGE BY CALLING IT

        
        #### if our cursor is on button3 which is ABOUT button
        if button3.collidepoint(x,y):
        ### changing from inactive to active by changing the color from white to red 
            pygame.draw.rect(screen,(155,0,0),button3,6)
        #### if we click on the ABOUT button ####
            if click:
                aboutIMG(0,0) ### DISPLAYING OUR ABOUT IMAGE BY CALLING IT
                
        ###### checking for mouse click event
        click = False
        for event in pygame.event.get():
         if event.type == pygame.QUIT:
            run = False
         if event.type == pygame.MOUSEBUTTONDOWN:
             if event.button == 1:
                 click = True
        pygame.display.update()

  ###### Countdown ######
def countdown():
    font2 = pygame.font.Font('freesansbold.ttf', 85)
    countdownBacground = pygame.image.load('car game/bg.png')
    three = font2.render('3',True, (187,30,16))
    two =   font2.render('2',True, (255,255,0))
    one =   font2.render('1',True, (51,165,50))
    go =    font2.render('GO!!!',True, (0,255,0))
    
    

               ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()

    ###### Displaying  three (3) ######
    screen.blit(three,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  two (2) ######
    screen.blit(two,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  one (1) ######
    screen.blit(one,(350,250))
    pygame.display.update()
    time.sleep(1)

    ##### displaying blank background #####
    screen.blit(countdownBacground, (0,0))
    pygame.display.update()
    time.sleep(1)

        ###### Displaying  Go!!! ######
    screen.blit(go,(300,250))
    pygame.display.update()
    time.sleep(1)
    gameloop() #calling the gamloop so that our game can start after the countdown
    pygame.display.update()


#defining our gameloop function
def gameloop():

      ####### music ####### 
    pygame.mixer.music.load('car game\BackgroundMusic.mp3')
    pygame.mixer.music.play()
    ###### sound effect for collision ######
    crash_sound = pygame.mixer.Sound('car game\car_crash.wav')

    ####### scoring part ######
    score_value = 0
    font1= pygame.font.Font("freesansbold.ttf",25)

    def show_score(x,y):
        score = font1.render("SCORE: "+ str(score_value), True, (255,0,0))
        screen.blit(score, (x,y))

    #highscore part
    with open ("car game\highscore.txt","r") as f:
            highscore = f.read()
    def show_highscore(x,y):
        Hiscore_text = font1.render('HISCORE :' + str(highscore),True,(255,0,0))
        screen.blit (Hiscore_text,(x,y))
        pygame.display.update()
    
    ###### creating our game over function #######

    def gameover():
        gameoverImg = pygame.image.load("car game\gameover.png")
        run = True
        while run:

            screen.blit(gameoverImg,(0,0))
            time.sleep(0.5)
            show_score(330,400)
            time.sleep(0.5)
            show_highscore(330,450)
            pygame.display.update()
            
            for event in pygame.event.get():
             if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()
             if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    countdown()
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
        
    
    #setting background image
    bg = pygame.image.load('car game/bg.png')
    
    
    # setting our player
    maincar = pygame.image.load('car game\car.png')
    maincarX = 350
    maincarY = 495
    maincarX_change = 0
    maincarY_change = 0

    #other cars
    car1 = pygame.image.load('car game\car1.jpeg')
    car1X = random.randint(178,490)
    car1Y = 100
    car1Ychange = 10    
    car2 = pygame.image.load('car game\car2.png')
    car2X = random.randint(178,490)
    car2Y = 100
    car2Ychange = 10

    car3 = pygame.image.load('car game\car3.png')
    car3X = random.randint(178,490)
    car3Y = 100
    car3Ychange = 10
       

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()

                #checking if any key has been pressed
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change += 5
            
                if event.key == pygame.K_LEFT:
                    maincarX_change -= 5
                
                if event.key == pygame.K_UP:
                    maincarY_change -= 5
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change += 5

                #checking if key has been lifted up
            if event.type == pygame.KEYUP: 
                if event.key == pygame.K_RIGHT:
                    maincarX_change = 0
            
                if event.key == pygame.K_LEFT:
                    maincarX_change = 0
                
                if event.key == pygame.K_UP:
                    maincarY_change = 0
                    
                if event.key == pygame.K_DOWN:
                    maincarY_change = 0            

        #setting boundary for our main car
        if maincarX < 178:
            maincarX = 178
        if maincarX > 490:
            maincarX = 490
        
        if maincarY < 0:
            maincarY = 0
        if maincarY > 495:
            maincarY = 495


        #CHANGING COLOR WITH RGB VALUE, RGB = RED, GREEN, BLUE 
        screen.fill((0,0,0))

        #displaying the background image
        screen.blit(bg,(0,0))

        #displaying our main car
        screen.blit(maincar,(maincarX,maincarY))

        #displaing other cars
        screen.blit(car1,(car1X,car1Y))
        screen.blit(car2,(car2X,car2Y))
        screen.blit(car3,(car3X,car3Y))
          #calling our show_score function
        show_score(570,280)
        #calling show_hiscore function
        show_highscore(0,0)

        
        
        #updating the values
        maincarX += maincarX_change
        maincarY += maincarY_change

        #movement of the enemies
        car1Y += car1Ychange
        car2Y += car2Ychange
        car3Y += car3Ychange
        #moving enemies infinitely
        if car1Y > 670:
            car1Y = -100
            car1X = random.randint(178,490)
            score_value += 1
        if car2Y > 670:
            car2Y = -150
            car2X = random.randint(178,490)
            score_value += 1
        if car3Y > 670:
            car3Y = -200
            car3X = random.randint(178,490)
            score_value += 1

        #checking if highscore has been created
        if score_value > int(highscore):
            highscore = score_value

          
         


        #DETECTING COLLISIONS BETWEEN THE CARS

        #getting distance between our main car and car1
        def iscollision(car1X,car1Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car1X-maincarX,2) + math.pow(car1Y - maincarY,2)) 

            #checking if distance is smaller than 50 after then collision will occur

            if distance < 50: 
                return True
            else:
                return False

        #getting distance between our main car and car2
        def iscollision(car2X,car2Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car2X-maincarX,2) + math.pow(car2Y - maincarY,2))

            #checking if distance is smaller than 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False

        #getting distance between our main car and car3
        def iscollision(car3X,car3Y,maincarX,maincarY):
            distance = math.sqrt(math.pow(car3X-maincarX,2) + math.pow(car3Y - maincarY,2))

            #checking if distance is smaller then 50 after then collision will occur
            if distance < 50:
                return True
            else:
                return False
        
        ##### giving collision a variable #####

        #collision between maincar and car1
        coll1 = iscollision(car1X,car1Y,maincarX,maincarY) 

        #collision between maincar and car2
        coll2 = iscollision(car2X,car2Y,maincarX,maincarY) 

        #collision between maincar and car3
        coll3 = iscollision(car3X,car3Y,maincarX,maincarY) 

        #if coll1 occur
        if coll1: 
            
            
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            car1Y = 0
            car2Y = 0
            car3Y = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
        ###### calling our game over function #######
            time.sleep(1)
            gameover()
          
           
            
        
        #if coll2 occur
        if coll2:
           
            
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            car1Y = 0
            car2Y = 0
            car3Y = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
        ###### calling our game over function #######
            time.sleep(1)
            gameover()
           

        #if coll3 occur    
        if coll3:
            
           
            car1Ychange = 0
            car2Ychange = 0
            car3Ychange = 0
            car1Y = 0
            car2Y = 0
            car3Y = 0
            maincarX_change = 0
            maincarY_change = 0
            pygame.mixer.music.stop()
            crash_sound.play()
        ###### calling our game over function #######
            time.sleep(1)
            gameover()
        
        if car1Ychange == 0 and car2Ychange == 0 and car3Ychange == 0 :
          pass
            
            
         
            
        
        # writing to our highscore.txt file
        with open ("car game\highscore.txt","w") as f:
            f.write(str(highscore))
        

        pygame.display.update()
introscreen()

For downloading the images and music click on the link given below.

RACING BEAST SPRITES AND MUSIC

I tried my best with me all my effort to explain the game development in python I tried to keep it at a very basic level so that even beginners can understand it. I hope you will all like my effort. However, if you have any problems or queries in any place to understand it you can comment down or you can also send a message to me on Instagram. My Instagram id is @sameer74242

Now, it’s time to show your creativity. Customize this game and add some new features to it and send it to me on Instagram @sameer74242 and @pythonhub. We would appreciate your effort. Till then keep learning, keep rocking and keep vising copyassignment.

Thank you.

Share:
Avatar of Sameer Pandey

Author: Sameer Pandey