Advertisement
Guest User

Untitled

a guest
Sep 13th, 2015
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. <!DOCTYPE HTML>
  2.  
  3. <html>
  4. <head>
  5. <title>Pastime</title>
  6. </head>
  7. <body>
  8. <canvas id="canvas" style="border: 1px solid black; position: fixed">This text is displaying if your browser is unable to display HTML5 canvas.</canvas>
  9. </body>
  10. <script>
  11. var Box = function(x, y, direction)
  12. {
  13. this.x = x;
  14. this.y = y;
  15. this.direction = direction;
  16. }
  17.  
  18. var canvas = document.getElementById("canvas");
  19. var ctx = canvas.getContext("2d");
  20. var snake = [];
  21. var head = new Box(100, 100, -1);
  22. canvas.width = window.innerWidth;
  23. canvas.height = window.innerHeight;
  24. ctx.fillStyle = "red";
  25.  
  26. snake.push(head);
  27. //addBox();
  28. //addBox();
  29. //addBox();
  30.  
  31.  
  32. Box.prototype.draw = function()
  33. {
  34. ctx.fillRect(this.x, this.y, 20, 20);
  35. }
  36.  
  37. function drawSnake()
  38. {
  39. //ctx.clearRect(0, 0, canvas.width, canvas.height);
  40. for (var i = 0; i < snake.length; i++)
  41. {
  42. switch (snake[i].direction)
  43. {
  44. case 0:
  45. snake[i].x -= 20;
  46. break;
  47. case 1:
  48. snake[i].y -= 20;
  49. break;
  50. case 2:
  51. snake[i].x += 20;
  52. break;
  53. case 3:
  54. snake[i].y += 20;
  55. break;
  56. }
  57. snake[i].draw();
  58. }
  59. }
  60.  
  61. function addBox()
  62. {
  63. var lastBox = snake[snake.length - 1];
  64. var direction = lastBox.direction;
  65. var x, y;
  66. switch (direction)
  67. {
  68. case 0:
  69. x = lastBox.x + 20;
  70. y = lastBox.y;
  71. break;
  72. case 1:
  73. x = lastBox.x;
  74. y = lastBox.y + 20;
  75. break;
  76. case 2:
  77. x = lastBox.x - 20;
  78. y = lastBox.y;
  79. break;
  80. case 3:
  81. x = lastBox.x;
  82. y = lastBox.y - 20;
  83. break;
  84. }
  85. snake.push(new Box(x, y, direction));
  86. }
  87.  
  88. document.addEventListener("keydown", function (event)
  89. {
  90. switch (event.keyCode)
  91. {
  92. case 37:
  93. head.direction = 0;
  94. break;
  95. case 38:
  96. head.direction = 1;
  97. break;
  98. case 39:
  99. head.direction = 2;
  100. break;
  101. case 40:
  102. head.direction = 3;
  103. break;
  104. }
  105. }, false);
  106.  
  107. function gameLoop()
  108. {
  109. setTimeout("gameLoop()", 100);
  110. drawSnake();
  111. }
  112.  
  113. gameLoop();
  114. </script>
  115. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement