Snake Game in JavaScript
Move a snake in JavaScript on a canvas grid using timed ticks and queued arrow keys. Place food in free cells; wall or body collisions end the game.
Save this as index.html and open it in a browser.
1<!doctype html>2<html lang="en">3<meta charset="utf-8">4<title>JavaScript practice</title>5<body>6<p>Click Start, then use arrow keys. Eat the red food. Avoid walls and your body.</p><button id="start">Start / Restart</button><canvas id="game" width="200" height="200" tabindex="0" aria-label="Snake game area"></canvas><p id="status">Ready</p>7<script>8const canvas = document.querySelector('#game');9const ctx = canvas.getContext('2d');10const status = document.querySelector('#status');11let body, direction, queued, food, timer = null, score;12function placeFood() {13 const free = [];14 for (let y = 0; y < 10; y++) for (let x = 0; x < 10; x++) {15 if (!body.some(part => part.x === x && part.y === y)) free.push({x, y});16 }17 return free.length ? free[Math.floor(Math.random() * free.length)] : null;18}19function draw() {20 ctx.clearRect(0, 0, 200, 200);21 ctx.fillStyle = 'green'; body.forEach(part => ctx.fillRect(part.x * 20, part.y * 20, 18, 18));22 if (food) { ctx.fillStyle = 'red'; ctx.fillRect(food.x * 20, food.y * 20, 18, 18); }23}24function end(message) { clearInterval(timer); timer = null; status.textContent = message + ' Score: ' + score; }25function tick() {26 direction = queued;27 const head = { x: body[0].x + direction.x, y: body[0].y + direction.y };28 const eating = head.x === food.x && head.y === food.y;29 // The old tail moves away unless this step eats food.30 const occupied = eating ? body : body.slice(0, -1);31 if (head.x < 0 || head.x >= 10 || head.y < 0 || head.y >= 10 || occupied.some(part => part.x === head.x && part.y === head.y)) { end('Game over.'); return; }32 body.unshift(head);33 if (eating) { score++; food = placeFood(); }34 else body.pop();35 draw();36 if (!food) end('You filled the board!');37 else status.textContent = 'Score: ' + score;38}39canvas.onkeydown = event => {40 if (timer === null) return;41 const moves = { ArrowUp: {x:0,y:-1}, ArrowDown: {x:0,y:1}, ArrowLeft: {x:-1,y:0}, ArrowRight: {x:1,y:0} };42 const next = moves[event.key];43 if (!next) return;44 event.preventDefault();45 if (next.x !== -direction.x || next.y !== -direction.y) queued = next;46};47document.querySelector('#start').onclick = () => {48 if (!ctx) { status.textContent = 'Canvas not supported.'; return; }49 clearInterval(timer);50 body = [{x:4,y:5},{x:3,y:5},{x:2,y:5}]; direction = queued = {x:1,y:0}; score = 0;51 food = placeFood(); draw(); status.textContent = 'Score: 0'; canvas.focus(); timer = setInterval(tick, 160);52};53</script>54</body>55</html>
Sample Output
Score: 1
Eating one red square increases the score and preserves the tail to grow the body.
Game over. Score: ...
The proposed head hit a boundary or an occupied body square. The interval stops.
In this one
- Represent a moving body as grid positions
- Grow only when eating food
- Check walls and body collisions
- Handle keyboard direction changes safely
How it works
- 1
Click Start to initialize the body, direction, food, and score.
- 2
Focus the canvas so arrow keys control this game.
- 3
On each tick, calculate the next head and whether it reaches food.
- 4
Reject collisions, then insert the head and remove the tail unless eating.
- 5
Draw the new board and show the score; random food means each run differs.
Edge cases
Immediate reversal
Turning directly into the current body direction is not allowed.
Compare a proposed turn with the active direction. Multiple key presses before a tick must not bypass that rule.
No free square
A full board has nowhere to place food.
Build a list of free squares and return null when empty. End with a win rather than retrying random positions forever.
What's going on
Snake is a game where a moving line grows when its head reaches food. The player must avoid walls and the snake's own body. This complete browser example uses a ten-by-ten grid so the movement and collision rules are easy to inspect.
The body array stores grid positions, with the head first. Each tick creates a new head in the chosen direction. If food is reached, the tail stays and the score increases; otherwise the tail is removed. Canvas turns each grid position into a small colored rectangle. A canvas is a rectangular drawing area on the page.
Keyboard input queues a direction for the next tick. The reversal check compares with the direction of the current tick, preventing an instant turn back into the body. Collision checking leaves out the departing tail on a non-growing step, because moving into that newly empty square is legal. Food is chosen only from unoccupied squares. Filling the board ends in a win instead of trapping food placement in an endless retry loop.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What makes the snake grow?
Pick an answer to check it.
Question 2
Where can new food appear?
Pick an answer to check it.
Questions people ask
Why remove the tail on normal movement?
Adding a head and removing a tail moves the snake while keeping its length unchanged.
Why can the head enter the old tail square?
On a non-growing step the tail leaves that square at the same time. The collision check excludes it.
Why must I click Start first?
It creates the game state and focuses the canvas so arrow keys go to the game. This version is keyboard-only.