-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
96 lines (80 loc) · 2.49 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
var gamePattern = [];
var userClickedPattern = [];
var gameStarted = false;
var level = 0;
var buttonColours = ['red', 'blue', 'green', 'yellow'];
// handle pressing any key to start the game
$(document).keypress(function () {
startGame(gameStarted);
gameStarted = true;
});
// handle clicking any button and adding to user sequence
$('.btn').click(function () {
// condition to prevent clicking on buttons when the game hasn't been started yet
if (gameStarted) {
// pushing user selected button into userSequence array
var userChosenColour = this.id;
userClickedPattern.push(userChosenColour);
// click effects (audio -> depending on color of button) / (flash animation)
animatePress(userChosenColour);
playAudio(userChosenColour);
// checking user answer after every click
checkAnswer(userClickedPattern.length - 1);
}
});
function checkAnswer(currentLevel) {
// checking if the user clicked the right button
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
// checking if the user has finished the sequence to call the nextSequence() function
if (userClickedPattern.length === gamePattern.length) {
setTimeout(function () {
nextSequence();
}, 1000);
}
} else {
// if the answer is wrong the game restarts
startOver();
}
}
function nextSequence() {
// empty user click pattern and click count every level
userClickedPattern = [];
clickCount = 0;
// selecting a button randomly and pushing it into gamePattern array
var randomNumber = Math.floor(Math.random() * 4);
var randomChosenColour = buttonColours[randomNumber];
gamePattern.push(randomChosenColour);
// flash the selected button
$('#' + randomChosenColour)
.fadeOut(100)
.fadeIn(100);
// play audio for selected button
playAudio(randomChosenColour);
// increasing the level
level++;
$('h1').text('Level ' + level);
}
function playAudio(name) {
var audio = new Audio('sounds/' + name + '.mp3');
audio.play();
}
function animatePress(currentColour) {
setTimeout(function () {
$('#' + currentColour).toggleClass('pressed');
}, 100);
$('#' + currentColour).toggleClass('pressed');
}
function startGame(bool) {
if (!bool) nextSequence();
}
function startOver() {
gameStarted = false;
$('h1').text('Game Over, Press Any Key to Restart');
playAudio('wrong');
level = 0;
gamePattern = [];
setTimeout(function () {
$('body').toggleClass('game-over');
}, 200);
$('body').toggleClass('game-over');
}