React Snake Game (Grid + Food + Collision)
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 committed direction and the nullable one-turn buffer in synchronous refs. Key events can arrive before React commits state, so every handler must see an already-occupied buffer immediately; clear it when the 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, food, score, and run state in React state, but keep committed direction and the nullable input buffer in synchronously updated refs. That makes a second keydown observe the first buffered turn even before React commits a render. Tick with setInterval, prepend the next head, and pop the tail unless food is eaten. Treat a full board as a win: food becomes null, the loop stops, and no food cell renders.
Solution
Overview
Keep snake coordinates, food, score, and run state in React state, but keep committed direction and the nullable input buffer in synchronously updated refs. That makes a second keydown observe the first buffered turn even before React commits a render. Tick with setInterval, prepend the next head, and pop the tail unless food is eaten. Treat a full board as a win: food becomes null, the loop stops, and no food cell renders.
Single-component game loop with immutable snake updates
On each keydown, synchronously update refs so later events in the same React batch see whether the one-turn buffer is occupied. On each tick, commit that buffered turn or keep the current direction, then clear the buffer before computing the next head. Validate collisions before mutating state. If food is eaten, keep the tail and choose a free cell; if none remains, stop with a win and no food.
Files
{
"name": "react-snake-game-solution",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "18.x",
"react-dom": "18.x",
"react-scripts": "5.0.1"
},
"scripts": { "start": "react-scripts start" }
}
{
"compilerOptions": {
"jsx": "react-jsx",
"target": "ES2020",
"module": "ESNext",
"strict": true
}
}
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>React SDK • Snake Game (solution)</title></head><body><div id="root"></div></body></html>:root {
color-scheme: dark;
}
html, body {
margin: 0;
height: 100%;
background: #0a0a0a;
}
body {
font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
}
.page {
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
background: #0a0a0a;
color: #e5e7eb;
}
.card {
width: min(680px, 100%);
background: #0b1020;
border: 1px solid #1f2937;
border-radius: 14px;
padding: 18px;
display: grid;
gap: 14px;
}
h1 {
margin: 0;
font-size: 22px;
font-weight: 800;
}
.subtitle {
margin: 0;
color: #9ca3af;
font-size: 13px;
}
.statusRow {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.pill {
border: 1px solid #334155;
border-radius: 999px;
padding: 6px 10px;
font-size: 12px;
color: #d1d5db;
background: #0a0f1e;
}
.pill--danger {
border-color: #7f1d1d;
color: #fecaca;
background: rgba(127, 29, 29, 0.25);
}
.actions {
display: flex;
gap: 10px;
}
.ghost {
background: transparent;
color: #e5e7eb;
border: 1px solid #374151;
border-radius: 12px;
padding: 10px 14px;
font-weight: 700;
cursor: pointer;
}
.ghost:hover {
border-color: #60a5fa;
}
.board {
width: min(560px, 100%);
display: grid;
gap: 4px;
border-radius: 12px;
background: #0a0f1e;
border: 1px solid #334155;
padding: 8px;
}
.cell {
aspect-ratio: 1 / 1;
border-radius: 4px;
background: #111827;
}
.cell--snake {
background: #2563eb;
}
.cell--head {
background: #93c5fd;
}
.cell--food {
background: #f43f5e;
}
.hint {
margin: 0;
color: #94a3b8;
font-size: 12px;
}
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import './App.css';
import {
bufferTurn,
placeFood,
stepSnake,
type Direction,
type Point,
type SnakeSnapshot
} from './snake-engine';
const BOARD_SIZE = 14;
const STEP_MS = 140;
const INITIAL_SNAKE: Point[] = [
{ x: 6, y: 7 }, { x: 5, y: 7 }, { x: 4, y: 7 }
];
type GameState = SnakeSnapshot & {
isRunning: boolean;
terminal: 'none' | 'lost' | 'won';
};
function pointKey(point: Point): string {
return point.x + ',' + point.y;
}
function directionFromKey(key: string): Direction | null {
if (key === 'arrowup' || key === 'w') return 'UP';
if (key === 'arrowdown' || key === 's') return 'DOWN';
if (key === 'arrowleft' || key === 'a') return 'LEFT';
if (key === 'arrowright' || key === 'd') return 'RIGHT';
return null;
}
function initialGame(): GameState {
const snake = INITIAL_SNAKE.map((point) => ({ ...point }));
return {
snake,
direction: 'RIGHT',
bufferedDirection: null,
food: placeFood(snake, BOARD_SIZE),
score: 0,
isRunning: false,
terminal: 'none'
};
}
export default function App() {
const gameRef = useRef<GameState>(initialGame());
const [game, setGame] = useState<GameState>(gameRef.current);
const commit = useCallback((next: GameState) => {
gameRef.current = next;
setGame(next);
}, []);
const resetGame = useCallback(() => commit(initialGame()), [commit]);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
const key = String(event.key || '').toLowerCase();
const current = gameRef.current;
if (key === ' ') {
event.preventDefault();
if (current.terminal === 'none') commit({ ...current, isRunning: !current.isRunning });
return;
}
if (key === 'enter' && current.terminal !== 'none') {
event.preventDefault();
resetGame();
return;
}
const requested = directionFromKey(key);
if (!requested) return;
event.preventDefault();
const bufferedDirection = bufferTurn(
current.direction,
current.bufferedDirection,
requested
);
if (bufferedDirection !== current.bufferedDirection) {
commit({ ...current, bufferedDirection });
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [commit, resetGame]);
useEffect(() => {
if (!game.isRunning || game.terminal !== 'none') return undefined;
const timerId = window.setInterval(() => {
const current = gameRef.current;
if (!current.isRunning || current.terminal !== 'none') return;
const result = stepSnake(current, BOARD_SIZE);
const terminal = result.outcome === 'lost'
? 'lost'
: result.outcome === 'won'
? 'won'
: 'none';
commit({
snake: result.snake,
direction: result.direction,
bufferedDirection: result.bufferedDirection,
food: result.food,
score: result.score,
terminal,
isRunning: terminal === 'none'
});
}, STEP_MS);
return () => window.clearInterval(timerId);
}, [game.isRunning, game.terminal, commit]);
const snakeSet = useMemo(() => new Set(game.snake.map(pointKey)), [game.snake]);
const foodKey = game.food === null ? null : pointKey(game.food);
const status = game.terminal === 'won'
? 'You win'
: game.terminal === 'lost'
? 'Game over'
: game.isRunning ? 'Running' : 'Paused';
return (
<main className="page">
<section className="card">
<h1>Snake (Grid + Collision)</h1>
<p className="subtitle">Build a keyboard-controlled snake game with safe buffered turns and an explicit full-board win.</p>
<div className="statusRow">
<span className="pill">Score: {game.score}</span>
<span className="pill">Length: {game.snake.length}</span>
<span className={game.terminal === 'lost' ? 'pill pill--danger' : 'pill'}>{status}</span>
</div>
<div className="actions">
<button type="button" className="ghost" onClick={() => {
const current = gameRef.current;
if (current.terminal === 'none') commit({ ...current, isRunning: !current.isRunning });
}}>{game.isRunning ? 'Pause' : 'Start'}</button>
<button type="button" className="ghost" onClick={resetGame}>Reset</button>
</div>
<div className="board" role="grid" aria-label="snake board" style={{ gridTemplateColumns: 'repeat(' + BOARD_SIZE + ', minmax(0, 1fr))' }}>
{Array.from({ length: BOARD_SIZE * BOARD_SIZE }, (_, index) => {
const x = index % BOARD_SIZE;
const y = Math.floor(index / BOARD_SIZE);
const key = x + ',' + y;
const isHead = game.snake[0]?.x === x && game.snake[0]?.y === y;
const isBody = snakeSet.has(key);
const isFood = key === foodKey;
return <div key={key} className={['cell', isBody ? 'cell--snake' : '', isHead ? 'cell--head' : '', isFood ? 'cell--food' : ''].join(' ').trim()} aria-label={isHead ? 'snake head' : isFood ? 'food' : 'empty cell'} />;
})}
</div>
<p className="hint">Use Arrow keys or WASD to move. Space pauses, Enter resets after game over or a win.</p>
</section>
</main>
);
}
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
createRoot(document.getElementById('root')!).render(<App />);
export type Direction = 'UP' | 'DOWN' | 'LEFT' | 'RIGHT';
export type Point = { x: number; y: number };
export interface SnakeSnapshot {
snake: Point[];
direction: Direction;
bufferedDirection: Direction | null;
food: Point | null;
score: number;
}
export interface SnakeStep extends SnakeSnapshot {
outcome: 'moved' | 'lost' | 'won';
}
const DELTA: Record<Direction, Point> = {
UP: { x: 0, y: -1 },
DOWN: { x: 0, y: 1 },
LEFT: { x: -1, y: 0 },
RIGHT: { x: 1, y: 0 }
};
const OPPOSITE: Record<Direction, Direction> = {
UP: 'DOWN',
DOWN: 'UP',
LEFT: 'RIGHT',
RIGHT: 'LEFT'
};
function key(point: Point): string {
return String(point.x) + ',' + String(point.y);
}
export function bufferTurn(
committed: Direction,
buffered: Direction | null,
requested: Direction
): Direction | null {
if (buffered !== null) return buffered;
if (requested === committed || OPPOSITE[committed] === requested) return null;
return requested;
}
export function placeFood(
snake: Point[],
boardSize: number,
random: () => number = Math.random
): Point | null {
const occupied = new Set(snake.map(key));
const free: Point[] = [];
for (let y = 0; y < boardSize; y += 1) {
for (let x = 0; x < boardSize; x += 1) {
const point = { x, y };
if (!occupied.has(key(point))) free.push(point);
}
}
if (free.length === 0) return null;
const index = Math.min(free.length - 1, Math.floor(random() * free.length));
return free[index];
}
export function stepSnake(
state: SnakeSnapshot,
boardSize: number,
random: () => number = Math.random
): SnakeStep {
const direction = state.bufferedDirection ?? state.direction;
const delta = DELTA[direction];
const head = state.snake[0];
const nextHead = { x: head.x + delta.x, y: head.y + delta.y };
const base = { ...state, direction, bufferedDirection: null };
if (
nextHead.x < 0 ||
nextHead.y < 0 ||
nextHead.x >= boardSize ||
nextHead.y >= boardSize
) {
return { ...base, outcome: 'lost' };
}
const ateFood = state.food !== null && key(nextHead) === key(state.food);
const collisionBody = ateFood ? state.snake : state.snake.slice(0, -1);
if (collisionBody.some((part) => key(part) === key(nextHead))) {
return { ...base, outcome: 'lost' };
}
const snake = [nextHead, ...state.snake];
if (!ateFood) {
snake.pop();
return { ...base, snake, outcome: 'moved' };
}
const food = placeFood(snake, boardSize, random);
return {
...base,
snake,
food,
score: state.score + 1,
outcome: food === null ? 'won' : 'moved'
};
}
Notes & Pitfalls
Validating each key against the previous key allows RIGHT → UP → LEFT to reverse before the tick commits; keep only the first valid turn. Forgetting interval cleanup leads to duplicate timers and speed glitches. Spawning food without excluding the snake—or inventing a fallback cell on a full board—can overlap the snake.
Occupancy keys like x,yfor constant-time lookups.Synchronous refs for committed direction and the one-turn input buffer. Deterministic state transitions inside interval callback.
Similar questions
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.