snake game html code

Solutions on MaxInterview for snake game html code by the best coders in the world

showing results for - "snake game html code"
Julia
30 Sep 2017
1
2<!DOCTYPE html>
3<html>
4<head>
5  <title></title>
6  <style>
7  html, body {
8    height: 100%;
9    margin: 0;
10  }
11
12  body {
13    background: black;
14    display: flex;
15    align-items: center;
16    justify-content: center;
17  }
18  canvas {
19    border: 1px solid white;
20  }
21  </style>
22</head>
23<body>
24<canvas width="400" height="400" id="game"></canvas>
25<script>
26var canvas = document.getElementById('game');
27var context = canvas.getContext('2d');
28
29var grid = 16;
30var count = 0;
31  
32var snake = {
33  x: 160,
34  y: 160,
35  
36  // snake velocity. moves one grid length every frame in either the x or y direction
37  dx: grid,
38  dy: 0,
39  
40  // keep track of all grids the snake body occupies
41  cells: [],
42  
43  // length of the snake. grows when eating an apple
44  maxCells: 4
45};
46var apple = {
47  x: 320,
48  y: 320
49};
50
51// get random whole numbers in a specific range
52// @see https://stackoverflow.com/a/1527820/2124254
53function getRandomInt(min, max) {
54  return Math.floor(Math.random() * (max - min)) + min;
55}
56
57// game loop
58function loop() {
59  requestAnimationFrame(loop);
60
61  // slow game loop to 15 fps instead of 60 (60/15 = 4)
62  if (++count < 4) {
63    return;
64  }
65
66  count = 0;
67  context.clearRect(0,0,canvas.width,canvas.height);
68
69  // move snake by it's velocity
70  snake.x += snake.dx;
71  snake.y += snake.dy;
72
73  // wrap snake position horizontally on edge of screen
74  if (snake.x < 0) {
75    snake.x = canvas.width - grid;
76  }
77  else if (snake.x >= canvas.width) {
78    snake.x = 0;
79  }
80  
81  // wrap snake position vertically on edge of screen
82  if (snake.y < 0) {
83    snake.y = canvas.height - grid;
84  }
85  else if (snake.y >= canvas.height) {
86    snake.y = 0;
87  }
88
89  // keep track of where snake has been. front of the array is always the head
90  snake.cells.unshift({x: snake.x, y: snake.y});
91
92  // remove cells as we move away from them
93  if (snake.cells.length > snake.maxCells) {
94    snake.cells.pop();
95  }
96
97  // draw apple
98  context.fillStyle = 'red';
99  context.fillRect(apple.x, apple.y, grid-1, grid-1);
100
101  // draw snake one cell at a time
102  context.fillStyle = 'green';
103  snake.cells.forEach(function(cell, index) {
104    
105    // drawing 1 px smaller than the grid creates a grid effect in the snake body so you can see how long it is
106    context.fillRect(cell.x, cell.y, grid-1, grid-1);  
107
108    // snake ate apple
109    if (cell.x === apple.x && cell.y === apple.y) {
110      snake.maxCells++;
111
112      // canvas is 400x400 which is 25x25 grids 
113      apple.x = getRandomInt(0, 25) * grid;
114      apple.y = getRandomInt(0, 25) * grid;
115    }
116
117    // check collision with all cells after this one (modified bubble sort)
118    for (var i = index + 1; i < snake.cells.length; i++) {
119      
120      // snake occupies same space as a body part. reset game
121      if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y) {
122        snake.x = 160;
123        snake.y = 160;
124        snake.cells = [];
125        snake.maxCells = 4;
126        snake.dx = grid;
127        snake.dy = 0;
128
129        apple.x = getRandomInt(0, 25) * grid;
130        apple.y = getRandomInt(0, 25) * grid;
131      }
132    }
133  });
134}
135
136// listen to keyboard events to move the snake
137document.addEventListener('keydown', function(e) {
138  // prevent snake from backtracking on itself by checking that it's 
139  // not already moving on the same axis (pressing left while moving
140  // left won't do anything, and pressing right while moving left
141  // shouldn't let you collide with your own body)
142  
143  // left arrow key
144  if (e.which === 37 && snake.dx === 0) {
145    snake.dx = -grid;
146    snake.dy = 0;
147  }
148  // up arrow key
149  else if (e.which === 38 && snake.dy === 0) {
150    snake.dy = -grid;
151    snake.dx = 0;
152  }
153  // right arrow key
154  else if (e.which === 39 && snake.dx === 0) {
155    snake.dx = grid;
156    snake.dy = 0;
157  }
158  // down arrow key
159  else if (e.which === 40 && snake.dy === 0) {
160    snake.dy = grid;
161    snake.dx = 0;
162  }
163});
164
165// start the game
166requestAnimationFrame(loop);
167</script>
168</body>
169</html>