-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
116 lines (102 loc) · 2.58 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
gamePattern = [];
userPattern = [];
buttonColors = ["red", "blue", "green", "yellow"];
// PRE-GAME SETTINGS
var started = false;
var level = 0;
$(document).keypress(function(){
if (!started){
nextSequence();
started = true;
}
})
// GENERATE GAME PATTERN
function nextSequence(){
// Set up level stats
level++;
$("h1").text("Level" + " " + level)
userPattern = [];
// Pick random color
var randomNumber = Math.floor(Math.random() * 4);
var randomColor = buttonColors[randomNumber];
gamePattern.push(randomColor);
// Loop through color array
interval = 500
var loop = function () {
return new Promise(function (outerResolve) {
var promise = Promise.resolve();
var i = 0;
var next = function () {
$("#" + gamePattern[i]).fadeOut(100).fadeIn(100);
playSound(gamePattern[i]);
if (++i < gamePattern.length) {
promise = promise.then(function () {
return new Promise(function (resolve) {
setTimeout(function () {
resolve();
next();
}, interval);
});
});
} else {
outerResolve();
}
};
next();
});
};
loop().then(function () {
console.log(gamePattern);
});
}
// REGISTER USER PATTERN
$(".btn").click(function (){
// var userColor = $(this).attr("id");
var userColor = this.id;
userPattern.push(userColor);
animatePress(userColor);
playSound(userColor);
// console.log(userPattern);
if(started){
checkAnswer(userPattern.length-1);
} else {
console.log("game hasn't started yet");
}
})
function animatePress(color){
$("#" + color).addClass("pressed");
setTimeout(function(){
// $("#" + color).removeClass("pressed");
$("#" + color).removeClass("pressed");
}, 100);
}
// CONTROL ALL SOUNDS
function playSound(filename){
var audio = new Audio("sounds/" + filename + ".mp3");
audio.play();
}
// CHECK USER PATTERN AGAINST GAME PATTERN
function checkAnswer(currentLevel){
if(userPattern[currentLevel] === gamePattern[currentLevel]){
if(userPattern.length === gamePattern.length){
setTimeout(function(){
nextSequence();
}, 1000);
}
} else {
playSound("wrong");
$("body").addClass("game-over");
$("h1").text("Game Over! You Reached Level " + level + ". Press Any Key to Restart.");
setTimeout(function(){
// $("#" + color).removeClass("pressed");
$("body").removeClass("game-over");
}, 200);
startOver();
}
}
// RESET
function startOver(){
started = false;
level = 0;
gamePattern = [];
}