-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1770 lines (1674 loc) · 62.2 KB
/
Copy pathindex.html
File metadata and controls
1770 lines (1674 loc) · 62.2 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Буки Веди</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
height: 100%;
background: #15171f;
color: #ddd;
font-family: 'Georgia', 'Times New Roman', serif;
overflow: hidden;
}
body { display: flex; align-items: center; justify-content: center; padding: 8px; }
#wrap {
position: relative;
width: min(calc(100vw - 16px), calc((100vh - 16px) * 1000 / 960));
aspect-ratio: 1000 / 960;
}
canvas {
background: #1f232f;
display: block;
border-radius: 10px;
box-shadow: 0 0 60px rgba(0,0,0,0.6);
width: 100%;
height: 100%;
}
.overlay {
position: absolute; inset: 0;
display: flex; flex-direction: column; align-items: center; justify-content: center;
background: rgba(21, 23, 31, 0.94);
color: #e8e2d5;
padding: 40px;
text-align: center;
border-radius: 10px;
}
.overlay h1 {
font-size: 56px; letter-spacing: 6px;
margin-bottom: 8px; color: #d4b483;
font-weight: normal;
}
.overlay h2 { color: #b3a98e; font-size: 22px; letter-spacing: 4px; margin-bottom: 24px; font-weight: normal; }
.overlay p { max-width: 580px; margin: 6px 0; line-height: 1.55; color: #c9c2b3; font-size: 17px; }
.byline {
color: #a59a78 !important;
font-style: italic;
font-size: 16px !important;
margin: -6px 0 18px !important;
letter-spacing: 1px;
}
.intro {
max-width: 580px;
text-align: left;
margin: 8px auto 12px;
}
.intro p { margin: 6px 0; font-size: 15px; line-height: 1.5; color: #c2bba6; }
.intro p strong { color: #d4b483; font-weight: 600; }
.overlay button {
margin-top: 28px;
font-family: inherit; font-size: 22px; letter-spacing: 3px;
background: #6b8a72; color: #f3efe5;
border: none; border-radius: 6px; padding: 14px 40px;
cursor: pointer;
transition: background .2s, transform .1s;
}
.overlay button:hover { background: #84a489; }
.overlay button:active { transform: translateY(1px); }
.scores { margin-top: 32px; font-size: 16px; color: #b3a98e; min-width: 280px; }
.scores .row { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px dotted #3a3f4f; }
.scores .row.head { border-bottom: 1px solid #5a5a4f; color: #d4b483; letter-spacing: 2px; }
.controls { margin-top: 22px; font-size: 13px; color: #7d7868; letter-spacing: 1px; }
.level-list {
margin: 26px auto 0;
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: center;
width: 100%; max-width: 720px;
}
.level-list button {
margin-top: 0;
font-size: 18px;
padding: 10px 14px;
flex: 0 1 calc(33.333% - 7px);
min-width: 200px;
max-width: 240px;
}
.level-list button.locked {
background: #34384a; color: #6a6657;
cursor: not-allowed;
}
.level-list button.locked:hover { background: #34384a; }
#wordsList { padding: 18px 24px; }
#wordsList h1 { font-size: 32px; letter-spacing: 4px; margin-bottom: 10px; }
#wordsListContent {
width: 100%; max-width: 920px;
max-height: 78vh; overflow-y: auto;
text-align: left;
padding: 2px 6px;
font-size: 12px;
line-height: 1.25;
}
.words-level {
margin: 0;
padding: 3px 0;
border-bottom: 1px dotted #2c3142;
display: flex;
align-items: baseline;
gap: 10px;
}
.words-level h3 {
color: #d4b483; font-size: 12px; font-weight: normal;
letter-spacing: 1px; margin: 0;
flex: 0 0 110px; /* fixed left column for level name */
white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.words-level h3 .count { color: #7d7868; font-size: 10px; margin-left: 6px; }
.words-grid { display: flex; flex-wrap: wrap; gap: 2px 10px; flex: 1 1 auto; }
.words-grid .word { font-size: 12px; }
.words-grid .word.found { color: #d4b483; font-weight: bold; }
.words-grid .word.missing { color: #5a5a4f; letter-spacing: 1px; }
.hidden { display: none !important; }
</style>
</head>
<body>
<div id="wrap">
<canvas id="game" width="1000" height="960"></canvas>
<div id="menu" class="overlay">
<h1>БУКИ ВЕДИ</h1>
<div class="intro">
<p><strong>Об игре.</strong> Выберите набор уровней — слова в нём появляются в порядке возрастания сложности.</p>
<p><strong>Как играть.</strong> Кликайте по слогам, чтобы складывать слова. Найдите больше половины слов уровня и расчистите тучу — тогда откроется следующий уровень.</p>
<p><strong>Если застряли.</strong> Нажмите <strong>ПРОБЕЛ</strong> — упадут ещё пять слогов. Кнопка <strong>ПОДСКАЗКА</strong> подсветит готовое слово (раз в полторы минуты).</p>
</div>
<div id="levelChooser" class="level-list"></div>
<div class="controls">КЛИК — выбрать слог · ESC — сбросить · ПРОБЕЛ — пять слогов раньше</div>
</div>
<div id="levelPicker" class="overlay hidden">
<h1>УРОВНИ</h1>
<div id="levelPickerList" class="level-list"></div>
<button id="levelPickerClose">ЗАКРЫТЬ</button>
</div>
<div id="wordsList" class="overlay hidden">
<h1>СЛОВА</h1>
<div id="wordsListContent"></div>
<button id="wordsListClose">ЗАКРЫТЬ</button>
</div>
<div id="gameover" class="overlay hidden">
<h1>ИГРА ОКОНЧЕНА</h1>
<p id="finalScore" style="font-size:22px;color:#d4b483;margin-top:10px"></p>
<button id="restart">ИГРАТЬ СНОВА</button>
<div class="scores" id="highscores2"></div>
</div>
</div>
<script src="levels.js"></script>
<script>
"use strict";
// ---- Geometry / palette ----
// Word Cloud: bubbles float freely; gravity pulls them toward the centre and
// AABB collisions push them apart. The player drags one bubble per turn; on
// release the formed word (if any) burns and a new bubble falls in.
const CHAR_W = 45, CELL_H = 55;
const CANVAS_W = 1000, CANVAS_H = 960;
const CENTER_X = CANVAS_W / 2;
const CENTER_Y = (CANVAS_H - 200) / 2 + 30;
const GRAVITY = 1560; // px/s² toward centre at the cloud edge
const DAMPING = 0.86; // velocity multiplier per 60-Hz frame-equivalent
const TOUCH_TOL = 4; // bubbles within this many pixels are "touching"
const COLLISION_ITERS = 6; // positional-correction passes per frame
// Button rectangles are recomputed by recomputeButtonLayout() so they can
// scale up on small viewports for tap-friendly targets.
const EXIT_RECT = { x: 0, y: 0, w: 0, h: 0 };
const LEVELS_RECT = { x: 0, y: 0, w: 0, h: 0 };
const HINT_RECT = { x: 0, y: 0, w: 0, h: 0 };
const COUNTER_RECT = { x: 0, y: 0, w: 0, h: 0 };
let uiScale = 1.0;
const HINT_COOLDOWN = 90; // seconds between hint uses (1:30)
// Decide how big buttons / fonts should be relative to the canvas's internal
// coordinate system. On big desktop displays the canvas renders 1:1 so 1.0
// is fine; on phones the canvas is shrunk by CSS to fit the viewport, so
// we scale internal sizes up to keep tap targets ≥ ~44 display pixels.
function updateUiScale() {
const vw = (typeof window !== 'undefined' && window.innerWidth) || CANVAS_W;
const vh = (typeof window !== 'undefined' && window.innerHeight) || CANVAS_H;
const displayW = Math.min(vw - 16, (vh - 16) * CANVAS_W / CANVAS_H);
const displayScale = displayW / CANVAS_W;
uiScale = Math.max(1, Math.min(2.2, 0.55 / Math.max(0.001, displayScale)));
recomputeButtonLayout();
}
function recomputeButtonLayout() {
const h = Math.round(36 * uiScale);
const y = Math.round(14 * uiScale);
const x0 = Math.round(14 * uiScale);
const gap = Math.round(10 * uiScale);
const exitW = Math.round(96 * uiScale);
EXIT_RECT.x = x0; EXIT_RECT.y = y; EXIT_RECT.w = exitW; EXIT_RECT.h = h;
const levelsW = Math.round(120 * uiScale);
LEVELS_RECT.x = EXIT_RECT.x + EXIT_RECT.w + gap;
LEVELS_RECT.y = y; LEVELS_RECT.w = levelsW; LEVELS_RECT.h = h;
const hintW = Math.round(140 * uiScale);
HINT_RECT.x = CANVAS_W - hintW - x0;
HINT_RECT.y = y; HINT_RECT.w = hintW; HINT_RECT.h = h;
}
if (typeof window !== 'undefined') window.addEventListener('resize', updateUiScale);
updateUiScale();
const HINT_TTL = 5; // seconds the hint halo stays visible
const PALETTE = [
'#c47b6b', // burnt rose
'#7b9c6e', // sage
'#6e8aaf', // muted slate-blue
'#b59a5f', // ochre
'#9b6c8e', // muted plum
'#5e9c97', // teal
'#a6845a', // tan
];
function letterColor(ch) {
let h = 0;
for (let i = 0; i < ch.length; i++) h = (h * 131 + ch.charCodeAt(i)) >>> 0;
return PALETTE[h % PALETTE.length];
}
function lighten(hex, amt) {
const c = hex.replace('#', '');
const num = parseInt(c, 16);
let r = (num >> 16) & 0xff, g = (num >> 8) & 0xff, b = num & 0xff;
r = Math.min(255, Math.round(r + (255 - r) * amt));
g = Math.min(255, Math.round(g + (255 - g) * amt));
b = Math.min(255, Math.round(b + (255 - b) * amt));
return '#' + ((r << 16) | (g << 8) | b).toString(16).padStart(6, '0');
}
// ---- Globals ----
let canvas, ctx;
let state = null;
let dictionary = new Set(); // current level's valid words (rebuilt per level)
let levelPack = null; // selected pack: { name, file }
let levelData = null; // array of arrays of words (one inner array per level)
// Dev mode (?dev=1 in the URL) unlocks every level for quick testing.
const devMode = (typeof window !== 'undefined' && window.location && /(?:^|[?&])dev=1(?:&|$)/.test(window.location.search));
let syllables = null; // current level's syllable inventory (cumulative weights)
let highScores = [];
// ---- Resource loading ----
async function loadFile(url) {
try {
const r = await fetch(url);
if (r.ok) {
const t = await r.text();
if (t && t.length > 0) return t;
}
} catch (e) { /* file:// — fall through */ }
return null;
}
// Build the level's validator: only words listed for the current level count.
function buildDictionaryFromWords(words) {
const set = new Set();
for (const raw of (words || [])) {
const w = (raw || '').toLowerCase();
if (!w || w.length < 4) continue;
if (!/^[a-zа-яё]+$/i.test(w)) continue;
set.add(w);
}
return set;
}
// Split a word into exactly 2 contiguous pieces, each at least MIN_PART
// letters. The cut point is biased toward the middle via a Gaussian weight,
// so a long word like "цивилизация" tends to split as "цивил" + "изация"
// rather than "ци" + "вилизация".
const MIN_PART = 2;
function splitWord(word) {
const L = word.length;
if (L < 2 * MIN_PART) return null;
const candidates = []; // p1 values
const weights = [];
const centre = L / 2;
// Tight bias: even for long words the cut almost always lands within one
// letter of the middle. Constant sigma so the bias doesn't relax with
// length.
const sigma = 0.8;
let total = 0;
for (let p1 = MIN_PART; p1 <= L - MIN_PART; p1++) {
const d = p1 - centre;
const w = Math.exp(-(d * d) / (2 * sigma * sigma));
candidates.push(p1);
weights.push(w);
total += w;
}
if (!candidates.length) return null;
let r = Math.random() * total;
let pick = candidates[0];
for (let i = 0; i < candidates.length; i++) {
r -= weights[i];
if (r <= 0) { pick = candidates[i]; break; }
}
return [word.substr(0, pick), word.substr(pick)];
}
// Cache a 2-part split for every word in the current level.
function preSplitLevelWords(words) {
if (!state.wordSplits) state.wordSplits = new Map();
for (const w of words) {
if (state.wordSplits.has(w)) continue;
const parts = splitWord(w);
if (!parts) continue;
state.wordSplits.set(w, parts.map(p => p.toUpperCase()));
}
}
// Build the level's syllable inventory by partitioning every unguessed pool
// word into 2 or 3 parts. The result is a multiset: a syllable that appears
// twice in a single split (e.g. "ба" + "ба" for "баба") gets count 2, and
// the screen may carry up to that many concurrent copies.
//
// IMPORTANT: each word's split is decided ONCE per session and cached on
// state.wordSplits. Otherwise every rebuildPool() would re-randomise the
// split, and bubbles whose syllable came from the previous split would look
// "stale" even though the word that created them is still unguessed.
function buildSyllablesFromWords(words) {
const counts = new Map(); // UPPERCASE syllable → total occurrences
const splits = new Map(); // lowercase word → array of UPPERCASE parts
if (!state.wordSplits) state.wordSplits = new Map();
for (const raw of words) {
const w = (raw || '').toLowerCase();
if (!/^[a-zа-яё]+$/i.test(w)) continue;
let upper = state.wordSplits.get(w);
if (!upper) {
const parts = splitWord(w);
if (!parts) continue;
upper = parts.map(p => p.toUpperCase());
state.wordSplits.set(w, upper);
}
splits.set(w, upper);
for (const p of upper) counts.set(p, (counts.get(p) || 0) + 1);
}
return { counts, splits };
}
// A level entry can be either an array of words OR an object {name, words}.
function levelEntryAt(level) {
if (!levelData || !levelData.length) return null;
const idx = Math.min(level - 1, levelData.length - 1);
return levelData[idx] || null;
}
function levelWordsAt(level) {
const e = levelEntryAt(level);
if (!e) return [];
return Array.isArray(e) ? e : (e.words || []);
}
function levelNameAt(level) {
const e = levelEntryAt(level);
if (!e || Array.isArray(e)) return '';
return e.name || '';
}
function levelWordCount(level) { return levelWordsAt(level).length; }
// Win threshold = ceil(N * pack.nextfrac). Each pack in levels.js declares
// what fraction of a level's words must be guessed before advancing
// (defaults to 0.5 if the pack didn't specify). nextfrac = 1.0 means every
// word on the level has to be found.
function levelWinTarget(level) {
const N = levelWordCount(level);
if (N <= 0) return 1;
const frac = (levelPack && typeof levelPack.nextfrac === 'number') ? levelPack.nextfrac : 0.5;
return Math.max(1, Math.min(N, Math.ceil(N * frac)));
}
// All distinct, sanitised words across levels 1..upTo (inclusive).
function poolWordsUpTo(upTo) {
const out = [];
const seen = new Set();
const max = Math.min(upTo, levelData ? levelData.length : 0);
for (let i = 1; i <= max; i++) {
const ws = pickLevelSource(i).words;
for (const w of ws) {
if (seen.has(w)) continue;
seen.add(w);
out.push(w);
}
}
return out;
}
// Active pool: pool words still unguessed.
function activeWords() {
if (!state) return [];
const found = state.foundLevelWords || new Set();
return poolWordsUpTo(state.level).filter(w => !found.has(w));
}
// Rebuild dictionary + syllable inventory from the active (unguessed) pool.
// Called whenever state.level changes or state.foundLevelWords gains a word.
function rebuildPool() {
const active = activeWords();
dictionary = buildDictionaryFromWords(active);
syllables = buildSyllablesFromWords(active);
pruneStaleBubbles();
}
// Remove any on-screen bubble whose syllable string is no longer part of the
// active pool's inventory — e.g. ABCDEF was found via ABCD + EF, leaving the
// ABC and DEF bubbles "stale" because no remaining word's split needs them.
// They animate out the same way burned bubbles do.
function pruneStaleBubbles() {
if (!state || !state.bubbles || !state.bubbles.length) return;
if (!syllables || !syllables.counts) return;
const valid = syllables.counts;
const stale = state.bubbles.filter(b => !valid.has(b.syllable));
if (!stale.length) return;
const ids = new Set(stale.map(b => b.id));
for (const b of stale) {
state.bursts.push({
x: b.x, y: b.y, w: b.w,
syllable: b.syllable,
t: 0, dur: 0.7,
});
}
state.bubbles = state.bubbles.filter(b => !ids.has(b.id));
if (state.selection) state.selection = state.selection.filter(id => !ids.has(id));
if (state.hintBubbleIds) state.hintBubbleIds = state.hintBubbleIds.filter(id => !ids.has(id));
if (state.draggedId !== null && ids.has(state.draggedId)) state.draggedId = null;
}
// How many of the CURRENT level's words have been guessed (across this run)?
function currentLevelGuessedCount() {
if (!state || !state.levelWords) return 0;
let n = 0;
for (const w of state.levelWords) if (state.foundLevelWords.has(w)) n++;
return n;
}
// Build the sanitised lowercase word list for the given level.
function pickLevelSource(level) {
const raw = levelWordsAt(level);
const out = [];
const seen = new Set();
for (const w of raw) {
if (typeof w !== 'string') continue;
const lw = w.toLowerCase();
if (lw.length < 4) continue; // need ≥4 letters to make a 2-part split
if (!/^[a-zа-яё]+$/i.test(lw)) continue;
if (seen.has(lw)) continue;
seen.add(lw);
out.push(lw);
}
return { name: levelNameAt(level), words: out };
}
// ---- Per-pack progress (saved in localStorage) ------------------------------
// Stored shape: { unlocked, current, foundLevel: [...], foundOther: [...] }
function packStorageKey(pack) { return 'pack.' + (pack && pack.file); }
function getPackProgress(pack) {
try {
const raw = localStorage.getItem(packStorageKey(pack));
if (raw) {
const p = JSON.parse(raw);
return {
unlocked: Math.max(1, p.unlocked | 0 || 1),
current: Math.max(1, p.current | 0 || 1),
foundLevel: Array.isArray(p.foundLevel) ? p.foundLevel.slice() : [],
wordsLog: Array.isArray(p.wordsLog) ? p.wordsLog.slice() : [],
};
}
} catch (e) { /* ignore */ }
return { unlocked: 1, current: 1, foundLevel: [], wordsLog: [] };
}
function setPackProgress(pack, p) {
try { localStorage.setItem(packStorageKey(pack), JSON.stringify(p)); } catch (e) {}
}
// Persist the in-memory progress (found words + recent ticker) into the
// pack's saved blob. Called every time a level is reached.
function persistFoundWords(pack) {
if (!pack || !state) return;
const p = getPackProgress(pack);
p.foundLevel = state.foundLevelWords ? [...state.foundLevelWords] : [];
p.wordsLog = state.wordsLog ? state.wordsLog.slice(-50) : [];
setPackProgress(pack, p);
}
function markLevelStarted(pack, level) {
const p = getPackProgress(pack);
p.current = level;
if (level > p.unlocked) p.unlocked = level;
setPackProgress(pack, p);
}
function markLevelCleared(pack, level) {
const p = getPackProgress(pack);
const next = level + 1;
if (next > p.unlocked) p.unlocked = next;
p.current = next;
setPackProgress(pack, p);
}
// Pick a syllable for spawning. The pool inventory is a multiset (a syllable
// that appears twice in a word's split — like "ба" + "ба" for "баба" — has
// count 2). We may spawn another copy as long as on-screen copies are still
// fewer than the inventory count. Sampling is weighted by remaining capacity.
function nextSyllable() {
const inv = syllables;
if (!inv || !inv.counts || inv.counts.size === 0) return null;
const onScreen = new Map();
if (state && state.bubbles) {
for (const b of state.bubbles) {
onScreen.set(b.syllable, (onScreen.get(b.syllable) || 0) + 1);
}
}
let total = 0;
const items = [];
for (const [syl, cnt] of inv.counts) {
const remaining = cnt - (onScreen.get(syl) || 0);
if (remaining <= 0) continue;
items.push({ syl, weight: remaining });
total += remaining;
}
if (total <= 0) return null;
let r = Math.random() * total;
for (const it of items) {
r -= it.weight;
if (r < 0) return it.syl;
}
return items[items.length - 1].syl;
}
// ---- Word-cloud helpers ----------------------------------------------------
// Each bubble is a rounded rectangle that floats freely; gravity pulls every
// bubble toward the cloud's centre, AABB collisions push them apart, the
// player can drag any bubble and the rest re-settle around it.
function makeBubble(syllable, x, y) {
const w = syllable.length * CHAR_W;
return {
id: state.nextBubbleId++,
syllable: syllable.toUpperCase(),
nominalW: w, nominalH: CELL_H,
w, h: CELL_H,
x, y,
vx: 0, vy: 0,
mass: w,
spawnT: 0,
spawnDur: 0.5,
};
}
// Bubble-size scale: 1.0 up to 20 bubbles, then each doubling multiplies by
// 0.75. Continuous so spawn-in churn doesn't snap.
function applyBubbleScale() {
if (!state || !state.bubbles) return;
const n = state.bubbles.length;
const scale = n <= 20 ? 1 : Math.pow(0.75, Math.log2(n / 20));
state.bubbleScale = scale;
for (const b of state.bubbles) {
if (b.nominalW == null) { b.nominalW = b.w; b.nominalH = b.h; }
b.w = b.nominalW * scale;
b.h = b.nominalH * scale;
}
}
function bubbleAt(x, y) {
// Topmost (last-drawn) wins.
for (let i = state.bubbles.length - 1; i >= 0; i--) {
const b = state.bubbles[i];
if (Math.abs(x - b.x) <= b.w / 2 && Math.abs(y - b.y) <= b.h / 2) return b;
}
return null;
}
function aabbOverlap(a, b) {
return {
x: (a.w + b.w) / 2 - Math.abs(a.x - b.x),
y: (a.h + b.h) / 2 - Math.abs(a.y - b.y),
};
}
function isTouching(a, b) {
const o = aabbOverlap(a, b);
// Touching if AABBs are within TOUCH_TOL on both axes.
return o.x + TOUCH_TOL >= 0 && o.y + TOUCH_TOL >= 0;
}
// Push two overlapping bubbles apart along the smaller-overlap axis.
// The dragged bubble (if either) is fully locked; otherwise we split mass-
// proportionally.
function isLocked(id) {
return id === state.draggedId || (state.selection && state.selection.indexOf(id) >= 0);
}
function resolveCollision(a, b) {
const o = aabbOverlap(a, b);
if (o.x <= 0 || o.y <= 0) return false;
const aLocked = isLocked(a.id);
const bLocked = isLocked(b.id);
if (aLocked && bLocked) return false;
let aShare, bShare;
if (aLocked) { aShare = 0; bShare = 1; }
else if (bLocked) { aShare = 1; bShare = 0; }
else {
const total = a.mass + b.mass;
aShare = b.mass / total;
bShare = a.mass / total;
}
if (o.x < o.y) {
const dir = a.x < b.x ? -1 : 1;
a.x += dir * o.x * aShare;
b.x -= dir * o.x * bShare;
// tiny restitution to keep things lively but stable
if (!aLocked) a.vx *= 0.5;
if (!bLocked) b.vx *= 0.5;
} else {
const dir = a.y < b.y ? -1 : 1;
a.y += dir * o.y * aShare;
b.y -= dir * o.y * bShare;
if (!aLocked) a.vy *= 0.5;
if (!bLocked) b.vy *= 0.5;
}
return true;
}
function physicsStep(dt) {
// spawn-in animation
for (const b of state.bubbles) {
if (b.spawnT < b.spawnDur) b.spawnT += dt;
}
// gravity + damping
for (const b of state.bubbles) {
if (isLocked(b.id)) continue;
const dx = CENTER_X - b.x;
const dy = CENTER_Y - b.y;
const d = Math.hypot(dx, dy);
if (d > 1) {
// Pull is gentler near center, stronger far away — softens settling.
const pull = GRAVITY * Math.min(1.5, d / 80);
b.vx += (dx / d) * pull * dt;
b.vy += (dy / d) * pull * dt;
}
const damp = Math.pow(DAMPING, dt * 60);
b.vx *= damp;
b.vy *= damp;
b.x += b.vx * dt;
b.y += b.vy * dt;
// Soft canvas walls (top of HUD strip is the floor)
const minY = 30 + b.h / 2;
const maxY = CANVAS_H - 220 - b.h / 2;
const minX = b.w / 2 + 10;
const maxX = CANVAS_W - b.w / 2 - 10;
if (b.x < minX) { b.x = minX; b.vx = Math.abs(b.vx) * 0.4; }
if (b.x > maxX) { b.x = maxX; b.vx = -Math.abs(b.vx) * 0.4; }
if (b.y < minY) { b.y = minY; b.vy = Math.abs(b.vy) * 0.4; }
if (b.y > maxY) { b.y = maxY; b.vy = -Math.abs(b.vy) * 0.4; }
}
// Iterative collision resolution for stability
for (let it = 0; it < COLLISION_ITERS; it++) {
let any = false;
for (let i = 0; i < state.bubbles.length; i++) {
for (let j = i + 1; j < state.bubbles.length; j++) {
if (resolveCollision(state.bubbles[i], state.bubbles[j])) any = true;
}
}
if (!any) break;
}
}
// ---- Word detection (during drag) ------------------------------------------
// A word is recognised ONLY when its syllables sit in a left-to-right row:
// each consecutive pair must be touching on the x-axis (using the same
// TOUCH_TOL the physics uses) and overlapping at all on the y-axis.
// Vertical, diagonal, and non-linear arrangements do nothing.
const MAX_CHAIN = 5;
function alignedHorizontally(a, b) {
// Any positive y-overlap qualifies.
const yOverlap = (a.h + b.h) / 2 - Math.abs(a.y - b.y);
if (yOverlap <= 0) return false;
// x-edges must be touching (gap within TOUCH_TOL).
const xGap = Math.abs(a.x - b.x) - (a.w + b.w) / 2;
return xGap <= TOUCH_TOL;
}
function rightNeighbour(of) {
let best = null, bestDx = Infinity;
for (const b of state.bubbles) {
if (b.id === of.id) continue;
if (b.x <= of.x) continue; // must be to the right
if (!alignedHorizontally(of, b)) continue;
const dx = b.x - of.x;
if (dx < bestDx) { bestDx = dx; best = b; }
}
return best;
}
function leftNeighbour(of) {
let best = null, bestDx = Infinity;
for (const b of state.bubbles) {
if (b.id === of.id) continue;
if (b.x >= of.x) continue; // must be to the left
if (!alignedHorizontally(of, b)) continue;
const dx = of.x - b.x;
if (dx < bestDx) { bestDx = dx; best = b; }
}
return best;
}
function buildHorizontalChain(d) {
const chain = [d];
const visited = new Set([d.id]);
let cur = d;
while (chain.length < MAX_CHAIN) {
const r = rightNeighbour(cur);
if (!r || visited.has(r.id)) break;
chain.push(r);
visited.add(r.id);
cur = r;
}
cur = d;
while (chain.length < MAX_CHAIN) {
const l = leftNeighbour(cur);
if (!l || visited.has(l.id)) break;
chain.unshift(l);
visited.add(l.id);
cur = l;
}
return chain;
}
function findWordsInvolvingDragged() {
const out = [];
if (state.draggedId === null) return out;
const d = state.bubbles.find(b => b.id === state.draggedId);
if (!d) return out;
const chain = buildHorizontalChain(d);
const idx = chain.indexOf(d);
if (idx < 0 || chain.length < 2) return out;
// Every contiguous sub-row including the dragged bubble, read left-to-right.
const seen = new Set();
for (let len = 2; len <= chain.length; len++) {
const sLo = Math.max(0, idx - len + 1);
const sHi = Math.min(chain.length - len, idx);
for (let s = sLo; s <= sHi; s++) {
const sub = chain.slice(s, s + len);
const concat = sub.map(b => b.syllable.toLowerCase()).join('');
if (concat.length < 4) continue;
if (!dictionary.has(concat)) continue;
if (state.foundLevelWords && state.foundLevelWords.has(concat)) continue;
if (seen.has(concat)) continue;
seen.add(concat);
out.push({ bubbles: sub.slice(), word: concat });
}
}
out.sort((a, b) => b.word.length - a.word.length);
return out;
}
// Drag is purely cosmetic — bubbles re-settle around the user's hand. The
// match check has been removed; only clicking spells words.
function onDragEnd() {
state.draggedId = null;
}
// Burn the bubbles forming a discovered secret word.
function burnWord(match) {
state.wordsLog.push(match.word.toUpperCase());
if (state.wordsLog.length > 50) state.wordsLog.splice(0, state.wordsLog.length - 50);
state.foundLevelWords.add(match.word);
const ids = new Set(match.bubbles.map(b => b.id));
for (const b of match.bubbles) {
state.bursts.push({
x: b.x, y: b.y, w: b.w,
syllable: b.syllable,
t: 0, dur: 0.55,
});
}
state.bubbles = state.bubbles.filter(b => !ids.has(b.id));
state.bursts.push({
x: CENTER_X, y: CENTER_Y,
text: match.word.toUpperCase(),
color: '#9bbf86',
t: 0, dur: 2.6, isText: true, slide: true,
});
// Pool shrinks: rebuild dictionary + syllable inventory excluding this word.
rebuildPool();
state.wordsThisLevel = currentLevelGuessedCount();
// After a burn, drop 5 new syllables — but only 2 if the cloud is already
// dense (≥ 20 letters on screen) to avoid runaway clutter.
let lettersOnScreen = 0;
for (const b of state.bubbles) lettersOnScreen += b.syllable.length;
dropSyllables(lettersOnScreen >= 20 ? 2 : 5);
// Advance only when MORE than half the level's words are guessed AND the
// cloud has shrunk below 20 syllables, so the player can't bypass a
// packed cloud or skip with a bare-minimum half.
if (state.wordsThisLevel >= state.wordsToWin && state.bubbles.length < 20) levelUp();
}
function spawnBubbleWithSyllable(syl) {
const angle = Math.random() * Math.PI * 2;
const dist = 480;
const x = CENTER_X + Math.cos(angle) * dist;
const y = CENTER_Y + Math.sin(angle) * dist;
const b = makeBubble(syl, x, y);
const dx = CENTER_X - x, dy = CENTER_Y - y;
const d = Math.hypot(dx, dy) || 1;
b.vx = (dx / d) * 280;
b.vy = (dy / d) * 280;
state.bubbles.push(b);
}
function spawnNewBubble() {
const syl = nextSyllable();
if (!syl) return; // every eligible syllable is banned or already on screen
spawnBubbleWithSyllable(syl);
}
// Spawn one bubble per syllable for every unguessed word in the current
// level — so reaching a level makes that level's full syllable inventory
// visible immediately.
function dropCurrentLevelSyllables() {
if (!state || !state.levelWords) return;
const found = state.foundLevelWords || new Set();
for (const w of state.levelWords) {
if (found.has(w)) continue;
const split = state.wordSplits && state.wordSplits.get(w);
if (!split) continue;
for (const syl of split) spawnBubbleWithSyllable(syl);
}
}
// ---- Score schedule (kept) -------------------------------------------------
function scoreFor(letters, combo) {
return Math.round(letters * letters * 5 * (1 + (Math.max(1, combo) - 1) * 0.4));
}
// ---- State init -------------------------------------------------------------
// `saved` (optional) is a getPackProgress() blob; its foundLevel / foundOther
// arrays are restored into the new state before installLevel() runs, so the
// pool is built around already-guessed words and the per-level save sticks.
function initState(startLevel, saved) {
startLevel = Math.max(1, startLevel | 0 || 1);
const restoredLevel = (saved && Array.isArray(saved.foundLevel)) ? saved.foundLevel : [];
const restoredLog = (saved && Array.isArray(saved.wordsLog)) ? saved.wordsLog.slice(-50) : [];
state = {
bubbles: [],
nextBubbleId: 1,
draggedId: null,
dragOffset: { x: 0, y: 0 },
mouseX: CENTER_X, mouseY: CENTER_Y,
score: 0,
lastT: 0,
gameOver: false,
bursts: [],
wordsLog: restoredLog,
level: startLevel,
levelName: '',
levelWords: [],
wordsThisLevel: 0,
wordsToWin: levelWinTarget(startLevel),
foundLevelWords: new Set(restoredLevel),
wordSplits: new Map(), // session-stable per-word split cache
selection: [],
dragMoved: false,
dragStart: null,
hintBubbleIds: [],
hintTTL: 0,
hintCooldown: 0,
endingShown: false,
autoSaveT: 0,
};
const isResume = !!(saved && (startLevel > 1 || restoredLevel.length > 0));
installLevel(startLevel, !isResume);
if (levelPack) markLevelStarted(levelPack, startLevel);
dropCurrentLevelSyllables();
}
// Drop up to `count` new syllables in from outside the cloud. Each one chooses
// its own random launch angle inside spawnNewBubble; if the inventory has
// nothing eligible, the call is a silent no-op so we never crash.
function dropSyllables(count) {
for (let i = 0; i < count; i++) spawnNewBubble();
}
function installLevel(level, silent) {
state.level = level;
state.selection = [];
state.hintBubbleIds = [];
state.hintTTL = 0;
// Don't reset hintCooldown on level change — it follows the player across
// levels so they can't farm hints by advancing.
const src = pickLevelSource(level);
state.levelName = src.name;
state.levelWords = src.words;
state.wordsToWin = levelWinTarget(level);
state.wordsThisLevel = currentLevelGuessedCount();
// Pre-pick splits for the current level so that ≥ half its words are
// 2-part. Uncached earlier-level words still fall back to a random split
// inside buildSyllablesFromWords.
preSplitLevelWords(src.words);
// Pool = unguessed words from levels 1..N. Rebuilt every match too.
rebuildPool();
// Save guessed-word progress every time a new level is reached.
if (levelPack) persistFoundWords(levelPack);
if (!silent) {
state.bursts.push({
x: CANVAS_W / 2, y: CENTER_Y,
text: 'УРОВЕНЬ ' + level + (src.name ? ' · ' + src.name.toUpperCase() : ''),
t: 0, dur: 2.4, isText: true, big: true,
});
}
}
function levelUp() {
if (levelPack) markLevelCleared(levelPack, state.level);
const isLast = !!levelData && state.level >= levelData.length;
if (isLast) {
// No more levels to install; suppress the re-announcement banner.
// The ending banner only fires once every word in every unlocked level
// has been found.
if (totalGuessedWordCount() >= totalUnlockedWordCount() && !state.endingShown) {
state.endingShown = true;
state.bursts.push({
x: CANVAS_W / 2, y: CENTER_Y,
text: 'С ПЕРЕРОЖДЕНИЕМ!',
t: 0, dur: 5.0, isText: true, big: true,
});
}
return;
}
installLevel(state.level + 1, false);
dropCurrentLevelSyllables();
}
// ---- Update / render --------------------------------------------------------
function update(dt) {
if (state.gameOver) {
for (const b of state.bursts) b.t += dt;
state.bursts = state.bursts.filter(x => x.t < x.dur);
return;
}
// Pin the dragged bubble to the cursor; physics treats it as locked.
if (state.draggedId !== null) {
const b = state.bubbles.find(x => x.id === state.draggedId);
if (b) {
b.x = state.mouseX - state.dragOffset.x;
b.y = state.mouseY - state.dragOffset.y;
b.vx = 0; b.vy = 0;
// Soft clamp so the dragged bubble can't escape the play area.
const minY = 30 + b.h / 2;
const maxY = CANVAS_H - 220 - b.h / 2;
const minX = b.w / 2 + 10;
const maxX = CANVAS_W - b.w / 2 - 10;
b.x = Math.max(minX, Math.min(maxX, b.x));
b.y = Math.max(minY, Math.min(maxY, b.y));
} else {
state.draggedId = null;
}
}
applyBubbleScale();
physicsStep(dt);
if (state.hintTTL > 0) state.hintTTL = Math.max(0, state.hintTTL - dt);
if (state.hintCooldown > 0) state.hintCooldown = Math.max(0, state.hintCooldown - dt);
// Auto-save every 60 seconds so a tab close doesn't cost progress.
state.autoSaveT = (state.autoSaveT || 0) + dt;
if (state.autoSaveT >= 60) {
state.autoSaveT = 0;
if (levelPack) persistFoundWords(levelPack);
}
for (const burst of state.bursts) {
burst.t += dt;
if (burst.falling) {
burst.vy += 900 * dt;
burst.x += burst.vx * dt;
burst.y += burst.vy * dt;
}
}
state.bursts = state.bursts.filter(b => b.t < b.dur);
}
function render() {
ctx.fillStyle = '#1f232f';
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H);
// Subtle radial backdrop suggesting the cloud's center of gravity
const grad = ctx.createRadialGradient(CENTER_X, CENTER_Y, 60, CENTER_X, CENTER_Y, 380);
grad.addColorStop(0, 'rgba(38, 43, 58, 0.55)');
grad.addColorStop(1, 'rgba(38, 43, 58, 0)');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, CANVAS_W, CANVAS_H);
// Active-match halos
let activeMatches = [];
if (state.draggedId !== null) activeMatches = findWordsInvolvingDragged();
const haloIds = new Set();
for (const m of activeMatches) for (const b of m.bubbles) haloIds.add(b.id);