-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
537 lines (475 loc) · 19.8 KB
/
script.js
File metadata and controls
537 lines (475 loc) · 19.8 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
/**
* Prevent zooming gestures on mobile devices
*/
document.addEventListener('touchmove', function(event) {
if (event.scale !== 1) event.preventDefault();
}, { passive: false });
/**
* Prevent double-click zoom
*/
document.addEventListener('dblclick', function(event) {
event.preventDefault();
}, { passive: false });
document.addEventListener('DOMContentLoaded', () => {
// --- DOM Elements ---
const themeToggleButton = document.getElementById('theme-toggle');
const themeIcon = themeToggleButton.querySelector('.theme-icon');
const keyboardToggleButton = document.getElementById('keyboard-toggle');
const newGameButton = document.getElementById('new-game-button');
const settingsToggleButton = document.getElementById('settings-toggle');
const closeSettingsButton = document.getElementById('close-settings-button');
const settingsModal = document.getElementById('settings-modal');
const guessContainer = document.getElementById('guess-container');
const keyboardContainer = document.getElementById('keyboard');
const messageContainer = document.getElementById('message-container');
const boldTextToggle = document.getElementById('bold-text-toggle');
const fontSizeSelect = document.getElementById('font-size-select');
const boardSizeSelect = document.getElementById('board-size-select');
const keyboardSizeSelect = document.getElementById('keyboard-size-select');
const themeColorMeta = document.querySelector('meta[name="theme-color"]');
// --- Game Constants ---
const WORD_LENGTH = 5;
const NUM_GUESSES = 6;
// --- Game State ---
let targetWord = '';
let currentGuess = [];
let currentRow = 0;
let isGameOver = false;
let answerList = []; // Curated list of possible answers
let allowedGuessesList = []; // Larger list of acceptable guesses
let usedWordsThisSession = []; // Tracks answers used to prevent repeats
/**
* Syncs the browser's theme color meta tag with the active background color
*/
const updateThemeColorMeta = () => {
if (!themeColorMeta) return;
const backgroundColor = getComputedStyle(document.documentElement)
.getPropertyValue('--background-color')
.trim();
if (backgroundColor) {
themeColorMeta.setAttribute('content', backgroundColor);
}
};
/**
* Fetches word lists and starts the game
* @async
*/
const loadGame = async () => {
try {
// Fetch the smaller, common list for answers
const answersResponse = await fetch('https://gist.githubusercontent.com/cfreshman/a03ef2cba789d8cf00c08f767e0fad7b/raw/c46f451920d5cf6326d550fb2d6abb1642717852/wordle-answers-alphabetical.txt');
if (!answersResponse.ok) {
throw new Error(`Answers list failed: ${answersResponse.status} ${answersResponse.statusText}`);
}
answerList = (await answersResponse.text()).split('\n');
// Fetch the larger list for additional allowed guesses
const allowedResponse = await fetch('https://gist.githubusercontent.com/cfreshman/cdcdf777450c5b5301e439061d29694c/raw/d7c9e02d45afd26e12a71b4564189a949c29e8a9/wordle-allowed-guesses.txt');
if (!allowedResponse.ok) {
throw new Error(`Allowed guesses list failed: ${allowedResponse.status} ${allowedResponse.statusText}`);
}
allowedGuessesList = (await allowedResponse.text()).split('\n');
// Final sanity check on lists
if (answerList.length === 0 || !answerList[0]) {
throw new Error('Answer list is empty - check word list format');
}
await startNewGame();
} catch (error) {
console.error("Failed to load word lists:", error);
showMessage("Error: Could not load words. Please refresh.");
}
};
/**
* Validates a word against dictionary API
* @param {string} word - The word to validate
* @returns {Promise<boolean>} - True if word is valid
*/
const validateWord = async (word) => {
try {
const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word.toLowerCase()}`);
if (!response.ok) {
console.log(`Dictionary rejected word "${word}":`, response.status);
return false;
}
return true;
} catch (error) {
console.error("Dictionary API error:", error);
return false;
}
};
/**
* Resets the game to a new state
* @async
*/
const startNewGame = async () => {
isGameOver = false;
currentRow = 0;
currentGuess = [];
// Find words that haven't been used yet in this session
let availableWords = answerList.filter(word =>
word && !usedWordsThisSession.includes(word.toUpperCase())
);
// If all words have been played, reset the list
if (availableWords.length === 0 && answerList.length > 0) {
console.log("All words have been played! Resetting the session list.");
usedWordsThisSession = [];
availableWords = answerList;
}
// Select a random word from available words
const randomWord = availableWords[Math.floor(Math.random() * availableWords.length)];
targetWord = randomWord.toUpperCase();
usedWordsThisSession.push(targetWord);
console.log("Target Word:", targetWord);
console.log(`Words used this session: ${usedWordsThisSession.length} of ${answerList.length}`);
guessContainer.innerHTML = '';
keyboardContainer.innerHTML = '';
showMessage('');
createBoard();
createKeyboard();
loadSettings();
};
/**
* Creates the visual game board
*/
const createBoard = () => {
for (let i = 0; i < NUM_GUESSES; i++) {
const row = document.createElement('div');
row.className = 'guess-row';
for (let j = 0; j < WORD_LENGTH; j++) {
const tile = document.createElement('div');
tile.className = 'guess-tile';
tile.id = `tile-${i}-${j}`;
row.appendChild(tile);
}
guessContainer.appendChild(row);
}
};
/**
* Creates the visual keyboard
*/
const createKeyboard = () => {
const layout = [
'q w e r t y u i o p',
'a s d f g h j k l',
'↩ z x c v b n m ⌫'
];
layout.forEach(row => {
const rowDiv = document.createElement('div');
rowDiv.className = 'keyboard-row';
row.split(' ').forEach(key => {
const button = document.createElement('button');
button.className = 'keyboard-button';
if (key === '↩') {
button.innerHTML = '<span class="material-icons">keyboard_return</span>';
button.dataset.key = 'Enter';
button.classList.add('wide');
} else if (key === '⌫') {
button.innerHTML = '<span class="material-icons">backspace</span>';
button.dataset.key = 'Backspace';
button.classList.add('wide');
} else {
button.textContent = key.toUpperCase();
button.dataset.key = key;
}
rowDiv.appendChild(button);
});
keyboardContainer.appendChild(rowDiv);
});
};
/**
* Handles keyboard input
* @param {string} key - The pressed key
*/
const handleKeyPress = (key) => {
if (isGameOver) return;
if (key === 'enter') {
submitGuess();
} else if (key === 'backspace') {
deleteLetter();
} else if (key.length === 1 && key >= 'a' && key <= 'z') {
addLetter(key.toUpperCase());
}
};
// Event listeners for keyboard input
keyboardContainer.addEventListener('click', (e) => {
const keyButton = e.target.closest('[data-key]');
if (!keyButton) return;
handleKeyPress(keyButton.dataset.key.toLowerCase());
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
}
handleKeyPress(e.key.toLowerCase());
});
/**
* Adds a letter to the current guess
* @param {string} letter - The letter to add
*/
const addLetter = (letter) => {
if (currentGuess.length < WORD_LENGTH) {
currentGuess.push(letter);
updateBoard();
}
};
/**
* Deletes the last letter from current guess
*/
const deleteLetter = () => {
if (currentGuess.length > 0) {
currentGuess.pop();
updateBoard();
}
};
/**
* Submits the current guess for validation
* @async
*/
const submitGuess = async () => {
if (currentGuess.length !== WORD_LENGTH) {
showMessage("Not enough letters");
return;
}
showMessage('');
const guess = currentGuess.join('');
const guessLower = guess.toLowerCase();
// Validate the word
let isValidWord = false;
if (answerList.includes(guessLower)) {
isValidWord = true;
}
else if (allowedGuessesList.includes(guessLower)) {
isValidWord = true;
}
else {
console.log(`Word not in local lists. Checking API for "${guessLower}"...`);
isValidWord = await validateWord(guessLower);
}
if (!isValidWord) {
showMessage("Not in word list");
return;
}
updateTileColors(guess);
updateKeyboardColors(guess);
if (guess === targetWord) {
showMessage(`You win! The word was <a href="https://www.merriam-webster.com/dictionary/${targetWord.toLowerCase()}" target="_blank">${targetWord}</a>.`);
isGameOver = true;
} else {
currentRow++;
currentGuess = [];
if (currentRow === NUM_GUESSES) {
showMessage(`Game over! The word was <a href="https://www.merriam-webster.com/dictionary/${targetWord.toLowerCase()}" target="_blank">${targetWord}</a>.`);
isGameOver = true;
}
}
};
/**
* Updates the game board with current guess
*/
const updateBoard = () => {
for (let i = 0; i < WORD_LENGTH; i++) {
const tile = document.getElementById(`tile-${currentRow}-${i}`);
tile.textContent = currentGuess[i] || '';
}
};
/**
* Updates tile colors based on guess accuracy
* @param {string} guess - The current guess
*/
const updateTileColors = (guess) => {
const guessLetters = guess.split('');
const targetLetters = targetWord.split('');
// First pass for correct (green) letters
for (let i = 0; i < WORD_LENGTH; i++) {
if (guessLetters[i] === targetLetters[i]) {
document.getElementById(`tile-${currentRow}-${i}`).classList.add('tile-correct');
targetLetters[i] = null;
}
}
// Second pass for present (yellow) letters
for (let i = 0; i < WORD_LENGTH; i++) {
const tile = document.getElementById(`tile-${currentRow}-${i}`);
if (!tile.classList.contains('tile-correct')) {
if (targetLetters.includes(guessLetters[i])) {
tile.classList.add('tile-present');
targetLetters[targetLetters.indexOf(guessLetters[i])] = null;
} else {
tile.classList.add('tile-absent');
}
}
}
};
/**
* Updates keyboard colors based on guess accuracy
* @param {string} guess - The current guess
*/
const updateKeyboardColors = (guess) => {
const guessLetters = guess.split('');
const targetLetters = targetWord.split('');
for (let i = 0; i < guessLetters.length; i++) {
const key = guessLetters[i].toLowerCase();
const button = keyboardContainer.querySelector(`[data-key="${key}"]`);
if (!button) continue;
const currentPriority = button.dataset.priority || 0;
let newClass = '';
let priority = 0;
if (targetLetters.includes(guessLetters[i])) {
if (guessLetters[i] === targetLetters[i]) {
newClass = 'tile-correct';
priority = 3;
} else {
newClass = 'tile-present';
priority = 2;
}
} else {
newClass = 'tile-absent';
priority = 1;
}
if (priority > currentPriority) {
button.classList.remove('tile-correct', 'tile-present', 'tile-absent');
button.classList.add(newClass);
button.dataset.priority = priority;
}
}
};
/**
* Displays a message to the user
* @param {string} message - The message to display
*/
const showMessage = (message) => {
messageContainer.innerHTML = message;
};
/**
* Toggles a modal's visibility
* @param {HTMLElement} modal - The modal element
* @param {boolean} [forceShow] - Force show/hide if provided
*/
const toggleModal = (modal, forceShow) => {
const isHidden = modal.classList.contains('hidden');
if (forceShow === true) {
modal.classList.remove('hidden');
} else if (forceShow === false) {
modal.classList.add('hidden');
} else {
modal.classList.toggle('hidden');
}
};
/**
* Applies current settings from UI to the game
*/
const applySettings = () => {
try {
// Bold Text
document.body.classList.toggle('bold-text', boldTextToggle.checked);
localStorage.setItem('boldText', boldTextToggle.checked);
// Font Size
const sizes = { small: '0.8rem', medium: '1rem', large: '1.2rem' };
document.documentElement.style.setProperty('--font-size', sizes[fontSizeSelect.value]);
localStorage.setItem('fontSize', fontSizeSelect.value);
// Board Size
const boardSizes = { compact: '45px', normal: '55px', expanded: '65px' };
document.documentElement.style.setProperty('--tile-size', boardSizes[boardSizeSelect.value]);
localStorage.setItem('boardSize', boardSizeSelect.value);
// Keyboard Size
const keyboardSizes = {
compact: { y: '12px', x: '8px' },
normal: { y: '15px', x: '10px' },
expanded:{ y: '20px', x: '15px' },
};
const kSize = keyboardSizes[keyboardSizeSelect.value];
document.documentElement.style.setProperty('--key-padding-y', kSize.y);
document.documentElement.style.setProperty('--key-padding-x', kSize.x);
localStorage.setItem('keyboardSize', keyboardSizeSelect.value);
} catch (error) {
console.error('Failed to apply settings:', error);
}
};
/**
* Loads saved settings from localStorage
*/
const loadSettings = () => {
try {
const isMobile = window.matchMedia("(max-width: 500px)").matches;
const storedBold = localStorage.getItem('boldText');
const storedFont = localStorage.getItem('fontSize');
const storedBoard = localStorage.getItem('boardSize');
const storedKeyboard = localStorage.getItem('keyboardSize');
// Default to bold + large-font + compact elements on mobile
boldTextToggle.checked = storedBold !== null ? storedBold === 'true' : isMobile;
fontSizeSelect.value = storedFont || (isMobile ? 'large' : 'medium');
boardSizeSelect.value = storedBoard || (isMobile ? 'compact' : 'normal');
keyboardSizeSelect.value = storedKeyboard || (isMobile ? 'compact' : 'normal');
// Theme
const theme = localStorage.getItem('themePreference') || 'light';
document.documentElement.setAttribute('data-theme', theme);
themeIcon.textContent = theme === 'dark' ? 'light_mode' : 'dark_mode';
// Keyboard visibility
const kbdVisible = localStorage.getItem('keyboardVisibility') !== 'hidden';
keyboardContainer.classList.toggle('hidden', !kbdVisible);
applySettings();
updateThemeColorMeta();
} catch (error) {
console.error('Failed to load settings:', error);
}
};
// --- Event Listeners ---
settingsToggleButton.addEventListener('click', () => toggleModal(settingsModal, true));
closeSettingsButton.addEventListener('click', () => toggleModal(settingsModal, false));
settingsModal.addEventListener('click', (e) => {
if (e.target === settingsModal) toggleModal(settingsModal, false);
});
themeToggleButton.addEventListener('click', () => {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
document.documentElement.setAttribute('data-theme', newTheme);
localStorage.setItem('themePreference', newTheme);
themeIcon.textContent = newTheme === 'dark' ? 'light_mode' : 'dark_mode';
updateThemeColorMeta();
});
keyboardToggleButton.addEventListener('click', () => {
const isHidden = keyboardContainer.classList.toggle('hidden');
localStorage.setItem('keyboardVisibility', isHidden ? 'hidden' : 'visible');
});
[boldTextToggle, fontSizeSelect, boardSizeSelect, keyboardSizeSelect].forEach(el => {
el.addEventListener('change', applySettings);
// --- PWA Installation Prompt Handling ---
let deferredPrompt;
window.addEventListener('beforeinstallprompt', (e) => {
// Prevent the mini-infobar from appearing on mobile
e.preventDefault();
// Stash the event so it can be triggered later
deferredPrompt = e;
console.log('PWA install prompt available');
});
// Handle app installed event
window.addEventListener('appinstalled', (e) => {
console.log('PWA was installed');
deferredPrompt = null;
});
});
newGameButton.addEventListener('click', startNewGame);
// --- Initial Load ---
updateThemeColorMeta();
loadGame();
// --- Service Worker Registration for PWA ---
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('./sw.js')
.then(registration => {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
// Check for updates
registration.addEventListener('updatefound', () => {
console.log('ServiceWorker update found');
const newWorker = registration.installing;
newWorker.addEventListener('statechange', () => {
console.log('ServiceWorker state changed to: ', newWorker.state);
});
});
})
.catch(error => {
console.error('ServiceWorker registration failed: ', error);
});
});
} else {
console.log('Service Workers not supported in this browser');
}
});