for loops work with range(), what enumerate() gives you, and how a list comprehension can filter items without crashing mid-loop.Complete the bonus food code
Fill in the 7 missing keywords. All must be correct to unlock Tier 2.
import time
bonus_foods = [] # each item: [x, y, spawn_time]
# Spawn 3 bonus foods at the start
for _ in [1](3): # blank 1
bx = random.randint(0, GRID_COLS-1)
by = random.randint(0, GRID_ROWS-1)
bonus_foods.[2]([bx, by, time.time()]) # blank 2
now = time.time()
# Draw each bonus food using enumerate
for [3], bf in [4](bonus_foods): # blank 3, blank 4
bx, by, _ = bf
pygame.draw.rect(screen, GOLD,
(bx*CELL_SIZE, by*CELL_SIZE, CELL_SIZE-2, CELL_SIZE-2))
# Filter: remove eaten foods and foods older than 8 s
bonus_foods = [
bf for bf in [5] # blank 5
if snake[0] != (bf[0], bf[ [6] ]) # blank 6: y-index
and now - bf[ [7] ] < 8 # blank 7: spawn_time index
]
Find and fix 3 bugs in the bonus food code
Type the corrected line in each box.
for _ in range():
bonus_foods.append([bx, by, time.time()])
for bf in bonus_foods:
if snake[0] == (bf[0], bf[1]):
bonus_foods.remove(bf) # bug here
for bf in enumerate(bonus_foods): # bug here
bx, by, _ = bf
Why does .remove(bf) inside a loop cause a bug?
Describe what happens when you call .remove() while iterating, and how the filter pattern fixes it. (10+ words)
Flash warning for expiring bonus foods
Using enumerate() and time.time(), draw bonus foods in RED when they have less than 2 seconds remaining, and GOLD otherwise. Write the draw loop below.
# Starter β fill in the flash logic
now = time.time()
for i, bf in enumerate(bonus_foods):
bx, by, spawn_t = bf
time_left = 8 - (now - spawn_t)
colour = ??? # GOLD if > 2s left, RED if <= 2s
pygame.draw.rect(screen, colour,
(bx*CELL_SIZE, by*CELL_SIZE, CELL_SIZE-2, CELL_SIZE-2))
Bonus food respawn system with streak multiplier
Design a system that: (1) uses range(needed) to refill bonus_foods back to 3 items whenever some expire, and (2) awards double points if the player eats 2 bonus foods in a row. Explain your design in code or words. (10+ words)
5 questions β answer honestly (first attempt counts for research)
No external help. Your genuine answers help improve this course.
1. What does for _ in range(5): do?
2. What does range(1, 8, 2) produce?
3. for i, bf in enumerate(bonus_foods): β what does this give you inside the loop?
4. Why shouldn't you call bonus_foods.remove(bf) inside a for bf in bonus_foods: loop?
5. The list comprehension [bf for bf in bonus_foods if snake[0] != (bf[0], bf[1]) and now - bf[2] < 8] keeps which items?
How confident do you feel now?
5 journal prompts β answer each in 5+ words