Vue 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 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.
Solution
Overview
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.
Single Vue component with deterministic game-loop state
On each keydown, accept only the first valid perpendicular turn into a nullable buffer and validate it against the committed direction. On the tick, commit and clear that buffer before computing the next head. If food is eaten, keep the tail and choose a free cell; when no cell remains, set food to null, stop the loop, and show a win. Otherwise remove the tail for standard movement.
Files
{"name":"vue-snake-game-solution","version":"0.1.0","private":true,"dependencies":{"vue":"3.x"},"scripts":{"serve":"vue-cli-service serve"}}
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"allowJs": true
}
}
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vue SDK • Snake Game (solution)</title></head><body><div id="app"></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(700px,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;
}
.status-row {
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,.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;
}
<template>
<main class="page">
<section class="card">
<h1>Snake (Grid + Collision)</h1>
<p class="subtitle">Build a keyboard-controlled snake game with safe buffered turns and an explicit full-board win.</p>
<div class="status-row">
<span class="pill">Score: {{ score }}</span>
<span class="pill">Length: {{ snake.length }}</span>
<span class="pill" :class="{ 'pill--danger': isGameOver }">{{ statusLabel }}</span>
</div>
<div class="actions">
<button class="ghost" type="button" @click="toggleRunning">{{ isRunning ? 'Pause' : 'Start' }}</button>
<button class="ghost" type="button" @click="resetGame">Reset</button>
</div>
<div class="board" role="grid" aria-label="snake board" :style="{ gridTemplateColumns: 'repeat(' + BOARD_SIZE + ', minmax(0, 1fr))' }">
<template v-for="row in rows" :key="'row-' + row">
<div v-for="col in cols" :key="cellKey(col, row)" class="cell" :class="{
'cell--snake': isSnake(col, row),
'cell--head': isHead(col, row),
'cell--food': isFood(col, row)
}" :aria-label="isHead(col, row) ? 'snake head' : (isFood(col, row) ? 'food' : 'empty cell')"></div>
</template>
</div>
<p class="hint">Use Arrow keys or WASD to move. Space pauses, Enter resets after game over or a win.</p>
</section>
</main>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import { bufferTurn, placeFood, stepSnake, type Direction, type Point } 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 }
];
const snake = ref<Point[]>(INITIAL_SNAKE.map((point) => ({ ...point })));
const direction = ref<Direction>('RIGHT');
const bufferedDirection = ref<Direction | null>(null);
const food = ref<Point | null>(placeFood(snake.value, BOARD_SIZE));
const isRunning = ref(false);
const isGameOver = ref(false);
const isWon = ref(false);
const score = ref(0);
let timerId: number | null = null;
const rows = computed(() => Array.from({ length: BOARD_SIZE }, (_, index) => index));
const cols = computed(() => Array.from({ length: BOARD_SIZE }, (_, index) => index));
const snakeLookup = computed(() => new Set(snake.value.map((point) => cellKey(point.x, point.y))));
const statusLabel = computed(() => isWon.value ? 'You win' : isGameOver.value ? 'Game over' : isRunning.value ? 'Running' : 'Paused');
function cellKey(x: number, y: number): string { return String(x) + ',' + String(y); }
function isSnake(x: number, y: number): boolean { return snakeLookup.value.has(cellKey(x, y)); }
function isHead(x: number, y: number): boolean { return snake.value[0]?.x === x && snake.value[0]?.y === y; }
function isFood(x: number, y: number): boolean { return food.value !== null && food.value.x === x && food.value.y === y; }
function clearTimer(): void {
if (timerId !== null) {
clearInterval(timerId);
timerId = null;
}
}
function startLoop(): void {
if (timerId !== null || isGameOver.value || isWon.value) return;
timerId = window.setInterval(tick, STEP_MS);
}
function pauseLoop(): void { clearTimer(); isRunning.value = false; }
function resetGame(): void {
clearTimer();
snake.value = INITIAL_SNAKE.map((point) => ({ ...point }));
direction.value = 'RIGHT';
bufferedDirection.value = null;
food.value = placeFood(snake.value, BOARD_SIZE);
score.value = 0;
isRunning.value = false;
isGameOver.value = false;
isWon.value = false;
}
function tick(): void {
if (!isRunning.value || isGameOver.value || isWon.value) return;
const result = stepSnake({
snake: snake.value,
direction: direction.value,
bufferedDirection: bufferedDirection.value,
food: food.value,
score: score.value
}, BOARD_SIZE);
snake.value = result.snake;
direction.value = result.direction;
bufferedDirection.value = result.bufferedDirection;
food.value = result.food;
score.value = result.score;
if (result.outcome === 'lost') { isGameOver.value = true; pauseLoop(); }
else if (result.outcome === 'won') { isWon.value = true; pauseLoop(); }
}
function toggleRunning(): void {
if (isGameOver.value || isWon.value) return;
isRunning.value = !isRunning.value;
if (isRunning.value) startLoop(); else pauseLoop();
}
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 onKeydown(event: KeyboardEvent): void {
const key = String(event.key || '').toLowerCase();
if (key === ' ') {
event.preventDefault();
if (!isGameOver.value && !isWon.value) toggleRunning();
return;
}
if (key === 'enter' && (isGameOver.value || isWon.value)) {
event.preventDefault();
resetGame();
return;
}
const requested = directionFromKey(key);
if (!requested) return;
event.preventDefault();
bufferedDirection.value = bufferTurn(direction.value, bufferedDirection.value, requested);
}
onMounted(() => window.addEventListener('keydown', onKeydown));
onBeforeUnmount(() => { window.removeEventListener('keydown', onKeydown); clearTimer(); });
</script>
import 'zone.js';
import { createApp } from 'vue';
import App from './App.vue';
import './App.css';
createApp(App).mount('#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.One nullable buffered turn validated against committed direction. Deterministic tick flow with explicit collision branches.
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.