Home programming How to Build a Snake Game In HTML, CSS & JavaScript 

How to Build a Snake Game In HTML, CSS & JavaScript 

0
Build a Snake Game In HTML, CSS & JavaScript

The best way to learn any programming language is through hands-on projects. Are you a game lover and want to create your own game? Don’t worry; I am here to show you how to build a snake game using HTML, CSS, and JavaScript. The Snake Game is a simple game you can make using the basics of JavaScript and HTML.

In the Snake game, there is a snake and an apple. The snake moves around a box, trying to eat an apple. Once the snake eats the apple successfully, the length & speed of the snake will get increase & faster.

The primary goal is to navigate a snake and eat as many apples without touching the walls or the snake’s body.

To build the Snake game, we need three files HTML, JavaScript and Images.

Step By Step procedure to Build the Snake Game:

Step 1: Create a New Folder on the Desktop.

Step 2: Open Notepad and save the file name as index.html.

Step 3: Then paste the given codes into the index.html file. 

Note: Create a file with a .html extension.

<!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">
    <title>My Snake Game | Techbanta</title>
    <style>
        *{
            box-sizing: border-box;
        }
        body{
            margin: 0;
            padding: 0;
        }
        .container{
            height: 100vh;
            width: 100%;
            background: #4714FC;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }
        .game-board{
            height: 90vmin;
            width: 90vmin;
            background: linear-gradient(orange, yellow);
            display: grid;
            grid-template-columns: repeat(16, 1fr);
            grid-template-rows: repeat(16, 1fr);
        }
        .score{
            background: yellow;
            padding: 10px 20px;
            border-radius: 20px;
        }

        .snake{
            background: #219d00;
            border: 2px solid #000;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
        }
        .head{
            background: url(snake.png);
            background-size: 100% 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            z-index: 22;
        }

        .food{
            background: url(apple.png);
            background-size: 100% 100%;
            z-index: 55;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 class="score"> Score : <span id="score">0</span></h2>
        <div class="game-board"></div>
    </div>
    <script src="game.js"></script>
</body>
</html>

Step 4: Second, Create a JavaScript file with the name game.js and paste the given codes into the JavaScript file. 

Note: Create a file with .js extension.

var lastPaintTime = 0;
let SNAKE_SPEED = 2;
let inputDirection = { x : 0, y : 0}
let lastInputDirection = inputDirection;


const EXPENTION_AMOUNT = 1;
var score = 0;
const snakeBody = [
    {x : 8, y : 8},
    
    
    

];
let food = getFoodrandomPosition();
const gameBoard = document.querySelector(".game-board");
const scoreBox = document.getElementById("score");
function paint(currentTime){
   var TimeSeconds = (currentTime - lastPaintTime) / 1000;
   requestAnimationFrame(paint);
   if( TimeSeconds < 1 / SNAKE_SPEED) return;
   lastPaintTime = currentTime;
    
    update();
    draw();

}

window.requestAnimationFrame(paint);



function draw(){
    drawSnake();
    drawFood();
}

function update(){
    
    gameBoard.innerHTML = "";
    snakeMove();
    snakeEatFood();
}


function drawSnake(){
    snakeBody.forEach((segment, index)=>{
        var snakeElement = document.createElement("div");
        snakeElement.style.gridColumnStart = segment.x;
        snakeElement.style.gridRowStart = segment.y;
        // snakeElement.innerHTML = index;
        snakeElement.style.transform = "rotate(0deg)";
        if(index == 0){
            snakeElement.classList.add("head");

            if(inputDirection.x == 1){
                snakeElement.style.transform = "rotate(-90deg)";
            }else if(inputDirection.x == -1){
                snakeElement.style.transform = "rotate(90deg)";
            }
            else if(inputDirection.y == -1){
                snakeElement.style.transform = "rotate(180deg)";
            }
            else if(inputDirection.y == 1){
                snakeElement.style.transform = "rotate(0deg)";
            }
        }else{
            snakeElement.classList.add("snake");
        }
        gameBoard.appendChild(snakeElement);

    });
}

function drawFood(){
    var foodElement = document.createElement("div");
    foodElement.style.gridColumnStart = food.x;
    foodElement.style.gridRowStart = food.y;
    foodElement.classList.add("food");
    gameBoard.appendChild(foodElement);
}

function snakeMove(){
    inputDirection = getInputDirection();

    for(i = snakeBody.length - 2; i >= 0; i--){
        snakeBody[i+1] = {...snakeBody[i]}
    }
    snakeBody[0].x += inputDirection.x;
    snakeBody[0].y += inputDirection.y;
    checkGameOver();
}


function getInputDirection(){
    window.addEventListener("keydown", e=>{
        
        switch(e.key){
            case 'ArrowUp' : 
            if(lastInputDirection.y == 1) break;
            inputDirection = {x : 0, y : -1}
            break;
            case 'ArrowDown' : 
            if(lastInputDirection.y == -1) break;
            inputDirection = {x : 0, y : 1}
            break;
            case 'ArrowLeft' : 
            if(lastInputDirection.x == 1) break;
            inputDirection = {x : -1, y : 0}
            break;
            case 'ArrowRight' : 
            if(lastInputDirection.x == -1) break;
            inputDirection = {x : 1, y : 0}
            break;
            default : inputDirection = { x : 0, y : 0}
        }
       
    })
    lastInputDirection = inputDirection;
    return inputDirection;
}


function snakeEatFood(){

    if(isEat()){
        score += 10;
        scoreBox.innerHTML = score;
        console.log("eated")
        food = getFoodrandomPosition();
        SNAKE_SPEED++;
        expendSnake();
    }
    
}

function isEat(){
     return snakeBody[0].x === food.x && snakeBody[0].y === food.y;
        
    
}

function getFoodrandomPosition(){

    let a,b, myCondition = true;
    while(myCondition){
        a = Math.ceil(Math.random()*16);
        b = Math.ceil(Math.random()*16);

        myCondition = snakeBody.some(segment=>{
             return segment.x === a && segment.y === b;
        })
    }
    return {x : a, y : b};
}

function expendSnake(){
    for(i=0; i<EXPENTION_AMOUNT; i++){
        snakeBody.push(snakeBody[snakeBody.length-1]);
    }
}

function checkGameOver(){
    if(snakeOutOfGrid() || snakeIntersection()){
        location.reload();
        alert("Game Over : You Loose");
    }
}

function snakeOutOfGrid(){
    return snakeBody[0].x < 0 || snakeBody[0].x > 16 || snakeBody[0].y < 0 || snakeBody[0].y > 16;
}

function snakeIntersection(){
    for(i=1; i<snakeBody.length; i++){
        if(snakeBody[0].x === snakeBody[i].x && snakeBody[0].y === snakeBody[i].y){
            return true;
        }
    }

    
}

Step 5: Download the images of a snake, and an apple given below and save them into a folder.

Step 6: Run the project by clicking on the index.html file from the folder.

Conclusion:

These are the steps to building a Snake Game. You can run the project by clicking on the index.html file and seeing the output of your project. If you want to learn any other language project, comment below.

Exit mobile version