How To Create A Snake Game Using Javascript

Snake Game Using Html Css Javascript

Learners, In this article we are going to design a very impressive project i.e., Snake Game Using HTML, CSS & JavaScript with detailed functionality.

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

But now the technology has grown and we have completely switched to smart phone. And now this games either upgraded to play in a smartphone or have been discontinued by the makers. But we as Front-End Developer can create this project and start gaining our knowledge in this field as a beginner.

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

Hey Learners!!!

Welcome to this blog with projectfreecode, In this blog we are going to learn how we can design a Snake Game Using HTML, CSS & JAVASCRIPT.

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

Let’s have a look at our project.

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

Following is the feature of our project:-

  • First we have gave the heading and as the game name.
  • Then we gave a label as 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.

HTML SECTION

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 gave a title. 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.
  • And in last we have created a gameboard so that the objects of the game lie under the box.

The HTML code is given below ๐Ÿ‘‡ run 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>  

CSS SECTION

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 which followed step by step.

We have the following part in the CSS section.

  • First, we have included every thing 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 have styled the classes which was called in HTML file. Setting their margin, padding & border.
  • Then giving the font size as rem for the headings and labels.
  • Giving the color for the game board the snake and the dot.
  • And in last setting the height for so that the gameboard.

Below is the CSS Code ๐Ÿ‘‡ write this and link this file in the header of your HTML Code.

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

JavaScript SECTION

Now the main and important part not build this but every Front-End Development. The JavaScript which has all the logics 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, gamespeed which is basically the snake speed and gamepoints. We have set the snake size and defined each cases 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 border of the gamepad.

What is CSS BOX Shadow โ€“ Example with Code

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

Final Output:

Through this blog, we have learned how to design Snake Game Using HTML, CSS & JavaScript

Now I’m looking for some positive reviews from your side.

So, How was 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 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

My name is ankit Dungawat Know as codewithrandom, I am frontend developer and run a Instagram page over 140k followers so I daily share new tutorial or project on this website. I run more then 3 website or 2 Instagram pages.

Leave a Comment