-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.js
More file actions
309 lines (241 loc) · 8.58 KB
/
client.js
File metadata and controls
309 lines (241 loc) · 8.58 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
import { days_into_year } from 'https://av.archive.org/js/time.js'
// puzzle config
let p = {}
// state of game play
let score = 0
const state = {
found: [],
letters: '',
}
// eslint-disable-next-line no-console
const log = console.log.bind(console)
/**
* Computes and returns score for given word
* @param string word
* @returns int
*/
function word_score(word) {
if (!p.words.includes(word))
return 0
return (
0 +
(p.alls.includes(word) ? 7 : 0) +
(word.length > 4 ? word.length : 1)
)
}
function words_score(words) {
return words.reduce((sum, e) => sum + word_score(e), 0)
}
function max_score() {
return words_score(p.words)
}
function storage_name() {
return `word-salad${(location.hostname === 'localhost' ? '-dev' : '')}`
}
function store_state() {
if (typeof localStorage !== 'object')
return
localStorage.setItem(storage_name(), JSON.stringify(state))
}
function update() {
store_state()
const founds = state.found.sort()
document.getElementById('found').innerHTML = founds.join('<br>')
document.getElementById('score').innerHTML = score
document.getElementById('nfound').innerHTML = founds.length
}
function restore_state() {
if (typeof localStorage !== 'object')
return
// first, see if they are importing a puzzle via CGI args
const cgi = new URLSearchParams(location.search)
if (cgi.get('letters')) {
state.letters = cgi.get('letters')
state.found = cgi.get('found').split(',').filter((e) => word_score(e))
store_state()
// state saved -- now redirect them to url w/o CGI args, so that if they refresh the
// page (w/ CGI args), they wont _revert_ and lose any further game progress.
location.href = location.href.replace(/\?.*/, '')
}
const json = localStorage.getItem(storage_name())
if (!json)
return
const stored = JSON.parse(json)
// if the day's puzzle has changed and they reloaded the page, they're starting over
if (stored.letters === p.letters.sort().join('')) {
// same puzzle - restore it
state.found = stored.found
state.letters = p.letters.sort().join('')
score = words_score(state.found)
document.getElementById('msg').innerHTML = '<div class="alert alert-info">welcome back!</div>'
update()
} else {
state.letters = p.letters.sort().join('')
}
}
function msg(str, evt = null) {
document.getElementById('msg').innerHTML = `<div class="alert alert-info">${str}</div>`
// eslint-disable-next-line no-return-assign
setTimeout(() => document.querySelector('#msg .alert').style.opacity = 0, 500)
// eslint-disable-next-line no-unused-expressions
evt && evt.preventDefault && evt.preventDefault()
// eslint-disable-next-line no-unused-expressions
evt && evt.stopPropagation && evt.stopPropagation()
return false
}
function enter(evt) {
const $enter = document.getElementById('enter')
const submitted = $enter.value.trim().toLowerCase()
if (submitted === '')
return false // to aid w/ iOS - as of now - we get 2 events a lot w/ 2nd as blank - ignore it
$enter.value = ''
log({ submitted })
if (!submitted.includes(p.center))
return msg(`${submitted} missing <b>${p.center.toUpperCase()}</b>`, evt)
if (state.found.includes(submitted))
return msg(`${submitted} already found`, evt)
const scored = word_score(submitted)
if (!scored)
return msg(`${submitted} not in list`, evt)
const pangram = p.alls.includes(submitted)
const encouragment = (
// eslint-disable-next-line no-nested-ternary
pangram
? '🎉 you are AMAZING!! 🎉'
: (
// eslint-disable-next-line no-nested-ternary
scored > 7
? '😍 OH SNAP!!'
: (scored > 1
? '🚀 fantastic!'
: '😎 nice!'
)
)
)
msg(`${encouragment} <b>+${scored} pts</b>`)
if (pangram) {
// special commendation for a pangram!
setTimeout(() => {
document.querySelector('body').classList.add('flip')
setTimeout(() => document.querySelector('body').classList.remove('flip'), 1200)
}, 750)
}
score += scored
state.found.push(submitted)
update()
// eslint-disable-next-line no-unused-expressions
evt && evt.preventDefault && evt.preventDefault()
// eslint-disable-next-line no-unused-expressions
evt && evt.stopPropagation && evt.stopPropagation()
return false
}
function del1() {
const $enter = document.getElementById('enter')
$enter.value = $enter.value.slice(0, -1)
}
/**
* Shuffles array in place. ES6 version
* Note however, that swapping variables with destructuring assignment causes significant
* performance loss, as of October 2017.
*
* @see https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
// eslint-disable-next-line no-param-reassign
[a[i], a[j]] = [a[j], a[i]]
}
return a
}
function letter_pressed(evt) {
const targ = evt.currentTarget
const letter = targ.innerText
targ.classList.add('pressed')
setTimeout(() => targ.classList.remove('pressed'), 250)
const val = `${document.getElementById('enter').value ?? ''}${letter}`
document.getElementById('enter').value = val
// eslint-disable-next-line no-unused-expressions
evt && evt.preventDefault && evt.preventDefault()
// eslint-disable-next-line no-unused-expressions
evt && evt.stopPropagation && evt.stopPropagation()
return false
}
function add_letters() {
const ltrs = shuffle(p.letters.filter((e) => e !== p.center))
let htm = `<a class="ltr" href="#"><div>${p.center}</div></a>`
while (ltrs.length)
htm += `<a class="ltr" href="#"><div>${ltrs.pop()}</div></a>`
document.querySelector('.ltrs').innerHTML = htm
document.querySelectorAll('.ltr').forEach((e) => e.addEventListener('click', letter_pressed))
}
function spoil() {
if (!document.querySelectorAll('#found i').length) {
const answers = []
p.words.map((e) => answers.push(state.found.includes(e) ? e : `<i>${p.alls.includes(e) ? `<b>${e} *</b>` : e}</i>`))
document.getElementById('found').innerHTML = answers.join('<br>')
} else {
update()
}
}
function transfer_url() {
const url = `${location.href.replace(/\?.*/, '')}?letters=${state.letters}&found=${state.found.join(',')}`
// eslint-disable-next-line no-alert
alert(`BETA! copy this url to another device: ${url}`)
}
function help() {
document.getElementById('help').innerHTML = `
<li>
today's puzzle contains <u>${p.words.length}</u> words
<span id="nfound">0</span> discovered
</li>
<li>today's puzzle maximum score: <u>${max_score()}</u></li>
<li>create words with 4 or more letters</li>
<li>each word must contain: <div class="must">${p.center}</div></li>
<li>letters can be repeated</li>
<li>1 point for 4 letter words</li>
<li>words longer than 4 letters get an additional point per letter</li>
<li>a “pangram” - which uses every letter - is worth 7 extra points</li>
<li>this puzzle contains <u>${p.alls.length}</u> pangrams</li>
`
}
async function setup_puzzle(letters, center) {
// now filter words dictionary to just the words made up of the limited letters,
// where each word _additionally_ has to contain center letter.
const words = (await (await fetch('./words.txt')).text())
.trimEnd()
.split('\n')
.filter((e) => e.match(RegExp(`^[${letters.join('')}]+$`)))
.filter((e) => e.includes(center))
// find the words that have _all letters_ in them
const alls = []
for (const word of words) {
if ([...new Set(word.split(''))].join('').length === letters.length)
alls.push(word)
}
return {
letters, center, words, alls,
}
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('enter').focus()
fetch('puzzles.txt').then((e) => e.text()).then(async (ret) => {
const n = days_into_year() // [0..366]
const multiplier = (new Date().getFullYear() - 2024) % 3 // 2024>0, 2025>1, 2026>2, 2027>0, ...
const letters = ret.split('\n')[n + multiplier * 366]
log({ letters })
// copy to p
p = await setup_puzzle(letters.split(''), letters[0])
log(p)
help()
add_letters()
restore_state()
})
document.getElementById('form').addEventListener('submit', enter)
document.getElementById('del1').addEventListener('click', del1)
document.getElementById('shuffle').addEventListener('click', add_letters)
document.getElementById('spoil').addEventListener('click', spoil)
document.getElementById('transfer').addEventListener('click', transfer_url)
})
export default setup_puzzle