Advertisement
lukesinclair12

Javascript Snake Game

Oct 4th, 2013
598
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <head>
  4.         <meta charset="utf-8">
  5.         <title></title>
  6.         <style>
  7.             ::-moz-selection {
  8.                 background: #b3d4fc;
  9.                 text-shadow: none;
  10.             }
  11.  
  12.             ::selection {
  13.                 background: #b3d4fc;
  14.                 text-shadow: none;
  15.             }
  16.  
  17.             html {
  18.                 padding: 30px 10px;
  19.                 font-size: 20px;
  20.                 line-height: 1.4;
  21.                 color: #737373;
  22.                 background: #f0f0f0;
  23.                 -webkit-text-size-adjust: 100%;
  24.                 -ms-text-size-adjust: 100%;
  25.             }
  26.  
  27.             html,
  28.             input {
  29.                 font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  30.             }
  31.  
  32.             body {
  33.                 max-width: 500px;
  34.                 _width: 500px;
  35.                 padding: 30px 20px 50px;
  36.                 border: 1px solid #b3b3b3;
  37.                 border-radius: 4px;
  38.                 margin: 0 auto;
  39.                 box-shadow: 0 1px 10px #a7a7a7, inset 0 1px 0 #fff;
  40.                 background: #fcfcfc;
  41.             }
  42.  
  43.             h1 {
  44.                 margin: 0 10px;
  45.                 font-size: 50px;
  46.                 text-align: center;
  47.             }
  48.  
  49.             h1 span {
  50.                 color: #bbb;
  51.             }
  52.  
  53.             h3 {
  54.                 margin: 1.5em 0 0.5em;
  55.             }
  56.  
  57.             p {
  58.                 margin: 1em 0;
  59.                 text-align: center;
  60.  
  61.             }
  62.  
  63.             .container {
  64.                 max-width: 380px;
  65.                 _width: 380px;
  66.                 margin: 0 auto;
  67.             }
  68.  
  69.             input::-moz-focus-inner {
  70.                 padding: 0;
  71.                 border: 0;
  72.             }
  73.            
  74.             #canvas{
  75.              margin-left: 5%;
  76.            
  77.             }
  78.             nav{
  79.             text-align: center;
  80.             }
  81.         </style>
  82.     </head>
  83.     <body>
  84.         <div class="container">
  85.             <h1>Snake Game</h1>
  86.            
  87.         </div>
  88.         <canvas id="canvas" width="450" height="450"></canvas>
  89.  
  90. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  91.  
  92. <script>
  93. $(document).ready(function(){
  94.     //Canvas stuff
  95.     var canvas = $("#canvas")[0];
  96.     var ctx = canvas.getContext("2d");
  97.     var w = $("#canvas").width();
  98.     var h = $("#canvas").height();
  99.    
  100.     //Lets save the cell width in a variable for easy control
  101.     var cw = 10;
  102.     var d;
  103.     var food;
  104.     var score;
  105.    
  106.     //Lets create the snake now
  107.     var snake_array; //an array of cells to make up the snake
  108.    
  109.     function init()
  110.     {
  111.         d = "right"; //default direction
  112.         create_snake();
  113.         create_food(); //Now we can see the food particle
  114.         //finally lets display the score
  115.         score = 0;
  116.        
  117.         //Lets move the snake now using a timer which will trigger the paint function
  118.         //every 60ms
  119.         if(typeof game_loop != "undefined") clearInterval(game_loop);
  120.         game_loop = setInterval(paint, 90);
  121.     }
  122.     init();
  123.    
  124.     function create_snake()
  125.     {
  126.         var length = 5; //Length of the snake
  127.         snake_array = []; //Empty array to start with
  128.         for(var i = length-1; i>=0; i--)
  129.         {
  130.             //This will create a horizontal snake starting from the top left
  131.             snake_array.push({x: i, y:0});
  132.         }
  133.     }
  134.    
  135.     //Lets create the food now
  136.     function create_food()
  137.     {
  138.         food = {
  139.             x: Math.round(Math.random()*(w-cw)/cw),
  140.             y: Math.round(Math.random()*(h-cw)/cw),
  141.         };
  142.         //This will create a cell with x/y between 0-44
  143.         //Because there are 45(450/10) positions accross the rows and columns
  144.     }
  145.    
  146.     //Lets paint the snake now
  147.     function paint()
  148.     {
  149.         //To avoid the snake trail we need to paint the BG on every frame
  150.         //Lets paint the canvas now
  151.         ctx.fillStyle = "white";
  152.         ctx.fillRect(0, 0, w, h);
  153.         ctx.strokeStyle = "black";
  154.         ctx.strokeRect(0, 0, w, h);
  155.        
  156.         //The movement code for the snake to come here.
  157.         //The logic is simple
  158.         //Pop out the tail cell and place it infront of the head cell
  159.         var nx = snake_array[0].x;
  160.         var ny = snake_array[0].y;
  161.         //These were the position of the head cell.
  162.         //We will increment it to get the new head position
  163.         //Lets add proper direction based movement now
  164.         if(d == "right") nx++;
  165.         else if(d == "left") nx--;
  166.         else if(d == "up") ny--;
  167.         else if(d == "down") ny++;
  168.        
  169.         //Lets add the game over clauses now
  170.         //This will restart the game if the snake hits the wall
  171.         //Lets add the code for body collision
  172.         //Now if the head of the snake bumps into its body, the game will restart
  173.         if(nx == -1 || nx == w/cw || ny == -1 || ny == h/cw || check_collision(nx, ny, snake_array))
  174.         {
  175.             //restart game
  176.             init();
  177.             //Lets organize the code a bit now.
  178.             return;
  179.         }
  180.        
  181.         //Lets write the code to make the snake eat the food
  182.         //The logic is simple
  183.         //If the new head position matches with that of the food,
  184.         //Create a new head instead of moving the tail
  185.         if(nx == food.x && ny == food.y)
  186.         {
  187.             var tail = {x: nx, y: ny};
  188.             score++;
  189.             //Create new food
  190.             create_food();
  191.         }
  192.         else
  193.         {
  194.             var tail = snake_array.pop(); //pops out the last cell
  195.             tail.x = nx; tail.y = ny;
  196.         }
  197.         //The snake can now eat the food.
  198.        
  199.         snake_array.unshift(tail); //puts back the tail as the first cell
  200.        
  201.         for(var i = 0; i < snake_array.length; i++)
  202.         {
  203.             var c = snake_array[i];
  204.             //Lets paint 10px wide cells
  205.             paint_cell(c.x, c.y);
  206.         }
  207.        
  208.         //Lets paint the food
  209.         paint_cell(food.x, food.y);
  210.         //Lets paint the score
  211.         var score_text = "Score: " + score;
  212.         ctx.fillText(score_text, 5, h-5);
  213.     }
  214.    
  215.     //Lets first create a generic function to paint cells
  216.     function paint_cell(x, y)
  217.     {
  218.         ctx.fillStyle = "black";
  219.         ctx.fillRect(x*cw, y*cw, cw, cw);
  220.         ctx.strokeStyle = "white";
  221.         ctx.strokeRect(x*cw, y*cw, cw, cw);
  222.     }
  223.    
  224.     function check_collision(x, y, array)
  225.     {
  226.         //This function will check if the provided x/y coordinates exist
  227.         //in an array of cells or not
  228.         for(var i = 0; i < array.length; i++)
  229.         {
  230.             if(array[i].x == x && array[i].y == y)
  231.              return true;
  232.         }
  233.         return false;
  234.     }
  235.    
  236.     //Lets add the keyboard controls now
  237.     $(document).keydown(function(e){
  238.         var key = e.which;
  239.         //We will add another clause to prevent reverse gear
  240.         if(key == "37" && d != "right") d = "left";
  241.         else if(key == "38" && d != "down") d = "up";
  242.         else if(key == "39" && d != "left") d = "right";
  243.         else if(key == "40" && d != "up") d = "down";
  244.         //The snake is now keyboard controllable
  245.     }) 
  246. })
  247. </script>
  248. </body>
  249. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement