Editor

Cool down the cannon

Pygame challenges · Alien Wave, step 1 of 4 · 15 XP

Hold Space and the cannon fires a solid beam, a new bullet every single frame.

Your task

To make the cannon wait between shots, the game measures time. pygame.time.get_ticks() gives the milliseconds since the game started (1000 milliseconds make one second), so if you remember when something happened, a subtraction tells you how long ago that was. Measuring time keeps the cannon at the same speed even on a slow computer that draws fewer frames each second.

Write can_fire(now, last_shot, cooldown). All three are in milliseconds: now is the time now, last_shot the time of the last shot, and cooldown how long the cannon needs between two shots. Return True if at least cooldown milliseconds have passed since last_shot (exactly cooldown is enough), else False.

While Space is held, the game asks can_fire(now, last_shot, 300) every frame. When the answer is True it fires and sets last_shot = now. At the start last_shot is -1000, so the first shot never waits.

The function is at the top of the program, marked fix this. Press Run to play the game as it is, then Check when your function is ready.

What Check tests

CallShould give
400 ms after the last shotcan_fire(1000, 600, 300)True
only 100 ms aftercan_fire(1000, 900, 300)False
exactly the cooldown is enoughcan_fire(1200, 900, 300)True
a slower cannon, 800 mscan_fire(2000, 1500, 800)False
the first shot of the gamecan_fire(0, -1000, 300)True