Building a Simple Game in Python using the PyGame Module

Pygame is a good game development library since it includes a variety of built-in tools and functions that can be used to create games of various genres, from simple to complicated. The library comprises graphics, sound, and input processing, all of which are required for any game.

The ability to create and alter sprites is one of Pygame's most remarkable capabilities. Sprites are graphical objects that depict the game's characters, objects, and other game features. Pygame includes a robust sprite class that allows the developer to incorporate graphics and animations into the game, move and rotate the sprites, and detect collisions between them.

Another important element of Pygame is collision detection, which allows the developer to identify when two game objects collide. In games, this is crucial since it allows the user to interact with the environment and other game items. Pygame includes a collision detection mechanism for detecting collisions between sprites and other game elements.

Pygame includes sound and music capabilities in addition to sprites and collision detection. This makes it simple for developers to incorporate sound effects and music into their games, which can significantly improve the gaming experience.

Overall, Pygame is a strong and adaptable toolkit that can be used to construct a variety of games and multimedia applications. Its simple API, broad documentation, and vast user base.

The game we will be building is a simple 2D game where you interact with the environment and move the player around to catch objects on the screen. Each time the player touches it, he gains a score.

It's a simple game but developing it will give you great insights over the the Pygame module and how you can use it to create more advanced games.

Getting Started

Before we dive into using the pygame library, we first need to install the library using pip.

However, since it does not come built-in, we must first install the pygame library. This can be done using the pip package manager.

To install the pygame library, open your terminal and type the following command −

pip install pygame

This will download and install the pygame library and its dependencies. Once installed, we can import pygame in our Python code using the following statement −

import pygame

Building a Simple Game Using the Pygame Module

This article is going to be a little different than the other articles because in this, we’ll code the entire script first with quick and easy comments to understand and then finally break down all the components and what we are doing. That way it’s easier to understand and does not interfere with the learning process!

Complete Code


Here is the complete code −

import pygame
import random

# Initialize pygame

# Set the width and height of the screen (width, height)
screen = pygame.display.set_mode((800, 600))

# Set the title of the window
pygame.display.set_caption("Catch Game")

# Set the clock
clock = pygame.time.Clock()

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# Player class
class Player(pygame.sprite.Sprite):
   def __init__(self):
      selfelf.image = pygame.Surface([50, 50])
      self.rect = self.image.get_rect()
      self.rect.x = 375
      self.rect.y = 500
      self.speed = 5

   def update(self):
      # Get the current key state
      keys = pygame.key.get_pressed()

      # Move the player
   if keys[pygame.K_LEFT]:
      self.rect.x -= self.speed
   elif keys[pygame.K_RIGHT]:
      self.rect.x += self.speed

# Object class
class Object(pygame.sprite.Sprite):
   def __init__(self):
      self.image = pygame.Surface([25, 25])
      self.rect = self.image.get_rect()
      self.rect.x = random.randrange(0, 750)
      self.rect.y = random.randrange(-100, -40)
      self.speed = random.randint(2, 8)

   def update(self):
      # Move the object down the screen
      self.rect.y += self.speed

      # If the object goes off the bottom of the screen, reset it
      if > 600:
         self.rect.x = random.randrange(0, 750)
         self.rect.y = random.randrange(-100, -40)
         self.speed = random.randint(2, 8)

# Create groups for all sprites and objects
all_sprites = pygame.sprite.Group()
objects = pygame.sprite.Group()

# Create the player
player = Player()

# Create the objects
for i in range(10):
   obj = Object()

# Set the score
score = 0

# Set the font
font_name = pygame.font.match_font("arial")

# Function to draw text on the screen
def draw_text(surf, text, size, x, y):
   font = pygame.font.Font(font_name, size)
   text_surface = font.render(text, True, WHITE)
   text_rect = text_surface.get_rect()
   text_rect.midtop = (x, y)
   surf.blit(text_surface, text_rect)

# Game loop
running = True
while running:
   # Set the frame rate

   # Process events
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         running = False

   # Update all sprites

   # Check for collisions between the player and objects
   hits = pygame.sprite.spritecollide(player, objects, True)
   for hit in hits:
      score += 1
      obj = Object()

   # Draw everything on the screen
   draw_text(screen, "Score: {}".format(score), 18, 50, 10)

   # Update the screen

Code Breakdown

This code is a basic example of a Pygame game. Here is an explanation of each part of the code −

  • pygame.init() − This initializes Pygame.

  • screen = pygame.display.set_mode((800, 600)) − This creates the game screen with a resolution of 800x600 pixels.

  • pygame.display.set_caption("Catch Game") − This sets the caption of the window to "Catch Game".

  • clock = pygame.time.Clock() − This creates a Pygame clock, which is used to regulate the game's frame rate.

  • Colors − These lines define various color constants that will be used later in the code.

  • Player class − This is a Pygame sprite class that defines the player object. It has a method called "update" that is called every frame to update the player's position based on user input.

  • Object class − This is another Pygame sprite class that defines the objects that the player needs to catch. It has a method called "update" that is called every frame to update the object's position.

  • all_sprites = pygame.sprite.Group() − This creates a Pygame sprite group that will contain all the sprites in the game.

  • objects = pygame.sprite.Group() − This creates a Pygame sprite group that will contain all the objects that the player needs to catch.

  • player = Player() − This creates an instance of the Player class and adds it to the all_sprites group.

  • for i in range(10) − This creates 10 instances of the Object class, adds them to the all_sprites group, and adds them to the objects group.

  • score = 0 − This initializes the score to 0.

  • font_name = pygame.font.match_font("arial") − This sets the font to be used for the score display.

  • draw_text(surf, text, size, x, y) − This is a helper function that draws text on the screen.

  • Game loop − This is the main game loop. It runs until the "running" variable is set to False.

  • clock.tick(60) − This sets the frame rate to 60 frames per second.

  • for event in pygame.event.get() − This processes all the Pygame events that occur during each frame.

  • all_sprites.update() − This calls the "update" method on all the sprites in the all_sprites group.

  • hits = pygame.sprite.spritecollide(player, objects, True) − This checks for collisions between the player and the objects. If a collision is detected, the object is removed from the objects group and the score is increased by 1.

  • screen.fill(BLACK) − This fills the screen with the color black.

  • all_sprites.draw(screen) − This draws all the sprites in the all_sprites group on the screen.

  • draw_text(screen, "Score − {}".format(score), 18, 50, 10): This draws the score on the screen.

  • pygame.display.update() − This updates the screen with all the changes made during the current frame.


Here is a sample output


Pygame is a robust open-source package for creating games and multimedia applications in Python. Its varied functions and tools allow it to be used to create games of various genres, ranging from simple 2D platformers to more complex 3D games. In this tutorial, we looked at how to use Pygame to make a simple game in which the player may interact with the environment, move around, and grab things on the screen.

Following this tutorial, you should have gotten an understanding of how Pygame works and how it can be used to create more complex games. Overall, Pygame is an excellent tool for game developers that want to construct Python-based games.

Updated on: 31-Aug-2023


Kickstart Your Career

Get certified by completing the course

Get Started