DEV Community

Cover image for Building a Simple Snake Game Using HTML, CSS, and JavaScript
Kato
Kato

Posted on

Building a Simple Snake Game Using HTML, CSS, and JavaScript

Setting Up the Project
First, you’ll need three key files:

index.html — the structure of the game.
style.css — the visual styling.
script.js — the game logic.

To create a simple Snake Game using HTML, CSS, and JavaScript, you can follow this step-by-step guide. Here, I'll walk you through each file, explain how each element works, and help you build the game from scratch.

Step 1: HTML - Creating the Game Layout
We start by setting up the structure of the game using HTML. Here's the basic structure of the index.html file:



<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Snake Game</title>
</head>
<body>
    <div class="container">
        <div class="wrapper">
            <div class="game-details">
                <span class="score">Score: 0</span>
                <button class="reset-btn">Restart</button>
                <span class="high-score">High Score: 0</span>
            </div>
            <div class="play-board"></div>
            <div class="controls">
                <i class="arrow left">←</i>
                <i class="arrow up">↑</i>
                <i class="arrow down">↓</i>
                <i class="arrow right">→</i>
            </div>
        </div>
        <div class="instructions-wrapper">
            <p>Instructions:</p>
            <ul>
                <li>Use the arrow keys to move the snake.</li>
                <li>Eat the red food to grow your snake.</li>
                <li>Avoid colliding with the walls and the snake's body.</li>
            </ul>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>



Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The game details section displays the current score, a reset button, and the high score.
  • The play-board is the area where the snake will move around.
  • The controls are visual indicators for arrow keys, which you can use to control the snake.
  • Below that, we have a simple instruction list.

Step 2: CSS - Styling the Game
In the style.css file, we define the styles for the game layout. Here’s how to design the game board and other elements:



* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body, html {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Arial', sans-serif;
}

.container {
  width: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.play-board {
  width: 400px;
  height: 400px;
  border: 2px solid black;
  background-color: #f0f0f0;
  position: relative;
  overflow: hidden;
}

.game-details {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.score, .high-score {
  font-size: 20px;
}

.controls {
  display: flex;
  justify-content: space-between;
  width: 200px;
  margin-top: 20px;
}

.controls i {
  font-size: 30px;
  cursor: pointer;
}

.instructions-wrapper {
  margin-top: 20px;
  text-align: center;
}

.reset-btn {
  cursor: pointer;
}



Enter fullscreen mode Exit fullscreen mode

Explanation:

  • We center the entire layout using Flexbox in the body and html elements.
  • The play-board is a 400x400px box where the snake will move.
  • Basic styling is provided for the score, controls, and reset button.

After completing the HTML and CSS sections, your game layout should look something like this:

Snake Game Basics

At this stage, you’ll see the basic game structure including:

The score display at the top.
The play board where the snake will move around.
The restart button and high score display.
The arrow icons representing the controls.

Step 3: JavaScript - Building the Snake Logic
Now, let's add the JavaScript to make the game functional. Here’s the script.js file:



const playBoard = document.querySelector('.play-board');
const scoreElement = document.querySelector('.score');
const highScoreElement = document.querySelector('.high-score');
const resetBtn = document.querySelector('.reset-btn');
const controls = document.querySelectorAll('.controls i');

let snakeX = 10, snakeY = 10;
let velocityX = 0, velocityY = 0;
let snakeBody = [];
let foodX, foodY;
let score = 0;
let highScore = localStorage.getItem('high-score') || 0;

highScoreElement.innerText = `High Score: ${highScore}`;

const changeFoodPosition = () => {
    foodX = Math.floor(Math.random() * 40) * 10;
    foodY = Math.floor(Math.random() * 40) * 10;
}

const handleGameOver = () => {
    alert("Game Over! Press OK to restart...");
    location.reload();
}

const changeDirection = (e) => {
    if (e.key === "ArrowUp" && velocityY != 1) {
        velocityX = 0;
        velocityY = -1;
    } else if (e.key === "ArrowDown" && velocityY != -1) {
        velocityX = 0;
        velocityY = 1;
    } else if (e.key === "ArrowLeft" && velocityX != 1) {
        velocityX = -1;
        velocityY = 0;
    } else if (e.key === "ArrowRight" && velocityX != -1) {
        velocityX = 1;
        velocityY = 0;
    }
}

const initGame = () => {
    snakeX += velocityX * 10;
    snakeY += velocityY * 10;

    if (snakeX < 0 || snakeX >= 400 || snakeY < 0 || snakeY >= 400) {
        return handleGameOver();
    }

    playBoard.innerHTML = `<div class="food" style="grid-area: ${foodY / 10 + 1} / ${foodX / 10 + 1};"></div>`;
    snakeBody.push([snakeX, snakeY]);

    if (snakeX === foodX && snakeY === foodY) {
        changeFoodPosition();
        score++;
        scoreElement.innerText = `Score: ${score}`;
        if (score > highScore) {
            highScore = score;
            localStorage.setItem('high-score', highScore);
            highScoreElement.innerText = `High Score: ${highScore}`;
        }
    } else {
        snakeBody.shift();
    }

    for (let i = 0; i < snakeBody.length; i++) {
        playBoard.innerHTML += `<div class="snake" style="left: ${snakeBody[i][0]}px; top: ${snakeBody[i][1]}px;"></div>`;
        if (i !== snakeBody.length - 1 && snakeBody[i][0] === snakeX && snakeBody[i][1] === snakeY) {
            return handleGameOver();
        }
    }
}

changeFoodPosition();
setInterval(initGame, 100);
document.addEventListener('keydown', changeDirection);


Enter fullscreen mode Exit fullscreen mode

Explanation:

  • The food is randomly positioned on the game board, and the snake moves according to the arrow keys.
  • Collision detection ensures the game ends if the snake hits a wall or its body.
  • The score increases when the snake eats food, and the high score is saved using localStorage.

Once you have added the JavaScript logic, the Snake Game will become interactive and playable! After implementing the JavaScript (explained in the previous section), your game will look something like this:

Snake Game Complete

At this point:

The snake will be visible on the game board and will start moving in the direction of the arrow keys.
The score will increase as the snake eats the food, and the high score will be updated.
The game will end if the snake hits the walls or itself, prompting a game-over alert and a reset option.

Conclusion:
This simple Snake Game is now fully functional using HTML, CSS, and JavaScript. You can improve it further by adding new features like different levels, mobile support, or improved graphics. The project is hosted on GitHub and can be customized as you wish.

You can access the complete source code here: Snake Game GitHub Repo.

Demo Snake Game

Top comments (0)