Snake Game
medium · simulation, collision rules
Brief-reported interview attribution (unverified): Microsoft, Amazon
How to approach an LLD roundImplement the Snake game on a width × height grid, rows 0..height-1,
columns 0..width-1. The snake starts as a single cell at (0, 0), facing right.
Food positions are passed in as a fixed list (no randomness — the list is the
deterministic stand-in for the random food spawner). move(direction) returns
"ok", "ate" (the head landed on the current food position — the snake grows
by one and the next food appears), or "game over".
class SnakeGame:
def __init__(self, width, height, food):
# food: list of [row, col] positions, in the order they appear
def move(self, direction):
# direction: "up" | "down" | "left" | "right"
# -> "ok" | "ate" | "game over"
def snake(self):
# -> list of [row, col] from head to tail
def score(self):
# -> number of food items eaten
def is_over(self):
# -> True once the game has ended
Rules. Hitting a wall ends the game. Moving into the snake's own body ends the
game — except moving into the tail cell is allowed, because the tail moves away
in the same step (unless the snake is eating, in which case the tail stays and the
move is a collision). Once the game is over, every further move returns
"game over". When the food list is exhausted there is no more food to eat.
Tests use explicit inputs and injected clocks/callbacks. No network, real threads or application-server execution is involved.
Public demo
# Public demo: run after implementing the class API above.
s = SnakeGame(5, 5, [(0, 1), (0, 2), (1, 2), (1, 1)])
print(s.move('right'))
print(s.snake())Starter code
class SnakeGame:
def __init__(self, width, height, food):
"""food: list of [row, col] positions, in the order they appear"""
pass
def move(self, direction):
'''direction: "up" | "down" | "left" | "right" -> "ok" | "ate" | "game over"'''
pass
def snake(self):
"""-> list of [row, col] from head to tail"""
pass
def score(self):
"""-> number of food items eaten"""
pass
def is_over(self):
"""-> True once the game has ended"""
pass
Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.
Return to the Python compiler