🎡 Fair Game, Episode 9

Collect five tickets and the gate at the end of the corridor opens. Walk through it and you ride the Ferris wheel. Lose all three tries and the bears walk you out of the fair.

Video: Fair Game, Episode 9 (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.
Episode 9 ends with this: it is a whole game. You collect tickets, and when you have five a message says "The gate is open! Run to the wheel!" and the gate at the end of the corridor is gone, so you can see the Ferris wheel up close. Walk through the opening and the screen says "You rode the Ferris wheel!". If the bears catch you three times it says "The bears walked you out of the fair". Either way, Enter starts again.

You will need: your project from episode 8, or the starter files below.
You will make: an open_gate function, a state variable, a message panel and a new_game function.
You will learn: changing the map while the game runs, game states (play, won, over), and starting a game again without restarting the program.
Starter files: fair-game-ep08.zip is where this episode begins, fair-game-ep09.zip is where it ends. Both have the art folder.

The code of each step was run headless on Python 3.12 with pygame 2.5, and what it does is described below.

Where we start

Open a terminal, go to the project, turn on the virtual environment and run the game:

$ cd fair-game
$ source .venv/bin/activate
(.venv) $ python game.py

Candy, soda, bears, tickets, 550 lines. You can play it, but there is no end to it: the tickets count up and nothing happens at five. Two steps: the gate and the states, then the messages.

Opening a gate

The gate is part of the map: the letter W in the middle of the top. A ray stops at W and draws the gate picture, and Pip cannot walk into it. To open the gate we change those letters. The map is a list of strings, and a string cannot be changed, but a list can have an item replaced with a new string:

  for y, row in enumerate(MAP):
      MAP[y] = row.replace("W", "G")

G is the opened gate. It is in neither SOLID nor WALLS, so a ray goes through it and Pip can walk into it, and the picture we used to draw is gone, so the corridor opens onto the fence and the Ferris wheel behind it. Nothing else had to change: the whole game reads the map every time it needs it, so the change shows in the 3D view, in the walking and in the bears' paths on the very next frame.

Winning is then one line: is the tile Pip is standing on a G?

  if MAP[int(player.y)][int(player.x)] == "G":

That is the whole of "ride the Ferris wheel". We do not animate the ride: the screen says you rode it.

Game states

Until now the game has always been playing. A game with an end needs to know which part of itself it is in. The usual answer is a variable that holds a word: state is "play", "won" or "over". Each part of the main loop looks at it:

  events:   Enter does something only when the state is not "play"
  update:   the world moves only when the state is "play"
  drawing:  a message is drawn on top of the picture when the state is "won" or "over"

When the player wins or loses, the state changes, the world stops, and the last frame stays on screen behind a message. Pressing Enter builds a new world and goes back to "play". That is a state machine too, like the bear's, and a very small one.

Starting again needs a new Player, new tickets and bears, and the gate closed again. So we keep a copy of the original map, MAP_START, and put it back with MAP[:] = MAP_START: assigning to the whole slice replaces the contents of the same list, so every function that looks at MAP sees the new rows. The function new_game does all of it and returns the player, the things, the shots and the bears.

Step 1: the gate and the states

Make these changes to game.py:

Add this after line 40 of your file (MAP_W, MAP_H = len(MAP[0]), len(MAP))

MAP_START = list(MAP)

- - -

Add this after line 455 of your file (return False)

def open_gate():
    """Five tickets: the ticket gate turns into an open way through."""
    for y, row in enumerate(MAP):
        MAP[y] = row.replace("W", "G")


def new_game():
    MAP[:] = MAP_START
    return Player(), make_things(), [], make_bears()

- - -

Replace line 496

    player, things, shots, bears = Player(), make_things(), [], make_bears()

with

    player, things, shots, bears = new_game()
    state = "play"

- - -

Replace lines 508-531

            elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and player.candy > 0:
                player.candy -= 1
                player.recoil = 0.25
                shots.append(Shot(player.x, player.y, player.angle))
            elif event.type == pygame.KEYDOWN and event.key in (pygame.K_x, pygame.K_LCTRL) and player.soda > 0:
                player.soda -= 1
                player.recoil = 0.25
                shot = Shot(player.x, player.y, player.angle)
                shot.kind = "soda"
                shots.append(shot)
        player.update(dt, pygame.key.get_pressed())
        collect(player, things)
        refill(player, dt)
        for shot in shots:
            shot.update(dt)
            hit_bears(shot, bears)
        shots = [shot for shot in shots if shot.alive]
        for bear in bears:
            bear.update(dt, player)
        if any(bear.catches(player) for bear in bears):
            player.lives -= 1
            if player.lives <= 0:
                player, things, shots, bears = Player(), make_things(), [], make_bears()
            respawn(player, bears)

with

            elif event.type == pygame.KEYDOWN and state == "play":
                if event.key == pygame.K_SPACE and player.candy > 0:
                    player.candy -= 1
                    player.recoil = 0.25
                    shots.append(Shot(player.x, player.y, player.angle))
                elif event.key in (pygame.K_x, pygame.K_LCTRL) and player.soda > 0:
                    player.soda -= 1
                    player.recoil = 0.25
                    shot = Shot(player.x, player.y, player.angle)
                    shot.kind = "soda"
                    shots.append(shot)
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN and state != "play":
                player, things, shots, bears = new_game()
                state = "play"
        if state == "play":
            player.update(dt, pygame.key.get_pressed())
            collect(player, things)
            refill(player, dt)
            for shot in shots:
                shot.update(dt)
                hit_bears(shot, bears)
            shots = [shot for shot in shots if shot.alive]
            for bear in bears:
                bear.update(dt, player)
            if any(bear.catches(player) for bear in bears):
                player.lives -= 1
                respawn(player, bears)
                player.say("Caught! Back to the entrance.")
                if player.lives <= 0:
                    state = "over"
            if player.tickets >= TICKETS_NEEDED and "W" in "".join(MAP):
                open_gate()
                player.say("The gate is open! Run to the wheel!", 4.0)
            if MAP[int(player.y)][int(player.x)] == "G":
                state = "won"

What is new:

MAP_START                     a copy of the map as it is when the program starts, with list(MAP)
open_gate                     the loop above
new_game                      puts the map back, and returns a new Player, a new list of things, an empty list of shots and new bears
state                         "play" to begin with, and set in the loop: lives gone is "over", a G under Pip is "won"
the events                    the Space and X keys work only while the state is "play". Enter works only when it is not, and builds a new game with new_game. Everything that happens in a frame is now inside if state == "play"
the update                    one place for everything that moves: Pip, the pickups, the refill, the shots, the bears. Then the new parts: if a bear catches Pip he loses a life, the bears go home and a message says "Caught! Back to the entrance."; if he has no lives left the state is "over"; if he has all the tickets and there is still a W on the map, the gate opens and a message says so; and if he stands on a G he has won
"W" in "".join(MAP)           is there a W anywhere in the map? The strings are joined into one so that a single "in" can look through all of them. It is a cheap way to open the gate once, not every frame

Run it:

(.venv) $ python game.py

You can play it as before. Collect five tickets: the message "The gate is open! Run to the wheel!" appears and the gate at the end of the corridor is gone. Walk into the opening: the world stops. (Checked by a script: with four tickets the gate was still there; with five it was gone and the message was showing; standing in the gate made the state "won"; Enter then started a new game with the gate closed again and no tickets; and three catches in a row took the lives from three to two, one and zero, and the state to "over".)

Step 2: the messages

Make these changes to game.py:

Add this after line 500 of your file (screen.blit(hand, (WIDTH - hand.get_width() - 40, HEIGHT - hand.get_height() + 60 + bob + player.recoil * 200)))

def draw_message(screen, font, lines, color=(255, 255, 255), middle=HEIGHT // 2):
    """A panel with a few lines of big text across the middle of the screen."""
    texts = [font.render(line, True, color) for line in lines]
    width = max(t.get_width() for t in texts) + 60
    draw_panel(screen, (WIDTH // 2 - width // 2, middle - 40 * len(texts) - 10, width, 80 * len(texts)))
    for i, text in enumerate(texts):
        screen.blit(text, (WIDTH // 2 - text.get_width() // 2, middle - 40 * len(texts) + i * 60 + 10))

- - -

Add this after line 567 of your file (pygame.draw.circle(screen, (255, 255, 255), (20 + int(player.x * 10), 20 + int(player.y * 10)), 4))

        if state == "won":
            draw_message(screen, font, ["You rode the Ferris wheel!", "Press Enter to play again"], (255, 240, 150))
        elif state == "over":
            draw_message(screen, font, ["The bears walked you out of the fair", "Press Enter to try again"], (255, 170, 215))

What is new:

draw_message                  a dark panel and some lines of big text across the middle of the screen. The panel is sized to fit the widest line
the won and over screens      drawn after everything else, so that the last frame is still there under them: "You rode the Ferris wheel!" in gold, or "The bears walked you out of the fair" in pink, each with "Press Enter to play again"

Run it:

(.venv) $ python game.py

Win, or let the bears catch you three times, and the message sits over the frozen view. Press Enter and you are back at the entrance with all the tickets back in the alleys. (Checked: it ran for 120 frames and closed normally, exit status 0.)
Fair Game episode 9 running
Episode 9 running (a screenshot of the finished step).

Things to try

Three changes before episode 10:

1  Change TICKETS_NEEDED to 2. Is a game of two tickets worth playing? What about 6, which is all of them?
2  Change the message when the gate opens. Why not give it a joke?
3  Make the gate open when you have five tickets AND no bear is chasing you. It is one more condition on the same line.

Episode 10 turns it into a proper game with a title screen, three levels, sound and music, and a best time.

Check your work

If something is different:

NameError: name 'new_game' is not defined      the function is missing, or it is below main in the file: it must be defined before the loop runs it
the gate opens, but you cannot walk in         G is in SOLID: it must not be
the gate never opens                           tickets are counted in collect, and the test is >= TICKETS_NEEDED; check both
the gate is open again after Enter             new_game does not put the map back with MAP[:] = MAP_START
Enter does nothing                             the Enter test is not outside the if state == "play" block

Not run in the lab: a map with two gates or no gate (open_gate changes every W, and a map without one can never be won) and a game that is won on the same frame as the last life is lost (the later test wins).