Dekufish

Untitled

Oct 18th, 2021
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1.  
  2.  
  3. <canvas id="gc" width="400" height="400"></canvas>
  4.  
  5. <script>
  6.  
  7. window.onload=function() {
  8.  
  9. canv=document.getElementById("gc");
  10.  
  11. ctx=canv.getContext("2d");
  12.  
  13. document.addEventListener("keydown",keyPush);
  14.  
  15. setInterval(game,1000/15);
  16.  
  17. }
  18.  
  19. px=py=10;
  20.  
  21. gs=tc=20;
  22.  
  23. ax=ay=15;
  24.  
  25. xv=yv=0;
  26.  
  27. trail=[];
  28.  
  29. tail = 5;
  30.  
  31. function game() {
  32.  
  33. px+=xv;
  34.  
  35. py+=yv;
  36.  
  37. if(px<0) {
  38.  
  39. px= tc-1;
  40.  
  41. }
  42.  
  43. if(px>tc-1) {
  44.  
  45. px= 0;
  46.  
  47. }
  48.  
  49. if(py<0) {
  50.  
  51. py= tc-1;
  52.  
  53. }
  54.  
  55. if(py>tc-1) {
  56.  
  57. py= 0;
  58.  
  59. }
  60.  
  61. ctx.fillStyle="black";
  62.  
  63. ctx.fillRect(0,0,canv.width,canv.height);
  64.  
  65.  
  66.  
  67. ctx.fillStyle="lime";
  68.  
  69. for(var i=0;i<trail.length;i++) {
  70.  
  71. ctx.fillRect(trail[i].x*gs,trail[i].y*gs,gs-2,gs-2);
  72.  
  73. if(trail[i].x==px && trail[i].y==py) {
  74.  
  75. tail = 5;
  76.  
  77. }
  78.  
  79. }
  80.  
  81. trail.push({x:px,y:py});
  82.  
  83. while(trail.length>tail) {
  84.  
  85. trail.shift();
  86.  
  87. }
  88.  
  89.  
  90.  
  91. if(ax==px && ay==py) {
  92.  
  93. tail++;
  94.  
  95. ax=Math.floor(Math.random()*tc);
  96.  
  97. ay=Math.floor(Math.random()*tc);
  98.  
  99. }
  100.  
  101. ctx.fillStyle="red";
  102.  
  103. ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2);
  104.  
  105. }
  106.  
  107. function keyPush(evt) {
  108.  
  109. switch(evt.keyCode) {
  110.  
  111. case 37:
  112.  
  113. xv=-1;yv=0;
  114.  
  115. break;
  116.  
  117. case 38:
  118.  
  119. xv=0;yv=-1;
  120.  
  121. break;
  122.  
  123. case 39:
  124.  
  125. xv=1;yv=0;
  126.  
  127. break;
  128.  
  129. case 40:
  130.  
  131. xv=0;yv=1;
  132.  
  133. break;
  134.  
  135. }
  136.  
  137. }
  138.  
  139. </script>
Advertisement
Add Comment
Please, Sign In to add comment