Build the Classic Snake Game

Build the Classic Snake Game in JavaScript – Step by Step

Classic games are a great way to learn programming. In this tutorial, we’ll build the iconic Snake game using pure HTML, CSS, and JavaScript. No libraries, no frameworks – just raw JavaScript logic. Let’s break it down!

🧩 Step 1: Setup the HTML Canvas

We'll use a simple HTML <canvas> element where the game will render.

<!DOCTYPE html>
<html>
<head>
  <title>Snake Game</title>
  <style>
    canvas {
      background: #111;
      display: block;
      margin: 0 auto;
      border: 2px solid #444;
    }
  </style>
</head>
<body>

  <canvas id="game" width="400" height="400"></canvas>

🧠 Step 2: Define the Game State

In JavaScript, we define the snake, food, direction, and game loop speed.

<script>
const canvas = document.getElementById("game");
const ctx = canvas.getContext("2d");

const grid = 20;
let count = 0;

let snake = {
  x: 160,
  y: 160,
  dx: grid,
  dy: 0,
  cells: [],
  maxCells: 4
};

let food = {
  x: 320,
  y: 320
};

🎮 Step 3: Game Loop and Movement

Now we update the snake's position, draw it, and detect collisions.

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function loop() {
  requestAnimationFrame(loop);

  if (++count < 4) return;
  count = 0;

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  snake.x += snake.dx;
  snake.y += snake.dy;

  if (snake.x < 0) snake.x = canvas.width - grid;
  if (snake.x >= canvas.width) snake.x = 0;
  if (snake.y < 0) snake.y = canvas.height - grid;
  if (snake.y >= canvas.height) snake.y = 0;

  snake.cells.unshift({x: snake.x, y: snake.y});

  if (snake.cells.length > snake.maxCells) {
    snake.cells.pop();
  }

  ctx.fillStyle = "red";
  ctx.fillRect(food.x, food.y, grid - 1, grid - 1);

  ctx.fillStyle = "lime";
  snake.cells.forEach(function(cell, index) {
    ctx.fillRect(cell.x, cell.y, grid - 1, grid - 1);

    if (cell.x === food.x && cell.y === food.y) {
      snake.maxCells++;
      food.x = getRandomInt(0, 20) * grid;
      food.y = getRandomInt(0, 20) * grid;
    }

    for (let i = index + 1; i < snake.cells.length; i++) {
      if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
        snake.x = 160;
        snake.y = 160;
        snake.cells = [];
        snake.maxCells = 4;
        snake.dx = grid;
        snake.dy = 0;

        food.x = getRandomInt(0, 20) * grid;
        food.y = getRandomInt(0, 20) * grid;
      }
    }
  });
}

⌨️ Step 4: Control the Snake

We’ll use the arrow keys to control the snake’s direction.

document.addEventListener("keydown", function(e) {
  if (e.key === "ArrowLeft" && snake.dx === 0) {
    snake.dx = -grid;
    snake.dy = 0;
  } else if (e.key === "ArrowUp" && snake.dy === 0) {
    snake.dy = -grid;
    snake.dx = 0;
  } else if (e.key === "ArrowRight" && snake.dx === 0) {
    snake.dx = grid;
    snake.dy = 0;
  } else if (e.key === "ArrowDown" && snake.dy === 0) {
    snake.dy = grid;
    snake.dx = 0;
  }
});

requestAnimationFrame(loop);
</script>
</body>
</html>

📌 Final Result

You now have a working Snake game built entirely with vanilla JavaScript!

▶️ Try It Online:

You can copy and paste the full code into this online editor to run it instantly:

Just paste everything into the HTML tab, and click “Run”!

Comments

Popular posts from this blog

Do You Really Need Advanced Algorithms to Be a Great Developer in 2025?

Advanced Chrome Dino Game (HTML + JS + Sprites)

Boost Productivity Using AI and REST APIs