-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
69 lines (60 loc) · 1.72 KB
/
script.js
File metadata and controls
69 lines (60 loc) · 1.72 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
const colors = ["green", "red", "yellow", "blue"];
let sequence = [];
let playerSequence = [];
let level = 0;
const startButton = document.getElementById('start-button');
const colorButtons = document.querySelectorAll('.color-button');
startButton.addEventListener('click', startGame);
colorButtons.forEach(button => {
button.addEventListener('click', event => {
const color = event.target.id;
playerSequence.push(color);
playSound(color);
checkPlayerSequence();
});
});
function startGame() {
level = 0;
sequence = [];
playerSequence = [];
nextLevel();
}
function nextLevel() {
level++;
playerSequence = [];
const nextColor = colors[Math.floor(Math.random() * colors.length)];
sequence.push(nextColor);
playSequence();
}
function playSequence() {
let delay = 0;
sequence.forEach((color, index) => {
setTimeout(() => {
playSound(color);
animateButton(color);
}, delay);
delay += 1000;
});
}
function playSound(color) {
const audio = new Audio(`sounds/${color}.mp3`);
audio.play();
}
function animateButton(color) {
const button = document.getElementById(color);
button.classList.add('active');
setTimeout(() => {
button.classList.remove('active');
}, 500);
}
function checkPlayerSequence() {
const currentLevel = playerSequence.length;
if (playerSequence[currentLevel - 1] !== sequence[currentLevel - 1]) {
alert('Game Over! You reached level ' + level);
startGame();
return;
}
if (playerSequence.length === sequence.length) {
setTimeout(nextLevel, 1000);
}
}