-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
61 lines (55 loc) · 1.6 KB
/
scripts.js
File metadata and controls
61 lines (55 loc) · 1.6 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
50
51
52
53
54
55
56
57
58
59
60
61
const dino = document.querySelector("#dino");
const cactus = document.querySelector("#cactus");
var score = 0;
// Start the Game
function startgame() {
if (cactus.classList != "cactus-animation") {
cactus.classList.add("cactus-animation");
}
}
// Stop the Game
function stopgame() {
cactus.classList.remove("cactus-animation");
}
// Make the Trex jump
function jump() {
if (dino.classList != "jump") {
dino.classList.add("jump");
// Calculate Dino Y Position
let dinoTop = parseInt(
window.getComputedStyle(dino).getPropertyValue("top")
);
// Calculate Cactus X Position
let cactusLeft = parseInt(
window.getComputedStyle(cactus).getPropertyValue("left")
);
// Approximate estimate of a successful jump
if (cactusLeft < 89 && cactusLeft > 0 && dinoTop == 150) {
score++;
}
setTimeout(function () {
dino.classList.remove("jump");
}, 300);
}
}
// Detect Collision
let isAlive = setInterval(function () {
// Calculate Dino Y Position
let dinoTop = parseInt(window.getComputedStyle(dino).getPropertyValue("top"));
// Calculate Cactus X Position
let cactusLeft = parseInt(
window.getComputedStyle(cactus).getPropertyValue("left")
);
if (cactusLeft < 50 && cactusLeft > 0 && dinoTop >= 140) {
// Give the alert
alert("Game Over! You scored " + score + ".");
// Re-initialize the score
score = 0;
// Stop the game
stopgame();
}
}, 10);
// Add Keyboard button press functionality
document.addEventListener("keydown", function (event) {
jump();
});