How to Build a JavaScript Snake Game

JavaScript Snake game in progress

The classic Snake game is a timeless favorite, and building it using JavaScript is a perfect way to hone your programming skills. This guide will lead you through creating a JavaScript Snake game, from setting up your environment to implementing movement, growth, and scoring logic. Let’s dive into the essentials and start coding your game!

What are the basics of a JavaScript Snake game?

The JavaScript Snake game involves controlling a continuously moving snake across a grid-like environment. The primary objectives are to grow the snake by eating food and avoid colliding with the walls or itself. The game ends when the snake collides with these obstacles, with the player’s score determined by the number of food items consumed.

How do you set up the game environment?

To create the game environment, start by setting up an HTML5 canvas element where the game will render. You will need to define the canvas dimensions and use CSS to style it as needed. Here’s a basic example:


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

In your JavaScript file, grab a reference to the canvas and set up the 2D drawing context:


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

Set a game loop to update the game state at regular intervals, typically using `setInterval` or `requestAnimationFrame` for smoother animations.

How can you code the Snake’s movement and growth?

Begin by defining the snake’s initial position and direction. You’ll represent the snake as an array of coordinates, with each segment of the snake stored as an object:


let snake = [{ x: 200, y: 200 }];
let direction = 'RIGHT';

Implement a function to change the snake’s direction based on user input, typically captured through keyboard events:


document.addEventListener('keydown', changeDirection);

function changeDirection(event) {
    const LEFT_KEY = 37;
    const RIGHT_KEY = 39;
    const UP_KEY = 38;
    const DOWN_KEY = 40;

    const keyPressed = event.keyCode;
    if (keyPressed === LEFT_KEY && direction !== 'RIGHT') {
        direction = 'LEFT';
    }
    if (keyPressed === UP_KEY && direction !== 'DOWN') {
        direction = 'UP';
    }
    if (keyPressed === RIGHT_KEY && direction !== 'LEFT') {
        direction = 'RIGHT';
    }
    if (keyPressed === DOWN_KEY && direction !== 'UP') {
        direction = 'DOWN';
    }
}

Update the snake’s position based on the current direction, and implement logic to grow the snake when it eats food:


function moveSnake() {
    const head = { x: snake[0].x, y: snake[0].y };

    if (direction === 'RIGHT') head.x += 20;
    if (direction === 'LEFT') head.x -= 20;
    if (direction === 'UP') head.y -= 20;
    if (direction === 'DOWN') head.y += 20;

    snake.unshift(head);

    // Assume food is eaten
    const hasEatenFood = head.x === food.x && head.y === food.y;
    if (hasEatenFood) {
        // Increase score
    } else {
        snake.pop();
    }
}

How do you add game logic and scoring?

Implement collision detection to end the game if the snake collides with the walls or itself:


function checkCollision() {
    for (let i = 4; i < snake.length; i++) {
        const hasCollided = snake[i].x === snake[0].x && snake[i].y === snake[0].y;
        if (hasCollided) return true;
    }

    const hitLeftWall = snake[0].x < 0;
    const hitRightWall = snake[0].x > canvas.width - 20;
    const hitToptWall = snake[0].y < 0;
    const hitBottomWall = snake[0].y > canvas.height - 20;

    return hitLeftWall || hitRightWall || hitToptWall || hitBottomWall;
}

For scoring, maintain a score variable and update it when the snake consumes food:


let score = 0;

function updateScore() {
    score += 10;
    document.getElementById('score').innerText = score;
}

With these components in place, you now have a basic JavaScript Snake game. Expand further by adding features like levels, increasing speed, or sound effects.