-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
71 lines (60 loc) · 1.76 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
import {update as updateSnake, draw as drawSnake, getSnakeHead, snakeIntersection} from "./snake.js";
import {update as updateFood, draw as drawFood} from "./food.js";
import {outsideBoard} from "./board.js";
export {difficultySelect};
let lastRenderTime;
let gameOver = false;
const board = document.getElementById('board');
const difficultySelect = document.getElementsByClassName('difficulty');
const easy = document.getElementById('easy');
const normal = document.getElementById('normal');
const hard = document.getElementById('hard');
easy.addEventListener('click', setDifficulty);
normal.addEventListener('click', setDifficulty);
hard.addEventListener('click', setDifficulty);
var difficulty;
window.requestAnimationFrame(game);
function game(currentTime) {
if (gameOver) {
window.location = '/Snake';
return;
}
window.requestAnimationFrame(game);
const secondsSinceLastRender = (currentTime - lastRenderTime) / 1000;
const SNAKE_SPEED = setSpeed();
if (secondsSinceLastRender < 1 / SNAKE_SPEED) return;
lastRenderTime = currentTime;
update();
draw();
}
function setDifficulty(event) {
difficultySelect[0].classList.remove('active');
difficulty = event.target.id;
}
function setSpeed() {
let snakeSpeed;
switch (difficulty) {
case 'easy':
snakeSpeed = 10;
break;
case 'normal':
snakeSpeed = 15;
break;
case 'hard':
snakeSpeed = 20;
break;
} return snakeSpeed;
}
function update() {
updateSnake();
updateFood();
checkFail();
}
function draw() {
board.innerHTML = "";
drawSnake(board);
drawFood(board);
}
function checkFail() {
gameOver = outsideBoard(getSnakeHead()) || snakeIntersection();
}