Cotton candy sticks a teddy bear to the floor for six seconds. Soda sends it sliding. A bear that is stuck or sliding cannot catch you, and you can walk straight past it.
▶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 8 ends with this: a puff of cotton candy that reaches a bear sticks it to the floor in a lump of pink, with its arms in the air and a worried look, for six seconds. A can of soda, thrown with X, sends it sliding backwards with stars round its head, for three and a half seconds. While it is stuck or sliding it cannot catch you, and you can walk straight past it. Then it shakes itself and goes back to its beat. The soda stands refill your soda, and the cans show under the puffs at the top right.
You will need: your project from episode 7, or the starter files below.
You will make: hit detection between a shot and a bear, two helpless states for the bear, and the soda.
You will learn: circle-against-circle collision, two more states in the bear's state machine, timers that run out, and an effect that moves a character without it walking.
Starter files: fair-game-ep07.zip is where this episode begins, fair-game-ep08.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
Four bears that patrol and chase, 497 lines. Two steps: first the candy and the helpless bear, then the soda.
Two more states
Last episode the bear had two states. Now it has four:
patrol walk the beat
chase after Pip
stuck glued to the floor by cotton candy: does nothing for 6 seconds
dizzy slipped on soda: slides in the direction it was hit, for 3.5 seconds
The first two changed nothing. The new states are not worked out from what the bear sees; they are put on it from outside, by a shot, and they wear off by themselves. So they are not a state variable with names, they are two timers: stuck and dizzy. A bear with either above zero is helpless, and the first thing update does is count them down and, if they are still above zero, do nothing else. A bear is a state machine whose states are partly numbers.
Hitting a bear
How does a shot know that it has hit? The shot is a point. A bear is, for this purpose, a circle round its feet: if the distance between the two is less than 0.5 tiles, they touch. It is a distance with a square root in it (math.hypot does that), compared with a number. That is circle collision, and it is the simplest and the most used kind. The bear is much taller than wide, but a circle is good enough: a shot flies at chest height and what we are testing is whether it passed through the bear's column.
A shot that has hit something is no longer alive, so that one puff cannot stick two bears. And a helpless bear is skipped: you cannot hit one that is already stuck, so you cannot waste ammo by throwing at it, and you cannot keep one stuck for ever by throwing candy at it every five seconds without letting it go: you can only stick it again once it has been free.
Step 1: cotton candy sticks
Make these changes to game.py:
Add this after line 51 of your file (PATROL_SPEED, CHASE_SPEED, VIEW, VIEW_ANGLE = 1.1, 2.0, 5.0, 1.0)
STUCK_TIME, DIZZY_TIME, MAX_SODA = 6.0, 3.5, 4
- - -
Add this after line 161 of your file (for name in ("guard_walk_a", "guard_walk_b", "pip_small"):)
art[name] = pygame.image.load(ART / f"{name}.png").convert_alpha()
for name in ("guard_stuck", "guard_slip", "shot_soda"):
- - -
Add this after line 279 of your file (self.alive = True)
self.kind = "candy"
- - -
Add this after line 345 of your file (self.walked = 0.0)
self.stuck = 0.0
self.dizzy = 0.0
self.slide = (0.0, 0.0)
- - -
Add this after line 348 of your file (return int(self.x), int(self.y))
def helpless(self):
return self.stuck > 0 or self.dizzy > 0
- - -
Add this after line 376 of your file (def update(self, dt, player):)
if self.stuck > 0:
self.stuck -= dt
return
if self.dizzy > 0:
self.dizzy -= dt
nx, ny = self.x + self.slide[0] * dt, self.y + self.slide[1] * dt
if not is_solid(nx, ny):
self.x, self.y = nx, ny
self.slide = (self.slide[0] * (1 - 2.5 * dt), self.slide[1] * (1 - 2.5 * dt))
self.path = []
return
- - -
Replace line 394
return math.hypot(self.x - player.x, self.y - player.y) < 0.8
with
return not self.helpless() and math.hypot(self.x - player.x, self.y - player.y) < 0.8
- - -
Add this after line 401 of your file (def bear_picture(bear):)
if bear.stuck > 0:
return "guard_stuck"
if bear.dizzy > 0:
return "guard_slip"
- - -
Add this after line 410 of your file (bear.reset())
def hit_bears(shot, bears):
"""A shot that reaches a bear sticks it to the ground (candy) or sends it sliding (soda)."""
for bear in bears:
if not bear.helpless() and math.hypot(shot.x - bear.x, shot.y - bear.y) < 0.5:
if shot.kind == "candy":
bear.stuck = STUCK_TIME
else:
bear.dizzy = DIZZY_TIME
bear.slide = (shot.dx * 3.0, shot.dy * 3.0)
shot.alive = False
return True
return False
- - -
Add this after line 470 of your file (shot.update(dt))
hit_bears(shot, bears)
What is new:
STUCK_TIME, DIZZY_TIME, MAX_SODA six seconds, three and a half seconds, and at most four cans. The soda is in the next step
Shot.kind "candy" for now. A shot is candy or soda, and the kind decides what it does to a bear
Bear.stuck, dizzy, slide the two timers and the direction the bear is sliding. The slide is a pair of numbers, tiles a second in x and y
Bear.helpless() true if either timer is above zero
the top of Bear.update if stuck, count it down and return: nothing else happens. If dizzy, count it down and move by the slide, if the new place is free, and make the slide smaller each frame (1 - 2.5 * dt, so it slows down, which is what sliding looks like). A dizzy bear also forgets where it was going: its path is emptied, so when it comes round it searches again
Bear.catches a helpless bear cannot catch you. One line: return not self.helpless() and ... The bear can be right next to you and you are safe. Bears are not solid for Pip, so you can walk straight through a stuck one, and there is no way to push it either
bear_picture a stuck bear is drawn with the stuck picture, pink up to its knees and its arms in the air; a dizzy one with the slipping picture, with stars
hit_bears(shot, bears) for each bear that is not helpless and is within 0.5 tiles of the shot: stick it if it is candy, make it dizzy if it is soda, and send the shot's direction at 3 tiles a second as its slide. Mark the shot as used and return True, so we know a hit happened. The loop over shots in main calls it for every shot every frame
Run it:
(.venv) $ python game.py
Walk up the corridor to the plaza and face a bear as it crosses. Press Space: the puff flies, hits the bear, and the bear is stuck: pink to the knees, with its arms up. It does not move for about six seconds, and if you walk up to it nothing happens. Then it puts its arms down and goes on with its beat. (Checked by a script: a puff that reached a bear made it stuck for 6 seconds, it was helpless, and a stuck bear touching Pip did not catch him: his lives stayed at three.)
Step 2: soda
Make these changes to game.py:
Add this after line 88 of your file (self.lives = 3)
self.soda = 2
- - -
Add this after line 309 of your file (player.say("Fresh cotton candy!"))
if near_stand(player, "d") and player.soda < MAX_SODA:
player.soda += 1
player.say("Fizzy soda!")
- - -
Add this after line 471 of your file (screen.blit(pygame.transform.scale(art["pip_small"], (44, 44)), (22 + i * 52, HEIGHT - 64)))
draw_panel(screen, (WIDTH - 14 - 48 * MAX_SODA, 78, 48 * MAX_SODA, 56))
for i in range(player.soda):
screen.blit(pygame.transform.scale(art["shot_soda"], (40, 40)), (WIDTH - 10 - 48 * MAX_SODA + i * 48, 86))
- - -
Add this after line 504 of your file (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)
- - -
Replace line 521
drawables += [("shot_candy", shot.x, shot.y, 0.25, 0.35) for shot in shots]
with
drawables += [("shot_soda" if shot.kind == "soda" else "shot_candy", shot.x, shot.y, 0.25, 0.35) for shot in shots]
What is new:
Player.soda two cans to start with
the X key (or the Left Ctrl key) throws a can. It is the same as the Space code with kind set to "soda" and the soda count going down
the refill next to a soda stand, one can every half second, up to four. The same near_stand function, with the character d
the soda panel one can picture for each can, under the puffs at the top right
the drawing of a shot a soda shot is drawn with the soda picture, and a candy one with the candy picture
Run it:
(.venv) $ python game.py
Two cans under the three puffs. Throw one at a bear with X: the bear slips, stars circle its head, it slides a little way away from you and then stops, dazed, for about three seconds, and then recovers. (Checked by a script: a can that reached a bear made it dizzy for 3.5 seconds and it slid about 0.6 tiles in the direction of the throw within the first second, and Pip's can count went from two to one.)
Candy or soda?
The two weapons are not the same, and the difference is the game. Candy holds a bear for six seconds: long enough to run past it, grab a ticket and be gone. Soda holds it for 3.5 seconds, less, but it also slides the bear away from you in the direction you threw, which can clear the way down an alley. Candy refills at pink stands and soda at blue ones, and the blue ones are in the far corners. So you choose, all the time, between the weapon you have and the one you need.
Episode 8 running (a screenshot of the finished step).
Things to try
Three changes before episode 9:
1 Make STUCK_TIME 60. Is the game too easy? What about 2?
2 Make the slide 6.0 instead of 3.0. Does the bear slide through a wall? Why not? (Look at the line that moves a dizzy bear.)
3 Add a third weapon. It is a Shot with a new kind, a new picture and a new effect. Slow a bear down? Make it chase a decoy?
Episode 9 gives you a goal: five tickets, a gate and the Ferris wheel.
Check your work
If something is different:
AttributeError: 'Bear' object has no attribute 'helpless' the helpless method is missing, or catches is from episode 7
the puff passes through the bear hit_bears is not called for each shot, or the distance is 0.05, not 0.5
the bear is stuck for ever the stuck timer is not counted down: the first lines of Bear.update must subtract dt
a bear slides through a wall the new position is not checked with is_solid before the move
the can is thrown but nothing happens shot.kind is not "soda", so hit_bears treats it as candy: check the X key code
Not run in the lab: a bear hit by two shots in the same frame (only the first counts, because the shot is used up and the bear becomes helpless), and a bear that is stuck while Pip is chased by another.