๐Ÿง Waddle Run, Episode 1

A window, a level made of text, and a night sky over the snow. Real commands, real output, on Ubuntu 24.04.

Video: Waddle Run, Episode 1 (Waddle Run 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.
Waddle Run: Tux, a very small penguin in a bobble hat, runs, jumps and slides through an icy world, collecting fish and stomping on grumpy crabs and snowballs. We build the game in eleven short episodes.
Episode 1 ends with this: a 1280x720 window with a starry night sky, aurora and two layers of mountains, and the first screen of the level drawn from text rows: snow, ice, snow bricks and a gap of water. Esc quits. Nothing moves yet.

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, and a picture folder called art.
You will learn: a virtual environment, the game loop, a level stored as text, and how to draw it tile by tile.
Starter files: waddle-run-ep01.zip has the art folder and 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 from pip), the same clean machine as the other game series on this site. The code of each step was run headless on Python 3.12 and pygame 2.5.2, and the numbers quoted below were measured by running it at 60 frames per second. Indentation matters in Python: the new lines on this page keep the indentation they need, so copy it exactly.

What we are making

The whole series, in one line each:

1  A window and a level
2  Scroll the world
3  Run and gravity
4  Jump
5  Solid ground
6  Fish and score
7  Crabs, stomps and hearts
8  Ice and sliding
9  Icicles, spikes and the igloo
10 Sound, title and best time
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 game is a side-scrolling platformer, the kind of game that Mario made famous: you run left to right through a long level, jump over gaps and enemies, and reach the goal. The level is far wider than the window, so the window is a camera that follows Tux. It is built from the same pieces as the other series on this site (a game loop, a grid of tiles, pictures drawn with a Python script), plus the things that make a platformer feel like one: gravity, a jump you can control, and solid ground. All the pictures were drawn for this project with Python, so there is nothing to license, and the sound effects and the electronic music loop are made with Python too.

Tux is the penguin's name. (It is also the name of the Linux mascot; this penguin was drawn from scratch for this project and is a different one.)

Make a project folder

$ mkdir -p waddle-run
$ cd waddle-run
$ 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: a class with a method for each job, and a loop that runs them 60 times a second.

#!/usr/bin/env python3
"""Waddle Run: Tux the penguin runs, jumps and stomps through an icy side-scroller."""
import sys

import pygame

WIDTH, HEIGHT = 1280, 720
FPS = 60


class Game:
    def __init__(self):
        self.t = 0.0

    def update(self, dt, keys):
        self.t += dt

    def draw(self, screen):
        screen.fill((40, 60, 110))  # night blue


def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Waddle Run")
    clock = pygame.time.Clock()
    game = Game()
    while True:
        dt = min(clock.tick(FPS) / 1000, 1 / 30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                pygame.quit()
                sys.exit()
        game.update(dt, pygame.key.get_pressed())
        game.draw(screen)
        pygame.display.flip()


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, min(..., 1 / 30)   we want seconds, so dt is the time of this frame in seconds (about 0.0167). The min stops one very slow frame from becoming a huge jump
event loop                 input: every key press and click since the last frame. Esc and the close button stop the loop
game.update(dt, keys)      move things, by speed times dt, so they move at the same speed on any computer. It only counts time for now
game.draw(screen)          paint the frame. fill gives the whole window one colour, (red, green, blue), and display.flip() shows it
if __name__ == "__main__"  run the game only when the file is run directly, so later we can import it for testing

Run it:

(.venv) $ python game.py

A plain night-blue 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 900 frames and closed cleanly.)

Step 2: a level made of text

Put the art folder next to game.py (it is in the zip). It holds the pictures for the whole series as PNG files with transparent backgrounds: Tux in six poses, fish, crabs, snowballs, icicles, spikes, the tiles, the igloo and the background layers. Now change the file. These are the edits; the whole file after step 3 is at the end of this episode.

Add this after line 3 of your file (import sys)

from pathlib import Path

- - -

Add this after line 8 of your file (FPS = 60)

TILE = 48
HERE = Path(__file__).resolve().parent
ART = HERE / "art"

# The level is a list of strings, one per row of tiles.
#   #  snow    =  ice (slippery)    B  snow brick    ~  water    P  where Tux starts
#   f  fish    F  golden fish       c  crab          o  snowball    ^  ice spikes
#   i  icicle  k  checkpoint flag   G  the igloo
LEVEL = [
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                        F                                                                       F                   f                                                                                                               F                  #",
    "                                                       f f                             BBB                                     f f     fff                                                               BBB           fff                                 BBB     f f                 #",
    "          fff           fff                           =====                             i                      fff    fff     =====   f   f         B                                                     i           f   f           fff                   i     =====                #",
    "#        f   f         f   f  ff f               B                              BBBBB                         f   f  f   f                         BBB                                        BBBBB                                  f   f      BBBBB                         f        #",
    "#  P                c           c     c     k   BBB           ^^        o ff     fff                  c     c                           ^^    c   BBBBB   k            ff o   ff      o        fff                      ^^  k                    fff                        c   c     G#",
    "########################~~~#######################################===========#########################################~~~###########################################===============###################################################~~~###############################################",
    "########################~~~###########################################################################################~~~#############################################################################################################~~~###############################################",
    "########################~~~###########################################################################################~~~#############################################################################################################~~~###############################################",
]
COLS, ROWS = len(LEVEL[0]), len(LEVEL)
LEVEL_W, LEVEL_H = COLS * TILE, ROWS * TILE


def load(name):
    return pygame.image.load(ART / name).convert_alpha()


def load_art():
    art = {
        "snow_top": load("tile_snow_top.png"),
        "snow": load("tile_snow.png"),
        "ice": load("tile_ice.png"),
        "block": load("tile_block.png"),
        "water": [load(f"tile_water_{i}.png") for i in range(3)],
    }
    return art


def tile_at(tx, ty):
    if tx < 0 or tx >= COLS:
        return "#"  # the edges of the world are walls
    if ty < 0 or ty >= ROWS:
        return " "
    return LEVEL[ty][tx]


def draw_level(screen, art, cam_x, t):
    first = int(cam_x // TILE)
    for ty in range(ROWS):
        for tx in range(first, min(first + WIDTH // TILE + 2, COLS)):
            ch = LEVEL[ty][tx]
            img = None
            if ch == "#":
                img = art["snow"] if tile_at(tx, ty - 1) in "#=B" else art["snow_top"]
            elif ch == "=":
                img = art["ice"]
            elif ch == "B":
                img = art["block"]
            elif ch == "~":
                img = art["water"][int(t * 3) % 3]
            if img:
                screen.blit(img, (tx * TILE - cam_x, ty * TILE))

- - -

Replace line 12

    def __init__(self):

with

    def __init__(self, art):
        self.art = art

- - -

Add this after line 13 of your file (self.t = 0.0)

        self.cam_x = 0.0

- - -

Replace line 19

        screen.fill((40, 60, 110))  # night blue

with

        screen.fill((40, 60, 110))  # night blue: the sky comes in step 3
        draw_level(screen, self.art, self.cam_x, self.t)

- - -

Replace line 27

    game = Game()

with

    art = load_art()
    game = Game(art)

What is new:

TILE = 48                  the world is a grid of squares 48 pixels wide. Everything in the game sits on this grid
LEVEL = [ ... ]            one string per row of tiles, and one character per tile. # is snow, = is slippery ice, B a snow brick, ~ water, f and F fish and a golden fish, c a crab, o a snowball, ^ ice spikes, i an icicle, k a checkpoint flag, G the igloo and P is where Tux starts. Edit the strings and you have a new level. (Most of the characters do nothing yet: later episodes add them one at a time.)
COLS, ROWS = len(...)      the size of the grid, worked out from the text: 280 columns and 15 rows
LEVEL_W, LEVEL_H           the world is 13,440 pixels wide and 720 tall. The window is only 1280 wide, so you can see about a tenth of the level at a time
HERE / ART                 the art folder, found next to the game file, wherever you run it from, using pathlib
load, load_art             read every picture we need into a dictionary, once. .convert_alpha() converts each picture to the window's pixel format, so drawing it later is fast and keeps the transparency
tile_at(tx, ty)            the character at a tile, with a safe answer for tiles outside the level: the sides are walls, above and below are empty. We will use this everywhere
draw_level                 for every row, and for the columns that can be on screen (first to first + 28), look at the character and blit the matching picture at x = tx * TILE - cam_x, y = ty * TILE. cam_x is how far the camera has moved right; for now it is 0
tile above is solid?       a snow tile with nothing above it gets the snowy top picture, and one with snow above it gets the plain one, so the ground has a clean edge on top and a solid fill below
int(t * 3) % 3             water has three pictures. This picks one three times a second, so the waves move

Run it:

(.venv) $ python game.py

The snowy ground runs across the bottom of the window with a gap of blue water to the right, and a small snow step at the far left. (Checked: the level is 280 tiles wide and 15 tall, with 27 water tiles, 41 ice tiles and 37 snow bricks.)

Step 3: the sky and the mountains

A flat blue window is not a night in the arctic. Four background pictures, each 1280 by 720, are drawn behind the level: the sky (stars and a green aurora), a layer of far mountains, a layer of nearer mountains and a layer of snowflakes. The whole file after step 3, which is also the file in waddle-run-ep01.zip:

#!/usr/bin/env python3
"""Waddle Run: Tux the penguin runs, jumps and stomps through an icy side-scroller."""
import sys
from pathlib import Path

import pygame

WIDTH, HEIGHT = 1280, 720
FPS = 60
TILE = 48
HERE = Path(__file__).resolve().parent
ART = HERE / "art"

# The level is a list of strings, one per row of tiles.
#   #  snow    =  ice (slippery)    B  snow brick    ~  water    P  where Tux starts
#   f  fish    F  golden fish       c  crab          o  snowball    ^  ice spikes
#   i  icicle  k  checkpoint flag   G  the igloo
LEVEL = [
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                                                                                                                                                                                                                                                       #",
    "                                                        F                                                                       F                   f                                                                                                               F                  #",
    "                                                       f f                             BBB                                     f f     fff                                                               BBB           fff                                 BBB     f f                 #",
    "          fff           fff                           =====                             i                      fff    fff     =====   f   f         B                                                     i           f   f           fff                   i     =====                #",
    "#        f   f         f   f  ff f               B                              BBBBB                         f   f  f   f                         BBB                                        BBBBB                                  f   f      BBBBB                         f        #",
    "#  P                c           c     c     k   BBB           ^^        o ff     fff                  c     c                           ^^    c   BBBBB   k            ff o   ff      o        fff                      ^^  k                    fff                        c   c     G#",
    "########################~~~#######################################===========#########################################~~~###########################################===============###################################################~~~###############################################",
    "########################~~~###########################################################################################~~~#############################################################################################################~~~###############################################",
    "########################~~~###########################################################################################~~~#############################################################################################################~~~###############################################",
]
COLS, ROWS = len(LEVEL[0]), len(LEVEL)
LEVEL_W, LEVEL_H = COLS * TILE, ROWS * TILE


def load(name):
    return pygame.image.load(ART / name).convert_alpha()


def load_art():
    art = {
        "sky": pygame.image.load(ART / "bg_sky.png").convert(),
        "far": load("bg_far.png"),
        "near": load("bg_near.png"),
        "flakes": load("snowflakes.png"),
        "snow_top": load("tile_snow_top.png"),
        "snow": load("tile_snow.png"),
        "ice": load("tile_ice.png"),
        "block": load("tile_block.png"),
        "water": [load(f"tile_water_{i}.png") for i in range(3)],
    }
    return art


def tile_at(tx, ty):
    if tx < 0 or tx >= COLS:
        return "#"  # the edges of the world are walls
    if ty < 0 or ty >= ROWS:
        return " "
    return LEVEL[ty][tx]


def draw_background(screen, art, cam_x, t):
    screen.blit(art["sky"], (0, 0))
    for key, speed in (("far", 0.15), ("near", 0.35)):  # far layers scroll slowly: that is what makes it look deep
        x = -(cam_x * speed) % WIDTH
        screen.blit(art[key], (x - WIDTH, 0))
        screen.blit(art[key], (x, 0))
    ox, oy = -(cam_x * 0.6) % WIDTH, (t * 50) % HEIGHT
    for dx in (ox - WIDTH, ox):
        for dy in (oy - HEIGHT, oy):
            screen.blit(art["flakes"], (dx, dy))


def draw_level(screen, art, cam_x, t):
    first = int(cam_x // TILE)
    for ty in range(ROWS):
        for tx in range(first, min(first + WIDTH // TILE + 2, COLS)):
            ch = LEVEL[ty][tx]
            img = None
            if ch == "#":
                img = art["snow"] if tile_at(tx, ty - 1) in "#=B" else art["snow_top"]
            elif ch == "=":
                img = art["ice"]
            elif ch == "B":
                img = art["block"]
            elif ch == "~":
                img = art["water"][int(t * 3) % 3]
            if img:
                screen.blit(img, (tx * TILE - cam_x, ty * TILE))


class Game:
    def __init__(self, art):
        self.art = art
        self.t = 0.0
        self.cam_x = 0.0

    def update(self, dt, keys):
        self.t += dt

    def draw(self, screen):
        draw_background(screen, self.art, self.cam_x, self.t)
        draw_level(screen, self.art, self.cam_x, self.t)


def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Waddle Run")
    clock = pygame.time.Clock()
    art = load_art()
    game = Game(art)
    while True:
        dt = min(clock.tick(FPS) / 1000, 1 / 30)
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
                pygame.quit()
                sys.exit()
        game.update(dt, pygame.key.get_pressed())
        game.draw(screen)
        pygame.display.flip()


if __name__ == "__main__":
    main()

What is new compared with step 2:

draw_background          draws the sky first, then each mountain layer, then the snow, then (in the next lines of Game.draw) the level on top. Whatever is drawn last is on top
speed 0.15 and 0.35      the layers move at a fraction of the camera. Far things move slowly and near things quickly: that is parallax, and it is what makes a flat picture look deep. Today the camera is still, so nothing moves; episode 2 scrolls it
% WIDTH                  the mountain pictures are drawn twice side by side and wrapped with a remainder, so they repeat forever. The pictures were drawn so that the left and right edges meet
oy = (t * 50) % HEIGHT   the snowflake layer also falls: 50 pixels a second, wrapped
Game.draw                two calls: the background, then the level

Run it:

(.venv) $ python game.py

A starry sky with a green glow, soft blue mountains in two layers, snow falling, and the ground with its water gap in front. Esc quits. (Checked: it ran for 300 frames and closed cleanly.)
Waddle Run episode 1 running
Episode 1 running (a screenshot of the finished episode).

Try it yourself

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

1  Change a letter in LEVEL: turn a # in the top row of the ground into a ~ and a new water gap appears. Keep every row the same length, or the right-hand edge goes ragged.
2  Add a row of B tiles above the ground to build a wall.
3  Change the window caption, and the speed of the falling snow.

Episode 2 makes the camera follow a penguin. For that, update(dt, keys) is where the work goes.

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
KeyError: 'snow_top'                              the art folder is not next to game.py, or it is empty
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 LEVEL row is shorter than the first one: every row must have the same number of characters
the window is there but black                     display.flip() is missing, or draw() 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. The setup commands come from the clean Ubuntu machine; the game steps were run headless (no window), so how smooth it feels on your screen was not measured here.