Sign In
Sign In

How to Make Games in Python with Pygame

How to Make Games in Python with Pygame
Hostman Team
Technical writer
Python
23.10.2024
Reading time: 10 min

This tutorial will help you create a simple game template in Python where you move a character to avoid obstacles. You'll use Pygame, a set of Python modules designed for video game development. Pygame builds on top of the powerful SDL library. The latest version of Pygame uses Pygame SDL2.

Installing the Library

Pygame includes several modules with functions for drawing graphics, playing sounds, handling mouse input, and more—all essential for building your first game with Python 3.

You need to install the library in your development environment to get started. Installation is done using pip:

python -m pip install -U pygame --user

To verify the library is working, you can run a built-in example game:

python -m pygame.examples.aliens

This will launch a game where you shoot down alien UFOs.

There are other installation methods for different operating systems, including compiling the library from source. Check the Pygame documentation for details.

Game Loop

The game loop is where all the game events happen, updates are made, and the game is displayed on the screen. Once the initial setup and variable initialization are complete, the game loop begins, and the program continues to run repeatedly until a QUIT event occurs.

Here’s an example of a game loop that we'll use in our Pygame program:

while True:
    # Code
    pygame.display.update()

Changes in the game only take effect after pygame.display.update() is called. Since games involve continuous updates, this function is placed inside the game loop and is executed repeatedly.

Exiting the Game Loop

Every game loop must have a way to exit or trigger the end of the game—for example, when the user clicks a quit button.

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

Here, pygame.quit() closes the Pygame window, and sys.exit() ends the Python script. Using only sys.exit() can sometimes cause the IDE to freeze, so it's important to call pygame.quit() first.

Game Events

An event occurs when the user performs a certain action, like clicking the mouse or pressing a key. Pygame tracks every event that happens.

You can find out which events have occurred by calling the function pygame.event.get(). It returns a list of pygame.event.Event objects, which we'll call event objects for simplicity.

One of the many attributes (or properties) that event objects have is type. The type attribute tells you what event the object represents.

In the example above, we used event.type == QUIT. This checks if the game should be closed. As long as the user does not trigger a QUIT event, the game will keep running in an infinite loop.

Game Window

For the game, we need to create a fixed-size window where all the events will occur. The window's width and height in pixels are passed to the pygame.set_mode() function as a tuple:

DISPLAYSURF = pygame.display.set_mode((300, 300))

A pixel is the smallest possible area on the screen. There is no such thing as half a pixel or a quarter of a pixel, so both the width and height must be integers.

Frame Rate (FPS)

If you don’t set a frame rate limit, the computer will run the game loop as many times as it can in a second. To control the frame rate, you can use the tick(fps) method, where fps is an integer representing the frame rate. The tick(fps) method belongs to the pygame.time.Clock class and must be used with an object of that class.

FPS = pygame.time.Clock()
FPS.tick(60)

This will cap the game’s frame rate at 60 frames per second (FPS). The ideal FPS may vary depending on the game, but generally, you should aim for a value between 30 and 60. Keep in mind that if your game is complex or resource-heavy, the computer may struggle to run it at higher frame rates.

Colors

Pygame uses the RGB color system (Red, Green, Blue), where each color component can have a value between 0 and 255, providing 256 possible values for each color. These three colors combine to create all the colors you see on screens.

To use colors in Pygame, you create Color objects using RGB values in the form of a tuple:

BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
GREY = pygame.Color(128, 128, 128)
RED = pygame.Color(255, 0, 0)

One thing to note about working with colors is that if you draw a shape and assign it a color (e.g., green), only the outline will be green by default. To fill the shape with color, you need to use the fill method, which makes the entire shape that color.

Creating the Game

Now it’s time for the fun part—developing your first Python game. Below is the complete code for the project that you’ll have by the end of this tutorial.

# Import libraries
import pygame, sys
from pygame.locals import *
import random

# Initialize Pygame
pygame.init()

# Set frame rate
FPS = 60
FramePerSec = pygame.time.Clock()

# Define colors
WHITE = (255, 255, 255)

# Set game screen size
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600

# Create and fill the display screen with white
DISPLAYSURF = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
DISPLAYSURF.fill(WHITE)
pygame.display.set_caption("Game")

# Define the Player class
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("Player.png")
        self.rect = self.image.get_rect()
        self.rect.center = (160, 520)

    def update(self):
        pressed_keys = pygame.key.get_pressed()
        if self.rect.left > 0:
            if pressed_keys[K_LEFT]:
                self.rect.move_ip(-5, 0)
        if self.rect.right < SCREEN_WIDTH:
            if pressed_keys[K_RIGHT]:
                self.rect.move_ip(5, 0)

    def draw(self, surface):
        surface.blit(self.image, self.rect)

# Define the Enemy class
class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("Enemy.png")
        self.rect = self.image.get_rect()
        self.rect.center = (random.randint(40, SCREEN_WIDTH - 40), 0)

    def move(self):
        self.rect.move_ip(0, 10)
        if self.rect.bottom > 600:
            self.rect.top = 0
            self.rect.center = (random.randint(30, 370), 0)

    def draw(self, surface):
        surface.blit(self.image, self.rect)

# Create characters
P1 = Player()
E1 = Enemy()

# Define the game loop
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    
    P1.update()
    E1.move()

    DISPLAYSURF.fill(WHITE)
    P1.draw(DISPLAYSURF)
    E1.draw(DISPLAYSURF)

    pygame.display.update()
    FramePerSec.tick(FPS)

Now let's go over which Pygame Python commands are used here.

Game Initialization

Creating a game in Python with Pygame begins with importing the library. Open a file in any IDE or code editor and add these two lines:

import pygame
from pygame.locals import *

The first line imports the Pygame module for Python 3. The second line imports all the variables from pygame.locals.

You can skip the second import, but it significantly reduces the amount of code. For example, without the import, the event for exiting the game would need to be written as pygame.locals.QUIT. With the import, the syntax is much shorter — just write QUIT to add the event.

To use random values, import the random library. Without it, the game would be too predictable:

import random

Another important line to add at the beginning of the file is:

pygame.init()

This is mandatory when using the Pygame library. It must be added before using any other functions from Pygame, or you'll run into initialization problems. Therefore, you add init() at the beginning to prevent errors.

Defining Characters

The project uses an object-oriented approach, which allows to create classes that serve as the foundation for different characters. For instance, you'll have one class for enemies (obstacles in the game), and as you progress through levels, they can evolve and gain additional abilities.

Let's start by defining the player class:

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("Player.png")
        self.rect = self.image.get_rect()
        self.rect.center = (160, 520)

The image.load() function loads the player's image from a file. To define the sprite boundaries, you use the get_rect() function, which automatically creates a rectangle matching the image's size. This will be useful later when, for example, you implement collision logic between objects. The last line, self.rect.center, sets the player's initial position on the game screen.

def update(self):
    pressed_keys = pygame.key.get_pressed()
    if self.rect.left > 0:
        if pressed_keys[K_LEFT]:
            self.rect.move_ip(-5, 0)
    if self.rect.right < SCREEN_WIDTH:
        if pressed_keys[K_RIGHT]:
            self.rect.move_ip(5, 0)

The update method controls the player's movement. When it's called, it checks if the arrow keys are pressed.

In this project, we're only interested in left and right movement, which allows the player to dodge obstacles. If the left arrow is pressed, the player moves left, and similarly for right movement.

The move_ip() method takes two parameters. The first is the number of pixels to move the object horizontally, and the second is the number of pixels to move it vertically.

The conditions if self.rect.left > 0 and if self.rect.right < SCREEN_WIDTH ensure that the player doesn't move beyond the screen's edges.

def draw(self, surface):
   surface.blit(self.image, self.rect)

The blit() function draws objects on the screen. The first parameter is the object to be drawn (in this case, self.image), and the second is the sprite rectangle.

The enemy class is similar, but it includes a random number generator:

self.rect.center = (random.randint(40, SCREEN_WIDTH - 40), 0)

This ensures that obstacles appear at random locations each time, making the game less predictable.

Creating the Game Loop

The most important part of the game is the game loop:

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    P1.update()
    E1.move()

    DISPLAYSURF.fill(WHITE)
    P1.draw(DISPLAYSURF)
    E1.draw(DISPLAYSURF)

    pygame.display.update()
    FramePerSec.tick(FPS)

The loop runs indefinitely until the user exits the game. This is the simplest implementation. In practice, various events (e.g., losing all lives) could end the game.

First, the update functions for both the Player and Enemy classes are called. Then the screen is refreshed with DISPLAY.fill(WHITE). Finally, the draw function is called to render the objects on the screen.

The pygame.display.update() command updates the screen, displaying all the changes made during that cycle. The tick() function ensures that the frames per second do not exceed the previously set FPS value.

Conclusion

Your game is now ready. While it's not polished enough to order a VPS on Hostman and await a flood of players, it's your first Python game — and now you know how to improve it. For instance, you could add vertical movement or change the logic for spawning obstacles.

There are many possibilities for improving the project. For example, you could make a 3D game by using Pygame's raycasting features. While Pygame can't create something like Cyberpunk 2077, you could certainly make your version of Wolfenstein 3D.

There are numerous tutorials and guides on Pygame that can help you explore both the library and some universal game development concepts. If you later switch to a more advanced game engine, many of these concepts will still be relevant.

Python
23.10.2024
Reading time: 10 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us