-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathindex.js
80 lines (70 loc) · 2.02 KB
/
index.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
const buttonColors = ["red", "green", "blue", "yellow"];
let level = 0;
let isStarted = false;
let sequencePattern = [];
let userSequencePattern = [];
document.addEventListener("keypress", () => {
if (!isStarted) {
document.body.style.backgroundColor = "#024";
document.getElementById("title").textContent = "Level " + level;
nextSequence();
isStarted = true;
}
});
document.querySelectorAll(".btn").forEach((btn) => {
btn.addEventListener("click", function () {
const userChosenColor = this.id;
userSequencePattern.push(userChosenColor);
playSound(userChosenColor);
userPress(userChosenColor);
buttonPressCheck(userSequencePattern.length - 1);
});
});
function buttonPressCheck(currentLevel) {
if (sequencePattern[currentLevel] === userSequencePattern[currentLevel]) {
if (sequencePattern.length === userSequencePattern.length) {
setTimeout(() => {
nextSequence();
}, 1000);
}
} else {
gameOver();
}
}
function nextSequence() {
userSequencePattern = [];
level++;
document.getElementById("title").textContent = "Level " + level;
const randomNumber = Math.floor(Math.random() * 4);
const randomColor = buttonColors[randomNumber];
sequencePattern.push(randomColor);
console.log(sequencePattern);
const button = document.getElementById(randomColor);
button.style.opacity = "0";
setTimeout(() => {
button.style.opacity = "1";
}, 100);
playSound(randomColor);
}
function playSound(colorName) {
const audio = new Audio("sounds/" + colorName + ".mp3");
audio.play();
}
function userPress(colorName) {
const button = document.getElementById(colorName);
button.classList.add("pressedButton");
setTimeout(() => {
button.classList.remove("pressedButton");
}, 100);
}
function gameOver() {
document.getElementById("title").textContent = "Game over!, press to start";
document.body.style.backgroundColor = "red";
restart();
}
function restart() {
isStarted = false;
level = 0;
sequencePattern = [];
userSequencePattern = [];
}