๐ŸŽก Fair Game, Episode 1

A window, and a fairground made of text. The map is a list of strings; everything else in the series stands on it. Real commands, real output, on Ubuntu 24.04.

Video: Fair Game, Episode 1 (Fair Game video)
Prefer to watch? This short video runs this page's main commands on a real Ubuntu 24.04 desktop, with on-screen captions and a synthetic voiceover (an AI voice trained on the author's own recording). Click to play, or watch it on YouTube.
Fair Game: you are Pip, a small kid who has sneaked into a fairground after closing time, and you want to ride the Ferris wheel. Giant teddy-bear security guards walk their beats. You stick them to the floor with cotton candy, or send them sliding with soda, collect five tickets and ride the wheel. Nobody gets hurt: a guard that catches you just walks you back to the entrance. We build it in eleven short episodes, as a first-person game in the style of the old shooters, but with cotton candy.
Episode 1 ends with this: a 1280x720 window with the whole fairground drawn from above in coloured squares: fence, striped tents, stall walls, a ticket gate at the top, two stands and six tickets. Esc quits.

You will need: Ubuntu 24.04 with a desktop, and a terminal. No pygame, no Python packages, nothing else.
You will make: one file, game.py.
You will learn: a virtual environment, the game loop, and a map stored as a list of text rows, drawn tile by tile.
Starter files: fair-game-ep01.zip has the finished game.py of this episode.

The setup commands and their output on this page are from a freshly installed Ubuntu 24.04 desktop (Python 3.12.3, pygame 2.6.1), the same clean machine as Burger Blaster episode 1. The game code of each step was run headless on Python 3.12 with pygame 2.5, and what it does is described below.

What we are making

The whole series, in one line each:

1   A window and a map          (this page)
2   Walk around
3   Casting rays
4   The fairground at night
5   Things to see
6   Cotton candy
7   The bears
8   Sticky and slippery
9   Open the gate
10  Title, levels and sound
11  Ship it: a launcher and a .deb

Each episode starts from the finished code of the one before, and the zip of each episode is a complete, working game. If you skip an episode, download its zip and carry on.

The trick behind a first-person game of this kind is old and simple. The world is a flat map, a grid of squares seen from above. The 3D view is made from that map: for every column of pixels on the screen we send a ray out across the map, see how far it goes before it hits a wall, and draw a taller strip for a near wall and a shorter strip for a far one. That is the whole of the 1990s shooter engine. The first two episodes only deal with the map and with walking about on it, so you can see what the later ones will be working from. All the pictures were drawn for this project with a Python script, the sound and the music are made with Python too, and the game uses nothing that is not ours.

Make a project folder

$ mkdir -p fair-game
$ cd fair-game
$ python3 --version
Python 3.12.3

Python 3.12 is what Ubuntu 24.04 ships. Any 3.10 or newer works the same.

A virtual environment, and the error you will probably get

A virtual environment is a folder that holds the Python packages of one project, so installing pygame here does not touch the rest of your system. Ubuntu makes it with the venv module:

$ python3 -m venv .venv
The virtual environment was not created successfully because ensurepip is not
available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.

    apt install python3.12-venv

You may need to use sudo with that command.  After installing the python3-venv
package, recreate your virtual environment.

Failing command: /home/ubuntu/burger-blaster/.venv/bin/python3

That is a clean Ubuntu: the venv module is split into its own package and is not installed by default. The message tells you the fix:

$ sudo apt install python3-venv
Setting up python3.12-venv (3.12.3-1ubuntu0.17) ...
Setting up python3-venv (3.12.3-0ubuntu2.1) ...

Running kernel seems to be up-to-date.

No services need to be restarted.

No containers need to be restarted.

No user sessions are running outdated binaries.

No VM guests are running outdated hypervisor (qemu) binaries on this host.

(Shortened to the last lines: apt also printed the package list and the download progress.) Now it works, and prints nothing when it does:

$ python3 -m venv .venv
$ ls -a
.
..
.venv

Turn the environment on. The prompt gets a (.venv) in front, and from now on python and pip mean the ones inside .venv:

$ source .venv/bin/activate
(.venv) $ which python
/home/ubuntu/burger-blaster/.venv/bin/python

Install pygame

pygame is the library that gives us the window, the keyboard, the pictures and the sound:

(.venv) $ pip install pygame
Collecting pygame
  Downloading pygame-2.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (12 kB)
Downloading pygame-2.6.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (14.0 MB)
   โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” 14.0/14.0 MB 28.1 MB/s eta 0:00:00
Installing collected packages: pygame
Successfully installed pygame-2.6.1
(Shortened to the last lines.)

Check that it imports. It prints its own version banner, then the number we asked for:

(.venv) $ python -c "import pygame; print(pygame.version.ver)"
pygame 2.6.1 (SDL 2.28.4, Python 3.12.3)
Hello from the pygame community. https://www.pygame.org/contribute.html
2.6.1

pygame 2.6.1 was the current release when this was written. The code in this series does not use anything new, so 2.5 and later will do.

Step 1: the smallest window

Make a file called game.py and put this in it. It is the whole skeleton of the game: one function with a loop that runs 60 times a second.

#!/usr/bin/env python3
"""Fair Game: sneak through the fairground in first person, stick the teddy-bear guards with cotton candy and ride the Ferris wheel."""
import sys

import pygame

WIDTH, HEIGHT = 1280, 720
FPS = 60


def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Fair Game")
    clock = pygame.time.Clock()
    running = True
    while running:
        dt = clock.tick(FPS) / 1000
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
        screen.fill((20, 30, 25))
        pygame.display.flip()
    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()

What each part does:

pygame.init()              start pygame's modules
set_mode((1280, 720))      open a window 1280 pixels wide and 720 tall, and give back its drawing surface
set_caption                the title in the title bar
Clock, tick(FPS)           waits until 1/60 s has passed since the last frame, and returns how many milliseconds that really was
/ 1000                     we want seconds, so dt is the time of this frame in seconds (about 0.0167). Nothing uses dt yet; from episode 2 everything that moves does
event.get()                every key press and click since the last frame. Esc and the close button stop the loop
screen.fill(colour)        paint the whole window one colour, (red, green, blue). Here a very dark green
display.flip()             show the frame we have just painted
if __name__ == "__main__"  run the game only when the file is run directly, so a test can import it without opening a window

Run it:

(.venv) $ python game.py

A plain dark window opens. Press Esc or click the close button and the program ends. That is a complete pygame program, and every game we write is this loop with more in it. (Checked: it ran for 60 frames and closed with Esc, exit status 0.)

Step 2: the fairground as a list of strings

Now the map. Change the file to this, which is also the file in fair-game-ep01.zip:

#!/usr/bin/env python3
"""Fair Game: sneak through the fairground in first person, stick the teddy-bear guards with cotton candy and ride the Ferris wheel."""
import sys

import pygame

WIDTH, HEIGHT = 1280, 720
FPS = 60

# The fairground is a list of strings, one per row of tiles.
#   F fence   # tent   S stall wall   N panel wall   W ticket gate   . sawdust
#   c candy stand   d soda stand   t ticket
MAP = [
    "FFFFFFFFFFFFFFFFFFFFFFFFFF",
    "FFFFFFFFFFFFFFFFFFFFFFFFFF",
    "FFt...##..NNWWNN..##..t.FF",
    "FF....##..NNWWNN..##....FF",
    "FF..####..........####..FF",
    "FF..####..........####..FF",
    "FF..##....SSt.SS....##..FF",
    "FF..##....SS..SS....##..FF",
    "FF......##SS..SS##......FF",
    "FF......##SS..SS##......FF",
    "FFt.##..............##t.FF",
    "FF..##.....c...d....##..FF",
    "FF..##..##SS..SS##..##..FF",
    "FF..##..##SS..SS##..##..FF",
    "FF....t.##......##......FF",
    "FF......##......##......FF",
    "FF..NN..............NN..FF",
    "FF.cNN..............NN.dFF",
    "FFFFFFFFFFFFFFFFFFFFFFFFFF",
    "FFFFFFFFFFFFFFFFFFFFFFFFFF",
]
WALL_COLORS = {"F": (150, 100, 62), "#": (224, 64, 56), "S": (64, 190, 178), "N": (130, 80, 170), "W": (250, 200, 60)}


def draw_map(screen, size, ox=0, oy=0):
    """The map seen from above: one square per tile."""
    for ty, row in enumerate(MAP):
        for tx, ch in enumerate(row):
            rect = (ox + tx * size, oy + ty * size, size, size)
            pygame.draw.rect(screen, WALL_COLORS.get(ch, (214, 178, 124)), rect)
            if ch == "t":
                pygame.draw.circle(screen, (250, 200, 60), (rect[0] + size // 2, rect[1] + size // 2), size // 3)
            elif ch in "cd":
                pygame.draw.rect(screen, (255, 150, 200) if ch == "c" else (90, 170, 240), (rect[0] + 2, rect[1] + 2, size - 4, size - 4))


def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Fair Game")
    clock = pygame.time.Clock()
    running = True
    while running:
        dt = clock.tick(FPS) / 1000
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False
        screen.fill((20, 30, 25))
        draw_map(screen, 36)
        pygame.display.flip()
    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()

What is new:

MAP = [ ... ]              one string per row of tiles, one character per tile. 26 columns and 20 rows. F is fence, # a striped tent, S a stall wall, N a panel wall, W the ticket gate, . is sawdust you can walk on, c and d are the candy and soda stands and t is a ticket. Edit the strings and you have a new fairground
MAP_W, ... (episode 2)     the map's size, worked out from the text, is added in the next episode, when something needs it
WALL_COLORS                a dictionary from a map character to a colour. A character that is not in it (the dots, the tickets, the stands) is drawn as sawdust
SOLID (episode 2)          which characters are walls. The next episode uses it for walking
draw_map(screen, size)     draws the whole map with squares of size pixels: 26 columns of 36 pixels is 936 pixels across, 20 rows is 720 pixels down. The size is a parameter because later we draw a small copy of it in the corner
enumerate(MAP)             gives the row number and the string; the inner enumerate gives the column number and the character
pygame.draw.rect           a filled square. Tickets get a gold circle on top, and the stands a small pink or blue square
ox, oy                     where on the screen the map starts. Zero for now

Run it:

(.venv) $ python game.py

The map fills the left of the window: a brown fence all round, red-and-cream tents shown in red, teal stall walls, a gold-and-purple gate at the top, a pink candy stand and a blue soda stand in the middle and in the corners, and six gold tickets. The top of the map is where the Ferris wheel will stand. (Checked: it ran for 60 frames and closed with Esc, exit status 0.)

Reading the map

A map is a path you can plan with. Look at it:

- the start is at the bottom, in the middle of the long corridor
- the corridor runs all the way up to the gate: that is the way to the wheel
- the stands are in the middle and in the two bottom corners, for refills
- the tents and stall walls make narrow alleys with tickets in them, and six teddy bears will walk those alleys

Row 0 and 1 and rows 18 and 19 are all fence: the outside edge is two tiles thick, so that a ray, a guard or Pip can never get out of the map, whatever happens. Games with a map in a list usually protect the edge like that.
Fair Game episode 1 running
Episode 1 running (a screenshot of the finished step).

Try it yourself

Three small changes, each a line or two. Do them before episode 2:

1  Change a letter in MAP: turn a # into a . and run it again. Keep every row the same length, or something later will break when we look up a column that is not there.
2  Change a colour in WALL_COLORS. Which colours do you like for the tents?
3  Change the size from 36 to 30 in the draw_map call. The map shrinks. Why does it not get bigger when you make it 40?

Episode 2 puts Pip on the map and lets you walk him about.

Check your work

If something is different:

ModuleNotFoundError: No module named 'pygame'   the environment is not active: run source .venv/bin/activate and try again
pygame.error: No available video device         no desktop session (for example over plain ssh): run it on the desktop, not in a text login
IndexError: string index out of range            a MAP row is shorter than the others; every row needs 26 characters
the window is there but black                    display.flip() is missing, or draw_map is not called

Not run in the lab: other Linux distributions, Wayland-only sessions (pygame uses SDL, which can run on either), Python older than 3.12, and pygame older than 2.5.