Build Dodger Game Using Pygame – Python

Pygame is a Python library that consists of cross-platform set of modules in Python that are used for creating multimedia video games. It includes libraries for graphics and sound which are used to make the game interactive.
In this tutorial, we will be using this library to build a beginner level dodger game.

Introduction to the Dodger Game in Python

This game consists a player controlled rectangle, and the objective is to avoid hitting the coming obstacles. Every time the player avoids an obstacle, it gets added to the score of the player. The game includes features like score tracking, background music running in loop, sound effects every time the player hits or evades an obstacle and also a ‘GAME OVER‘ screen.

Algorithm of the game

  1. Initialize the Pygame and other required libraries.
  2. Setting up the game window and other important parameters such as colors, players, obstacles, score and fonts.
  3. Loading background music and sound effects – Pygame.
  4. Defining the player and obstacle characteristics.
  5. Inside the main game loop :
    • clearing the screen.
    • handling events like quitting the game.
    • Updating player position based on keyboard input.
    • generate new obstacles at random positions and speeds.
    • moving the passed-on obstacles down the screen.
    • displaying the score and updating it if the obstacle passes.
    • updating the display
    • fixing the frame rate to 60 FPS.
  6. If collision happens with an obstacle – Pygame :
    • play the collision music
    • display the game over screen for 4 seconds
    • exit the game

Libraries used in the game

  • Pygame : It includes graphics and sound modules.
  • Sys : for system specific parameters and functions.
  • Random : for generating random numbers.
  • Time : for time-related functions.
  • pygame.init()  : used to initialize all the pygame modules.

Code implementation in Python

Initialization and Importing Libraries

# Import required libraries
import pygame
import sys
import random
import time

# Initialize Pygame and set up the game window
pygame.init()

Setting up the Game screen

# Set the dimensions for the game window
screen_width = 800
screen_height = 600

# Create the game window
screen = pygame.display.set_mode((screen_width, screen_height))  

# Set the title of the window
pygame.display.set_caption("Dodger Game")
  • screen_width: sets width of the game window.
  • screen_height: sets height of the game window.
  • pygame.display.set_mode(): sets the mode of the game window with specified height and width.
  • pygame.display.set_caption(): sets the title of the display window.

Colors

# Define colors using RGB values
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# List of colors for game over text
COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255)]
  • WHITE, BLACK, RED: RGB tuples for colors.
  • COLORS: List of colors used for the game over text.

Player Setup

# Set up player properties
player_width = 50
player_height = 50

# Center the player horizontally
player_x = screen_width // 2 - player_width // 2  

# Position the player near the bottom
player_y = screen_height - player_height - 10  

# Speed at which the player moves
player_speed = 5  

# Create a rectangle for the player
player = pygame.Rect(player_x, player_y, player_width, player_height)
  • player_width, player_height: Dimensions of the player rectangle.
  • player_x, player_y: Initial position of the player.
  • player_speed: Speed of the player rectangle.
  • pygame.Rect(): Creates a rectangle for the player.

Obstacle Setup

# Set up obstacle properties
obstacle_width = 50
obstacle_height = 50

# Speed of falling obstacles
obstacle_speed = 5  

# Minimum distance between consecutive obstacles
obstacle_gap = 200  

# List to keep track of obstacles
obstacle_list = []
  • obstacle_width, obstacle_height: Dimensions of obstacles.
  • obstacle_speed: Speed at which obstacles fall.
  • obstacle_gap: Minimum distance between consecutive obstacles.
  • obstacle_list: List to store obstacle rectangles.

Score and Font Setup

# Initialize the score and fonts for displaying text
score = 0

# Font for displaying score
font = pygame.font.SysFont(None, 55)  

# Font for displaying game over text
game_over_font = pygame.font.SysFont(None, 100)
  • score: Variable to store the player’s score.
  • font: Font for displaying the score.
  • game_over_font: Font for displaying the game over message.

Sounds Setup

# Load and set up background music and sound effects

# Load background music file
pygame.mixer.music.load('background_music.mp3')  

pygame.mixer.music.set_volume(0.5)  # Set volume for background music
pygame.mixer.music.play(-1)  # Play background music in a loop
boing_sound = pygame.mixer.Sound('boing.wav')  # Load sound effect for scoring
arrgh_sound = pygame.mixer.Sound('arrgh.wav')  # Load sound effect for collision

# Set volume levels for sound effects
boing_sound.set_volume(0.75)  # Volume for scoring sound
arrgh_sound.set_volume(1.0)  # Volume for collision sound
  • pygame.mixer.music.load(): Loads the background music file.
  • pygame.mixer.music.set_volume(): Sets the volume of the background music.
  • pygame.mixer.music.play(): Plays the background music in a loop.
  • pygame.mixer.Sound(): Loads sound effect files.
  • boing_sound.set_volume(), arrgh_sound.set_volume(): Sets the volume of sound effects.

Game Clock Setup

# Set up clock object to manage the frame rate
clock = pygame.time.Clock()

Score Function and display

# Function to display the current score on the screen
def display_score(score):
    # Render the score text
    score_text = font.render(f'SCORE: {score}', True, BLACK)  
    # Draw the score text on the screen at the top-left corner
    screen.blit(score_text, [10, 10])
  • display_score(): Renders and displays the current score on the screen.

Game Over Function

# Function to handle the game over sequence
def game_over():
    pygame.mixer.music.stop()  # Stop the background music
    end_time = time.time() + 4  # Set the duration for the game over display
    color_index = 0  # Index to cycle through colors
    while time.time() < end_time:
        screen.fill(WHITE)  # Clear the screen
        game_over_text = game_over_font.render('GAME OVER!', True, COLORS[color_index])  # Render game over text
        # Center the text
        screen.blit(game_over_text, [screen_width // 2 - game_over_text.get_width() // 2, screen_height // 2 - game_over_text.get_height() // 2])  
        pygame.display.flip()  # Update the display
        color_index = (color_index + 1) % len(COLORS)  # Cycle through colors
        time.sleep(0.2)  # Wait for 0.2 seconds before changing color
  • game_over(): Displays the game over message with changing colors for 4 seconds and stops the background music.

Main Game Loop

# Main game loop
running = True  # Variable to keep the game loop running
while running:
    screen.fill(WHITE)  # Clear the screen for each frame

    # Event handling loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # Check if the window close button is clicked
            pygame.quit()  # Quit Pygame
            sys.exit()  # Exit the program

    # Handle player movement based on keyboard input
    keys = pygame.key.get_pressed()  # Get the state of all keyboard keys
    if keys[pygame.K_LEFT] and player.x > 0:  # Move player left if left arrow key is pressed
        player.x -= player_speed
    if keys[pygame.K_RIGHT] and player.x < screen_width - player_width:  # Move player right if right arrow key is pressed
        player.x += player_speed

    # Spawn new obstacles at random positions
    if len(obstacle_list) == 0 or obstacle_list[-1].y > obstacle_gap:  # Check if a new obstacle should be spawned
        obstacle_x = random.randint(0, screen_width - obstacle_width)  # Random x position for the new obstacle
        obstacle_y = 0 - obstacle_height  # Start above the screen
        # Create a new obstacle rectangle
        obstacle = pygame.Rect(obstacle_x, obstacle_y, obstacle_width, obstacle_height)  
        obstacle_list.append(obstacle)  # Add the new obstacle to the list

    # Move obstacles down the screen
    for obstacle in obstacle_list:
        obstacle.y += obstacle_speed  # Move the obstacle down
        pygame.draw.rect(screen, RED, obstacle)  # Draw the obstacle

        # Check for collision with the player
        if obstacle.colliderect(player):
            arrgh_sound.play()  # Play collision sound
            game_over()  # Show game over screen
            pygame.quit()  # Quit Pygame
            sys.exit()  # Exit the program

    # Remove obstacles that are off the screen and update the score
    for obstacle in obstacle_list[:]:  # Iterate over a copy of the obstacle list
        if obstacle.y > screen_height:  # Check if the obstacle is off the screen
            obstacle_list.remove(obstacle)  # Remove the obstacle from the list
            score += 1  # Increment the score
            boing_sound.play()  # Play scoring sound

    # Display the current score
    display_score(score)

    # Draw the player rectangle on the screen
    pygame.draw.rect(screen, BLACK, player)

    # Update the display
    pygame.display.flip()

    # Cap the frame rate at 60 FPS
    clock.tick(60)  # Limit the frame rate to 60 frames per second
  • while running: Main game loop runs until the game is over.
  • screen.fill(): Clears the screen at the beginning of each frame.
  • pygame.event.get(): Retrieves all the events from the event queue.
  • pygame.key.get_pressed(): Checks the state of all keyboard buttons.
  • pygame.draw.rect(): Draws rectangles on the screen.
  • pygame.display.flip(): Updates the contents of the entire display.
  • clock.tick(60): Ensures the program runs at 60 frames per second.

Output :

 

Game Folder Zip File Download

Dodger_Game.zip
This zip folder contains the python file, game music mp3 file and .wav sound effects files.

Ideas and Suggestions for Improvement

The readers can take a basic idea of this game and use it as a starting point to build even more advanced and sophisticated features. They can build more onto this game by using this code as framework and working upon it. Some suggested improvements can be :

  • Addition of levels into the game : Easy, Medium and Hard by increasing the obstacles speed and density of the obstacles on the game window.
  • They can add a feature of High Score and update whenever a player breaks it.
  • They can also add few options like Try Again and Exit Game checkbox, instead of the game abruptly ending itself.
  • A more advanced improvement could be adding a player login system in which the players’ credentials gets stored using python file system. Whenever players log into the game, they can see their game statistics such as Games played, Highest Score, Average Score etc.

Leave a Reply

Your email address will not be published. Required fields are marked *