Complete the Snake class. Fill each blank with the correct attribute name, method body, or keyword.
class Snake:
def __init__(self, start_x, start_y):
self.▢1 = [(start_x, start_y),
(start_x-1, start_y),
(start_x-2, start_y)]
self.body_set = ▢2(self.body)
self.▢3 = "RIGHT"
self.grew = False
def turn(self, new_dir):
opposite = {"UP":"DOWN","DOWN":"UP",
"LEFT":"RIGHT","RIGHT":"LEFT"}
if new_dir != opposite[self.▢4]:
self.direction = ▢5
def is_alive(self):
hx, hy = self.body[▢6]
return (0 <= hx < GRID_COLS) and (0 <= hy < GRID_ROWS) \
and self.body[0] not in set(self.body[▢7:])
b___s__d________d________n________The Snake class below has 3 bugs. Type the corrected line for each.
class Snake:
def __init__(self, sx, sy):
self.body = [(sx,sy),(sx-1,sy),(sx-2,sy)]
self.body_set = set(self.body)
self.direction = "RIGHT"
def turn(self, new_dir):
opposite = {"UP":"DOWN","DOWN":"UP","LEFT":"RIGHT","RIGHT":"LEFT"}
if new_dir != opposite[direction]: # Bug 1 – missing self.
self.direction = new_dir
def move(self):
hx, hy = body[0] # Bug 2 – missing self.
dx, dy = {"RIGHT":(1,0),"LEFT":(-1,0),
"UP":(0,-1),"DOWN":(0,1)}[self.direction]
new_head = (hx+dx, hy+dy)
self.body.append(new_head) # Bug 3 – wrong end
self.body_set.add(new_head)
if not self.grew:
tail = self.body.pop()
self.body_set.discard(tail)
self.grew = False
Bug 1
Buggy line:
Your fix:
Hint: `direction` is an instance attribute — access it through `self.` inside a method.
Bug 2
Buggy line:
Your fix:
Hint: `body` is `self.body` — the list is an attribute of the instance, not a standalone variable.
Bug 3
Buggy line:
Your fix:
Hint: The new head goes at the FRONT of the body list (index 0), not appended to the back.
Complete the `Snake.move()` method (starter below). It should compute the new head from direction, update body and body_set, and handle growing.
def move(self):
hx, hy = self.body[0]
dx, dy = {"RIGHT":(1,0),"LEFT":(-1,0),
"UP":(0,-1),"DOWN":(0,1)}[self.direction]
new_head = (hx + dx, hy + dy) # no wrap here; handle in caller if needed
# YOUR CODE:
# 1. Insert new_head at front of self.body and self.body_set
# 2. If not self.grew: pop tail from self.body and discard from self.body_set
# 3. Reset self.grew = False
pass
**Challenge:** Write a `Game` class that owns a `Snake` instance plus `food`, `score`, and `running`. Give it `handle_events()`, `update()`, and `draw(screen)` methods. Paste the complete class.
Answer all 5 questions, then the Reflective Journal will unlock.
1. TypeError: unsupported operand type(s) for +: 'int' and 'str' usually means:
2. Why read a Python traceback from the bottom up?
3. Adding print(snake_body) inside the game loop helps because:
4. IndentationError means:
5. 'Rubber-duck debugging' means:
Answer each prompt thoughtfully. There are no right or wrong answers — this is your own reflection.