Complete the set-based collision system. Fill each blank with the correct set operation or data structure expression.
# Build a set for O(1) membership testing
snake_set = ▢1(snake)
# In the update step:
snake.insert(0, new_head)
snake_set.▢2(new_head)
if not ate_food:
tail = snake.pop()
snake_set.▢3(tail) # remove tail from set
# Self-collision check (O(1)):
body_set = set(snake[▢4:]) # exclude head (index 0)
alive = new_head ▢5 body_set
# Score with high-score tracking:
score = ▢6
if ate_food:
score["player"] ▢7= 1
if score["player"] > score[▢8]:
score["high"] = score["player"]
s__a__d_______n_____"______________________"_____The set-based code below has 3 bugs. Type the corrected line for each.
snake_set = set(snake)
snake.insert(0, new_head)
snake_set.add(new_head)
if not ate_food:
tail = snake.pop()
snake_set.remove(tail) # Bug 1 – can raise KeyError
body_set = set(snake) # Bug 2 – includes head
alive = new_head not in body_set
score["player"] + 1 # Bug 3 – doesn't save the result
Bug 1
Buggy line:
Your fix:
Hint: `remove()` raises KeyError if the element is missing. Which set method silently ignores a missing element?
Bug 2
Buggy line:
Your fix:
Hint: `set(snake)` includes the head at index 0. Collision with your own head would always end the game immediately.
Bug 3
Buggy line:
Your fix:
Hint: `+` computes the sum but discards it. Use `+=` to update the value stored in the dictionary.
Write a function `check_alive(snake, new_head, wall_death)` that returns `True` if the snake is alive after the move. It should check self-collision using a set AND optionally wall collision.
def check_alive(snake, new_head, wall_death=False):
hx, hy = new_head
# Check wall collision if wall_death is True
# YOUR CODE here
# Check self-collision using a set of body positions (exclude head)
# YOUR CODE here
return True # replace with correct logic
**Performance experiment:** Write a script that creates a list of 1 000 (x, y) tuples, then times 100 000 membership checks using both a list and a set. Print the ratio. Paste your timing code and results.
Answer all 5 questions, then the Reflective Journal will unlock.
1. snake = [(5,5),(4,5),(3,5)] — what is snake[1]?
2. How does the snake appear to move each frame?
3. snake.insert(0, new_head) — what does this do?
4. What does len(snake) tell you?
5. snake.pop() removes:
Answer each prompt thoughtfully. There are no right or wrong answers — this is your own reflection.