-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
80 lines (68 loc) · 1.69 KB
/
index.js
File metadata and controls
80 lines (68 loc) · 1.69 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
let gameSeq=[];
let userSeq=[];
let started=false;
let level=0;
let buttons=['red','green','yellow','blue'];
let h2=document.querySelector(".heading-2");
let body=document.querySelector('body');
// key pressed
// random button will flash and level will be updated
document.addEventListener('keypress', function(){
if(started==false){
console.log("Game started");
started=true;
levelUp();
}
});
function btnFlash(btn) {
btn.classList.add('flash');
setTimeout(function(){
btn.classList.remove('flash');
},350);
}
function checkAnswer(index){
if(userSeq[index]==gameSeq[index]){
// middle
// last
if(userSeq.length==gameSeq.length){
setTimeout(levelUp,200);
}
}
else{
body.classList.add('alert');
setTimeout(() => {
body.classList.remove('alert');
}, 100);
h2.innerHTML=`Game Over! Your Score was <b>${level}</b><br>
Press any key to restart`;
reSet();
}
}
function levelUp(){
userSeq=[];
level++;
h2.innerText=`Level : ${level}`;
let random=Math.floor(Math.random() * 4);
let button=buttons[random];
let randomButton=document.querySelector(`.${button}`);
gameSeq.push(button);
btnFlash(randomButton);
}
function btnPress(){
// which button you have pressed
let btn=this;
let userColor=btn.getAttribute('id');
userSeq.push(userColor);
btnFlash(btn);
checkAnswer(userSeq.length-1);
}
let allButtons = document.querySelectorAll('.btn');
for(btn of allButtons){
btn.addEventListener('click',btnPress);
}
function reSet(){
started = false;
gameSeq=[];
userSeq=[];
level=0;
}