-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.js
78 lines (61 loc) · 1.6 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
import { words } from './utils/words.js'
function validate(guess) {
return words.includes(guess)
}
function check(answer, guess) {
const result = Array.from({ length: answer.length }).fill('absent')
const whitelist = answer.split('')
for (let i = 0; i < answer.length; i++) {
if (whitelist[i] === guess[i]) {
result[i] = 'correct'
whitelist[i] = '_'
}
}
for (let i = 0; i < answer.length; i++) {
if (whitelist.includes(guess[i])) {
result[i] = 'present'
whitelist[i] = '_'
}
}
return result
}
function withTranstion(callback) {
setTimeout(callback, 150)
}
export function buildGame({ $board, $keyboard }) {
const today = new Date()
const index = today.getDate() + today.getMonth()
const answer = words[index]
let row = 0
$keyboard.on('key', key => {
$board.row(row).write(key)
})
$keyboard.on('delete', () => {
$board.row(row).erase()
})
$keyboard.on('enter', async () => {
const guess = $board.row(row).read()
const keys = guess.split('')
const diff = check(answer, guess)
const isValid = validate(guess)
if (!isValid) {
alert('Not in word list')
return
}
$board.row(row).paint(diff)
$keyboard.keys(keys).paint(diff)
if (guess === answer) {
withTranstion(() => alert('You won!'))
$keyboard.disable()
navigator.clipboard.writeText($board.read())
return
}
if (row === 5) {
withTranstion(() => alert(`You lost! The answer was ${answer}.`))
$keyboard.disable()
navigator.clipboard.writeText($board.read())
return
}
row++
})
}