Creating A Very Simple Snake Game Using jQuery

In this tutorial we will try to make a very simple game called Snake. Snake is the most popular games in the late 1997 that comes from the Nokia 6110 Phone. This game become a favorite past time for all of us a long time ago, even our grand parents played this awesome game. So for today we will try to replicate the game, but this time we will create it through HTML & jQuery Script. Let's get started. Before we proceed I hope that you already have the jQuery plugin, if there's not I already attached the jQuery plugin inside the zip file. The Mark Up The very first step is we're going to create the mark up. This page will display the game through the web browser. To create the file open any kind of text editor(notepad++, etc) then copy/paste the code that I provided below.
  1. <!DOCTYPE html>
  2. <html lang = "en">
  3.         <head>
  4.                 <title>Snake Game</title>
  5.                 <link rel = "stylesheet" type = "text/css" href = "css/bootstrap.css"/>
  6.                 <meta charset = "UTF-=8" name = "viewport" content = "width=device-width, initial-scale=1"/>
  7.         </head>
  8.         <nav class = "navbar navbar-default">
  9.                 <div class = "container-fluid">
  10.                         <a class = "navbar-brand" href = "https://sourcecodester.com">Sourcecodester</a>
  11.                 </div>
  12.         </nav>
  13.         <div class = "col-md-3"></div>
  14.         <div class = "col-md-6 well">
  15.                 <h3 class = "text-primary">Creating A Simple Snake Game</h3>
  16.                 <hr style = "bolder-top:1px dotted #000;"/>
  17.                 <center><canvas id = "canvas" width = "450" height = "400"></canvas</center>//this is where the game will be display
  18.         </div>
  19.        
  20. </body>
  21. <script src = "js/jquery-3.1.1.js" ></script>
  22. <script src = "js/snake.js"></script>
  23. </html>
Save & name it 'index.html' Creating the snake The next step is we're going to create the snake, open your text editor and copy/paste this script.
  1. $(document).ready(function(){
  2.   var canvas = $('#canvas')[0];
  3.   var context = canvas.getContext('2d');
  4.   var width = $('#canvas').width();
  5.   var height = $('#canvas').height();  
  6.   var cell_width = 10;
  7.   var run;
  8.   var snake_food;
  9.   var score;
  10.   var snake_array;
  11.  
  12.   function create_snake(){
  13.           var snake_size = 3; //the size of the snake is 3
  14.           snake_array = []; //creating the array of snake
  15.           for(var m = 0; m < snake_size; m++){
  16.                   snake_array.push({x: 45, y: 14});  //this will handle the position of the snake
  17.           }
  18.   }
  19. });
Save this file and name it 'snake.js' Creating the snake food After creating the body of snake, we will now create the food of the snake. Just add this script inside the javascript code
  1. function create_food(){
  2.     snake_food = {
  3.       x: Math.round(Math.random() * (width - cell_width) / cell_width), //this will display the food randomly based on the x and y ordinates of the canvas  
  4.       y: Math.round(Math.random() * (height - cell_width) / cell_width)
  5.     };
  6. }
Creating the stage of the game This will be the background of the game, just simply add this script to your javascript code.
  1. function stage_color(){
  2.     context.fillStyle = "orange";
  3.     context.fillRect(0, 0, width, height);
  4.     context.strokeStyle = "#000000";
  5.     context.strokeRect(0, 0, width, height);           
  6. }
Adding the sprite of the snake This will be the sprite of the snake. Just simply add the script to your javascript code
  1. function snake_body(x, y){
  2.     context.fillStyle = "#ffffff";
  3.     context.fillRect(x * cell_width, y * cell_width, cell_width, cell_width);
  4.     context.strokeStyle = "#000000";   
  5.     context.strokeRect(x * cell_width, y * cell_width, cell_width, cell_width);
  6. }
Creating the collision of object to object This will handle the collision of the snake when it hit its own body.
  1. function collision(x, y, array){
  2.   for(var i = 0; i < array.length; i++){
  3.     if(array[i].x == x && array[i].y == y){ //this will check if the snake hit its own body, and will return true
  4.       return true;
  5.     }
  6.   }
  7.   return false; //if not return false
  8. }
Creating the movement of snake This will be the handler for the movement of the snake within the game.
  1. $(document).keydown(function(e){
  2.     var key = e.which;
  3.       if(key == "40" && run != "up"){ //check if the key you pressed is arrow down
  4.         run = "down"; //return the string down
  5.       }
  6.       else if(key == "39" && run != "left"){ //check if the key you pressed is arrow right
  7.         run = "right"; //return the string right
  8.       }
  9.       else if(key == "38" && run != "down"){ //check if the key you pressed is arrow up
  10.         run = "up"; //return the string up
  11.       }
  12.       else if(key == "37" && run != "right"){//check if the key you pressed is arrow left
  13.         run = "left"; return the string left
  14.       }
  15. });
Creating the config of the game This will handle the logic of the game on how the food will be eaten by the snake, and then make its body increase.
  1. function config(){     
  2.   stage_color(); //display the stage of the game
  3.                
  4.   var pop_x = snake_array[0].x; //assigned the x ordinate of the canvas
  5.   var pop_y = snake_array[0].y; // assigned the y ordinate of the canvas
  6.                
  7.   switch(run){ //check the variable run
  8.     case "right": //if run == right
  9.       pop_x++; //the movement of the snake will be right
  10.       break;
  11.     case "left": //if run == left
  12.       pop_x--; //the movement of the snake will be left
  13.       break;
  14.     case "down": //if run == down
  15.       pop_y++; //the movement of the snake will be down
  16.       break;
  17.     case "up": //if run == up
  18.       pop_y--; //the movement of the snake will be up
  19.       break;
  20. }
  21.                
  22.   if(pop_x == -1 || pop_x == width / cell_width || pop_y == -1 || pop_y == height / cell_width || collision(pop_x, pop_y, snake_array)){ //check if the snake collide within the boundary of the canvas or the snake collide with its own body
  23.     start(); //if true the game will restart
  24.     return;
  25.   }
  26.                
  27.   if(pop_x == snake_food.x && pop_y == snake_food.y){ //check if the snake collide with the food
  28.     var snake_tail = {x: pop_x, y: pop_y}; //if true assign the variable for the snake tail
  29.     score += 3; //add a score
  30.     create_food(); //create another food randomly
  31.   }else{
  32.     var snake_tail = snake_array.pop(); /if false will create the variable for the snake tail
  33.     snake_tail.x = pop_x; //assign variable for the x ordinate of snake
  34.     snake_tail.y = pop_y; //assign variable for the y ordinate of snake        
  35.   }
  36.                
  37.   snake_array.unshift(snake_tail); //if the condition is true it will add the value of the food inside the snake_array
  38.                
  39.   for (var i = 0; i < snake_array.length; i++){ //if there's a new valued inside the snake_array it will increment
  40.     var c = snake_array[i]; //assigned the incremented valued
  41.     snake_body(c.x, c.y); //then will increase the size of the snake
  42.   }
  43.                
  44.   snake_body(snake_food.x, snake_food.y); //increase the snake body in the correct position
  45.   var score_text = "Score: " + score; //assign the variable of score
  46.   context.fillText(score_text, 5, 10); //display the score
  47. }
Creating the configuration of the game This will handle the initialize of the game
  1.   start(); //this will start running the game
  2.  
  3.     function start(){
  4.       run = "left"; // this is the default movement of the snake
  5.       create_snake(); //will create the food
  6.       create_food(); //will create the snake
  7.       score = 0; //display the default score
  8.                
  9.       if(typeof game_start != "undefined")clearInterval(game_start); //check if the loop of the game is undefined and initialize the game simultaneously
  10.         game_start = setInterval(config, 60); //this the fps of the game when running
  11.       }
This is the full code of the snake.js
  1. $(document).ready(function(){
  2.         var canvas = $('#canvas')[0];
  3.         var context = canvas.getContext('2d');
  4.         var width = $('#canvas').width();
  5.         var height = $('#canvas').height();    
  6.         var cell_width = 10;
  7.         var run;
  8.         var snake_food;
  9.         var score;
  10.         var snake_array;
  11.        
  12.        
  13.        
  14.         function create_snake(){
  15.                 var snake_size = 3;
  16.                 snake_array = [];
  17.                 for(var m = 0; m < snake_size; m++){
  18.                         snake_array.push({x: 45, y: 14});
  19.                 }
  20.         }
  21.        
  22.         function create_food(){
  23.                 snake_food = {
  24.                         x: Math.round(Math.random() * (width - cell_width) / cell_width),
  25.                         y: Math.round(Math.random() * (height - cell_width) / cell_width)
  26.                 };
  27.         }
  28.        
  29.         function config(){
  30.                
  31.                 stage_color();
  32.                
  33.                 var pop_x = snake_array[0].x;
  34.                 var pop_y = snake_array[0].y;
  35.                
  36.                 switch(run){
  37.                         case "right":
  38.                                 pop_x++;
  39.                                 break;
  40.                         case "left":
  41.                                 pop_x--;
  42.                                 break;
  43.                         case "down":
  44.                                 pop_y++;
  45.                                 break;
  46.                         case "up":
  47.                                 pop_y--;
  48.                                 break;
  49.                 }
  50.                
  51.                
  52.                 if(pop_x == -1 || pop_x == width / cell_width || pop_y == -1 || pop_y == height / cell_width || collision(pop_x, pop_y, snake_array)){
  53.                         start();
  54.                         return;
  55.                 }
  56.                
  57.                 if(pop_x == snake_food.x && pop_y == snake_food.y){
  58.                         var snake_tail = {x: pop_x, y: pop_y};
  59.                         score += 3;
  60.                         create_food();
  61.                 }else{
  62.                         var snake_tail = snake_array.pop();
  63.                         snake_tail.x = pop_x;
  64.                         snake_tail.y = pop_y;
  65.                        
  66.                 }
  67.                
  68.                 snake_array.unshift(snake_tail);
  69.                
  70.                 for (var i = 0; i < snake_array.length; i++){
  71.                         var c = snake_array[i];
  72.                         snake_body(c.x, c.y);
  73.                 }
  74.                
  75.                 snake_body(snake_food.x, snake_food.y);
  76.                
  77.                 var score_text = "Score: " + score;
  78.                 var title = "Sourcecodester"
  79.                 context.fillText(score_text, 5, 10);
  80.                 context.fillText(title, 0, height-2);
  81.         }
  82.        
  83.         function stage_color(){
  84.                 context.fillStyle = "orange";
  85.                 context.fillRect(0, 0, width, height);
  86.                 context.strokeStyle = "#000000";
  87.                 context.strokeRect(0, 0, width, height);
  88.                
  89.         }
  90.        
  91.         function snake_body(x, y){
  92.                 context.fillStyle = "#ffffff";
  93.                 context.fillRect(x * cell_width, y * cell_width, cell_width, cell_width);
  94.                 context.strokeStyle = "#000000";       
  95.                 context.strokeRect(x * cell_width, y * cell_width, cell_width, cell_width);
  96.         }
  97.        
  98.         function collision(x, y, array){
  99.                 for(var i = 0; i < array.length; i++){
  100.                         if(array[i].x == x && array[i].y == y){
  101.                                 return true;
  102.                         }
  103.                 }
  104.                 return false;
  105.         }
  106.        
  107.         $(document).keydown(function(e){
  108.                 var key = e.which;
  109.                 if(key == "40" && run != "up"){
  110.                         run = "down";
  111.                 }
  112.                 else if(key == "39" && run != "left"){
  113.                         run = "right";
  114.                 }
  115.                 else if(key == "38" && run != "down"){
  116.                         run = "up";
  117.                 }
  118.                 else if(key == "37" && run != "right"){
  119.                         run = "left";
  120.                 }
  121.         });
  122.        
  123.         start();
  124.        
  125.         function start(){
  126.                 run = "left";
  127.                 create_snake();
  128.                 create_food();
  129.                 score = 0;
  130.                
  131.                 if(typeof game_start != "undefined")clearInterval(game_start);
  132.                 game_start = setInterval(config, 60);
  133.         }
  134. });
There you have it we create a simple snake game. I hope that this tutorial help you to your programming carrier, and enhance your skill on looping. For more updates and tutorials just kindly visit this site. Enjoy Coding!!
Tags

Comments

I have all the code and index, but no jquery plugin, I have the one you provided open in notepad++ but it still doesn't work. Any help?

Add new comment