Snake Game using Javascript | HTML and CSS Project

Hello, learner today In this blog post, We will be creating a Snake Game using Javascript.  In the past post, we have created many projects one of them is the Typing Test App. Without wasting time Now it is time to create a Snake Game.

Snake Game using Javascript | HTML and CSS Project

In this Snake game, the player controls a snake that moves in a left, right, up, or down direction, to consume randomly appearing food to grow longer. A continuous game loop manages the updating of the snake’s position and checks for collisions with walls or the snake’s own body. The player earns points for each food item consumed by the snake, and the game ends if the snake collides with a wall or its own body. The game displays a final score and a “Game Over” message when the player loses.

As you see in the below output of the source code. There is a snake that looks like a box-box you can control the snake by arrow buttons upside, downside, right side, and left side for the food. There is a red box that is the food for the snake after eating the food the snake grows by 1 box.

If you’re having difficulty understanding what I’m saying or what this Snake Game uses javascript then You can ask me in the comment.

Code ByCoding thai
Language UsedHTML, CSS and JS
ResponsiveYes
External Link / DependenciesNo

There are 3 types of styles to connect CSS with HTML files. Inline CSS, Internal CSS, External CSS. For Inline CSS in this, we have to write the CSS code inside the HTML code using style Attribute elements. For internal CSS we have to use the Style tag in the Head section on HTML File. We have used this Internal CSS in The below section. Last is External CSS for this we have to create another CSS File in the same folder this

Preview of Snake Game

In this preview, we have used internal CSS in the code. In the internal CSS, we have to write the code in the head section using the Style tag. We have to write the code in <Style> CSS code </style> in the Head section in the HTML file. This code is run in Codepen.io

See the Pen Snake Game using javascript by Coding thai (@Codingthai) on CodePen.

You might like this

Snake Game using javaScript [Source code]

For Creating A Snake Game using HTML, CSS, and JSFirst, you have to create Three files (HTML, CSS, and JS) files with the named index.html, style.css, and Script.js in the same folder and you have to link the CSS and JS files to HTML. after that paste the below code, the HTML code in index.html, and paste the CSS code in style.css Again paste the Js code in script.js that’s all after pasting the code.

First, you have to create an HTML file with the named index.html paste the below HTML code on it, and save it. Remember to give a .html extension to the HTML file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
    <link rel="stylesheet" href="style.css">
    <title>Snake Game | Coding Thia</title>
</head>
<body>
    <div class="wrapper">
        <div class="game-details">
            <span class="score">Score: 0</span>
            <span class="high-score">High Score: 0</span>
        </div>
        <div class="play-board"></div>
        <div class="controls">
            <i data-key="ArrowLeft" class="fa-solid fa-arrow-left-long"></i>
            <i data-key="ArrowUp" class="fa-solid fa-arrow-up-long"></i>
            <i data-key="ArrowRight" class="fa-solid fa-arrow-right-long"></i>
            <i data-key="ArrowDown" class="fa-solid fa-arrow-down-long"></i>
        </div>
    </div>
    <script src="index.js"></script>
</body>
</html>

After pasting the HTML code, Now have to create a second CSS file with the named style.css. Paste the below code on it and save it. Again remember to give a .css extension to the CSS file.

@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&display=swap');

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Open Sans', sans-serif;
}

body{
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    background: #e3f2fd;
}

.wrapper{
    width: 65vmin;
    height: 70vmin;
    display: flex;
    overflow: hidden;
    flex-direction: column;
    justify-content: center;
    background: #293447;
    border-radius: 5px;
    box-shadow: 0 20px 40px rgba(52, 87, 220, 0.2);
}

.game-details{
    color: #b8c6dc;
    font-weight: 500;
    font-size: 1.2rem;
    padding: 20px 27px;
    display: flex;
    justify-content: space-between;
}

.play-board{
    height: 100%;
    width: 100%;
    display: grid;
    background: #212837;
    grid-template: repeat(30, 1fr) / repeat(30, 1fr);
}

.play-board .food{
    background: #ff003d;
}

.play-board .head{
    background: #60cbff;
}

.controls{
    display: none;
    justify-content: space-between;
}

.controls i{
    padding: 25px 0;
    text-align: center;
    font-size: 1.3rem;
    color: #b8c6dc;
    width: calc(100% / 4);
    cursor: pointer;
    border-right: 1px solid #171b26;
}

@media screen and (max-width: 800px) {
    .wrapper{
        width: 90vmin;
        height: 115vmin;
    }

    .game-details{
        font-size: 1rem;
        padding: 15px 27px;
    }

    .controls{
        display: flex;
    }

    .controls i{
        padding: 15px 0;
        font-size: 1rem;
    }
}

After pasting the HTML and CSS code, Now have to create a third Javascript file with the named script.js. Paste the below code on it and save it. Again remember to give a .js extension to the javascript file.

const playBoard = document.querySelector(".play-board");
const scoreElement = document.querySelector(".score");
const highScoreElement = document.querySelector(".high-score");
const controls = document.querySelectorAll(".controls i");

let gameOver = false;
let foodX, foodY;
let snakeX = 5, snakeY = 5;
let velocityX = 0, velocityY = 0;
let snakeBody = [];
let setIntervalId;
let score = 0;

// Get high score from local storage

let highScore = localStorage.getItem("high-score") || 0;
highScoreElement.innerText = `High Score: ${highScore}`;

// Pass a random between 1 and 30 as food position

const updateFoodPosition = () => {
    foodX = Math.floor(Math.random() * 30) + 1;
    foodY = Math.floor(Math.random() * 30) + 1;
}

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

// Change velocity value based on key press

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;
    }
}

// Change Direction on each key click

controls.forEach(button => button.addEventListener("click", () => changeDirection({ key: button.dataset.key })));

const initGame = () => {
    if (gameOver) return handleGameOver();
    let html = `<div class="food" style="grid-area: ${foodY} / ${foodX}"></div>`;

    // When snake eat food
    if (snakeX === foodX && snakeY === foodY) {
        updateFoodPosition();
        snakeBody.push([foodY, foodX]); //Add food to snake body array
        score++;
        highScore = score >= highScore ? score : highScore; // if score > high score => high score = score

        localStorage.setItem("high-score", highScore);
        scoreElement.innerText = `Score: ${score}`;
        highScoreElement.innerText = `High Score: ${highScore}`;
    }

    // Update Snake Head
    snakeX += velocityX;
    snakeY += velocityY;

    // Shifthing forward values of elements in snake body by one

    for (let i = snakeBody.length - 1; i > 0; i--) {
        snakeBody[i] = snakeBody[i - 1];
    }

    snakeBody[0] = [snakeX, snakeY];

    // Check snake body is out of wall or no

    if (snakeX <= 0 || snakeX > 30 || snakeY <= 0 || snakeY > 30) {
        return gameOver = true;
    }

    // Add div for each part of snake body

    for (let i = 0; i < snakeBody.length; i++) {
        html += `<div class="head" style="grid-area: ${snakeBody[i][1]} / ${snakeBody[i][0]}"></div>`;
        // Check snake head hit body or no
        if (i !== 0 && snakeBody[0][1] === snakeBody[i][1] && snakeBody[0][0] === snakeBody[i][0]) {
            gameOver = true;
        }
    }
    playBoard.innerHTML = html;
}
updateFoodPosition();
setIntervalId = setInterval(initGame, 100);
document.addEventListener("keyup", changeDirection);

That’s all after pasting the code your code will be successfully run. If you get any kind of error/problem in the code just comment or contact me on social media

Written By@narendra-chand
Code By Coding thai
Code idea@AsmrProg

About the Author

Leave a Reply

Your email address will not be published. Required fields are marked *

You may also like these