-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
83 lines (67 loc) · 2.06 KB
/
game.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
79
80
81
82
83
var buttonColors = ["red","blue","green","yellow"];
var gamePattern = [];
var userChosenPattern=[];
function nextSequence(){
var randomNumber = Math.floor(Math.random()*4);
var randomChosenClr = buttonColors[randomNumber];
gamePattern.push(randomChosenClr);
console.log(gamePattern);
$(`#${randomChosenClr}`).fadeOut(100).fadeIn(100)
playSound(randomChosenClr);
level=level+1;
$("h1").text(`Level ${level}`);
}
$(".btn").click(function(event){
var userChosenColor = $(this).attr("id");
userChosenPattern.push(userChosenColor);
playSound(userChosenColor);
animatePress(userChosenColor)
var lastindex = (userChosenPattern.length)-1;
checkAnswer(lastindex);
// var userChosenColor = event.target.id; My own method
// userChosenPattern.push(userChosenColor);
console.log(userChosenPattern);
})
function playSound(name){
var audioclick = new Audio(`sounds/${name}.mp3`);
audioclick.play();
}
function animatePress(currentColor){
$(`#${currentColor}`).addClass("pressed")
setTimeout(() => {
$(`#${currentColor}`).removeClass("pressed");
}, 100);
}
//game starting
var level = 0;
$(document).keydown(function(){
$("h1").text("Level 0");
nextSequence();
})
function checkAnswer(lastColor){
// console.log(gamePattern);
// console.log(userChosenPattern);
if(userChosenPattern[lastColor]===gamePattern[lastColor]){
console.log("success");
if(userChosenPattern.length===gamePattern.length){
setTimeout(() => {
nextSequence();
userChosenPattern=[];
}, 1000);
}
}
else{
$("body").addClass("game-over");
playSound("wrong");
$("h1").text("Game Over, Press Any Key to Restart")
setTimeout(() => {
$("body").removeClass("game-over");
}, 200);
startOver();
}
}
function startOver(){
gamePattern = [];
userChosenPattern=[];
level=0;
}