-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (62 loc) · 1.66 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
var buttonColors=["red","blue","green","yellow"];
var gamePattern=[];
var userChosenColors=[];
var level=0;
var started=false;
$(document).on("keypress",function(){
if(!started){
nextSequence();
started=true;
}
});
$(".btn").on("click",function(event){
var userChosenColour = $(this).attr("id");
userChosenColors.push(userChosenColour);
playSound(userChosenColour);
animatePress(userChosenColour);
checkAnswer(userChosenColors.length);
});
function nextSequence(){
userChosenColors=[];
var randomNumber=Math.floor(Math.random()*4);
var randomChosenColor=buttonColors[randomNumber];
gamePattern.push(randomChosenColor);
$("#" + randomChosenColor).fadeIn(100).fadeOut(100).fadeIn(100);
$("h1").text("Level "+level++);
var soundName=randomChosenColor;
playSound(soundName);
}
function checkAnswer(size){
if(gamePattern[size-1]===userChosenColors[size-1]){
if(gamePattern.length===userChosenColors.length){
setTimeout(function(){
nextSequence();}
,500);
}
}
else{
playSound("wrong");
$("body").addClass("game-over");
$("h1").text("Game Over!!Press any key to restart!!");
setTimeout(function(){
$("body").removeClass("game-over");}
,500);
startOver();
}
}
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(colorName){
$("#"+colorName).addClass("pressed");
setTimeout(function(){
$("#"+colorName).removeClass("pressed");}
,100);
}
function startOver(){
userChosenColors=[];
gamePattern=[];
level=1;
started=false;
}