Guest User

Untitled

a guest
Jun 25th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.97 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Snake Game</title>
  5. </head>
  6. <body>
  7. <div id="score">0</div>
  8. <canvas id="gameCanvas" width="300" height="300"></canvas>
  9.  
  10. <script>
  11. /** CONSTANTS **/
  12. const CANVAS_BORDER_COLOUR = 'black';
  13. const CANVAS_BACKGROUND_COLOUR = "white";
  14. const SNAKE_COLOUR = 'lightgreen';
  15. const SNAKE_BORDER_COLOUR = 'darkgreen';
  16. const FOOD_COLOUR = 'red';
  17. const FOOD_BORDER_COLOUR = 'darkred';
  18.  
  19. let snake = [
  20. {x: 150, y: 150},
  21. {x: 140, y: 150},
  22. {x: 130, y: 150},
  23. {x: 120, y: 150},
  24. {x: 110, y: 150}
  25. ]
  26.  
  27. // The user's score
  28. let score = 0;
  29.  
  30. // Horizontal velocity
  31. let dx = 10;
  32. // Vertical velocity
  33. let dy = 0;
  34.  
  35. // Get the canvas element
  36. var gameCanvas = document.getElementById("gameCanvas");
  37. // Return a two dimensional drawing context
  38. var ctx = gameCanvas.getContext("2d");
  39. // Select the colour to fill the canvas
  40. ctx.fillStyle = CANVAS_BACKGROUND_COLOUR;
  41. // Select the colour for the border of the canvas
  42. ctx.strokestyle = CANVAS_BORDER_COLOUR;
  43. // Draw a "filled" rectangle to cover the entire canvas
  44. ctx.fillRect(0, 0, gameCanvas.width, gameCanvas.height);
  45. // Draw a "border" around the entire canvas
  46. ctx.strokeRect(0, 0, gameCanvas.width, gameCanvas.height);
  47.  
  48. // Start game
  49. main();
  50. // Create the first food location
  51. createFood();
  52. // Call changeDirection whenever a key is pressed
  53. document.addEventListener("keydown", changeDirection);
  54.  
  55. function main() {
  56.  
  57. if (didGameEnd()) return;
  58.  
  59. setTimeout(function onTick() {
  60. clearCanvas();
  61. drawFood();
  62. advanceSnake();
  63. drawSnake();
  64.  
  65. // Call main again
  66. main();
  67. }, 100)
  68. }
  69.  
  70. /**
  71. * Change the background colour of the canvas to CANVAS_BACKGROUND_COLOUR and
  72. * draw a border around it
  73. */
  74. function clearCanvas() {
  75. // Select the colour to fill the drawing
  76. ctx.fillStyle = CANVAS_BACKGROUND_COLOUR;
  77. // Select the colour for the border of the canvas
  78. ctx.strokestyle = CANVAS_BORDER_COLOUR;
  79.  
  80. // Draw a "filled" rectangle to cover the entire canvas
  81. ctx.fillRect(0, 0, gameCanvas.width, gameCanvas.height);
  82. // Draw a "border" around the entire canvas
  83. ctx.strokeRect(0, 0, gameCanvas.width, gameCanvas.height);
  84. }
  85.  
  86. /**
  87. * Returns true if the head of the snake touched another part of the game
  88. * or any of the walls
  89. */
  90. function didGameEnd() {
  91. for (let i = 4; i < snake.length; i++) {
  92. const didCollide = snake[i].x === snake[0].x && snake[i].y === snake[0].y
  93. if (didCollide) return true
  94. }
  95.  
  96. const hitLeftWall = snake[0].x < 0;
  97. const hitRightWall = snake[0].x > gameCanvas.width - 10;
  98. const hitToptWall = snake[0].y < 0;
  99. const hitBottomWall = snake[0].y > gameCanvas.height - 10;
  100.  
  101. return hitLeftWall || hitRightWall || hitToptWall || hitBottomWall
  102. }
  103.  
  104. /**
  105. * Draw the food on the canvas
  106. */
  107. function drawFood() {
  108. ctx.fillStyle = FOOD_COLOUR;
  109. ctx.strokestyle = FOOD_BORDER_COLOUR;
  110. ctx.fillRect(foodX, foodY, 10, 10);
  111. ctx.strokeRect(foodX, foodY, 10, 10);
  112. }
  113.  
  114. /**
  115. * Advances the snake by changing the x-coordinates of its parts
  116. * according to the horizontal velocity and the y-coordinates of its parts
  117. * according to the vertical veolocity
  118. */
  119. function advanceSnake() {
  120. // Create the new Snake's head
  121. const head = {x: snake[0].x + dx, y: snake[0].y + dy};
  122. // Add the new head to the beginning of snake body
  123. snake.unshift(head);
  124.  
  125.  
  126. const didEatFood = snake[0].x === foodX && snake[0].y === foodY;
  127. if (didEatFood) {
  128. // Increase score
  129. score += 10;
  130. // Display score on screen
  131. document.getElementById('score').innerHTML = score;
  132.  
  133. // Generate new food location
  134. createFood();
  135. } else {
  136. // Remove the last part of snake body
  137. snake.pop();
  138. }
  139. }
  140.  
  141. /**
  142. * Generates a random number that is a multiple of 10 given a minumum
  143. * and a maximum number
  144. * @param { number } min - The minimum number the random number can be
  145. * @param { number } max - The maximum number the random number can be
  146. */
  147. function randomTen(min, max) {
  148. return Math.round((Math.random() * (max-min) + min) / 10) * 10;
  149. }
  150.  
  151. /**
  152. * Creates random set of coordinates for the snake food.
  153. */
  154. function createFood() {
  155. // Generate a random number the food x-coordinate
  156. foodX = randomTen(0, gameCanvas.width - 10);
  157. // Generate a random number for the food y-coordinate
  158. foodY = randomTen(0, gameCanvas.height - 10);
  159.  
  160. // if the new food location is where the snake currently is, generate a new food location
  161. snake.forEach(function isOnSnake(part) {
  162. if (part.x == foodX && part.y == foodY) createFood();
  163. });
  164. }
  165.  
  166.  
  167. /**
  168. * Draws the snake on the canvas
  169. */
  170. function drawSnake() {
  171. // loop through the snake parts drawing each part on the canvas
  172. snake.forEach(drawSnakePart)
  173. }
  174. /**
  175. * Draws a part of the snake on the canvas
  176. * @param { object } snakePart - The coordinates where the part should be drawn
  177. */
  178. function drawSnakePart(snakePart) {
  179. // Set the colour of the snake part
  180. ctx.fillStyle = SNAKE_COLOUR;
  181. // Set the border colour of the snake part
  182. ctx.strokestyle = SNAKE_BORDER_COLOUR;
  183. // Draw a "filled" rectangle to represent the snake part at the coordinates
  184. // the part is located
  185. ctx.fillRect(snakePart.x, snakePart.y, 10, 10);
  186. // Draw a border around the snake part
  187. ctx.strokeRect(snakePart.x, snakePart.y, 10, 10);
  188. }
  189.  
  190. /**
  191. * Changes the vertical and horizontal velocity of the snake according to the
  192. * key that was pressed.
  193. * The direction cannot be switched to the opposite direction, to prevent the snake
  194. * from reversing
  195. * For example if the the direction is 'right' it cannot become 'left'
  196. * @param { object } event - The keydown event
  197. */
  198. function changeDirection(event) {
  199. const LEFT_KEY = 37;
  200. const RIGHT_KEY = 39;
  201. const UP_KEY = 38;
  202. const DOWN_KEY = 40;
  203.  
  204. const keyPressed = event.keyCode;
  205. if (keyPressed === LEFT_KEY && dx !== 10) {
  206. dx = -10;
  207. dy = 0;
  208. }
  209.  
  210. if (keyPressed === UP_KEY && dy !== 10) {
  211. dx = 0;
  212. dy = -10;
  213. }
  214.  
  215. if (keyPressed === RIGHT_KEY && dx !== -10) {
  216. dx = 10;
  217. dy = 0;
  218. }
  219.  
  220. if (keyPressed === DOWN_KEY && dy !== -10) {
  221. dx = 0;
  222. dy = 10;
  223. }
  224. }
  225. </script>
  226. </body>
  227. </html>
Add Comment
Please, Sign In to add comment