Building a Classic Snake Game with JavaScript: Code Walkthrough & Live Demo

 

Building a Classic Snake Game Using JavaScript

Introduction

The Snake game is a simple yet fun classic game that has been recreated in various programming languages. In this post, we will walk through a JavaScript implementation of the game using HTML5 Canvas. The game runs on a laptop and is controlled using arrow keys.

Note: This game is only playable on a laptop as it requires arrow key controls and does not support mobile touch interactions.

Live Demo

Click here to play the Snake Game (Replace with actual hosted link)

How the Game Works

  • The player controls a snake that moves on a grid.
  • The objective is to eat the red food blocks, which increase the snake's length and score.
  • The game ends if the snake collides with itself.
  • The snake wraps around the screen edges, meaning it appears on the opposite side if it moves beyond the boundary.

Screenshots

Initial State


Playing the Game



Game Over Screen

 (


Understanding the Code

The game is built using HTML, CSS, and JavaScript.

1. Setting Up the HTML Structure

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Snake Game</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            background-color: #000;
            color: #fff;
            margin: 0;
        }
        canvas {
            background-color: #222;
            border: 2px solid #fff;
        }
        .score {
            margin-top: 20px;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <canvas id="gameCanvas" width="400" height="400"></canvas>
    <div class="score">Score: <span id="scoreValue">0</span></div>

This structure defines the game canvas and a score display.

2. JavaScript Code Explanation

The game logic is written in JavaScript and runs when the page loads.

Initializing the Game Variables

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreValue = document.getElementById('scoreValue');

const gridSize = 20;
let snake = [{ x: 10 * gridSize, y: 10 * gridSize }];
let food = { x: 15 * gridSize, y: 15 * gridSize };
let dx = 1, dy = 0, score = 0;
let gameInterval;
let gameSpeed = 150;
  • gridSize defines the size of each movement step.
  • snake is an array storing the snake's body segments.
  • food holds the food position.
  • dx and dy determine movement direction.

Generating Random Food Position

function getRandomPosition() {
    return Math.floor(Math.random() * canvas.width / gridSize) * gridSize;
}
function generateFood() {
    food = { x: getRandomPosition(), y: getRandomPosition() };
}

This function ensures that food appears within the grid.

Drawing the Snake and Food

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = 'red';
    ctx.fillRect(food.x, food.y, gridSize, gridSize);
    ctx.fillStyle = 'green';
    snake.forEach(segment => {
        ctx.fillRect(segment.x, segment.y, gridSize, gridSize);
    });
}
  • Clears the previous frame.
  • Draws the food in red and the snake in green.

Updating the Snake’s Movement

function update() {
    let head = { x: snake[0].x + dx * gridSize, y: snake[0].y + dy * gridSize };
    
    if (head.x < 0) head.x = canvas.width - gridSize;
    else if (head.x >= canvas.width) head.x = 0;
    if (head.y < 0) head.y = canvas.height - gridSize;
    else if (head.y >= canvas.height) head.y = 0;
    
    for (let i = 1; i < snake.length; i++) {
        if (head.x === snake[i].x && head.y === snake[i].y) {
            gameOver();
            return;
        }
    }
    snake.unshift(head);
    
    if (head.x === food.x && head.y === food.y) {
        score++;
        scoreValue.textContent = score;
        generateFood();
    } else {
        snake.pop();
    }
}
  • Moves the snake by adding a new head.
  • Wraps the snake when it moves out of bounds.
  • Ends the game if the snake collides with itself.
  • If the snake eats food, the score increases and a new food piece is generated.

Handling Keyboard Input

function changeDirection(event) {
    switch (event.key) {
        case 'ArrowUp': if (dy !== 1) { dx = 0; dy = -1; } break;
        case 'ArrowDown': if (dy !== -1) { dx = 0; dy = 1; } break;
        case 'ArrowLeft': if (dx !== 1) { dx = -1; dy = 0; } break;
        case 'ArrowRight': if (dx !== -1) { dx = 1; dy = 0; } break;
    }
}

This function ensures that the snake does not reverse direction.

Conclusion

This simple Snake Game demonstrates fundamental JavaScript concepts such as event handling, game loops, and canvas drawing. Try modifying it to add new features like obstacles or increasing speed over time!

Reminder: This game is designed for laptops as it requires arrow key input and does not support touch controls.

Comments