-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
66 lines (60 loc) · 1.69 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
var buttonColours = ["red", "blue", "green", "yellow"];
var gamePattern = [];
var userClickedPattern = [];
var started = false;
var currentLevel = 0;
$(document).keydown(function(){
if (!started){
$("#level-title").text("Level " + currentLevel.toString());
nextSequence();
}
});
$(".btn").click(function(){
var userChosenColor = $(this).attr("id");
userClickedPattern.push(userChosenColor);
animatePressed(userChosenColor);
playSound(userChosenColor);
if (userClickedPattern.length == gamePattern.length){
validate();
}
});
function nextSequence(){
currentLevel++;
$("#level-title").text("Level " + currentLevel.toString());
started = true;
if (started)
{
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColours[randomNumber];
gamePattern.push(randomChosenColour);
animatePressed(randomChosenColour);
playSound(randomChosenColour);
console.log("end of nextSequence(), gamePatter: " + gamePattern)
}
}
function playSound(colour){
var audio = new Audio("sounds/" + colour + ".mp3");
audio.play();
}
function animatePressed(currentColour){
$("." + currentColour).addClass("pressed");
setTimeout(function(){
$("." + currentColour).removeClass("pressed");
}, 200);
}
function validate(){
var miss = false;
for (var i = 0; i < gamePattern.length; i++){
if (gamePattern[i] != userClickedPattern[i]){
miss = true;
}
}
if (miss){
$("#level-title").text("Game over.")
} else {
userClickedPattern = [];
setTimeout(function(){
nextSequence();
}, 1000);
}
}