-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
100 lines (80 loc) · 2.69 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { update as updateSnake, draw as drawSnake, getSnakeHead, getSnakeBody, snakeIntersection, SNAKE_SPEED, reset as resetSnake } from './snake.js'
import { update as updateFood, draw as drawFood, getScores, setHighScore, drawHighScore, reset as resetFood} from './food.js'
import { update as updateEnemy, draw as drawEnemy, enemyKilledSnake, drawEnemyNextPath, reset as resetEnemy } from './enemy.js';
import { outsideGrid, getGridSize } from './grid.js';
import { getGameUI, getDifficulty } from './game-ui.js';
let lastRenderTime = 0;
let gameOver = false;
let gamePaused = true;
const gameBoard = document.getElementById('game-board');
const scoreBoard = document.getElementById('score');
const levelBoard = document.getElementById('level');
const gameUI = document.getElementById('game-ui');
gameBoard.style.setProperty("--grid-size", getGridSize());
function main(currentTime) {
if (gameOver || gamePaused) {
setHighScore();
getGameUI(gameOver);
}
if (!gamePaused && !gameOver) {
window.requestAnimationFrame(main);
const secondsSinceLastRender = (currentTime - lastRenderTime) / 1000;
if (secondsSinceLastRender < 1 / SNAKE_SPEED) return
lastRenderTime = currentTime;
update();
if (!gameOver) draw();
}
}
window.requestAnimationFrame(main);
function update() {
checkDeath();
updateSnake();
updateFood();
updateEnemy();
}
function draw() {
// Emptying gameBoard
gameBoard.innerHTML = '';
// Setting Score with getScores()
scoreBoard.innerText = getScores().score;
levelBoard.innerText = `Level ${getScores().level}`;
// Drawing elements
drawHighScore(gameBoard);
// drawEnemyNextPath(gameBoard); // For debugging
drawEnemy(gameBoard);
drawFood(gameBoard);
drawSnake(gameBoard);
}
function checkDeath() {
let userDifficulty = getDifficulty();
if (userDifficulty == 'hard') {
gameOver = outsideGrid(getSnakeHead()) || snakeIntersection() || enemyKilledSnake(getSnakeBody());
} else {
gameOver = snakeIntersection() || enemyKilledSnake(getSnakeBody());
}
if (gameOver) setHighScore();
}
export function restart() {
resetFood();
resetEnemy();
resetSnake();
gameOver = false;
gamePaused = false;
window.requestAnimationFrame(main);
gameUI.classList.remove('active');
}
export function startGame() {
if (gameOver) restart();
else {
gamePaused = false;
resetEnemy();
window.requestAnimationFrame(main);
gameUI.classList.remove('active');
}
}
export function checkGameOver() {
return gameOver;
}
export function setGamePaused(bool) {
gamePaused = bool;
}