-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
2966 lines (2655 loc) · 116 KB
/
script.js
File metadata and controls
2966 lines (2655 loc) · 116 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
// ============================================================
// WORD TRAIL
// ============================================================
// ─────────────────────────────────────────────
// THEME DEFINITIONS
// ─────────────────────────────────────────────
const THEMES = {
default: {
name: 'Forest',
icon: '🌿',
desc: 'Deep forest zen',
locked: false,
cost: 0,
menuImages: [
'assets/images/menu/zen-bg-menu1.jpg',
'assets/images/menu/zen-bg-menu2.jpg',
'assets/images/menu/zen-bg-menu3.jpg',
],
music: 'assets/sounds/zen-default.mp3',
},
sakura: {
name: 'Sakura',
icon: '🌸',
desc: 'Cherry blossom serenity',
locked: true,
cost: 500,
menuImages: [
'assets/images/menu/zen-bg-sakura1.jpg',
'assets/images/menu/zen-bg-sakura2.jpg',
'assets/images/menu/zen-bg-sakura3.jpg',
],
music: 'assets/sounds/zen-sakura.mp3',
},
ocean: {
name: 'Ocean',
icon: '🌊',
desc: 'Abyssal depths',
locked: true,
cost: 800,
menuImages: [
'assets/images/menu/zen-bg-ocean1.jpg',
'assets/images/menu/zen-bg-ocean2.jpg',
'assets/images/menu/zen-bg-ocean3.jpg',
],
music: 'assets/sounds/zen-ocean.mp3',
},
cosmos: {
name: 'Cosmos',
icon: '🌌',
desc: 'Infinite starfields',
locked: true,
cost: 1000,
menuImages: [
'assets/images/menu/zen-bg-cosmos1.jpg',
'assets/images/menu/zen-bg-cosmos2.jpg',
'assets/images/menu/zen-bg-cosmos3.jpg',
],
music: 'assets/sounds/zen-cosmos.mp3',
},
};
const THEME_ORDER = ['default', 'sakura', 'ocean', 'cosmos'];
// ─────────────────────────────────────────────
// CATEGORY BACKGROUND IMAGES
// ─────────────────────────────────────────────
const CAT_BG_IMAGES = {
animals: ['assets/images/animals/bg1.jpg','assets/images/animals/bg2.jpg','assets/images/animals/bg3.jpg','assets/images/animals/bg4.jpg','assets/images/animals/bg5.jpg', 'assets/images/animals/bg6.jpg','assets/images/animals/bg7.jpg','assets/images/animals/bg8.jpg','assets/images/animals/bg9.jpg','assets/images/animals/bg10.jpg'],
nature: ['assets/images/nature/bg1.jpg','assets/images/nature/bg2.jpg','assets/images/nature/bg3.jpg','assets/images/nature/bg4.jpg','assets/images/nature/bg5.jpg', 'assets/images/nature/bg6.jpg','assets/images/nature/bg7.jpg','assets/images/nature/bg8.jpg','assets/images/nature/bg9.jpg','assets/images/nature/bg10.jpg'],
cosmos: ['assets/images/cosmos/bg1.jpg','assets/images/cosmos/bg2.jpg','assets/images/cosmos/bg3.jpg','assets/images/cosmos/bg4.jpg','assets/images/cosmos/bg5.jpg', 'assets/images/cosmos/bg6.jpg','assets/images/cosmos/bg7.jpg','assets/images/cosmos/bg8.jpg','assets/images/cosmos/bg9.jpg','assets/images/cosmos/bg10.jpg'],
zen: ['assets/images/zen/bg1.jpg','assets/images/zen/bg2.jpg','assets/images/zen/bg3.jpg','assets/images/zen/bg4.jpg','assets/images/zen/bg5.jpg', 'assets/images/zen/bg6.jpg','assets/images/zen/bg7.jpg','assets/images/zen/bg8.jpg','assets/images/zen/bg9.jpg','assets/images/zen/bg10.jpg'],
ocean: ['assets/images/ocean/bg1.jpg','assets/images/ocean/bg2.jpg','assets/images/ocean/bg3.jpg','assets/images/ocean/bg4.jpg','assets/images/ocean/bg5.jpg', 'assets/images/ocean/bg6.jpg','assets/images/ocean/bg7.jpg','assets/images/ocean/bg8.jpg','assets/images/ocean/bg9.jpg','assets/images/ocean/bg10.jpg'],
seasons: ['assets/images/seasons/bg1.jpg','assets/images/seasons/bg2.jpg','assets/images/seasons/bg3.jpg','assets/images/seasons/bg4.jpg','assets/images/seasons/bg5.jpg', 'assets/images/seasons/bg6.jpg','assets/images/seasons/bg7.jpg','assets/images/seasons/bg8.jpg','assets/images/seasons/bg9.jpg','assets/images/seasons/bg10.jpg'],
mystical: ['assets/images/mystical/bg1.jpg','assets/images/mystical/bg2.jpg','assets/images/mystical/bg3.jpg','assets/images/mystical/bg4.jpg','assets/images/mystical/bg5.jpg', 'assets/images/mystical/bg6.jpg','assets/images/mystical/bg7.jpg','assets/images/mystical/bg8.jpg','assets/images/mystical/bg9.jpg','assets/images/mystical/bg10.jpg'],
};
// ─────────────────────────────────────────────
// LEVEL TITLES
// ─────────────────────────────────────────────
const LEVEL_TITLES = [
{ level: 1, title: "Seedling", desc: "Just beginning the path", icon: "fas fa-seedling" },
{ level: 8, title: "Trail Walker", desc: "Finding your first footing", icon: "fas fa-shoe-prints" },
{ level: 18, title: "Forest Seeker", desc: "Eyes open, mind beginning to calm", icon: "fas fa-tree" },
{ level: 30, title: "Stream Follower", desc: "Learning to go with the flow", icon: "fas fa-water" },
{ level: 45, title: "Stone Carver", desc: "Patience shaping something permanent", icon: "fas fa-mountain" },
{ level: 60, title: "Wind Reader", desc: "Sensing what others miss", icon: "fas fa-wind" },
{ level: 78, title: "Dawn Walker", desc: "Rising before the rest of the world", icon: "fas fa-sun" },
{ level: 95, title: "Zen Apprentice", desc: "Discipline is becoming second nature", icon: "fas fa-yin-yang" },
{ level: 115, title: "Word Weaver", desc: "Language begins to flow through you", icon: "fas fa-pen-nib" },
{ level: 135, title: "Night Scout", desc: "Comfort in navigating the unknown", icon: "fas fa-moon" },
{ level: 155, title: "Storm Walker", desc: "Unbothered by difficulty or confusion", icon: "fas fa-bolt" },
{ level: 175, title: "Deep Reader", desc: "Finding layers where others see plain", icon: "fas fa-book-open" },
{ level: 200, title: "Path Keeper", desc: "Guardian of the way forward", icon: "fas fa-map" },
{ level: 225, title: "Wandering Sage", desc: "Wisdom deepens with each step taken", icon: "fas fa-scroll" },
{ level: 255, title: "Lotus Master", desc: "Rooted deep, always rising upward", icon: "fas fa-spa" },
{ level: 285, title: "Celestial Eye", desc: "Seeing patterns beyond the grid", icon: "fas fa-eye" },
{ level: 320, title: "Dragon Scholar", desc: "Fierce intellect, serene presence", icon: "fas fa-dragon" },
{ level: 355, title: "Void Dancer", desc: "Moving gracefully between the letters", icon: "fas fa-infinity" },
{ level: 390, title: "Grand Seeker", desc: "Approaching the summit of one trail", icon: "fas fa-compass" },
{ level: 430, title: "Word Sovereign", desc: "Mastery over language and the grid", icon: "fas fa-crown" },
{ level: 470, title: "Zenith Walker", desc: "The summit was just a new beginning", icon: "fas fa-star" },
{ level: 520, title: "Ember Keeper", desc: "The inner flame burns steady and true", icon: "fas fa-fire-flame-curved" },
{ level: 570, title: "Echo Listener", desc: "Words resonate long after they're found", icon: "fas fa-ear-listen" },
{ level: 620, title: "Tide Watcher", desc: "Patient as the eternal ocean's pull", icon: "fas fa-water" },
{ level: 675, title: "Root Binder", desc: "Anchored in deep, hard-won knowledge", icon: "fas fa-leaf" },
{ level: 730, title: "Sky Scribe", desc: "Writing meanings across open skies", icon: "fas fa-cloud" },
{ level: 790, title: "Iron Pilgrim", desc: "Forged stronger by relentless seeking", icon: "fas fa-shield" },
{ level: 850, title: "Rune Keeper", desc: "Ancient letters bend to your will", icon: "fas fa-font" },
{ level: 920, title: "Mist Caller", desc: "Finding clarity deep inside the haze", icon: "fas fa-smog" },
{ level: 990, title: "Phantom Seeker", desc: "Chasing meanings unseen by others", icon: "fas fa-ghost" },
{ level: 1060, title: "Meridian Lord", desc: "Standing at the crossing of all paths", icon: "fas fa-globe" },
{ level: 1140, title: "Veil Piercer", desc: "Truth revealed through quiet patience", icon: "fas fa-eye-slash" },
{ level: 1220, title: "Astral Scribe", desc: "Words flow outward like distant starlight", icon: "fas fa-star-half-stroke" },
{ level: 1300, title: "Thunder Sage", desc: "Immense power held in perfect balance", icon: "fas fa-cloud-bolt" },
{ level: 1380, title: "Abyssal Reader", desc: "No depth can conceal a word from you", icon: "fas fa-magnifying-glass" },
{ level: 1450, title: "Eternal Pilgrim", desc: "The journey itself became the reward", icon: "fas fa-person-hiking" },
{ level: 1520, title: "Cosmos Weaver", desc: "Stitching galaxies together with language", icon: "fas fa-atom" },
{ level: 1600, title: "Oracle of Words", desc: "Answers arrive before the questions do", icon: "fas fa-circle-question" },
{ level: 1680, title: "Grand Zenith", desc: "Among the highest word-walkers ever", icon: "fas fa-mountain-sun" },
{ level: 1760, title: "Infinite Seeker", desc: "True mastery has no final form", icon: "fas fa-infinity" },
{ level: 1400, title: "Word Transcendent", desc: "Beyond the trail — you are the path", icon: "fas fa-meteor" },
];
// ─────────────────────────────────────────────
// PER-CATEGORY AMBIENT SFX
// ─────────────────────────────────────────────
const CAT_AMBIENT = {
animals: 'assets/sounds/ambient-animals.mp3',
nature: 'assets/sounds/ambient-nature.mp3',
cosmos: 'assets/sounds/ambient-cosmos.mp3',
zen: 'assets/sounds/ambient-zen.mp3',
ocean: 'assets/sounds/ambient-ocean.mp3',
seasons: 'assets/sounds/ambient-seasons.mp3',
mystical: 'assets/sounds/ambient-mystical.mp3',
};
let _ambientAudio = null;
let _ambientFadeTimer = null;
let _ambientCurrentCat = null;
let _ambientPrimed = false;
let _ambientPrimedCat = null;
let _ambientLoopTimer = null;
const AMBIENT_FADE_OUT_MS = 2800;
const AMBIENT_FADE_IN_MS = 2800;
function _scheduleAmbientLoop(audioRef, targetVol) {
audioRef._loopTarget = targetVol;
function _onEnded() {
if (audioRef !== _ambientAudio) return;
audioRef.currentTime = 0;
audioRef._fadingOut = false;
audioRef.play().catch(() => {});
_fadeAmbientTo(targetVol, AMBIENT_FADE_IN_MS);
_scheduleAmbientLoop(audioRef, targetVol);
}
function _onTimeUpdate() {
if (audioRef !== _ambientAudio) {
audioRef.removeEventListener('timeupdate', _onTimeUpdate);
audioRef.removeEventListener('ended', _onEnded);
return;
}
if (!audioRef.duration || isNaN(audioRef.duration)) return;
const timeLeft = audioRef.duration - audioRef.currentTime;
if (timeLeft <= AMBIENT_FADE_OUT_MS / 1000 + 0.1 && !audioRef._fadingOut) {
audioRef._fadingOut = true;
audioRef.removeEventListener('timeupdate', _onTimeUpdate);
audioRef.removeEventListener('ended', _onEnded);
_fadeAmbientTo(0, AMBIENT_FADE_OUT_MS, () => {
if (audioRef !== _ambientAudio) return;
audioRef.currentTime = 0;
audioRef._fadingOut = false;
audioRef.play().catch(() => {});
_fadeAmbientTo(targetVol, AMBIENT_FADE_IN_MS);
_scheduleAmbientLoop(audioRef, targetVol);
});
}
}
audioRef.removeEventListener('timeupdate', audioRef._loopTimeUpdate);
audioRef.removeEventListener('ended', audioRef._loopEnded);
audioRef._loopTimeUpdate = _onTimeUpdate;
audioRef._loopEnded = _onEnded;
audioRef.addEventListener('timeupdate', _onTimeUpdate);
audioRef.addEventListener('ended', _onEnded);
}
function primeAmbient(catKey) {
if (!S.settings.sfx) return;
const src = CAT_AMBIENT[catKey];
if (!src) return;
if (_ambientPrimedCat === catKey && _ambientAudio) return;
if (_ambientAudio) { _ambientAudio.pause(); _ambientAudio = null; }
_ambientPrimed = false;
_ambientPrimedCat = catKey;
const a = new Audio(src);
a.loop = false;
a.volume = 0;
a.play().then(() => {
a.pause();
a.currentTime = 0;
_ambientAudio = a;
_ambientPrimed = true;
}).catch(() => {
_ambientPrimed = false;
});
}
function startCatAmbient(catKey) {
if (!S.settings.sfx) return;
const src = CAT_AMBIENT[catKey];
if (!src) return;
if (_ambientCurrentCat === catKey && _ambientAudio && !_ambientAudio.paused) return;
_ambientCurrentCat = catKey;
if (_ambientAudio && _ambientPrimed && _ambientPrimedCat === catKey) {
_ambientAudio.loop = false;
_ambientAudio.volume = 0;
_ambientAudio.play().catch(() => {});
_fadeAmbientTo(1.0, 2400);
_ambientPrimed = false;
_scheduleAmbientLoop(_ambientAudio, 1.0);
} else {
if (_ambientAudio) { _ambientAudio.pause(); _ambientAudio = null; }
const a = new Audio(src);
a.loop = false;
a.volume = 0;
_ambientAudio = a;
a.play().catch(() => {});
_fadeAmbientTo(1.0, 2400);
_scheduleAmbientLoop(a, 1.0);
}
}
function stopCatAmbient(fadeDurationMs = 2400) {
if (_ambientFadeTimer) { clearInterval(_ambientFadeTimer); _ambientFadeTimer = null; }
if (_ambientLoopTimer) { clearTimeout(_ambientLoopTimer); _ambientLoopTimer = null; }
const dying = _ambientAudio;
_ambientAudio = null;
_ambientCurrentCat = null;
_ambientPrimed = false;
_ambientPrimedCat = null;
if (!dying) return;
const steps = 30;
const interval = fadeDurationMs / steps;
const startVol = dying.volume;
let step = 0;
const t = setInterval(() => {
step++;
dying.volume = Math.max(0, startVol - (startVol / steps) * step);
if (step >= steps) { clearInterval(t); dying.pause(); dying.currentTime = 0; }
}, interval);
}
function _fadeAmbientTo(targetVol, durationMs, onDone) {
if (!_ambientAudio) { if (onDone) onDone(); return; }
if (_ambientFadeTimer) { clearInterval(_ambientFadeTimer); _ambientFadeTimer = null; }
const steps = 20;
const interval = durationMs / steps;
const startVol = _ambientAudio ? _ambientAudio.volume : 0;
const delta = (targetVol - startVol) / steps;
let step = 0;
const ref = _ambientAudio;
_ambientFadeTimer = setInterval(() => {
step++;
if (!ref) { clearInterval(_ambientFadeTimer); _ambientFadeTimer = null; if (onDone) onDone(); return; }
ref.volume = Math.min(1, Math.max(0, startVol + delta * step));
if (step >= steps) {
ref.volume = targetVol;
clearInterval(_ambientFadeTimer);
_ambientFadeTimer = null;
if (onDone) onDone();
}
}, interval);
}
function getTitleForLevel(l) {
let t = LEVEL_TITLES[0];
for (const lt of LEVEL_TITLES) { if (l >= lt.level) t = lt; else break; }
return t;
}
function getNextTitle(l) {
for (const lt of LEVEL_TITLES) { if (lt.level > l) return lt; }
return null;
}
const CAT_ORDER = ['animals', 'nature', 'cosmos', 'zen', 'ocean', 'seasons', 'mystical'];
// ─────────────────────────────────────────────
// DIFFICULTY SCALING
// ─────────────────────────────────────────────
function getDifficultyConfig(catKey) {
const lv = S.currentLevel;
let wordCount;
if (lv <= 3) wordCount = 3;
else if (lv <= 15) wordCount = 5;
else if (lv <= 40) wordCount = 6;
else if (lv <= 80) wordCount = 7;
else if (lv <= 130) wordCount = 8;
else if (lv <= 190) wordCount = 9;
else wordCount = 10;
let dirs = ['H', 'V'];
if (lv >= 20) dirs.push('HR', 'VR');
if (lv >= 40) dirs.push('DR', 'DL');
if (lv >= 65) dirs.push('DRR', 'DLR');
const absMax = lv <= 3 ? 4 : 13;
let prefMin, prefMax;
if (lv <= 3) { prefMin = 3; prefMax = 4; }
else if (lv <= 20) { prefMin = 3; prefMax = 5; }
else if (lv <= 40) { prefMin = 3; prefMax = 6; }
else if (lv <= 65) { prefMin = 3; prefMax = 7; }
else if (lv <= 90) { prefMin = 3; prefMax = 8; }
else if (lv <= 130) { prefMin = 4; prefMax = 10; }
else { prefMin = 5; prefMax = 13; }
return { wordCount, dirs, prefMin, prefMax, absMax };
}
function computeGridSize(words) {
if (!words || words.length === 0) return 8;
const lv = S.currentLevel;
const longestLen = Math.max(...words.map(w => w.w.length));
const totalChars = words.reduce((s, w) => s + w.w.length, 0);
const byLength = longestLen + 1;
const byDensity = Math.ceil(Math.sqrt(totalChars * 2.2));
const minGrid = lv <= 3 ? 4 : 5;
return Math.min(14, Math.max(minGrid, byLength, byDensity));
}
// ─────────────────────────────────────────────
// SAVE STATE
// ─────────────────────────────────────────────
let S = {
currentLevel: 1,
score: 0,
coins: 0,
streak: 0,
totalWordsFound: 0,
settings: { music: true, sfx: true, vibrate: true, clues: true, theme: 'default' },
unlockedThemes: ['default'],
currentGame: null,
savedGame: null,
activityLog: [],
lastCat: 'animals',
unlockedCats: ['animals'],
usedWords: { animals: [] },
catSession: { animals: 0 },
catCycles: { animals: 0 },
allPathsComplete: false,
allPathsShownCinematic: false,
gridSkin: 'default',
ownedSkins: ['default'],
shownUnlocks: [],
};
// ─────────────────────────────────────────────
// ALL PATHS COMPLETE CHECK
// ─────────────────────────────────────────────
function areAllPathsComplete() {
return CAT_ORDER.every(key => {
const cat = CATEGORIES[key];
const found = S.usedWords[key] || [];
return cat && cat.words.every(w => found.includes(w.w));
});
}
function resetAllPathsForReplay() {
CAT_ORDER.forEach(key => {
S.usedWords[key] = [];
S.catCycles[key] = (S.catCycles[key] || 0) + 1;
});
CAT_ORDER.forEach(key => {
if (!S.unlockedCats.includes(key)) S.unlockedCats.push(key);
if (!S.catSession[key]) S.catSession[key] = 0;
});
S.allPathsComplete = true;
save();
}
// ─────────────────────────────────────────────
// MENU BACKGROUND SYSTEM
// ─────────────────────────────────────────────
let _menuLayerFront = null;
let _menuLayerBack = null;
let menuBgIndex = 0;
let menuBgTimer = null;
const MENU_BG_INTERVAL = 300000;
const MENU_FADE_MS = 2800;
const MENU_FADE_EASE = 'cubic-bezier(0.45, 0, 0.25, 1)';
function _buildMenuBgLayers() {
const menuEl = document.getElementById('screen-menu');
if (!menuEl || _menuLayerFront) return;
_menuLayerBack = document.createElement('div');
_menuLayerBack.className = 'menu-bg-layer';
_menuLayerBack.id = 'menu-bg-back';
_menuLayerBack.style.cssText = `
position:absolute;inset:0;background-size:cover;background-position:center;
z-index:1;pointer-events:none;opacity:0;will-change:opacity;
`;
_menuLayerFront = document.createElement('div');
_menuLayerFront.className = 'menu-bg-layer';
_menuLayerFront.id = 'menu-bg-front';
_menuLayerFront.style.cssText = `
position:absolute;inset:0;background-size:cover;background-position:center;
z-index:2;pointer-events:none;opacity:1;will-change:opacity;
`;
menuEl.insertBefore(_menuLayerBack, menuEl.firstChild);
menuEl.insertBefore(_menuLayerFront, menuEl.firstChild);
}
function getMenuImages() {
const td = THEMES[S.settings.theme] || THEMES.default;
return td.menuImages || [];
}
function preloadImage(src) {
return new Promise(resolve => {
const img = new Image();
img.onload = () => resolve(src);
img.onerror = () => resolve(src);
img.src = src;
});
}
function setMenuBgDirect(src, animate = false) {
_buildMenuBgLayers();
_menuLayerFront.style.transition = 'none';
_menuLayerBack.style.transition = 'none';
_menuLayerFront.style.backgroundImage = `url('${src}')`;
_menuLayerBack.style.backgroundImage = `url('${src}')`;
_menuLayerBack.style.opacity = '0';
if (animate) {
_menuLayerFront.style.opacity = '0';
_menuLayerFront.style.transform = 'scale(1.08)';
_menuLayerFront.classList.remove('menu-bg-reveal');
void _menuLayerFront.offsetWidth;
_menuLayerFront.classList.add('menu-bg-reveal');
setTimeout(() => {
_menuLayerFront.style.opacity = '1';
_menuLayerFront.style.transform = 'scale(1)';
_menuLayerFront.classList.remove('menu-bg-reveal');
}, 1450);
} else {
_menuLayerFront.style.opacity = '1';
_menuLayerFront.style.transform = 'scale(1)';
}
}
let _menuFadeInProgress = false;
async function crossfadeMenuBg(src) {
if (_menuFadeInProgress) return;
_menuFadeInProgress = true;
_buildMenuBgLayers();
await preloadImage(src);
_menuLayerBack.style.transition = 'none';
_menuLayerBack.style.opacity = '0';
_menuLayerBack.style.backgroundImage = `url('${src}')`;
await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
const t = `opacity ${MENU_FADE_MS}ms ${MENU_FADE_EASE}`;
_menuLayerBack.style.transition = t;
_menuLayerFront.style.transition = t;
_menuLayerBack.style.opacity = '1';
_menuLayerFront.style.opacity = '0';
setTimeout(() => {
_menuLayerFront.style.transition = 'none';
_menuLayerFront.style.backgroundImage = `url('${src}')`;
_menuLayerFront.style.opacity = '1';
_menuLayerBack.style.transition = 'none';
_menuLayerBack.style.opacity = '0';
_menuFadeInProgress = false;
}, MENU_FADE_MS + 80);
}
function initMenuBg() {
const images = getMenuImages();
if (!images.length) return;
menuBgIndex = Math.floor(Math.random() * images.length);
setMenuBgDirect(images[menuBgIndex], true);
startMenuBgRotation();
}
function startMenuBgRotation() {
if (menuBgTimer) clearInterval(menuBgTimer);
menuBgTimer = setInterval(() => {
const images = getMenuImages();
if (!images.length) return;
menuBgIndex = (menuBgIndex + 1) % images.length;
crossfadeMenuBg(images[menuBgIndex]);
}, MENU_BG_INTERVAL);
}
function stopMenuBgRotation() {
if (menuBgTimer) { clearInterval(menuBgTimer); menuBgTimer = null; }
}
function refreshMenuBgForTheme() {
_menuFadeInProgress = false;
menuBgIndex = 0;
const images = getMenuImages();
if (!images.length) return;
setMenuBgDirect(images[0]);
startMenuBgRotation();
}
// ─────────────────────────────────────────────
// GAME BACKGROUND SYSTEM
// ─────────────────────────────────────────────
const GAME_BG_OVERLAY_OPACITY = 0.52;
const GAME_FADE_MS = 2400;
const GAME_FADE_EASE = 'cubic-bezier(0.45, 0, 0.25, 1)';
const BG_ROTATE_INTERVAL = 2 * 60 * 1000; // 2 mins lang
let _gameBgFront = null;
let _gameBgBack = null;
let bgCurrentIndex = 0;
let bgRotateTimer = null;
let _gameFadeActive = false;
let _currentCatKey = null;
function _buildGameBgLayers() {
const gameEl = document.getElementById('screen-game');
if (_gameBgFront) return;
_gameBgBack = document.createElement('div');
_gameBgBack.id = 'game-bg-back';
_gameBgBack.style.cssText = `
position:absolute;inset:0;
background-size:cover;background-position:center;
pointer-events:none;will-change:opacity;
z-index:1;opacity:0;
`;
_gameBgFront = document.createElement('div');
_gameBgFront.id = 'game-bg-front';
_gameBgFront.style.cssText = `
position:absolute;inset:0;
background-size:cover;background-position:center;
pointer-events:none;will-change:opacity;
z-index:2;opacity:1;
`;
const overlay = document.createElement('div');
overlay.id = 'game-bg-overlay';
overlay.style.cssText = `
position:absolute;inset:0;
z-index:3;
pointer-events:none;
background:
linear-gradient(to bottom,
rgba(0,0,0,0.55) 0%,
rgba(0,0,0,0.30) 30%,
rgba(0,0,0,0.08) 55%,
rgba(0,0,0,0.00) 70%
),
rgba(0,0,0,${GAME_BG_OVERLAY_OPACITY});
`;
gameEl.insertBefore(overlay, gameEl.firstChild);
gameEl.insertBefore(_gameBgFront, gameEl.firstChild);
gameEl.insertBefore(_gameBgBack, gameEl.firstChild);
Array.from(gameEl.children).forEach(child => {
if (child !== _gameBgBack && child !== _gameBgFront && child !== overlay) {
child.style.position = 'relative';
child.style.zIndex = '4';
}
});
}
function ensureBgLayers() { _buildGameBgLayers(); }
function getCatBgImages(catKey) {
return CAT_BG_IMAGES[catKey] || CAT_BG_IMAGES['animals'];
}
function setGameBgDirect(src) {
_buildGameBgLayers();
_gameBgFront.style.transition = 'none';
_gameBgBack.style.transition = 'none';
_gameBgFront.style.backgroundImage = `url('${src}')`;
_gameBgBack.style.backgroundImage = `url('${src}')`;
_gameBgFront.style.opacity = '1';
_gameBgBack.style.opacity = '0';
}
async function crossfadeGameBg(src) {
if (_gameFadeActive) return;
_gameFadeActive = true;
_buildGameBgLayers();
await preloadImage(src);
_gameBgBack.style.transition = 'none';
_gameBgBack.style.opacity = '0';
_gameBgBack.style.backgroundImage = `url('${src}')`;
await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
const t = `opacity ${GAME_FADE_MS}ms ${GAME_FADE_EASE}`;
_gameBgBack.style.transition = t;
_gameBgFront.style.transition = t;
_gameBgBack.style.opacity = '1';
_gameBgFront.style.opacity = '0';
setTimeout(() => {
_gameBgFront.style.transition = 'none';
_gameBgFront.style.backgroundImage = `url('${src}')`;
_gameBgFront.style.opacity = '1';
_gameBgBack.style.transition = 'none';
_gameBgBack.style.opacity = '0';
_gameFadeActive = false;
}, GAME_FADE_MS + 80);
}
function initGameBgForCategory(catKey) {
stopBgRotation();
_gameFadeActive = false;
if (_gameBgFront) { _gameBgFront.remove(); _gameBgFront = null; }
if (_gameBgBack) { _gameBgBack.remove(); _gameBgBack = null; }
const ov = document.getElementById('game-bg-overlay');
if (ov) ov.remove();
_currentCatKey = catKey;
bgCurrentIndex = Math.floor(Math.random() * getCatBgImages(catKey).length);
_buildGameBgLayers();
setGameBgDirect(getCatBgImages(catKey)[bgCurrentIndex]);
startBgRotation();
}
function resetBgForThemeChange() {
initGameBgForCategory(_currentCatKey || G.catKey || 'animals');
}
function startBgRotation() {
if (bgRotateTimer) clearInterval(bgRotateTimer);
bgRotateTimer = setInterval(() => {
const images = getCatBgImages(_currentCatKey || G.catKey || 'animals');
bgCurrentIndex = (bgCurrentIndex + 1) % images.length;
crossfadeGameBg(images[bgCurrentIndex]);
}, BG_ROTATE_INTERVAL);
}
function stopBgRotation() {
if (bgRotateTimer) { clearInterval(bgRotateTimer); bgRotateTimer = null; }
}
function rotateBgImage() {
const images = getCatBgImages(_currentCatKey || G.catKey || 'animals');
bgCurrentIndex = (bgCurrentIndex + 1) % images.length;
crossfadeGameBg(images[bgCurrentIndex]);
}
// ─────────────────────────────────────────────
// ACTIVE GAME STATE
// ─────────────────────────────────────────────
let G = {
grid: [], gridSize: 0,
words: [],
foundWords: [],
foundCells: [],
bonusWords: [],
foundBonusWords: [],
score: 0,
selecting: false, startCell: null, currentCells: [],
combo: 0, hintUsed: 0,
catKey: 'animals', catName: 'Animals',
};
// ─────────────────────────────────────────────
// IN-GAME MUSIC & SFX
// ─────────────────────────────────────────────
let bgMusic = null;
let bgMusicFadeTimer = null;
let _musicPrimed = false;
function getGameMusicSrc() {
const td = THEMES[S.settings.theme] || THEMES.default;
return td.music || 'assets/sounds/zen-default.mp3';
}
function primeBgMusic() {
if (!S.settings.music) return;
stopBgMusic();
_musicPrimed = false;
const src = getGameMusicSrc();
bgMusic = new Audio(src);
bgMusic.loop = true;
bgMusic.volume = 0;
bgMusic.play().then(() => {
bgMusic.pause();
bgMusic.currentTime = 0;
_musicPrimed = true;
}).catch(() => {
_musicPrimed = false;
});
}
function startBgMusic() {
if (!S.settings.music) return;
if (bgMusic && _musicPrimed) {
bgMusic.volume = 0;
bgMusic.play().catch(() => {});
fadeMusicTo(1.0, 1400);
_musicPrimed = false;
} else {
stopBgMusic();
const src = getGameMusicSrc();
bgMusic = new Audio(src);
bgMusic.loop = true;
bgMusic.volume = 0;
bgMusic.play().catch(() => {});
fadeMusicTo(1.0, 1400);
}
}
function continueBgMusic() {
if (!S.settings.music) return;
if (bgMusic && !bgMusic.paused) { fadeMusicTo(1.0, 900); }
else startBgMusic();
}
function fadeMusicTo(targetVol, durationMs) {
if (!bgMusic) return;
if (bgMusicFadeTimer) clearInterval(bgMusicFadeTimer);
const steps = 30, interval = durationMs / steps;
const startVol = bgMusic.volume, delta = (targetVol - startVol) / steps;
let step = 0;
bgMusicFadeTimer = setInterval(() => {
step++;
if (!bgMusic) { clearInterval(bgMusicFadeTimer); return; }
bgMusic.volume = Math.min(1, Math.max(0, startVol + delta * step));
if (step >= steps) { bgMusic.volume = targetVol; clearInterval(bgMusicFadeTimer); bgMusicFadeTimer = null; }
}, interval);
}
function stopBgMusic() {
if (bgMusicFadeTimer) { clearInterval(bgMusicFadeTimer); bgMusicFadeTimer = null; }
if (bgMusic) { bgMusic.pause(); bgMusic.currentTime = 0; bgMusic = null; }
_musicPrimed = false;
}
function pauseBgMusicSoft() { fadeMusicTo(0.08, 400); }
function resumeBgMusicSoft() { fadeMusicTo(1.0, 600); }
let audioCtx = null, sfxGain = null;
function getCtx() {
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
sfxGain = audioCtx.createGain(); sfxGain.gain.value = 1.10;
sfxGain.connect(audioCtx.destination);
}
if (audioCtx.state === 'suspended') audioCtx.resume();
return audioCtx;
}
function tone(freq, type, dur, t, gain = 0.25) {
if (!S.settings.sfx) return;
try {
const ctx = getCtx(); const o = ctx.createOscillator(), g = ctx.createGain();
o.connect(g); g.connect(sfxGain); o.type = type;
o.frequency.setValueAtTime(freq, t);
g.gain.setValueAtTime(gain, t);
g.gain.exponentialRampToValueAtTime(0.001, t + dur);
o.start(t); o.stop(t + dur + 0.05);
} catch (e) {}
}
function playSound(id) {
if (!S.settings.sfx) return;
try {
const ctx = getCtx(), now = ctx.currentTime;
switch (id) {
case 'click': {
const fund = 370;
const o1 = ctx.createOscillator(), g1 = ctx.createGain();
o1.connect(g1); g1.connect(sfxGain);
o1.type = 'sine';
o1.frequency.setValueAtTime(fund, now);
g1.gain.setValueAtTime(0, now);
g1.gain.linearRampToValueAtTime(0.13, now + 0.004);
g1.gain.exponentialRampToValueAtTime(0.001, now + 0.9);
o1.start(now); o1.stop(now + 0.95);
const o2 = ctx.createOscillator(), g2 = ctx.createGain();
o2.connect(g2); g2.connect(sfxGain);
o2.type = 'sine';
o2.frequency.setValueAtTime(fund * 2.76, now);
g2.gain.setValueAtTime(0, now);
g2.gain.linearRampToValueAtTime(0.05, now + 0.003);
g2.gain.exponentialRampToValueAtTime(0.001, now + 0.35);
o2.start(now); o2.stop(now + 0.40);
break;
}
case 'select': {
const freqs = [392, 440, 523, 587, 659];
const freq = freqs[Math.floor(Math.random() * freqs.length)];
const o = ctx.createOscillator(), g = ctx.createGain();
o.connect(g); g.connect(sfxGain);
o.type = 'sine';
o.frequency.setValueAtTime(freq, now);
g.gain.setValueAtTime(0, now);
g.gain.linearRampToValueAtTime(0.10, now + 0.005);
g.gain.exponentialRampToValueAtTime(0.001, now + 0.10);
o.start(now); o.stop(now + 0.12);
break;
}
case 'drag-cell': {
const pentatonic = [523, 587, 659, 784, 880, 988, 1047];
const idx = Math.min((G.currentCells ? G.currentCells.length - 1 : 0), pentatonic.length - 1);
const freq = pentatonic[idx];
const o = ctx.createOscillator(), g = ctx.createGain();
o.connect(g); g.connect(sfxGain);
o.type = 'triangle';
o.frequency.setValueAtTime(freq, now);
g.gain.setValueAtTime(0, now);
g.gain.linearRampToValueAtTime(0.08, now + 0.004);
g.gain.exponentialRampToValueAtTime(0.001, now + 0.09);
o.start(now); o.stop(now + 0.10);
break;
}
case 'correct': tone(523,'sine',0.12,now,0.28); tone(659,'sine',0.14,now+0.1,0.28); tone(784,'sine',0.16,now+0.2,0.28); tone(1046,'sine',0.18,now+0.32,0.22); break;
case 'wrong': {
const o1 = ctx.createOscillator(), g1 = ctx.createGain();
o1.connect(g1); g1.connect(sfxGain);
o1.type = 'sine';
o1.frequency.setValueAtTime(200, now);
o1.frequency.exponentialRampToValueAtTime(160, now + 0.25);
g1.gain.setValueAtTime(0, now);
g1.gain.linearRampToValueAtTime(0.15, now + 0.006);
g1.gain.exponentialRampToValueAtTime(0.001, now + 0.55);
o1.start(now); o1.stop(now + 0.60);
const o2 = ctx.createOscillator(), g2 = ctx.createGain();
o2.connect(g2); g2.connect(sfxGain);
o2.type = 'sine';
o2.frequency.setValueAtTime(310, now);
g2.gain.setValueAtTime(0, now);
g2.gain.linearRampToValueAtTime(0.06, now + 0.004);
g2.gain.exponentialRampToValueAtTime(0.001, now + 0.18);
o2.start(now); o2.stop(now + 0.20);
if (S.settings.vibrate && navigator.vibrate) navigator.vibrate([18]);
break;
}
case 'hint': tone(660,'sine',0.1,now,0.18); tone(880,'triangle',0.12,now+0.12,0.2); break;
case 'shuffle': for(let i=0;i<7;i++) tone(180+i*70,'square',0.04,now+i*0.035,0.08); break;
case 'combo': tone(880,'triangle',0.1,now,0.12); tone(1100,'triangle',0.1,now+0.08,0.15); break;
case 'unlock': [440,550,660,880].forEach((f,i)=>tone(f,'triangle',0.2,now+i*0.1,0.3)); break;
case 'buy': [523,659,784,1046,1319].forEach((f,i)=>tone(f,'sine',0.25,now+i*0.08,0.3)); break;
case 'levelup': [523,659,784,1046,1319,1568].forEach((f,i)=>tone(f,'sine',0.3,now+i*0.09,0.35)); break;
case 'complete':[262,330,392,523,659,784,1046].forEach((f,i)=>tone(f,'sine',0.35,now+i*0.11,0.45)); if(S.settings.vibrate&&navigator.vibrate) navigator.vibrate([100,50,200,50,300]); break;
case 'already-found': {
const o = ctx.createOscillator(), g = ctx.createGain();
o.connect(g); g.connect(sfxGain);
o.type = 'sine';
o.frequency.setValueAtTime(1046, now);
o.frequency.exponentialRampToValueAtTime(1318, now + 0.12);
g.gain.setValueAtTime(0, now);
g.gain.linearRampToValueAtTime(0.10, now + 0.01);
g.gain.exponentialRampToValueAtTime(0.001, now + 0.28);
o.start(now); o.stop(now + 0.30);
break;
}
case 'deny': {
const od = ctx.createOscillator(), gd = ctx.createGain();
od.connect(gd); gd.connect(sfxGain);
od.type = 'sine';
od.frequency.setValueAtTime(180, now);
od.frequency.exponentialRampToValueAtTime(120, now + 0.5);
gd.gain.setValueAtTime(0, now);
gd.gain.linearRampToValueAtTime(0.18, now + 0.012);
gd.gain.exponentialRampToValueAtTime(0.001, now + 0.7);
od.start(now); od.stop(now + 0.75);
const od2 = ctx.createOscillator(), gd2 = ctx.createGain();
od2.connect(gd2); gd2.connect(sfxGain);
od2.type = 'sine';
od2.frequency.setValueAtTime(360, now);
od2.frequency.exponentialRampToValueAtTime(240, now + 0.4);
gd2.gain.setValueAtTime(0, now);
gd2.gain.linearRampToValueAtTime(0.07, now + 0.008);
gd2.gain.exponentialRampToValueAtTime(0.001, now + 0.45);
od2.start(now); od2.stop(now + 0.5);
break;
}
}
} catch (e) {}
}
function playCorrectByLength(len) {
if (!S.settings.sfx) return;
try {
const ctx = getCtx(), now = ctx.currentTime;
const scales = {
3: [330, 415, 494, 659],
4: [370, 466, 554, 740],
5: [392, 494, 587, 784],
6: [440, 554, 659, 880],
7: [494, 622, 740, 988],
8: [523, 659, 784, 1046],
9: [587, 740, 880, 1175],
};
const notes = scales[Math.min(len, 9)] || scales[9];
const vol = 0.22 + Math.min(len, 10) * 0.012;
notes.forEach((freq, i) => {
tone(freq, 'sine', 0.13 + i * 0.02, now + i * 0.10, vol);
});
if (len >= 8) {
tone(notes[3] * 2, 'sine', 0.10, now + 0.42, vol * 0.5);
}
} catch (e) {}
}
function playComboByIntensity(combo) {
if (!S.settings.sfx) return;
try {
const ctx = getCtx(), now = ctx.currentTime;
if (combo === 2) {
tone(659, 'triangle', 0.10, now, 0.14);
tone(880, 'triangle', 0.12, now + 0.09, 0.16);
}
else if (combo === 3) {
tone(659, 'triangle', 0.12, now, 0.18);
tone(880, 'triangle', 0.13, now + 0.08, 0.20);
tone(1100, 'triangle', 0.14, now + 0.17, 0.22);
}
else if (combo === 4) {
tone(659, 'sine', 0.12, now, 0.20);
tone(880, 'triangle', 0.14, now + 0.08, 0.22);
tone(1100, 'triangle', 0.15, now + 0.16, 0.24);
tone(1320, 'sine', 0.16, now + 0.25, 0.26);
}
else if (combo === 5) {
[659, 784, 880, 1046, 1320].forEach((f, i) => {
tone(f, 'triangle', 0.14 + i * 0.01, now + i * 0.08, 0.22 + i * 0.02);
});
}
else if (combo <= 9) {
const speed = Math.max(0.05, 0.09 - (combo - 6) * 0.008);
const freqs = [659, 784, 880, 1046, 1175, 1320];
const count = Math.min(3 + (combo - 6), freqs.length);
freqs.slice(0, count).forEach((f, i) => {
tone(f, 'triangle', 0.14, now + i * speed, 0.28);
});
tone(220, 'sine', 0.18, now, 0.18);
}
else {
[220, 440, 659, 880, 1046, 1320, 1760].forEach((f, i) => {
tone(f, i % 2 === 0 ? 'sine' : 'triangle', 0.18, now + i * 0.045, 0.32);
});
tone(2093, 'sine', 0.12, now + 0.35, 0.20);
if (S.settings.vibrate && navigator.vibrate) navigator.vibrate([30, 20, 30]);
}
} catch (e) {}
}
function playBonusWordSound(len) {
if (!S.settings.sfx) return;
try {
const ctx = getCtx(), now = ctx.currentTime;
const baseFreqs = [
523, 659, 784, 1046, 1319
];
const count = Math.min(3 + Math.floor((len - 3) / 2), baseFreqs.length);
baseFreqs.slice(0, count).forEach((freq, i) => {
tone(freq, 'sine', 0.14 + i * 0.02, now + i * 0.07, 0.20);
tone(freq * 2, 'sine', 0.08, now + i * 0.07 + 0.04, 0.10);
});