Complete the snake body update logic. Fill each blank so the snake moves, eats food, grows, and scores correctly.
import random
snake = [(10,7),(9,7),(8,7)] # head at index 0
food = (random.randint(0,GRID_COLS-1), random.randint(0,GRID_ROWS-1))
score = 0
# --- compute new head ---
hx, hy = snake[▢1]
if direction == "RIGHT": hx += 1
elif direction == "LEFT": hx -= 1
elif direction == "UP": hy -= 1
elif direction == "DOWN": hy += 1
new_head = (hx, hy)
# --- eat check ---
ate_food = (new_head == ▢2)
# --- update body ---
snake.▢3(0, new_head)
if not ate_food:
snake.▢4()
# --- score & respawn food ---
if ate_food:
score ▢5= 1
food = (random.randint(0,GRID_COLS-1), random.randint(0,GRID_ROWS-1))
_f___i_____p___The snake body code below has 3 bugs. Type the corrected line for each.
snake = [(10,7),(9,7),(8,7)]
food = (5, 5)
score = 0
hx, hy = snake[0]
if direction == "RIGHT": hx += 1
new_head = (hx, hy)
ate_food = (new_head == food)
snake.append(new_head) # Bug 1 – wrong end
if ate_food:
snake.pop(0) # Bug 2 – pops from wrong end; also should only pop when NOT eating
score += 1 # Bug 3 – score always increments
Bug 1
Buggy line:
Your fix:
Hint: The new head goes at the FRONT (index 0) of the list, not the back.
Bug 2
Buggy line:
Your fix:
Hint: Remove the TAIL only when NOT eating, and pop() removes the last element (the tail), not pop(0).
Bug 3
Buggy line:
Your fix:
Hint: Score should only increase when the snake actually eats — wrap it in the ate_food check.
Add **wall collision detection**: if the new head is outside the grid boundaries (hx < 0, hx >= GRID_COLS, hy < 0, hy >= GRID_ROWS), set `running = False` to end the game.
# After computing new_head, before updating body:
hx, hy = new_head
# YOUR CODE: check if new_head is outside the grid.
# If it is, set running = False and skip the body update.
ate_food = (new_head == food)
snake.insert(0, new_head)
if not ate_food:
snake.pop()
**Challenge:** Spawn food that avoids the snake's current body. Write a `spawn_food(snake)` function that loops until it finds a position not in the snake list, then call it whenever food is eaten. Paste the full function and the updated eat block.
Answer all 5 questions honestly. Your responses are recorded for research. Submit once to unlock the Reflective Journal.
1. Which code correctly adds a new head to the front of the snake list?
2. When the snake eats food, what is different about the body update?
3. snake = [(10,7),(9,7),(8,7)]. What does snake[0] return?
4. The snake body is stored as a list of tuples. What does each tuple represent?
5. Food is at (5, 3). The snake's new head is also at (5, 3). How is eating detected?