-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
49 lines (36 loc) · 1.11 KB
/
Copy pathgame.js
File metadata and controls
49 lines (36 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Module import
import { SNAKE_SPEED, update as updateSnake, draw as drawSnake, getSnakeHead, snakeIntersection } from './game_modules/snake.js';
import { update as updateFood, draw as drawFood } from './game_modules/food.js';
import { outsideGrid } from './game_modules/grid.js';
let lastRenderTime = 0;
let gameOver = false;
const gameBoard = document.querySelector('#game-board');
function main(currentTime) {
if (gameOver) {
if (confirm('You lost. Press ok to restart')) {
return window.location.reload();
} else {
return
}
}
window.requestAnimationFrame(main);
const secondsSinceLastRender = (currentTime - lastRenderTime) / 1000;
if (secondsSinceLastRender < 1 / SNAKE_SPEED) return;
lastRenderTime = currentTime;
update();
draw();
}
window.requestAnimationFrame(main);
function update() {
updateSnake();
updateFood();
checkDeath();
}
function draw() {
gameBoard.innerHTML = '';
drawSnake(gameBoard);
drawFood(gameBoard);
}
function checkDeath() {
gameOver = outsideGrid(getSnakeHead()) || snakeIntersection();
}