-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
100 lines (79 loc) · 2.11 KB
/
script.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
const genius = function () {
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
return {
isPlaying: false,
isIddle: false,
level: 1,
sequence: [],
key: null,
match: [],
get display () {
if (!this.isPlaying) return "GO 👆"
else return `Level ${this.level}`
},
isActive (key) {
return key === this.key ? "active" : ""
},
get randomKey () {
const newKey = () => Math.round(Math.random() * 3)
let key = newKey()
while (this.sequence.length >= 2) {
const index = this.sequence.length - 2
const lastKey = this.sequence[index]
if (key === lastKey) key = newKey()
else break
}
return key
},
get speed () {
return 500 / Math.sqrt(this.level)
},
async playSequence () {
for (key of this.sequence) {
await sleep(this.speed)
this.key = key
await sleep(this.speed)
this.key = null
}
this.key = null
},
userInput () {
return new Promise(resolve => {
const loop = setInterval(() => {
if (!this.isIddle || this.match.length === this.sequence.length) {
clearInterval(loop)
resolve()
}
}, 50)
})
},
push (key) {
if (!this.isIddle) return
const index = this.match.length
const lastKey = this.sequence[index]
if (key === lastKey) this.match.push(key)
else this.isIddle = false
},
async start () {
if (this.isPlaying) return
this.isPlaying = true
while (this.isPlaying) {
this.sequence.push(this.randomKey)
this.match = []
await this.playSequence()
this.isIddle = true
await this.userInput()
this.isIddle = false
if (this.match.length === this.sequence.length) {
this.level++
await sleep(1000)
}
else break
}
this.isPlaying = false
this.isIddle = false
this.sequence = []
this.level = 1
}
}
}