This page contains exercise answers and teaching guidance for
Step 5 — Bonus Food 🌟.
Not linked from the student pages.
Students: please go back and try the activities first.
for loop with range() to spawn a fixed number of bonus food itemsrange() to generate integer sequences with start, stop, and optional stepenumerate() to iterate over a list with both index and value simultaneouslybonus_foods)import time
# Bonus foods: list of [x, y, spawn_time] lists
bonus_foods = []
# Spawn 3 bonus foods at once using range()
for _ in range(3):
bx = random.randint(0, GRID_COLS - 1)
by = random.randint(0, GRID_ROWS - 1)
bonus_foods.append([bx, by, time.time()]) # store position + spawn time
now = time.time()
# Draw all bonus foods using enumerate() — gives index AND item
for i, bf in enumerate(bonus_foods):
bx, by, spawn_t = bf
time_left = 8 - (now - spawn_t)
colour = RED if time_left <= 2 else GOLD # flash warning!
pygame.draw.rect(screen, colour,
(bx * CELL_SIZE, by * CELL_SIZE, CELL_SIZE - 2, CELL_SIZE - 2))
# Filter: remove eaten foods AND foods older than 8 seconds
bonus_foods = [
bf for bf in bonus_foods
if snake[0] != (bf[0], bf[1]) # not eaten
and now - bf[2] < 8 # not expired
]
for _ in range(3):range(3) generates 0, 1, 2 — three iterations. The underscore _ is a convention meaning "we don't care about this counter value". Emphasise that range(n) gives exactly n repetitions, starting from 0.
enumerate(bonus_foods)Wraps a list and yields (index, item) pairs on each iteration. Without enumerate, you can loop over items but not know their position. With it, you get both: i for the index and bf for the item. Ask: "When might knowing the index matter?" (e.g., to update a specific element by position, or colour-code by index).
time.time()Returns current time as seconds since epoch (a float). Subtracting two calls gives elapsed seconds — this is how any timed event works in Python, not just games.
Storing [x, y, spawn_time] means each item carries its own metadata — a common pattern for game objects. Ask students: "What other properties might we store here?" This plants the seed for Step 9's OOP refactor.
[item for item in list if condition] creates a new list containing only items where the condition is True. This is how we "remove" items — we rebuild the list without them.
Why not list.remove() inside a for loop? Modifying a list while iterating it causes skipped elements — Python's for loop uses an index internally and removal shifts subsequent positions. The filter pattern avoids this entirely by creating a new list.
| Blank | Answer | Concept tested |
|---|---|---|
| 1 | range |
for _ in range(3): — using range() to repeat exactly 3 times |
| 2 | append |
bonus_foods.append([bx, by, time.time()]) — list method to add a new item at the end |
| 3 | i |
The index variable when unpacking enumerate — convention for "integer index" |
| 4 | enumerate |
for i, bf in enumerate(bonus_foods): — built-in that yields (index, item) pairs |
| 5 | bonus_foods |
The list being filtered — [bf for bf in bonus_foods if …] |
| 6 | 1 |
Index of y in [x, y, spawn_time] — bf[1] gives the y-coordinate |
| 7 | 2 |
Index of spawn_time in [x, y, spawn_time] — bf[2] gives the spawn timestamp |
Buggy code: for _ in range():
Effect: TypeError: range expected at least 1 argument, got 0 — the program crashes immediately.
for _ in range(3):
Teaching note: range() requires at least one argument — the stop value. range(3) gives 0, 1, 2 — three iterations.
Buggy code: bonus_foods.remove(bf) inside for bf in bonus_foods:
Effect: Skips items — removal shifts the list indices mid-iteration so some bonus foods are never checked.
bonus_foods = [bf for bf in bonus_foods if snake[0] != (bf[0], bf[1])]
Teaching note: Never modify a list you are currently iterating. The filter pattern builds a new list and replaces the old one atomically.
Buggy code: for bf in enumerate(bonus_foods):
Effect: bf receives a tuple like (0, [bx, by, t]) — the subsequent bx, by, _ = bf unpacking fails with ValueError: too many values to unpack.
for i, bf in enumerate(bonus_foods):
Teaching note: enumerate() yields pairs — always unpack into two variables: i (index) and the item name.
Students extend the draw loop to colour bonus foods RED when less than 2 seconds remain, GOLD otherwise. Uses enumerate() and time.time().
now = time.time()
for i, bf in enumerate(bonus_foods):
bx, by, spawn_t = bf
time_left = 8 - (now - spawn_t)
colour = RED if time_left <= 2 else GOLD
pygame.draw.rect(screen, colour,
(bx * CELL_SIZE, by * CELL_SIZE, CELL_SIZE - 2, CELL_SIZE - 2))
Key point: enumerate() is practised here — the index i is available for per-food state if needed. The ternary RED if time_left <= 2 else GOLD is an elegant one-liner for conditional colour choice. Accept equivalent if/else blocks.
Students design a system that refills bonus_foods back to 3 items using range(needed) and awards double points after 2 consecutive bonus foods eaten.
# After filtering expired/eaten foods, refill to 3
needed = 3 - len(bonus_foods)
for _ in range(needed):
bx = random.randint(0, GRID_COLS - 1)
by = random.randint(0, GRID_ROWS - 1)
bonus_foods.append([bx, by, time.time()])
# Streak multiplier (track separately)
streak = 0
# When bonus food eaten:
streak += 1
points = 3 * (2 if streak >= 2 else 1) # double points on streak
score += points
# When normal food eaten OR bonus expires without being eaten:
streak = 0
Accept any design that correctly uses range(needed) to refill and a counter variable for the streak. Award full marks for clear logic even if syntax is approximate.
| Prompt | Key ideas a strong answer contains |
|---|---|
1. When use for instead of while? Example from the game. |
Use for when iterating over a known collection or a fixed count (e.g., for bf in bonus_foods or for _ in range(3)). Use while when the number of iterations depends on a runtime condition (while running:). Example: spawning 3 bonus foods at once uses for _ in range(3). |
2. What does range(0, 10, 2) produce? Why is the last value 8, not 10? |
Produces 0, 2, 4, 6, 8. The stop value (10) is exclusive — range never includes it. After 8, the next step would be 10 which equals stop, so it is excluded. There are 5 values total. |
3. Why is enumerate() useful when drawing bonus foods? |
enumerate() gives both the index i and the item bf in each iteration. Without it you only get the item. The index lets you reference or update a specific food by its position — useful for per-food state such as a flashing phase offset unique to each food. |
| 4. Trace the filter pattern with 3 foods — 1 eaten, 1 expired. Which remain? | Start with [A, B, C] where A is the snake's position (eaten) and B is older than 8 s (expired). A fails the "not eaten" test → excluded. B fails the "not expired" test → excluded. C passes both → kept. Result: [C]. Only 1 food remains. |
| 5. New mechanic idea + which Step 5 concepts used | Accept any creative mechanic that names specific concepts. Example of strong answer: "A 'mega food' that spawns 1 per type using range(3) — I'd draw each type with a different colour using enumerate(), and use the filter pattern to remove it when eaten or after 5 seconds." |
Correct answers: CQ_ANS = [2, 2, 3, 2, 2] (1-indexed). The student's first attempt is recorded for research; re-attempts do not count.
| Q | Answer | Question & explanation |
|---|---|---|
| 1 | B (2) | "What does for _ in range(5): do?"Correct: Runs the loop body 5 times (values 0, 1, 2, 3, 4). range(5) starts at 0 and excludes 5 — five iterations total. |
| 2 | B (2) | "What does range(1, 8, 2) produce?"Correct: 1, 3, 5, 7. Starts at 1, steps by 2, stops before 8. The next value (9) exceeds stop, so it is excluded. |
| 3 | C (3) | "for i, bf in enumerate(bonus_foods): — what does this give you?"Correct: Both the index i and the item bf. enumerate() yields (index, item) tuples unpacked into two variables each iteration. |
| 4 | B (2) | "Why shouldn't you call bonus_foods.remove(bf) inside a for loop?"Correct: It shifts indices, causing the loop to skip items. Removing an element moves all subsequent elements one position earlier, so the loop's internal pointer skips one. |
| 5 | B (2) | "The list comprehension … keeps which items?" Correct: Foods less than 8 seconds old AND not yet eaten. Both conditions must be True — the food's position does not equal the snake head, AND its age is under 8 seconds. |
| What they did | What they see | What to say |
|---|---|---|
range() with no argument |
TypeError: range expected at least 1 argument |
"range() needs at least a stop value. range(3) gives 0, 1, 2 — three iterations." |
list.remove(bf) inside for loop |
Some bonus foods never removed; random skipping | "Modifying a list while iterating skips items. Build a new list with only what you want to keep." |
for bf in enumerate(bonus_foods): without unpacking |
ValueError: too many values to unpack |
"enumerate() gives pairs — write for i, bf in enumerate(…): to unpack both index and item." |
time.time() called only once outside the loop |
All bonus foods get the same spawn time; age calculation is wrong | "Call time.time() each frame and store as now. Use now - bf[2] to measure elapsed time." |
Used bf = [bx, by, now] then compared bf == (food_x, food_y) |
Never matches — list vs tuple | "bonus_foods items are lists; compare (bf[0], bf[1]) with the snake head tuple." |
"How does a game spawn enemies over time? How does it 'clean up' enemies that are dead or off-screen?" Both use the same pattern students are implementing here.
Draw range(3) as boxes on the board: [0] [1] [2] — three boxes. Then show enumerate(['A','B','C']) yields (0,'A'), (1,'B'), (2,'C'). Ask: "What's the difference between just iterating a list and using enumerate?" Emphasise that the index is free — you're not paying a performance cost to have it.
Spend 5 minutes walking through the list comprehension slowly. Write on the board: "New list = [item | keep it if condition is true]". Ask students to predict which items survive before running the code.
Each bonus food is a self-contained object (position + time). Ask: "What other properties might a more complex game object carry?" This plants the seed for Step 9's OOP refactor.
Differentiation: Fast finishers can try adding a second type of bonus food (e.g., a "slow" power-up that halves FPS for 3 seconds) — this requires a type field stored in each [x, y, t, type] item, and using enumerate() to draw each type with a different colour.