forked from SouravVerma-art/Simon-Says-Game
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
80 lines (67 loc) · 1.79 KB
/
Copy pathapp.js
File metadata and controls
80 lines (67 loc) · 1.79 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
let highScore = localStorage.getItem("highScore") || 0;
let userSq = [];
let gameSq = [];
let btns = ["yellow", "red", "purple", "green"];
let started = false;
let level = 0;
let h2 = document.querySelector(".h2txt");
let scoreDisplay = document.querySelector(".score");
scoreDisplay.innerText = `High Score: ${highScore}`;
let boxes = document.querySelectorAll(".box");
// Start Game
document.addEventListener("keypress", function(){
if(!started){
started = true;
levelUp();
}
});
// Flash Animation
function btnFlash(btn){
btn.classList.add("flash");
setTimeout(function(){
btn.classList.remove("flash");
}, 400);
}
// Level Up Logic
function levelUp(){
userSq = [];
level++;
h2.innerText = `Level ${level}`;
let randomIdx = Math.floor(Math.random() * 4);
let randomColor = btns[randomIdx];
gameSq.push(randomColor);
let randomBtn = document.querySelector(`#${randomColor}`);
btnFlash(randomBtn);
}
// Button Click
boxes.forEach(function(box){
box.addEventListener("click", function(){
let userColor = box.getAttribute("id");
userSq.push(userColor);
btnFlash(box);
checkAnswer(userSq.length - 1);
});
});
// Check Answer
function checkAnswer(idx){
if(userSq[idx] === gameSq[idx]){
if(userSq.length === gameSq.length){
setTimeout(levelUp, 1000);
}
} else {
if(level - 1 > highScore){
highScore = level - 1;
localStorage.setItem("highScore", highScore);
scoreDisplay.innerText = `High Score: ${highScore}`;
}
h2.innerText = `Game Over! Your score is ${level - 1}. Press any key to restart.`;
resetGame();
}
}
// Reset Game
function resetGame(){
started = false;
level = 0;
gameSq = [];
userSq = [];
}