DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Snake Game with JavaScript

The Snake game is a classic for a reason: the rules fit in one sentence, but the code teaches you the canvas, the game loop, keyboard input, and collision detection. It is a perfect second or third JavaScript project.

What you are building

A snake moves around a grid on a canvas. Arrow keys steer it. Eating food makes it longer and adds points. Hitting a wall or its own body ends the game. A score display and a restart button finish it off.

Setting up the canvas

Use a canvas and split it into a grid of cells. A cell size of 20 pixels on a 400x400 canvas gives a 20x20 grid — big enough to be fun, small enough to manage:

<canvas id="game" width="400" height="400"></canvas>
<p>Score: <span id="score">0</span></p>
<button id="restart">Restart</button>
Enter fullscreen mode Exit fullscreen mode
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");
const box = 20;
let snake = [{ x: 9 * box, y: 10 * box }];
let direction = "RIGHT";
let food = randomFood();
let score = 0;
Enter fullscreen mode Exit fullscreen mode

The game loop

setInterval drives the game. Every tick, move the snake one cell in the current direction:

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the food
  ctx.fillStyle = "red";
  ctx.fillRect(food.x, food.y, box, box);

  // Draw the snake
  ctx.fillStyle = "green";
  snake.forEach((part) => ctx.fillRect(part.x, part.y, box, box));

  // Move the head
  let head = { ...snake[0] };
  if (direction === "LEFT") head.x -= box;
  if (direction === "RIGHT") head.x += box;
  if (direction === "UP") head.y -= box;
  if (direction === "DOWN") head.y += box;

  snake.unshift(head);

  // Eating food
  if (head.x === food.x && head.y === food.y) {
    score++;
    document.getElementById("score").textContent = score;
    food = randomFood();
  } else {
    snake.pop();
  }

  // Game over: wall or self collision
  if (
    head.x < 0 || head.x >= canvas.width ||
    head.y < 0 || head.y >= canvas.height ||
    snake.slice(1).some((part) => part.x === head.x && part.y === head.y)
  ) {
    clearInterval(game);
    alert("Game Over! Score: " + score);
  }
}

const game = setInterval(draw, 120);
Enter fullscreen mode Exit fullscreen mode

Steering without reversing

Never let the snake reverse into itself — block the opposite direction:

document.addEventListener("keydown", (event) => {
  if (event.key === "ArrowLeft" && direction !== "RIGHT") direction = "LEFT";
  if (event.key === "ArrowUp" && direction !== "DOWN") direction = "UP";
  if (event.key === "ArrowRight" && direction !== "LEFT") direction = "RIGHT";
  if (event.key === "ArrowDown" && direction !== "UP") direction = "DOWN";
});
Enter fullscreen mode Exit fullscreen mode

What to add next

Add a speed increase as the score grows, a high score saved in localStorage, touch buttons for mobile, or walls as obstacles. Each one is a small change to the loop above.

Top comments (0)