CHoff719

snake.html

May 31st, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.09 KB | None | 0 0
  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. ctx.fillStyle="red";
  51. ctx.fillRect(ax*gs,ay*gs,gs-2,gs-2);
  52. }
  53. function keyPush(evt) {
  54. switch(evt.keyCode) {
  55. case 37:
  56. xv=-1;yv=0;
  57. break;
  58. case 38:
  59. xv=0;yv=-1;
  60. break;
  61. case 39:
  62. xv=1;yv=0;
  63. break;
  64. case 40:
  65. xv=0;yv=1;
  66. break;
  67. }
  68. }
  69. </script>
Add Comment
Please, Sign In to add comment