-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
92 lines (81 loc) · 2.19 KB
/
app.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
91
92
let gameSeq = [];
let userSeq = [];
let scores = [];
let started = false;
let level = 0;
function startGame() {
if (!started) {
levelUp();
started = true;
}
}
document.addEventListener("keypress", startGame);
document.addEventListener("click", startGame);
function levelUp() {
userSeq = [];
document.querySelector("h3").innerText = `Level ${++level}`;
let randomColor = getRandomColor();
gameSeq.push(randomColor);
setTimeout (() => {
flashSequence(gameSeq, false);
}, 300);
}
function flashSequence(gameSeq, flashAll) {
if (flashAll) {
let time = 300;
for (let btns of gameSeq) {
setTimeout(() => {
flash(btns);
}, time);
time += 600;
}
} else {
flash(gameSeq[gameSeq.length - 1]);
}
}
function getRandomColor() {
return Math.ceil(Math.random() * 4);
}
function flash(num) {
let button = document.querySelector(`#button-${num}`);
button.style.backgroundColor = "white";
setTimeout(() => {
button.style.backgroundColor = "";
}, 300);
}
function btnPressed() {
let btnNumber = this.id[this.id.length - 1];
flash(btnNumber);
userSeq.push(btnNumber);
checkAnswer(userSeq.length - 1);
}
let allbtns = document.querySelectorAll(".button");
for (let btn of allbtns) {
btn.addEventListener("click", btnPressed);
}
function checkAnswer(index) {
if(userSeq[index] == gameSeq[index]) {
if(userSeq.length == gameSeq.length) {
setTimeout(levelUp, 700);
}
} else {
scores.push(level - 1);
let highestScore = scores.reduce((highest, current) => (highest > current ? highest : current));
document.querySelector("h3").innerHTML = `Game Over! You score was <b>${level - 1}</b> <br> Your highest score is <b>${highestScore}</b> <br> Press any key to continue`;
bodyFlash();
reset();
}
}
function bodyFlash() {
let body = document.querySelector("body");
body.style.backgroundColor = "red";
setTimeout(() => {
body.style.backgroundColor = "";
}, 200);
}
function reset() {
started = false;
level = 0;
gameSeq = [];
userSeq = [];
}