Snake Game Using HTML , CSS And JavaScript With Source Code

Snake Game Using HTML , CSS And Javascript

Introduction :

Today we have made a wonderful snake game which is very amazing. To make this game we have used HTML CSS and JavaScript. Also the interesting thing is that this game is completely responsive which you can play on mobile, laptop and tablet. Can play different types of Davis and have fun

We have made this game very well, like we have added sound effects in this game, if a user gets out while playing, then he will hear the sound of out, you can see in this code below 👇👇

const foodSound = new Audio(‘music/food.mp3’);
const gameOverSound = new Audio(‘music/gameover.mp3’);
const moveSound = new Audio(‘music/move.mp3’);
const musicSound = new Audio(‘music/music.mp3’);

Also, friends, we have also added a score box in this game in which the user can check the score of his game.

let speed = 9;
let score = 0;
let lastPaintTime = 0;
let snakeArr = [
{x: 13, y: 15}
,

Friends, you will get the source code of this entire game below, but you will have to keep some things in mind, otherwise you may face problems in the code. 👇👇

Snake Game Step By Step Guide:-

Let’s start, first of all create a folder in your computer with the name of Snake Game, then open that folder in your vs code, then in this folder you will have to create three files in which the first will be the index.html file which will be the game. Will design the structure, then style.css and then the final file will be script.js which will work in playing the game.

We have used some sound effects in this game like if a user gets out in the game then he will hear out type sound in which the game is very good and it is a lot of fun to play the game.

In this game, we have used the keyboard arrows to control the snake, like if you want to move the snake up, you can use the keyboard up arrow, in this way you can control the snake by using the remaining arrows. Is

 

HTML (index.html)

				
					


    
    
    
    <title>SnakeMania - Developergtm</title>
    


    <div class="body">
        <div id="scoreBox">Score: 0</div>
        <div id="hiscoreBox">HiScore: 0</div>
        <div id="board"></div>
    </div>


 
				
			

CSS (Style.css)

				
					@import url('https://fonts.googleapis.com/css2?family=New+Tegomin&amp;display=swap');

* {
    padding: 0;
    margin: 0;
}

body {
    background-image: linear-gradient(45deg, #3e618f, #29a594);
}

.body {
    min-height: 100vh;
    background-size: 100vw 100vh;
    background-repeat: no-repeat;
    display: flex;
    justify-content: center;
    align-items: center;
}

#scoreBox {
    position: absolute;
    top: 9px;
    right: 200px;
    font-size: 39px;
    font-weight: bold;
    font-family: 'New Tegomin', serif;
    padding: 9px;
    color: red;
    background-color: black;
}

#hiscoreBox {
    position: absolute;
    top: 93px;
    right: 156px;
    font-size: 39px;
    font-weight: bold;
    font-family: 'New Tegomin', serif;
    padding: 9px;
    color: red;
    background-color: black;
}

#board {
    background-image: linear-gradient(45deg, #3e618f, #29a594);
    width: 90vmin;
    height: 92vmin;
    border: 2px solid black;
    display: grid;
    grid-template-rows: repeat(18, 1fr);
    grid-template-columns: repeat(18, 1fr);
}

.head {
    background: red;
    border: 2px solid rgb(34, 4, 34);
    transform: scale(1.02);
    border-radius: 50%;
}

.snake {
    background-color: purple;
    border: .25vmin solid white;
    border-radius: 12px;
}

.food {
    background: yellow;
    border: .25vmin solid black;
    border-radius: 8px;
}
				
			

Javascript (Script.js)

				
					// Game Constants &amp; Variables
let inputDir = {x: 0, y: 0}; 
const foodSound = new Audio('music/food.mp3');
const gameOverSound = new Audio('music/gameover.mp3');
const moveSound = new Audio('music/move.mp3');
const musicSound = new Audio('music/music.mp3');
let speed = 9;
let score = 0;
let lastPaintTime = 0;
let snakeArr = [
    {x: 13, y: 15}
];

food = {x: 6, y: 7};

// Game Functions
function main(ctime) {
    window.requestAnimationFrame(main);
    // console.log(ctime)
    if((ctime - lastPaintTime)/1000 &lt; 1/speed){
        return;
    }
    lastPaintTime = ctime;
    gameEngine();
}

function isCollide(snake) {
    // If you bump into yourself 
    for (let i = 1; i = 18 || snake[0].x = 18 || snake[0].y hiscoreval){
            hiscoreval = score;
            localStorage.setItem("hiscore", JSON.stringify(hiscoreval));
            hiscoreBox.innerHTML = "HiScore: " + hiscoreval;
        }
        scoreBox.innerHTML = "Score: " + score;
        snakeArr.unshift({x: snakeArr[0].x + inputDir.x, y: snakeArr[0].y + inputDir.y});
        let a = 2;
        let b = 16;
        food = {x: Math.round(a + (b-a)* Math.random()), y: Math.round(a + (b-a)* Math.random())}
    }

    // Moving the snake
    for (let i = snakeArr.length - 2; i&gt;=0; i--) { 
        snakeArr[i+1] = {...snakeArr[i]};
    }

    snakeArr[0].x += inputDir.x;
    snakeArr[0].y += inputDir.y;

    // Part 2: Display the snake and Food
    // Display the snake
    board.innerHTML = "";
    snakeArr.forEach((e, index)=&gt;{
        snakeElement = document.createElement('div');
        snakeElement.style.gridRowStart = e.y;
        snakeElement.style.gridColumnStart = e.x;

        if(index === 0){
            snakeElement.classList.add('head');
        }
        else{
            snakeElement.classList.add('snake');
        }
        board.appendChild(snakeElement);
    });
    // Display the food
    foodElement = document.createElement('div');
    foodElement.style.gridRowStart = food.y;
    foodElement.style.gridColumnStart = food.x;
    foodElement.classList.add('food')
    board.appendChild(foodElement);


}


// Main logic starts here
musicSound.play();
let hiscore = localStorage.getItem("hiscore");
if(hiscore === null){
    hiscoreval = 0;
    localStorage.setItem("hiscore", JSON.stringify(hiscoreval))
}
else{
    hiscoreval = JSON.parse(hiscore);
    hiscoreBox.innerHTML = "HiScore: " + hiscore;
}

window.requestAnimationFrame(main);
window.addEventListener('keydown', e =&gt;{
    inputDir = {x: 0, y: 1} // Start the game
    moveSound.play();
    switch (e.key) {
        case "ArrowUp":
            console.log("ArrowUp");
            inputDir.x = 0;
            inputDir.y = -1;
            break;

        case "ArrowDown":
            console.log("ArrowDown");
            inputDir.x = 0;
            inputDir.y = 1;
            break;

        case "ArrowLeft":
            console.log("ArrowLeft");
            inputDir.x = -1;
            inputDir.y = 0;
            break;

        case "ArrowRight":
            console.log("ArrowRight");
            inputDir.x = 1;
            inputDir.y = 0;
            break;
        default:
            break;
    }

});
				
			

Complain Management using Python with a Graphical User Interface (GUI) Introduction: The Complain Management using Python program designed to manage complaints effectively …

COVID 19 Hospital Management Using Python [Django Framework] Introduction: The COVID-19 Hospital Management is a Python-based application that tracks web applications for Hospitals. …

Drawing Ganesha Using Python Turtle Graphics[Drawing Ganapati Using Python] Introduction In this blog post, we will learn how to draw Lord Ganesha …

Contact Management System in Python with a Graphical User Interface (GUI) Introduction: The Contact Management System is a Python-based application designed to …

Get Huge Discounts
More Python Projects