-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
90 lines (83 loc) · 2.4 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
let game = {
score: 0,
bestScore: 0,
speed: 200,
frame: false,
reset: function () {
snakeElements = [];
game.setInitialSpeed();
snake.reset();
this.resetScore();
grid.reset();
snake.createNew();
snake.show();
food.generateNew();
food.show();
},
//main function where everything happens :)
start: function () {
function main(timestamp) {
let gameOver;
if (!start || timestamp - start >= game.speed) {
start = timestamp;
snake.changeDirection();
snake.move();
snake.show();
gameOver = game.checkGameOver();
snake.checkFood();
food.show();
game.writeScore();
game.writeBestScore();
}
if (!gameOver) window.requestAnimationFrame(main);
}
this.animationFrame = window.requestAnimationFrame(main);
},
// Setting initial excecution rate of the game, the higher the rate, the lower the speed
setInitialSpeed: function () {
let speedLevel = document.querySelector(
'input[name="speed-level"]:checked'
).value;
switch (speedLevel) {
case "1":
this.speed = 400;
break;
case "2":
this.speed = 200;
break;
case "3":
this.speed = 100;
break;
default:
break;
}
},
// Check if snake collided with frame, or with itself
checkGameOver: function () {
let gameOver = false;
if (snake.checkBite() || snake.checkCollision()) {
gameOver = true;
document.querySelector("#background-music").pause();
document.querySelector("#background-music").currentTime = 0;
window.cancelAnimationFrame(this.animationFrame);
document.querySelector(".pop-up h1").textContent = "Game Over !!!";
document.querySelector("#mask").classList.remove("hidden");
document.querySelector(".pop-up").classList.remove("hidden");
document.querySelector(".grid").classList.add("blurred");
}
return gameOver;
},
// Write current score on the interface
writeScore: function () {
let scoreElement = document.querySelector("#score");
scoreElement.textContent = `Score: ${this.score}`;
},
resetScore: function () {
this.score = 0;
},
// Write best score on the interface
writeBestScore: function () {
let bestScoreElement = document.querySelector("#best-score");
bestScoreElement.textContent = `Best score: ${this.bestScore}`;
},
};