Editor

Clear away spent bullets

Pygame challenges · Alien Wave, step 2 of 4 · 20 XP

After three shots the cannon goes quiet: bullets that flew off the top are still in the list.

Your task

Each bullet is a point (x, y), the tip of the bullet. The cannon can have three bullets in the list at once (the game checks len(bullets) < 3 before it fires), so a bullet that leaves the screen has to leave the list as well. Otherwise the list fills up with bullets nobody can see, and the cannon thinks they are still flying.

Write move_bullets(bullets, dy, height). Move every bullet down by dy: the new point is (x, y + dy), and a negative dy moves it up. Keep only the bullets still on the screen, those whose new y is from 0 to height - 1. Return them as a new list of (x, y) tuples in the same order, and leave the list you were given as it was.

Removing items from a list while a for loop walks through it makes the loop skip some, so build a new list of the bullets to keep instead.

The game calls bullets = move_bullets(bullets, -8, 360) every frame. In the last step the aliens drop bombs, and the same function moves them down with a dy of 3 (more in later waves). Your can_fire from the last step times the shots.

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
a bullet moves upmove_bullets([(100, 200)], -8, 360)[(100, 192)]
bombs move downmove_bullets([(50, 100), (80, 20)], 3, 360)[(50, 103), (80, 23)]
off the top is droppedmove_bullets([(10, 5), (40, 300)], -8, 360)[(40, 292)]
off the bottom is droppedmove_bullets([(10, 358), (40, 100)], 3, 360)[(40, 103)]
y of 0 is still on the screenmove_bullets([(10, 8)], -8, 360)[(10, 0)]
the list given is unchangedbefore = [(10, 5), (40, 300)] move_bullets(before, -8, 360)before[(10, 5), (40, 300)]