-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
430 lines (349 loc) · 12.4 KB
/
Copy pathscript.js
File metadata and controls
430 lines (349 loc) · 12.4 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// Deploy backend and add url here
const backend = "https://wordle-clone-18oz.onrender.com"
let state = "running"
let board = Array(6).fill(Array(5).fill(''))
let evaluation = Array(6).fill(Array(5).fill(null))
let pause_game = true
let game_over = false
let current_row = 0
let current_grid = 0
const loaderMessages = [
"Checking if the server is awake...",
"Starting cloud instance...",
"Preparing today's puzzle...",
"Loading dictionaries...",
"Almost there...",
"Connecting securely...",
"Optimizing your experience...",
"Thanks for waiting ❤️"
]
const backendLoader = document.getElementById("backend-loader")
const backendMessage = document.getElementById("backend-message")
let messageInterval
async function waitForBackend() {
let visible = false
const showTimeout = setTimeout(() => {
visible = true
backendLoader.classList.remove("hidden")
let index = 0
messageInterval = setInterval(() => {
backendMessage.classList.add("fade")
setTimeout(() => {
index++
backendMessage.textContent =
loaderMessages[index % loaderMessages.length]
backendMessage.classList.remove("fade")
}, 250)
}, 2400)
}, 2000)
while (true) {
try {
const response = await fetch(backend + "/keep-alive",
{
cache: "no-store"
}
)
if (response.ok) {
clearTimeout(showTimeout)
clearInterval(messageInterval)
if (visible) {
backendLoader.classList.add("hidden")
await new Promise(resolve => {
setTimeout(resolve, 450)
})
}
return
}
}
catch (e) { }
await new Promise(resolve => {
setTimeout(resolve, 1500)
})
}
}
// Returns native user's prev board, evaluation and state
async function previousBoard(user_id) {
const response = await fetch(backend + '/board/fetch?id=' + user_id)
const data = await response.json()
// Incorrect user-id in local storage
if (data.success == false) {
localStorage.removeItem('user-id')
}
return {
board: data.board,
evaluation: data.evaluation,
state: data.state
}
}
// Registers new user in database, saves in local storage
// Returns user-id
async function register() {
const response = await fetch(backend + '/register')
const data = await response.json()
localStorage.setItem('user-id', data.user)
return {
success: data.success,
user_id: data.user
}
}
// Get and display user's board from database
async function displayBoard() {
const user_id = localStorage.getItem('user-id')
// User played wordle before
if (user_id) {
const data = await previousBoard(user_id)
state = data.state
board = data.board
evaluation = data.evaluation
}
// New user - register in database
else {
const data = await register()
// Register fail - user ip already in databse
// Get previous board
if (data.success == false) {
const prev = await previousBoard(data.user_id)
state = prev.state
board = prev.board
evaluation = prev.evaluation
}
}
game_over = (state != "running")
const grid = document.querySelector('.grid')
board.forEach((column, column_index) => {
const grid_column = document.createElement('div')
grid_column.setAttribute('id', 'grid-column-' + column_index)
grid.append(grid_column)
if (column[0].length) {
current_row++
}
column.forEach((row, row_index) => {
const grid_element = document.createElement('div')
grid_element.setAttribute('id', 'grid-column-' + column_index + '-row-' + row_index)
if (row.length) {
grid_element.textContent = row
color(grid_element, evaluation[column_index][row_index])
}
grid_column.append(grid_element)
})
})
if (game_over == false) {
grid_indicator(current_row, current_grid)
}
}
// Adds color class to grid and keyboard
// Value can be correct, present or absent
function color(grid, value) {
const letter = grid.textContent.toLowerCase()
const keyboard_btn = document.getElementById('keyboard-' + letter)
if (value == 'correct') {
grid.classList.add('green-card')
keyboard_btn.classList.add('keyboard-green')
} else if (value == 'present') {
grid.classList.add('yellow-card')
keyboard_btn.classList.add('keyboard-yellow')
} else {
grid.classList.add('grey-card')
keyboard_btn.classList.add('keyboard-grey')
}
}
// Creates on-screen keyboard
function createKeyboard() {
const keyboard = document.querySelector('.keyboard')
const keys = [
'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'BACKSPACE', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'ENTER', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'
]
keys.forEach(key => {
const button_element = document.createElement('button')
button_element.textContent = key
button_element.setAttribute('id', 'keyboard-' + key.toLowerCase())
button_element.addEventListener('click', () => clicked(key))
keyboard.append(button_element)
})
// Animate on-screen keyboard on key press
document.addEventListener('keydown', (event) => {
const key = event.key.toUpperCase()
if (keys.includes(key)) {
clicked(key)
const highlighter = document.getElementById('keyboard-' + key.toLowerCase())
highlighter.classList.add('animate-click')
setTimeout(() => {
highlighter.classList.remove('animate-click')
}, 200)
}
})
}
async function initialize(){
await waitForBackend()
await displayBoard()
}
initialize()
// Handles keyboard clicks
async function clicked(key) {
if (game_over) {
display_message("Game over")
return
}
if (pause_game) { return }
const line = document.getElementById('grid-column-' + current_row)
if (key == 'BACKSPACE') {
// Not the first cell of current row
if (current_grid != 0) {
// Last cell - remove purple row highlight
// Else shift current grid indicator to previous cell
if (current_grid == 5) {
line.classList.remove('complete-row')
} else {
grid_indicator(current_row, current_grid, reverse = true)
}
// Remove letter from current cell
current_grid--
const grid = document.getElementById('grid-column-' + current_row + '-row-' + current_grid)
grid.textContent = ''
board[current_row][current_grid] = ''
} else {
display_message("Nothing to delete")
}
} else if (key == 'ENTER') {
// Last cell
// Remove purple row highlight & perform wordle check
if (current_grid == 5) {
line.classList.remove('complete-row')
// Send user guess to backend for checking
const response = await fetch(backend + '/board/verify', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: localStorage.getItem('user-id'),
row: board[current_row]
})
})
const data = await response.json()
if (data.success == false) {
// User guess isn't valid dictionary word
if (data.code == 5104) {
display_message('Please enter a valid word')
line.classList.add('animate-shake')
setTimeout(() => {
line.classList.remove('animate-shake')
}, 650)
} else {
display_message('Something went wrong')
}
return
}
for (let i = 0; i < 5; i++) {
const cell = document.getElementById('grid-column-' + current_row + '-row-' + i)
// Animate flipping of cards
setTimeout(() => {
// Prevents user from typing during animation
pause_game = true
color(cell, data.evaluation[i])
// Fifth grid is being checked
if (i == 4) {
if (data.state == 'won') {
display_message("You won")
game_over = true
bounce()
}
else if (data.state == 'lose') {
display_message("You lose")
game_over = true
}
// Resume game play & shift cursor to next row
else {
pause_game = false
current_row++
current_grid = 0
grid_indicator(current_row, current_grid)
}
}
}, 500 * i)
}
} else {
display_message("Please fill remaining cells of current row")
}
} else {
// User entered a letter
// Add keyboard input to grid, shift grid indicator to next cell
if (current_grid < 5) {
const grid = document.getElementById('grid-column-' + current_row + '-row-' + current_grid)
grid.textContent = key
board[current_row][current_grid] = key
if (current_grid != 4) {
grid_indicator(current_row, current_grid + 1)
} else {
line.classList.add('complete-row')
}
// Pop animation on type
grid.classList.add('animate-pop')
setTimeout(() => {
grid.classList.remove('animate-pop')
}, 150)
current_grid++
} else {
display_message("Press enter to check current word")
}
}
}
// Displays information pop-up messages
const display_message = (message) => {
const element = document.getElementById('message')
element.innerHTML = message
element.style.opacity = 1
setTimeout(() => {
element.style.opacity = 0
}, 2800)
}
// Highlights next empty grid
const grid_indicator = (row, grid, reverse = false) => {
if (reverse) {
document.getElementById('grid-column-' + row + '-row-' + grid).classList.remove('dashed-box')
document.getElementById('grid-column-' + row + '-row-' + (grid - 1)).classList.add('dashed-box')
}
else {
document.getElementById('grid-column-' + row + '-row-' + grid).classList.add('dashed-box')
if (grid != 0) {
document.getElementById('grid-column-' + row + '-row-' + (grid - 1)).classList.remove('dashed-box')
}
}
}
// Bounce animation on win
const bounce = () => {
for (let i = 0; i < 5; i++) {
setTimeout(() => {
const card = document.getElementById('grid-column-' + current_row + '-row-' + i)
card.classList.add('animate-bounce')
}, 100 * i)
}
}
const splash = document.querySelector('.splash-screen')
// Hide instructions and start game
splash.addEventListener('click', () => {
pause_game = false
splash.style.display = 'none'
})
createKeyboard()
const container = document.querySelector('.container')
const toggle = document.querySelector('.theme-switch')
const theme = localStorage.getItem('theme')
// Set theme on initial page load
if (theme == 'dark') {
container.classList.remove('light-theme')
container.classList.add('dark-theme')
toggle.classList.add('checked')
}
// Toggle theme
toggle.addEventListener('click', () => {
toggle.classList.toggle('checked')
container.classList.toggle('light-theme')
container.classList.toggle('dark-theme')
const current_theme = localStorage.getItem('theme')
if (current_theme == 'dark') {
localStorage.setItem('theme', 'light')
} else {
localStorage.setItem('theme', 'dark')
}
})