Skip to content

Commit d31d54f

Browse files
committed
add event listener
1 parent 1b22edf commit d31d54f

File tree

1 file changed

+34
-32
lines changed

1 file changed

+34
-32
lines changed

Source-Code/DinosaurGame/script.js

+34-32
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,39 @@
1-
const character = document.querySelector(".dino");
2-
const block = document.querySelector(".cactus");
1+
document.addEventListener("DOMContentLoaded", () => {
2+
const character = document.querySelector(".dino");
3+
const block = document.querySelector(".cactus");
34

4-
const jump = () => {
5-
// Add class to initiate jump
6-
character.classList.add("animate");
5+
const jump = () => {
6+
// Add class to initiate jump
7+
character.classList.add("animate");
78

8-
// Remove class after animation duration (500ms)
9-
setTimeout(() => {
10-
character.classList.remove("animate");
11-
}, 500);
12-
};
9+
// Remove class after animation duration (500ms)
10+
setTimeout(() => {
11+
character.classList.remove("animate");
12+
}, 500);
13+
};
1314

14-
// Trigger jump on spacebar press
15-
document.addEventListener("keydown", (event) => {
16-
if (event.code === "Space") {
17-
jump();
18-
}
19-
});
20-
21-
// Check for collision
22-
const checkDead = setInterval(() => {
23-
const blockLeft = parseInt(
24-
window.getComputedStyle(block).getPropertyValue("left")
25-
);
26-
const characterTop = parseInt(
27-
window.getComputedStyle(character).getPropertyValue("top")
28-
);
15+
// Trigger jump on spacebar press
16+
document.addEventListener("keydown", (event) => {
17+
if (event.code === "Space") {
18+
jump();
19+
}
20+
});
2921

3022
// Check for collision
31-
if (blockLeft < 20 && blockLeft > 0 && characterTop >= 178) {
32-
block.style.animation = "none";
33-
block.style.display = "none";
34-
alert("Uh..Oh, you lose.");
35-
clearInterval(checkDead); // Stop checking for collisions
36-
}
37-
}, 100);
23+
const checkDead = setInterval(() => {
24+
const blockLeft = parseInt(
25+
window.getComputedStyle(block).getPropertyValue("left")
26+
);
27+
const characterTop = parseInt(
28+
window.getComputedStyle(character).getPropertyValue("top")
29+
);
30+
31+
// Check for collision
32+
if (blockLeft < 20 && blockLeft > 0 && characterTop >= 178) {
33+
block.style.animation = "none";
34+
block.style.display = "none";
35+
alert("Uh..Oh, you lose.");
36+
clearInterval(checkDead); // Stop checking for collisions
37+
}
38+
}, 100);
39+
});

0 commit comments

Comments
 (0)