-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
59 lines (50 loc) · 1.31 KB
/
game.js
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
50
51
52
53
54
55
56
57
58
59
import {
update as updateSnake,
render as renderSnake,
snakeSpeed,
getSnakeHead,
snakeOverlap,
} from "./js/snake.js";
import { update as updateFood, render as renderFood } from "./js/food.js";
import { outsideSurface } from "./js/surface.js";
let prevRender = 0;
let gameOver = false;
let bodyCount = document.getElementsByClassName("snake");
const gameSurface = document.getElementById("game-surface");
// game loop
function main(currentTime) {
let gameScore = bodyCount.length - 1;
if (gameOver) {
if (
confirm(
`You lost! 🐍💀\nYour score was ${gameScore}!\nPress OK to restart.`
)
) {
window.location.reload();
}
return;
}
window.requestAnimationFrame(main);
const secsSincePrevRender = (currentTime - prevRender) / 1000;
if (secsSincePrevRender < 1 / snakeSpeed) return;
prevRender = currentTime;
update();
render();
}
window.requestAnimationFrame(main);
// calls functions to update data for the game surface
function update() {
updateSnake();
updateFood();
snakeFail();
}
// calls functions to draw updated game to surface
function render() {
gameSurface.innerHTML = "";
renderSnake(gameSurface);
renderFood(gameSurface);
}
// function to fail game
function snakeFail() {
gameOver = outsideSurface(getSnakeHead()) || snakeOverlap();
}