-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
139 lines (117 loc) · 2.66 KB
/
main.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
127
128
129
130
131
132
133
134
135
136
137
138
139
import Alpine from 'alpinejs';
import sound1Url from './audio/simonSound1.mp3';
import sound2Url from './audio/simonSound2.mp3';
import sound3Url from './audio/simonSound3.mp3';
import sound4Url from './audio/simonSound4.mp3';
import './style.css';
function sleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
function playAudio(audioUrl) {
return new Promise((res) => {
const audio = new Audio(audioUrl);
audio.play();
audio.onended = res;
})
}
const keyMap = {
'ArrowUp': 'top',
'ArrowDown': 'bottom',
'ArrowLeft': 'left',
'ArrowRight': 'right',
}
Alpine.data('game', () => ({
items: {
'top': {
activeCount: 0,
audioUrl: sound1Url,
},
'right': {
activeCount: 0,
audioUrl: sound2Url,
},
'left': {
activeCount: 0,
audioUrl: sound3Url,
},
'bottom': {
activeCount: 0,
audioUrl: sound4Url,
},
},
blocked: true,
lost: false,
simonEntries: [],
userEntries: [],
init() {
document.addEventListener('keydown', (e) => {
if (!Object.keys(keyMap).includes(e.key)) return;
e.preventDefault();
this.enter(keyMap[e.key]);
return;
});
},
async blink(dir) {
this.items[dir].activeCount += 1;
await playAudio(this.items[dir].audioUrl);
this.items[dir].activeCount -= 1;
},
async nextRound() {
this.blocked = true;
this.userEntries = [];
this.simonEntries.push(
Object.keys(this.items).sort(() => 0.5 - Math.random())[0]
);
for (const dir of this.simonEntries) {
await this.blink(dir);
await sleep(300);
}
this.blocked = false;
},
async enter(dir) {
if (this.blocked || this.everyEntered) return;
this.userEntries.push(dir);
this.blink(dir);
if (
this.userEntries.some(
(value, index) => value !== this.simonEntries[index]
)
) {
this.setLost();
return;
}
// every entered
if (this.everyEntered) {
await sleep(1500);
await this.nextRound();
}
},
setLost() {
this.lost = true;
this.blocked = true;
},
isActive(dir) {
return this.items[dir].activeCount > 0;
},
get round() {
return Math.max(this.simonEntries.length, 0);
},
get wonRounds() {
return Math.max(this.round - 1, 0);
},
get everyEntered() {
return this.userEntries.length === this.simonEntries.length;
},
get running() {
return this.simonEntries.length !== 0 && !this.lost;
},
startGame() {
this.simonEntries = [];
this.userEntries = [];
this.lost = false;
this.blocked = false;
this.nextRound();
},
}));
window.Alpine = Alpine;
Alpine.start();