🎡 Fair Game, Episode 7
Four teddy-bear guards walk their beats. If one sees you it chases you round the corners, and if it catches you, you go back to the entrance and lose one of your three tries.
Episode 7 ends with this: four giant teddy bears in security caps walk up and down the alleys of the fairground, two tiles at a time, with a rolling walk. Get in front of one and in its sight and it turns on you and chases you, round corners and down alleys, and it is faster than a walk but slower than a run. If it gets to you, you are put back at the entrance and a Pip face disappears from the three at the bottom left. Lose all three and the game starts again. Hide behind a wall for three seconds and it gives up and goes back to its patrol. You will need: your project from episode 6, or the starter files below. You will make: a Bear class that patrols, sees, chases and catches, a find_path function, a lives counter and a respawn. You will learn: a state machine in its smallest form (patrolling or chasing), a field of view, line of sight by stepping along a line, and breadth-first search. Starter files: fair-game-ep06.zip is where this episode begins, fair-game-ep07.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 The fairground with ammo and a hand, 374 lines. This episode is the longest so far: the bear is about 100 lines on its own. Two steps: the bears and their rules, then the lives on the screen.
What a bear does
A bear has two states and one rule to switch between them: patrol walk to the other end of its beat, turn round, walk back. Forever. chase walk to where Pip is, as fast as it can. If it sees Pip, it chases. If it has not seen Pip for three seconds, it goes back to patrolling. That is all. A state machine with two states, and it is still enough to make a guard that feels alive: it turns round at the end of its beat, it spots you at the end of the alley, it follows you round the corner, it loses you and goes back to its post. Every enemy in the rest of this kind of game is this shape with more states. The next episode adds two more: stuck and slipping. Two questions make it work, and they are the interesting ones: How does a bear SEE Pip? How does a bear find its way round the walls to Pip?
Seeing: a field of view and a line
A bear sees Pip if three things are true: 1 He is close enough. VIEW is 5 tiles. 2 He is in front of the bear. VIEW_ANGLE is 1.0 radian either side of the way the bear faces, which is about 57 degrees, a cone of 115 degrees in all. The angle to Pip is atan2(dy, dx) minus the way the bear faces, wrapped to between minus pi and plus pi: that wrapping is the strange-looking (a - b + pi) % (2 pi) - pi, and it is there so that an angle of 359 degrees and one of 1 degree are 2 degrees apart and not 358. A bear also notices anything within 1.5 tiles, even behind it, so you cannot stand right behind one and tickle it. 3 Nothing is in the way. We walk along the line from the bear to Pip in steps of 0.2 tiles, and ask is_solid at each point. If one of the points is in a wall, the bear cannot see. This is not a raycast like the ones that draw the walls; it is simpler, and it is good enough for a guard. Condition 3 is what makes walls useful for hiding. Cotton candy and soda are the weapons; the corners are the defence.
Finding the way: breadth-first search
A bear chasing Pip cannot just walk in a straight line to him: there are walls. We want the shortest way round them. The classic answer is breadth-first search, and it takes a dozen lines. Start at the bear's tile. Look at its four neighbours (right, left, down, up). Every one that is not a wall and has not been seen gets written down, together with where we came from. Then look at the neighbours of those, and so on, one ring at a time, like a ripple spreading out from the bear. The first time the ripple reaches Pip's tile, we have found a shortest path, because we have gone ring by ring and no shorter one could have arrived earlier. Follow the "where we came from" notes backwards from Pip's tile to the bear, reverse the list, and you have the tiles to walk through. The queue of tiles still to look at is a deque, from the collections module: a list that is fast to take from the front. The map is only 26 by 20, so a whole search takes a small fraction of a millisecond. A bear repeats it every 0.35 seconds while it is chasing, so it follows Pip as he moves.
Step 1: bears
Make these changes to game.py:
Add this after line 4 of your file (import sys)
from collections import deque
- - -
Add this after line 49 of your file (SHOT_SPEED, MAX_CANDY = 9.0, 5)
PATROL_SPEED, CHASE_SPEED, VIEW, VIEW_ANGLE = 1.1, 2.0, 5.0, 1.0
# Each bear walks between two tiles: its post and the other end of its beat.
BEARS = [((2, 2), (2, 8)), ((22, 2), (22, 8)), ((8, 4), (16, 4)), ((6, 10), (18, 10)), ((2, 14), (6, 14)), ((18, 14), (22, 14))]
- - -
Add this after line 82 of your file (self.message, self.message_time = "", 0.0)
self.lives = 3
- - -
Add this after line 154 of your file (for name in ("shot_candy",):)
art[name] = pygame.image.load(ART / f"{name}.png").convert_alpha()
for name in ("guard_walk_a", "guard_walk_b", "pip_small"):
- - -
Add this after line 300 of your file (player.say("Fresh cotton candy!"))
def find_path(start, goal):
"""The shortest way between two tiles around the walls (a breadth-first search). Returns the tiles to walk through."""
came = {start: None}
todo = deque([start])
while todo:
cur = todo.popleft()
if cur == goal:
break
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nxt = (cur[0] + dx, cur[1] + dy)
if nxt not in came and not is_solid(nxt[0] + 0.5, nxt[1] + 0.5):
came[nxt] = cur
todo.append(nxt)
if goal not in came:
return []
path = []
while goal != start:
path.append(goal)
goal = came[goal]
return path[::-1]
class Bear:
"""A security guard. Walks between two tiles; chases when it sees us."""
def __init__(self, post, beat):
self.post, self.beat = post, beat
self.reset()
def reset(self):
self.x, self.y = self.post[0] + 0.5, self.post[1] + 0.5
self.goal = self.beat
self.path = []
self.facing = 0.0
self.chasing = False
self.lost = 0.0
self.repath = 0.0
self.walked = 0.0
def tile(self):
return int(self.x), int(self.y)
def sees(self, player):
dx, dy = player.x - self.x, player.y - self.y
dist = math.hypot(dx, dy)
if dist > VIEW:
return False
turned = (math.atan2(dy, dx) - self.facing + math.pi) % (2 * math.pi) - math.pi
if abs(turned) > VIEW_ANGLE and dist > 1.5: # only sees what is in front of it (or right beside it)
return False
steps = int(dist / 0.2)
return not any(is_solid(self.x + dx * i / steps, self.y + dy * i / steps) for i in range(1, steps))
def walk(self, dt, speed):
if not self.path:
return
tx, ty = self.path[0][0] + 0.5, self.path[0][1] + 0.5
dist = math.hypot(tx - self.x, ty - self.y)
step = speed * dt
self.walked += step
if dist <= step:
self.x, self.y = tx, ty
self.path.pop(0)
else:
self.facing = math.atan2(ty - self.y, tx - self.x)
self.x += (tx - self.x) / dist * step
self.y += (ty - self.y) / dist * step
def update(self, dt, player):
if self.sees(player):
self.chasing, self.lost = True, 0.0
self.repath -= dt
if self.repath <= 0:
self.path = find_path(self.tile(), (int(player.x), int(player.y)))
self.repath = 0.35
elif self.chasing:
self.lost += dt
if self.lost > 3.0: # lost us: back to the beat
self.chasing, self.path = False, []
if not self.chasing and not self.path:
if self.tile() == self.goal:
self.goal = self.post if self.goal == self.beat else self.beat
self.path = find_path(self.tile(), self.goal)
self.walk(dt, CHASE_SPEED if self.chasing else PATROL_SPEED)
def catches(self, player):
return math.hypot(self.x - player.x, self.y - player.y) < 0.8
def make_bears():
return [Bear(post, beat) for post, beat in BEARS[:4]] # four bears to start with: the other two join in the later levels
def bear_picture(bear):
return "guard_walk_a" if int(bear.walked * 2) % 2 == 0 else "guard_walk_b"
def respawn(player, bears):
"""Caught: the bears walk us back to the entrance, and everybody goes back to their beat."""
player.x, player.y = START
player.angle = -math.pi / 2
for bear in bears:
bear.reset()
- - -
Replace line 335
player, things, shots = Player(), make_things(), []
with
player, things, shots, bears = Player(), make_things(), [], make_bears()
- - -
Add this after line 356 of your file (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)
- - -
Add this after line 359 of your file (drawables += [("shot_candy", shot.x, shot.y, 0.25, 0.35) for shot in shots])
drawables += [(bear_picture(bear), bear.x, bear.y, 1.1, 0.0) for bear in bears]
What is new:
PATROL_SPEED, CHASE_SPEED, VIEW, VIEW_ANGLE 1.1 tiles a second on patrol, 2.0 when chasing (Pip walks at 3.0, so you can outrun a bear in a straight line), 5 tiles of sight and 1.0 radian of half-angle
BEARS four patrols now, as two tile positions each: the post and the other end of the beat. There are six in the list, and make_bears takes the first four. The last two join in the later levels (episode 10)
Player.lives three tries
find_path(start, goal) the search above. It returns the tiles to walk through, nearest first, or an empty list if there is no way
Bear.reset() puts the bear back on its post. The state is in a handful of fields: a position, the goal it is walking to, a path (a list of tiles), the angle it faces, whether it is chasing, a timer for how long it has lost us, and one for when to search again
Bear.sees(player) the three conditions above
Bear.walk(dt, speed) takes the next tile off the path and moves towards its middle. When it gets there it takes the next one. It also sets the angle it faces to the way it is moving, and counts how far it has walked, which is what we use to swap the legs
Bear.update(dt, player) the state machine. If it sees Pip, it is chasing: it searches again every 0.35 seconds. If it was chasing and does not see Pip now, it counts to three seconds and then stops. If it is not chasing and has no path, it picks the other end of its beat and searches for the way there
Bear.catches(player) true if it is within 0.8 tiles
bear_picture the walking picture changes every half a tile walked: that is two legs
respawn puts Pip back at START, facing up the corridor, and sends every bear back to its post
the drawing the bears go into the same list of things to draw as the tickets and the shots, so they are sorted with them: a bear in front of a lamp hides it, and a lamp in front of a bear hides the bear. A bear is 1.1 walls tall
the catch in main: if any bear catches Pip, he loses a life and is sent back. When he has none left, the game starts again with a new Player, new things and new bears
Run it:
(.venv) $ python game.py
You see the corridor again, and in it, walking across the plaza from side to side, a teddy bear in a blue security cap. Wait at the bottom: it walks left and right on its beat. Walk up to it: when it sees you it turns and comes at you, and the three Pip faces at the bottom left go down to two. (Checked by a script: a bear facing Pip from four tiles away was chasing within four frames, walked down the corridor to him and caught him: his lives went from three to two, he was back at the entrance and every bear was back on its post. It also ran 120 frames and closed normally, exit status 0.)
Step 2: the lives on the screen
Make these changes to game.py:
Add this after line 429 of your file (screen.blit(text, (WIDTH // 2 - text.get_width() // 2, HEIGHT - 140)))
draw_panel(screen, (14, HEIGHT - 70, 52 * player.lives + 16, 56))
for i in range(player.lives):
screen.blit(pygame.transform.scale(art["pip_small"], (44, 44)), (22 + i * 52, HEIGHT - 64))
What is new:
the lives panel one small Pip face per life, in a dark panel at the bottom left, sized to fit them. When he is caught, one face goes
Run it:
(.venv) $ python game.py
Three Pip faces at the bottom left, the ticket counter at the top and the ammo on the right. (Checked: it ran for 120 frames and closed normally, exit status 0.)

Things to try
Three changes before episode 8: 1 Change VIEW to 10 and VIEW_ANGLE to 3. What does a bear that sees everything do to the game? 2 Change CHASE_SPEED to 3.2, a little faster than Pip. Is it still possible to win? 3 Add a fifth bear: it is one more line in BEARS, and the first four are on the left and the right and in the plaza. Where would you put one? Episode 8 is the one that makes the game worth playing: cotton candy that sticks.
Check your work
If something is different: AttributeError: 'Bear' object has no attribute 'stuck' that is from the next episode; if you see it, you have lines from episode 8 in your file the bear walks through walls find_path is not used for walking, or is_solid is not checked in it the bear never notices you VIEW or VIEW_ANGLE is too small, or the angle wrap is wrong the bear spins on the spot the path is empty and the goal is the tile it is already on: the line that swaps post and beat must run the game freezes when a bear is chasing the path search loops forever: the came dictionary must record each tile as it is queued Not run in the lab: a map with a closed room that a bear is shut in (find_path then returns an empty list and it stands still) and very large maps (the search is fast, but not free).