-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
126 lines (108 loc) · 2.54 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
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
const buttons = [...$("div[type='button']")];
const soundsLoc = "sounds/";
const soundButtons = [];
var gameSequence = [];
var roundSeguence = [];
initialize();
function initialize(){
gameSequence=[];
roundSeguence=[];
navigator.userAgent.match(/Android/i)?mobileHandler():pcHandler();
}
function pcHandler(){
$('body').on("keypress",function(){
$('body').unbind();
bindButtons();
$("#level-title").text("Repeat the pattern");
nextSeq();
});
}
function mobileHandler(){
//$("#level-title").text("-> Start <-");
$("#level-title").on("click",function(){
$("#level-title").unbind();
bindButtons();
$("#level-title").text("Repeat the pattern");
nextSeq();
});
}
///sound buttons constructor
function Button(id, soundSrc,targt) {
this.id = id;
this.targt = targt;
this.soundSrc = soundSrc;
this.playSound = function() {
(new Audio(this.soundSrc)).play();
}
}
///create sound buttons
buttons.forEach(function(bt1) {
soundButtons.push(new Button(bt1.id, soundsLoc + bt1.id + ".mp3",$("#" + bt1.id)));
});
///bind buttons to soundbuttons
function bindButtons(){
soundButtons.forEach(function(bt1) {
$("#" + bt1.id).click(function() {
bt1.playSound();
flash($("#" + bt1.id), 100);
checkSeq(bt1.id,roundSeguence);
});
});
}
///unbind buttons
function unbindButtons(){
soundButtons.forEach(function(bt1) {
$("#" + bt1.id).unbind();
});
}
///add .pressed to ellement for "time" ms
function flash(bt1, time) {
bt1.addClass("pressed");
setTimeout(function() {
bt1.removeClass("pressed");
}, time);
}
function checkSeq(input, sequence) {
if(input===sequence[0]){
sequence.splice(0,1);
console.log("corret");
}else{
console.log("wrong");
gameOver();
}
if(sequence.length==0){
console.log("finish");
setTimeout(function() {
nextSeq();
},500);
}
}
function gameOver(){
$("#level-title").html("Game Over! <h6> (Press Any Key to restart) </h2>")
unbindButtons();
initialize();
}
function nextSeq(){
let i=Math.floor(Math.random()*soundButtons.length);
gameSequence.push(soundButtons[i].id);
roundSeguence=[...gameSequence];
flash(soundButtons[i].targt, 100);
console.log(soundButtons[i].id);
soundButtons[i].playSound();
}
function sleep(t){
return new Promise(resolve=>{
setTimeout(resolve,t);
})
}
function repeat(ra,t=500,i=0){
if(ra.length>i){
sleep(t).then(()=>{
flash($("#" + ra[i]), 100);
(new Audio(soundsLoc + ra[i] + ".mp3")).play();
i++
repeat(ra,t,i);
});
}
return
}