Skip to main content
🎮 Game Logic

What you're building

The game loop of Snake, distilled to a single pure function: one tick of movement.

You will implement a SnakeGame class with:

  • constructor(rows, cols, startPos) — initialise the snake at startPos ([row,col]), facing "right", on a rows×cols grid. Place the first food randomly (not on the snake).
  • changeDirection(dir) — change heading to "up", "down", "left", or "right". Ignore reversal (can't go right while facing left).
  • step() — advance one tick. Returns "ate" (snake grew), "dead" (wall or self collision), or "ok" (normal move).

The snake is stored as an array of [row,col] segments, head first.

Requirements

  • On each step, compute the new head position based on current direction.
  • If new head is out of bounds or overlaps the snake body → "dead".
  • If new head is on food → grow (keep the tail, add new head), place new food not on the snake, return "ate".
  • Otherwise → normal move (add new head, remove tail), return "ok".
  • changeDirection must reject direct reversals: up↔down, left↔right.

Stretch goals

  • Expose getScore() (food eaten count).
  • Detect a "win" state (snake fills the entire grid).

What this proves

Queue-based body management, edge detection, and state-machine transitions — plus the ability to model a real-time game loop as pure, testable logic that's decoupled from any rendering layer.

⚡ 60 XP
solution.jsRuns in your browser
Loading editor…
Tests4 to pass
step moves snake right by default
step returns dead on wall collision
step returns ate and grows snake
changeDirection rejects reversal

Run your code to check these.