JavaScriptWeb Development Projects

How to make Snake Game using HTML, CSS and JavaScript ?

Hey Friends! Today we are learn How to create Snake Game using html css and JavaScript and i hope you like it. Here you can get my all videos source code this source code just phaste in your code editor and save it filename.html 

Friends, it is not at all easy to make a game as easy as it is to play a game, here we are not talking about any online game making software or application that makes a game in 5 minutes without coding, here we are in notepad You are going to learn to make games from coding.

Nowadays even a small child can make a game with online software, but the real fun is in making a game from coding, in this post we are not going to teach you coding because it is not possible to learn coding in any article but if you want then from start to finish. Learn Hindi till free. If I want to learn coding then definitely tell us by commenting below.

Here we will tell you how to make snake game using html ,css and javascript. If you want to make snake game so first of all learn html css and jaascript from w3school. It is the best platform for lean this courses and i hope you understand alredy then open your code editor. If you not download any code editor in your system then go to browser and type visual studio code editor and download it. After this install in your system. If you are already installed it in your sytem then open it.

JavaScript Snake tutorial

JavaScript Snake tutorial shows how to create a Snakes game in JavaScript. The images and sources are available at the author’s Github JavaScript-Snake-Game repository.

Snake game

Snakes is an older classic video game which was first created in late 70s. Later it was brought to PCs. In this game the player controls a snakes. The objective is to eat as many apples as possible. Each time the snakes eats an apple, its body grows. The snakes must avoid the walls and its own body. This game is sometimes called Nibbles.

HTML5 Canvas

HTML5 canvas element provides a resolution-dependent bitmap area, which can be used for rendering graphs, game graphics, art, or other visual images on the fly. In simple terms, canvas is a new element in HTML5, which allows you to draw graphics using JavaScript. Canvas brings animations to web pages without the need of plugins like Flash, Silverlight, or Java.

JavaScript Snake code example

The size of each of the joints of a snakes is 10 px. The snakes is controlled with the cursor keys. Initially, the snakes has three joints. If the game is finished, the “Game Over” message is displayed in the middle of the canvas.

A snakes game is a simple game where a snakes moves around a box trying to eat an apple. Once it successfully eats the apple, the length of the snake increases and the movement becomes faster.

Then the game is over when the snakes runs into itself or any of the four walls of the box.

Alright, let’s start with the HTML and CSS (the skeleton for our game).

The HTML above is pretty basic.

We have a div of class scoreDisplay that will display our scores.
There’s a div of class grid that will house the game (this is going to be a 10 by 10 grid)
The class button basically contains a button for users playing the game on a phone (we will automate it with the keyboard for desktop user).
And the popup class will hold our replay button.
Now let’s add some styling with CSS.

In the CSS, the grid which is the gameboard has a set dimension and a display of flex. This allows the contents (div) of this grid to line up in a horizontal manner as if they were inline elements instead of the normal block display which they possess.

The flex wrap property simply moves the divs to the next line, preventing them from going past the set dimension of their parent element (grid).

We will be dynamically creating the game board contents from JS but we can give a width and height here (with the .grid div). I included the comments here to help you actually see the divs, so as time goes on we will uncomment the code.

The snakes and Apple classes are to show us where the snake and bonus is on the game, while the popup class is a fixed div that houses the replay div.

At this point, you should have something like this:

<!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>Snake Game by Code with Nizami</title>
    <style>
      body{
          background-color: rgb(110, 110, 110);
      }
      .canvas{
          border: 15px solid rgb(48, 47, 47);
          border-radius: 10px;
      }
    </style>
</head>
<body>
    <center>
    <canvas id="canvas"></canvas>
</center>
    <script>
        const BG_COLOR = "black";
        const SNAKE_COLOR = "white";
        const FOOD_COLOR = "green";
        const canvas = document.getElementById("canvas");
        const ctx = canvas.getContext('2d');
        canvas.width = canvas.height = 500;
        const FR = 10;
        const S = 20;
        const T = canvas.width / S;
        let pos, vel, food, snake;
        function init(){
            pos = {x: 10, y: 10};
            vel = {x: 0, y: 0};
            snake = [
            {x: 8, y: 10},
            {x: 9, y: 10},
            {x: 10, y: 10},
            ]
            randomFood();
        }
        init();
        function randomFood(){
            food = {
               x: Math.floor(Math.random() * T),
               y: Math.floor(Math.random() * T), 
            }
            for(let cell of snake){
                if(cell.x === food.x && food.y === cell.y){
                   return randomFood(); 
                }
            }
        }
        document.addEventListener('keydown', keydown);
        function keydown(e){
            switch(e.keyCode){
                case 37: {
                    return vel = {x: -1, y: 0}
                }
                case 38: {
                    return vel = {x: 0, y: -1}
                }
                case 39: {
                    return vel = {x: 1, y: 0}
                }
                case 40: {
                    return vel = {x: 0, y: 1}
                }
            }
        }
        setInterval(() => {
            requestAnimationFrame(gameLoop);
        }, 1000 /FR);
        function gameLoop(){
            ctx.fillStyle = BG_COLOR;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = SNAKE_COLOR;
            for(let cell of snake){
                ctx.fillRect(cell.x*S, cell.y*S, S,S);
            }
            ctx.fillStyle = FOOD_COLOR;
            ctx.fillRect(food.x*S, food.y*S,S,S);
            pos.x += vel.x;
            pos.y += vel.y;
            if(pos.x < 0 || pos.x > T || pos.y < 0 || pos.y > T) {
                init();
            }
            if(food.x === pos.x && food.y === pos.y){
                snake.push({...pos});
                pos.x += vel.x;
                pos.y += vel.y;
                randomFood();
            }
            if(vel.x || vel.y){
                for(let cell of snake){
                    if(cell.x === pos.x && cell.y === pos.y) {
                        return init();
                    }
                }
                snake.push({...pos});
                snake.shift();
            }
        }
    </script>
</body>
</html>

Watch video related this article…

Related Articles

Leave a Reply

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

Back to top button