Advertisement
Guest User

snake javascript

a guest
Nov 14th, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <canvas id="gc" width="400" height="400"></canvas>
  2. <script>
  3.     window.onload=function(){
  4.         canv=document.getElementById("gc");
  5.         ctx=canv.getContext("2d");
  6.         document.addEventListener("keydown",keyPush);
  7.         setInterval(game,1000/15);
  8.     }
  9.     px=py=10;
  10.     gs=tc=20;
  11.     ax=ay=15;
  12.     xv=yv=0;
  13.     trail=[];
  14.     tail = 5;
  15.     function game(){
  16.         px+=xv;
  17.         py+=yv;
  18.         if (px<0) {
  19.             px=tc-1;
  20.         }
  21.         if (px>tc-1) {
  22.             px=0;
  23.         }
  24.         if (py<0) {
  25.             py=tc-1;
  26.         }
  27.         if (py>tc-1) {
  28.             py=0;
  29.         }
  30.         ctx.fillStyle="black";
  31.         ctx.fillRect(0,0,canv.width,canv.height);
  32.  
  33.         ctx.fillStyle="lime";
  34.         for(var i=0;i<trail.length;i++){
  35.             ctx.fillRect(trail[i].x*gs,trail[i].y*gs,gs-2,gs-2);
  36.             if(trail[i].x==px && trail[i].y==py){
  37.                 tail = 5;
  38.             }
  39.         }
  40.         trail.push({x:px,y:py});
  41.         while(trail.length>tail){
  42.             trail.shift();
  43.         }
  44.  
  45.         if(ax==px && ay==py){
  46.                 tail++;
  47.                 ax=Math.floor(Math.random()*tc);
  48.                 ay=Math.floor(Math.random()*tc);
  49.                    
  50.             }
  51.  
  52.         ctx.fillStyle="red";
  53.         ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2);
  54.        
  55.        
  56.     }
  57.     function keyPush(evt){
  58.         switch(evt.keyCode){
  59.             case 37:
  60.                 xv=-1;yv=0;
  61.                 break;
  62.             case 38:
  63.                 xv=0;yv=-1;
  64.                 break;
  65.             case 39:
  66.                 xv=1;yv=0;
  67.                 break;
  68.             case 40:
  69.                 xv=0;yv=1;
  70.                 break;
  71.            
  72.         }
  73.     }
  74. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement