Vue Snake Game (Grid + Food + Collision)

hard
By FrontendAtlas Editorial · Updated Nov 23, 2026
hard level
Vue 3 Composition API (ref/computed)Interval lifecycle managementKeyboard event handlingDeterministic state updates for moving/growing arrays
Build a Snake game in Vue 3 using a grid board. Support keyboard controls, food spawning, score updates, and game-over handling for wall/body collisions.

Requirements

  • Render a fixed-size board (for example 14×14) with snake body and food cells.
  • Move the snake using Arrow keys (optionally WASD).
  • Run game ticks on an interval while the game is running.
  • Eating food should grow the snake and increment score.
  • Colliding with walls or snake body should end the game.
  • Provide Start/Pause and Reset controls.
  • Expose score and current snake length in the UI.
  • Buffer at most one valid perpendicular turn per tick. Validate it against the committed movement direction; same/opposite inputs do not consume the buffer.
  • When the snake fills the board, render “You win”, stop movement, and render no food cell.

What the checks look for

The checks find elements by .cell, .cell--snake, .cell--food, text "Score: 0", text "Length: 3", text "Paused", button "Start", text "Running", button "Pause", body, text "Game over", text "Score: 1", text "Length: 4", .cell--food.cell--snake, button "Reset". Keep these in your markup.

Expected behavior

  • Initial state shows a short snake, one food cell, and score 0.
  • Press Start to begin movement; snake advances one cell per tick.
  • When head reaches food, score increases and snake length grows by 1.
  • RIGHT → UP → LEFT during one tick commits UP; only the first valid perpendicular turn is buffered.
  • Hitting boundary or own body stops the game and shows game-over state.
  • Reset returns to initial state with a new food position.
  • Filling the last free cell stops the timer, renders “You win”, and leaves no food cell.

Implementation notes

  • Store snake as ordered coordinates, with index 0 as the head.
  • Keep a nullable one-turn buffer separate from the committed direction; clear it immediately when the next tick commits.
  • Use Set/string keys for fast cell occupancy checks.
  • Generate food only on free cells that are not occupied by snake.
  • Clear interval correctly on pause, game over, and unmount.

Solution idea

Keep snake coordinates, direction, one nullable buffered turn, food, score, and run state in refs. Tick with setInterval, prepend next head, and pop tail unless food is eaten. End the game on wall/body collision. Treat a full board as a win: food becomes null, the loop stops, and no food cell renders.