Advertisement
Guest User

JS Snake Score

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