-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
131 lines (96 loc) · 2.87 KB
/
index.js
File metadata and controls
131 lines (96 loc) · 2.87 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
var colors = [];
var level = 0;
var index = 0;
var buttons_disabled = true;
var game_started = false;
$(document).ready(function () {
$("body").bind('keypress',function(e) {
if (e.keyCode == 65 || e.keyCode == 97 && game_started == false) {
startGame();
}
});
$("#level-title").on("click", function () {
if (game_started == false) {
startGame();
$(this).css("cursor", "default");
}
});
function startGame() {
resetGame();
$("body").removeClass("game-over");
game_started = true;
newLevel();
}
async function flashColors(colors) {
for (let i = 0; i < colors.length; i++) {
const element = colors[i];
colorFlash(element);
await sleep(1000);
}
buttons_disabled = false;
}
function addColor(color_array) {
color_array.push(Math.floor(Math.random()*4))
}
var buttonColors = ["green", "red", "yellow", "blue"];
function colorFlash(color_number) {
$("#" + buttonColors[color_number]).fadeIn(500).fadeOut(500).fadeIn(500);
audio = new Audio("sounds/" + buttonColors[color_number] + ".mp3");
audio.play()
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function newLevel() {
index = 0;
addColor(colors);
flashColors(colors);
level++;
$("#level-title").text("Level : " + (parseInt(level)));
await sleep(2000);
}
function Lose() {
var audio = new Audio("sounds/wrong.mp3");
audio.play();
$("body").addClass("game-over");
$("#level-title").text("Click here or press 'A' to start again.");
$("#level-subtitle").text("Wrong, You lose!");
game_started = false;
buttons_disabled = true;
$("#level-title").css("cursor", "pointer");
}
function resetGame(){
index = 0;
colors = [];
level = 0;
$("#level-subtitle").text("");
}
async function checkCorrect(color) {
if (colors[index++] == color) {
var correct_sound = new Audio("sounds/"+ buttonColors[color] +".mp3")
correct_sound.play();
if (index == colors.length)
{
var correct_sound = new Audio("sounds/right.mp3");
correct_sound.play();
buttons_disabled = true;
await sleep(1000);
newLevel();
}
}
else{
Lose();
}
}
$(".btn").click(async function (e) {
if (!buttons_disabled) {
if (game_started) {
var color = buttonColors.indexOf($(this)[0].id);
$(this).toggleClass("pressed");
await sleep(100);
$(this).toggleClass("pressed");
checkCorrect(color);
}
}
});
});