-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
124 lines (109 loc) · 2.77 KB
/
index.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
const blue = document.getElementById('blue');
const purple = document.getElementById('purple');
const orange = document.getElementById('orange');
const green = document.getElementById('green');
const btnBegin = document.getElementById('btnBegin');
const LAST_LEVEL = 5;
class Game {
constructor() {
this.init = this.init.bind(this);
this.init();
this.generateSequence();
this.nextLevel();
}
init() {
this.level = 1;
this.colors = [blue, purple, orange, green];
this.selectColor = this.selectColor.bind(this);
this.nextLevel = this.nextLevel.bind(this);
this.toogleBtnBegin();
}
toogleBtnBegin() {
btnBegin.classList.contains('hide')
? btnBegin.classList.remove('hide')
: btnBegin.classList.add('hide');
}
generateSequence() {
this.sequence = new Array(LAST_LEVEL)
.fill(0)
.map((item) => Math.floor(Math.random() * 4));
}
nextLevel() {
this.subLevel = 0;
this.lightSequence();
this.createClickEvents();
}
lightSequence() {
for (let i = 0; i < this.level; i++) {
const item = this.sequence[i];
setTimeout(() => {
this.lightColor(item);
}, 1000 * i);
}
}
lightColor(color) {
this.colors[color].classList.add('light');
setTimeout(() => {
this.offColor(color);
}, 500);
}
offColor(color) {
this.colors[color].classList.remove('light');
}
createClickEvents() {
this.colors.forEach((item) =>
item.addEventListener('click', this.selectColor)
);
}
removeClickEvents() {
this.colors.forEach((item) =>
item.removeEventListener('click', this.selectColor)
);
}
selectColor(event) {
const colorSelected = event.target.getAttribute('data-color');
const numColor = this.colors.findIndex((item) => item.id == colorSelected);
this.validateSelectedColor(numColor);
}
validateSelectedColor(numColor) {
if (numColor === this.sequence[this.subLevel]) {
this.subLevel++;
if (this.subLevel === this.level) {
this.level++;
this.removeClickEvents();
if (this.level === LAST_LEVEL + 1) {
this.winner();
} else {
setTimeout(() => {
this.nextLevel();
}, 2000);
}
}
} else {
this.looser();
}
}
winner() {
swal('Simon Said', 'You the the winnie!', 'success').then(() => {
this.restartGame();
});
}
looser() {
swal('Simon Said', 'Buuu! Looser ', 'error').then(() => {
this.restartGame();
});
}
restartGame() {
this.removeClickEvents();
this.init();
btnBegin.innerHTML = "Let's go again!";
}
}
function startGame() {
swal('The game will start soon. Get Ready', {
buttons: false,
timer: 2000,
}).then(() => {
var game = new Game();
});
}