Question presented to candidate: "Build the classic Snake game in the browser. The snake moves one cell per tick on a grid, arrow keys steer it, eating food makes it longer and scores a point, and hitting a wall or itself ends the game. Add start, pause and restart."
Requirements:
- A 12 by 12 grid, a snake of length 3 moving right, one piece of food on a free cell.
- A fixed tick (about 150 ms): the snake moves exactly one cell per tick, independent of how often the UI re-renders.
- Arrow keys (and WASD) steer; pressing the direct opposite direction is ignored, and two quick presses within one tick must never reverse the snake into itself.
- Eating grows the snake by one and places new food on a free cell; walls and the body end the game.
- Space or a button pauses and resumes; Restart starts a new game; on-screen buttons for touch.
What a strong answer should cover:
- Rules as a pure
step(game)function, separate from rendering and from the timer, with the food RNG injected (seeded) so the game is reproducible. - A game loop with one interval that exists only while running, cleaned up on pause, game over and unmount.
- A direction queue validated against the last queued direction, consumed one per tick, which is what blocks the fast double-press 180-degree bug.
- Collision rules, including that the tail cell is free on a non-eating tick.
- Keyboard handling on
windowwithpreventDefaultfor arrows, and a note onsetIntervalversus arequestAnimationFrameaccumulator.
Clarifying questions expected:
- "Do walls kill the snake, or does it wrap around to the other side?"
- "Should the speed increase as the score grows?"
- "Do you need touch controls or just the keyboard?"
Code / implementation expected: Yes. A playable game with the rules in a plain module and the loop and input wired in the framework of your choice.