-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
99 lines (80 loc) · 2.54 KB
/
index.js
File metadata and controls
99 lines (80 loc) · 2.54 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const buttonColours = ["red", "blue", "green", "yellow"];
let gamePattern = [];
let userClickPattern = [];
let level = 0;
let start = false;
const title = document.getElementById("level-title");
document.addEventListener("keydown", function() {
if(!start) {
title.textContent = "Level " + level;
nextSequence();
start = true;
}
})
const btn = document.querySelectorAll(".btn");
btn.forEach((btn) => {
btn.addEventListener("click", function() {
const userChosenColor = btn.id;
userClickPattern.push(userChosenColor);
animatePress(userChosenColor);
playSound(userChosenColor);
checkAnswer(userClickPattern.length-1);
});
})
// aminmate flash color when clicking
function flash(color) {
// $("#" + randomChosenColour).fadeIn(100).fadeOut(100).fadeIn(100);
const el = document.getElementById(color);
el.animate(
[{opacity:1}, {opacity:0}, {opacity:1}],
{duration: 300, easing: "Linear" }
);
}
function nextSequence() {
userClickPattern = [];
level++;
title.textContent = "Level " + level;
let randomNumber = Math.floor(Math.random()*4);
let randomChosenColour = buttonColours[randomNumber];
// generate and random color and flash
gamePattern.push(randomChosenColour);
flash(randomChosenColour);
playSound(randomChosenColour);
console.log("game:" + gamePattern);
}
function playSound(name){
let audio = new Audio("sounds/" + name + ".mp3");
audio.play();
}
function animatePress(colour) {
const el = document.getElementById(colour);
el.classList.add("pressed");
setTimeout(function () {
el.classList.remove("pressed");
}, 100);
}
function checkAnswer(currentLevel) {
if (userClickPattern[currentLevel] === gamePattern[currentLevel]) {
console.log("success");
if (userClickPattern.length === gamePattern.length) {
setTimeout(function(){
nextSequence();
}, 1000);
};
}
else {
console.log("wrong");
playSound("wrong");
document.querySelector("body").classList.add("game-over");
setTimeout( function() {
document.querySelector("body").classList.remove("game-over");
}, 200);
title.textContent = "Game Over, Press Any key to Restart";
startOver();
}
}
function startOver() {
level = 0;
gamePattern = [];
start = false;
}