-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwordcraft.html
1738 lines (1500 loc) · 64.8 KB
/
wordcraft.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>WordCraft</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'><rect x='2' y='2' width='20' height='20' fill='%234CAF50'/><rect x='4' y='4' width='16' height='16' fill='%231F2937'/><rect x='10' y='2' width='4' height='20' fill='%23F44336'/><rect x='2' y='10' width='20' height='4' fill='%232196F3'/><rect x='4' y='4' width='4' height='4' fill='%23FFC107'/><rect x='16' y='4' width='4' height='4' fill='%23FFC107'/><rect x='4' y='16' width='4' height='4' fill='%23FF9800'/><rect x='16' y='16' width='4' height='4' fill='%23FF9800'/></svg>">
<script src="https://cdn.tailwindcss.com"></script>
<style>
@keyframes gentle-pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
.animate-gentle-pulse {
animation: gentle-pulse 1.5s ease-in-out infinite;
}
.word-cell {
transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
}
.word-cell.animating {
z-index: 10;
}
.cell {
aspect-ratio: 1;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
position: relative;
border: 1px solid rgba(255, 255, 255, 0.1);
transition: all 0.3s ease;
overflow: hidden;
}
@media (max-width: 768px) {
.cell {
font-size: 0.75rem; /* Default font size */
}
}
.wall {
background-color: #4B5563;
box-shadow: inset -2px -2px 5px rgba(0,0,0,0.3), inset 2px 2px 5px rgba(255,255,255,0.1);
background-image:
linear-gradient(45deg, #3f4652 25%, transparent 25%),
linear-gradient(-45deg, #3f4652 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, #3f4652 75%),
linear-gradient(-45deg, transparent 75%, #3f4652 75%);
background-size: 10px 10px;
background-position: 0 0, 0 5px, 5px -5px, -5px 0px;
}
.empty { background-color: #1F2937; }
.selected-word {
ring: 2px #EAB308;
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
}
.word {
box-shadow: 0 4px 6px rgba(0,0,0,0.1), 0 1px 3px rgba(0,0,0,0.08);
transition: all 0.3s ease;
border-radius: 8px;
transform: translateY(0);
user-select: none;
cursor: pointer;
}
.cell {
user-select: none; /* Prevent text selection */
}
.word::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
border-radius: 8px;
background: linear-gradient(135deg, rgba(255,255,255,0.3) 0%, rgba(255,255,255,0) 100%);
pointer-events: none;
}
.selection-rectangle {
position: absolute;
inset: 0;
border: 4px solid #F0F0F0;
box-shadow: 0 0 8px 2px rgba(240, 240, 240, 0.6);
pointer-events: none;
}
</style>
</head>
<body class="bg-black min-h-screen flex items-center justify-center overflow-hidden" ontouchstart="return true;">
<div id="intro-screen" class="text-center">
<!-- SVG Logo -->
<div class="mb-6">
<svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 mx-auto" viewBox="0 0 24 24">
<rect x="2" y="2" width="20" height="20" fill="#4CAF50" />
<rect x="4" y="4" width="16" height="16" fill="#1F2937" />
<rect x="10" y="2" width="4" height="20" fill="#F44336" />
<rect x="2" y="10" width="20" height="4" fill="#2196F3" />
<rect x="4" y="4" width="4" height="4" fill="#FFC107" />
<rect x="16" y="4" width="4" height="4" fill="#FFC107" />
<rect x="4" y="16" width="4" height="4" fill="#FF9800" />
<rect x="16" y="16" width="4" height="4" fill="#FF9800" />
</svg>
</div>
<!-- Game Title -->
<h1 class="text-4xl font-bold mb-2 text-white">WordCraft</h1>
<p class="text-xl mb-6 text-gray-300">Arrange the words to craft the
target sentence, horizontally or vertically.</p>
<!-- Instructions -->
<div class="text-sm text-gray-400 mb-6">
<p>Use arrow keys or WASD to move the cursor.</p>
<p>Press Enter or Space to select/deselect a word (or use your mouse/touch screen).</p>
<p>Move the words to craft the target sentence either horizontally or vertically (in both directions is OK).</p>
<p>Press R to restart the current level.</p>
</div>
<!-- Play Buttons -->
<!-- Tutorial Button -->
<button id="start-demo" class="bg-green-500 hover:bg-green-700 text-white px-6 py-3 rounded-lg text-lg font-semibold mr-4">
Tutorial
</button>
<button id="start-easy" class="bg-blue-500 hover:bg-blue-700 text-white px-6 py-3 rounded-lg text-lg font-semibold mr-4">
Play (Normal)
</button>
<button id="start-hard" class="bg-red-500 hover:bg-red-700 text-white px-6 py-3 rounded-lg text-lg font-semibold">
Play (Hard)
</button>
<!-- Copyright Notice and Technical Documentation Link -->
<p class="text-xs text-gray-500 mt-4">
© 2024 Vladimir Prelovac. All rights reserved.
<a href="https://github.com/vprelovac/wordcraft" class="text-blue-500 hover:text-blue-700" target="_blank">source</a>
</p>
<script>
document.addEventListener('keydown', function(event) {
if ((event.key === 'Enter' || event.key === ' ') && !document.getElementById('intro-screen').classList.contains('hidden')) {
document.getElementById('start-game').click();
}
});
</script>
</div>
<div id="game-container" class="bg-gray-900 p-4 sm:p-8 rounded-lg shadow-lg max-w-6xl w-full max-h-screen overflow-auto hidden">
<div class="flex flex-col lg:flex-row">
<div id="game-info" class="w-full lg:w-1/4 text-white mb-4 lg:mb-0 order-2 lg:order-1 lg:pt-10">
<p id="level" class="text-xl flex justify-between">Level: <span class="font-bold text-3xl">1</span></p>
<p id="timer" class="text-xl flex justify-between">Time: <span class="font-bold text-3xl">03:00</span></p>
<p id="moves" class="text-xl flex justify-between">Moves: <span class="font-bold text-3xl">0</span></p>
<p id="min-moves" class="text-xl flex justify-between hidden">Minimum: <span class="font-bold text-3xl">0</span></p>
<p id="your-best" class="text-xl flex justify-between hidden">Your Best: <span class="font-bold text-3xl">0</span></p>
<div class="flex space-x-2 mt-4">
<button id="restart-level" class="bg-yellow-500 hover:bg-yellow-700 text-white font-bold py-2 px-4 rounded flex-1">
Restart
</button>
<button id="skip-level" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded flex-1 hidden">
Skip
</button>
</div>
</div>
<div class="flex-grow order-1 lg:order-2 lg:ml-4">
<p id="target-sentence" class="text-lg font-semibold mb-4 text-white">Craft: <span class="text-blue-400"></span></p>
<div id="game-board" class="w-full grid gap-1 bg-gray-800 rounded text-xs sm:text-sm md:text-base" style="grid-template-columns: repeat(8, minmax(30px, 1fr));">
<!-- Game board will be populated by JavaScript -->
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/confetti.browser.min.js"></script>
<script>
// Game constants
const INITIAL_TIMER = 0; // Start from 0 and count up
const EASY_GRID_SIZE = { rows: 8, cols: 8 };
const HARD_GRID_SIZE = { rows: 10, cols: 10 };
let GRID_SIZE = EASY_GRID_SIZE;
let isHardMode = false;
const ANIMATION_DURATION = 200; // milliseconds
const TIME_BONUS_MULTIPLIER = 10;
const MOVE_PENALTY_MULTIPLIER = 5;
const WALL_PERCENTAGE_INITIAL = 0.3;
const WALL_PERCENTAGE_DECREASE = 0.02;
const MIN_WALL_PERCENTAGE = 0.11;
const TIMER_INTERVAL = 10; // 10 milliseconds for smoother updates
const LEVEL_COMPLETION_CHECK_DELAY = 50; // milliseconds
const SWIPE_THRESHOLD = 50; // minimum distance for swipe detection
// Audio context for sound generation
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
// Game mode detection
let isDesktopMode = true;
function detectGameMode() {
isDesktopMode = !('ontouchstart' in window) && !navigator.maxTouchPoints;
console.log(`Game mode detected: ${isDesktopMode ? 'Desktop' : 'Mobile'}`);
}
// Sound generation functions
function playVerySoftSelectionSound() {
// Sound disabled
}
function playVerySoftDeselectionSound() {
// Sound disabled
}
function playSoftSound(frequency) {
// Sound disabled
}
// CSS classes
const CSS_CLASSES = {
CELL: 'aspect-square flex items-center justify-center text-sm font-bold relative',
WALL: 'bg-gray-600',
EMPTY: 'bg-gray-100',
SELECTED_WORD: 'ring-2 ring-yellow-500',
SELECTION_RECTANGLE: 'absolute inset-0 border-4 border-blue-500 pointer-events-none',
ANIMATION: 'animate-gentle-pulse'
};
// Key mappings
const KEY_MAPPINGS = {
UP: ['ArrowUp', 'w', 'W'],
DOWN: ['ArrowDown', 's', 'S'],
LEFT: ['ArrowLeft', 'a', 'A'],
RIGHT: ['ArrowRight', 'd', 'D'],
SELECT: ['Enter', ' '],
RESTART: ['r', 'R'],
NEXT_LEVEL: ['n', 'N']
};
const gameState = {
level: 1,
timer: INITIAL_TIMER,
timerInterval: null,
targetSentence: '',
words: [],
selectedWordIndex: null,
gridSize: GRID_SIZE,
wordPositions: [],
walls: [],
moves: 0,
selectionRectangle: { row: 0, col: 0 },
rng: null,
completedLevels: [],
};
const easyLevels = [
{ sentence: "The quick brown fox", seed: 12345, minMoves: 11 },
{ sentence: "Jumps over the lazy dog", seed: 67894, minMoves: 8 },
{ sentence: "Better late than never friend", seed: 7788, minMoves: 9 },
{ sentence: "Make hay while the sun shines", seed: 13579, knownMinMoves: 20 },
{ sentence: "A stitch in time saves nine", seed: 24226, knownMinMoves: 21 },
{ sentence: "Actions speak louder than words", seed: 11224, minMoves: 10 },
{ sentence: "All that glitters is not gold", seed: 447, knownMinMoves: 25 },
{ sentence: "A rolling stone gathers no moss", seed: 91, knownMinMoves: 21 },
{ sentence: "Fortune always favors the brave soul", seed: 1321, knownMinMoves: 21 },
{ sentence: "Practice makes perfect or at least less bad", seed: 46, knownMinMoves: 29 },
{ sentence: "So you are not tired of this yet", seed: 28, knownMinMoves: 28 },
{ sentence: "This one is for the fans", seed: 12345678, minMoves: 0 },
{ sentence: "Make the most of your time on earth", seed: 12345, knownMinMoves: 24 },
{ sentence: "I dare you to speed run me", seed: 1345, knownMinMoves: 23 },
];
const hardLevels = [
{ sentence: "The quick brown fox", seed: 1, minMoves: 12 },
{ sentence: "Jumps over the lazy dog", seed: 0, knownMinMoves: 21 },
{ sentence: "Better late than never friend", seed: 1240, knownMinMoves: 17 },
{ sentence: "Make hay while the sun shines", seed: 97531, knownMinMoves: 19 },
{ sentence: "A stitch in time saves nine", seed: 444, knownMinMoves: 23 },
{ sentence: "Actions speak louder than words", seed: 5, minMoves: 9 },
{ sentence: "All that glitters is not gold", seed: 744, knownMinMoves: 19 },
{ sentence: "A rolling stone gathers no moss", seed: 261076, knownMinMoves: 25 },
{ sentence: "Fortune always favors the brave soul", seed: 21443, knownMinMoves: 29 },
{ sentence: "Practice makes perfect or at least less bad", seed: 64, knownMinMoves: 25 },
{ sentence: "So you are not tired of this yet", seed: 824, knownMinMoves: 23 },
{ sentence: "This one is for the fans", seed: 821, knownMinMoves: 33 },
{ sentence: "Make the most of your time on earth", seed: 5421, knownMinMoves: 27 },
{ sentence: "I dare you to speed run me", seed: 261076, knownMinMoves: 29 },
];
let levels = easyLevels;
const demoLevel = { sentence: "Welcome to WordCraft", seed: 3 };
const wordColors = [
'bg-red-500', 'bg-blue-500', 'bg-green-500', 'bg-yellow-500',
'bg-purple-500', 'bg-pink-500', 'bg-indigo-500', 'bg-orange-500'
];
// Game Initialization
function initGame(isDemo = false) {
try {
detectGameMode(); // Re-detect game mode in case of window resize or device rotation
if (isDemo) {
gameState.isDemo = true;
gameState.level = 0;
gameState.gridSize = { rows: 4, cols: 4 };
generateLevel(0);
} else {
gameState.isDemo = false;
if (gameState.level < 1 || gameState.level > levels.length) {
throw new Error(`Invalid level: ${gameState.level}`);
}
gameState.gridSize = GRID_SIZE;
generateLevel(gameState.level);
}
// Load completed levels from local storage
const modePrefix = isHardMode ? 'hard_' : '';
const completedLevels = localStorage.getItem(`${modePrefix}completedLevels`);
if (completedLevels) {
gameState.completedLevels = JSON.parse(completedLevels);
} else {
// If no completed levels for hard mode, inherit from easy mode
if (isHardMode) {
const easyCompletedLevels = localStorage.getItem('completedLevels');
gameState.completedLevels = easyCompletedLevels ? JSON.parse(easyCompletedLevels) : [];
} else {
gameState.completedLevels = [];
}
}
// Debug information
// Debug information in CSV format
const csvData = [
['Level', 'Sentence', 'Type', 'Row', 'Col'],
...gameState.wordPositions.map((pos, index) => [gameState.level, gameState.targetSentence, `Word ${index + 1}`, pos.row, pos.col]),
...gameState.walls.map((wall, index) => [gameState.level, gameState.targetSentence, `Wall ${index + 1}`, wall.row, wall.col])
];
console.log(csvData.map(row => row.join(',')).join('\n'));
gameState.moves = 0;
gameState.selectionRectangle = gameState.wordPositions[0]; // Initialize to first word
gameState.selectedWordIndex = 0; // Select first word by default on both desktop and mobile
updateGameInfo();
createGameBoard();
startTimer();
updateMovesDisplay();
// Update UI based on game mode
updateUIForGameMode();
if (isDemo) {
startDemoTutorial();
}
} catch (error) {
console.error("Error initializing game:", error);
alert("An error occurred while initializing the game. Please try again.");
}
}
function startDemoTutorial() {
const tutorialSteps = [
{ message: "Welcome to WordCraft! Let's learn how to play.", target: '#game-board' },
{ message: "Your goal is to arrange the words to form the sentence shown at the top.", target: '#target-sentence' },
{ message: "Words will move until they hit a wall or another word.", target: '#game-board' },
{ message: isDesktopMode ? "Use arrow keys (or WASD) to move around." : "Tap a word to select it.", target: '.selection-rectangle' },
{ message: isDesktopMode ? "Press Enter or Space to select or deselect a word." : "Swipe in any direction to move the selected word.", target: '.word' },
{ message: "Try moving 'to' next to 'Welcome'", target: '#game-board' },
{ message: "Great job! You've completed the tutorial. Now try the real levels!", target: '#game-board' }
];
let currentStep = 0;
function showTutorialStep() {
const step = tutorialSteps[currentStep];
const tooltip = document.createElement('div');
tooltip.className = 'fixed bg-white text-black p-4 rounded-lg shadow-lg z-50';
tooltip.textContent = step.message;
document.body.appendChild(tooltip);
const target = document.querySelector(step.target);
if (target) {
const targetRect = target.getBoundingClientRect();
tooltip.style.left = `${targetRect.left}px`;
tooltip.style.top = `${targetRect.bottom + 10}px`;
}
setTimeout(() => {
document.body.removeChild(tooltip);
currentStep++;
if (currentStep < tutorialSteps.length && step.message !== "Great job! You've completed the tutorial. Now try the real levels!") {
showTutorialStep();
}
}, 5000);
}
showTutorialStep();
}
function updateUIForGameMode() {
const instructionsElement = document.querySelector('#intro-screen .text-sm');
if (isDesktopMode) {
instructionsElement.innerHTML = `
<p>Desktop controls:</p>
<p>- Use arrow keys or WASD to move the cursor.</p>
<p>- Press Enter or Space to select/deselect a word.</p>
<p>- Move the words to craft the target sentence either horizontally or vertically.</p>
<p>- Press R to restart the current level.</p>
`;
} else {
instructionsElement.innerHTML = `
<p>Touch controls (recommended for mobile):</p>
<p>- Tap a word to select/deselect it.</p>
<p>- Swipe in any direction to move the selected word.</p>
<p>- Arrange the words to form the target sentence either horizontally or vertically.</p>
`;
}
}
// Game State Management
function generateLevel(level) {
try {
const { gridSize } = gameState;
if (!gridSize || typeof gridSize.rows !== 'number' || typeof gridSize.cols !== 'number') {
throw new Error('Invalid grid size');
}
const currentLevel = level === 0 ? demoLevel : levels[level - 1];
if (!currentLevel) {
throw new Error(`Level ${level} not found`);
}
gameState.targetSentence = currentLevel.sentence;
if (typeof gameState.targetSentence !== 'string' || gameState.targetSentence.trim() === '') {
throw new Error('Invalid target sentence');
}
gameState.words = gameState.targetSentence.split(' ').filter(word => word.trim() !== '');
if (gameState.words.length === 0) {
throw new Error('No valid words in target sentence');
}
gameState.wordPositions = [];
// Initialize seeded random number generator for this level
gameState.rng = mulberry32(currentLevel.seed);
// Calculate the number of walls based on the level
const totalCells = gridSize.rows * gridSize.cols;
const wallPercentage = level <= 4
? Math.max(WALL_PERCENTAGE_INITIAL - (level - 1) * WALL_PERCENTAGE_DECREASE, MIN_WALL_PERCENTAGE)
: Math.min(WALL_PERCENTAGE_INITIAL + (level - 4) * WALL_PERCENTAGE_DECREASE, WALL_PERCENTAGE_INITIAL);
const numWalls = Math.floor(totalCells * wallPercentage)*(isHardMode?0.5:1);
gameState.walls = [];
if (isHardMode) {
// Add outer walls for hard mode
for (let i = 0; i < gridSize.rows; i++) {
if (gameState.rng() < 0.5) {
gameState.walls.push({ row: i, col: 0 });
}
if (gameState.rng < 0.5) {
gameState.walls.push({ row: i, col: gridSize.cols - 1 });
}
}
for (let j = 0; j < gridSize.cols; j++) {
if (gameState.rng() < 0.5) {
gameState.walls.push({ row: 0, col: j });
}
if (gameState.rng() < 0.5) {
gameState.walls.push({ row: gridSize.rows - 1, col: j });
}
}
}
for (let i = 0; i < numWalls; i++) {
let wall;
let attempts = 0;
const maxAttempts = 100;
do {
wall = {
row: Math.floor(gameState.rng() * gridSize.rows),
col: Math.floor(gameState.rng() * gridSize.cols)
};
attempts++;
if (attempts > maxAttempts) {
throw new Error('Unable to place walls after maximum attempts');
}
} while (isPositionOccupied(wall));
gameState.walls.push(wall);
}
gameState.words.forEach(() => {
let position;
let attempts = 0;
const maxAttempts = 100;
do {
position = {
row: Math.floor(gameState.rng() * gridSize.rows),
col: Math.floor(gameState.rng() * gridSize.cols)
};
attempts++;
if (attempts > maxAttempts) {
throw new Error('Unable to place words after maximum attempts');
}
} while (isPositionOccupied(position) || isPositionIsolated(position));
gameState.wordPositions.push(position);
});
gameState.isAnimating = false; // Add this line to initialize the animation state
} catch (error) {
console.error("Error generating level:", error);
alert("An error occurred while generating the level. Please try again.");
throw error; // Re-throw the error to be caught by the calling function
}
}
function generateLevel2(level) {
try {
const { gridSize } = gameState;
if (!gridSize || typeof gridSize.rows !== 'number' || typeof gridSize.cols !== 'number') {
throw new Error('Invalid grid size');
}
if (isHardMode) {
}
const currentLevel = levels[level - 1];
if (!currentLevel) {
throw new Error(`Level ${level} not found`);
}
gameState.targetSentence = currentLevel.sentence;
if (typeof gameState.targetSentence !== 'string' || gameState.targetSentence.trim() === '') {
throw new Error('Invalid target sentence');
}
gameState.words = gameState.targetSentence.split(' ').filter(word => word.trim() !== '');
if (gameState.words.length === 0) {
throw new Error('No valid words in target sentence');
}
gameState.wordPositions = [];
// Initialize seeded random number generator for this level
gameState.rng = mulberry32(currentLevel.seed);
// Calculate the number of walls based on the level
const totalCells = gridSize.rows * gridSize.cols;
const wallPercentage = level <= 4
? Math.max(WALL_PERCENTAGE_INITIAL - (level - 1) * WALL_PERCENTAGE_DECREASE, MIN_WALL_PERCENTAGE)
: Math.min(WALL_PERCENTAGE_INITIAL + (level - 4) * WALL_PERCENTAGE_DECREASE, WALL_PERCENTAGE_INITIAL);
let numWalls = Math.floor(totalCells * wallPercentage)*(isHardMode?0.5:1);
gameState.walls = [];
if (isHardMode) {
// Add outer walls for hard mode
for (let i = 0; i < gridSize.rows; i++) {
if (Math.random() < 0.5) {
gameState.walls.push({ row: i, col: 0 });
}
if (Math.random() < 0.5) {
gameState.walls.push({ row: i, col: gridSize.cols - 1 });
}
}
for (let j = 0; j < gridSize.cols; j++) {
if (Math.random() < 0.5) {
gameState.walls.push({ row: 0, col: j });
}
if (Math.random() < 0.5) {
gameState.walls.push({ row: gridSize.rows - 1, col: j });
}
}
}
for (let i = 0; i < numWalls; i++) {
let wall;
let attempts = 0;
const maxAttempts = 10000;
do {
wall = {
row: Math.floor(gameState.rng() * gridSize.rows),
col: Math.floor(gameState.rng() * gridSize.cols)
};
attempts++;
if (attempts > maxAttempts) {
throw new Error('Unable to place walls after maximum attempts');
}
} while (isPositionOccupied(wall));
gameState.walls.push(wall);
}
gameState.words.forEach(() => {
let position;
let attempts = 0;
const maxAttempts = 10000;
do {
position = {
row: Math.floor(gameState.rng() * gridSize.rows),
col: Math.floor(gameState.rng() * gridSize.cols)
};
attempts++;
if (attempts > maxAttempts) {
throw new Error('Unable to place words after maximum attempts');
}
} while (isPositionOccupied(position));
gameState.wordPositions.push(position);
});
gameState.isAnimating = false; // Add this line to initialize the animation state
} catch (error) {
console.error("Error generating level:", error);
alert("An error occurred while generating the level. Please try again.");
throw error; // Re-throw the error to be caught by the calling function
}
}
function isPositionIsolated(position) {
if (isHardMode) {
return false
}
const { row, col } = position;
const { gridSize, walls, wordPositions } = gameState;
// Check horizontal path
let leftBlocked = false;
let rightBlocked = false;
for (let c = col - 1; c >= 0; c--) {
if (walls.some(w => w.row === row && w.col === c)) {
leftBlocked = true;
break;
}
if (wordPositions.some(pos => pos.row === row && pos.col === c)) {
leftBlocked = false;
break;
}
}
for (let c = col + 1; c < gridSize.cols; c++) {
if (walls.some(w => w.row === row && w.col === c)) {
rightBlocked = true;
break;
}
if (wordPositions.some(pos => pos.row === row && pos.col === c)) {
rightBlocked = false;
break;
}
}
// Check vertical path
let topBlocked = false;
let bottomBlocked = false;
for (let r = row - 1; r >= 0; r--) {
if (walls.some(w => w.row === r && w.col === col)) {
topBlocked = true;
break;
}
if (wordPositions.some(pos => pos.row === r && pos.col === col)) {
topBlocked = false;
break;
}
}
for (let r = row + 1; r < gridSize.rows; r++) {
if (walls.some(w => w.row === r && w.col === col)) {
bottomBlocked = true;
break;
}
if (wordPositions.some(pos => pos.row === r && pos.col === col)) {
bottomBlocked = false;
break;
}
}
return (leftBlocked && rightBlocked) || (topBlocked && bottomBlocked);
}
function isPositionOccupied({ row, col }, excludeWordIndex = -1) {
return gameState.wordPositions.some((pos, index) =>
index !== excludeWordIndex && pos.row === row && pos.col === col
) ||
gameState.walls.some(wall => wall.row === row && wall.col === col);
}
function findEmptyPosition() {
const { gridSize } = gameState;
for (let row = 0; row < gridSize.rows; row++) {
for (let col = 0; col < gridSize.cols; col++) {
if (!isPositionOccupied({ row, col })) {
return { row, col };
}
}
}
return { row: 0, col: 0 }; // Default position if no empty space is found
}
// Utility Functions
function mulberry32(a) {
return function() {
var t = a += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
}
function formatTime(milliseconds, showMs = false) {
const totalSeconds = Math.floor(milliseconds / 1000);
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
const ms = milliseconds % 1000;
const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
return showMs ? `${timeString}.${ms.toString().padStart(3, '0')}` : timeString;
}
function isOutOfBounds({ row, col }, gridSize) {
return row < 0 || row >= gridSize.rows || col < 0 || col >= gridSize.cols;
}
function getNextPosition(currentPosition, direction) {
return {
row: currentPosition.row + directionMap[direction].row,
col: currentPosition.col + directionMap[direction].col
};
}
function isValidMove(position, selectedWordIndex) {
const { gridSize, walls, wordPositions } = gameState;
return !isOutOfBounds(position, gridSize) &&
!walls.some(wall => wall.row === position.row && wall.col === position.col) &&
!wordPositions.some((pos, index) => index !== selectedWordIndex && pos.row === position.row && pos.col === position.col);
}
function isPositionOccupied({ row, col }, excludeWordIndex = -1) {
return gameState.wordPositions.some((pos, index) =>
index !== excludeWordIndex && pos.row === row && pos.col === col
) ||
gameState.walls.some(wall => wall.row === row && wall.col === col);
}
function isPositionIsolated(position) {
const { row, col } = position;
const { gridSize, walls, wordPositions } = gameState;
// Check horizontal path
let leftBlocked = false;
let rightBlocked = false;
for (let c = col - 1; c >= 0; c--) {
if (walls.some(w => w.row === row && w.col === c)) {
leftBlocked = true;
break;
}
if (wordPositions.some(pos => pos.row === row && pos.col === c)) {
leftBlocked = false;
break;
}
}
for (let c = col + 1; c < gridSize.cols; c++) {
if (walls.some(w => w.row === row && w.col === c)) {
rightBlocked = true;
break;
}
if (wordPositions.some(pos => pos.row === row && pos.col === c)) {
rightBlocked = false;
break;
}
}
// Check vertical path
let topBlocked = false;
let bottomBlocked = false;
for (let r = row - 1; r >= 0; r--) {
if (walls.some(w => w.row === r && w.col === col)) {
topBlocked = true;
break;
}
if (wordPositions.some(pos => pos.row === r && pos.col === col)) {
topBlocked = false;
break;
}
}
for (let r = row + 1; r < gridSize.rows; r++) {
if (walls.some(w => w.row === r && w.col === col)) {
bottomBlocked = true;
break;
}
if (wordPositions.some(pos => pos.row === r && pos.col === col)) {
bottomBlocked = false;
break;
}
}
return (leftBlocked && rightBlocked) || (topBlocked && bottomBlocked);
}
function findEmptyPosition() {
const { gridSize } = gameState;
for (let row = 0; row < gridSize.rows; row++) {
for (let col = 0; col < gridSize.cols; col++) {
if (!isPositionOccupied({ row, col })) {
return { row, col };
}
}
}
return { row: 0, col: 0 }; // Default position if no empty space is found
}
// UI Update Functions
function updateGameInfo() {
const targetSentenceElement = document.querySelector('#target-sentence span');
const newHighlightedSentence = highlightCorrectWords(gameState.targetSentence);
if (targetSentenceElement.innerHTML !== newHighlightedSentence) {
targetSentenceElement.innerHTML = newHighlightedSentence;
document.querySelector('#target-sentence').classList.add('animate-gentle-pulse');
setTimeout(() => {
document.querySelector('#target-sentence').classList.remove('animate-gentle-pulse');
}, 1000);
}
document.querySelector('#level span').textContent = gameState.level;
// Update moves display with minimum moves if applicable
const currentLevel = levels[gameState.level - 1];
const movesElement = document.querySelector('#moves span');
const minMovesElement = document.querySelector('#min-moves');
const yourBestElement = document.querySelector('#your-best');
const skipLevelButton = document.getElementById('skip-level');
const modePrefix = isHardMode ? 'hard_' : '';
const bestMoves = localStorage.getItem(`${modePrefix}bestMoves_level${gameState.level}`);
minMovesElement.classList.remove('hidden');
if (currentLevel && currentLevel.minMoves > 0) {
minMovesElement.querySelector('span').textContent = currentLevel.minMoves;
} else if (currentLevel && currentLevel.knownMinMoves > 0) {
minMovesElement.querySelector('span').textContent = currentLevel.knownMinMoves + '?';
} else {
minMovesElement.querySelector('span').textContent = '?';
}
if (bestMoves) {
yourBestElement.classList.remove('hidden');
yourBestElement.querySelector('span').textContent = bestMoves;
} else {
yourBestElement.classList.add('hidden');
}
movesElement.textContent = gameState.moves;
// Make both numbers green if they are the same
if (currentLevel && bestMoves && currentLevel.minMoves == bestMoves) {
minMovesElement.querySelector('span').classList.add('text-green-500', 'font-bold');
yourBestElement.querySelector('span').classList.add('text-green-500', 'font-bold');
} else {
minMovesElement.querySelector('span').classList.remove('text-green-500', 'font-bold');
yourBestElement.querySelector('span').classList.remove('text-green-500', 'font-bold');
}
// Show or hide Skip Level button
if (gameState.completedLevels.includes(gameState.level)) {
skipLevelButton.classList.remove('hidden');
} else {
skipLevelButton.classList.add('hidden');
}
}
function highlightCorrectWords(sentence) {
const words = sentence.split(' ');
const correctPositions = findCorrectWordPositions();
return words.map((word, index) =>
correctPositions.includes(index)
? `<span class="text-green-500 font-bold">${word}</span>`
: word
).join(' ');
}
function findCorrectWordPositions() {
const { gridSize, wordPositions, words, targetSentence } = gameState;
const targetWords = targetSentence.split(' ');
const correctPositions = new Set();
const directions = [
{ dx: 1, dy: 0 }, // right
{ dx: 0, dy: 1 }, // down
{ dx: -1, dy: 0 }, // left
{ dx: 0, dy: -1 } // up
];
// Find the first word of the sentence
const firstWordIndex = wordPositions.findIndex(pos => words[wordPositions.indexOf(pos)] === targetWords[0]);
if (firstWordIndex === -1) return [];
const startPos = wordPositions[firstWordIndex];
for (const direction of directions) {
let x = startPos.col;
let y = startPos.row;
// Check if there's enough space in this direction
let spaceAvailable = true;
for (let i = 0; i < targetWords.length; i++) {
if (x < 0 || x >= gridSize.cols || y < 0 || y >= gridSize.rows) {
spaceAvailable = false;
break;
}
x += direction.dx;
y += direction.dy;
}
if (!spaceAvailable) continue;
// Reset position and check words
x = startPos.col;
y = startPos.row;
let matchedWords = [];
for (let i = 0; i < targetWords.length; i++) {
const wordIndex = wordPositions.findIndex(pos => pos.row === y && pos.col === x);
if (wordIndex !== -1 && words[wordIndex] === targetWords[i]) {
matchedWords.push(wordIndex);
}
x += direction.dx;
y += direction.dy;
}
matchedWords.forEach(index => correctPositions.add(index));
}
return Array.from(correctPositions);
}
function updateTimerDisplay() {
document.querySelector('#timer span').textContent = formatTime(gameState.timer, false);
}
function updateMovesDisplay() {
document.querySelector('#moves span').textContent = gameState.moves;
}
function createGameBoard() {
const { gridSize, walls } = gameState;
const gameBoard = document.getElementById('game-board');
const fragment = document.createDocumentFragment();
gameBoard.style.gridTemplateColumns = `repeat(${gridSize.cols}, minmax(40px, 1fr))`;
for (let row = 0; row < gridSize.rows; row++) {
for (let col = 0; col < gridSize.cols; col++) {
const cell = document.createElement('div');
cell.className = 'cell';
cell.classList.add(walls.some(wall => wall.row === row && wall.col === col) ? 'wall' : 'empty');
fragment.appendChild(cell);
}
}
gameBoard.innerHTML = '';
gameBoard.appendChild(fragment);
updateGameBoard();
// Remove click event listener and rely on touch events for mobile
gameBoard.removeEventListener('click', handleCellClick);
}
function updateGameBoard() {
const { gridSize, wordPositions, words, walls, selectedWordIndex, selectionRectangle } = gameState;
const gameBoard = document.getElementById('game-board');
const cells = gameBoard.children;
for (let i = 0; i < cells.length; i++) {
const row = Math.floor(i / gridSize.cols);
const col = i % gridSize.cols;
const cell = cells[i];
const wordIndex = wordPositions.findIndex(pos => pos.row === row && pos.col === col);
cell.textContent = wordIndex !== -1 ? words[wordIndex] : '';
cell.className = 'cell';
if (walls.some(wall => wall.row === row && wall.col === col)) {
cell.classList.add('wall');
} else if (wordIndex !== -1) {
cell.classList.add('word', wordColors[wordIndex % wordColors.length]);
if (wordIndex === selectedWordIndex) {
cell.classList.add('selected-word');
}
} else {
cell.classList.add('empty');
}
// Draw selection rectangle
if (row === selectionRectangle.row && col === selectionRectangle.col) {
const selectionRect = cell.querySelector('.selection-rectangle') || document.createElement('div');
selectionRect.className = 'selection-rectangle';
cell.appendChild(selectionRect);
} else {
const existingRect = cell.querySelector('.selection-rectangle');
if (existingRect) {
cell.removeChild(existingRect);
}
}
// Animate selected word
if (wordIndex === selectedWordIndex) {
cell.classList.add('animate-gentle-pulse');
} else {