-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
79 lines (60 loc) · 1.63 KB
/
script.js
File metadata and controls
79 lines (60 loc) · 1.63 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
let gameSeq = [];
let userSeq = [];
let colors = ["red", "green", "blue", "yellow"];
let level = 0;
let started = false;
let h2 = document.querySelector("#level");
let scoreDisplay = document.querySelector("#score");
document.addEventListener("keypress", function () {
if (!started) {
started = true;
nextlevel();
}
});
function nextlevel() {
userSeq = [];
level++;
h2.innerText = "Level " + level;
score = level - 1;
scoreDisplay.innerText = "Score: " + score;
let randColor = colors[Math.floor(Math.random() * 4)];
gameSeq.push(randColor);
flashBtn(randColor);
}
function flashBtn(color) {
let btn = document.getElementById(color);
btn.classList.add("flash");
setTimeout(() => {
btn.classList.remove("flash");
}, 300);
}
let allBtns = document.querySelectorAll(".btn");
allBtns.forEach((btn) => {
btn.addEventListener("click", function () {
let color = this.id;
userSeq.push(color);
flashBtn(color);
checkAnswer(userSeq.length - 1);
});
});
function checkAnswer(index) {
if (userSeq[index] === gameSeq[index]) {
if (userSeq.length === gameSeq.length) {
setTimeout(nextlevel, 1000);
}
} else {
h2.innerText = "Game Over! Press any key to restart";
scoreDisplay.innerText = "Score: " + score;
document.body.style.backgroundColor = "red";
setTimeout(() => {
document.body.style.backgroundColor = "#222";
}, 300);
reset();
}
}
function reset() {
started = false;
level = 0;
gameSeq = [];
userSeq = [];
}