Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Turtle
  • Tkinter
  • Matplotlib
  • Python Imaging Library
  • Pyglet
  • Python
  • Numpy
  • Pandas
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Django
  • Flask
  • R
Open In App
Next Article:
Spiral Sprint Game in Python Using Pygame
Next article icon

Car Race Game In PyGame

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to create a racing car game in Python using Pygame. In this game, we will have functionality like driving, obstacle crashing, speed increment when levels are passed, pause, countdown, scoreboard, and Instruction manual screen. 

Required Modules:

Before going any further Install necessary packages by running the following lines in the command prompt and import them to your game.py file: 

pip install pygame
pip install time
pip install random

Project Structure:

Racing Car Game using Python Pygame
Repository 

Step 1: Import all the modules

Python3
# code for developing car racing game in python import pygame import time import random 

Step 2: Setting the Screen

Initialize all the Pygame modules with the help of pygame.init(). Now set the color values. Now set the captions for different texts

pygame.image.load() is used for loading image resources
Python3
# Initialize pygame and set the colors with captions pygame.init()  # Define color codes gray = (119, 118, 110) black = (0, 0, 0) red = (255, 0, 0) green = (0, 200, 0) blue = (0, 0, 200) bright_red = (255, 0, 0) bright_green = (0, 255, 0) bright_blue = (0, 0, 255)  # Define display dimensions display_width = 800 display_height = 600  # Set up game display gamedisplays = pygame.display.set_mode((display_width,                                          display_height)) pygame.display.set_caption("car game") clock = pygame.time.Clock()  # Load car image and background images carimg = pygame.image.load('car1.jpg') backgroundpic = pygame.image.load("download12.jpg") yellow_strip = pygame.image.load("yellow strip.jpg") strip = pygame.image.load("strip.jpg") intro_background = pygame.image.load("background.jpg") instruction_background = pygame.image.load("background2.jpg")  # Set car width and initialize pause state car_width = 56 pause = False 

Step 3: Working with Start screen

In the intro screen, there will be three buttons named START, QUIT, and INSTRUCTION. The START button will initialize the game, the QUIT button will exit the window, INSTRUCTION button will show the player controls

Now if the current screen is the intro screen then a boolean named intro will be set to True.

Draw rectangles using .rect(). Pass length, breadth, width & height to make the rectangle. 
blit() will take that rectangular Surface and put it on top of the screen.
Python3
# Intro screen def intro_loop():     intro = True     while intro:         for event in pygame.event.get():             if event.type == pygame.QUIT:                 pygame.quit()                 quit()                 sys.exit()          # Display background image         gamedisplays.blit(intro_background,                            (0, 0))          # Render and display "CAR GAME" text         largetext = pygame.font.Font                     ('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects                         ("CAR GAME", largetext)         TextRect.center = (400, 100)         gamedisplays.blit(TextSurf, TextRect)          # Render and display "START" button         button("START", 150, 520, 100, 50, green,                                    bright_green, "play")          # Render and display "QUIT" button         button("QUIT", 550, 520, 100, 50, red,                                    bright_red, "quit")          # Render and display "INSTRUCTION" button         button("INSTRUCTION", 300, 520, 200,                        50, blue, bright_blue, "intro")          pygame.display.update()         clock.tick(50) 

Step 4:  Add Functionality for Buttons

Now let's make those fancy-looking buttons into reactive buttons. Think of scenarios like what should be  the ability of the button that you have created i.e The PLAY button should trigger the main game loop with a counter which counts the number of seconds a player has played game The QUIT button should exit the window INTRO button should give an instruction manual of the game(Details discussed as you move downwards)The PAUSE button should freeze the current flow of the game and show a new screen with CONTINUE, RESTART, and MAIN MENU buttons (Details discussed as you move downwards).

Python3
# Function to create a button with specified parameters # msg: The text to be displayed on the button # x, y: The coordinates of the top-left corner of the button # w, h: The width and height of the button # ic: The color of the button when inactive # ac: The color of the button when active (hovered over) # action: The action to be performed when the button is clicked  def button(msg, x, y, w, h, ic, ac, action=None):     # Get the current mouse position     mouse = pygame.mouse.get_pos()     # Get the current state of mouse buttons     click = pygame.mouse.get_pressed()      # Check if mouse is within the button's boundaries     if x+w > mouse[0] > x and y+h > mouse[1] > y:         # Draw button with active color         pygame.draw.rect(gamedisplays, ac, (x, y, w, h))         # Check if left mouse button is clicked         # and action is specified         if click[0] == 1 and action != None:              # If action is "play", call the countdown()             if action == "play":                 countdown()              # If action is "quit", quit the game             elif action == "quit":                 pygame.quit()                 quit()                 sys.exit()              elif action == "intro":                 introduction()             # If action is "menu", call the intro_loop() function             elif action == "menu":                 intro_loop()             # If action is "pause", call the paused() function             elif action == "pause":                 paused()              # If action is "unpause", call the unpaused() function                 unpaused()             elif action == "unpause":      else:         # Draw button with inactive color         pygame.draw.rect(gamedisplays, ic, (x, y, w, h))     smalltext = pygame.font.Font("freesansbold.ttf", 20)     textsurf, textrect = text_objects(msg, smalltext)     textrect.center = ((x+(w/2)), (y+(h/2)))     gamedisplays.blit(textsurf, textrect) 

Step 5: Implementing Introduction Screen

Since the current screen is the instruction screen we will set the instruction boolean to true. Now in an Instruction manual, the most important things are the controls of the player and what the game is about. So we will organize those details in the instructions screen.

pygame.font.Font('fontname.ttf', fontsize) => This will display the font woth its given font size
Python3
# Function to display the introduction screen def introduction():     introduction = True     while introduction:          # Get events from the event queue         for event in pygame.event.get():             # If the 'QUIT' event is triggered              # (e.g., window closed)             if event.type == pygame.QUIT:                 pygame.quit()  # Quit pygame                 quit()  # Quit the game                 sys.exit()  # Exit the system         # Draw the instruction background         gamedisplays.blit(instruction_background, (0, 0))         # Set font for large text         largetext = pygame.font.Font('freesansbold.ttf', 80)         # Set font for small text         smalltext = pygame.font.Font('freesansbold.ttf', 20)         # Set font for medium text         mediumtext = pygame.font.Font('freesansbold.ttf', 40)          # Render and draw the instruction text         textSurf, textRect = text_objects("This is an car game" +                "in which you need dodge the coming cars", smalltext)         textRect.center = ((350), (200))         TextSurf, TextRect = text_objects("INSTRUCTION", largetext)         TextRect.center = ((400), (100))         gamedisplays.blit(TextSurf, TextRect)         gamedisplays.blit(textSurf, textRect)          # Render and draw the control instructions         stextSurf, stextRect = text_objects(             "ARROW LEFT : LEFT TURN", smalltext)         stextRect.center = ((150), (400))         hTextSurf, hTextRect = text_objects(             "ARROW RIGHT : RIGHT TURN", smalltext)         hTextRect.center = ((150), (450))         atextSurf, atextRect = text_objects                     ("A : ACCELERATOR", smalltext)         atextRect.center = ((150), (500))         rtextSurf, rtextRect = text_objects                         ("B : BRAKE ", smalltext)         rtextRect.center = ((150), (550))         ptextSurf, ptextRect = text_objects                         ("P : PAUSE  ", smalltext)         ptextRect.center = ((150), (350))         sTextSurf, sTextRect = text_objects                             ("CONTROLS", mediumtext)         sTextRect.center = ((350), (300))         gamedisplays.blit(sTextSurf, sTextRect)         gamedisplays.blit(stextSurf, stextRect)         gamedisplays.blit(hTextSurf, hTextRect)         gamedisplays.blit(atextSurf, atextRect)         gamedisplays.blit(rtextSurf, rtextRect)         gamedisplays.blit(ptextSurf, ptextRect)          # Render and draw the 'BACK' button         button("BACK", 600, 450, 100, 50, blue,                                 bright_blue, "menu")          pygame.display.update()  # Update the display         clock.tick(30)  # Limit frame rate to 30 FPS 

Step 6:  Implementing the Pause Function

Since the pause function will be there when you are playing the game it should have the capability to freeze every global action except its own function. So to make sure this happens we use a global declaration in the Pause button with the value set as True. When Pause is pressed it shows a new screen with CONTINUE, RESTART, and MAIN MENU buttons. When unpaused we simply reset the global boolean pause to False.

Python3
def paused():     global pause      # Loop for handling events during pause state     while pause:         for event in pygame.event.get():             if event.type == pygame.QUIT:                 pygame.quit()                 quit()                 sys.exit()         gamedisplays.blit(instruction_background,                            (0, 0))         largetext = pygame.font.Font('freesansbold.ttf',                                115)         TextSurf, TextRect = text_objects("PAUSED",                              largetext)         TextRect.center = (           (display_width/2),            (display_height/2))         gamedisplays.blit(TextSurf, TextRect)         # Create buttons for continue, restart, and main menu         button("CONTINUE", 150,                 450, 150, 50,                 green, bright_green, "unpause")         button("RESTART", 350,                 450, 150, 50,                 blue, bright_blue, "play")         button("MAIN MENU", 550,                 450, 200, 50,                 red, bright_red, "menu")         pygame.display.update()         clock.tick(30)   def unpaused():     global pause     pause = False 

Step 7: Countdown System of the Game

Let us make a scoreboard where the score and dodged cars will be accounted for. Apart from this let us also put the pause button in the countdown_background().

Python3
def countdown_background():     # Import the necessary modules and set up the game display     # Initialize the font for displaying text     font = pygame.font.SysFont(None, 25)     # Set the initial positions for the game objects     # (background, strips, car, and text)     x = (display_width*0.45)     y = (display_height*0.8)     # Draw the background images on the game display     gamedisplays.blit(backgroundpic, (0, 0))     gamedisplays.blit(backgroundpic, (0, 200))     gamedisplays.blit(backgroundpic, (0, 400))     gamedisplays.blit(backgroundpic, (700, 0))     gamedisplays.blit(backgroundpic, (700, 200))     gamedisplays.blit(backgroundpic, (700, 400))     # Draw the yellow strips on the game display     gamedisplays.blit(yellow_strip, (400, 100))     gamedisplays.blit(yellow_strip, (400, 200))     gamedisplays.blit(yellow_strip, (400, 300))     gamedisplays.blit(yellow_strip, (400, 400))     gamedisplays.blit(yellow_strip, (400, 100))     gamedisplays.blit(yellow_strip, (400, 500))     gamedisplays.blit(yellow_strip, (400, 0))     gamedisplays.blit(yellow_strip, (400, 600))     # Draw the side strips on the game display     gamedisplays.blit(strip, (120, 200))     gamedisplays.blit(strip, (120, 0))     gamedisplays.blit(strip, (120, 100))     gamedisplays.blit(strip, (680, 100))     gamedisplays.blit(strip, (680, 0))     gamedisplays.blit(strip, (680, 200))     # Draw the car on the game display     gamedisplays.blit(carimg, (x, y))     # Draw the text for the score and number of dodged cars     text = font.render("DODGED: 0", True, black)     score = font.render("SCORE: 0", True, red)     gamedisplays.blit(text, (0, 50))     gamedisplays.blit(score, (0, 30))     # Draw the "PAUSE" button on the game display     button("PAUSE", 650, 0, 150, 50, blue, bright_blue, "pause") 

Step 8:  Implementing the Countdown function

Whenever the game is on our countdown will be on so let's set the boolean countdown as true. Now loop until the countdown is true and in the loop call countdown_background. Also during the countdown, the clock should be ticking every 1sec so set the clock. tick(1). After every second we will update the display. This loop continues till the countdown boolean becomes false.

gamedisplay.fill(color) => This will file the gamedisplay woth the given color
pygame.display.update() => This updates the entire game GUI every time it is called
Python3
def countdown():     # Initialize a boolean variable to indicate if countdown is i         # n progress     countdown = True     # Continue looping until countdown is complete     while countdown:         # Check for events in the pygame event queue         for event in pygame.event.get():             # If user closes the game window             if event.type == pygame.QUIT:                 pygame.quit()  # Quit pygame                 quit()  # Quit the game                 sys.exit()  # Exit the program         # Fill the game display with a gray color         gamedisplays.fill(gray)         # Call a function to display the countdown background         countdown_background()          # Display "3" in large font at the center of the screen         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("3", largetext)         TextRect.center = ((display_width/2), (display_height/2))         gamedisplays.blit(TextSurf, TextRect)         pygame.display.update()         clock.tick(1)  # Delay for 1 second          gamedisplays.fill(gray)         countdown_background()          # Display "2" in large font at the center of the screen         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("2", largetext)         TextRect.center = ((display_width/2), (display_height/2))         gamedisplays.blit(TextSurf, TextRect)         pygame.display.update()         clock.tick(1)  # Delay for 1 second          gamedisplays.fill(gray)         countdown_background()          # Display "1" in large font at the center of the screen         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("1", largetext)         TextRect.center = ((display_width/2), (display_height/2))         gamedisplays.blit(TextSurf, TextRect)         pygame.display.update()         clock.tick(1)  # Delay for 1 second          gamedisplays.fill(gray)         countdown_background()          # Display "GO!!!" in large font at the center of the screen         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("GO!!!", largetext)         TextRect.center = ((display_width/2), (display_height/2))         gamedisplays.blit(TextSurf, TextRect)         pygame.display.update()         clock.tick(1)  # Delay for 1 second         # Call the game loop function after the countdown is complete         game_loop() 

Step 9: Defining Obstacles in Game

In a car race there will be some obstacles like opponent cars so let us define those obstacles. For obstacles to be made, we need their x,y, and obs id. Once we get this we can easily load those obstacles in the game window.

Python3
# Loading the obstacles def obstacle(obs_startx, obs_starty, obs):     if obs == 0:         obs_pic = pygame.image.load("car.jpg")     elif obs == 1:         obs_pic = pygame.image.load("car1.jpg")     elif obs == 2:         obs_pic = pygame.image.load("car2.jpg")     elif obs == 3:         obs_pic = pygame.image.load("car4.jpg")     elif obs == 4:         obs_pic = pygame.image.load("car5.jpg")     elif obs == 5:         obs_pic = pygame.image.load("car6.jpg")     elif obs == 6:         obs_pic = pygame.image.load("car7.jpg")     gamedisplays.blit(obs_pic, (obs_startx, obs_starty)) 

Step 10: Implementing Score System 

The score_system() function is used for showing the score and is used in the game_loop function which will be discussed below.text_objects() function is used for text rendering on screen.message_display() is used for displaying text we just need to pass the text that we want to show on the game screen.

Python3
def score_system(passed, score):     # Create a font object with size 25     font = pygame.font.SysFont(None, 25)     # Render the "Passed" text with passed parameter     # and color black     text = font.render("Passed"+str(passed), True, black)     # Render the "Score" text with score parameter and color red     score = font.render("Score"+str(score), True, red)     # Draw the "Passed" text on the game display at (0, 50)     # coordinates     gamedisplays.blit(text, (0, 50))     # Draw the "Score" text on the game display at (0, 30)     # coordinates     gamedisplays.blit(score, (0, 30))   def text_objects(text, font):     # Render the given text with the given font and color black     textsurface = font.render(text, True, black)     return textsurface, textsurface.get_rect()   def message_display(text):     # Create a font object with size 80     largetext = pygame.font.Font("freesansbold.ttf", 80)     # Render the given text with the created font     textsurf, textrect = text_objects(text, largetext)     textrect.center = ((display_width/2), (display_height/2))     # Draw the rendered text on the game display at the center of the     # screen     gamedisplays.blit(textsurf, textrect)     pygame.display.update()     time.sleep(3)     game_loop() 

Step 11: Fallback Logic

Whatever a developer builds the developer should always think about some fallback mechanism i.e if something goes wrong and the program does not work then the user should know what has happened. In this case, we will be displaying the message "YOU CRASHED" on the main screen. 

Python3
def crash():     message_display("YOU CRASHED") 

Step 12: Onscreen Game UI

For a racing game, we will need a road image and some background scenery terrain. We make this UI in the background function. Yellow strips are the vertical strip in the road that are usually placed in the middle of the road. 

Python3
# on Screen UI def background():     gamedisplays.blit(backgroundpic, (0, 0))     gamedisplays.blit(backgroundpic, (0, 200))     gamedisplays.blit(backgroundpic, (0, 400))     gamedisplays.blit(backgroundpic, (700, 0))     gamedisplays.blit(backgroundpic, (700, 200))     gamedisplays.blit(backgroundpic, (700, 400))     gamedisplays.blit(yellow_strip, (400, 0))     gamedisplays.blit(yellow_strip, (400, 100))     gamedisplays.blit(yellow_strip, (400, 200))     gamedisplays.blit(yellow_strip, (400, 300))     gamedisplays.blit(yellow_strip, (400, 400))     gamedisplays.blit(yellow_strip, (400, 500))     gamedisplays.blit(strip, (120, 0))     gamedisplays.blit(strip, (120, 100))     gamedisplays.blit(strip, (120, 200))     gamedisplays.blit(strip, (680, 0))     gamedisplays.blit(strip, (680, 100))     gamedisplays.blit(strip, (680, 200))   def car(x, y):     gamedisplays.blit(carimg, (x, y)) 

Step 13:  Working on the Game

As soon as game_loop() is initialized we check whether the boolean pause if it's false then we go further. We will set the obstacle_speed to 9 you can change the speed according to your convenience. Now we need to pop obstacles in random co-ords of the road so for that use random.randrange() for setting random x-coord.To check if the player has bumped into a car we will set initially a boolean bumped to false. Apart from this, In the game_loop function, we will configure controls for a player, a speed increase of obstacles after every level, and Incrementing scoreboard.

Python3
#!/usr/bin/python # -*- coding: utf-8 -*-  def game_loop():     global pause     x = display_width * 0.45     y = display_height * 0.8     x_change = 0     obstacle_speed = 9     obs = 0     y_change = 0     obs_startx = random.randrange(200, display_width - 200)     obs_starty = -750     obs_width = 56     obs_height = 125     passed = 0     level = 0     score = 0     y2 = 7     fps = 120      # flag to indicate that the player has been crashed      bumped = False      while not bumped:         for event in pygame.event.get():             if event.type == pygame.QUIT:                 pygame.quit()                 quit()              if event.type == pygame.KEYDOWN:                 if event.key == pygame.K_LEFT:                     x_change = -5                 if event.key == pygame.K_RIGHT:                     x_change = 5                 if event.key == pygame.K_a:                     obstacle_speed += 2                 if event.key == pygame.K_b:                     obstacle_speed -= 2             if event.type == pygame.KEYUP:                 if event.key == pygame.K_LEFT:                     x_change = 0                 if event.key == pygame.K_RIGHT:                     x_change = 0          # Update player's car position      x += x_change      # Set pause flag to True      pause = True      # Fill the game display with gray color      gamedisplays.fill(gray)      # Update background position      rel_y = y2 % backgroundpic.get_rect().width     gamedisplays.blit(backgroundpic, (0, rel_y                                       - backgroundpic.get_rect().width))     gamedisplays.blit(backgroundpic, (700, rel_y                                       - backgroundpic.get_rect().width))      # Draw background strips      if rel_y < 800:          # Draw background strips          gamedisplays.blit(backgroundpic, (0, rel_y))         gamedisplays.blit(backgroundpic, (700, rel_y))         gamedisplays.blit(yellow_strip, (400, rel_y))         gamedisplays.blit(yellow_strip, (400, rel_y + 100))      # Update obstacle positions and display them      y2 += obstacle_speed     obs_starty -= obstacle_speed / 4     obstacle(obs_startx, obs_starty, obs)     obs_starty += obstacle_speed      # Update player's car position and display it      car(x, y)      # Update score system and display score      score_system(passed, score)      # Check for collision with screen edges and call crash()     # function if collision occurs      if x > 690 - car_width or x < 110:         crash()     if x > display_width - (car_width + 110):         crash()     if x < 110:         crash()      # Update obstacle positions and display them      if obs_starty > display_height:         obs_starty = 0 - obs_height         obs_startx = random.randrange(170, display_width - 170)         obs = random.randrange(0, 7)         passed = passed + 1         score = passed * 10          # Check for level up and update obstacle speed, display         # level text, and pause for 3 seconds          if int(passed) % 10 == 0:             level = level + 1             obstacle_speed += 2             largetext = pygame.font.Font('freesansbold.ttf', 80)             (textsurf, textrect) = text_objects('LEVEL' + str(level),                                                 largetext)             textrect.center = (display_width / 2, display_height / 2)             gamedisplays.blit(textsurf, textrect)             pygame.display.update()             time.sleep(3)      # Check for collision with obstacles and call crash()     # function if collision occurs      if y < obs_starty + obs_height:         if x > obs_startx and x < obs_startx + obs_width or x \             + car_width > obs_startx and x + car_width < obs_startx \                 + obs_width:             crash()      # Draw pause button      button(         'Pause',         650,         0,         150,         50,         blue,         bright_blue,         'pause',     )      # Update game display and set frames per second to 60      pygame.display.update()     clock.tick(60) 

Step 14:  Calling the functions

Now let's initiate the game by calling important functions i.e. 

  • intro_loop(): PLAY, QUIT, and INSTRUCTION button screen.
  • game_loop() : Logic of the game.quit(): For exiting the game window
Python3
intro_loop() game_loop() pygame.quit() quit() 

Step 15:  Window.py file

Now all these programs require a window tab to run. So let's create a new file window.py in the same directory as the current one(A snapshot is attached below) and copy the following code, Now run the code & you should be able to play the game.

Python3
# Importing the Pygame library for game development import pygame  # Importing the Time module for handling  # time-related operations import time  # Initializing Pygame pygame.init()  # Width of the game window display_width = 800  # Height of the game window display_height = 600  # Setting the display mode with specified width and height display = pygame.display.set_mode((display_width,                                     display_height))  # Updating the display pygame.display.update()  # Setting the caption/title of the game window pygame.display.set_caption("Car Game")  # Creating a Clock object to control game frame rate clock = pygame.time.Clock()  # Flag to indicate if the car is bumped or not bumped = False  # Looping until the car is bumped while not bumped:     # Checking for events (e.g. key presses, mouse clicks)     for event in pygame.event.get():         # If the QUIT event is triggered (user closes the game window)         if event.type == pygame.QUIT:             # Set the bumped flag to True to exit the game loop             bumped = True             # Quitting the game and closing the game window             quit() 

Complete Code Snippet:

Python3
# code for developing car racing game in python import pygame import time import random  # initialize pygame and set the colors pygame.init() gray = (119, 118, 110) black = (0, 0, 0) red = (255, 0, 0) green = (0, 200, 0) blue = (0, 0, 200) bright_red = (255, 0, 0) bright_green = (0, 255, 0) bright_blue = (0, 0, 255) display_width = 800 display_height = 600  gamedisplays = pygame.display.set_mode(     (display_width, display_height)) pygame.display.set_caption("car game") clock = pygame.time.Clock() carimg = pygame.image.load('car1.jpg') backgroundpic = pygame.image.load("download12.jpg") yellow_strip = pygame.image.load("yellow strip.jpg") strip = pygame.image.load("strip.jpg") intro_background = pygame.image.load("background.jpg") instruction_background = pygame.image.load("background2.jpg") car_width = 56 pause = False  # Intro screen   def intro_loop():     intro = True     while intro:         for event in pygame.event.get():             if event.type == pygame.QUIT:                 pygame.quit()                 quit()                 sys.exit()         gamedisplays.blit(intro_background, (0, 0))         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("CAR GAME", largetext)         TextRect.center = (400, 100)         gamedisplays.blit(TextSurf, TextRect)         button("START", 150, 520, 100, 50, green,                bright_green, "play")         button("QUIT", 550, 520, 100,                50,                red,                bright_red,                "quit")         button("INSTRUCTION", 300, 520, 200,                50, blue, bright_blue,                "intro")         pygame.display.update()         clock.tick(50)   def button(msg, x, y, w, h, ic, ac, action=None):     mouse = pygame.mouse.get_pos()     click = pygame.mouse.get_pressed()     if x+w > mouse[0] > x and y+h > mouse[1] > y:         pygame.draw.rect(gamedisplays,                          ac, (x, y, w, h))         if click[0] == 1 and action != None:             if action == "play":                 countdown()             elif action == "quit":                 pygame.quit()                 quit()                 sys.exit()             elif action == "intro":                 introduction()             elif action == "menu":                 intro_loop()             elif action == "pause":                 paused()             elif action == "unpause":                 unpaused()      else:         pygame.draw.rect(gamedisplays,                          ic,                          (x, y, w, h))     smalltext = pygame.font.Font("freesansbold.ttf", 20)     textsurf, textrect = text_objects(msg, smalltext)     textrect.center = ((x+(w/2)), (y+(h/2)))     gamedisplays.blit(textsurf, textrect)   def introduction():     introduction = True     while introduction:         for event in pygame.event.get():             if event.type == pygame.QUIT:                 pygame.quit()                 quit()                 sys.exit()         gamedisplays.blit(instruction_background, (0, 0))         largetext = pygame.font.Font('freesansbold.ttf', 80)         smalltext = pygame.font.Font('freesansbold.ttf', 20)         mediumtext = pygame.font.Font('freesansbold.ttf', 40)         textSurf, textRect = text_objects(             "This is an car game in which you" +             "need dodge the coming cars", smalltext)         textRect.center = ((350), (200))         TextSurf, TextRect = text_objects("INSTRUCTION", largetext)         TextRect.center = ((400), (100))         gamedisplays.blit(TextSurf, TextRect)         gamedisplays.blit(textSurf, textRect)         stextSurf, stextRect = text_objects(             "ARROW LEFT : LEFT TURN", smalltext)         stextRect.center = ((150), (400))         hTextSurf, hTextRect = text_objects(             "ARROW RIGHT : RIGHT TURN", smalltext)         hTextRect.center = ((150), (450))         atextSurf, atextRect = text_objects("A : ACCELERATOR", smalltext)         atextRect.center = ((150), (500))         rtextSurf, rtextRect = text_objects("B : BRAKE ", smalltext)         rtextRect.center = ((150), (550))         ptextSurf, ptextRect = text_objects("P : PAUSE  ", smalltext)         ptextRect.center = ((150), (350))         sTextSurf, sTextRect = text_objects("CONTROLS", mediumtext)         sTextRect.center = ((350), (300))         gamedisplays.blit(sTextSurf, sTextRect)         gamedisplays.blit(stextSurf, stextRect)         gamedisplays.blit(hTextSurf, hTextRect)         gamedisplays.blit(atextSurf, atextRect)         gamedisplays.blit(rtextSurf, rtextRect)         gamedisplays.blit(ptextSurf, ptextRect)         button("BACK", 600, 450, 100, 50, blue,                bright_blue, "menu")         pygame.display.update()         clock.tick(30)   def paused():     global pause      while pause:         for event in pygame.event.get():             if event.type == pygame.QUIT:                 pygame.quit()                 quit()                 sys.exit()         gamedisplays.blit(instruction_background, (0, 0))         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("PAUSED", largetext)         TextRect.center = (             (display_width/2),             (display_height/2)         )         gamedisplays.blit(TextSurf, TextRect)         button("CONTINUE", 150, 450,                150, 50, green,                bright_green, "unpause")         button("RESTART", 350, 450, 150,                50, blue, bright_blue,                "play")         button("MAIN MENU", 550, 450,                200, 50, red, bright_red,                "menu")         pygame.display.update()         clock.tick(30)   def unpaused():     global pause     pause = False   def countdown_background():     font = pygame.font.SysFont(None, 25)     x = (display_width*0.45)     y = (display_height*0.8)     gamedisplays.blit(backgroundpic, (0, 0))     gamedisplays.blit(backgroundpic, (0, 200))     gamedisplays.blit(backgroundpic, (0, 400))     gamedisplays.blit(backgroundpic, (700, 0))     gamedisplays.blit(backgroundpic, (700, 200))     gamedisplays.blit(backgroundpic, (700, 400))     gamedisplays.blit(yellow_strip, (400, 100))     gamedisplays.blit(yellow_strip, (400, 200))     gamedisplays.blit(yellow_strip, (400, 300))     gamedisplays.blit(yellow_strip, (400, 400))     gamedisplays.blit(yellow_strip, (400, 100))     gamedisplays.blit(yellow_strip, (400, 500))     gamedisplays.blit(yellow_strip, (400, 0))     gamedisplays.blit(yellow_strip, (400, 600))     gamedisplays.blit(strip, (120, 200))     gamedisplays.blit(strip, (120, 0))     gamedisplays.blit(strip, (120, 100))     gamedisplays.blit(strip, (680, 100))     gamedisplays.blit(strip, (680, 0))     gamedisplays.blit(strip, (680, 200))     gamedisplays.blit(carimg, (x, y))     text = font.render("DODGED: 0", True, black)     score = font.render("SCORE: 0", True, red)     gamedisplays.blit(text, (0, 50))     gamedisplays.blit(score, (0, 30))     button("PAUSE", 650, 0, 150, 50, blue, bright_blue, "pause")   def countdown():     countdown = True      while countdown:         for event in pygame.event.get():             if event.type == pygame.QUIT:                 pygame.quit()                 quit()                 sys.exit()         gamedisplays.fill(gray)         countdown_background()         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("3", largetext)         TextRect.center = (             (display_width/2),             (display_height/2))         gamedisplays.blit(TextSurf, TextRect)         pygame.display.update()         clock.tick(1)         gamedisplays.fill(gray)         countdown_background()         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("2", largetext)         TextRect.center = (             (display_width/2),             (display_height/2))         gamedisplays.blit(TextSurf, TextRect)         pygame.display.update()         clock.tick(1)         gamedisplays.fill(gray)         countdown_background()         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("1", largetext)         TextRect.center = (             (display_width/2),             (display_height/2))         gamedisplays.blit(TextSurf, TextRect)         pygame.display.update()         clock.tick(1)         gamedisplays.fill(gray)         countdown_background()         largetext = pygame.font.Font('freesansbold.ttf', 115)         TextSurf, TextRect = text_objects("GO!!!", largetext)         TextRect.center = (             (display_width/2),             (display_height/2))         gamedisplays.blit(TextSurf, TextRect)         pygame.display.update()         clock.tick(1)         game_loop()   def obstacle(obs_startx, obs_starty, obs):     if obs == 0:         obs_pic = pygame.image.load("car.jpg")     elif obs == 1:         obs_pic = pygame.image.load("car1.jpg")     elif obs == 2:         obs_pic = pygame.image.load("car2.jpg")     elif obs == 3:         obs_pic = pygame.image.load("car4.jpg")     elif obs == 4:         obs_pic = pygame.image.load("car5.jpg")     elif obs == 5:         obs_pic = pygame.image.load("car6.jpg")     elif obs == 6:         obs_pic = pygame.image.load("car7.jpg")     gamedisplays.blit(obs_pic,                       (obs_startx,                        obs_starty))   def score_system(passed, score):     font = pygame.font.SysFont(None, 25)     text = font.render("Passed"+str(passed), True, black)     score = font.render("Score"+str(score), True, red)     gamedisplays.blit(text, (0, 50))     gamedisplays.blit(score, (0, 30))   def text_objects(text, font):     textsurface = font.render(text, True, black)     return textsurface, textsurface.get_rect()   def message_display(text):     largetext = pygame.font.Font("freesansbold.ttf", 80)     textsurf, textrect = text_objects(text, largetext)     textrect.center = (         (display_width/2),         (display_height/2))     gamedisplays.blit(textsurf, textrect)     pygame.display.update()     time.sleep(3)     game_loop()   def crash():     message_display("YOU CRASHED")   def background():     gamedisplays.blit(backgroundpic, (0, 0))     gamedisplays.blit(backgroundpic, (0, 200))     gamedisplays.blit(backgroundpic, (0, 400))     gamedisplays.blit(backgroundpic, (700, 0))     gamedisplays.blit(backgroundpic, (700, 200))     gamedisplays.blit(backgroundpic, (700, 400))     gamedisplays.blit(yellow_strip, (400, 0))     gamedisplays.blit(yellow_strip, (400, 100))     gamedisplays.blit(yellow_strip, (400, 200))     gamedisplays.blit(yellow_strip, (400, 300))     gamedisplays.blit(yellow_strip, (400, 400))     gamedisplays.blit(yellow_strip, (400, 500))     gamedisplays.blit(strip, (120, 0))     gamedisplays.blit(strip, (120, 100))     gamedisplays.blit(strip, (120, 200))     gamedisplays.blit(strip, (680, 0))     gamedisplays.blit(strip, (680, 100))     gamedisplays.blit(strip, (680, 200))   def car(x, y):     gamedisplays.blit(carimg, (x, y))   def game_loop():     global pause     x = (display_width*0.45)     y = (display_height*0.8)     x_change = 0     obstacle_speed = 9     obs = 0     y_change = 0     obs_startx = random.randrange(200,                                   (display_width-200))     obs_starty = -750     obs_width = 56     obs_height = 125     passed = 0     level = 0     score = 0     y2 = 7     fps = 120      bumped = False     while not bumped:         for event in pygame.event.get():             if event.type == pygame.QUIT:                 pygame.quit()                 quit()              if event.type == pygame.KEYDOWN:                 if event.key == pygame.K_LEFT:                     x_change = -5                 if event.key == pygame.K_RIGHT:                     x_change = 5                 if event.key == pygame.K_a:                     obstacle_speed += 2                 if event.key == pygame.K_b:                     obstacle_speed -= 2             if event.type == pygame.KEYUP:                 if event.key == pygame.K_LEFT:                     x_change = 0                 if event.key == pygame.K_RIGHT:                     x_change = 0          x += x_change         pause = True         gamedisplays.fill(gray)          rel_y = y2 % backgroundpic.get_rect().width         gamedisplays.blit(             backgroundpic, (0,                             rel_y-backgroundpic.get_rect().width))         gamedisplays.blit(backgroundpic,                           (700, rel_y -                            backgroundpic.get_rect().width))         if rel_y < 800:             gamedisplays.blit(backgroundpic, (0, rel_y))             gamedisplays.blit(backgroundpic, (700, rel_y))             gamedisplays.blit(yellow_strip, (400, rel_y))             gamedisplays.blit(yellow_strip, (400, rel_y+100))             gamedisplays.blit(yellow_strip, (400, rel_y+200))             gamedisplays.blit(yellow_strip, (400, rel_y+300))             gamedisplays.blit(yellow_strip, (400, rel_y+400))             gamedisplays.blit(yellow_strip, (400, rel_y+500))             gamedisplays.blit(yellow_strip, (400, rel_y-100))             gamedisplays.blit(strip, (120, rel_y-200))             gamedisplays.blit(strip, (120, rel_y+20))             gamedisplays.blit(strip, (120, rel_y+30))             gamedisplays.blit(strip, (680, rel_y-100))             gamedisplays.blit(strip, (680, rel_y+20))             gamedisplays.blit(strip, (680, rel_y+30))          y2 += obstacle_speed          obs_starty -= (obstacle_speed/4)         obstacle(obs_startx, obs_starty, obs)         obs_starty += obstacle_speed         car(x, y)         score_system(passed, score)         if x > 690-car_width or x < 110:             crash()         if x > display_width-(car_width+110) or x < 110:             crash()         if obs_starty > display_height:             obs_starty = 0-obs_height             obs_startx = random.randrange(170,                                           (display_width-170))             obs = random.randrange(0, 7)             passed = passed+1             score = passed*10             if int(passed) % 10 == 0:                 level = level+1                 obstacle_speed+2                 largetext = pygame.font.Font("freesansbold.ttf", 80)                 textsurf, textrect = text_objects(                     "LEVEL"+str(level), largetext)                 textrect.center = (                     (display_width/2), (display_height/2))                 gamedisplays.blit(textsurf, textrect)                 pygame.display.update()                 time.sleep(3)          if y < obs_starty+obs_height:             if x > obs_startx and x < \                     obs_startx + obs_width or x+car_width > \                     (obs_startx and x+car_width < obs_startx+obs_width):                 crash()         button("Pause", 650, 0, 150, 50, blue, bright_blue, "pause")         pygame.display.update()         clock.tick(60)   intro_loop() game_loop() pygame.quit() quit() 

Output :

Racing Car Game using Python Pygame
Output GIF

Next Article
Spiral Sprint Game in Python Using Pygame

C

cosmic
Improve
Article Tags :
  • Python
  • Python Programs
  • Python-PyGame
Practice Tags :
  • python

Similar Reads

    PyGame Tutorial
    Pygame is a free and open-source library for making games and multimedia applications in Python. It helps us create 2D games by giving us tools to handle graphics, sounds and user input (like keyboard and mouse events) without needing to dig deep into complex stuff like graphics engines.Release date
    7 min read

    Introduction

    Introduction to pygame
    Pygame is a set of Python modules designed for writing video games. It adds functionality on top of the excellent SDL library, enabling you to create fully-featured games and multimedia programs in the Python language. It's key benefits include:Beginner-Friendly: Simple Python syntax makes it ideal
    4 min read
    Getting Started with Pygame
    Pygame is a free-to-use and open-source set of Python Modules.  And as the name suggests, it can be used to build games. You can code the games and then use specific commands to change it into an executable file that you can share with your friends to show them the work you have been doing.  It incl
    3 min read
    How to Install Pygame on Windows ?
    In this article, we will learn how to Install PyGame module of Python on Windows. PyGame is a library of python language. It is used to develop 2-D games and is a platform where you can set python modules to develop a game. It is a user-friendly platform that helps to build games quickly and easily.
    2 min read
    Install Pygame in MacOS
    PyGame is a collection of modules that break through the language of Python applications. These modules are designed to edit video games. PyGame, therefore, includes computer graphics and audio libraries created for the use and language of Python programs. At first, open the Terminal which is locate
    1 min read
    Interesting Facts about PYGAME
    Pygame is a set of python module which is used in designing video games. In Pygame, there are computer graphics and sound libraries in order to develop high quality and user interactive games. Pygame was developed by Pete Shinners. Till 2000, it was a community project, later on it was released unde
    2 min read

    Getting Started

    PyGame - Import and Initialize
    In this article, we will see how to import and initialize PyGame. Installation The best way to install pygame is with the pip tool, we can install pygame by using the below command: pip install pygameImporting the Pygame library To import the pygame library, make sure you have installed pygame alrea
    2 min read
    How to initialize all the imported modules in PyGame?
    PyGame is Python library designed for game development. PyGame is built on the top of SDL library so it provides full functionality to develop game in Python. Pygame has many modules to perform it's operation, before these modules can be used, they must be initialized. All the modules can be initial
    2 min read
    How to create an empty PyGame window?
    Pygame window is a simple window like any other window, in which we display our game screen. It is the first task we do so that we can display our output onto something. Our main goal here is to create a window and keep it running unless the user wants to quit. To perform these tasks first we need t
    2 min read
    How to get the size of PyGame Window?
    In this article, we will learn How to get the size of a PyGame Window.  Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game
    1 min read
    Allowing resizing window in PyGame
    In this article, we will learn How to allow resizing a PyGame Window.  Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game
    2 min read
    How to change screen background color in Pygame?
    Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Functions Used: pygame.init(): This function is used to initialize all the pygame
    1 min read
    How to Change the Name of a Pygame window?
    PyGame window is a simple window that displays our game on the window screen. By default, pygame uses "Pygame window" as its title and pygame icon as its logo for pygame window. We can use set_caption() function to change the name and set_icon() to set icon of our window. To change the name of pygam
    2 min read
    How to set up the Game Loop in PygGame ?
    In this article, we will see how to set up a game loop in PyGame. Game Loop is the loop that keeps the game running. It keeps running till the user wants to exit. While the game loop is running it mainly does the following tasks: Update our game window to show visual changesUpdate our game states ba
    3 min read
    How to change the PyGame icon?
    While building a video game, do you wish to set your image or company's logo as the icon for a game? If yes, then you can do it easily by using set_icon() function after declaring the image you wish to set as an icon. Read the article given below to know more in detail.  Syntax: pygame_icon = pygame
    2 min read
    Pygame - Surface
    When using Pygame, surfaces are generally used to represent the appearance of the object and its position on the screen. All the objects, text, images that we create in Pygame are created using surfaces. Creating a surface Creating surfaces in pygame is quite easy. We just have to pass the height an
    6 min read
    Pygame - Time
    While using pygame we sometimes need to perform certain operations that include the usage of time. Like finding how much time our program has been running, pausing the program for an amount of time, etc. For operations of this kind, we need to use the time methods of pygame. In this article, we will
    4 min read

    Drawing Shapes

    Pygame – Drawing Objects and Shapes
    In this article, we are going to see how to draw an object using Pygame. There can be two versions for drawing any shape, it can be a solid one or just an outline of it. Drawing Objects and Shapes in PyGame You can easily draw basic shapes in pygame using the draw method of pygame.  Drawing Rectangl
    10 min read
    Python | Drawing different shapes on PyGame window
    Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using th
    3 min read
    How to draw rectangle in Pygame?
    Pygame is a popular Python library for game development and multimedia, built on top of the SDL library. One of the most basic graphical operations in Pygame is drawing shapes, such as rectangles. Rectangles are essential for making buttons, frames, game objects and more. It's key functions for draw
    3 min read
    How to draw a rectangle with rounded corner in PyGame?
    Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. In this article, we will see how can we draw a rectangle with rounded corners in P
    2 min read

    Event Handling

    How to add Custom Events in Pygame?
    In this article, we will see how to add custom events in PyGame.  Installation PyGame library can be installed using the below command: pip install pygame Although PyGame comes with a set of events (Eg: KEYDOWN and KEYUP), it allows us to create our own additional custom events according to the requ
    4 min read
    How to get keyboard input in PyGame ?
    While using pygame module of Python, we sometimes need to use the keyboard input for various operations such as moving a character in a certain direction. To achieve this, we have to see all the events happening. Pygame keeps track of events that occur, which we can see with the events.get() functio
    3 min read

    Working with Text

    Pygame - Working with Text
    In this article, we will see how to play with texts using the Pygame module. We will be dealing here with initializing the font, rendering the text, editing the text using the keyboard, and adding a blinking cursor note.  Installation To install this module type the below command in the terminal. pi
    5 min read
    Python | Display text to PyGame window
    Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop usin
    6 min read
    How to create a text input box with Pygame?
    In this article, we will discuss how to create a text input box using PyGame. Installation Before initializing pygame library we need to install it. This library can be installed into the system by using pip tool that is provided by Python for its library installation. Pygame can be installed by wri
    3 min read

    Working with images

    Python | Display images with PyGame
    Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop usin
    2 min read
    Getting width and height of an image in Pygame
    Prerequisites: Pygame To use graphics in python programs we use a module called Pygame. Pygame provides high functionality for developing games and graphics in Python. Nowadays Pygame are very much popular to build simple 2D games. In order to run a program written in Python using Pygame module, a s
    3 min read
    How to Rotate and Scale images using PyGame ?
    In this article, we are going to see how to Rotate and Scale the image. Image Scaling refers to the resizing of the original image and Image Rotation refers to turning off an image with some angle. Rotations in the coordinate plane are counterclockwise. Let's proceed with the methods used and the co
    3 min read
    Pygame - Flip the image
    In this article, we are going to see how images can be flipped using Pygame. To flip the image we need to use pygame.transform.flip(Surface, xbool, ybool) method which is called to flip the image in vertical direction or horizontal direction according to our needs. Syntax: pygame.transform.flip(Surf
    2 min read
    How to move an image with the mouse in PyGame?
    Pygame is a Python library that is used to create cross-platform video games. The games created by Pygame can be easily run through any of the input devices such as a mouse, keyboard, and joystick. Do you want to make a game that runs through mouse controls? Don't you know how to move the image with
    4 min read
    How to use the mouse to scale and rotate an image in PyGame ?
    In this article, we will discuss how to transform the image i.e (scaling and rotating images) using the mouse in Pygame. Approach Step 1: First, import the libraries Pygame and math. import pygame import math from pygame.locals import * Step 2: Now, take the colors as input that we want to use in th
    5 min read

    PyGame Advance

    How to create Buttons in a game using PyGame?
    Pygame is a Python library that can be used specifically to design and build games. Pygame only supports 2D games that are build using different shapes/images called sprites. Pygame is not particularly best for designing games as it is very complex to use and lacks a proper GUI like unity gaming eng
    3 min read
    Python - Drawing design using arrow keys in PyGame
    Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using th
    3 min read
    Moving an object in PyGame - Python
    To make a game or animation in Python using PyGame, moving an object on the screen is one of the first things to learn. We will see how to move an object such that it moves horizontally when pressing the right arrow key or left arrow key on the keyboard and it moves vertically when pressing up arrow
    2 min read
    Python | Making an object jump in PyGame
    Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using th
    3 min read
    Adding Boundary to an Object in Pygame
    Boundaries to any game are very important. In snake games, space invaders, ping pong game, etc. the boundary condition is very important. The ball bounces at the boundaries of the screen in ping pong games. So, the idea behind this boundaries is to change the position of the ball or object in revers
    5 min read
    Collision Detection in PyGame
    Prerequisite: Introduction to pygame Collision detection is a very often concept and used in almost games such as ping pong games, space invaders, etc. The simple and straight forward concept is to match up the coordinates of the two objects and set a condition for the happening of collision. In thi
    7 min read
    Pygame - Creating Sprites
    Sprites are objects, with different properties like height, width, color, etc., and methods like moving right, left, up and down, jump, etc. In this article, we are looking to create an object in which users can control that object and move it forward, backward, up, and down using arrow keys. Let fi
    2 min read
    Pygame - Control Sprites
    In this article, we will discuss how to control the sprite, like moving forward, backward, slow, or accelerate, and some of the properties that sprite should have. We will be adding event handlers to our program to respond to keystroke events, when the player uses the arrow keys on the keyboard we w
    4 min read
    How to add color breezing effect using pygame?
    Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use and doesn’t have a proper GUI like unity but it definitely builds
    2 min read
    Python | Playing audio file in Pygame
    Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doin
    2 min read

    Exercise, Applications, and Projects

    Snowfall display using Pygame in Python
    Not everybody must have witnessed Snowfall personally but wait a minute, What if you can see the snowfall right on your screen by just a few lines of creativity and Programming.  Before starting the topic, it is highly recommended revising the basics of Pygame.  Steps for snowfall creation 1. Import
    3 min read
    Rhodonea Curves and Maurer Rose in Python
    In this article, we will create a Rhodonea Curve and Maurer Rose pattern in Python! Before we proceed to look at what exactly is a rhodonea curve or maurer rose we need to get the basic structure of our program ready!  Basic Structure of the Program - Before we move on to learn anything about Rhodon
    7 min read
    Creating start Menu in Pygame
    Pygame is a Python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different shapes or sprites. Pygame doesn't have an in-built layout design or any in-built UI system this means there is no easy way to make UI or levels for a game.
    3 min read
    Tic Tac Toe GUI In Python using PyGame
    This article will guide you and give you a basic idea of designing a game Tic Tac Toe using pygame library of Python. Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming l
    15+ min read
    Snake Game in Python - Using Pygame module
    Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginne
    15+ min read
    8-bit game using pygame
    Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use doesn’t have a proper GUI like unity but it definitely builds log
    9 min read
    Bubble sort visualizer using PyGame
    In this article we will see how we can visualize the bubble sort algorithm using PyGame i.e when the pygame application get started we can see the unsorted bars with different heights and when we click space bar key it started getting arranging in bubble sort manner i.e after every iteration maximum
    3 min read
    Ternary Search Visualization using Pygame in Python
    An algorithm like Ternary Search can be understood easily by visualizing. In this article, a program that visualizes the Ternary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any s
    5 min read
    Sorting algorithm visualization : Heap Sort
    An algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach: Generate random array and fill the pygame window wi
    4 min read
    Sorting algorithm visualization : Insertion Sort
    An algorithm like Insertion Sort can be understood easily by visualizing. In this article, a program that visualizes the Insertion Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in python using pygame library. Approach: Generate random array and fill the pygame
    3 min read
    Binary Search Visualization using Pygame in Python
    An algorithm like Binary Search can be understood easily by visualizing. In this article, a program that visualizes the Binary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sor
    4 min read
    Building and visualizing Sudoku Game Using Pygame
    Sudoku is a logic-based, combinatorial number-placement puzzle. The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid contain all of the digits from 1 to 9.  We will be building the Sudoku Game in python using pygame li
    7 min read
    Create Bingo Game Using Python
    A card with a grid of numbers on it is used to play the popular dice game of bingo. Players check off numbers on their cards when they are selected at random by a caller, competing to be the first to mark off all of their numbers in a particular order. We'll examine how to utilise Python to create a
    9 min read
    Create Settings Menu in Python - Pygame
    Python is a flexible programming language with a large selection of libraries and modules for a variety of applications. Pygame menu is one such toolkit that enables programmers to design graphical user interfaces for games and apps. In this tutorial, we'll look at how to use the pygame menu package
    9 min read
    Car Race Game In PyGame
    In this article, we will see how to create a racing car game in Python using Pygame. In this game, we will have functionality like driving, obstacle crashing, speed increment when levels are passed, pause, countdown, scoreboard, and Instruction manual screen.  Required Modules: Before going any furt
    15+ min read
    Spiral Sprint Game in Python Using Pygame
    In this article, we will see how to create a spiral sprint game in Python using Pygame. In this game, we will have functionality like difficulty modes, obstacle crashing, speed increment when points are increased, scoreboard, Particle animation, color-changing orbits, coins, and game sounds. Spiral
    15+ min read
    Selection sort visualizer using PyGame
    In this article, we will see how to visualize Selection sort using a Python library PyGame. It is easy for the human brain to understand algorithms with the help of visualization. Selection sort is a simple and easy-to-understand algorithm that is used to sort elements of an array by dividing the ar
    3 min read
    Mouse Clicks on Sprites in PyGame
    The interactiveness of your game can be significantly increased by using Pygame to respond to mouse clicks on sprites. You may develop unique sprite classes that manage mouse events and react to mouse clicks with the aid of Pygame's sprite module. This article will teach you how to use Pygame to mak
    3 min read
    Slide Puzzle using PyGame - Python
    Slide Puzzle game is a 2-dimensional game i.e the pieces can only be removed inside the grid and reconfigured by sliding them into an empty spot. The slide puzzle game developed here is a 3X3 grid game i.e 9 cells will be there from 1 to 8(9 is not here since a blank cell is needed for sliding the n
    14 min read
    Brick Breaker Game In Python using Pygame
    Brick Breaker is a 2D arcade video game developed in the 1990s. The game consists of a paddle/striker located at the bottom end of the screen, a ball, and many blocks above the striker. The basic theme of this game is to break the blocks with the ball using the striker. The score is calculated by th
    14 min read
    Hover Button in Pygame
    Here, we will talk about while hovering over the button different actions will perform like background color, text size, font color, etc. will change. In this article we are going to create a button using the sprites Pygame module of Python then, when hovering over that button we will perform an eve
    6 min read
    Create a Pong Game in Python - Pygame
    Pong is a table tennis-themed 2-player 2D arcade video game developed in the early 1970s. The game consists of two paddles/strikers, located at the left and right edges of the screen, and a ball. Create a Pong Game in PythonThe basic theme of this game is to make sure that the ball doesn't hit the w
    10 min read
    Save/load game Function in Pygame
    Pygame is a free-to-use and open-source set of Python Modules.  And as the name suggests, it can be used to build games, and to save game data or the last position of the player you need to store the position of the player in a file so when a user resumes the game its game resumes when he left. In t
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences