-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
77 lines (63 loc) · 2.34 KB
/
Copy pathindex.js
File metadata and controls
77 lines (63 loc) · 2.34 KB
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
var gamePattern = [];
var buttoncolours = ["red","green","blue","yellow"];
var userClickedPattern = [];
var level = 0;
var started = false;
$(document).keypress(function(){
if (!started) {
$("#level-title").text("Level " + level);
nextSequence();
started = true;
}
})
function nextSequence(){
userClickedPattern = []; // redeclaring to empty array to input pattern
var randomNumber = Math.floor(Math.random() * 4); // random number from 0-4
var randomcolour = buttoncolours[randomNumber]; // index array to get random colour
gamePattern.push(randomcolour); // add colour to array
$("#" + randomcolour).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100); // fade out pressed button
playSound(randomcolour); // play the button's sound
level ++; // increment level and change text in title
$('#level-title').text("Level " + level);
}
$('.btn').click(function(){
var userChosencolour = $(this).attr('id'); // get id for clicked button and add to user choice list pattern
userClickedPattern.push(userChosencolour);
playSound(userChosencolour); // play sound and animate button press with changing class
animatePress(userChosencolour);
checkAnswer(userClickedPattern.length-1);
})
function playSound(name){ // Playing sound from folder for the button
audio = new Audio('sounds/' + name +'.mp3');
audio.play()
}
function animatePress(currentcolour){
$("#" + currentcolour).addClass('pressed')
setTimeout(function () {
$("#" + currentcolour).removeClass("pressed");
}, 100);
}
function checkAnswer(currentLevel) {
if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) { // check each element by element is equal
// across both the user choices and the game correct pattern.
if (userClickedPattern.length === gamePattern.length){ // once equal in length (all choices made) - generate
// next sequence.
setTimeout(function () {
nextSequence();
}, 1000);
}
} else { // if not same colour chosen. Then wrong. change html text and sound.
playSound("wrong");
$("body").addClass("game-over");
$("#level-title").text("Game Over, Press Any Key to Restart");
setTimeout(function () {
$("body").removeClass("game-over");
}, 200);
startOver();
}
}
function startOver() {
level = 0;
gamePattern = [];
started = false;
}