Snake Game Using HTML,CSS & JavaScript (Source Code)

Snake Game Using HTML,CSS and JavaScript

Create Snake Game Using HTML, CSS, and JavaScript

Hello learners, a very warm welcome to the Codewithrandom. In today’s blog, we are going to Create a Snake Game using Html, Css, and JavaScript with Source Code.

Now we are familiar with this game in our childhood there was the phone of companies like Nokia, Motorola, lava, and Blackberry used to manufacture phones with keypads. It had pre-installed this application and it was very fun to play in it. Earlier at the point of gaming this game used to entertain each and every kid.

50+ HTML, CSS & JavaScript Projects With Source Code

But now the technology has grown and we have completely switched to smartphones. And now these games have either been upgraded to play on a smartphone or have been discontinued by the makers. But we as front-end developers can create this project and start gaining knowledge in this field as a beginner.

Similarly, we are going to clone the snake game app by ourselves.

Hey learners!!!

I hope you guys have got an idea about the project.

Let’s have a look at our project.

Code byAndrew Gablehouse
Project DownloadLink Available Below
Language usedHTML , CSS and JavaScript
External link / DependenciesYes
ResponsiveNo
Snake Game Table
 
 
snake game in javascript
Snake Game Using HTML,CSS & JavaScript
 

As you are looking in the project preview how the thing is organized.

Portfolio Website using HTML and CSS (Source Code)

Following is the feature of our project:-

First, we have given the heading and the game name.Then we gave a label as a score so that the user knows the score he scores while playing.
We styled it in the css, setting the padding for the class and tags which are defined in the html code.And in last, we have given the logic part in the javascript code.

Snake Game Html Code:-

Here I’m gonna add the file from the body part and tell you how exactly we have defined our structure.

We have the following part in the html section.

First, we created a container, then in the header class, we have given a title. Then we defined a class in the h3 tag.
Then again we have specified a container and in that, we have a section of overlay then we have set a class again in the h3 tag.
Then created a button to start the game.

Ecommerce Website Using HTML, CSS, & JavaScript (Source Code)

And in last we have created a gameboard so that the objects of the game lie under the box.

The html code given below runs it in your idle before css styling.

<div class="container">
    <header class="title">
        <h2>JavaScript Snake Game</h2>
        <h3 id="score">Score:</h3>
    </header>
</div>
<div class="container">
    <section class="overlay">
        <div class="gameOverGrid"><h3 id="gameOver">You lose!</h3></div>
        <button class="gameOverGrid btn">Play</button>
    </section>
    <section id="gameBoard"></section>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Snake Game Css Code:-

Here I’m gonna add the file of the stylesheet which is used to style the page of the snake game and tell you the parts followed step by step.

We have the following part in the css section.
First, we included everything from html tag to every small part which is present there in the html code, then styled the margin, padding & border for it.


Then we styled the classes which were called in html file. Setting their margin, padding & border. Then give the font size as rem for the headings and labels. Giving the color for the game board are the snake and the dot.And in the last setting the height so that the gameboard is.

Gym Website Using HTML and CSS With Source Code

Below is the css code write this and link this file in the header of your html code.

ADVERTISEMENT

html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,
h6,p,blockquote,pre,a,abbr,acronym,
address,big,cite,code,del,dfn,em,
img,ins,kbd,q,s,samp,small,strike,
strong,sub,sup,tt,var,b,u,i,center,
dl,dt,dd,ol,ul,li,fieldset,form,
label,legend,table,caption,tbody,tfoot,
thead,tr,th,td,article,aside,canvas,details,embed,
figure,figcaption,footer,header,hgroup,menu,
nav,output,ruby,section,summary,
time,mark,audio,video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
} /* HTML5 display-role reset for older browsers */
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
    display: block;
}
body {
    line-height: 1;
}
ol,
ul {
    list-style: none;
}
blockquote,
q {
    quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
    content: "";
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
} /* Grid */
html {
    box-sizing: border-box;
}
*,
*:before,
*:after {
    box-sizing: inherit;
}
.container {
    margin: 0 auto;
    padding: 0 25px;
    text-align: center;
    position: relative;
}
.overlay {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 25%;
    height: 50%;
    transform: translate(-50%, -50%);
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 5%;
    display: flex;
    flex-flow: column;
    justify-content: center;
    align-items: center;
}
.title {
    margin-bottom: 15px;
}
#gameBoard,
.row {
    display: flex;
    flex-flow: row wrap;
}
#gameBoard {
    width: 600px;
    height: 600px;
    margin: 0 auto;
    border: 2px groove #000;
    box-sizing: content-box;
    background: #a8c899;
}
.gameOverGrid {
    margin: auto;
} /* Game */
.pixel {
    width: 15px;
    height: 15px;
    box-sizing: border-box;
}
.snakePixel {
    background-color: #000;
}
.foodPixel {
    background-color: cyan;
}
#gameOver {
    color: cornflowerblue;
    display: none;
}
.pixel:last-child {
    border-right: none;
}
.row:last-child .pixel {
    border-bottom: none;
} /* Style */
.btn {
    background: #3498db;
    background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
    background-image: -moz-linear-gradient(top, #3498db, #2980b9);
    background-image: -ms-linear-gradient(top, #3498db, #2980b9);
    background-image: -o-linear-gradient(top, #3498db, #2980b9);
    background-image: linear-gradient(to bottom, #3498db, #2980b9);
    -webkit-border-radius: 6;
    -moz-border-radius: 6;
    border-radius: 6px;
    font-family: Arial;
    color: #ffffff;
    font-size: 20px;
    padding: 10px 20px 10px 20px;
    text-decoration: none;
    border: 0;
}
.btn:hover {
    background: #3cb0fd;
    background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
    background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
    background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
    background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
    background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
    text-decoration: none;
} /* Typog */ /*! Typebase.less v0.1.0 | MIT License */ /* Setup */
html {
    /* Change default typefaces here */
    font-family: serif;
    font-size: 137.5%;
    -webkit-font-smoothing: antialiased;
} /* Copy & Lists */
p {
    line-height: 1.5rem;
    margin-top: 1.5rem;
    margin-bottom: 0;
}
ul,
ol {
    margin-top: 1.5rem;
    margin-bottom: 1.5rem;
}
ul li,
ol li {
    line-height: 1.5rem;
}
ul ul,
ol ul,
ul ol,
ol ol {
    margin-top: 0;
    margin-bottom: 0;
}
blockquote {
    line-height: 1.5rem;
    margin-top: 1.5rem;
    margin-bottom: 1.5rem;
} /* Headings */
h1,
h2,
h3,
h4,
h5,
h6 {
    /* Change heading typefaces here */
    font-family: sans-serif;
    margin-top: 1.5rem;
    margin-bottom: 0;
    line-height: 1.5rem;
}
h1 {
    font-size: 4.242rem;
    line-height: 4.5rem;
    margin-top: 3rem;
}
h2 {
    font-size: 2.828rem;
    line-height: 3rem;
    margin-top: 3rem;
}
h3 {
    font-size: 1.414rem;
}
h4 {
    font-size: 0.707rem;
}
h5 {
    font-size: 0.4713333333333333rem;
}
h6 {
    font-size: 0.3535rem;
} /* Tables */
table {
    margin-top: 1.5rem;
    border-spacing: 0px;
    border-collapse: collapse;
}
table td,
table th {
    padding: 0;
    line-height: 33px;
} /* Code blocks */
code {
    vertical-align: bottom;
} /* Leading paragraph text */
.lead {
    font-size: 1.414rem;
} /* Hug the block above you */
.hug {
    margin-top: 0;
}

Snake Game Javascript Code:-

In this project, we are using some basic functionalities of js (javascript) like an array, and styling using js.

ADVERTISEMENT

Now the main and important part is not building this but every front-end development. The javascript has all the logic and the working of the projects, similarly, in this project, we’ll code the java part. We have defined variable I.E., var for gameboard, a game speed which is basically the snake speed and game points.

ADVERTISEMENT

100+ JavaScript Projects With Source Code ( Beginners to Advanced)

ADVERTISEMENT

We have set the snake size and defined each case for the moving of the snake and set a number for the score and it will increase after the snake will eat the food. And set the condition when the snake will collide with a border of the gamepad.

ADVERTISEMENT

Below is the javascript code write it in your idle and linked it under the script tag of the html code:

/*jslint browser: true*/
/*global $, jQuery, alert*/

var gameBoardSize = 40;
var gamePoints = 0;
var gameSpeed = 100;

$(document).ready(function () {
    console.log("Ready Player One!");
    createBoard();
    $(".btn").click(function() {
        startGame();
    });
});

var Snake = {
    position: [[20, 20], [20, 19], [20, 18]], // snake start position
    size: 3,
    direction: "r",
    alive: true
}

var Food = {
    position: [],
    present: false
}

function createBoard() {
    $("#gameBoard").empty();
    var size = gameBoardSize;
    
    for (i = 0; i < size; i++) {
        $("#gameBoard").append('<div class="row"></div>');
        for (j = 0; j < size; j++) {
            $(".row:last-child").append('<div class="pixel"></div>');
        }
    }
}

function moveSnake() {
  var head = Snake.position[0].slice();

  switch (Snake.direction) {
    case 'r':
      head[1] += 1;
      break;
    case 'l':
      head[1] -= 1;
      break;
    case 'u':
      head[0] -= 1;
      break;
    case 'd':
      head[0] += 1;
      break;
  }

  // check after head is moved
  if (alive(head)) {
    // draw head
    $(".row:nth-child(" + head[0] + ") > .pixel:nth-child(" + head[1] + ")").addClass("snakePixel");

    // draw rest of body loop
    for (var i = 0; i < Snake.size; i++) {
      $(".row:nth-child(" + Snake.position[i][0] + ") > .pixel:nth-child(" + Snake.position[i][1] + ")").addClass("snakePixel");
    }

    // if head touches food
    if (head.every(function(e,i) {
      return e === Food.position[i];
    })) {
      Snake.size++;
      Food.present = false;
      gamePoints += 5;
      $(".row:nth-child(" + Food.position[0] + ") > .pixel:nth-child(" + Food.position[1] + ")").removeClass("foodPixel");
      $("#score").html("Score: "+gamePoints)
        if (gamePoints % 16 == 0 && gameSpeed > 10) { gameSpeed -= 5; };
    } else {
      $(".row:nth-child(" + Snake.position[Snake.size-1][0] + ") > .pixel:nth-child(" + Snake.position[Snake.size-1][1] + ")").removeClass("snakePixel");
      Snake.position.pop();
    }
    Snake.position.unshift(head);
  } else {
    gameOver();
  }
}


function generateFood() {
    if (Food.present === false) {
        Food.position = [Math.floor((Math.random()*40) + 1), Math.floor((Math.random()*40) + 1)]
        Food.present = true;
        console.log("Food at: "+Food.position);
        $(".row:nth-child(" + Food.position[0] + ") > .pixel:nth-child(" + Food.position[1] + ")").addClass("foodPixel");
    }
}

function keyPress() {
    $(document).one("keydown", function(key) {
        switch(key.which) {
            case 37: // left arrow
                if (Snake.direction != "r") {Snake.direction = "l";}
                break;
            case 38: // up arrow
                if (Snake.direction != "d") {Snake.direction = "u";}
                break;
            case 39: // right arrow
                if (Snake.direction != "l") {Snake.direction = "r";}
                break;
            case 40: // down arrow
                if (Snake.direction != "u") {Snake.direction = "d";}
                break;
        }
    });
}

function gameLoop() {
    setTimeout(function() {
        keyPress();
        generateFood();
        moveSnake();
        if (Snake.alive) {gameLoop(); }
    }, gameSpeed);
}

function alive(head) {
  // head check
  if (head[0] < 1 || head[0] > 40 || head[1] < 1 || head[1] > 40) {
    return false;
  }
  // wall collision
  if (Snake.position[0][0] < 1 || Snake.position[0][0] > 40 || Snake.position[0][1] < 1 || Snake.position[0][1] > 40) {
    return false;
  }
  // self collision
  for (var i = 1; i < Snake.size; i++) {
    if ((Snake.position[0]).every(function(element,index) {
      return element === Snake.position[i][index];
    })) {
      return false;
    }
  }
  return true;
}

function gameOver() {
    Snake.alive = false;
    console.log("Game Over!");
    $(".overlay").show();
    $("#gameOver").show();
    var blink = function() {
        $(".row:nth-child(" + Snake.position[0][0] + ") > .pixel:nth-child(" + Snake.position[0][1] + ")").toggleClass("snakePixel");
    }
    
    var i = 0;
    function blinkLoop() {
        blink();
        setTimeout(function() {
            i++;
            if (i < 10) { blinkLoop();}
        }, 400);
    }
    blinkLoop();
}

function startGame() {
    // reset game settings
    Snake.size = 3;
    Snake.position = [[20,20],[20,19],[20,18]];
    Snake.direction = "r";
    Snake.alive = true;
    gameSpeed = 100;
    gamePoints = 0;
    Food.present = false;
    
    // start game
    createBoard();
    $(".overlay").hide();
    gameLoop();
}

Now, we write Javascript Code for the complete Snake Game and Yes now you can play it in our Live Preview:-

Final Output Of Snake Game Using JavaScript:-

snake game in javascript
Snake Game Using HTML,CSS & JavaScript
Snake Game Using HTML,CSS & JavaScript
Snake Game Using HTML,CSS & JavaScript

Through this blog, we have learned how to Create a Snake Game using Html, Css and JavaScript.Now I’m looking for some positive reviews from your side.

Create a Multi-Step Form Using HTML, CSS & JavaScript

So, how were the blog learners,

If you want a more interesting blog like this then please check our blog sites. Stay tuned because every day you will learn something new here.

I hope that I’m able to make you understand this topic and that you have learned something new from this blog. If you faced any difficulty feel free to reach out to us with the help of the comment box and if you liked it, please show your love in the comment section. This fills bloggers’ hearts with enthusiasm for writing more new blogs.

Happy coding

Written by @harsh_9

Which code editor do you use for this Snake Game coding?

I personally recommend using VS Code Studio, it’s straightforward and easy to use.

is this project responsive or not?

No! this is not a responsive project

Do you use any external links to create this project?

Yes!



Leave a Reply