Advertisement
Guest User

Untitled

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