Guest User

Untitled

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