forked from FOSS-Community/frontend-session-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
86 lines (70 loc) · 2.09 KB
/
script.js
File metadata and controls
86 lines (70 loc) · 2.09 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
80
81
82
83
84
85
86
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)
const button = document.getElementById(randomColor);
button.style.opacity = "0";
setTimeout(() => {
button.style.opacity = "1";
},100)
playSound(randomColor);
}
function userPress(colorName){
const button = document.getElementById(colorName)
button.classList.add("pressedButton");
setTimeout(() => {
button.classList.remove("pressedButton");
}, 100);
}
function playSound(colorName){
const audio = new Audio("sounds/"+ colorName + ".mp3");
audio.play();
}
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 = [];
}