keepcalculator

06 Numbers and Powers

Python Game for Raspberry Pi: How to Build One

Card No. 06·21375 · Updated · Standard formula, shown below

Average pace 5.00 min/km
Average speed
12.00 km/h
Result
Finish time
50 min
You entered
Distance
10 km
You entered
You enter
Finish time, Distance
You get
Average pace, Average speed
Rounding
2 dp

To create a Python game for the Raspberry Pi, you use the Pygame library, which handles graphics, sound, and input, then run your script from the terminal or desktop. You write the game logic in a standard Python file, and Pygame provides the window, sprites, and event loop. This guide walks you through the full process, from setting up your environment to packaging your game for others to play.

What You Need to Start

Before writing any code, make sure your Raspberry Pi is running a recent version of Raspberry Pi OS (formerly Raspbian). The default installation includes Python 3 and the Thonny IDE, but Pygame is not always pre-installed. You can install it with the package manager:

  • Open a terminal window and run sudo apt update to refresh the package list.
  • Install Pygame with sudo apt install python3-pygame. This pulls the version that works with your system’s Python.
  • Alternatively, use pip3 install pygame to get the latest release from the Python Package Index.

You also need a display. Any HDMI monitor or the official touchscreen works. For input, a USB keyboard and mouse are sufficient for most games; a gamepad can be added later using the pygame.joystick module.

Setting Up a Project Structure

Organizing your code from the start saves time. A typical project folder looks like this:

my_game/
  main.py
  sprites/
    player.png
    enemy.png
  sounds/
    jump.wav
    hit.wav
  settings.py

Keep assets (images, sounds) separate from code. Use relative paths in your script, like os.path.join('sprites', 'player.png'), so the game runs regardless of where the folder is located. This also makes it easier to share your project with others.

Writing the Game Loop

Every Pygame game follows the same core structure: initialize, load assets, then run an infinite loop that handles events, updates game state, and draws. Here is a minimal example that opens a window and keeps it open until you close it:

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("My First Game")
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    screen.fill((0, 0, 0))
    pygame.display.flip()
    clock.tick(60)

The clock.tick(60) limits the frame rate to 60 FPS, which prevents the game from running too fast on a powerful Pi and keeps CPU usage reasonable. Without it, the loop would run as fast as possible, making the game speed inconsistent.

Handling Input and Sprites

Player input is captured in the event loop. Keyboard presses generate KEYDOWN and KEYUP events. For continuous movement, check the state of keys each frame with pygame.key.get_pressed(). Here is a simple sprite that moves with arrow keys:

player_x = 400
player_y = 300
speed = 5

while True:
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        player_x -= speed
    if keys[pygame.K_RIGHT]:
        player_x += speed
    if keys[pygame.K_UP]:
        player_y -= speed
    if keys[pygame.K_DOWN]:
        player_y += speed

For more complex games, use the pygame.sprite.Sprite class. Create a subclass for each type of object (player, enemy, bullet) and give it an image and rect attribute. Then use pygame.sprite.Group to manage all sprites and detect collisions with pygame.sprite.groupcollide().

Adding Graphics and Sound

Pygame supports common image formats like PNG and JPG. For transparent backgrounds, PNG is best. Load images with pygame.image.load() and convert them to the display format with .convert_alpha() for faster blitting. Sound files in WAV or OGG work well; MP3 can be problematic due to licensing. Use pygame.mixer.Sound() for short effects and pygame.mixer.music for background tracks.

If you do not have art skills, create simple shapes with pygame.draw (rectangles, circles, polygons) or use free asset sites. For sound, you can generate basic tones with the numpy library or record your own. The Pi’s audio output is via the 3.5mm jack or HDMI; check the audio settings in the taskbar if you hear nothing.

Testing and Debugging on the Pi

Run your game from the terminal with python3 main.py. If you get an error, the terminal prints a traceback that tells you the line number and the problem. Common issues include:

  • Missing assets: the script cannot find an image or sound file. Check the path and that the file exists.
  • Performance lag: if the game is slow, reduce the window size, use smaller images, or lower the frame rate. The Pi’s GPU is limited, especially on older models.
  • Input not working: ensure the window has focus. Click on it first. Also check that you are using the correct key constants.

For more complex bugs, add print() statements to see variable values, or use the Thonny debugger. The Raspberry Pi also has a vcgencmd measure_temp command to check if the CPU is overheating, which can cause throttling and slowdowns.

Performance Tips for the Raspberry Pi

The Pi is not a gaming PC, but you can still get good performance with optimization. Use the full screen instead of a window for a small boost. Limit the number of sprites and avoid per-pixel effects. Pre-load all assets before the main loop. Use pygame.Rect collision detection instead of pixel-perfect masks unless absolutely necessary. For a 2D platformer or puzzle game, 60 FPS is achievable on a Pi 4; on a Pi Zero, you may need to drop to 30 FPS and reduce the resolution.

Also consider using the pygame.transform module to scale images once, rather than every frame. If you need to draw many particles, use a surface with per-pixel alpha sparingly; it is slow. Instead, use simple rectangles or small images.

Packaging and Sharing Your Game

Once your game works, you can share it. The simplest method is to zip the project folder and send it. The recipient must have Python and Pygame installed. For a more polished experience, create a desktop shortcut or a shell script that runs python3 main.py. You can also make it executable with chmod +x and add a shebang line at the top of your script: #!/usr/bin/env python3.

If you want to distribute a standalone executable, tools like pyinstaller can bundle everything into a single file, but they are not always reliable on the Pi due to the architecture. A simpler option is to provide a requirements.txt file with the Pygame version, and instructions to install it. For the Raspberry Pi, the most practical way is to share the source code and a short README.

Frequently Asked Questions

Do I need to install anything else besides Pygame? No, Pygame is the only required library for basic 2D games. For advanced features like 3D graphics, you might consider pygame-opengl or ursina, but they are more complex and not necessary for most projects.

Can I use Pygame on a Raspberry Pi Zero? Yes, but with limitations. The Pi Zero has a slower CPU and less RAM, so keep games simple: low resolution, few sprites, and no heavy effects. A snake or Tetris clone runs fine; a full 3D shooter does not.

Why is my game window not showing up when I run the script? This usually happens when you run the script from the terminal without a display environment, or if the script is not in the same directory as the assets. Make sure you are running it from the desktop session and that you have set the correct paths.

How do I add a gamepad controller? Pygame supports joysticks via pygame.joystick.Joystick. Initialize it at the start, then poll its axes and buttons in the main loop. Many USB controllers are plug-and-play; test with pygame.joystick.get_count() to see if it is detected.

Can I make a 3D game with Pygame? Pygame is not designed for 3D. It is a 2D library. For 3D, you would need OpenGL bindings or a different engine like Godot. However, you can simulate 3D with 2D sprites (like in classic Doom-style games) using raycasting, but that is advanced.

Is it better to use Godot or Pygame for a Pi game? Godot is a full game engine with a visual editor and can export to the Pi, but it has a steeper learning curve. Pygame is simpler and purely code-based, which is great for learning programming. For a quick prototype or a simple game, Pygame is faster; for a complex project, Godot might be worth the effort.

Related

Formula used
in t | Finish time | min | 50 | 0
in d | Distance | km | 10 | 0 | 100000
out pace | Average pace | min/km | t / d | 2
out speed | Average speed | km/h | d / (t / 60) | 2

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →