-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1143 lines (1012 loc) · 36.8 KB
/
script.js
File metadata and controls
1143 lines (1012 loc) · 36.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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { shareGame, generateResultText, createShareableLink } from "./share.js";
import * as Ui from "./uiHandling.js";
document.addEventListener("DOMContentLoaded", () => {
const urlParams = new URLSearchParams(window.location.search);
let variant = "standard";
const gameVariant = urlParams.get("v");
// 1 = standard
// 2 = alphabetical
// 3 = 6-letter
// 4 = alphabetical, daily
if (gameVariant) {
if (gameVariant === "1") {
variant = "standard";
} else if (gameVariant === "2") {
variant = "alpha";
// document.getElementById("helpModal").style.display = "block";
} else if (gameVariant === "3") {
variant = "6-letter";
} else if (gameVariant === "4") {
variant = "alpha-daily";
// document.getElementById("helpModal").style.display = "block";
}
} else {
// set variant here
// let variant = "standard";
variant = "alpha-daily";
// document.getElementById("helpModal").style.display = "block";
// variant = "6-letter";
}
const standardKeyboardLayout = ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"];
const alphabeticalKeyboardLayout = ["ABCDEFGHIJ", "KLMNOPQRS", "TUVWXYZ"];
const now = new Date();
let wordList = [];
let validGuesses = [];
let targetWord = "";
let currentAttempt = 0;
let currentInput = "";
let focusCellIndex = 0;
let statusMapHistory = [];
let guesses = [];
// variables to track game state, TODO clean up
let gameOver = false;
let gameWon = false;
let hardMode = false;
// set standard settings
let maxAttempts = 6;
let letterCount = 5;
let feedbackStyle = "standard";
let name = "Wordlish";
let dailyWord = false; // whether the game is a daily puzzle
let requireValidGuesses = true;
// override with variant settings
if (variant === "alpha") {
feedbackStyle = "alphabetical";
name = "Worderly";
document.getElementById("subhead").textContent +=
"practice mode, play as much as you want!";
} else if (variant === "6-letter") {
maxAttempts = 8;
letterCount = 6;
name = "Woordle";
} else if (variant === "alpha-daily") {
feedbackStyle = "alphabetical";
name = "Worderly";
dailyWord = true;
}
let letterRanges = Array(letterCount)
.fill()
.map(() => ({ min: "@", max: "[" })); // set min and max outside the A-Z range
document.title = name;
document.getElementById("gameName").textContent = name.toUpperCase();
createGrid(letterCount, maxAttempts);
generateKeyboardLayout();
generateAlphabetHelper();
// load wordlist_{letterCount}.txt
fetch("wordlists/wordlist_" + letterCount + ".txt")
.then((response) => response.text())
.then((text) => {
wordList = text.split("\n").map((word) => word.trim().toUpperCase());
})
.catch((err) => console.error("Failed to load word list:", err));
// Load valid guesses_{letterCount}.txt list
if (requireValidGuesses) {
fetch("wordlists/validguesses_" + letterCount + ".txt")
.then((response) => response.text())
.then((text) => {
validGuesses = text
.split("\n")
.map((word) => word.trim().toUpperCase());
console.log(validGuesses.length + " valid guesses loaded");
startGame();
})
.catch((err) => console.error("Failed to load valid guesses list:", err));
}
// set state of option checkboxes
document.getElementById("alphabetHelperToggle").checked =
localStorage.getItem("alphabetHelper") === "true";
document.getElementById("hardModeToggle").checked =
localStorage.getItem("hardMode") === "true";
document.addEventListener("keydown", handleKeyPress);
function InitializeGameState() {
targetWord = "";
currentAttempt = 0;
currentInput = "";
focusCellIndex = 0;
statusMapHistory = [];
guesses = [];
gameOver = false;
gameWon = false;
//letter range?
// get hardmode from localstorage, if available (default to false)
hardMode = JSON.parse(localStorage.getItem("hardMode")) || false;
// get alphabet helper visibility from localStorage
Ui.setAlphabetHelperVisibility(
JSON.parse(localStorage.getItem("alphabetHelper")) || false
);
}
function startGame() {
InitializeGameState();
if (variant == "alpha-daily") {
// show help modal if it's been more than a week since last visit
const lastVisitDate = localStorage.getItem("lastVisitDate");
const lastVisitTime = lastVisitDate
? new Date(lastVisitDate).getTime()
: 0;
const oneWeek = 7 * 24 * 60 * 60 * 1000; // One week in milliseconds
if (!lastVisitDate || now.getTime() - lastVisitTime > oneWeek) {
document.getElementById("helpModal").style.display = "block";
}
localStorage.setItem("lastVisitDate", now.toISOString());
// set subheader to today's date in format Month Day, Year
// const today = new Date();
const dateString = now.toLocaleDateString("en-US", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
});
document.getElementById("subhead").textContent +=
"daily puzzle for " + dateString;
// check if daily game has been completed today
const dailyCompletion = JSON.parse(
localStorage.getItem("dailyGameCompleted")
);
const today = now.toDateString();
if (
// game state is present for today's puzzle
dailyCompletion &&
dailyCompletion.date === today
) {
// if game is not completed, restore game state
if (!dailyCompletion.completed) {
restoreGameState(dailyCompletion);
} else {
// set game to ended and show completion message
gameOver = true;
showCompletionMessage(dailyCompletion.message);
// get game state from localStorage
guesses = dailyCompletion.guesses;
statusMapHistory = dailyCompletion.statusMapHistory;
gameWon = dailyCompletion.won;
// also show results modal
// populateStatsHTML(variant);
// showResultModal("title", "message", guesses, variant, true);
return;
}
}
}
// tag game start event
gtag("event", "game_start", {
event_category: "Game",
event_label: "Start",
game_variant: variant,
game_name: name,
});
setTargetWord();
// console.log(targetWord);
clearGrid();
clearKeyboard();
}
function setTargetWord() {
// set target word
if (dailyWord) {
targetWord = getTodaysWord().toUpperCase();
} else if (getWordFromUrl()) {
targetWord = getWordFromUrl().toUpperCase();
} else {
targetWord = getRandomWord();
}
}
function getRandomWord() {
return wordList.length > 0
? wordList[Math.floor(Math.random() * wordList.length)]
: "ERRORS";
}
function getTodaysWord() {
const index = Ui.getTodaysWordIndex() % wordList.length; // Use modulo to loop back to start
return wordList[index];
}
function restoreGameState(gameState) {
// restore game state
gameOver = gameState.completed;
gameWon = gameState.won;
currentAttempt = 0;
currentInput = "";
setTargetWord();
// guesses = gameState.guesses;
// statusMapHistory = gameState.statusMapHistory;
// currentAttempt = guesses.length;
// iterate through guesses to update keyboard and grid
gameState.guesses.forEach((guess) => {
console.log("restoring guess: ", guess);
// updateGrid();
currentInput = "";
// split each guess into individual letters and submit as keypresses
guess.split("").forEach((letter, index) => {
// pause for 100ms between each letter
setTimeout(() => {
handleKeyPress({ key: letter.trim() });
}, 100);
});
setTimeout(() => {
handleKeyPress({ key: "Enter" });
}, 100);
});
// tag game restore event
gtag("event", "game_restore", {
event_category: "Game",
event_label: "Restore",
game_variant: variant,
game_name: name,
});
}
function clearGrid() {
for (let i = 0; i < maxAttempts; i++) {
for (let j = 0; j < letterCount; j++) {
const cell = document.getElementById(`cell${i}-${j}`);
const front = cell.querySelector(".front");
const back = cell.querySelector(".back");
front.textContent = "";
back.textContent = "";
back.className = "back"; // Reset classes
cell.classList.remove("flip", "correct", "present", "incorrect");
}
}
document.getElementById("playAgain").innerHTML = "";
}
function clearKeyboard() {
document.querySelectorAll(".key").forEach((key) => {
key.classList.remove("correct", "present", "incorrect");
});
}
function handleKeyPress(e) {
// Ignore clicks if game is over
if (gameOver) {
return;
}
if (currentAttempt < maxAttempts && e.key.match(/^[a-z]$/i)) {
// Convert the currentInput string to an array for easy manipulation
while (currentInput.length < letterCount) {
currentInput += " ";
}
let inputArray = currentInput.split("");
// Insert or replace the character at the focus position
inputArray[focusCellIndex] = e.key.toUpperCase();
// Convert the array back to a string
currentInput = inputArray.join("").trimEnd();
if (focusCellIndex < letterCount - 1) {
updateFocus(focusCellIndex + 1);
}
updateGrid();
} else if (e.key === "Backspace") {
// Convert the currentInput string to an array for easy manipulation
let inputArray = currentInput.split("");
// if current focus cell is empty, just move focus to the previous cell
if (
inputArray[focusCellIndex] === " " ||
inputArray[focusCellIndex] === undefined
) {
updateFocus(Math.max(0, focusCellIndex - 1));
}
if (inputArray[focusCellIndex] !== " ") {
// if current focus cell is not empty, delete the current cell and don't move focus
inputArray[focusCellIndex] = " ";
}
// Convert the array back to a string
currentInput = inputArray.join("");
updateGrid();
} else if (e.key === "Enter" && currentInput.length === letterCount) {
submitGuess(currentInput);
currentInput = "";
// wait 1 second before clearing the grid
setTimeout(() => {
updateGrid();
}, 1000);
} else if (e.key === "ArrowRight" || e.key === " ") {
// move focus to the right if right arrow or spacebar is pressed
if (focusCellIndex < letterCount - 1) {
updateFocus(focusCellIndex + 1);
}
} else if (e.key === "ArrowLeft") {
// move focus to the right if right arrow is pressed
if (focusCellIndex > 0) {
updateFocus(focusCellIndex - 1);
}
} else if (e.key === "?") {
// show help modal
document.getElementById("helpModal").style.display = "block";
} else if (e.key === ".") {
// toggle visibility of alphabet helper
const alphabetHelper = document.getElementById("alphabetHelper");
if (alphabetHelper.style.display === "none") {
Ui.displayMessage("Showing Alphabetical Helper");
Ui.setAlphabetHelperVisibility(true);
} else {
Ui.displayMessage("Hiding Alphabetical Helper");
Ui.setAlphabetHelperVisibility(false);
}
}
// focusCellIndex = currentInput.length;
if (focusCellIndex < letterCount) {
updateKeyboardForLetterPosition(focusCellIndex);
updateAlphabetHelperForLetterPosition(focusCellIndex);
}
}
function handleKeyClick(keyValue) {
let value = keyValue;
if (value === "⌫") {
value = "Backspace";
} else if (value === "Enter") {
value = "Enter";
}
handleKeyPress({ key: value });
}
function updateGrid() {
// return if game is over
if (gameOver) {
return;
}
for (let i = 0; i < letterCount; i++) {
const cellId = `cell${currentAttempt}-${i}`;
const cell = document.getElementById(cellId);
if (cell) {
const front = cell.querySelector(".front");
if (front) {
front.textContent = currentInput[i] || "";
} else {
console.error(`Front not found in cell ${cellId}`);
}
// Do not remove classes here; they should be handled in updateGridStatus
} else {
console.error(`Cell not found: ${cellId}`);
}
}
}
function submitGuess(guess, saveState = true) {
if (!gameOver && currentAttempt < maxAttempts) {
if (targetWord === "") {
console.error("Oops, target word is empty, reloading page");
// reload the page (could instead try re-setting the word?)
location.reload();
return;
}
let statusMap = {};
let targetWordCopy = targetWord;
let correctCount = 0;
guess = guess.toUpperCase().trim();
// Check if the guess is a valid word
if (!validGuesses.includes(guess)) {
Ui.displayMessage("that's not a word", true);
updateFocus(0);
return; // Do not proceed further
}
// if hardmode is enabled, don't allow guesses that have been shown to be impossible based on previous guesses
if (hardMode) {
// check if guess is possible based on previous guesses
console.log("hardmode! checking guess: ", guess);
let possible = true;
for (let i = 0; i < letterCount; i++) {
// skip to next letter if the letter is correct
if (statusMapHistory.length > 0) {
if (
statusMapHistory[statusMapHistory.length - 1][i] === "correct"
) {
continue;
}
}
// if guessed letter is not is the possible range for this letter, guess is not possible
if (
guess[i] <= letterRanges[i].min ||
guess[i] >= letterRanges[i].max
) {
possible = false;
}
}
if (!possible) {
Ui.displayMessage("that's not possible", true);
updateFocus(0);
return;
}
}
// add guess to guesses array
guesses.push(guess);
// console feedback for Alex's solver
let consoleFeedback = "";
if (feedbackStyle === "alphabetical") {
// Alphabetical variant logic
updateKeyboardForLetterPosition(0);
updateAlphabetHelperForLetterPosition(0);
for (let i = 0; i < letterCount; i++) {
const guessedLetter = guess[i];
const correctLetter = targetWord[i];
if (guessedLetter === correctLetter) {
statusMap[i] = "correct";
correctCount++;
consoleFeedback += "0";
} else if (guessedLetter < correctLetter) {
statusMap[i] = "bef"; // Guessed letter comes before alphabetically
consoleFeedback += "1";
} else {
statusMap[i] = "aft"; // Guessed letter comes after alphabetically
consoleFeedback += "-1";
}
consoleFeedback += ",";
}
} else {
// First pass: Mark correct letters
for (let i = 0; i < letterCount; i++) {
if (guess[i] === targetWord[i]) {
statusMap[i] = "correct";
targetWordCopy = replaceAt(targetWordCopy, i, "_");
correctCount++;
}
}
// Second pass: Mark present and incorrect letters
for (let i = 0; i < letterCount; i++) {
if (!statusMap[i]) {
if (targetWordCopy.includes(guess[i])) {
statusMap[i] = "present";
// targetWordCopy = targetWordCopy.replace(guess[i], "_");
let indexOfLetter = targetWordCopy.indexOf(guess[i]);
targetWordCopy = replaceAt(targetWordCopy, indexOfLetter, "_");
} else {
statusMap[i] = "incorrect";
}
}
}
// After determining the status of each letter
for (let i = 0; i < letterCount; i++) {
// updateKeyboardStatus(guess[i], statusMap[i] || "incorrect");
updateKeyboardStatus(guess[i], statusMap[i]);
}
}
statusMapHistory.push(statusMap);
updateGridStatus(guess, statusMap);
// Win condition
if (correctCount === letterCount) {
const winMessages = [
"Spectacular!",
"Top notch!",
"Woohoo!",
"Nice one!",
"Not bad!",
"Phew!",
];
// Set timeout for confetti/message to trigger after flip animations
setTimeout(() => {
Ui.displayMessage(winMessages[guesses.length - 1]);
Ui.triggerConfetti();
endGame(true);
}, 1000);
return;
}
//save game state
if (saveState) {
storeGameState(
`Picking up where you left off...`,
gameOver,
gameWon,
guesses,
statusMapHistory
);
}
currentAttempt++;
if (currentAttempt === maxAttempts) {
Ui.displayMessage(`Sorry, you lose. The word was ${targetWord}.`);
gameOver = true; // Set gameOver to true when the game ends
endGame(false);
return;
}
updateFocus(0); // back to the beginning
if (feedbackStyle === "alphabetical") {
updateLetterRanges(guess, statusMap, currentAttempt % letterCount);
// remove trailing "," from consoleFeedback
consoleFeedback = consoleFeedback.slice(0, -1);
console.log(consoleFeedback);
}
}
}
function updateGridStatus(guess, statusMap) {
for (let i = 0; i < letterCount; i++) {
const cell = document.getElementById(`cell${currentAttempt}-${i}`);
const back = cell.querySelector(".back");
if (!cell || !back) {
console.error(`Cell or back not found for cell ${i}`);
continue;
}
// Reset content and classes
back.textContent = guess[i];
back.innerHTML = guess[i]; // Ensure any existing overlay is cleared
cell.classList.remove(
"correct",
"present",
"incorrect",
"bef",
"aft",
"possible",
"impossible"
);
back.classList.add(statusMap[i] || "incorrect");
if (feedbackStyle === "alphabetical") {
if (statusMap[i] === "bef") {
// Overlay '>' symbol
// back.innerHTML += '<span class="overlay">></span>';
// add dot before
// displayContent = "•" + displayContent; // Dot before the letter
} else if (statusMap[i] === "aft") {
// Overlay '<' symbol
// back.innerHTML += '<span class="overlay"><</span>';
// // add dot after
// displayContent += "•"; // Dot after the letter
}
}
// Trigger the flip animation
setTimeout(() => {
cell.classList.add("flip");
}, i * 180); // Delay for cascading effect
}
}
function updateKeyboardStatus(letter, status) {
const keyElement = document.getElementById(`key-${letter}`);
// const keyElement = document.getElementsByClassName(`key ${letter}`);
if (keyElement && !keyElement.classList.contains("correct")) {
keyElement.classList.add(status);
}
}
// for alphabetical only
function updateLetterRanges(guess, statusMap, currentPosition) {
for (let i = 0; i < letterCount; i++) {
// if (i === currentPosition) {
if (statusMap[i] === "aft" && guess[i] < letterRanges[i].max) {
letterRanges[i].max = guess[i];
} else if (statusMap[i] === "bef" && guess[i] > letterRanges[i].min) {
letterRanges[i].min = guess[i];
} else if (statusMap[i] === "correct") {
letterRanges[i].min = guess[i];
letterRanges[i].max = guess[i];
}
// }
}
}
function updateKeyboardForLetterPosition(currentPosition) {
if (feedbackStyle !== "alphabetical") return;
const currentRange = letterRanges[currentPosition];
document.querySelectorAll(".key").forEach((keyElement) => {
const letter = keyElement.textContent; // or keyElement.getAttribute('data-letter') if you use data attributes
if (letter !== "Enter" && letter !== "⌫") {
if (letter <= currentRange.min || letter >= currentRange.max) {
keyElement.classList.add("impossible"); // Highlight as impossible
} else {
keyElement.classList.remove("impossible");
keyElement.classList.remove("correct");
}
if (currentRange.min === currentRange.max) {
if (currentRange.min === letter) {
keyElement.classList.add("correct"); // Highlight as correct
keyElement.classList.remove("impossible");
} else {
keyElement.classList.add("impossible"); // Highlight as impossible
}
}
}
});
}
function updateAlphabetHelperForLetterPosition(currentPosition) {
if (feedbackStyle !== "alphabetical") return;
const currentRange = letterRanges[currentPosition];
document.querySelectorAll(".letter").forEach((helperLetter) => {
const letter = helperLetter.textContent;
if (letter !== "Enter" && letter !== "⌫") {
if (letter <= currentRange.min || letter >= currentRange.max) {
helperLetter.classList.add("impossible"); // Highlight as impossible
helperLetter.classList.remove("correct");
//hide this helperLetter
// helperLetter.style.display = "none";
} else {
helperLetter.classList.remove("impossible");
helperLetter.classList.remove("correct");
// show this helperLetter
// helperLetter.style.display = "block";
}
if (currentRange.min === currentRange.max) {
if (currentRange.min === letter) {
helperLetter.classList.add("correct"); // Highlight as correct
helperLetter.classList.remove("impossible");
// helperLetter.style.display = "block";
} else {
helperLetter.classList.add("impossible"); // Highlight as impossible
}
}
}
});
}
function getFocusedCell() {
return document.getElementById(`cell${currentAttempt}-${focusCellIndex}`);
}
function updateFocus(newFocusCellIndex) {
// remove focus class from all cells
document.querySelectorAll(".cell").forEach((cell) => {
cell.classList.remove("cell-focused");
});
let currentRow = currentAttempt;
// ID for the previously focused cell
const oldFocusCellId = `cell${currentRow}-${focusCellIndex}`;
// Remove focus from the previously focused cell
if (focusCellIndex !== null) {
const oldFocusCell = document.getElementById(oldFocusCellId);
if (oldFocusCell) {
oldFocusCell.classList.remove("cell-focused");
}
}
// Update the focus cell index
focusCellIndex = newFocusCellIndex;
// ID for the new focus cell
const newFocusCellId = `cell${currentRow}-${focusCellIndex}`;
// Apply focus to the new cell
const newFocusCell = document.getElementById(newFocusCellId);
if (newFocusCell) {
newFocusCell.classList.add("cell-focused");
} else {
console.error("New focus cell not found: ", newFocusCellId);
}
updateKeyboardForLetterPosition(focusCellIndex);
updateAlphabetHelperForLetterPosition(focusCellIndex);
}
function replaceAt(string, index, replacement) {
return (
string.substr(0, index) +
replacement +
string.substr(index + replacement.length)
);
}
function endGame(won) {
gameOver = true; // Set gameOver to true when the game ends
gameWon = won;
let endMessage,
endTitle = "";
if (won) {
endTitle = "Nice work!";
endMessage = `You found the word ${targetWord} in ${
statusMapHistory.length
} ${statusMapHistory.length === 1 ? "guess!" : "guesses."}`;
} else {
endTitle = "Better luck next time.";
endMessage = `Sorry, you failed to find the word ${targetWord} in ${statusMapHistory.length} guesses.`;
}
// update stats
updateStats(won, statusMapHistory.length, variant);
populateStatsHTML(variant);
// event tracking
gtag("event", "game_end", {
event_category: "Game",
event_label: "End",
game_won: won,
guess_count: statusMapHistory.length,
game_variant: variant,
game_name: name,
});
setTimeout(() => {
showResultModal(
// `${statusMapHistory.length}/${maxAttempts}`,
endTitle,
endMessage,
guesses,
variant,
won
);
}, 2500);
// save game state
storeGameState(endMessage, gameOver, won, guesses, statusMapHistory);
// add link to play again
// const gameUrl = window.location.href.split("?")[0]; // Base URL
// document.getElementById(
// "playAgain"
// ).innerHTML = `<a href="${gameUrl}">Play Again</a>`;
}
function createGrid(letterCount, maxAttempts) {
const gridContainer = document.getElementById("grid");
gridContainer.innerHTML = ""; // Clear existing grid if any
for (let row = 0; row < maxAttempts; row++) {
const rowDiv = document.createElement("div");
rowDiv.className = "row";
for (let col = 0; col < letterCount; col++) {
const cellDiv = document.createElement("div");
cellDiv.className = "cell";
cellDiv.id = `cell${row}-${col}`;
cellDiv.addEventListener("click", () => updateFocus(col));
const frontDiv = document.createElement("div");
frontDiv.className = "front";
const backDiv = document.createElement("div");
backDiv.className = "back";
cellDiv.appendChild(frontDiv);
cellDiv.appendChild(backDiv);
rowDiv.appendChild(cellDiv);
}
gridContainer.appendChild(rowDiv);
}
}
function generateKeyboardLayout(feedbackStyle = "standard") {
let layout;
if (feedbackStyle === "alphabetic") {
//todo update with separate keyboard style variant option
layout = alphabeticalKeyboardLayout;
} else {
layout = standardKeyboardLayout;
}
const keyboardContainer = document.getElementById("keyboard");
keyboardContainer.innerHTML = ""; // Clear existing keyboard
layout.forEach((row, rowIndex) => {
const rowDiv = document.createElement("div");
rowDiv.className = "keyboard-row";
// Add "Enter" at the start of the third row
if (rowIndex === 2) {
const enterKey = document.createElement("button");
enterKey.className = "key enter";
enterKey.textContent = "Enter";
enterKey.id = "key-Enter";
enterKey.addEventListener("click", () => handleKeyClick("Enter"));
rowDiv.appendChild(enterKey);
}
row.split("").forEach((key) => {
const keyButton = document.createElement("button");
keyButton.className = "key";
keyButton.textContent = key;
keyButton.id = `key-${key}`;
keyButton.addEventListener("click", () => handleKeyClick(key));
rowDiv.appendChild(keyButton);
});
// Add "Backspace" at the end of the last row
if (rowIndex === layout.length - 1) {
const backspaceKey = document.createElement("button");
backspaceKey.className = "key backspace";
backspaceKey.textContent = "⌫";
backspaceKey.id = "key-Backspace";
backspaceKey.addEventListener("click", () => handleKeyClick("⌫"));
rowDiv.appendChild(backspaceKey);
}
keyboardContainer.appendChild(rowDiv);
});
}
function generateAlphabetHelper() {
const alphabetHelper = document.getElementById("alphabetHelper");
alphabetHelper.innerHTML = ""; // Clear existing alphabet helper
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
alphabet.split("").forEach((letter) => {
const letterDiv = document.createElement("div");
letterDiv.className = "letter";
letterDiv.textContent = letter;
letterDiv.id = `letter-${letter}`;
alphabetHelper.appendChild(letterDiv);
});
}
function getWordFromUrl() {
const urlParams = new URLSearchParams(window.location.search);
const encodedWord = urlParams.get("w");
if (encodedWord) {
return atob(encodedWord); // Decode from Base64
}
return null; // or default word
}
const resultModal = document.getElementById("resultModal");
const helpModal = document.getElementById("helpModal");
const scoreElement = document.getElementById("gameScore");
const resultHeaderElement = document.getElementById("resultHeader");
const resultTextElement = document.getElementById("resultText");
// const shareButton = document.getElementById("shareButton");
// Function to show the modal with the game's score
function showResultModal(endTitle, endText, guesses, variant, won) {
resultHeaderElement.textContent = `${endTitle}`;
resultTextElement.textContent = `${endText}`;
// hide play again button if daily variant
if (dailyWord) {
document.getElementById("playAgainButton").style.display = "none";
}
// hide buttons if game is not over
if (!gameOver) {
console.log("game is not over, hide buttons");
Ui.setVisibilityByClass("button-row", false, "flex");
} else {
Ui.setVisibilityByClass("button-row", true, "flex");
}
// show completion message if game is over and daily game
if (gameOver && dailyWord) {
showCompletionMessage(endText);
}
resultModal.style.display = "block";
}
// Add event listener to the share buttons
const shareButtons = document.querySelectorAll(".share-button");
shareButtons.forEach((button) => {
button.addEventListener("click", shareClicked);
});
// shareButton.addEventListener("click", () => {
// shareClicked();
// });
function shareClicked(event) {
// needs name, gameWon, statusMapHistory, maxAttempts, targetWord, feedbackStyle
// of which, only gameWon and statusMapHistory should be needed
let resultText =
`${name}, ` +
now.toLocaleDateString("en-US", { month: "short", day: "numeric" }) +
` - ${gameWon ? statusMapHistory.length : "X"}/${maxAttempts} \n`;
// add word to share link, unless daily variant
let shareWord = "";
if (!dailyWord) {
shareWord = targetWord;
}
resultText += generateResultText(
shareWord,
statusMapHistory,
feedbackStyle
);
shareGame(resultText, shareWord);
}
// add event listener to the play again button
document.getElementById("playAgainButton").addEventListener("click", () => {
// reload the page, without the "w" parameter
console.log("reloading");
// window.location = window.location.href.split("?")[0];
window.location = createShareableLink();
});
// Close modal
// closeModal.addEventListener("click", () => {
// modal.style.display = "none";
// });
const closeButtons = document.querySelectorAll(".close-modal-button");
closeButtons.forEach((button) => {
button.addEventListener("click", closeModal);
});
function closeModal(event) {
let modal = event.target.closest(".modal");
if (modal) {
modal.style.display = "none";
}
}
function storeGameState(message, gameOver, won, guesses, statusMapHistory) {
if (!dailyWord) {
// only store game state for daily game
return;
}
console.log("storing game state");
// const today = new Date().toDateString();
const today = now.toDateString();
localStorage.setItem(
"dailyGameCompleted",
JSON.stringify({
date: today,
completed: gameOver,
message: message,
won: won,
guesses: guesses,
statusMapHistory: statusMapHistory,
})
);
}
function showCompletionMessage(message = "") {
const completionMessage = document.getElementById("completionMessage");
completionMessage.style.display = "block";
// append the dynamic message to the completionMessage div
// completionMessage.innerHTML += message;
// set the p id completedMessage to the dynamic message
document.getElementById("completedMessage").textContent = message;