Snake Game Simulation matches LeetCode 353. Design Snake Game, a common Atlassian interview problem tagged with Simulation, Deque (for snake body), HashSet (for collision detection), and Game Design elements.[1][3][5]
Design a SnakeGame class for a grid-based game. The snake starts at (0,0) as length 1. It moves via directions "U" (up), "D" (down), "L" (left), "R" (right). Food appears sequentially from a given list—only one at a time, next after eating current. Eating food grows snake by 1 (tail stays) and increments score; else tail moves. Game ends (return -1) on wall hit or self-collision (new head on body except tail when shrinking).[3][5][1]
` class SnakeGame: def init(self, width: int, height: int, food: List[List[int]]): # Initialize game state
def move(self, direction: str) -> int:
# Return score or -1 if game over
` Grid: width columns, height rows. Food: list of [row,col] positions.[3]
Example 1 (width=3, height=2, food=[,,]):[2][1]
snakeGame = SnakeGame(3, 2, food) snakeGame.move("R") → 0 # (0,1), tail moves from (0,0) snakeGame.move("D") → 0 # (1,1), tail from (0,1) snakeGame.move("R") → 1 # (1,2) eats food[0], grows, score=1 snakeGame.move("U") → 1 # (0,2), tail stays (1,1) snakeGame.move("D") → 2 # (1,2) eats food[1], grows, score=2 snakeGame.move("D") → -1 # (2,2) out of bounds
Visual steps:
Example 2 (Self-collision after loop): ` width=3, height=3, food=[[2,2]]