BlueGit

projects-timfalken-com meteors

Files

meteors / build / game.js

game.js

game.js 265.2 KiB Download Raw
1/*
2 * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
3 * Built by src/build.sh from the sources in src/.
4 */
5var PLANET_CATALOG = {
6 "planets": [
7 {
8 "id": "terra",
9 "name": "Terra",
10 "people": "Terrans",
11 "jumpsToClear": 2,
12 "fallTime": 3,
13 "riseTime": 1.5,
14 "colors": [
15 {"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"},
16 {"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"},
17 {"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"},
18 {"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"},
19 {"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"}
20 ]
21 },
22 {
23 "id": "aurel",
24 "name": "Aurel",
25 "people": "Aurelians",
26 "jumpsToClear": 1,
27 "fallTime": 5,
28 "riseTime": 3,
29 "colors": [
30 {"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"},
31 {"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"},
32 {"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"},
33 {"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"},
34 {"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"}
35 ]
36 },
37 {
38 "id": "cinder",
39 "name": "Cinder",
40 "people": "Cindari",
41 "jumpsToClear": 4,
42 "fallTime": 1,
43 "riseTime": 0.5,
44 "colors": [
45 {"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"},
46 {"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"},
47 {"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"},
48 {"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"},
49 {"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"}
50 ]
51 },
52 {
53 "id": "lunara",
54 "name": "Lunara",
55 "people": "Lunarites",
56 "jumpsToClear": 1,
57 "fallTime": 2,
58 "riseTime": 1.2,
59 "colors": [
60 {"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"},
61 {"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"},
62 {"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"},
63 {"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"},
64 {"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"}
65 ]
66 },
67 {
68 "id": "mire",
69 "name": "Mire",
70 "people": "Mirians",
71 "jumpsToClear": 2,
72 "fallTime": 5,
73 "riseTime": 2.5,
74 "colors": [
75 {"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"},
76 {"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"},
77 {"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"},
78 {"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"},
79 {"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"}
80 ]
81 },
82 {
83 "id": "galeon",
84 "name": "Galeon",
85 "people": "Galeoni",
86 "jumpsToClear": 3,
87 "fallTime": 1,
88 "riseTime": 1.8,
89 "colors": [
90 {"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"},
91 {"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"},
92 {"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"},
93 {"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"},
94 {"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"}
95 ]
96 },
97 {
98 "id": "obsid",
99 "name": "Obsid",
100 "people": "Obsidians",
101 "jumpsToClear": 4,
102 "fallTime": 3.5,
103 "riseTime": 2.2,
104 "colors": [
105 {"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"},
106 {"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"},
107 {"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"},
108 {"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"},
109 {"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"}
110 ]
111 },
112 {
113 "id": "wisp",
114 "name": "Wisp",
115 "people": "Wisplings",
116 "jumpsToClear": 2,
117 "fallTime": 3.5,
118 "riseTime": 0.5,
119 "colors": [
120 {"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"},
121 {"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"},
122 {"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"},
123 {"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"},
124 {"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"}
125 ]
126 },
127 {
128 "id": "thorn",
129 "name": "Thorn",
130 "people": "Thornfolk",
131 "jumpsToClear": 3,
132 "fallTime": 2,
133 "riseTime": 1.0,
134 "colors": [
135 {"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"},
136 {"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"},
137 {"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"},
138 {"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"},
139 {"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"}
140 ]
141 },
142 {
143 "id": "zephyr",
144 "name": "Zephyr",
145 "people": "Zephyrites",
146 "jumpsToClear": 1,
147 "fallTime": 1.2,
148 "riseTime": 2.8,
149 "colors": [
150 {"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"},
151 {"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"},
152 {"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"},
153 {"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"},
154 {"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"}
155 ]
156 },
157 {
158 "id": "frore",
159 "name": "Frore",
160 "people": "Frorians",
161 "jumpsToClear": 3,
162 "fallTime": 4.5,
163 "riseTime": 0.8,
164 "colors": [
165 {"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"},
166 {"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"},
167 {"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"},
168 {"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"},
169 {"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"}
170 ]
171 },
172 {
173 "id": "forge",
174 "name": "Forge",
175 "people": "Forgelings",
176 "jumpsToClear": 4,
177 "fallTime": 2,
178 "riseTime": 1.5,
179 "colors": [
180 {"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"},
181 {"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"},
182 {"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"},
183 {"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"},
184 {"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"}
185 ]
186 }
187 ]
188}
189;
190var BLOCK_REGISTRY = {
191 "_comment": "Append-only block registry. Never reorder, rename ids, or insert in the middle. New blocks go at the end. The first five (Terra) are unlocked by default; index 5 requires 500 lifetime points, each next index requires 14.5% more (rounded).",
192 "terraCount": 5,
193 "firstThreshold": 500,
194 "thresholdGrowth": 1.145,
195 "blocks": [
196 {
197 "id": "terra-ember",
198 "name": "Ember",
199 "hex": "#e85d3a",
200 "shape": "triangle",
201 "image": "images/block-terra-ember.png",
202 "terra": true
203 },
204 {
205 "id": "terra-aqua",
206 "name": "Aqua",
207 "hex": "#3db8e8",
208 "shape": "circle",
209 "image": "images/block-terra-aqua.png",
210 "terra": true
211 },
212 {
213 "id": "terra-leaf",
214 "name": "Leaf",
215 "hex": "#4cbf4c",
216 "shape": "square",
217 "image": "images/block-terra-leaf.png",
218 "terra": true
219 },
220 {
221 "id": "terra-sun",
222 "name": "Sun",
223 "hex": "#f0c53a",
224 "shape": "diamond",
225 "image": "images/block-terra-sun.png",
226 "terra": true
227 },
228 {
229 "id": "terra-orchid",
230 "name": "Orchid",
231 "hex": "#c45ad4",
232 "shape": "star",
233 "image": "images/block-terra-orchid.png",
234 "terra": true
235 },
236 {
237 "id": "rune-fehu",
238 "name": "Fehu",
239 "hex": "#e8a44a",
240 "shape": "rune_fehu",
241 "image": "images/block-rune-fehu.png",
242 "terra": false
243 },
244 {
245 "id": "rune-ansuz",
246 "name": "Ansuz",
247 "hex": "#6ab0e8",
248 "shape": "rune_ansuz",
249 "image": "images/block-rune-ansuz.png",
250 "terra": false
251 },
252 {
253 "id": "rune-thurisaz",
254 "name": "Thurisaz",
255 "hex": "#c05040",
256 "shape": "rune_thurisaz",
257 "image": "images/block-rune-thurisaz.png",
258 "terra": false
259 },
260 {
261 "id": "rune-raido",
262 "name": "Raido",
263 "hex": "#d0c070",
264 "shape": "rune_raido",
265 "image": "images/block-rune-raido.png",
266 "terra": false
267 },
268 {
269 "id": "rune-sowilo",
270 "name": "Sowilo",
271 "hex": "#f0d040",
272 "shape": "rune_sowilo",
273 "image": "images/block-rune-sowilo.png",
274 "terra": false
275 },
276 {
277 "id": "rune-algiz",
278 "name": "Algiz",
279 "hex": "#80d0a0",
280 "shape": "rune_algiz",
281 "image": "images/block-rune-algiz.png",
282 "terra": false
283 },
284 {
285 "id": "arrow-up",
286 "name": "Arrow",
287 "hex": "#f07040",
288 "shape": "arrow",
289 "image": "images/block-arrow-up.png",
290 "terra": false
291 },
292 {
293 "id": "arrow-chevron",
294 "name": "Chevron",
295 "hex": "#50c0e0",
296 "shape": "chevron",
297 "image": "images/block-arrow-chevron.png",
298 "terra": false
299 },
300 {
301 "id": "arrow-double",
302 "name": "Double Arrow",
303 "hex": "#e05080",
304 "shape": "double_arrow",
305 "image": "images/block-arrow-double.png",
306 "terra": false
307 },
308 {
309 "id": "arrow-return",
310 "name": "Return",
311 "hex": "#a080e0",
312 "shape": "return_arrow",
313 "image": "images/block-arrow-return.png",
314 "terra": false
315 },
316 {
317 "id": "fig-person",
318 "name": "Figure",
319 "hex": "#f0c0a0",
320 "shape": "person",
321 "image": "images/block-fig-person.png",
322 "terra": false
323 },
324 {
325 "id": "fig-walker",
326 "name": "Walker",
327 "hex": "#c09070",
328 "shape": "walker",
329 "image": "images/block-fig-walker.png",
330 "terra": false
331 },
332 {
333 "id": "fig-hero",
334 "name": "Hero",
335 "hex": "#e8b070",
336 "shape": "hero",
337 "image": "images/block-fig-hero.png",
338 "terra": false
339 },
340 {
341 "id": "face-smile",
342 "name": "Smile",
343 "hex": "#f0d060",
344 "shape": "smile",
345 "image": "images/block-face-smile.png",
346 "terra": false
347 },
348 {
349 "id": "face-wink",
350 "name": "Wink",
351 "hex": "#f0a050",
352 "shape": "wink",
353 "image": "images/block-face-wink.png",
354 "terra": false
355 },
356 {
357 "id": "face-cool",
358 "name": "Cool",
359 "hex": "#6090d0",
360 "shape": "cool",
361 "image": "images/block-face-cool.png",
362 "terra": false
363 },
364 {
365 "id": "face-grin",
366 "name": "Grin",
367 "hex": "#f0c848",
368 "shape": "grin",
369 "image": "images/block-face-grin.png",
370 "terra": false
371 },
372 {
373 "id": "icon-heart",
374 "name": "Heart",
375 "hex": "#e04060",
376 "shape": "heart",
377 "image": "images/block-icon-heart.png",
378 "terra": false
379 },
380 {
381 "id": "icon-moon",
382 "name": "Moon",
383 "hex": "#d0d8f0",
384 "shape": "crescent",
385 "image": "images/block-icon-moon.png",
386 "terra": false
387 },
388 {
389 "id": "icon-bolt",
390 "name": "Bolt",
391 "hex": "#f0e050",
392 "shape": "lightning",
393 "image": "images/block-icon-bolt.png",
394 "terra": false
395 },
396 {
397 "id": "icon-shield",
398 "name": "Shield",
399 "hex": "#5080c0",
400 "shape": "shield",
401 "image": "images/block-icon-shield.png",
402 "terra": false
403 },
404 {
405 "id": "icon-crown",
406 "name": "Crown",
407 "hex": "#f0c030",
408 "shape": "crown",
409 "image": "images/block-icon-crown.png",
410 "terra": false
411 },
412 {
413 "id": "icon-eye",
414 "name": "Eye",
415 "hex": "#70d0c0",
416 "shape": "eye",
417 "image": "images/block-icon-eye.png",
418 "terra": false
419 },
420 {
421 "id": "icon-star6",
422 "name": "Hexastar",
423 "hex": "#f0e8a0",
424 "shape": "star6",
425 "image": "images/block-icon-star6.png",
426 "terra": false
427 },
428 {
429 "id": "icon-spiral",
430 "name": "Spiral",
431 "hex": "#c070d0",
432 "shape": "spiral",
433 "image": "images/block-icon-spiral.png",
434 "terra": false
435 },
436 {
437 "id": "icon-wave",
438 "name": "Wave",
439 "hex": "#3090d0",
440 "shape": "wave",
441 "image": "images/block-icon-wave.png",
442 "terra": false
443 },
444 {
445 "id": "icon-mountain",
446 "name": "Mountain",
447 "hex": "#809070",
448 "shape": "mountain",
449 "image": "images/block-icon-mountain.png",
450 "terra": false
451 },
452 {
453 "id": "icon-fish",
454 "name": "Fish",
455 "hex": "#40a8c8",
456 "shape": "fish",
457 "image": "images/block-icon-fish.png",
458 "terra": false
459 },
460 {
461 "id": "icon-bird",
462 "name": "Bird",
463 "hex": "#e07050",
464 "shape": "bird",
465 "image": "images/block-icon-bird.png",
466 "terra": false
467 },
468 {
469 "id": "icon-key",
470 "name": "Key",
471 "hex": "#d0b050",
472 "shape": "key",
473 "image": "images/block-icon-key.png",
474 "terra": false
475 },
476 {
477 "id": "icon-comet",
478 "name": "Comet",
479 "hex": "#90d0f0",
480 "shape": "comet",
481 "image": "images/block-icon-comet.png",
482 "terra": false
483 },
484 {
485 "id": "icon-clover",
486 "name": "Clover",
487 "hex": "#40b060",
488 "shape": "clover",
489 "image": "images/block-icon-clover.png",
490 "terra": false
491 },
492 {
493 "id": "icon-paw",
494 "name": "Paw",
495 "hex": "#c08050",
496 "shape": "paw",
497 "image": "images/block-icon-paw.png",
498 "terra": false
499 },
500 {
501 "id": "icon-sword",
502 "name": "Sword",
503 "hex": "#b0b8c0",
504 "shape": "sword",
505 "image": "images/block-icon-sword.png",
506 "terra": false
507 },
508 {
509 "id": "icon-bell",
510 "name": "Bell",
511 "hex": "#f0c848",
512 "shape": "bell",
513 "image": "images/block-icon-bell.png",
514 "terra": false
515 },
516 {
517 "id": "icon-mushroom",
518 "name": "Mushroom",
519 "hex": "#e06050",
520 "shape": "mushroom",
521 "image": "images/block-icon-mushroom.png",
522 "terra": false
523 },
524 {
525 "id": "icon-cactus",
526 "name": "Cactus",
527 "hex": "#50b068",
528 "shape": "cactus",
529 "image": "images/block-icon-cactus.png",
530 "terra": false
531 },
532 {
533 "id": "icon-ring",
534 "name": "Ring",
535 "hex": "#e8d080",
536 "shape": "ring",
537 "image": "images/block-icon-ring.png",
538 "terra": false
539 },
540 {
541 "id": "icon-flag",
542 "name": "Flag",
543 "hex": "#d04050",
544 "shape": "flag",
545 "image": "images/block-icon-flag.png",
546 "terra": false
547 },
548 {
549 "id": "icon-snow",
550 "name": "Snowflake",
551 "hex": "#c8e0f8",
552 "shape": "snowflake",
553 "image": "images/block-icon-snow.png",
554 "terra": false
555 },
556 {
557 "id": "icon-flame",
558 "name": "Flame",
559 "hex": "#ff7030",
560 "shape": "flame_icon",
561 "image": "images/block-icon-flame.png",
562 "terra": false
563 },
564 {
565 "id": "icon-ankh",
566 "name": "Ankh",
567 "hex": "#d0a060",
568 "shape": "ankh",
569 "image": "images/block-icon-ankh.png",
570 "terra": false
571 },
572 {
573 "id": "icon-yin",
574 "name": "Yin Yang",
575 "hex": "#606080",
576 "shape": "yinyang",
577 "image": "images/block-icon-yin.png",
578 "terra": false
579 },
580 {
581 "id": "aurel-gold",
582 "name": "Aurel gold",
583 "hex": "#f4c860",
584 "shape": "hexagon",
585 "image": "images/block-aurel-gold.png",
586 "terra": false
587 },
588 {
589 "id": "aurel-cream",
590 "name": "Aurel cream",
591 "hex": "#f6e7c1",
592 "shape": "circle",
593 "image": "images/block-aurel-cream.png",
594 "terra": false
595 },
596 {
597 "id": "aurel-amber",
598 "name": "Aurel amber",
599 "hex": "#e09a3e",
600 "shape": "teardrop",
601 "image": "images/block-aurel-amber.png",
602 "terra": false
603 },
604 {
605 "id": "aurel-sage",
606 "name": "Aurel sage",
607 "hex": "#8fb86f",
608 "shape": "plus",
609 "image": "images/block-aurel-sage.png",
610 "terra": false
611 },
612 {
613 "id": "aurel-rose",
614 "name": "Aurel rose",
615 "hex": "#e8a0a8",
616 "shape": "pentagon",
617 "image": "images/block-aurel-rose.png",
618 "terra": false
619 },
620 {
621 "id": "cinder-magma",
622 "name": "Cinder magma",
623 "hex": "#ff3b1f",
624 "shape": "triangle",
625 "image": "images/block-cinder-magma.png",
626 "terra": false
627 },
628 {
629 "id": "cinder-coal",
630 "name": "Cinder coal",
631 "hex": "#3a3232",
632 "shape": "square",
633 "image": "images/block-cinder-coal.png",
634 "terra": false
635 },
636 {
637 "id": "cinder-spark",
638 "name": "Cinder spark",
639 "hex": "#ffb347",
640 "shape": "diamond",
641 "image": "images/block-cinder-spark.png",
642 "terra": false
643 },
644 {
645 "id": "cinder-ash",
646 "name": "Cinder ash",
647 "hex": "#8a7a76",
648 "shape": "circle",
649 "image": "images/block-cinder-ash.png",
650 "terra": false
651 },
652 {
653 "id": "cinder-core",
654 "name": "Cinder core",
655 "hex": "#ff6a00",
656 "shape": "star",
657 "image": "images/block-cinder-core.png",
658 "terra": false
659 },
660 {
661 "id": "lunara-silver",
662 "name": "Lunara silver",
663 "hex": "#c5d0e0",
664 "shape": "circle",
665 "image": "images/block-lunara-silver.png",
666 "terra": false
667 },
668 {
669 "id": "lunara-dust",
670 "name": "Lunara dust",
671 "hex": "#8b90a0",
672 "shape": "diamond",
673 "image": "images/block-lunara-dust.png",
674 "terra": false
675 },
676 {
677 "id": "lunara-pale",
678 "name": "Lunara pale",
679 "hex": "#e8d9a8",
680 "shape": "crescent",
681 "image": "images/block-lunara-pale.png",
682 "terra": false
683 },
684 {
685 "id": "lunara-void",
686 "name": "Lunara void",
687 "hex": "#2c3348",
688 "shape": "square",
689 "image": "images/block-lunara-void.png",
690 "terra": false
691 },
692 {
693 "id": "lunara-lilac",
694 "name": "Lunara lilac",
695 "hex": "#b9a4d4",
696 "shape": "star",
697 "image": "images/block-lunara-lilac.png",
698 "terra": false
699 },
700 {
701 "id": "mire-moss",
702 "name": "Mire moss",
703 "hex": "#3d7a45",
704 "shape": "hexagon",
705 "image": "images/block-mire-moss.png",
706 "terra": false
707 },
708 {
709 "id": "mire-bog",
710 "name": "Mire bog",
711 "hex": "#1f4d3a",
712 "shape": "teardrop",
713 "image": "images/block-mire-bog.png",
714 "terra": false
715 },
716 {
717 "id": "mire-rust",
718 "name": "Mire rust",
719 "hex": "#8b5a2b",
720 "shape": "pentagon",
721 "image": "images/block-mire-rust.png",
722 "terra": false
723 },
724 {
725 "id": "mire-spore",
726 "name": "Mire spore",
727 "hex": "#9cbf5a",
728 "shape": "circle",
729 "image": "images/block-mire-spore.png",
730 "terra": false
731 },
732 {
733 "id": "mire-murk",
734 "name": "Mire murk",
735 "hex": "#2e3b2f",
736 "shape": "diamond",
737 "image": "images/block-mire-murk.png",
738 "terra": false
739 },
740 {
741 "id": "galeon-sky",
742 "name": "Galeon sky",
743 "hex": "#4aa3ff",
744 "shape": "arrow",
745 "image": "images/block-galeon-sky.png",
746 "terra": false
747 },
748 {
749 "id": "galeon-cloud",
750 "name": "Galeon cloud",
751 "hex": "#e8eef6",
752 "shape": "circle",
753 "image": "images/block-galeon-cloud.png",
754 "terra": false
755 },
756 {
757 "id": "galeon-storm",
758 "name": "Galeon storm",
759 "hex": "#3d4d6e",
760 "shape": "square",
761 "image": "images/block-galeon-storm.png",
762 "terra": false
763 },
764 {
765 "id": "galeon-sand",
766 "name": "Galeon sand",
767 "hex": "#d4b483",
768 "shape": "diamond",
769 "image": "images/block-galeon-sand.png",
770 "terra": false
771 },
772 {
773 "id": "galeon-kite",
774 "name": "Galeon kite",
775 "hex": "#7fd0c0",
776 "shape": "star",
777 "image": "images/block-galeon-kite.png",
778 "terra": false
779 },
780 {
781 "id": "obsid-glass",
782 "name": "Obsid glass",
783 "hex": "#1a1a22",
784 "shape": "gem",
785 "image": "images/block-obsid-glass.png",
786 "terra": false
787 },
788 {
789 "id": "obsid-violet",
790 "name": "Obsid violet",
791 "hex": "#5a3d8a",
792 "shape": "hexagon",
793 "image": "images/block-obsid-violet.png",
794 "terra": false
795 },
796 {
797 "id": "obsid-shard",
798 "name": "Obsid shard",
799 "hex": "#8a8aa0",
800 "shape": "triangle",
801 "image": "images/block-obsid-shard.png",
802 "terra": false
803 },
804 {
805 "id": "obsid-vein",
806 "name": "Obsid vein",
807 "hex": "#c45a3a",
808 "shape": "diamond",
809 "image": "images/block-obsid-vein.png",
810 "terra": false
811 },
812 {
813 "id": "obsid-basalt",
814 "name": "Obsid basalt",
815 "hex": "#3a3a42",
816 "shape": "square",
817 "image": "images/block-obsid-basalt.png",
818 "terra": false
819 },
820 {
821 "id": "wisp-glow",
822 "name": "Wisp glow",
823 "hex": "#c8ffe0",
824 "shape": "circle",
825 "image": "images/block-wisp-glow.png",
826 "terra": false
827 },
828 {
829 "id": "wisp-mist",
830 "name": "Wisp mist",
831 "hex": "#a8d4e8",
832 "shape": "diamond",
833 "image": "images/block-wisp-mist.png",
834 "terra": false
835 },
836 {
837 "id": "wisp-sparkle",
838 "name": "Wisp sparkle",
839 "hex": "#fff6a8",
840 "shape": "star",
841 "image": "images/block-wisp-sparkle.png",
842 "terra": false
843 },
844 {
845 "id": "wisp-veil",
846 "name": "Wisp veil",
847 "hex": "#d0b8f0",
848 "shape": "teardrop",
849 "image": "images/block-wisp-veil.png",
850 "terra": false
851 },
852 {
853 "id": "wisp-gleam",
854 "name": "Wisp gleam",
855 "hex": "#f4f7ff",
856 "shape": "plus",
857 "image": "images/block-wisp-gleam.png",
858 "terra": false
859 },
860 {
861 "id": "thorn-briar",
862 "name": "Thorn briar",
863 "hex": "#5a7a30",
864 "shape": "triangle",
865 "image": "images/block-thorn-briar.png",
866 "terra": false
867 },
868 {
869 "id": "thorn-berry",
870 "name": "Thorn berry",
871 "hex": "#8b1a4a",
872 "shape": "circle",
873 "image": "images/block-thorn-berry.png",
874 "terra": false
875 },
876 {
877 "id": "thorn-bark",
878 "name": "Thorn bark",
879 "hex": "#5a3a20",
880 "shape": "square",
881 "image": "images/block-thorn-bark.png",
882 "terra": false
883 },
884 {
885 "id": "thorn-petal",
886 "name": "Thorn petal",
887 "hex": "#e89ab0",
888 "shape": "diamond",
889 "image": "images/block-thorn-petal.png",
890 "terra": false
891 },
892 {
893 "id": "thorn-gold",
894 "name": "Thorn gold",
895 "hex": "#c8a030",
896 "shape": "star",
897 "image": "images/block-thorn-gold.png",
898 "terra": false
899 },
900 {
901 "id": "zephyr-azure",
902 "name": "Zephyr azure",
903 "hex": "#6ec8ff",
904 "shape": "crescent",
905 "image": "images/block-zephyr-azure.png",
906 "terra": false
907 },
908 {
909 "id": "zephyr-breeze",
910 "name": "Zephyr breeze",
911 "hex": "#b8e8ff",
912 "shape": "circle",
913 "image": "images/block-zephyr-breeze.png",
914 "terra": false
915 },
916 {
917 "id": "zephyr-cirrus",
918 "name": "Zephyr cirrus",
919 "hex": "#f0f7ff",
920 "shape": "plus",
921 "image": "images/block-zephyr-cirrus.png",
922 "terra": false
923 },
924 {
925 "id": "zephyr-dusk",
926 "name": "Zephyr dusk",
927 "hex": "#7a6ab0",
928 "shape": "diamond",
929 "image": "images/block-zephyr-dusk.png",
930 "terra": false
931 },
932 {
933 "id": "zephyr-haze",
934 "name": "Zephyr haze",
935 "hex": "#ffe08a",
936 "shape": "star",
937 "image": "images/block-zephyr-haze.png",
938 "terra": false
939 },
940 {
941 "id": "frore-ice",
942 "name": "Frore ice",
943 "hex": "#a8d8f0",
944 "shape": "hexagon",
945 "image": "images/block-frore-ice.png",
946 "terra": false
947 },
948 {
949 "id": "frore-frost",
950 "name": "Frore frost",
951 "hex": "#eef7ff",
952 "shape": "circle",
953 "image": "images/block-frore-frost.png",
954 "terra": false
955 },
956 {
957 "id": "frore-deep",
958 "name": "Frore deep",
959 "hex": "#3a6a8a",
960 "shape": "diamond",
961 "image": "images/block-frore-deep.png",
962 "terra": false
963 },
964 {
965 "id": "frore-aurora",
966 "name": "Frore aurora",
967 "hex": "#5ae8c0",
968 "shape": "star",
969 "image": "images/block-frore-aurora.png",
970 "terra": false
971 },
972 {
973 "id": "frore-rime",
974 "name": "Frore rime",
975 "hex": "#d0e4f0",
976 "shape": "triangle",
977 "image": "images/block-frore-rime.png",
978 "terra": false
979 },
980 {
981 "id": "forge-iron",
982 "name": "Forge iron",
983 "hex": "#6a6a72",
984 "shape": "square",
985 "image": "images/block-forge-iron.png",
986 "terra": false
987 },
988 {
989 "id": "forge-slag",
990 "name": "Forge slag",
991 "hex": "#3a3028",
992 "shape": "hexagon",
993 "image": "images/block-forge-slag.png",
994 "terra": false
995 },
996 {
997 "id": "forge-spark",
998 "name": "Forge spark",
999 "hex": "#ff7a1a",
1000 "shape": "triangle",
1001 "image": "images/block-forge-spark.png",
1002 "terra": false
1003 },
1004 {
1005 "id": "forge-brass",
1006 "name": "Forge brass",
1007 "hex": "#c8a048",
1008 "shape": "diamond",
1009 "image": "images/block-forge-brass.png",
1010 "terra": false
1011 },
1012 {
1013 "id": "forge-soot",
1014 "name": "Forge soot",
1015 "hex": "#2a2a28",
1016 "shape": "circle",
1017 "image": "images/block-forge-soot.png",
1018 "terra": false
1019 }
1020 ]
1021}
1022;
1023
1024/*
1025 * Start File:
1026 * /workspace/meteors/src/rng.js
1027 */
1028'use strict';
1029
1030/**
1031 * Seedable mulberry32 RNG, so the game core stays deterministic in tests
1032 * and (later) for multiplayer replays.
1033 */
1034function createRng (seed)
1035{
1036 var a = (seed >>> 0) || 1;
1037 return function rng ()
1038 {
1039 a |= 0;
1040 a = a + 0x6D2B79F5 | 0;
1041 var t = Math.imul(a ^ a >>> 15, 1 | a);
1042 t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
1043 return ((t ^ t >>> 14) >>> 0) / 4294967296;
1044 };
1045}
1046
1047function pickIndex (rng, count)
1048{
1049 var n = count | 0;
1050 if (n <= 0)
1051 { return 0; }
1052 return Math.floor(rng() * n) % n;
1053}
1054
1055function pickFrom (rng, list)
1056{
1057 if (!list || !list.length)
1058 { return undefined; }
1059 return list[pickIndex(rng, list.length)];
1060}
1061
1062var Rng = {
1063 create: createRng,
1064 pickIndex: pickIndex,
1065 pickFrom: pickFrom
1066};
1067
1068if (typeof module !== 'undefined' && module.exports)
1069{ module.exports = Rng; }
1070else if (typeof globalThis !== 'undefined')
1071{ globalThis.Rng = Rng; }
1072
1073/*
1074 * End File:
1075 * /workspace/meteors/src/rng.js
1076 */
1077
1078/*
1079 * Start File:
1080 * /workspace/meteors/src/planet.js
1081 */
1082'use strict';
1083
1084/**
1085 * Planet physics and visuals for Meteors.
1086 *
1087 * Stage 1 uses a single default planet. Stage 3 lets the player pick a
1088 * planet; the numbers and jump-height rules are already applied here so
1089 * that later planets only need new data, not new physics code.
1090 *
1091 * Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
1092 * A horizontal match of 3 jumps JUMP_HEIGHT_SCALE * FIELD_HEIGHT
1093 * / jumpsToClear tiles (JUMP_HEIGHT_SCALE is 1.5 since t1119: the
1094 * minimum jump is 50% higher). At gravity 1 that is 19.5 tiles, so
1095 * one jump from the floor clears the 13-tile field with room to spare;
1096 * at 4 you still need more than one jump, but each is 50% taller.
1097 * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
1098 * Spawn, unsupported and cargo blocks fall at FIELD_HEIGHT / fallTime
1099 * tiles/s. After a jump peaks, a flying cluster floats down at
1100 * DESCENT_SPEED_SCALE * that speed (0.5 since t1122 / t1124: only the
1101 * cluster float-down is halved). Relative differences between planets
1102 * (1 / fallTime) are unchanged. Upward launch is not affected.
1103 * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
1104 * Time to reach the apex, independent of jump height.
1105 *
1106 * Jump-height multipliers (never explained in the game):
1107 * A vertical match of 3 is 120 % of a horizontal row of 3.
1108 * Each extra block beyond 3 adds 5 %.
1109 *
1110 * Power is the average of the three difficulty axes (0 easy .. 1 hard)
1111 * and is shown as a percentage. Miss chance (stage 2) goes from 60 % at
1112 * power 0 to 5 % at power 1.
1113 */
1114
1115var FIELD_WIDTH = 10;
1116var FIELD_HEIGHT = 13;
1117/** t1119: every match jump (the gravity-applied minimum and the
1118 * vertical / extra-block bonuses derived from it) is 50% higher. */
1119var JUMP_HEIGHT_SCALE = 1.5;
1120/** t1122 / t1124: only a flying cluster's post-apex float-down
1121 * (terminal speed and the apex ease into it) is halved. Spawn fall,
1122 * unsupported / released singles and dropped cargo use the full
1123 * fallSpeed. Upward launch is unchanged. */
1124var DESCENT_SPEED_SCALE = 0.5;
1125
1126
1127function clamp (value, lo, hi)
1128{
1129 return Math.max(lo, Math.min(hi, value));
1130}
1131
1132function defaultColors ()
1133{
1134 return [
1135 { id: 0, name: 'ember', hex: '#e85d3a', shape: 'triangle', image: 'images/block-ember.png' },
1136 { id: 1, name: 'aqua', hex: '#3db8e8', shape: 'circle', image: 'images/block-aqua.png' },
1137 { id: 2, name: 'leaf', hex: '#4cbf4c', shape: 'square', image: 'images/block-leaf.png' },
1138 { id: 3, name: 'sun', hex: '#f0c53a', shape: 'diamond', image: 'images/block-sun.png' },
1139 { id: 4, name: 'orchid', hex: '#c45ad4', shape: 'star', image: 'images/block-orchid.png' }
1140 ];
1141}
1142
1143function createPlanet (opts)
1144{
1145 opts = opts || {};
1146 var jumpsToClear = clamp(opts.jumpsToClear == null ? 2 : opts.jumpsToClear, 1, 4);
1147 var fallTime = clamp(opts.fallTime == null ? 3 : opts.fallTime, 1, 5);
1148 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
1149 var colors = opts.colors || defaultColors();
1150 var planet = {
1151 id: opts.id || null,
1152 name: opts.name || 'Terra',
1153 people: opts.people || 'Terrans',
1154 jumpsToClear: jumpsToClear,
1155 fallTime: fallTime,
1156 riseTime: riseTime,
1157 colors: colors,
1158 baseJumpHeight: JUMP_HEIGHT_SCALE * FIELD_HEIGHT / jumpsToClear,
1159 // Single-block fall (spawn, unsupported, dropped cargo).
1160 fallSpeed: FIELD_HEIGHT / fallTime,
1161 // Time to ease from vy=0 at the apex to terminal speed.
1162 // Shorter when air resistance is low (small fallTime).
1163 apexEaseTime: 0.15 * fallTime,
1164 fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
1165 // t1122 / t1124: flying-cluster float-down only. Same ease
1166 // duration; accel scales with the halved terminal speed.
1167 clusterFallSpeed: DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime,
1168 clusterFallAccel: (DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
1169 // Visual landing bounce: faster at low air resistance. Stage-3 params.
1170 bounceDuration: 0.12 * fallTime,
1171 bounceSquash: 0.16
1172 };
1173 return planet;
1174}
1175
1176function loadCatalog ()
1177{
1178 if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
1179 { return PLANET_CATALOG; }
1180 if (typeof require !== 'undefined')
1181 {
1182 try
1183 { return require('../server/lib/planets.json'); }
1184 catch (e) {}
1185 }
1186 return { planets: [] };
1187}
1188
1189/** Player-owned custom planets (from the profile) and any remembered
1190 * snapshots (opponents in a lobby), not part of the official catalog. */
1191var _customPlanets = [];
1192var _remembered = Object.create(null);
1193
1194function setCustomPlanets (list)
1195{
1196 _customPlanets = [];
1197 if (!list || !list.length)
1198 { return; }
1199 for (var i = 0; i < list.length; i++)
1200 { _customPlanets.push(planetFromData(list[i])); }
1201}
1202
1203function rememberPlanet (data)
1204{
1205 if (!data || !data.id)
1206 { return null; }
1207 var pl = planetFromData(data);
1208 _remembered[pl.id] = pl;
1209 return pl;
1210}
1211
1212function forgetRemembered ()
1213{
1214 _remembered = Object.create(null);
1215}
1216
1217function planetFromData (data)
1218{
1219 var planet = createPlanet({
1220 name: data.name,
1221 people: data.people,
1222 jumpsToClear: data.jumpsToClear,
1223 fallTime: data.fallTime,
1224 riseTime: data.riseTime,
1225 colors: data.colors
1226 });
1227 planet.id = data.id;
1228 if (data.custom)
1229 { planet.custom = true; }
1230 if (data.owner_id)
1231 { planet.owner_id = data.owner_id; }
1232 return planet;
1233}
1234
1235function allPlanets ()
1236{
1237 var raw = loadCatalog().planets || [];
1238 var out = [];
1239 for (var i = 0; i < raw.length; i++)
1240 { out.push(planetFromData(raw[i])); }
1241 if (out.length === 0)
1242 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
1243 for (var c = 0; c < _customPlanets.length; c++)
1244 { out.push(_customPlanets[c]); }
1245 return out;
1246}
1247
1248function planetById (id)
1249{
1250 var all = allPlanets();
1251 for (var i = 0; i < all.length; i++)
1252 {
1253 if (all[i].id === id)
1254 { return all[i]; }
1255 }
1256 if (id && _remembered[id])
1257 { return _remembered[id]; }
1258 return defaultPlanet();
1259}
1260
1261function officialPlanets ()
1262{
1263 var raw = loadCatalog().planets || [];
1264 var out = [];
1265 for (var i = 0; i < raw.length; i++)
1266 { out.push(planetFromData(raw[i])); }
1267 return out;
1268}
1269
1270function customPlanets ()
1271{
1272 return _customPlanets.slice();
1273}
1274
1275function pickerPlanets ()
1276{
1277 return officialPlanets().concat(_customPlanets);
1278}
1279
1280function defaultPlanet ()
1281{
1282 var all = allPlanets();
1283 for (var i = 0; i < all.length; i++)
1284 {
1285 if (all[i].id === 'terra')
1286 { return all[i]; }
1287 }
1288 return all[0];
1289}
1290
1291function formatStats (planet)
1292{
1293 var d = displayValues(planet);
1294 return 'g ' + d.gravity.toFixed(2)
1295 + ' d ' + d.density.toFixed(2)
1296 + ' F ' + Math.round(d.newtons) + ' N'
1297 + ' Power ' + d.power + '%';
1298}
1299
1300function spriteKey (planet, colorIndex)
1301{
1302 var colors = planet && planet.colors;
1303 var c = colors && colors[colorIndex];
1304 if (!c)
1305 { return 'gray'; }
1306 // Custom planets (and any color that names a registry block) share
1307 // the preloaded Blocks.images() sprite, so late-loaded customs and
1308 // opponent snapshots do not need a second preload.
1309 if (c.block)
1310 { return 'block:' + c.block; }
1311 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
1312}
1313
1314/**
1315 * Jump height in tiles for a match line.
1316 * @param {object} planet
1317 * @param {number} matchLength number of blocks in the line (>= 3)
1318 * @param {boolean} vertical true for a vertical line
1319 */
1320function jumpHeight (planet, matchLength, vertical)
1321{
1322 var extra = Math.max(0, (matchLength | 0) - 3);
1323 var multiplier = (vertical ? 1.2 : 1.0) + 0.05 * extra;
1324 return planet.baseJumpHeight * multiplier;
1325}
1326
1327/** Initial upward speed (tiles/s) so a jump of `height` peaks in riseTime. */
1328function launchVelocity (planet, height)
1329{
1330 if (height <= 0)
1331 { return 0; }
1332 return (2 * height) / planet.riseTime;
1333}
1334
1335/** Constant deceleration (tiles/s^2) paired with launchVelocity. */
1336function launchDeceleration (planet, height)
1337{
1338 if (height <= 0)
1339 { return 0; }
1340 return (2 * height) / (planet.riseTime * planet.riseTime);
1341}
1342
1343/**
1344 * Difficulty power in 0..1. Higher is harder (and, in stage 2, a lower
1345 * chance that a shot-off block misses the opponent).
1346 */
1347function power (planet)
1348{
1349 var gravity = (planet.jumpsToClear - 1) / 3;
1350 var air = (5 - planet.fallTime) / 4;
1351 var mass = (3 - planet.riseTime) / 2.5;
1352 return (gravity + air + mass) / 3;
1353}
1354
1355/** Maximum miss chance, used by the gameplay formula and the displayed Power. */
1356var MAX_MISS_CHANCE = 0.60;
1357var MIN_MISS_CHANCE = 0.05;
1358
1359/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */
1360function missChance (planet)
1361{
1362 return MAX_MISS_CHANCE - (MAX_MISS_CHANCE - MIN_MISS_CHANCE) * power(planet);
1363}
1364
1365/**
1366 * Displayed Power, as a 0–100 percentage. This is the complement of the
1367 * miss chance against the maximum (60%): 0% miss → 100% Power, 60% miss
1368 * → 0% Power. The gameplay power() and missChance() formulas are unchanged.
1369 */
1370function displayPower (planet)
1371{
1372 return Math.round((1 - missChance(planet) / MAX_MISS_CHANCE) * 100);
1373}
1374
1375/**
1376 * Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),
1377 * launch force (N), and displayed Power as a percentage. The numbers do
1378 * not have to explain themselves.
1379 */
1380function displayValues (planet)
1381{
1382 var gravity = 9.81 * planet.jumpsToClear / 2;
1383 var density = 0.25 + ((5 - planet.fallTime) / 4) * 1.60;
1384 var newtons = 40 + ((planet.riseTime - 0.5) / 2.5) * 160;
1385 return {
1386 gravity: gravity,
1387 density: density,
1388 newtons: newtons,
1389 power: displayPower(planet),
1390 missChance: missChance(planet)
1391 };
1392}
1393
1394var Planet = {
1395 FIELD_WIDTH: FIELD_WIDTH,
1396 FIELD_HEIGHT: FIELD_HEIGHT,
1397 JUMP_HEIGHT_SCALE: JUMP_HEIGHT_SCALE,
1398 DESCENT_SPEED_SCALE: DESCENT_SPEED_SCALE,
1399 COLOR_COUNT: 5,
1400 SETTLE_TIME: 3,
1401 SPAWN_INTERVAL: 1,
1402 JUMP_VERTICAL_BONUS: 1.2,
1403 JUMP_EXTRA_BLOCK: 0.05,
1404 createPlanet: createPlanet,
1405 defaultPlanet: defaultPlanet,
1406 defaultColors: defaultColors,
1407 allPlanets: allPlanets,
1408 officialPlanets: officialPlanets,
1409 customPlanets: customPlanets,
1410 pickerPlanets: pickerPlanets,
1411 setCustomPlanets: setCustomPlanets,
1412 rememberPlanet: rememberPlanet,
1413 forgetRemembered: forgetRemembered,
1414 planetById: planetById,
1415 planetFromData: planetFromData,
1416 formatStats: formatStats,
1417 spriteKey: spriteKey,
1418 jumpHeight: jumpHeight,
1419 launchVelocity: launchVelocity,
1420 launchDeceleration: launchDeceleration,
1421 MAX_MISS_CHANCE: MAX_MISS_CHANCE,
1422 MIN_MISS_CHANCE: MIN_MISS_CHANCE,
1423 power: power,
1424 missChance: missChance,
1425 displayPower: displayPower,
1426 displayValues: displayValues
1427};
1428
1429if (typeof module !== 'undefined' && module.exports)
1430{ module.exports = Planet; }
1431else if (typeof globalThis !== 'undefined')
1432{ globalThis.Planet = Planet; }
1433
1434/*
1435 * End File:
1436 * /workspace/meteors/src/planet.js
1437 */
1438
1439/*
1440 * Start File:
1441 * /workspace/meteors/src/blocks.js
1442 */
1443'use strict';
1444
1445/**
1446 * Append-only block registry. Thresholds and order stay in lockstep with
1447 * server/lib/Blocks.php: Terra's first five are free; the next costs 500
1448 * lifetime points; each one after that costs 14.5% more (rounded, always
1449 * strictly increasing). Points are a requirement, not a spend.
1450 */
1451
1452var Blocks = (function ()
1453{
1454 var TERRA_COUNT = 5;
1455 var FIRST_THRESHOLD = 500;
1456 var GROWTH = 1.145;
1457 var _all = null;
1458
1459 function loadRegistry ()
1460 {
1461 if (_all)
1462 { return _all; }
1463 var data = null;
1464 if (typeof BLOCK_REGISTRY !== 'undefined' && BLOCK_REGISTRY && BLOCK_REGISTRY.blocks)
1465 { data = BLOCK_REGISTRY; }
1466 else if (typeof require !== 'undefined')
1467 {
1468 try
1469 { data = require('../server/lib/blocks.json'); }
1470 catch (e) { data = null; }
1471 }
1472 _all = (data && data.blocks) ? data.blocks.slice() : [];
1473 return _all;
1474 }
1475
1476 function all ()
1477 {
1478 return loadRegistry();
1479 }
1480
1481 function byId (id)
1482 {
1483 var list = all();
1484 for (var i = 0; i < list.length; i++)
1485 {
1486 if (list[i].id === id)
1487 { return list[i]; }
1488 }
1489 return null;
1490 }
1491
1492 function indexOf (id)
1493 {
1494 var list = all();
1495 for (var i = 0; i < list.length; i++)
1496 {
1497 if (list[i].id === id)
1498 { return i; }
1499 }
1500 return -1;
1501 }
1502
1503 function threshold (index)
1504 {
1505 if (index < TERRA_COUNT)
1506 { return 0; }
1507 var t = FIRST_THRESHOLD;
1508 for (var i = TERRA_COUNT; i < index; i++)
1509 {
1510 var next = Math.round(t * GROWTH);
1511 t = Math.max(t + 1, next);
1512 }
1513 return t;
1514 }
1515
1516 function unlocked (index, points)
1517 {
1518 points = points || 0;
1519 return points >= threshold(index);
1520 }
1521
1522 function unlockedId (id, points)
1523 {
1524 var i = indexOf(id);
1525 return i >= 0 && unlocked(i, points);
1526 }
1527
1528 function present (points)
1529 {
1530 points = points || 0;
1531 var list = all();
1532 var out = [];
1533 for (var i = 0; i < list.length; i++)
1534 {
1535 var b = list[i];
1536 var need = threshold(i);
1537 out.push({
1538 id: b.id,
1539 name: b.name || b.id,
1540 hex: b.hex,
1541 shape: b.shape,
1542 image: b.image,
1543 terra: !!b.terra || i < TERRA_COUNT,
1544 index: i,
1545 threshold: need,
1546 unlocked: points >= need
1547 });
1548 }
1549 return out;
1550 }
1551
1552 function asColor (id, slot)
1553 {
1554 var b = byId(id);
1555 if (!b)
1556 { return null; }
1557 return {
1558 id: slot,
1559 block: b.id,
1560 name: b.name || b.id,
1561 hex: b.hex,
1562 shape: b.shape,
1563 image: b.image
1564 };
1565 }
1566
1567 function images ()
1568 {
1569 var list = all();
1570 var out = [];
1571 var seen = Object.create(null);
1572 for (var i = 0; i < list.length; i++)
1573 {
1574 var url = list[i].image;
1575 if (!url || seen[url])
1576 { continue; }
1577 seen[url] = true;
1578 out.push({ name: 'block:' + list[i].id, url: url });
1579 }
1580 return out;
1581 }
1582
1583 return {
1584 TERRA_COUNT: TERRA_COUNT,
1585 FIRST_THRESHOLD: FIRST_THRESHOLD,
1586 GROWTH: GROWTH,
1587 all: all,
1588 byId: byId,
1589 indexOf: indexOf,
1590 threshold: threshold,
1591 unlocked: unlocked,
1592 unlockedId: unlockedId,
1593 present: present,
1594 asColor: asColor,
1595 images: images
1596 };
1597})();
1598
1599if (typeof module !== 'undefined' && module.exports)
1600{ module.exports = Blocks; }
1601else if (typeof globalThis !== 'undefined')
1602{ globalThis.Blocks = Blocks; }
1603
1604/*
1605 * End File:
1606 * /workspace/meteors/src/blocks.js
1607 */
1608
1609/*
1610 * Start File:
1611 * /workspace/meteors/src/easing.js
1612 */
1613'use strict';
1614
1615/**
1616 * Easing curves matching Qt QEasingCurve defaults (the same values Tim's
1617 * KWin Click Tween effect uses). Formulas and default parameters come from
1618 * Qt 6's QEasingCurve and https://easings.net/.
1619 *
1620 * Source of the click/release defaults:
1621 * /workspace/click-tween/settings.h (clickTime, releaseTime, easing names)
1622 * /workspace/click-tween/clicktween.cpp (press scale 0.8, release scale 1.0)
1623 * /workspace/click-tween/README.md
1624 */
1625
1626/** Qt QEasingCurve default overshoot for InBack / OutBack / InOutBack. */
1627var BACK_OVERSHOOT = 1.70158;
1628
1629/** Qt QEasingCurve default period and amplitude for Elastic curves. */
1630var ELASTIC_PERIOD = 0.3;
1631var ELASTIC_AMPLITUDE = 1.0;
1632
1633function clamp01 (t)
1634{
1635 if (t <= 0)
1636 { return 0; }
1637 if (t >= 1)
1638 { return 1; }
1639 return t;
1640}
1641
1642/** easeOutBack: overshoots the end value, then settles. Qt / easings.net. */
1643function easeOutBack (t)
1644{
1645 t = clamp01(t);
1646 var c1 = BACK_OVERSHOOT;
1647 var c3 = c1 + 1;
1648 var u = t - 1;
1649 return 1 + c3 * u * u * u + c1 * u * u;
1650}
1651
1652/**
1653 * easeOutElastic: decaying sine overshoot past the end value.
1654 * Qt default amplitude 1, period 0.3 (equivalent to easings.net).
1655 */
1656function easeOutElastic (t)
1657{
1658 t = clamp01(t);
1659 if (t === 0 || t === 1)
1660 { return t; }
1661 var p = ELASTIC_PERIOD;
1662 var s = p / 4;
1663 return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
1664}
1665
1666/** easeOutCubic: 1 − (1−t)³. Smooth, no overshoot (easings.net). */
1667function easeOutCubic (t)
1668{
1669 t = clamp01(t);
1670 var u = 1 - t;
1671 return 1 - u * u * u;
1672}
1673
1674function tween (from, to, t, ease)
1675{
1676 return from + (to - from) * ease(clamp01(t));
1677}
1678
1679/**
1680 * Visual-only block swap tween (t1121). Game logic and the grid update
1681 * immediately; this only moves the displaced sprite. 100 ms sits in the
1682 * requested 80–120 ms range.
1683 */
1684var SWAP_TWEEN = {
1685 duration: 0.100,
1686 ease: easeOutCubic
1687};
1688
1689/**
1690 * DEFAULT settings of Tim's KWin Click Tween
1691 * (git.timfalken.com/timfa/click-tween).
1692 *
1693 * Press: shrink to 80% in 150 ms with easeOutBack, stay at 80% while held.
1694 * Release: grow back to 100% in 720 ms with easeOutElastic.
1695 * Mid-animation release starts from the current scale, like QVariantAnimation.
1696 */
1697var CLICK_TWEEN = {
1698 pressScale: 0.8,
1699 releaseScale: 1.0,
1700 pressDuration: 0.150,
1701 releaseDuration: 0.720,
1702 pressEase: easeOutBack,
1703 releaseEase: easeOutElastic,
1704 backOvershoot: BACK_OVERSHOOT,
1705 elasticPeriod: ELASTIC_PERIOD,
1706 elasticAmplitude: ELASTIC_AMPLITUDE,
1707 source: 'click-tween settings.h + clicktween.cpp (Qt QEasingCurve defaults)'
1708};
1709
1710/**
1711 * Visual landing bounce, u in 0..1. Subtle squash with a slight stretch
1712 * on the other axis and a tiny upward rebound (in tiles, visual only).
1713 */
1714function bouncePose (u, squash)
1715{
1716 if (u <= 0 || u >= 1)
1717 { return { sx: 1, sy: 1, dy: 0 }; }
1718 var wave = Math.sin(Math.PI * u);
1719 return {
1720 sx: 1 + squash * 0.6 * wave,
1721 sy: 1 - squash * wave,
1722 dy: 0.07 * wave * (1 - u)
1723 };
1724}
1725
1726var Easing = {
1727 BACK_OVERSHOOT: BACK_OVERSHOOT,
1728 ELASTIC_PERIOD: ELASTIC_PERIOD,
1729 ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,
1730 easeOutBack: easeOutBack,
1731 easeOutElastic: easeOutElastic,
1732 easeOutCubic: easeOutCubic,
1733 tween: tween,
1734 CLICK_TWEEN: CLICK_TWEEN,
1735 SWAP_TWEEN: SWAP_TWEEN,
1736 clamp01: clamp01,
1737 bouncePose: bouncePose
1738};
1739
1740if (typeof module !== 'undefined' && module.exports)
1741{ module.exports = Easing; }
1742else if (typeof globalThis !== 'undefined')
1743{ globalThis.Easing = Easing; }
1744
1745/*
1746 * End File:
1747 * /workspace/meteors/src/easing.js
1748 */
1749
1750/*
1751 * Start File:
1752 * /workspace/meteors/src/gameCore.js
1753 */
1754'use strict';
1755
1756/**
1757 * Deterministic Meteors game core. No DOM, no rendering, no input devices.
1758 * The view layer reads this state and translates pointer events into
1759 * beginDrag / moveDrag / endDrag.
1760 */
1761
1762var PlanetMod = (typeof require !== 'undefined' && typeof module !== 'undefined')
1763 ? require('./planet.js')
1764 : (typeof Planet !== 'undefined' ? Planet : globalThis.Planet);
1765
1766var COLOR_GRAY = -1;
1767
1768var STATE_STILL = 'still';
1769var STATE_FALLING = 'falling';
1770var STATE_FLYING = 'flying';
1771var STATE_SETTLING = 'settling';
1772var STATE_LOCKED = 'locked';
1773var STATE_MANUAL = 'manual';
1774
1775var ALIGN_EPS = 0.15;
1776var SUBSTEP = 1 / 120;
1777var DRAG_LAUNCH_SLACK = 0.65;
1778// Upward pull (tiles past the press point) that launches an already-topmost block.
1779var LAUNCH_PULL = 0.35;
1780// Minimal accumulated vertical pointer travel (tiles) to swap one step.
1781// No hold delay: the first swap fires as soon as this distance is reached.
1782var SWAP_DISTANCE = 0.25;
1783// Fallback snap (tiles) when the press cell is empty: nearest block in the column.
1784var SNAP_Y = 0.5;
1785// Horizontal slop (tiles) for snapping to a neighbouring column on press.
1786var HORIZONTAL_SLOP = 0.35;
1787/** t1120: additive jump bonus per landing-chain step. A landing that
1788 * immediately makes a match launches at (1 + 0.25 * chain) times the
1789 * usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */
1790var LANDING_CHAIN_BONUS = 0.25;
1791/** t1123: a column pulses red at or above this many grounded rows
1792 * (10 of 13 is just over 70%). */
1793var COLUMN_WARN_ROWS = 10;
1794
1795function UnionFind ()
1796{
1797 this.parent = Object.create(null);
1798}
1799
1800UnionFind.prototype.add = function (id)
1801{
1802 if (this.parent[id] == null)
1803 { this.parent[id] = id; }
1804};
1805
1806UnionFind.prototype.find = function (id)
1807{
1808 if (this.parent[id] !== id)
1809 { this.parent[id] = this.find(this.parent[id]); }
1810 return this.parent[id];
1811};
1812
1813UnionFind.prototype.union = function (a, b)
1814{
1815 this.add(a);
1816 this.add(b);
1817 var ra = this.find(a);
1818 var rb = this.find(b);
1819 if (ra !== rb)
1820 { this.parent[rb] = ra; }
1821};
1822
1823function GameCore (planet, rng)
1824{
1825 this.planet = planet || PlanetMod.defaultPlanet();
1826 this.rng = rng || Math.random;
1827 this.width = PlanetMod.FIELD_WIDTH;
1828 this.height = PlanetMod.FIELD_HEIGHT;
1829 this.blocks = [];
1830 this.clusters = Object.create(null);
1831 this.nextBlockId = 1;
1832 this.nextClusterId = 1;
1833 this.spawnTimer = 0;
1834 this.spawnInterval = PlanetMod.SPAWN_INTERVAL;
1835 this.settleTime = PlanetMod.SETTLE_TIME;
1836 this.score = 0;
1837 this.state = 'playing';
1838 this.drag = null;
1839 this.gameOverTime = 0;
1840 this.outgoingShots = [];
1841 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
1842 this.missChance = optsMissChance(arguments);
1843 // t1112: invariant checker. strictInvariants throws (tests);
1844 // debugInvariants records violations for the ?debug overlay.
1845 this.strictInvariants = false;
1846 this.debugInvariants = false;
1847 this.lastInvariantViolations = [];
1848 // t1121: visual-only swap events, consumed by the view each frame.
1849 this.swapEvents = [];
1850 // t1120: last landing-chain indicator { chain, bonusPct }, or null.
1851 this.lastChainIndicator = null;
1852}
1853
1854function optsMissChance (args)
1855{
1856 // GameCore(planet, rng, missChance) — third arg is optional.
1857 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
1858 { return Math.max(0, Math.min(1, args[2])); }
1859 var planet = args[0];
1860 if (planet && typeof PlanetMod.missChance === 'function')
1861 { return PlanetMod.missChance(planet); }
1862 return GameCore.DEFAULT_MISS_CHANCE;
1863}
1864
1865GameCore.COLOR_GRAY = COLOR_GRAY;
1866GameCore.LAUNCH_PULL = LAUNCH_PULL;
1867GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
1868GameCore.SNAP_Y = SNAP_Y;
1869GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
1870GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS;
1871GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS;
1872GameCore.DEFAULT_MISS_CHANCE = 0.30;
1873GameCore.STATE_STILL = STATE_STILL;
1874GameCore.STATE_FALLING = STATE_FALLING;
1875GameCore.STATE_FLYING = STATE_FLYING;
1876GameCore.STATE_SETTLING = STATE_SETTLING;
1877GameCore.STATE_LOCKED = STATE_LOCKED;
1878GameCore.STATE_MANUAL = STATE_MANUAL;
1879
1880GameCore.prototype.randomColor = function ()
1881{
1882 return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length;
1883};
1884
1885GameCore.prototype.createBlock = function (col, y, color, state)
1886{
1887 var block = {
1888 id: this.nextBlockId++,
1889 col: col,
1890 y: y,
1891 color: color,
1892 state: state || STATE_STILL,
1893 vy: 0,
1894 clusterId: null,
1895 settleTime: 0,
1896 flame: false,
1897 pushedClusters: null,
1898 manualTarget: 0,
1899 manualDecel: 0,
1900 manualPhase: null,
1901 bouncing: false,
1902 bounceAge: 0
1903 };
1904 this.blocks.push(block);
1905 return block;
1906};
1907
1908GameCore.prototype.removeBlock = function (block)
1909{
1910 if (block.clusterId != null)
1911 { this.leaveCluster(block); }
1912 var index = this.blocks.indexOf(block);
1913 if (index >= 0)
1914 { this.blocks.splice(index, 1); }
1915};
1916
1917GameCore.prototype.leaveCluster = function (block)
1918{
1919 var id = block.clusterId;
1920 block.clusterId = null;
1921 block.flame = false;
1922 if (id == null || !this.clusters[id])
1923 { return; }
1924 var still = 0;
1925 for (var i = 0; i < this.blocks.length; i++)
1926 {
1927 if (this.blocks[i].clusterId === id)
1928 { still++; }
1929 }
1930 if (still === 0)
1931 { delete this.clusters[id]; }
1932};
1933
1934GameCore.prototype.blocksInColumn = function (col)
1935{
1936 var out = [];
1937 for (var i = 0; i < this.blocks.length; i++)
1938 {
1939 if (this.blocks[i].col === col)
1940 { out.push(this.blocks[i]); }
1941 }
1942 out.sort(function (a, b) { return a.y - b.y; });
1943 return out;
1944};
1945
1946GameCore.prototype.isGrounded = function (block)
1947{
1948 return block.state === STATE_STILL
1949 || block.state === STATE_SETTLING
1950 || block.state === STATE_LOCKED;
1951};
1952
1953/**
1954 * Highest grounded landing surface in `col`. If `belowY` is given, only
1955 * blocks strictly below that y count — a hanging still block above a
1956 * gap must never pull a falling or thrown block upward through the gap.
1957 */
1958GameCore.prototype.stackTop = function (col, ignore, belowY)
1959{
1960 var top = 0;
1961 for (var i = 0; i < this.blocks.length; i++)
1962 {
1963 var block = this.blocks[i];
1964 if (block.col !== col)
1965 { continue; }
1966 if (ignore && ignore(block))
1967 { continue; }
1968 if (belowY != null && block.y + 1e-9 >= belowY)
1969 { continue; }
1970 if (this.isGrounded(block))
1971 {
1972 var surface = block.y + 1;
1973 if (surface > top)
1974 { top = surface; }
1975 }
1976 }
1977 return top;
1978};
1979
1980GameCore.prototype.isColumnLocked = function (col)
1981{
1982 for (var i = 0; i < this.blocks.length; i++)
1983 {
1984 var block = this.blocks[i];
1985 if (block.col === col && block.state === STATE_LOCKED)
1986 { return true; }
1987 }
1988 return false;
1989};
1990
1991GameCore.prototype.isColumnStill = function (col)
1992{
1993 if (this.isColumnLocked(col))
1994 { return false; }
1995 for (var i = 0; i < this.blocks.length; i++)
1996 {
1997 var block = this.blocks[i];
1998 if (block.col !== col)
1999 { continue; }
2000 if (block.state === STATE_FLYING
2001 || block.state === STATE_FALLING
2002 || block.state === STATE_MANUAL
2003 || block.state === STATE_SETTLING)
2004 { return false; }
2005 }
2006 return true;
2007};
2008
2009GameCore.prototype.groundedCount = function (col)
2010{
2011 var n = 0;
2012 for (var i = 0; i < this.blocks.length; i++)
2013 {
2014 if (this.blocks[i].col === col && this.isGrounded(this.blocks[i]))
2015 { n++; }
2016 }
2017 return n;
2018};
2019
2020GameCore.prototype.columnNeedsWarn = function (col)
2021{
2022 return this.groundedCount(col) >= COLUMN_WARN_ROWS;
2023};
2024
2025/**
2026 * Which columns of a field snapshot should pulse (t1123). Flying,
2027 * falling and manual (airborne) blocks do not count: they are
2028 * temporary and would flicker the warning. Still, settling and
2029 * locked (grounded) blocks do.
2030 */
2031GameCore.warnColumnsFromSnapshot = function (snapshot, threshold)
2032{
2033 threshold = threshold == null ? COLUMN_WARN_ROWS : threshold;
2034 var width = (snapshot && snapshot.width) || 10;
2035 var flags = [];
2036 var counts = [];
2037 for (var c = 0; c < width; c++)
2038 {
2039 counts[c] = 0;
2040 flags[c] = false;
2041 }
2042 var blocks = (snapshot && snapshot.blocks) || [];
2043 for (var i = 0; i < blocks.length; i++)
2044 {
2045 var b = blocks[i];
2046 if (b.col < 0 || b.col >= width)
2047 { continue; }
2048 if (b.state === 'still' || b.state === 'settling' || b.state === 'locked')
2049 { counts[b.col]++; }
2050 }
2051 for (var c = 0; c < width; c++)
2052 { flags[c] = counts[c] >= threshold; }
2053 return flags;
2054};
2055
2056GameCore.columnWarnPulse = function (timeSec)
2057{
2058 // Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player
2059 // field and opponent / bot minis so they pulse in sync.
2060 var t = timeSec;
2061 if (t == null)
2062 {
2063 t = (typeof performance !== 'undefined' && performance.now)
2064 ? performance.now() / 1000
2065 : Date.now() / 1000;
2066 }
2067 return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55));
2068};
2069
2070GameCore.prototype.blockAt = function (col, row)
2071{
2072 for (var i = 0; i < this.blocks.length; i++)
2073 {
2074 var block = this.blocks[i];
2075 if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS)
2076 { return block; }
2077 }
2078 return null;
2079};
2080
2081GameCore.prototype.place = function (col, row, color, state)
2082{
2083 return this.createBlock(col, row, color, state || STATE_STILL);
2084};
2085
2086GameCore.prototype.lockedColumnCount = function ()
2087{
2088 var n = 0;
2089 for (var c = 0; c < this.width; c++)
2090 {
2091 if (this.isColumnLocked(c))
2092 { n++; }
2093 }
2094 return n;
2095};
2096
2097GameCore.prototype.startBounce = function (block)
2098{
2099 if (!block)
2100 { return; }
2101 block.bouncing = true;
2102 block.bounceAge = 0;
2103};
2104
2105GameCore.prototype.advanceBounces = function (dt)
2106{
2107 var duration = this.planet.bounceDuration;
2108 for (var i = 0; i < this.blocks.length; i++)
2109 {
2110 var block = this.blocks[i];
2111 if (!block.bouncing)
2112 { continue; }
2113 block.bounceAge += dt;
2114 if (duration <= 0 || block.bounceAge >= duration)
2115 {
2116 block.bouncing = false;
2117 block.bounceAge = duration;
2118 }
2119 }
2120};
2121
2122/**
2123 * True if `block` rests on the floor or on a solid (still / settling /
2124 * locked) block immediately below it in the same column.
2125 */
2126GameCore.prototype.hasSupport = function (block)
2127{
2128 if (block.y <= 1e-9)
2129 { return true; }
2130 for (var i = 0; i < this.blocks.length; i++)
2131 {
2132 var other = this.blocks[i];
2133 if (other === block || other.col !== block.col)
2134 { continue; }
2135 if (!this.isGrounded(other))
2136 { continue; }
2137 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
2138 { return true; }
2139 }
2140 return false;
2141};
2142
2143/** Highest flying block in this column whose top is at or below `block.y + 1`. */
2144GameCore.prototype.highestFlyingBelow = function (block)
2145{
2146 var best = null;
2147 for (var i = 0; i < this.blocks.length; i++)
2148 {
2149 var other = this.blocks[i];
2150 if (other === block || other.col !== block.col)
2151 { continue; }
2152 if (other.state !== STATE_FLYING || other.clusterId == null)
2153 { continue; }
2154 var cluster = this.clusters[other.clusterId];
2155 if (!cluster || cluster.phase === 'landed')
2156 { continue; }
2157 // The falling block is at or above this flyer (or already overlapping).
2158 if (block.y + 1e-9 < other.y)
2159 { continue; }
2160 if (!best || other.y > best.y)
2161 { best = other; }
2162 }
2163 return best;
2164};
2165
2166GameCore.prototype.highestFallingBelow = function (block)
2167{
2168 var best = null;
2169 for (var i = 0; i < this.blocks.length; i++)
2170 {
2171 var other = this.blocks[i];
2172 if (other === block || other.col !== block.col)
2173 { continue; }
2174 if (other.state !== STATE_FALLING)
2175 { continue; }
2176 if (other.y > block.y - 1e-9)
2177 { continue; }
2178 if (!best || other.y > best.y)
2179 { best = other; }
2180 }
2181 return best;
2182};
2183
2184/**
2185 * Make an unsupported still block start falling from rest, so it eases
2186 * into fallSpeed under normal gravity. Skips the block being dragged.
2187 */
2188/**
2189 * Strip leftover launch / manual kinematics so a block that has just
2190 * become still or falling starts from rest. Used after a landed grey
2191 * cluster recolors, and whenever an unsupported still block drops.
2192 */
2193GameCore.prototype.clearFlightState = function (block)
2194{
2195 block.vy = 0;
2196 block.flame = false;
2197 block.manualPhase = null;
2198 block.manualTarget = null;
2199 block.manualDecel = 0;
2200 block.pushedClusters = null;
2201};
2202
2203GameCore.prototype.releaseUnsupported = function ()
2204{
2205 // Repeat until stable: a still sitting on a still that itself just
2206 // became falling must also drop. Two fixed passes are not enough
2207 // for a chain of hanging blocks (t1112).
2208 var guard = 0;
2209 var changed = true;
2210 while (changed && guard++ < this.height + 2)
2211 {
2212 changed = false;
2213 for (var i = 0; i < this.blocks.length; i++)
2214 {
2215 var block = this.blocks[i];
2216 if (block.state !== STATE_STILL)
2217 { continue; }
2218 if (this.drag && this.drag.blockId === block.id)
2219 { continue; }
2220 if (this.hasSupport(block))
2221 { continue; }
2222 this.leaveCluster(block);
2223 this.clearFlightState(block);
2224 block.state = STATE_FALLING;
2225 changed = true;
2226 }
2227 }
2228};
2229
2230GameCore.prototype.accelerateFall = function (block, dt)
2231{
2232 var target = -this.planet.fallSpeed;
2233 if (block.vy > target)
2234 { block.vy = Math.max(target, block.vy - this.planet.fallAccel * dt); }
2235 else
2236 { block.vy = target; }
2237};
2238
2239GameCore.prototype.landFallingBlock = function (block)
2240{
2241 block.vy = 0;
2242 block.flame = false;
2243 this.startBounce(block);
2244 if (block.color === COLOR_GRAY)
2245 {
2246 block.state = STATE_SETTLING;
2247 block.settleTime = 0;
2248 }
2249 else
2250 { block.state = STATE_STILL; }
2251};
2252
2253/**
2254 * Sit `block` on top of the flying cluster that `flyer` belongs to, and
2255 * carry it along as cargo (no flame). Returns true if attached.
2256 */
2257GameCore.prototype.attachToFlyingCluster = function (block, flyer)
2258{
2259 var cluster = this.clusters[flyer.clusterId];
2260 if (!cluster || cluster.phase === 'landed')
2261 { return false; }
2262 this.prepareClusterBody(cluster);
2263 var maxOff = null;
2264 var members = this.clusterMembers(cluster.id);
2265 for (var i = 0; i < members.length; i++)
2266 {
2267 if (members[i].col !== block.col)
2268 { continue; }
2269 if (maxOff == null || members[i].clusterOffset > maxOff)
2270 { maxOff = members[i].clusterOffset; }
2271 }
2272 var oldN = members.length;
2273 var fallingVy = block.vy;
2274 if (block.clusterId != null && block.clusterId !== cluster.id)
2275 { this.leaveCluster(block); }
2276 block.state = STATE_FLYING;
2277 block.clusterId = cluster.id;
2278 block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1;
2279 block.flame = false;
2280 block.settleTime = 0;
2281 block.manualPhase = null;
2282 block.manualTarget = null;
2283 block.manualDecel = 0;
2284 block.pushedClusters = null;
2285 // A cluster born from a thrown block averages in falling cargo
2286 // the same way two flying clusters merge (t1108). Other rockets
2287 // keep their velocity and just pick the cargo up.
2288 if (cluster.fromManual)
2289 {
2290 var newN = oldN + 1;
2291 cluster.vy = (cluster.vy * oldN + fallingVy) / newN;
2292 cluster.decel = ((cluster.decel || 0) * oldN) / newN;
2293 cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
2294 cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
2295 }
2296 this.syncClusterMembers(cluster);
2297 return true;
2298};
2299
2300GameCore.prototype.catchFallingOntoCluster = function (cluster, members)
2301{
2302 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
2303 { return; }
2304 // Snapshot falling blocks; attaching mutates state.
2305 var falling = [];
2306 for (var i = 0; i < this.blocks.length; i++)
2307 {
2308 if (this.blocks[i].state === STATE_FALLING)
2309 { falling.push(this.blocks[i]); }
2310 }
2311 for (var i = 0; i < falling.length; i++)
2312 {
2313 var block = falling[i];
2314 var flyer = null;
2315 for (var m = 0; m < members.length; m++)
2316 {
2317 var other = members[m];
2318 if (other.col !== block.col)
2319 { continue; }
2320 // Overlap or rest on this member's top.
2321 if (block.y < other.y + 1 + 1e-9 && block.y + 1 > other.y - 1e-9)
2322 {
2323 if (!flyer || other.y > flyer.y)
2324 { flyer = other; }
2325 }
2326 }
2327 if (flyer)
2328 { this.attachToFlyingCluster(block, flyer); }
2329 }
2330};
2331
2332GameCore.prototype.tick = function (dt)
2333{
2334 if (this.state === 'gameover')
2335 {
2336 this.gameOverTime += Math.max(0, dt);
2337 return;
2338 }
2339 if (dt <= 0)
2340 { return; }
2341 dt = Math.min(dt, 0.1);
2342
2343 this.spawnTimer += dt;
2344 while (this.spawnTimer >= this.spawnInterval)
2345 {
2346 this.spawnTimer -= this.spawnInterval;
2347 this.trySpawn();
2348 }
2349
2350 var left = dt;
2351 while (left > 1e-12)
2352 {
2353 var step = Math.min(SUBSTEP, left);
2354 this.snapshotPrevY();
2355 this.integrateFalling(step);
2356 this.resolveFlyingMatches();
2357 this.integrateClusters(step);
2358 this.mergeFlyingClusters();
2359 this.integrateManual(step);
2360 this.mergeAnyManualFallingOverlaps();
2361 this.resolveAirborneCollisions();
2362 this.cullOffTop();
2363 left -= step;
2364 }
2365
2366 this.releaseUnsupported();
2367 this.advanceSettle(dt);
2368 // After a landed grey group is released, blocks that were sitting on
2369 // hanging members are still STILL (the earlier pass ran while those
2370 // members counted as support). Drop them from rest before matching,
2371 // so they cannot form a mid-air match and shoot off the top.
2372 this.releaseUnsupported();
2373 this.advanceBounces(dt);
2374 if (!this.drag)
2375 { this.resolveMatches(); }
2376 this.checkLocks();
2377 this.checkGameOver();
2378 this.assertInvariants('tick');
2379};
2380
2381/** Step a stretch of time in fixed substeps. Useful for tests. */
2382GameCore.prototype.step = function (seconds, dt)
2383{
2384 dt = dt || SUBSTEP;
2385 var t = 0;
2386 while (t < seconds - 1e-15)
2387 {
2388 var s = Math.min(dt, seconds - t);
2389 this.tick(s);
2390 t += s;
2391 }
2392};
2393
2394GameCore.prototype.trySpawn = function ()
2395{
2396 if (this.state !== 'playing')
2397 { return null; }
2398 var eligible = [];
2399 for (var col = 0; col < this.width; col++)
2400 {
2401 if (this.isColumnLocked(col))
2402 { continue; }
2403 if (this.groundedCount(col) >= this.height)
2404 { continue; }
2405 var alreadyFalling = false;
2406 var list = this.blocksInColumn(col);
2407 for (var i = 0; i < list.length; i++)
2408 {
2409 if (list[i].state === STATE_FALLING)
2410 {
2411 alreadyFalling = true;
2412 break;
2413 }
2414 }
2415 if (!alreadyFalling)
2416 { eligible.push(col); }
2417 }
2418 if (!eligible.length)
2419 { return null; }
2420 var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2421 var color = this.randomColor();
2422 var block = this.createBlock(col, this.height, color, STATE_FALLING);
2423 block.vy = -this.planet.fallSpeed;
2424 return block;
2425};
2426
2427GameCore.prototype.integrateFalling = function (dt)
2428{
2429 var falling = [];
2430 for (var i = 0; i < this.blocks.length; i++)
2431 {
2432 if (this.blocks[i].state === STATE_FALLING)
2433 { falling.push(this.blocks[i]); }
2434 }
2435 // Lowest first, so a stack of falling blocks rests on itself.
2436 falling.sort(function (a, b) { return a.y - b.y; });
2437 for (var i = 0; i < falling.length; i++)
2438 {
2439 var block = falling[i];
2440 if (block.state !== STATE_FALLING)
2441 { continue; }
2442 this.accelerateFall(block, dt);
2443 var nextY = block.y + block.vy * dt;
2444 var manual = this.manualInColumnHit(block, block.y, nextY);
2445 if (manual)
2446 {
2447 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
2448 continue;
2449 }
2450 var flyer = this.highestFlyingBelow(block);
2451 if (flyer && nextY <= flyer.y + 1 + 1e-9)
2452 {
2453 if (this.attachToFlyingCluster(block, flyer))
2454 { continue; }
2455 }
2456 var top = this.stackTop(block.col, null, block.y);
2457 var below = this.highestFallingBelow(block);
2458 if (below && below.y + 1 > top)
2459 { top = below.y + 1; }
2460 if (nextY <= top)
2461 {
2462 block.y = top;
2463 this.landFallingBlock(block);
2464 }
2465 else
2466 { block.y = nextY; }
2467 }
2468};
2469
2470GameCore.prototype.clusterMembers = function (clusterId)
2471{
2472 var out = [];
2473 for (var i = 0; i < this.blocks.length; i++)
2474 {
2475 if (this.blocks[i].clusterId === clusterId)
2476 { out.push(this.blocks[i]); }
2477 }
2478 return out;
2479};
2480
2481
2482/**
2483 * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a
2484 * jump of height H peaks at exactly H after riseTime. Returns dy.
2485 * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the
2486 * upward deceleration. After the apex, vy eases from 0 to the
2487 * terminal descent speed at the matching accel, then stays there.
2488 * Flying clusters (forCluster) use the halved cluster float-down
2489 * (t1122 / t1124); manual jumps use the full single-block fallSpeed.
2490 */
2491GameCore.prototype.descentParams = function (forCluster)
2492{
2493 var p = this.planet;
2494 if (forCluster)
2495 {
2496 return {
2497 fallSpeed: p.clusterFallSpeed,
2498 fallAccel: p.clusterFallAccel
2499 };
2500 }
2501 return { fallSpeed: p.fallSpeed, fallAccel: p.fallAccel };
2502};
2503
2504GameCore.prototype.advanceJump = function (body, dt, forCluster)
2505{
2506 var dy = 0;
2507 var left = dt;
2508 if (body.phase === 'up')
2509 {
2510 var decel = body.decel;
2511 var vy = body.vy;
2512 var tApex = decel > 1e-12 ? vy / decel : Infinity;
2513 if (tApex <= left + 1e-15)
2514 {
2515 dy += vy * tApex - 0.5 * decel * tApex * tApex;
2516 body.vy = 0;
2517 body.phase = 'down';
2518 left -= tApex;
2519 }
2520 else
2521 {
2522 var vyNew = vy - decel * left;
2523 dy += (vy + vyNew) * 0.5 * left;
2524 body.vy = vyNew;
2525 left = 0;
2526 }
2527 }
2528 if (body.phase === 'up' && body.vy <= 1e-10)
2529 {
2530 body.vy = 0;
2531 body.phase = 'down';
2532 }
2533 if (body.phase === 'down' && left > 0)
2534 {
2535 var desc = this.descentParams(forCluster);
2536 var target = -desc.fallSpeed;
2537 var accel = desc.fallAccel;
2538 if (accel < 1e-12)
2539 {
2540 body.vy = target;
2541 dy += body.vy * left;
2542 }
2543 else if (body.vy > target + 1e-12)
2544 {
2545 var tReach = (body.vy - target) / accel;
2546 if (tReach <= left + 1e-15)
2547 {
2548 dy += (body.vy + target) * 0.5 * tReach;
2549 body.vy = target;
2550 left -= tReach;
2551 dy += body.vy * left;
2552 }
2553 else
2554 {
2555 var vyNew = body.vy - accel * left;
2556 dy += (body.vy + vyNew) * 0.5 * left;
2557 body.vy = vyNew;
2558 }
2559 }
2560 else
2561 {
2562 body.vy = target;
2563 dy += body.vy * left;
2564 }
2565 }
2566 return dy;
2567};
2568
2569GameCore.prototype.integrateClusters = function (dt)
2570{
2571 var ids = Object.keys(this.clusters);
2572 for (var n = 0; n < ids.length; n++)
2573 {
2574 var cluster = this.clusters[ids[n]];
2575 if (!cluster)
2576 { continue; }
2577 var members = this.clusterMembers(cluster.id);
2578 if (!members.length)
2579 {
2580 delete this.clusters[cluster.id];
2581 continue;
2582 }
2583 if (cluster.phase === 'landed' || cluster.phase === 'hold')
2584 { continue; }
2585
2586 this.prepareClusterBody(cluster);
2587 var dy = this.advanceJump(cluster, dt, true);
2588 cluster.anchorY += dy;
2589 this.syncClusterMembers(cluster);
2590
2591 this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id));
2592 this.checkChainRelaunch(cluster);
2593
2594 if (cluster.phase === 'down' && this.clusters[cluster.id])
2595 { this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }
2596 }
2597};
2598
2599
2600/**
2601 * If two or more flying clusters overlap in the same column, merge them
2602 * into one cluster. Velocity (and deceleration and jumpHeight) is the
2603 * mass-weighted average by block count. Phase is 'up' when the merged
2604 * vy is positive, otherwise 'down'. Overlapping members in a column
2605 * are packed so the higher one sits flush on the lower.
2606 */
2607GameCore.prototype.mergeFlyingClusters = function ()
2608{
2609 var flying = [];
2610 var ids = Object.keys(this.clusters);
2611 for (var n = 0; n < ids.length; n++)
2612 {
2613 var cluster = this.clusters[ids[n]];
2614 if (!cluster)
2615 { continue; }
2616 if (cluster.phase === 'landed' || cluster.phase === 'hold')
2617 { continue; }
2618 flying.push(cluster);
2619 }
2620 if (flying.length < 2)
2621 { return; }
2622
2623 var uf = new UnionFind();
2624 for (var i = 0; i < flying.length; i++)
2625 { uf.add(flying[i].id); }
2626 for (var i = 0; i < flying.length; i++)
2627 {
2628 for (var j = i + 1; j < flying.length; j++)
2629 {
2630 if (this.flyingClustersOverlap(flying[i], flying[j]))
2631 { uf.union(flying[i].id, flying[j].id); }
2632 }
2633 }
2634
2635 var groups = Object.create(null);
2636 for (var i = 0; i < flying.length; i++)
2637 {
2638 var root = uf.find(flying[i].id);
2639 if (!groups[root])
2640 { groups[root] = []; }
2641 groups[root].push(flying[i]);
2642 }
2643 for (var root in groups)
2644 {
2645 if (groups[root].length >= 2)
2646 { this.mergeClusterGroup(groups[root]); }
2647 }
2648};
2649
2650GameCore.prototype.flyingClustersOverlap = function (a, b)
2651{
2652 var ma = this.clusterMembers(a.id);
2653 var mb = this.clusterMembers(b.id);
2654 for (var i = 0; i < ma.length; i++)
2655 {
2656 for (var j = 0; j < mb.length; j++)
2657 {
2658 if (ma[i].col !== mb[j].col)
2659 { continue; }
2660 if (this.sweptIntervalsOverlap(ma[i], mb[j]))
2661 { return true; }
2662 }
2663 }
2664 return false;
2665};
2666
2667/**
2668 * Swept [y, y+1) of two blocks this substep, using _prevY when present.
2669 * Catches pairs that crossed without sharing a cell at either endpoint.
2670 */
2671GameCore.prototype.sweptIntervalsOverlap = function (a, b)
2672{
2673 var a0 = (a._prevY != null) ? a._prevY : a.y;
2674 var a1 = a.y;
2675 var b0 = (b._prevY != null) ? b._prevY : b.y;
2676 var b1 = b.y;
2677 var aLo = Math.min(a0, a1);
2678 var aHi = Math.max(a0, a1) + 1;
2679 var bLo = Math.min(b0, b1);
2680 var bHi = Math.max(b0, b1) + 1;
2681 return aLo < bHi - 1e-9 && bLo < aHi - 1e-9;
2682};
2683
2684GameCore.prototype.mergeClusterGroup = function (clusters)
2685{
2686 clusters.sort(function (a, b) { return a.id - b.id; });
2687 var keep = clusters[0];
2688 var n = 0;
2689 var vySum = 0;
2690 var decelSum = 0;
2691 var hSum = 0;
2692 for (var c = 0; c < clusters.length; c++)
2693 {
2694 var mem = this.clusterMembers(clusters[c].id);
2695 var m = mem.length;
2696 n += m;
2697 vySum += clusters[c].vy * m;
2698 decelSum += (clusters[c].decel || 0) * m;
2699 hSum += (clusters[c].jumpHeight || 0) * m;
2700 }
2701 if (n === 0)
2702 { return; }
2703 keep.vy = vySum / n;
2704 keep.decel = decelSum / n;
2705 keep.jumpHeight = hSum / n;
2706 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
2707 var maxChain = 0;
2708 for (var c = 0; c < clusters.length; c++)
2709 {
2710 var ch = clusters[c].landingChain || 0;
2711 if (ch > maxChain)
2712 { maxChain = ch; }
2713 }
2714 keep.landingChain = maxChain;
2715 for (var c = 0; c < clusters.length; c++)
2716 {
2717 var mem = this.clusterMembers(clusters[c].id);
2718 for (var i = 0; i < mem.length; i++)
2719 {
2720 mem[i].clusterId = keep.id;
2721 mem[i].vy = keep.vy;
2722 mem[i].state = STATE_FLYING;
2723 }
2724 if (clusters[c] !== keep)
2725 { delete this.clusters[clusters[c].id]; }
2726 }
2727 this.prepareClusterBody(keep);
2728 this.checkChainRelaunch(keep);
2729 if (keep.phase === 'down' && this.clusters[keep.id])
2730 { this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
2731};
2732
2733GameCore.prototype.packClusterOverlaps = function (cluster)
2734{
2735 var members = this.clusterMembers(cluster.id);
2736 var byCol = Object.create(null);
2737 for (var i = 0; i < members.length; i++)
2738 {
2739 var col = members[i].col;
2740 if (!byCol[col])
2741 { byCol[col] = []; }
2742 byCol[col].push(members[i]);
2743 }
2744 var cols = Object.keys(byCol);
2745 for (var c = 0; c < cols.length; c++)
2746 {
2747 var list = byCol[cols[c]];
2748 list.sort(function (a, b) { return a.y - b.y; });
2749 for (var i = 1; i < list.length; i++)
2750 {
2751 var minY = list[i - 1].y + 1;
2752 if (list[i].y < minY - 1e-12)
2753 { list[i].y = minY; }
2754 }
2755 }
2756};
2757
2758
2759/**
2760 * Derive integer cell offsets from current member positions and a
2761 * single anchorY, packing overlaps in each column while preserving
2762 * order (lower y stays lower; ties break on id). Then sync.
2763 * Flying clusters are one rigid body: one y, one vy, integer offsets.
2764 */
2765GameCore.prototype.prepareClusterBody = function (cluster)
2766{
2767 if (!cluster)
2768 { return; }
2769 var members = this.clusterMembers(cluster.id);
2770 if (!members.length)
2771 { return; }
2772 this.rebuildClusterOffsets(cluster, members);
2773};
2774
2775GameCore.prototype.rebuildClusterOffsets = function (cluster, members)
2776{
2777 members = members || this.clusterMembers(cluster.id);
2778 if (!members.length)
2779 { return; }
2780 var byCol = Object.create(null);
2781 for (var i = 0; i < members.length; i++)
2782 {
2783 var col = members[i].col;
2784 if (!byCol[col])
2785 { byCol[col] = []; }
2786 byCol[col].push(members[i]);
2787 }
2788 var minY = Infinity;
2789 for (var i = 0; i < members.length; i++)
2790 {
2791 if (members[i].y < minY)
2792 { minY = members[i].y; }
2793 }
2794 if (cluster.anchorY == null || !isFinite(cluster.anchorY))
2795 { cluster.anchorY = minY; }
2796 var cols = Object.keys(byCol);
2797 for (var c = 0; c < cols.length; c++)
2798 {
2799 var list = byCol[cols[c]];
2800 list.sort(function (a, b)
2801 {
2802 if (a.y !== b.y)
2803 { return a.y - b.y; }
2804 return a.id - b.id;
2805 });
2806 var prevOff = -Infinity;
2807 for (var i = 0; i < list.length; i++)
2808 {
2809 var off = Math.round(list[i].y - cluster.anchorY);
2810 if (off <= prevOff)
2811 { off = prevOff + 1; }
2812 list[i].clusterOffset = off;
2813 prevOff = off;
2814 }
2815 }
2816 // Re-base so the lowest offset is 0, keeping relative integers.
2817 var minOff = Infinity;
2818 for (var i = 0; i < members.length; i++)
2819 {
2820 if (members[i].clusterOffset < minOff)
2821 { minOff = members[i].clusterOffset; }
2822 }
2823 if (minOff !== 0 && isFinite(minOff))
2824 {
2825 cluster.anchorY += minOff;
2826 for (var i = 0; i < members.length; i++)
2827 { members[i].clusterOffset -= minOff; }
2828 }
2829 this.syncClusterMembers(cluster);
2830};
2831
2832GameCore.prototype.syncClusterMembers = function (cluster)
2833{
2834 if (!cluster)
2835 { return; }
2836 var members = this.clusterMembers(cluster.id);
2837 if (cluster.anchorY == null)
2838 {
2839 var minY = Infinity;
2840 for (var i = 0; i < members.length; i++)
2841 {
2842 if (members[i].y < minY)
2843 { minY = members[i].y; }
2844 }
2845 cluster.anchorY = isFinite(minY) ? minY : 0;
2846 }
2847 for (var i = 0; i < members.length; i++)
2848 {
2849 var block = members[i];
2850 if (block.clusterOffset == null)
2851 { block.clusterOffset = Math.round(block.y - cluster.anchorY); }
2852 block.y = cluster.anchorY + block.clusterOffset;
2853 if (cluster.phase !== 'landed')
2854 { block.vy = cluster.vy; }
2855 }
2856};
2857
2858GameCore.prototype.snapshotPrevY = function ()
2859{
2860 for (var i = 0; i < this.blocks.length; i++)
2861 { this.blocks[i]._prevY = this.blocks[i].y; }
2862};
2863
2864/**
2865 * Safety net after the specific integrates: any remaining mid-air
2866 * overlap or swept crossing is resolved with the same rules, then
2867 * every flying cluster is rebuilt as a rigid body. Repeats a few
2868 * times because one attach can create a new contact.
2869 */
2870GameCore.prototype.resolveAirborneCollisions = function ()
2871{
2872 var guard = 0;
2873 while (guard++ < this.height + 4)
2874 {
2875 var changed = false;
2876
2877 // Manual vs falling / cluster / manual.
2878 var manuals = [];
2879 for (var i = 0; i < this.blocks.length; i++)
2880 {
2881 if (this.blocks[i].state === STATE_MANUAL)
2882 { manuals.push(this.blocks[i]); }
2883 }
2884 manuals.sort(function (a, b) { return b.y - a.y; });
2885 for (var m = 0; m < manuals.length; m++)
2886 {
2887 var manual = manuals[m];
2888 if (manual.state !== STATE_MANUAL)
2889 { continue; }
2890 var oldY = (manual._prevY != null) ? manual._prevY : manual.y;
2891 if (this.resolveManualCollisions(manual, oldY, manual.y))
2892 { changed = true; }
2893 }
2894
2895 // Falling vs flying (sit on the roof).
2896 for (var i = 0; i < this.blocks.length; i++)
2897 {
2898 var block = this.blocks[i];
2899 if (block.state !== STATE_FALLING)
2900 { continue; }
2901 var flyer = this.highestFlyingBelow(block);
2902 if (!flyer)
2903 {
2904 // Also a flyer whose swept path crosses this falling block.
2905 flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y);
2906 }
2907 if (flyer && this.sweptIntervalsOverlap(block, flyer))
2908 {
2909 if (this.attachToFlyingCluster(block, flyer))
2910 { changed = true; }
2911 }
2912 }
2913
2914 // Cluster vs cluster (swept, including after a column push).
2915 var before = Object.keys(this.clusters).length;
2916 this.mergeFlyingClusters();
2917 if (Object.keys(this.clusters).length !== before)
2918 { changed = true; }
2919
2920 // Rebuild every flying body so offsets stay integer and unique.
2921 var ids = Object.keys(this.clusters);
2922 for (var n = 0; n < ids.length; n++)
2923 {
2924 var cluster = this.clusters[ids[n]];
2925 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
2926 { continue; }
2927 this.prepareClusterBody(cluster);
2928 }
2929
2930 if (!changed)
2931 { break; }
2932 }
2933};
2934
2935/**
2936 * Invariant checker (t1112). No two blocks occupy the same cell or
2937 * overlap their [y, y+1) intervals. Flying-cluster members are
2938 * grid-aligned to a single anchor. Returns a list of violation
2939 * strings (empty if clean).
2940 */
2941GameCore.prototype.checkInvariants = function ()
2942{
2943 var issues = [];
2944 var byCol = Object.create(null);
2945 var ids = Object.create(null);
2946 for (var i = 0; i < this.blocks.length; i++)
2947 {
2948 var block = this.blocks[i];
2949 if (ids[block.id])
2950 { issues.push('duplicate id ' + block.id); }
2951 ids[block.id] = true;
2952 if (!byCol[block.col])
2953 { byCol[block.col] = []; }
2954 byCol[block.col].push(block);
2955 if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet
2956 && block.color >= this.planet.colors.length))
2957 { issues.push('block ' + block.id + ' has invalid color ' + block.color); }
2958 }
2959 var cols = Object.keys(byCol);
2960 for (var c = 0; c < cols.length; c++)
2961 {
2962 var list = byCol[cols[c]];
2963 list.sort(function (a, b)
2964 {
2965 if (a.y !== b.y)
2966 { return a.y - b.y; }
2967 return a.id - b.id;
2968 });
2969 for (var i = 0; i < list.length; i++)
2970 {
2971 var a = list[i];
2972 if (i > 0)
2973 {
2974 var prev = list[i - 1];
2975 if (a.y < prev.y + 1 - 1e-6)
2976 {
2977 issues.push('overlap col=' + a.col
2978 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)
2979 + ' gap=' + (a.y - prev.y));
2980 }
2981 var cellA = Math.floor(a.y + 1e-9);
2982 var cellP = Math.floor(prev.y + 1e-9);
2983 if (cellA === cellP)
2984 {
2985 issues.push('duplicate cell col=' + a.col + ' row=' + cellA
2986 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a));
2987 }
2988 }
2989 }
2990 }
2991 var cids = Object.keys(this.clusters);
2992 for (var n = 0; n < cids.length; n++)
2993 {
2994 var cluster = this.clusters[cids[n]];
2995 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
2996 { continue; }
2997 var mem = this.clusterMembers(cluster.id);
2998 var seenOff = Object.create(null);
2999 for (var i = 0; i < mem.length; i++)
3000 {
3001 var b = mem[i];
3002 if (cluster.anchorY != null && b.clusterOffset != null)
3003 {
3004 var expected = cluster.anchorY + b.clusterOffset;
3005 if (Math.abs(b.y - expected) > 1e-6)
3006 {
3007 issues.push('cluster ' + cluster.id + ' member ' + b.id
3008 + ' y=' + b.y + ' != anchor+off ' + expected);
3009 }
3010 if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9)
3011 {
3012 issues.push('cluster ' + cluster.id + ' member ' + b.id
3013 + ' non-integer offset ' + b.clusterOffset);
3014 }
3015 var key = b.col + ':' + b.clusterOffset;
3016 if (seenOff[key])
3017 {
3018 issues.push('cluster ' + cluster.id + ' duplicate offset ' + key);
3019 }
3020 seenOff[key] = true;
3021 }
3022 }
3023 }
3024 return issues;
3025};
3026
3027GameCore.prototype._invBlock = function (b)
3028{
3029 return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y='
3030 + (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')';
3031};
3032
3033GameCore.prototype.assertInvariants = function (label)
3034{
3035 if (!this.strictInvariants && !this.debugInvariants)
3036 { return; }
3037 var issues = this.checkInvariants();
3038 this.lastInvariantViolations = issues;
3039 if (!issues.length)
3040 { return; }
3041 var msg = 'physics invariants failed'
3042 + (label ? ' at ' + label : '')
3043 + ':\n ' + issues.join('\n ')
3044 + '\n' + (this.snapshot ? this.snapshot().picture : '');
3045 if (this.strictInvariants)
3046 { throw new Error(msg); }
3047};
3048
3049GameCore.prototype.tryLandCluster = function (cluster, members)
3050{
3051 if (!members.length)
3052 { return; }
3053 var shift = 0;
3054 var hit = false;
3055 for (var i = 0; i < members.length; i++)
3056 {
3057 var block = members[i];
3058 var top = this.stackTop(block.col, function (other)
3059 {
3060 return other.clusterId === cluster.id;
3061 }, block.y);
3062 if (block.y <= top + 1e-9)
3063 {
3064 hit = true;
3065 var need = top - block.y;
3066 if (need > shift)
3067 { shift = need; }
3068 }
3069 }
3070 if (!hit)
3071 { return; }
3072 // Lift the whole rigid body so the deepest contact sits flush.
3073 this.prepareClusterBody(cluster);
3074 cluster.anchorY += shift;
3075 this.syncClusterMembers(cluster);
3076 this.landCluster(cluster, this.clusterMembers(cluster.id));
3077};
3078
3079/**
3080 * Land as a rigid group: relative positions are kept, so part of the
3081 * cluster may hang above a gap. Grey members start the 3s settle timer;
3082 * coloured cargo stays put with them until every grey has recolored.
3083 * Members that actually rest on the floor or on another block bounce.
3084 */
3085GameCore.prototype.landCluster = function (cluster, members)
3086{
3087 for (var i = 0; i < members.length; i++)
3088 {
3089 var block = members[i];
3090 block.vy = 0;
3091 block.flame = false;
3092 block.clusterId = cluster.id;
3093 if (block.color === COLOR_GRAY)
3094 {
3095 block.state = STATE_SETTLING;
3096 block.settleTime = 0;
3097 }
3098 else
3099 {
3100 // Cargo stays in the rigid group (not matchable) until release.
3101 block.state = STATE_SETTLING;
3102 block.settleTime = 0;
3103 }
3104 if (this.hasSupport(block))
3105 { this.startBounce(block); }
3106 }
3107 cluster.phase = 'landed';
3108 cluster.vy = 0;
3109 cluster.landedPending = true;
3110 if (cluster.landingChain == null)
3111 { cluster.landingChain = 0; }
3112};
3113
3114/**
3115 * After every grey in a landed cluster has recolored, let the group go.
3116 * Unsupported blocks fall individually from rest; supported ones stay.
3117 */
3118GameCore.prototype.releaseLandedCluster = function (cluster)
3119{
3120 var members = this.clusterMembers(cluster.id);
3121 var releasing = Object.create(null);
3122 for (var i = 0; i < members.length; i++)
3123 { releasing[members[i].id] = true; }
3124
3125 for (var i = 0; i < members.length; i++)
3126 {
3127 var block = members[i];
3128 if (block.color === COLOR_GRAY)
3129 {
3130 block.color = this.randomColor();
3131 block.settleTime = 0;
3132 }
3133 // Persist the chain across release so a post-recolor match in
3134 // this same tick still gets the landing bonus (t1120).
3135 block.justLanded = !!cluster.landedPending;
3136 block.landingChain = cluster.landingChain || 0;
3137 this.leaveCluster(block);
3138 // Always drop leftover launch / manual velocity. A stale upward
3139 // vy here is what sends blocks off the top "very fast" after
3140 // a grey group recolors.
3141 this.clearFlightState(block);
3142 // Support from outside the group (floor or a foreign block). Fellow
3143 // members that will also fall do not count, so a hanging stack
3144 // drops together without the top one staying put.
3145 var supported = this.hasSupportOutside(block, releasing);
3146 block.state = supported ? STATE_STILL : STATE_FALLING;
3147 }
3148 delete this.clusters[cluster.id];
3149};
3150
3151GameCore.prototype.hasSupportOutside = function (block, ignoreIds)
3152{
3153 if (block.y <= 1e-9)
3154 { return true; }
3155 for (var i = 0; i < this.blocks.length; i++)
3156 {
3157 var other = this.blocks[i];
3158 if (other === block || other.col !== block.col)
3159 { continue; }
3160 if (ignoreIds && ignoreIds[other.id])
3161 { continue; }
3162 if (!this.isGrounded(other))
3163 { continue; }
3164 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
3165 { return true; }
3166 }
3167 return false;
3168};
3169
3170GameCore.prototype.integrateManual = function (dt)
3171{
3172 for (var i = 0; i < this.blocks.length; i++)
3173 {
3174 var block = this.blocks[i];
3175 if (block.state !== STATE_MANUAL)
3176 { continue; }
3177
3178 if (block.manualPhase === 'up')
3179 {
3180 var oldY = block.y;
3181 var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
3182 var dy = this.advanceJump(proxy, dt);
3183 var nextY = oldY + dy;
3184 block.vy = proxy.vy;
3185 block.manualPhase = proxy.phase;
3186 if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget)))
3187 { continue; }
3188 block.y = Math.min(nextY, block.manualTarget);
3189 if (block.y >= block.manualTarget - 1e-12)
3190 {
3191 block.y = block.manualTarget;
3192 block.vy = 0;
3193 block.manualPhase = 'down';
3194 }
3195 if (block.y > this.height - 1)
3196 {
3197 block.y = this.height - 1;
3198 block.vy = 0;
3199 block.manualPhase = 'down';
3200 }
3201 }
3202
3203 if (block.manualPhase === 'down')
3204 {
3205 var proxy = { phase: 'down', vy: block.vy, decel: 0 };
3206 var dy = this.advanceJump(proxy, dt);
3207 block.vy = proxy.vy;
3208 var nextY = block.y + dy;
3209 var top = this.stackTop(block.col, null, block.y);
3210 if (nextY <= top)
3211 {
3212 block.y = top;
3213 block.state = STATE_STILL;
3214 block.vy = 0;
3215 block.manualPhase = null;
3216 block.flame = false;
3217 this.startBounce(block);
3218 }
3219 else
3220 {
3221 var downNext = Math.min(nextY, this.height - 1);
3222 if (this.resolveManualCollisions(block, block.y, downNext))
3223 { continue; }
3224 block.y = downNext;
3225 }
3226 }
3227 }
3228};
3229
3230/**
3231 * If the manual throw (or its path this step) hits falling blocks, merge
3232 * them into a flying cluster with mass-weighted velocity, the same rule
3233 * as two flying clusters colliding (t1108). Returns true if merged.
3234 */
3235GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
3236{
3237 if (!manual || manual.state !== STATE_MANUAL)
3238 { return false; }
3239 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
3240 if (!hits.length)
3241 { return false; }
3242 this.mergeManualWithFalling(manual, hits);
3243 return true;
3244};
3245
3246GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
3247{
3248 var lo = Math.min(oldY, newY);
3249 var hi = Math.max(oldY, newY) + 1;
3250 for (var i = 0; i < this.blocks.length; i++)
3251 {
3252 var other = this.blocks[i];
3253 if (other === falling || other.col !== falling.col)
3254 { continue; }
3255 if (other.state !== STATE_MANUAL)
3256 { continue; }
3257 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
3258 { return other; }
3259 }
3260 return null;
3261};
3262
3263GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
3264{
3265 var lo = Math.min(oldY, newY);
3266 var hi = Math.max(oldY, newY) + 1;
3267 var hits = [];
3268 for (var i = 0; i < this.blocks.length; i++)
3269 {
3270 var other = this.blocks[i];
3271 if (other === manual || other.col !== manual.col)
3272 { continue; }
3273 if (other.state !== STATE_FALLING)
3274 { continue; }
3275 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
3276 { hits.push(other); }
3277 }
3278 if (!hits.length)
3279 { return hits; }
3280 return this.contiguousFallingInColumn(manual.col, manual, hits);
3281};
3282
3283/**
3284 * Every falling block in `col` that overlaps `anchor` or a hit already
3285 * in `seed`, plus a contiguous falling stack sitting on them.
3286 */
3287GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
3288{
3289 var falling = [];
3290 for (var i = 0; i < this.blocks.length; i++)
3291 {
3292 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
3293 { falling.push(this.blocks[i]); }
3294 }
3295 falling.sort(function (a, b) { return a.y - b.y; });
3296 var include = Object.create(null);
3297 var queue = [];
3298 function enqueue (b)
3299 {
3300 if (!b || include[b.id])
3301 { return; }
3302 include[b.id] = true;
3303 queue.push(b);
3304 }
3305 if (seed)
3306 {
3307 for (var s = 0; s < seed.length; s++)
3308 { enqueue(seed[s]); }
3309 }
3310 // Also include falling that already overlap the anchor.
3311 if (anchor)
3312 {
3313 for (var i = 0; i < falling.length; i++)
3314 {
3315 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
3316 { enqueue(falling[i]); }
3317 }
3318 }
3319 for (var q = 0; q < queue.length; q++)
3320 {
3321 var a = queue[q];
3322 for (var i = 0; i < falling.length; i++)
3323 {
3324 var b = falling[i];
3325 if (include[b.id])
3326 { continue; }
3327 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
3328 { enqueue(b); }
3329 }
3330 }
3331 var out = [];
3332 for (var i = 0; i < falling.length; i++)
3333 {
3334 if (include[falling[i].id])
3335 { out.push(falling[i]); }
3336 }
3337 return out;
3338};
3339
3340/**
3341 * Merge a thrown (manual) block with falling blocks into one flying
3342 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
3343 * averages by block count, identical to mergeClusterGroup. The thrown
3344 * block stops being manual and the group follows normal cluster physics.
3345 * fromManual marks the cluster so later falling cargo also averages in.
3346 */
3347GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
3348{
3349 if (!manual || manual.state !== STATE_MANUAL)
3350 { return null; }
3351 var blocks = [manual];
3352 for (var i = 0; i < fallingList.length; i++)
3353 {
3354 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
3355 { blocks.push(fallingList[i]); }
3356 }
3357 if (blocks.length < 2)
3358 { return null; }
3359 var n = blocks.length;
3360 var vySum = 0;
3361 var decelSum = 0;
3362 var hSum = 0;
3363 for (var i = 0; i < n; i++)
3364 {
3365 var b = blocks[i];
3366 vySum += b.vy;
3367 if (b === manual)
3368 {
3369 decelSum += manual.manualDecel || 0;
3370 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
3371 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
3372 }
3373 }
3374 var cluster = {
3375 id: this.nextClusterId++,
3376 jumpHeight: hSum / n,
3377 vy: vySum / n,
3378 decel: decelSum / n,
3379 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
3380 fromManual: true
3381 };
3382 this.clusters[cluster.id] = cluster;
3383 for (var i = 0; i < n; i++)
3384 {
3385 var b = blocks[i];
3386 b.clusterId = cluster.id;
3387 b.state = STATE_FLYING;
3388 b.vy = cluster.vy;
3389 b.flame = b.color === COLOR_GRAY;
3390 b.manualPhase = null;
3391 b.manualTarget = null;
3392 b.manualDecel = 0;
3393 b.manualJumpHeight = 0;
3394 b.pushedClusters = null;
3395 b.settleTime = 0;
3396 }
3397 if (this.drag && this.drag.blockId === manual.id)
3398 { this.drag = null; }
3399 this.prepareClusterBody(cluster);
3400 this.checkChainRelaunch(cluster);
3401 return cluster;
3402};
3403
3404/** Safety net: any remaining manual/falling overlaps after the substep. */
3405GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
3406{
3407 var manuals = [];
3408 for (var i = 0; i < this.blocks.length; i++)
3409 {
3410 if (this.blocks[i].state === STATE_MANUAL)
3411 { manuals.push(this.blocks[i]); }
3412 }
3413 for (var m = 0; m < manuals.length; m++)
3414 {
3415 var manual = manuals[m];
3416 if (manual.state !== STATE_MANUAL)
3417 { continue; }
3418 var hits = this.contiguousFallingInColumn(manual.col, manual);
3419 if (hits.length)
3420 { this.mergeManualWithFalling(manual, hits); }
3421 }
3422};
3423
3424/**
3425 * Resolve collisions of a thrown (manual) block along [oldY, nextY].
3426 * Falling blocks merge (t1108). A flying cluster is pushed one cell up
3427 * in the hit column and the shot attaches at the bottom (t1111).
3428 * Another thrown block is promoted to a 1-block cluster and then the
3429 * same attach-at-bottom rule applies. Returns true if `manual` is no
3430 * longer in the MANUAL state.
3431 */
3432GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY)
3433{
3434 if (!manual || manual.state !== STATE_MANUAL)
3435 { return true; }
3436
3437 var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY);
3438 if (fallingHits.length)
3439 {
3440 this.mergeManualWithFalling(manual, fallingHits);
3441 return manual.state !== STATE_MANUAL;
3442 }
3443
3444 var flyer = this.flyingHitOnManualPath(manual, oldY, nextY);
3445 if (flyer)
3446 {
3447 var cluster = this.clusters[flyer.clusterId];
3448 if (cluster && cluster.phase !== 'landed')
3449 {
3450 if (nextY + 1e-12 < oldY)
3451 { this.attachToFlyingCluster(manual, flyer); }
3452 else
3453 { this.attachShotUnderCluster(manual, cluster, manual.col); }
3454 return manual.state !== STATE_MANUAL;
3455 }
3456 }
3457
3458 var other = this.manualHitOnManualPath(manual, oldY, nextY);
3459 if (other)
3460 {
3461 var host = this.promoteManualToCluster(other);
3462 if (host)
3463 {
3464 if (nextY + 1e-12 < oldY)
3465 { this.attachToFlyingCluster(manual, other); }
3466 else
3467 { this.attachShotUnderCluster(manual, host, manual.col); }
3468 return manual.state !== STATE_MANUAL;
3469 }
3470 }
3471 return false;
3472};
3473
3474/** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */
3475GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY)
3476{
3477 var lo = Math.min(oldY, nextY);
3478 var hi = Math.max(oldY, nextY) + 1;
3479 var best = null;
3480 var bestY = Infinity;
3481 for (var i = 0; i < this.blocks.length; i++)
3482 {
3483 var other = this.blocks[i];
3484 if (other === manual || other.col !== manual.col)
3485 { continue; }
3486 if (other.state !== STATE_FLYING || other.clusterId == null)
3487 { continue; }
3488 var cluster = this.clusters[other.clusterId];
3489 if (!cluster || cluster.phase === 'landed')
3490 { continue; }
3491 var o0 = (other._prevY != null) ? other._prevY : other.y;
3492 var o1 = other.y;
3493 var oLo = Math.min(o0, o1);
3494 var oHi = Math.max(o0, o1) + 1;
3495 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
3496 {
3497 if (other.y < bestY)
3498 {
3499 bestY = other.y;
3500 best = other;
3501 }
3502 }
3503 }
3504 return best;
3505};
3506
3507/** Another thrown block in the same column on the path (prefer the lower). */
3508GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY)
3509{
3510 var lo = Math.min(oldY, nextY);
3511 var hi = Math.max(oldY, nextY) + 1;
3512 var best = null;
3513 for (var i = 0; i < this.blocks.length; i++)
3514 {
3515 var other = this.blocks[i];
3516 if (other === manual || other.col !== manual.col)
3517 { continue; }
3518 if (other.state !== STATE_MANUAL)
3519 { continue; }
3520 var o0 = (other._prevY != null) ? other._prevY : other.y;
3521 var o1 = other.y;
3522 var oLo = Math.min(o0, o1);
3523 var oHi = Math.max(o0, o1) + 1;
3524 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
3525 {
3526 if (!best || other.y < best.y)
3527 { best = other; }
3528 }
3529 }
3530 return best;
3531};
3532
3533/**
3534 * t1111: push every member of `cluster` in `col` up by one cell, then
3535 * attach `manual` at the bottom of that column, grid-aligned, as part
3536 * of the cluster. The cluster keeps its velocity; the shot takes it.
3537 * Other columns are untouched. Same rule for every successive shot.
3538 */
3539GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col)
3540{
3541 if (!manual || !cluster || !this.clusters[cluster.id])
3542 { return false; }
3543 if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id)
3544 {
3545 // Already belonging elsewhere: leave first.
3546 if (manual.clusterId != null)
3547 { this.leaveCluster(manual); }
3548 }
3549 this.prepareClusterBody(cluster);
3550 var members = this.clusterMembers(cluster.id);
3551 var minOff = null;
3552 for (var i = 0; i < members.length; i++)
3553 {
3554 if (members[i].col !== col)
3555 { continue; }
3556 if (minOff == null || members[i].clusterOffset < minOff)
3557 { minOff = members[i].clusterOffset; }
3558 }
3559 if (minOff == null)
3560 { minOff = 0; }
3561 else
3562 {
3563 for (var i = 0; i < members.length; i++)
3564 {
3565 if (members[i].col === col)
3566 { members[i].clusterOffset += 1; }
3567 }
3568 }
3569 if (this.drag && this.drag.blockId === manual.id)
3570 { this.drag = null; }
3571 manual.clusterId = cluster.id;
3572 manual.clusterOffset = minOff;
3573 manual.state = STATE_FLYING;
3574 manual.flame = manual.color === COLOR_GRAY;
3575 manual.settleTime = 0;
3576 manual.manualPhase = null;
3577 manual.manualTarget = null;
3578 manual.manualDecel = 0;
3579 manual.manualJumpHeight = 0;
3580 manual.pushedClusters = null;
3581 this.syncClusterMembers(cluster);
3582 this.cullOffTop();
3583 if (this.clusters[cluster.id])
3584 { this.checkChainRelaunch(cluster); }
3585 return true;
3586};
3587
3588/**
3589 * Turn a lone thrown block into a 1-block flying cluster so a later
3590 * shot can use the t1111 attach-at-bottom rule. A single throw stays
3591 * MANUAL (and is capped at the top of the field) until it collides.
3592 */
3593GameCore.prototype.promoteManualToCluster = function (manual)
3594{
3595 if (!manual)
3596 { return null; }
3597 if (manual.state === STATE_FLYING && manual.clusterId != null)
3598 {
3599 var existing = this.clusters[manual.clusterId];
3600 if (existing && existing.phase !== 'landed')
3601 { return existing; }
3602 }
3603 if (manual.state !== STATE_MANUAL)
3604 { return null; }
3605 var height = manual.manualJumpHeight != null ? manual.manualJumpHeight
3606 : Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y);
3607 var cluster = {
3608 id: this.nextClusterId++,
3609 jumpHeight: height,
3610 vy: manual.vy,
3611 decel: manual.manualDecel || 0,
3612 phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up',
3613 fromManual: true,
3614 anchorY: manual.y
3615 };
3616 this.clusters[cluster.id] = cluster;
3617 manual.state = STATE_FLYING;
3618 manual.clusterId = cluster.id;
3619 manual.clusterOffset = 0;
3620 manual.flame = manual.color === COLOR_GRAY;
3621 manual.settleTime = 0;
3622 manual.manualPhase = null;
3623 manual.manualTarget = null;
3624 manual.manualDecel = 0;
3625 manual.manualJumpHeight = 0;
3626 manual.pushedClusters = null;
3627 this.syncClusterMembers(cluster);
3628 return cluster;
3629};
3630
3631/** Kept for older tests / call sites: push a cluster column by one cell. */
3632GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
3633{
3634 return this.resolveManualCollisions(manual, oldY, nextY);
3635};
3636
3637
3638/**
3639 * Push every flying block of the cluster that sits in `col` one tile up.
3640 * Other columns stay put (they remain linked). Then look for a new
3641 * same-color line of 3+ in the flying cluster; if there is one, those
3642 * blocks turn gray, join the link, and the whole cluster re-launches
3643 * with the same jump height from its current position.
3644 */
3645GameCore.prototype.pushClusterColumn = function (clusterId, col)
3646{
3647 var cluster = this.clusters[clusterId];
3648 if (!cluster)
3649 { return false; }
3650 var members = this.clusterMembers(clusterId);
3651 for (var i = 0; i < members.length; i++)
3652 {
3653 if (members[i].col === col)
3654 { members[i].y += 1; }
3655 }
3656 this.cullOffTop();
3657 if (!this.clusters[clusterId])
3658 { return true; }
3659 this.checkChainRelaunch(cluster);
3660 return true;
3661};
3662
3663/**
3664 * After a cargo attach or a cluster merge (or any other mid-air state
3665 * change), turn spontaneous lines of 3+ into rockets and give the whole
3666 * already-flying cluster an extra launch from its current position —
3667 * the same re-launch as a player push that completes a row.
3668 */
3669GameCore.prototype.resolveFlyingMatches = function ()
3670{
3671 var ids = Object.keys(this.clusters);
3672 for (var n = 0; n < ids.length; n++)
3673 {
3674 var cluster = this.clusters[ids[n]];
3675 if (!cluster || cluster.phase === 'landed')
3676 { continue; }
3677 this.checkChainRelaunch(cluster);
3678 }
3679};
3680
3681GameCore.prototype.checkChainRelaunch = function (cluster)
3682{
3683 if (!this.clusters[cluster.id])
3684 { return; }
3685 var lines = this.findFlyingMatchLines(cluster.id);
3686 if (!lines.length)
3687 { return; }
3688 var newly = [];
3689 var seen = Object.create(null);
3690 for (var i = 0; i < lines.length; i++)
3691 {
3692 for (var j = 0; j < lines[i].blocks.length; j++)
3693 {
3694 var block = lines[i].blocks[j];
3695 if (seen[block.id])
3696 { continue; }
3697 seen[block.id] = true;
3698 newly.push(block);
3699 }
3700 }
3701 for (var i = 0; i < newly.length; i++)
3702 {
3703 var block = newly[i];
3704 block.color = COLOR_GRAY;
3705 block.flame = true;
3706 block.clusterId = cluster.id;
3707 block.state = STATE_FLYING;
3708 }
3709 this.relaunchCluster(cluster, cluster.jumpHeight);
3710};
3711
3712GameCore.prototype.relaunchCluster = function (cluster, height)
3713{
3714 cluster.jumpHeight = height;
3715 cluster.vy = PlanetMod.launchVelocity(this.planet, height);
3716 cluster.decel = PlanetMod.launchDeceleration(this.planet, height);
3717 cluster.phase = 'up';
3718 var members = this.clusterMembers(cluster.id);
3719 for (var i = 0; i < members.length; i++)
3720 {
3721 members[i].vy = cluster.vy;
3722 members[i].state = STATE_FLYING;
3723 if (members[i].color === COLOR_GRAY)
3724 { members[i].flame = true; }
3725 }
3726};
3727
3728GameCore.prototype.startManualLaunch = function (block)
3729{
3730 var target = this.height - 1;
3731 var height = Math.max(0.05, target - block.y);
3732 this.leaveCluster(block);
3733 block.state = STATE_MANUAL;
3734 block.pushedClusters = Object.create(null);
3735 block.manualTarget = target;
3736 block.manualPhase = 'up';
3737 block.manualJumpHeight = height;
3738 block.vy = PlanetMod.launchVelocity(this.planet, height);
3739 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
3740 block.flame = false;
3741 if (this.drag && this.drag.blockId === block.id)
3742 { this.drag = null; }
3743};
3744
3745GameCore.prototype.cullOffTop = function ()
3746{
3747 var gone = [];
3748 for (var i = 0; i < this.blocks.length; i++)
3749 {
3750 var block = this.blocks[i];
3751 if (block.state === STATE_MANUAL)
3752 {
3753 if (block.y > this.height - 1)
3754 { block.y = this.height - 1; }
3755 continue;
3756 }
3757 if (block.y >= this.height - 1e-9)
3758 { gone.push(block); }
3759 }
3760 for (var i = 0; i < gone.length; i++)
3761 {
3762 var block = gone[i];
3763 this.outgoingShots.push({
3764 id: block.id,
3765 color: block.color,
3766 col: block.col,
3767 y: block.y,
3768 vy: block.vy
3769 });
3770 this.score += 1;
3771 this.removeBlock(block);
3772 }
3773};
3774
3775GameCore.prototype.consumeOutgoingShots = function ()
3776{
3777 var shots = this.outgoingShots;
3778 this.outgoingShots = [];
3779 return shots;
3780};
3781
3782/**
3783 * A compact field picture for the multiplayer snapshot (miniatures).
3784 * Includes every block's col, y, color, state and flame.
3785 */
3786GameCore.prototype.fieldSnapshot = function ()
3787{
3788 var blocks = [];
3789 for (var i = 0; i < this.blocks.length; i++)
3790 {
3791 var b = this.blocks[i];
3792 blocks.push({
3793 id: b.id,
3794 col: b.col,
3795 y: Math.round(b.y * 1000) / 1000,
3796 color: b.color,
3797 state: b.state,
3798 flame: !!b.flame
3799 });
3800 }
3801 return {
3802 score: this.score,
3803 state: this.state,
3804 width: this.width,
3805 height: this.height,
3806 locked: this.lockedColumnCount(),
3807 blocks: blocks
3808 };
3809};
3810
3811/**
3812 * Incoming garbage from another player: a dark-grey block that falls
3813 * normally from the top of an open column. After landing it uses the
3814 * usual 3s settle and then a random colour (landFallingBlock).
3815 * `col` is optional; a random eligible column is used otherwise.
3816 * Returns the new block, or null if every column is locked or full.
3817 */
3818/**
3819 * Open columns a garbage block can fall into (not locked, not full).
3820 */
3821GameCore.prototype.eligibleGarbageColumns = function ()
3822{
3823 var eligible = [];
3824 for (var c = 0; c < this.width; c++)
3825 {
3826 if (this.isColumnLocked(c))
3827 { continue; }
3828 if (this.groundedCount(c) >= this.height)
3829 { continue; }
3830 eligible.push(c);
3831 }
3832 return eligible;
3833};
3834
3835/**
3836 * Choose a garbage column. If `preferred` is still open, it wins;
3837 * otherwise a random eligible column (t1126). Returns null if none.
3838 */
3839GameCore.prototype.pickGarbageColumn = function (preferred)
3840{
3841 var eligible = this.eligibleGarbageColumns();
3842 if (!eligible.length)
3843 { return null; }
3844 if (preferred != null && isFinite(preferred))
3845 {
3846 var want = preferred | 0;
3847 for (var i = 0; i < eligible.length; i++)
3848 {
3849 if (eligible[i] === want)
3850 { return want; }
3851 }
3852 }
3853 return eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
3854};
3855
3856GameCore.prototype.ingestGarbage = function (col)
3857{
3858 if (this.state !== 'playing')
3859 { return null; }
3860 var chosen = this.pickGarbageColumn(col);
3861 if (chosen == null)
3862 { return null; }
3863 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
3864 block.vy = -this.planet.fallSpeed;
3865 block.flame = false;
3866 return block;
3867};
3868
3869GameCore.prototype.advanceSettle = function (dt)
3870{
3871 for (var i = 0; i < this.blocks.length; i++)
3872 {
3873 var block = this.blocks[i];
3874 if (block.state !== STATE_SETTLING)
3875 { continue; }
3876 var inLanded = block.clusterId != null
3877 && this.clusters[block.clusterId]
3878 && this.clusters[block.clusterId].phase === 'landed';
3879 if (block.color === COLOR_GRAY)
3880 {
3881 block.settleTime += dt;
3882 if (block.settleTime >= this.settleTime)
3883 {
3884 block.color = this.randomColor();
3885 block.settleTime = 0;
3886 block.flame = false;
3887 if (inLanded)
3888 {
3889 // Stay in the rigid group; releaseLandedCluster runs below.
3890 block.state = STATE_SETTLING;
3891 }
3892 else
3893 {
3894 this.leaveCluster(block);
3895 this.clearFlightState(block);
3896 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
3897 }
3898 }
3899 }
3900 else if (!inLanded)
3901 {
3902 // Coloured settling that is not in a landed cluster (shouldn't
3903 // normally happen): just become still or fall, from rest.
3904 this.leaveCluster(block);
3905 this.clearFlightState(block);
3906 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
3907 }
3908 }
3909
3910 var ids = Object.keys(this.clusters);
3911 for (var n = 0; n < ids.length; n++)
3912 {
3913 var cluster = this.clusters[ids[n]];
3914 if (!cluster || cluster.phase !== 'landed')
3915 { continue; }
3916 var members = this.clusterMembers(cluster.id);
3917 var greySettling = false;
3918 for (var i = 0; i < members.length; i++)
3919 {
3920 if (members[i].color === COLOR_GRAY && members[i].state === STATE_SETTLING)
3921 { greySettling = true; }
3922 }
3923 if (!greySettling)
3924 { this.releaseLandedCluster(cluster); }
3925 }
3926};
3927
3928GameCore.prototype.findMatchLines = function ()
3929{
3930 var candidates = [];
3931 for (var i = 0; i < this.blocks.length; i++)
3932 {
3933 var block = this.blocks[i];
3934 // Coloured cargo in a just-landed cluster (SETTLING) can match
3935 // with already-resting blocks immediately (t1110). Greys have no
3936 // colour and wait until they recolor; after release they are STILL.
3937 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
3938 && block.color >= 0)
3939 { candidates.push(block); }
3940 }
3941 return this.collectLines(candidates, true);
3942};
3943
3944GameCore.prototype.findFlyingMatchLines = function (clusterId)
3945{
3946 var candidates = [];
3947 for (var i = 0; i < this.blocks.length; i++)
3948 {
3949 var block = this.blocks[i];
3950 if (block.clusterId === clusterId && block.color >= 0
3951 && (block.state === STATE_FLYING))
3952 { candidates.push(block); }
3953 }
3954 return this.collectLines(candidates, false);
3955};
3956
3957GameCore.prototype.collectLines = function (candidates, snapInteger)
3958{
3959 var lines = [];
3960 if (!candidates.length)
3961 { return lines; }
3962
3963 var byRow = Object.create(null);
3964 for (var i = 0; i < candidates.length; i++)
3965 {
3966 var block = candidates[i];
3967 var row = Math.round(block.y);
3968 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
3969 { continue; }
3970 if (!byRow[row])
3971 { byRow[row] = []; }
3972 byRow[row].push(block);
3973 }
3974 var rows = Object.keys(byRow);
3975 for (var r = 0; r < rows.length; r++)
3976 {
3977 var list = byRow[rows[r]];
3978 list.sort(function (a, b) { return a.col - b.col; });
3979 this.pushRuns(lines, list, false, function (a, b)
3980 {
3981 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
3982 });
3983 }
3984
3985 var byCol = Object.create(null);
3986 for (var i = 0; i < candidates.length; i++)
3987 {
3988 var block = candidates[i];
3989 if (!byCol[block.col])
3990 { byCol[block.col] = []; }
3991 byCol[block.col].push(block);
3992 }
3993 var cols = Object.keys(byCol);
3994 for (var c = 0; c < cols.length; c++)
3995 {
3996 var list = byCol[cols[c]];
3997 list.sort(function (a, b) { return a.y - b.y; });
3998 this.pushRuns(lines, list, true, function (a, b)
3999 {
4000 return a.color === b.color && a.color >= 0
4001 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
4002 });
4003 }
4004 return lines;
4005};
4006
4007GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
4008{
4009 var start = 0;
4010 for (var i = 1; i <= list.length; i++)
4011 {
4012 var same = i < list.length && adjacent(list[i - 1], list[i]);
4013 if (!same)
4014 {
4015 var length = i - start;
4016 if (length >= 3)
4017 {
4018 lines.push({
4019 blocks: list.slice(start, i),
4020 length: length,
4021 vertical: vertical
4022 });
4023 }
4024 start = i;
4025 }
4026 }
4027};
4028
4029GameCore.prototype.resolveMatches = function ()
4030{
4031 if (this.state !== 'playing' || this.drag)
4032 { return []; }
4033 var lines = this.findMatchLines();
4034 if (!lines.length)
4035 {
4036 this.finishLandingChains([]);
4037 return [];
4038 }
4039
4040 var uf = new UnionFind();
4041 var blockById = Object.create(null);
4042 for (var i = 0; i < lines.length; i++)
4043 {
4044 var line = lines[i];
4045 for (var j = 0; j < line.blocks.length; j++)
4046 {
4047 uf.add(line.blocks[j].id);
4048 blockById[line.blocks[j].id] = line.blocks[j];
4049 if (j > 0)
4050 { uf.union(line.blocks[0].id, line.blocks[j].id); }
4051 }
4052 }
4053 var matched = [];
4054 var seen = Object.create(null);
4055 for (var id in blockById)
4056 {
4057 if (!seen[id])
4058 {
4059 seen[id] = true;
4060 matched.push(blockById[id]);
4061 }
4062 }
4063 for (var i = 0; i < matched.length; i++)
4064 {
4065 for (var j = i + 1; j < matched.length; j++)
4066 {
4067 if (matched[i].col === matched[j].col)
4068 { uf.union(matched[i].id, matched[j].id); }
4069 }
4070 }
4071
4072 var groups = Object.create(null);
4073 for (var i = 0; i < matched.length; i++)
4074 {
4075 var root = uf.find(matched[i].id);
4076 if (!groups[root])
4077 { groups[root] = []; }
4078 groups[root].push(matched[i]);
4079 }
4080
4081 var launched = [];
4082 for (var root in groups)
4083 {
4084 var group = groups[root];
4085 var height = 0;
4086 for (var i = 0; i < lines.length; i++)
4087 {
4088 var line = lines[i];
4089 var overlaps = false;
4090 for (var j = 0; j < line.blocks.length; j++)
4091 {
4092 for (var k = 0; k < group.length; k++)
4093 {
4094 if (line.blocks[j].id === group[k].id)
4095 { overlaps = true; }
4096 }
4097 }
4098 if (overlaps)
4099 {
4100 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
4101 if (h > height)
4102 { height = h; }
4103 }
4104 }
4105 var chain = this.landingChainFor(group);
4106 var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;
4107 height *= bonusMul;
4108 this.launchCluster(group, height, { landingChain: chain });
4109 launched.push({
4110 blocks: group,
4111 jumpHeight: height,
4112 landingChain: chain,
4113 chainBonus: bonusMul
4114 });
4115 }
4116 this.finishLandingChains(launched);
4117 this.updateChainIndicator(launched);
4118 return launched;
4119};
4120
4121/**
4122 * Gray the matched blocks, take everything sitting on top of them in
4123 * those columns, link them, and launch with jump height `height`.
4124 */
4125GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)
4126{
4127 opts = opts || {};
4128 var lowestInCol = Object.create(null);
4129 var matchedIds = Object.create(null);
4130 for (var i = 0; i < matchedBlocks.length; i++)
4131 {
4132 var block = matchedBlocks[i];
4133 matchedIds[block.id] = true;
4134 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
4135 { lowestInCol[block.col] = block.y; }
4136 }
4137
4138 var clusterId = this.nextClusterId++;
4139 var cluster = {
4140 id: clusterId,
4141 jumpHeight: height,
4142 vy: PlanetMod.launchVelocity(this.planet, height),
4143 decel: PlanetMod.launchDeceleration(this.planet, height),
4144 phase: 'up',
4145 landingChain: opts.landingChain || 0,
4146 landedPending: false
4147 };
4148 this.clusters[clusterId] = cluster;
4149
4150 var riders = [];
4151 var cols = Object.keys(lowestInCol);
4152 for (var c = 0; c < cols.length; c++)
4153 {
4154 var col = +cols[c];
4155 var lowest = lowestInCol[col];
4156 var list = this.blocksInColumn(col);
4157 for (var i = 0; i < list.length; i++)
4158 {
4159 var block = list[i];
4160 if (!this.isGrounded(block) && block.state !== STATE_STILL)
4161 {
4162 if (block.state !== STATE_SETTLING)
4163 { continue; }
4164 }
4165 if (block.y + ALIGN_EPS >= lowest)
4166 { riders.push(block); }
4167 }
4168 }
4169
4170 for (var i = 0; i < riders.length; i++)
4171 {
4172 var block = riders[i];
4173 var isMatch = !!matchedIds[block.id];
4174 if (isMatch || block.color === COLOR_GRAY)
4175 {
4176 block.color = COLOR_GRAY;
4177 block.flame = true;
4178 }
4179 else
4180 { block.flame = false; }
4181 block.state = STATE_FLYING;
4182 block.clusterId = clusterId;
4183 block.vy = cluster.vy;
4184 block.settleTime = 0;
4185 }
4186 this.prepareClusterBody(cluster);
4187 return cluster;
4188};
4189
4190GameCore.prototype.checkLocks = function ()
4191{
4192 for (var col = 0; col < this.width; col++)
4193 {
4194 if (this.isColumnLocked(col))
4195 { continue; }
4196 if (this.groundedCount(col) < this.height)
4197 { continue; }
4198 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
4199 var filled = true;
4200 for (var row = 0; row < this.height; row++)
4201 {
4202 var block = this.blockAt(col, row);
4203 if (!block || !this.isGrounded(block))
4204 {
4205 filled = false;
4206 break;
4207 }
4208 }
4209 if (!filled)
4210 { continue; }
4211 var list = this.blocksInColumn(col);
4212 for (var i = 0; i < list.length; i++)
4213 {
4214 var block = list[i];
4215 if (!this.isGrounded(block))
4216 { continue; }
4217 block.state = STATE_LOCKED;
4218 block.color = COLOR_GRAY;
4219 block.flame = false;
4220 block.vy = 0;
4221 block.settleTime = 0;
4222 if (block.clusterId != null)
4223 { this.leaveCluster(block); }
4224 }
4225 }
4226};
4227
4228GameCore.prototype.checkGameOver = function ()
4229{
4230 if (this.state !== 'playing')
4231 { return; }
4232 for (var col = 0; col < this.width; col++)
4233 {
4234 if (!this.isColumnLocked(col))
4235 { return; }
4236 }
4237 this.state = 'gameover';
4238 this.gameOverTime = 0;
4239 this.drag = null;
4240};
4241
4242/* ---------- dragging -------------------------------------------------- */
4243
4244GameCore.prototype.beginDrag = function (col, y)
4245{
4246 if (this.state !== 'playing')
4247 { return false; }
4248 var block = this.snapDragBlock(col, y);
4249 if (!block)
4250 { return false; }
4251 var top = this.columnStackTopRow(block.col);
4252 var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
4253 this.drag = {
4254 blockId: block.id,
4255 pointerY: y,
4256 startY: y,
4257 accum: 0,
4258 launchIntent: false,
4259 startedAsTop: startedAsTop
4260 };
4261 return true;
4262};
4263
4264/**
4265 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
4266 * floor(col), floor(y); any press inside that cell — corners, padding,
4267 * gaps between sprites, a visually tweened or bouncing sprite — grabs
4268 * the block that occupies it. This uses simulation cells, not the drawn
4269 * sprite bounds. If no block sits in that cell (mid-animation, a block
4270 * whose y is off the integer), fall back to the nearest grabbable block
4271 * in the same column within SNAP_Y (about half a tile). A small
4272 * horizontal slop still consults a neighbouring column when the press
4273 * is near the edge and the primary cell is empty.
4274 */
4275GameCore.prototype.snapDragBlock = function (col, y)
4276{
4277 var raw = col;
4278 var c0 = Math.floor(raw + 1e-9);
4279 var row = Math.floor(y + 1e-9);
4280 var frac = raw - c0;
4281
4282 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
4283 {
4284 var exact = this.draggableInCell(c0, row);
4285 if (exact)
4286 { return exact; }
4287 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
4288 if (near)
4289 { return near; }
4290 }
4291
4292 // Primary cell empty: allow a small horizontal slop into a neighbour.
4293 var neighbours = [];
4294 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
4295 { neighbours.push(c0 - 1); }
4296 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
4297 { neighbours.push(c0 + 1); }
4298 var best = null;
4299 var bestDist = Infinity;
4300 for (var n = 0; n < neighbours.length; n++)
4301 {
4302 var cc = neighbours[n];
4303 if (!this.columnAllowsDrag(cc))
4304 { continue; }
4305 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
4306 if (!hit)
4307 { continue; }
4308 var dist = this.pointerDistToBlock(hit, raw, y);
4309 if (dist < bestDist)
4310 {
4311 bestDist = dist;
4312 best = hit;
4313 }
4314 }
4315 return best;
4316};
4317
4318/** The draggable block that occupies grid cell (col, row), if any. */
4319GameCore.prototype.draggableInCell = function (col, row)
4320{
4321 var best = null;
4322 var bestOverlap = 0;
4323 var list = this.blocksInColumn(col);
4324 for (var i = 0; i < list.length; i++)
4325 {
4326 var block = list[i];
4327 if (!this.isDraggableBlock(block))
4328 { continue; }
4329 var lo = Math.max(block.y, row);
4330 var hi = Math.min(block.y + 1, row + 1);
4331 var overlap = hi - lo;
4332 if (overlap > bestOverlap + 1e-12)
4333 {
4334 bestOverlap = overlap;
4335 best = block;
4336 }
4337 }
4338 if (best && bestOverlap > 1e-9)
4339 { return best; }
4340 return null;
4341};
4342
4343/** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
4344GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
4345{
4346 var best = null;
4347 var bestDist = Infinity;
4348 var list = this.blocksInColumn(col);
4349 for (var i = 0; i < list.length; i++)
4350 {
4351 var block = list[i];
4352 if (!this.isDraggableBlock(block))
4353 { continue; }
4354 var dist = this.pointerDistToBlock(block, col + 0.5, y);
4355 if (dist < bestDist)
4356 {
4357 bestDist = dist;
4358 best = block;
4359 }
4360 }
4361 if (!best || bestDist > maxDist)
4362 { return null; }
4363 return best;
4364};
4365
4366GameCore.prototype.pointerDistToBlock = function (block, col, y)
4367{
4368 var dx;
4369 if (col >= block.col && col < block.col + 1)
4370 { dx = 0; }
4371 else if (col < block.col)
4372 { dx = block.col - col; }
4373 else
4374 { dx = col - (block.col + 1); }
4375 var dy;
4376 if (y >= block.y && y < block.y + 1)
4377 { dy = 0; }
4378 else if (y < block.y)
4379 { dy = block.y - y; }
4380 else
4381 { dy = y - (block.y + 1); }
4382 return Math.sqrt(dx * dx + dy * dy);
4383};
4384
4385GameCore.prototype.moveDrag = function (y)
4386{
4387 if (!this.drag)
4388 { return; }
4389 var block = this.blockById(this.drag.blockId);
4390 if (!block || !this.isDraggableBlock(block))
4391 {
4392 this.drag = null;
4393 return;
4394 }
4395 if (!this.columnAllowsDrag(block.col))
4396 {
4397 this.drag = null;
4398 return;
4399 }
4400 this.drag.pointerY = y;
4401 // 1:1 tracking: the target row is the one under the pointer, clamped
4402 // to the still stack. Swap step by step with each neighbour, and stop
4403 // exactly there. When the pointer stops, nothing else moves.
4404 // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
4405 // used to jump a full cell on a short pull, and one large event
4406 // could walk the entire column (the "jumps all the way" bug).
4407 var top = this.columnStackTopRow(block.col);
4408 var bottom = this.columnStackBottomRow(block.col);
4409 var target = Math.floor(y + 1e-12);
4410 if (bottom < 0)
4411 { bottom = 0; }
4412 if (target < bottom)
4413 { target = bottom; }
4414 if (target > top)
4415 { target = top; }
4416 this.swapToward(block, target);
4417
4418 top = this.columnStackTopRow(block.col);
4419 var isTop = Math.abs(block.y - top) < ALIGN_EPS;
4420 if (this.drag.startedAsTop)
4421 {
4422 // Already the topmost block: pulling upward past its own position
4423 // (LAUNCH_PULL tiles above the press point) starts a manual jump.
4424 this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL);
4425 }
4426 else
4427 {
4428 // Started mid-stack: swap first, and only launch once the pointer
4429 // is pulled into the empty space above the (new) top.
4430 this.drag.launchIntent = isTop && (y > top + 1 + 0.25);
4431 }
4432};
4433
4434/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
4435GameCore.prototype.swapOne = function (block, dir)
4436{
4437 var neighbor = this.blockAt(block.col, block.y + dir);
4438 if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
4439 {
4440 this.swapBlocks(block, neighbor);
4441 return true;
4442 }
4443 return false;
4444};
4445
4446GameCore.prototype.endDrag = function ()
4447{
4448 if (!this.drag)
4449 { return; }
4450 var block = this.blockById(this.drag.blockId);
4451 var launch = this.drag.launchIntent;
4452 this.drag = null;
4453 if (launch && block && block.state === STATE_STILL)
4454 { this.startManualLaunch(block); }
4455 else
4456 { this.resolveMatches(); }
4457};
4458
4459GameCore.prototype.blockById = function (id)
4460{
4461 for (var i = 0; i < this.blocks.length; i++)
4462 {
4463 if (this.blocks[i].id === id)
4464 { return this.blocks[i]; }
4465 }
4466 return null;
4467};
4468
4469GameCore.prototype.columnStackTopRow = function (col)
4470{
4471 var top = -1;
4472 var list = this.blocksInColumn(col);
4473 for (var i = 0; i < list.length; i++)
4474 {
4475 if (this.isGrounded(list[i]) && list[i].y > top)
4476 { top = list[i].y; }
4477 }
4478 return top;
4479};
4480
4481GameCore.prototype.columnStackBottomRow = function (col)
4482{
4483 var bottom = Infinity;
4484 var list = this.blocksInColumn(col);
4485 for (var i = 0; i < list.length; i++)
4486 {
4487 if (this.isGrounded(list[i]) && list[i].y < bottom)
4488 { bottom = list[i].y; }
4489 }
4490 return bottom === Infinity ? 0 : bottom;
4491};
4492
4493GameCore.prototype.swapToward = function (block, targetY)
4494{
4495 var guard = 0;
4496 while (guard++ < this.height + 2)
4497 {
4498 var current = block.y;
4499 if (targetY > current + 0.5)
4500 {
4501 var above = this.blockAt(block.col, current + 1);
4502 if (above && this.isGrounded(above) && above !== block)
4503 { this.swapBlocks(block, above); }
4504 else
4505 { break; }
4506 }
4507 else if (targetY < current - 0.5)
4508 {
4509 var below = this.blockAt(block.col, current - 1);
4510 if (below && this.isGrounded(below) && below !== block)
4511 { this.swapBlocks(block, below); }
4512 else
4513 { break; }
4514 }
4515 else
4516 { break; }
4517 }
4518};
4519
4520GameCore.prototype.swapBlocks = function (a, b)
4521{
4522 var ay = a.y;
4523 var by = b.y;
4524 a.y = by;
4525 b.y = ay;
4526 this.transferLandedMembership(a, b);
4527 if (!this.swapEvents)
4528 { this.swapEvents = []; }
4529 this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });
4530 this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });
4531};
4532
4533GameCore.prototype.consumeSwapEvents = function ()
4534{
4535 var ev = this.swapEvents || [];
4536 this.swapEvents = [];
4537 return ev;
4538};
4539
4540/**
4541 * Highest landing-chain counter among just-landed members of this
4542 * match group, plus one. Returns 0 when the match did not come from
4543 * a cluster landing (player/bot swap, mid-air, etc.).
4544 */
4545GameCore.prototype.landingChainFor = function (group)
4546{
4547 var maxChain = 0;
4548 var fromLanding = false;
4549 for (var i = 0; i < group.length; i++)
4550 {
4551 var block = group[i];
4552 if (block.justLanded)
4553 {
4554 fromLanding = true;
4555 if ((block.landingChain || 0) > maxChain)
4556 { maxChain = block.landingChain || 0; }
4557 }
4558 if (block.clusterId != null)
4559 {
4560 var cluster = this.clusters[block.clusterId];
4561 if (cluster && cluster.landedPending)
4562 {
4563 fromLanding = true;
4564 if ((cluster.landingChain || 0) > maxChain)
4565 { maxChain = cluster.landingChain || 0; }
4566 }
4567 }
4568 }
4569 if (!fromLanding)
4570 { return 0; }
4571 return maxChain + 1;
4572};
4573
4574/**
4575 * After resolveMatches: clear the landing-pending flag and reset the
4576 * chain on landings that did not make a match. A cluster that is still
4577 * settling (greys not yet recolored) keeps landedPending so a later
4578 * post-recolor match in this same landing still gets the bonus.
4579 */
4580GameCore.prototype.finishLandingChains = function (launched)
4581{
4582 var launchedIds = Object.create(null);
4583 launched = launched || [];
4584 for (var i = 0; i < launched.length; i++)
4585 {
4586 var blocks = launched[i].blocks || [];
4587 for (var j = 0; j < blocks.length; j++)
4588 { launchedIds[blocks[j].id] = true; }
4589 }
4590
4591 for (var i = 0; i < this.blocks.length; i++)
4592 {
4593 var block = this.blocks[i];
4594 if (!block.justLanded)
4595 { continue; }
4596 if (!launchedIds[block.id])
4597 { block.landingChain = 0; }
4598 block.justLanded = false;
4599 }
4600
4601 var ids = Object.keys(this.clusters);
4602 for (var c = 0; c < ids.length; c++)
4603 {
4604 var cluster = this.clusters[ids[c]];
4605 if (!cluster || !cluster.landedPending)
4606 { continue; }
4607 var members = this.clusterMembers(cluster.id);
4608 var anyLaunched = false;
4609 var stillSettling = false;
4610 for (var i = 0; i < members.length; i++)
4611 {
4612 if (launchedIds[members[i].id])
4613 { anyLaunched = true; }
4614 if (members[i].state === STATE_SETTLING)
4615 { stillSettling = true; }
4616 }
4617 if (anyLaunched)
4618 {
4619 cluster.landingChain = 0;
4620 cluster.landedPending = false;
4621 }
4622 else if (!stillSettling)
4623 {
4624 // Released leftovers or a fully-still landed group that
4625 // already had its match opportunity and missed it.
4626 cluster.landingChain = 0;
4627 cluster.landedPending = false;
4628 }
4629 // else: still settling, no match yet — keep landedPending.
4630 }
4631};
4632
4633GameCore.prototype.updateChainIndicator = function (launched)
4634{
4635 var maxChain = 0;
4636 for (var i = 0; i < launched.length; i++)
4637 {
4638 var ch = launched[i].landingChain || 0;
4639 if (ch > maxChain)
4640 { maxChain = ch; }
4641 }
4642 if (maxChain >= 1)
4643 {
4644 this.lastChainIndicator = {
4645 chain: maxChain,
4646 bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)
4647 };
4648 return;
4649 }
4650 if (!this.hasActiveLandingChain())
4651 { this.lastChainIndicator = null; }
4652};
4653
4654GameCore.prototype.hasActiveLandingChain = function ()
4655{
4656 var ids = Object.keys(this.clusters);
4657 for (var i = 0; i < ids.length; i++)
4658 {
4659 var cluster = this.clusters[ids[i]];
4660 if (cluster && (cluster.landingChain || 0) >= 1
4661 && cluster.phase !== 'landed')
4662 { return true; }
4663 }
4664 return false;
4665};
4666
4667/**
4668 * A landed cluster (grey rockets or linked cargo resting on the ground)
4669 * is a swappable part of the contiguous grounded stack. Flying, falling
4670 * and manual blocks are not. A locked column is not.
4671 */
4672GameCore.prototype.isDraggableBlock = function (block)
4673{
4674 if (!block)
4675 { return false; }
4676 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
4677 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
4678 { return false; }
4679 if (block.clusterId != null)
4680 {
4681 var cluster = this.clusters[block.clusterId];
4682 // Flying (rising / descending) clusters stay non-draggable.
4683 if (cluster && cluster.phase !== 'landed')
4684 { return false; }
4685 }
4686 return block.state === STATE_STILL || block.state === STATE_SETTLING;
4687};
4688
4689/**
4690 * The grounded contiguous stack in this column can be dragged, even if a
4691 * flying cluster or a falling spawn occupies the air above it. Only a
4692 * locked column is blocked as a whole.
4693 */
4694GameCore.prototype.columnAllowsDrag = function (col)
4695{
4696 return !this.isColumnLocked(col);
4697};
4698
4699GameCore.prototype.landedClusterId = function (block)
4700{
4701 if (!block || block.clusterId == null)
4702 { return null; }
4703 var cluster = this.clusters[block.clusterId];
4704 if (!cluster || cluster.phase !== 'landed')
4705 { return null; }
4706 return block.clusterId;
4707};
4708
4709/**
4710 * After a swap: leaving a landed cluster clears membership; joining one
4711 * makes the block part of that rigid group. Same-cluster swaps only
4712 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
4713 */
4714GameCore.prototype.transferLandedMembership = function (a, b)
4715{
4716 var ca = this.landedClusterId(a);
4717 var cb = this.landedClusterId(b);
4718 if (ca === cb)
4719 { return; }
4720 // Join first so leaveCluster does not delete a cluster that still
4721 // has the incoming member.
4722 this.applyLandedMembership(b, ca);
4723 this.applyLandedMembership(a, cb);
4724};
4725
4726GameCore.prototype.applyLandedMembership = function (block, clusterId)
4727{
4728 if (clusterId == null)
4729 {
4730 var wasGrey = block.color === COLOR_GRAY;
4731 var wasSettling = block.state === STATE_SETTLING;
4732 this.leaveCluster(block);
4733 if (wasGrey && wasSettling)
4734 {
4735 // Keep settling and recolor on its own, same remaining timer.
4736 block.state = STATE_SETTLING;
4737 }
4738 else if (wasSettling)
4739 {
4740 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
4741 }
4742 return;
4743 }
4744 if (!this.clusters[clusterId])
4745 { return; }
4746 block.clusterId = clusterId;
4747 block.flame = false;
4748 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
4749 { block.state = STATE_SETTLING; }
4750};
4751
4752/**
4753 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
4754 * Returns the moved block, or null if the column does not allow a drag.
4755 */
4756GameCore.prototype.swapTo = function (col, fromRow, toRow)
4757{
4758 if (!this.columnAllowsDrag(col))
4759 { return null; }
4760 var block = this.blockAt(col, fromRow);
4761 if (!block)
4762 { return null; }
4763 this.swapToward(block, toRow);
4764 return block;
4765};
4766
4767/**
4768 * Test helper: a compact picture of grounded/falling/flying blocks.
4769 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
4770 * L locked, f falling, m manual, . empty. Flying colored blocks use
4771 * their color with a marker in `flying`.
4772 */
4773GameCore.prototype.snapshot = function ()
4774{
4775 var grid = [];
4776 for (var r = 0; r < this.height; r++)
4777 {
4778 var row = [];
4779 for (var c = 0; c < this.width; c++)
4780 { row.push('.'); }
4781 grid.push(row);
4782 }
4783 var airborne = [];
4784 for (var i = 0; i < this.blocks.length; i++)
4785 {
4786 var block = this.blocks[i];
4787 var ch;
4788 if (block.state === STATE_LOCKED)
4789 { ch = 'L'; }
4790 else if (block.color === COLOR_GRAY)
4791 { ch = 'g'; }
4792 else
4793 { ch = String(block.color); }
4794 if (this.isGrounded(block) || block.state === STATE_FALLING)
4795 {
4796 var row = Math.round(block.y);
4797 if (row >= 0 && row < this.height)
4798 { grid[row][block.col] = ch; }
4799 }
4800 else
4801 {
4802 airborne.push({
4803 id: block.id,
4804 col: block.col,
4805 y: block.y,
4806 color: block.color,
4807 state: block.state,
4808 clusterId: block.clusterId,
4809 flame: block.flame,
4810 vy: block.vy
4811 });
4812 }
4813 }
4814 var lines = [];
4815 for (var r = this.height - 1; r >= 0; r--)
4816 { lines.push(grid[r].join('')); }
4817 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
4818};
4819
4820var GameCoreAPI = {
4821 GameCore: GameCore,
4822 COLOR_GRAY: COLOR_GRAY,
4823 STATE_STILL: STATE_STILL,
4824 STATE_FALLING: STATE_FALLING,
4825 STATE_FLYING: STATE_FLYING,
4826 STATE_SETTLING: STATE_SETTLING,
4827 STATE_LOCKED: STATE_LOCKED,
4828 STATE_MANUAL: STATE_MANUAL
4829};
4830
4831if (typeof module !== 'undefined' && module.exports)
4832{ module.exports = GameCoreAPI; }
4833else if (typeof globalThis !== 'undefined')
4834{
4835 globalThis.GameCore = GameCore;
4836 globalThis.GameCoreAPI = GameCoreAPI;
4837}
4838
4839/*
4840 * End File:
4841 * /workspace/meteors/src/gameCore.js
4842 */
4843
4844/*
4845 * Start File:
4846 * /workspace/meteors/src/miniLayout.js
4847 */
4848'use strict';
4849
4850/**
4851 * Opponent miniature layout for online and Offline Strijd
4852 * (t1125, t1127, t1129, t1131, t1133).
4853 * Wide screens: minis sit beside the field, anchored to the outer
4854 * screen edges, filling inward (1 = left outer, 2 = right outer,
4855 * 3 = left next inward, …). Extra minis wrap to a new row upward
4856 * only when a side's row is full. Narrow / portrait: a row above
4857 * the field.
4858 */
4859
4860var MiniLayout = (function ()
4861{
4862
4863var GAP = 12;
4864var VGAP = 8;
4865var EDGE = 16;
4866var MIN_TILE_FOR_SIDES = 18;
4867var LABEL_H = 32;
4868/* Extra space above the field in the wide (sides) layout so
4869 enemy↔player arcs can route around the top edge (t1129). */
4870var ARC_TOP_PAD = 100;
4871/* Below this width, or in a narrow portrait, keep the top row (t1131). */
4872var PORTRAIT_NARROW = 700;
4873var PORTRAIT_MAX = 850;
4874
4875function preferredMini ()
4876{
4877 return { w: 80, h: 104, outerW: 90, outerH: 104 + LABEL_H };
4878}
4879
4880function canvasSize (n, mode, availH, rows)
4881{
4882 n = n || 0;
4883 if (mode === 'sides')
4884 {
4885 rows = Math.max(1, rows || 1);
4886 if (availH && rows > 1)
4887 {
4888 var maxOuter = Math.floor((availH - (rows - 1) * VGAP) / rows);
4889 var ch = Math.max(40, Math.min(104, maxOuter - LABEL_H));
4890 var cw = Math.max(32, Math.round(ch * 10 / 13));
4891 return {
4892 w: cw,
4893 h: ch,
4894 outerW: Math.max(cw + 8, 56),
4895 outerH: ch + LABEL_H
4896 };
4897 }
4898 return preferredMini();
4899 }
4900 if (n >= 10)
4901 { return { w: 40, h: 52, outerW: 56, outerH: 52 + LABEL_H }; }
4902 if (n >= 6)
4903 { return { w: 56, h: 73, outerW: 68, outerH: 73 + LABEL_H }; }
4904 return { w: 80, h: 104, outerW: 90, outerH: 104 + LABEL_H };
4905}
4906
4907/**
4908 * How many minis fit in one row on a side, between the screen edge
4909 * and the field: EDGE + n*outerW + n*GAP <= sideWidth.
4910 */
4911function colsThatFit (sideWidth, mini)
4912{
4913 if (!mini || !mini.outerW)
4914 { return 0; }
4915 var stride = mini.outerW + GAP;
4916 if (stride <= 0)
4917 { return 0; }
4918 return Math.max(0, Math.floor((sideWidth - EDGE) / stride));
4919}
4920
4921/**
4922 * Place n opponents. Anchored to the OUTER screen edges, filling
4923 * inward toward the field (t1133). Row 0 is bottom-aligned with the
4924 * field; further rows stack upward only after a side's row is full
4925 * (t1127).
4926 *
4927 * Index 0 → left outer, 1 → right outer, 2 → left next inward, …
4928 */
4929function sidePositions (n, fieldX, fieldY, fieldW, fieldH, mini, hudH, vw, colsPerSide)
4930{
4931 var positions = [];
4932 if (n <= 0)
4933 { return positions; }
4934 vw = vw || (fieldX * 2 + fieldW);
4935 var leftSpace = fieldX;
4936 var rightSpace = vw - (fieldX + fieldW);
4937 var colsL = colsPerSide != null ? colsPerSide : Math.max(1, colsThatFit(leftSpace, mini));
4938 var colsR = colsPerSide != null ? colsPerSide : Math.max(1, colsThatFit(rightSpace, mini));
4939 if (colsL < 1)
4940 { colsL = 1; }
4941 if (colsR < 1)
4942 { colsR = 1; }
4943
4944 var leftCount = Math.ceil(n / 2);
4945 var rightCount = Math.floor(n / 2);
4946 var rows = Math.max(
4947 Math.ceil(leftCount / colsL),
4948 rightCount ? Math.ceil(rightCount / colsR) : 1
4949 );
4950 var stackH = rows * mini.outerH + Math.max(0, rows - 1) * VGAP;
4951 var bottom = fieldY + fieldH;
4952 var top = bottom - stackH;
4953 if (top < hudH + 4)
4954 {
4955 top = hudH + 4;
4956 bottom = top + stackH;
4957 }
4958
4959 for (var i = 0; i < n; i++)
4960 {
4961 var isLeft = (i % 2) === 0;
4962 var slot = Math.floor(i / 2);
4963 var cols = isLeft ? colsL : colsR;
4964 var row = Math.floor(slot / cols);
4965 var fromOuter = slot % cols;
4966 var x = isLeft
4967 ? EDGE + fromOuter * (mini.outerW + GAP)
4968 : vw - EDGE - mini.outerW - fromOuter * (mini.outerW + GAP);
4969 var y = bottom - (row + 1) * mini.outerH - row * VGAP;
4970 positions.push({
4971 index: i,
4972 side: isLeft ? 'left' : 'right',
4973 row: row,
4974 fromOuter: fromOuter,
4975 colsPerSide: cols,
4976 x: x,
4977 y: y,
4978 w: mini.outerW,
4979 h: mini.outerH,
4980 canvasW: mini.w,
4981 canvasH: mini.h
4982 });
4983 }
4984 return positions;
4985}
4986
4987function isPortraitNarrow (vw, vh)
4988{
4989 if (vw < PORTRAIT_NARROW)
4990 { return true; }
4991 if (vw < vh && vw < PORTRAIT_MAX)
4992 { return true; }
4993 return false;
4994}
4995
4996/**
4997 * Compute the field and mini plan for a viewport.
4998 * `n` is the number of opponents (0 = solo, no minis).
4999 */
5000function plan (vw, vh, n, hudH, margin)
5001{
5002 vw = vw || 320;
5003 vh = vh || 480;
5004 n = n || 0;
5005 hudH = hudH == null ? 56 : hudH;
5006 margin = margin == null ? Math.max(6, Math.round(Math.min(vw, vh) * 0.015)) : margin;
5007
5008 function finish (mode, tile, fieldX, fieldY, miniH, mini, positions, cols)
5009 {
5010 return {
5011 mode: mode,
5012 tile: tile,
5013 fieldW: tile * 10,
5014 fieldH: tile * 13,
5015 fieldX: fieldX,
5016 fieldY: fieldY,
5017 miniH: miniH,
5018 mini: mini,
5019 positions: positions || [],
5020 colsPerSide: cols || 0,
5021 n: n
5022 };
5023 }
5024
5025 if (n > 0 && !isPortraitNarrow(vw, vh))
5026 {
5027 var availHSide = Math.max(80, vh - hudH - margin);
5028 var probe = preferredMini();
5029 var availWSide = Math.max(80, vw - margin * 2 - 2 * (probe.outerW + GAP));
5030 var availHForField = Math.max(80, availHSide - ARC_TOP_PAD);
5031 var tileSide = Math.max(14, Math.floor(Math.min(availWSide / 10, availHForField / 13)));
5032 var fieldWSide = tileSide * 10;
5033 var leftover = (vw - fieldWSide) / 2;
5034 var cols = colsThatFit(leftover, probe);
5035 // If a large mini does not fit, shrink it so a small one still can (t1131).
5036 if (cols < 1)
5037 {
5038 var shrinkStride = leftover - EDGE;
5039 if (shrinkStride >= 56 + GAP)
5040 {
5041 var ow = Math.max(56, shrinkStride - GAP);
5042 var oh = Math.round(ow * (104 + LABEL_H) / 90);
5043 var ch = Math.max(40, oh - LABEL_H);
5044 var cw = Math.max(32, Math.round(ch * 10 / 13));
5045 probe = { w: cw, h: ch, outerW: ow, outerH: ch + LABEL_H };
5046 cols = colsThatFit(leftover, probe);
5047 }
5048 }
5049 var need = probe.outerW + GAP + EDGE;
5050 if (leftover >= need && tileSide >= MIN_TILE_FOR_SIDES && cols >= 1)
5051 {
5052 var fieldX = Math.floor((vw - fieldWSide) / 2);
5053 var fieldHSide = tileSide * 13;
5054 var fieldY = hudH + ARC_TOP_PAD
5055 + Math.floor((availHForField - fieldHSide) / 2);
5056 if (fieldY < hudH + ARC_TOP_PAD)
5057 { fieldY = hudH + ARC_TOP_PAD; }
5058
5059 var leftCount = Math.ceil(n / 2);
5060 var rows = Math.max(1, Math.ceil(leftCount / cols));
5061 var stackAvail = fieldY + fieldHSide - (hudH + 4);
5062 if (rows > 1)
5063 {
5064 probe = canvasSize(n, 'sides', stackAvail, rows);
5065 cols = Math.max(1, colsThatFit(leftover, probe));
5066 rows = Math.max(1, Math.ceil(leftCount / cols));
5067 }
5068
5069 return finish('sides', tileSide, fieldX, fieldY, 0, probe,
5070 sidePositions(n, fieldX, fieldY, fieldWSide, fieldHSide, probe, hudH, vw, cols),
5071 cols);
5072 }
5073 }
5074
5075 var miniTop = canvasSize(n, 'top', 0);
5076 var miniH = 0;
5077 if (n > 0)
5078 {
5079 var share = n > 6 ? 0.26 : 0.20;
5080 miniH = Math.min(n > 6 ? 180 : 150, Math.max(86, Math.round(vh * share)));
5081 }
5082 var availW = Math.max(80, vw - margin * 2);
5083 var availH = Math.max(80, vh - hudH - miniH - margin);
5084 var tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
5085 var fieldW = tile * 10;
5086 var fieldH = tile * 13;
5087 var fieldX = Math.floor((vw - fieldW) / 2);
5088 var topBand = hudH + miniH;
5089 var fieldY = topBand + Math.floor((vh - topBand - fieldH - margin / 2) / 2);
5090 if (fieldY < topBand)
5091 { fieldY = topBand; }
5092 return finish('top', tile, fieldX, fieldY, miniH, miniTop, [], 0);
5093}
5094
5095var api = {
5096 GAP: GAP,
5097 VGAP: VGAP,
5098 EDGE: EDGE,
5099 MIN_TILE_FOR_SIDES: MIN_TILE_FOR_SIDES,
5100 ARC_TOP_PAD: ARC_TOP_PAD,
5101 PORTRAIT_NARROW: PORTRAIT_NARROW,
5102 LABEL_H: LABEL_H,
5103 canvasSize: canvasSize,
5104 colsThatFit: colsThatFit,
5105 sidePositions: sidePositions,
5106 plan: plan
5107};
5108
5109if (typeof module !== 'undefined' && module.exports)
5110{ module.exports = api; }
5111else if (typeof globalThis !== 'undefined')
5112{ globalThis.MiniLayout = api; }
5113
5114return api;
5115
5116})();
5117
5118if (typeof module !== 'undefined' && module.exports && typeof MiniLayout !== 'undefined')
5119{ module.exports = MiniLayout; }
5120
5121/*
5122 * End File:
5123 * /workspace/meteors/src/miniLayout.js
5124 */
5125
5126/*
5127 * Start File:
5128 * /workspace/meteors/src/online.js
5129 */
5130'use strict';
5131
5132/**
5133 * Online play: talks to api.php (cookie session), polls lobby and game
5134 * state, and draws opponent miniatures plus flying-block tweens.
5135 * Real-time sync is not required; a 0.75 s poll is enough.
5136 */
5137
5138var Online = {
5139 POLL_MS: 750,
5140 DEFAULT_MISS_CHANCE: 0.30,
5141 FLIGHT_DURATION: 1.2,
5142 configured: false,
5143 local: false,
5144 csrf: '',
5145 me: null,
5146 lifetimePoints: 0,
5147 locale: null,
5148 blocks: [],
5149 planets: [],
5150 lobby: null,
5151 incoming: [],
5152 shotResults: [],
5153 error: '',
5154 _timer: null,
5155 _pendingShots: [],
5156 _flights: [],
5157 _lastStatus: null,
5158 onChange: null,
5159 onGameStart: null,
5160 onIncoming: null,
5161 onFinished: null,
5162 onLobbyReturn: null
5163};
5164
5165Online._headers = function (json)
5166{
5167 var h = { 'Accept': 'application/json' };
5168 if (json)
5169 { h['Content-Type'] = 'application/json'; }
5170 if (this.csrf)
5171 { h['X-CSRF-Token'] = this.csrf; }
5172 return h;
5173};
5174
5175Online._apply = function (data)
5176{
5177 if (!data)
5178 { return; }
5179 if (typeof data.configured === 'boolean')
5180 { this.configured = data.configured; }
5181 if (typeof data.local === 'boolean')
5182 { this.local = data.local; }
5183 if (data.csrf)
5184 { this.csrf = data.csrf; }
5185 if (data.me !== undefined)
5186 { this.me = data.me; }
5187 if (data.lobby !== undefined)
5188 { this.lobby = data.lobby; }
5189 if (data.incoming)
5190 { this.incoming = data.incoming; }
5191 if (data.shot_results)
5192 { this.shotResults = data.shot_results; }
5193 if (data.miss_chance_default != null)
5194 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
5195 if (data.flight_duration != null)
5196 { this.FLIGHT_DURATION = data.flight_duration; }
5197 if (data.error)
5198 { this.error = data.error; }
5199 else if (data.ok)
5200 { this.error = ''; }
5201 if (data.lifetime_points != null)
5202 { this.lifetimePoints = data.lifetime_points; }
5203 if (data.locale !== undefined)
5204 { this.locale = data.locale; }
5205 if (data.blocks)
5206 { this.blocks = data.blocks; }
5207 if (data.planets)
5208 {
5209 this.planets = data.planets;
5210 if (typeof Planet !== 'undefined' && Planet.setCustomPlanets)
5211 { Planet.setCustomPlanets(data.planets); }
5212 }
5213 if (data.lobby && data.lobby.players && typeof Planet !== 'undefined' && Planet.rememberPlanet)
5214 {
5215 for (var i = 0; i < data.lobby.players.length; i++)
5216 {
5217 if (data.lobby.players[i].planet)
5218 { Planet.rememberPlanet(data.lobby.players[i].planet); }
5219 }
5220 }
5221};
5222
5223Online.request = function (action, body)
5224{
5225 var self = this;
5226 var isGet = action === 'me' || action === '';
5227 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
5228 var opts = {
5229 method: isGet && !body ? 'GET' : 'POST',
5230 credentials: 'same-origin',
5231 headers: this._headers(!!body || !isGet)
5232 };
5233 if (opts.method === 'POST')
5234 {
5235 var payload = body ? Object.assign({ action: action }, body) : { action: action };
5236 opts.body = JSON.stringify(payload);
5237 }
5238 return fetch(url, opts).then(function (res)
5239 {
5240 return res.json().then(function (data)
5241 {
5242 data = data || {};
5243 if (!res.ok && !data.error)
5244 { data.error = 'De server gaf ' + res.status; data.ok = false; }
5245 self._apply(data);
5246 return data;
5247 }, function ()
5248 {
5249 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
5250 self.error = fail.error;
5251 return fail;
5252 });
5253 }).catch(function (err)
5254 {
5255 var fail = { ok: false, error: 'Geen verbinding met de server.' };
5256 self.error = fail.error;
5257 return fail;
5258 });
5259};
5260
5261Online.refresh = function ()
5262{
5263 return this.request('me');
5264};
5265
5266Online.testLogin = function (who)
5267{
5268 return this.request('test_login', { user: who });
5269};
5270
5271Online.createLobby = function (planetId)
5272{
5273 return this.request('lobby_create', {
5274 miss_chance: this.DEFAULT_MISS_CHANCE,
5275 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
5276 });
5277};
5278
5279Online.joinLobby = function (code, planetId)
5280{
5281 return this.request('lobby_join', {
5282 code: code,
5283 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
5284 });
5285};
5286
5287Online.setPlanet = function (planetId)
5288{
5289 return this.request('lobby_set_planet', { planet_id: planetId });
5290};
5291
5292Online.playBegin = function (mode)
5293{
5294 return this.request('play_begin', { mode: mode || 'solo' });
5295};
5296
5297Online.playFinish = function (token, score)
5298{
5299 return this.request('play_finish', { token: token, score: score || 0 });
5300};
5301
5302Online.savePlanet = function (planet)
5303{
5304 return this.request('planet_save', { planet: planet });
5305};
5306
5307Online.deletePlanet = function (id)
5308{
5309 return this.request('planet_delete', { id: id });
5310};
5311
5312Online.setLocale = function (locale)
5313{
5314 return this.request('set_locale', { locale: locale });
5315};
5316
5317Online.leaveLobby = function ()
5318{
5319 return this.request('lobby_leave');
5320};
5321
5322Online.setReady = function (ready)
5323{
5324 return this.request('lobby_ready', { ready: !!ready });
5325};
5326
5327Online.startGame = function ()
5328{
5329 var self = this;
5330 var prev = this.lobby && this.lobby.status;
5331 return this.request('lobby_start').then(function (data)
5332 {
5333 self._handleTransitions(prev, data);
5334 return data;
5335 });
5336};
5337
5338Online.queueShots = function (shots)
5339{
5340 for (var i = 0; i < shots.length; i++)
5341 {
5342 this._pendingShots.push({
5343 client_id: String(shots[i].id),
5344 color: shots[i].color,
5345 col: shots[i].col,
5346 y: shots[i].y
5347 });
5348 }
5349};
5350
5351Online.poll = function (opts)
5352{
5353 opts = opts || {};
5354 var body = {};
5355 if (opts.snapshot)
5356 { body.snapshot = opts.snapshot; }
5357 if (opts.score != null)
5358 { body.score = opts.score; }
5359 if (opts.eliminated)
5360 { body.eliminated = true; }
5361 if (this._pendingShots.length)
5362 {
5363 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
5364 }
5365 var self = this;
5366 var prevStatus = this.lobby && this.lobby.status;
5367 return this.request('poll', body).then(function (data)
5368 {
5369 self._handleTransitions(prevStatus, data);
5370 if (self.onChange)
5371 { self.onChange(self); }
5372 return data;
5373 });
5374};
5375
5376Online._handleTransitions = function (prevStatus, data)
5377{
5378 var lobby = this.lobby;
5379 var status = lobby && lobby.status;
5380 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
5381 { this.onGameStart(lobby); }
5382 if (data && data.incoming && data.incoming.length && this.onIncoming)
5383 { this.onIncoming(data.incoming); }
5384 // Own outgoing results (immediate) and lobby-wide recent flights
5385 // (so every client can draw opponent and enemy-to-enemy arcs, t1125).
5386 var flights = [];
5387 if (data && data.shot_results && data.shot_results.length)
5388 { flights = flights.concat(data.shot_results); }
5389 if (data && data.shot_flights && data.shot_flights.length)
5390 { flights = flights.concat(data.shot_flights); }
5391 if (flights.length)
5392 { this.spawnFlights(flights, this._flightLocals); }
5393 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
5394 { this.onFinished(lobby); }
5395 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
5396 { this.onLobbyReturn(lobby); }
5397};
5398
5399Online.startPolling = function (getPayload)
5400{
5401 this.stopPolling();
5402 var self = this;
5403 var tick = function ()
5404 {
5405 var payload = getPayload ? getPayload() : {};
5406 self.poll(payload);
5407 };
5408 tick();
5409 this._timer = setInterval(tick, this.POLL_MS);
5410};
5411
5412Online.stopPolling = function ()
5413{
5414 if (this._timer)
5415 {
5416 clearInterval(this._timer);
5417 this._timer = null;
5418 }
5419};
5420
5421Online.loginUrl = function ()
5422{
5423 return 'auth.php';
5424};
5425
5426Online.logoutUrl = function ()
5427{
5428 return 'logout.php';
5429};
5430
5431Online.opponents = function ()
5432{
5433 if (!this.lobby || !this.lobby.players)
5434 { return []; }
5435 return this.lobby.players.filter(function (p) { return !p.is_me; });
5436};
5437
5438Online.aliveOpponents = function ()
5439{
5440 return this.opponents().filter(function (p) { return !p.eliminated; });
5441};
5442
5443Online.mePlayer = function ()
5444{
5445 if (!this.lobby || !this.lobby.players)
5446 { return null; }
5447 for (var i = 0; i < this.lobby.players.length; i++)
5448 {
5449 if (this.lobby.players[i].is_me)
5450 { return this.lobby.players[i]; }
5451 }
5452 return null;
5453};
5454
5455/* ---------- miniatures --------------------------------------------- */
5456
5457Online.renderMinis = function (container)
5458{
5459 if (!container)
5460 { return; }
5461 var opponents = this.opponents();
5462 var existing = {};
5463 var kids = container.querySelectorAll('[data-player]');
5464 for (var i = 0; i < kids.length; i++)
5465 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
5466
5467 var seen = Object.create(null);
5468 for (var i = 0; i < opponents.length; i++)
5469 {
5470 var p = opponents[i];
5471 seen[p.id] = true;
5472 var el = existing[p.id];
5473 if (!el)
5474 {
5475 el = document.createElement('div');
5476 el.className = 'mini';
5477 el.setAttribute('data-player', p.id);
5478 el.innerHTML = '<div class="mini-name"></div>'
5479 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
5480 + '<div class="mini-meta"></div>';
5481 container.appendChild(el);
5482 }
5483 var mz = (typeof app !== 'undefined' && app.miniLayout && app.miniLayout.mini)
5484 ? app.miniLayout.mini
5485 : { w: 80, h: 104 };
5486 var canvas = el.querySelector('canvas');
5487 if (canvas && (canvas.width !== mz.w || canvas.height !== mz.h))
5488 {
5489 canvas.width = mz.w;
5490 canvas.height = mz.h;
5491 }
5492 if (canvas)
5493 {
5494 canvas.style.width = mz.w + 'px';
5495 canvas.style.height = mz.h + 'px';
5496 }
5497 el.classList.toggle('eliminated', !!p.eliminated);
5498 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
5499 el.querySelector('.mini-meta').textContent = p.eliminated
5500 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
5501 : ('Punten ' + (p.score || 0));
5502 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
5503 }
5504 for (var id in existing)
5505 {
5506 if (!seen[id])
5507 { existing[id].remove(); }
5508 }
5509 if (typeof applyMinisLayout === 'function')
5510 { applyMinisLayout(); }
5511};
5512
5513var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
5514
5515function miniColor (planet, color)
5516{
5517 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
5518 { return planet.colors[color].hex; }
5519 return MINI_COLORS[color] || '#888';
5520}
5521
5522
5523Online._drawMini = function (canvas, snapshot, planet)
5524{
5525 if (!canvas)
5526 { return; }
5527 var ctx = canvas.getContext('2d');
5528 var w = 10;
5529 var h = 13;
5530 var tw = canvas.width / w;
5531 var th = canvas.height / h;
5532 ctx.fillStyle = '#0c1020';
5533 ctx.fillRect(0, 0, canvas.width, canvas.height);
5534 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
5535 ctx.lineWidth = 1;
5536 for (var c = 0; c <= w; c++)
5537 {
5538 ctx.beginPath();
5539 ctx.moveTo(c * tw + 0.5, 0);
5540 ctx.lineTo(c * tw + 0.5, canvas.height);
5541 ctx.stroke();
5542 }
5543 for (var r = 0; r <= h; r++)
5544 {
5545 ctx.beginPath();
5546 ctx.moveTo(0, r * th + 0.5);
5547 ctx.lineTo(canvas.width, r * th + 0.5);
5548 ctx.stroke();
5549 }
5550 if (!snapshot || !snapshot.blocks)
5551 { return; }
5552 // t1123: cheap sine pulse behind blocks of nearly-full columns.
5553 if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
5554 {
5555 var warns = GameCore.warnColumnsFromSnapshot(snapshot);
5556 var pulse = GameCore.columnWarnPulse();
5557 for (var wc = 0; wc < warns.length; wc++)
5558 {
5559 if (!warns[wc])
5560 { continue; }
5561 ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
5562 ctx.fillRect(wc * tw, 0, tw, canvas.height);
5563 }
5564 }
5565 var blocks = snapshot.blocks;
5566 for (var i = 0; i < blocks.length; i++)
5567 {
5568 var b = blocks[i];
5569 var x = b.col * tw;
5570 var y = canvas.height - (b.y + 1) * th;
5571 if (b.state === 'locked')
5572 { ctx.fillStyle = '#3a3d4a'; }
5573 else if (b.color < 0)
5574 { ctx.fillStyle = '#5a5d66'; }
5575 else
5576 { ctx.fillStyle = miniColor(planet, b.color); }
5577 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
5578 }
5579};
5580
5581Online.miniElement = function (playerId)
5582{
5583 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
5584};
5585
5586/* ---------- flight tweens ------------------------------------------ */
5587
5588function colorSpriteUrl (color, planetId)
5589{
5590 if (color < 0)
5591 { return 'images/block-gray.png'; }
5592 var planet = null;
5593 if (typeof Planet !== 'undefined')
5594 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
5595 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
5596 { return planet.colors[color].image; }
5597 return 'images/block-gray.png';
5598}
5599
5600/**
5601 * Animate shot results. `locals` is a map of client_id → {col, y, color,
5602 * startX, startY} in viewport pixels, filled by the view just after
5603 * consumeOutgoingShots.
5604 */
5605Online.playerId = function ()
5606{
5607 if (typeof app !== 'undefined' && app.offline)
5608 { return 'player'; }
5609 if (this.lobby && this.lobby.players)
5610 {
5611 for (var i = 0; i < this.lobby.players.length; i++)
5612 {
5613 if (this.lobby.players[i].is_me)
5614 { return this.lobby.players[i].id; }
5615 }
5616 }
5617 return 'player';
5618};
5619
5620/**
5621 * Classify a shot for visual treatment (t1125).
5622 * player-to-enemy, enemy-to-player, enemy-to-enemy,
5623 * player-miss, enemy-miss.
5624 */
5625Online.flightKind = function (fromId, targetId, miss)
5626{
5627 var me = this.playerId();
5628 var fromMe = !fromId || fromId === me || fromId === 'player';
5629 if (miss)
5630 { return fromMe ? 'player-miss' : 'enemy-miss'; }
5631 if (fromMe)
5632 { return 'player-to-enemy'; }
5633 if (targetId === me || targetId === 'player')
5634 { return 'enemy-to-player'; }
5635 return 'enemy-to-enemy';
5636};
5637
5638/**
5639 * Parabolic arc: linear in x, a rise of `height` pixels above the
5640 * chord at mid-flight (screen y grows downward, so we subtract).
5641 */
5642Online.arcPoint = function (start, end, u, height)
5643{
5644 var t = u < 0 ? 0 : (u > 1 ? 1 : u);
5645 var x = start.x + (end.x - start.x) * t;
5646 var y = start.y + (end.y - start.y) * t - 4 * height * t * (1 - t);
5647 return { x: x, y: y };
5648};
5649
5650Online.arcHeight = function (start, end)
5651{
5652 var dx = end.x - start.x;
5653 var dy = end.y - start.y;
5654 var dist = Math.sqrt(dx * dx + dy * dy);
5655 return Math.max(48, Math.min(220, dist * 0.28));
5656};
5657
5658Online.easeInOutCubic = function (t)
5659{
5660 if (t < 0.5)
5661 { return 4 * t * t * t; }
5662 var u = -2 * t + 2;
5663 return 1 - (u * u * u) / 2;
5664};
5665
5666/** Bounding box of the player's field in viewport pixels. */
5667Online.playerFieldRect = function ()
5668{
5669 var appRef = typeof app !== 'undefined' ? app : null;
5670 var canvas = appRef && appRef.scene && appRef.scene.canvas;
5671 if (canvas && canvas.getBoundingClientRect)
5672 { return canvas.getBoundingClientRect(); }
5673 if (appRef && appRef.fieldW)
5674 {
5675 return {
5676 left: appRef.fieldX,
5677 top: appRef.fieldY,
5678 right: appRef.fieldX + appRef.fieldW,
5679 bottom: appRef.fieldY + appRef.fieldH,
5680 width: appRef.fieldW,
5681 height: appRef.fieldH
5682 };
5683 }
5684 return null;
5685};
5686
5687/**
5688 * True if (x, y) is inside the field's interior. The top edge (a few
5689 * pixels) is not interior: launch and landing may use that band.
5690 */
5691Online.pointInFieldInterior = function (x, y, field, slop)
5692{
5693 if (!field)
5694 { return false; }
5695 slop = slop == null ? 6 : slop;
5696 return x > field.left + 0.5 && x < field.right - 0.5
5697 && y > field.top + slop && y < field.bottom - 0.5;
5698};
5699
5700/** Cubic Bezier C(t), t ∈ [0, 1]. C¹ (in fact C^∞) on (0, 1) — no corners (t1134). */
5701Online.cubicBezier = function (p0, p1, p2, p3, t)
5702{
5703 if (t < 0)
5704 { t = 0; }
5705 if (t > 1)
5706 { t = 1; }
5707 var u = 1 - t;
5708 var a = u * u * u;
5709 var b = 3 * u * u * t;
5710 var c = 3 * u * t * t;
5711 var d = t * t * t;
5712 return {
5713 x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
5714 y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
5715 };
5716};
5717
5718/** C'(t) = 3(1−t)²(P1−P0) + 6(1−t)t(P2−P1) + 3t²(P3−P2). */
5719Online.cubicBezierDeriv = function (p0, p1, p2, p3, t)
5720{
5721 if (t < 0)
5722 { t = 0; }
5723 if (t > 1)
5724 { t = 1; }
5725 var u = 1 - t;
5726 return {
5727 x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x),
5728 y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y)
5729 };
5730};
5731
5732Online.cubicBezierDeriv2 = function (p0, p1, p2, p3, t)
5733{
5734 if (t < 0)
5735 { t = 0; }
5736 if (t > 1)
5737 { t = 1; }
5738 var u = 1 - t;
5739 // C''(t) = 6(1−t)(P2−2P1+P0) + 6t(P3−2P2+P1)
5740 return {
5741 x: 6 * u * (p2.x - 2 * p1.x + p0.x) + 6 * t * (p3.x - 2 * p2.x + p1.x),
5742 y: 6 * u * (p2.y - 2 * p1.y + p0.y) + 6 * t * (p3.y - 2 * p2.y + p1.y)
5743 };
5744};
5745
5746/** Degree-5 Bézier. One polynomial ⇒ C^∞ on (0, 1) (t1138). */
5747Online.quinticBezier = function (pts, t)
5748{
5749 if (t < 0)
5750 { t = 0; }
5751 if (t > 1)
5752 { t = 1; }
5753 var u = 1 - t;
5754 var u2 = u * u, u3 = u2 * u, u4 = u3 * u, u5 = u4 * u;
5755 var t2 = t * t, t3 = t2 * t, t4 = t3 * t, t5 = t4 * t;
5756 var b0 = u5, b1 = 5 * u4 * t, b2 = 10 * u3 * t2;
5757 var b3 = 10 * u2 * t3, b4 = 5 * u * t4, b5 = t5;
5758 return {
5759 x: b0 * pts[0].x + b1 * pts[1].x + b2 * pts[2].x
5760 + b3 * pts[3].x + b4 * pts[4].x + b5 * pts[5].x,
5761 y: b0 * pts[0].y + b1 * pts[1].y + b2 * pts[2].y
5762 + b3 * pts[3].y + b4 * pts[4].y + b5 * pts[5].y
5763 };
5764};
5765
5766Online.quinticBezierDeriv = function (pts, t)
5767{
5768 if (t < 0)
5769 { t = 0; }
5770 if (t > 1)
5771 { t = 1; }
5772 var d = [];
5773 for (var i = 0; i < 5; i++)
5774 { d.push({ x: pts[i + 1].x - pts[i].x, y: pts[i + 1].y - pts[i].y }); }
5775 var u = 1 - t;
5776 var u2 = u * u, u3 = u2 * u, u4 = u3 * u;
5777 var t2 = t * t, t3 = t2 * t, t4 = t3 * t;
5778 var b0 = u4, b1 = 4 * u3 * t, b2 = 6 * u2 * t2, b3 = 4 * u * t3, b4 = t4;
5779 return {
5780 x: 5 * (b0 * d[0].x + b1 * d[1].x + b2 * d[2].x + b3 * d[3].x + b4 * d[4].x),
5781 y: 5 * (b0 * d[0].y + b1 * d[1].y + b2 * d[2].y + b3 * d[3].y + b4 * d[4].y)
5782 };
5783};
5784
5785Online.quinticBezierDeriv2 = function (pts, t)
5786{
5787 if (t < 0)
5788 { t = 0; }
5789 if (t > 1)
5790 { t = 1; }
5791 var d2 = [];
5792 for (var i = 0; i < 4; i++)
5793 {
5794 d2.push({
5795 x: pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x,
5796 y: pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y
5797 });
5798 }
5799 var u = 1 - t;
5800 var u2 = u * u, u3 = u2 * u;
5801 var t2 = t * t, t3 = t2 * t;
5802 var b0 = u3, b1 = 3 * u2 * t, b2 = 3 * u * t2, b3 = t3;
5803 return {
5804 x: 20 * (b0 * d2[0].x + b1 * d2[1].x + b2 * d2[2].x + b3 * d2[3].x),
5805 y: 20 * (b0 * d2[0].y + b1 * d2[1].y + b2 * d2[2].y + b3 * d2[3].y)
5806 };
5807};
5808
5809/** Signed curvature κ = (x'y'' − y'x'') / |r'|³ (independent of parametrisation). */
5810Online.curvature = function (d1, d2)
5811{
5812 var sp = d1.x * d1.x + d1.y * d1.y;
5813 var den = Math.pow(sp, 1.5);
5814 if (den < 1e-12)
5815 { return 0; }
5816 return (d1.x * d2.y - d1.y * d2.x) / den;
5817};
5818
5819/**
5820 * de Casteljau evaluation of a Bézier of any degree, plus first
5821 * and second derivatives (t1138). A single polynomial is C^∞ on (0, 1).
5822 */
5823Online.bezierPoint = function (pts, t)
5824{
5825 if (!pts || !pts.length)
5826 { return { x: 0, y: 0 }; }
5827 if (t < 0)
5828 { t = 0; }
5829 if (t > 1)
5830 { t = 1; }
5831 var tmp = [];
5832 var i, k, u = 1 - t;
5833 for (i = 0; i < pts.length; i++)
5834 { tmp.push({ x: pts[i].x, y: pts[i].y }); }
5835 for (k = 1; k < pts.length; k++)
5836 {
5837 for (i = 0; i < pts.length - k; i++)
5838 {
5839 tmp[i] = {
5840 x: u * tmp[i].x + t * tmp[i + 1].x,
5841 y: u * tmp[i].y + t * tmp[i + 1].y
5842 };
5843 }
5844 }
5845 return tmp[0];
5846};
5847
5848Online.bezierDeriv = function (pts, t)
5849{
5850 var n = pts ? pts.length - 1 : 0;
5851 if (n < 1)
5852 { return { x: 0, y: 0 }; }
5853 var d = [];
5854 for (var i = 0; i < n; i++)
5855 {
5856 d.push({
5857 x: n * (pts[i + 1].x - pts[i].x),
5858 y: n * (pts[i + 1].y - pts[i].y)
5859 });
5860 }
5861 return this.bezierPoint(d, t);
5862};
5863
5864Online.bezierDeriv2 = function (pts, t)
5865{
5866 var n = pts ? pts.length - 1 : 0;
5867 if (n < 2)
5868 { return { x: 0, y: 0 }; }
5869 var s = n * (n - 1);
5870 var d2 = [];
5871 for (var i = 0; i < n - 1; i++)
5872 {
5873 d2.push({
5874 x: s * (pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x),
5875 y: s * (pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y)
5876 });
5877 }
5878 return this.bezierPoint(d2, t);
5879};
5880
5881/**
5882 * Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1.
5883 * v0=v1=1 is linear (constant speed in t, no endpoint halt).
5884 */
5885Online.smoothParam = function (t, v0, v1)
5886{
5887 if (t < 0)
5888 { return 0; }
5889 if (t > 1)
5890 { return 1; }
5891 if (v0 == null)
5892 { v0 = 1; }
5893 if (v1 == null)
5894 { v1 = 1; }
5895 var b = 3 - 2 * v0 - v1;
5896 var a = v0 + v1 - 2;
5897 return ((a * t + b) * t + v0) * t;
5898};
5899
5900/**
5901 * One continuous degree-7 Bézier: a single big, round, ballistic
5902 * arch (t1138). Vertical at the exit (heading up) and at the
5903 * landing (heading down). Horizontal travel sits on the apex,
5904 * above the field — a cluster of high control points on each
5905 * side keeps the hull out of the interior, with no straight
5906 * cruise and no quarter-turn kinks. C^∞ on (0, 1).
5907 *
5908 * Incoming (low mini → high field): the first mid controls stay
5909 * on the outside so the rise clears the top before crossing.
5910 * Outgoing (high exit → low mini): mid controls sit above the
5911 * target so the dive happens outside. Enemy→enemy (no field)
5912 * is a symmetric parabola behind the field.
5913 */
5914Online.makeAroundCurve = function (start, end, field, opts)
5915{
5916 opts = opts || {};
5917 if (!start)
5918 { start = { x: 0, y: 0 }; }
5919 if (!end)
5920 { end = { x: 0, y: 0 }; }
5921 var clearance = opts.clearance || 150;
5922 if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)
5923 { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD); }
5924 if (clearance < 150)
5925 { clearance = 150; }
5926
5927 var apexY;
5928 var left, right, top;
5929 if (field)
5930 {
5931 top = field.top;
5932 left = field.left;
5933 right = field.right;
5934 apexY = top - clearance;
5935 if (apexY < 8)
5936 { apexY = Math.max(8, top - Math.max(28, clearance * 0.5)); }
5937 }
5938 else
5939 {
5940 apexY = Math.min(start.y, end.y) - Math.max(56, clearance * 0.6);
5941 if (apexY < 8)
5942 { apexY = Math.min(start.y, end.y) - 40; }
5943 left = right = top = null;
5944 }
5945
5946 function outsideX (x)
5947 {
5948 if (!field)
5949 { return x; }
5950 var pad = 40;
5951 if (x < left + 8)
5952 { return Math.min(x, left - pad); }
5953 if (x > right - 8)
5954 { return Math.max(x, right + pad); }
5955 return x;
5956 }
5957
5958 var startLow = field && start.y > top + 8;
5959 var endLow = field && end.y > top + 8;
5960 var startInside = field && start.x > left + 8 && start.x < right - 8;
5961 var endInside = field && end.x > left + 8 && end.x < right - 8;
5962 // Incoming: rise on the outside first. Outgoing: cross at
5963 // the apex, then dive outside. Otherwise a symmetric arch.
5964 var kind;
5965 if (startLow && !endLow)
5966 { kind = 'in'; }
5967 else if (!startLow && endLow)
5968 { kind = 'out'; }
5969 else if (startLow && endLow)
5970 { kind = startInside ? 'out' : (endInside ? 'in' : 'sym'); }
5971 else
5972 { kind = 'sym'; }
5973
5974 var sx = outsideX(start.x);
5975 var ex = outsideX(end.x);
5976 var rise = Math.max(80, Math.abs(start.y - apexY) * 0.35);
5977 var P0 = { x: start.x, y: start.y };
5978 var P1 = { x: start.x, y: start.y - rise };
5979 var P2, P3, P4, P5;
5980 var P6 = { x: end.x, y: apexY };
5981 var P7 = { x: end.x, y: end.y };
5982 if (kind === 'in')
5983 {
5984 P2 = { x: sx, y: apexY };
5985 P3 = { x: sx, y: apexY };
5986 P4 = { x: sx + (ex - sx) * 0.5, y: apexY };
5987 P5 = { x: sx + (ex - sx) * 0.85, y: apexY };
5988 }
5989 else if (kind === 'out')
5990 {
5991 P2 = { x: start.x, y: apexY };
5992 P3 = { x: sx + (ex - sx) * 0.55, y: apexY };
5993 P4 = { x: ex, y: apexY };
5994 P5 = { x: end.x, y: apexY };
5995 }
5996 else
5997 {
5998 P2 = { x: sx, y: apexY };
5999 P3 = { x: sx + (ex - sx) * 0.35, y: apexY };
6000 P4 = { x: sx + (ex - sx) * 0.65, y: apexY };
6001 P5 = { x: ex, y: apexY };
6002 }
6003 var pts = [P0, P1, P2, P3, P4, P5, P6, P7];
6004
6005 var curve = {
6006 degree: 7,
6007 pts: pts,
6008 p0: P0,
6009 p3: P7,
6010 apexY: apexY,
6011 kind: kind,
6012 arcLength: true
6013 };
6014 this._buildArcLut(curve);
6015 return curve;
6016};
6017
6018Online._evalPoly = function (curve, t)
6019{
6020 if (curve && curve.pts && curve.pts.length >= 2)
6021 { return this.bezierPoint(curve.pts, t); }
6022 if (curve && curve.p1)
6023 { return this.cubicBezier(curve.p0, curve.p1, curve.p2, curve.p3, t); }
6024 if (curve && curve.segments)
6025 {
6026 var n = curve.segments.length;
6027 var at = (t < 0 ? 0 : (t > 1 ? 1 : t)) * n;
6028 var i = Math.floor(at);
6029 if (i >= n)
6030 { i = n - 1; }
6031 var s = curve.segments[i];
6032 return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at - i);
6033 }
6034 return { x: 0, y: 0 };
6035};
6036
6037Online._evalPolyDeriv = function (curve, t)
6038{
6039 if (curve && curve.pts && curve.pts.length >= 2)
6040 { return this.bezierDeriv(curve.pts, t); }
6041 if (curve && curve.p1)
6042 { return this.cubicBezierDeriv(curve.p0, curve.p1, curve.p2, curve.p3, t); }
6043 return { x: 0, y: 0 };
6044};
6045
6046Online._evalPolyDeriv2 = function (curve, t)
6047{
6048 if (curve && curve.pts && curve.pts.length >= 3)
6049 { return this.bezierDeriv2(curve.pts, t); }
6050 if (curve && curve.p1)
6051 { return this.cubicBezierDeriv2(curve.p0, curve.p1, curve.p2, curve.p3, t); }
6052 return { x: 0, y: 0 };
6053};
6054
6055/** Cumulative-length LUT so u is a fraction of arc length (t1138). */
6056Online._buildArcLut = function (curve, steps)
6057{
6058 steps = steps || 48;
6059 var acc = [0];
6060 var prev = this._evalPoly(curve, 0);
6061 for (var i = 1; i <= steps; i++)
6062 {
6063 var p = this._evalPoly(curve, i / steps);
6064 acc.push(acc[i - 1] + Math.sqrt((p.x - prev.x) * (p.x - prev.x)
6065 + (p.y - prev.y) * (p.y - prev.y)));
6066 prev = p;
6067 }
6068 curve.lutS = acc;
6069 curve.lutN = steps;
6070 curve.totalLen = Math.max(acc[steps], 1);
6071 return curve;
6072};
6073
6074/** Polynomial t whose arc length fraction is u. */
6075Online._arcT = function (curve, u)
6076{
6077 if (u <= 0)
6078 { return 0; }
6079 if (u >= 1)
6080 { return 1; }
6081 if (!curve.lutS)
6082 { this._buildArcLut(curve); }
6083 var s = u * curve.totalLen;
6084 var acc = curve.lutS;
6085 var n = curve.lutN;
6086 var lo = 0;
6087 var hi = n;
6088 while (lo < hi)
6089 {
6090 var mid = (lo + hi) >> 1;
6091 if (acc[mid] < s)
6092 { lo = mid + 1; }
6093 else
6094 { hi = mid; }
6095 }
6096 var i = lo;
6097 if (i <= 0)
6098 { return 0; }
6099 var s0 = acc[i - 1];
6100 var s1 = acc[i];
6101 var f = (s1 > s0) ? (s - s0) / (s1 - s0) : 0;
6102 return ((i - 1) + f) / n;
6103};
6104
6105Online._measureCurve = function (curve)
6106{
6107 if (!curve)
6108 { return curve; }
6109 if (!curve.lutS)
6110 { this._buildArcLut(curve); }
6111 return curve;
6112};
6113
6114Online._segLen = function (seg, steps)
6115{
6116 steps = steps || 10;
6117 if (seg && seg.degree === 5)
6118 {
6119 if (!seg.lutS)
6120 { this._buildArcLut(seg, steps * 4); }
6121 return seg.totalLen;
6122 }
6123 var len = 0;
6124 var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0);
6125 for (var i = 1; i <= steps; i++)
6126 {
6127 var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps);
6128 len += Math.sqrt((p.x - prev.x) * (p.x - prev.x) + (p.y - prev.y) * (p.y - prev.y));
6129 prev = p;
6130 }
6131 return Math.max(len, 1);
6132};
6133
6134/** Point at arc-length fraction u ∈ [0, 1]. */
6135Online.curvePoint = function (curve, u)
6136{
6137 if (!curve)
6138 { return { x: 0, y: 0 }; }
6139 var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u));
6140 return this._evalPoly(curve, t);
6141};
6142
6143/**
6144 * dP/du under arc-length parametrisation: unit tangent × total length
6145 * (constant speed in u, direction from the polynomial).
6146 */
6147Online.curveDeriv = function (curve, u)
6148{
6149 if (!curve)
6150 { return { x: 0, y: 0 }; }
6151 var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u));
6152 var d = this._evalPolyDeriv(curve, t);
6153 if (curve.arcLength !== false)
6154 {
6155 if (!curve.lutS)
6156 { this._buildArcLut(curve); }
6157 var mag = Math.sqrt(d.x * d.x + d.y * d.y);
6158 if (mag < 1e-9)
6159 { return { x: 0, y: 0 }; }
6160 var s = curve.totalLen / mag;
6161 return { x: d.x * s, y: d.y * s };
6162 }
6163 return d;
6164};
6165
6166Online.curveDeriv2 = function (curve, u)
6167{
6168 if (!curve)
6169 { return { x: 0, y: 0 }; }
6170 var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u));
6171 return this._evalPolyDeriv2(curve, t);
6172};
6173
6174/** Curvature at arc-length fraction u (uses polynomial t, κ is invariant). */
6175Online.curveCurvature = function (curve, u)
6176{
6177 var t = curve && curve.arcLength !== false ? this._arcT(curve, u) : u;
6178 return this.curvature(this._evalPolyDeriv(curve, t), this._evalPolyDeriv2(curve, t));
6179};
6180
6181/**
6182 * Endpoint ease rates so arrival speed ≈ fallSpeed under arc-length
6183 * parametrisation: v = (L / duration) * p'(raw).
6184 */
6185Online.flightEaseRates = function (curve, duration, fallPx)
6186{
6187 if (!curve || !curve.lutS)
6188 { this._measureCurve(curve); }
6189 var L = (curve && curve.totalLen) || 400;
6190 duration = duration || this.FLIGHT_DURATION;
6191 var v1 = fallPx && L ? (fallPx * duration) / L : 0.75;
6192 if (v1 < 0.28)
6193 { v1 = 0.28; }
6194 if (v1 > 1.15)
6195 { v1 = 1.15; }
6196 var v0 = v1 + 0.2;
6197 if (v0 > 1)
6198 { v0 = 1; }
6199 if (v0 < 0.45)
6200 { v0 = 0.45; }
6201 return { v0: v0, v1: v1 };
6202};
6203
6204Online.aroundFieldPoint = function (start, end, u, field, clearance)
6205{
6206 var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance };
6207 var curve = opts.curve || this.makeAroundCurve(start, end, field, opts);
6208 return this.curvePoint(curve, u);
6209};
6210
6211Online.waypointsAroundField = function (start, end, field, clearance)
6212{
6213 var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 100 });
6214 if (c.pts && c.pts.length)
6215 { return c.pts.slice(); }
6216 return [c.p0, c.p1, c.p2, c.p3];
6217};
6218
6219Online.pointOnPath = function (points, u)
6220{
6221 // Legacy polyline; new flights use cubicBezier.
6222 u = u < 0 ? 0 : (u > 1 ? 1 : u);
6223 if (!points || !points.length)
6224 { return { x: 0, y: 0 }; }
6225 if (points.length === 4 && points[0] && points[3])
6226 { return this.cubicBezier(points[0], points[1], points[2], points[3], u); }
6227 if (points.length === 1)
6228 { return { x: points[0].x, y: points[0].y }; }
6229 var n = points.length - 1;
6230 var at = u * n;
6231 var i = Math.floor(at);
6232 if (i >= n)
6233 { i = n - 1; }
6234 var t = at - i;
6235 var a = points[i];
6236 var b = points[i + 1];
6237 return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
6238};
6239
6240/** Viewport centre of a field cell (y=0 is the bottom row). */
6241Online.cellViewport = function (col, y, rect)
6242{
6243 if (!rect)
6244 {
6245 var field = this.playerFieldRect();
6246 if (!field)
6247 { return { x: 0, y: 0 }; }
6248 rect = field;
6249 }
6250 var w = rect.width != null ? rect.width : (rect.right - rect.left);
6251 var h = rect.height != null ? rect.height : (rect.bottom - rect.top);
6252 return {
6253 x: rect.left + ((col + 0.5) / 10) * w,
6254 y: rect.top + (1 - (y + 0.5) / 13) * h
6255 };
6256};
6257
6258/** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */
6259Online.fieldEntry = function (col)
6260{
6261 return this.cellViewport(col == null ? 4.5 : col, 13);
6262};
6263
6264Online.miniCellViewport = function (playerId, col, y)
6265{
6266 var el = this.miniElement(playerId);
6267 var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
6268 var box = canvas || el;
6269 if (!box || !box.getBoundingClientRect)
6270 { return { x: window.innerWidth / 2, y: 48 }; }
6271 return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect());
6272};
6273
6274Online._fallSpeedPx = function (field, duration)
6275{
6276 var px = 40;
6277 if (field && field.height)
6278 { px = field.height / 13; }
6279 else if (typeof app !== 'undefined' && app.tile)
6280 { px = app.tile; }
6281 var cells = 13 / 3;
6282 if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed)
6283 { cells = app.planet.fallSpeed; }
6284 duration = duration || this.FLIGHT_DURATION;
6285 // Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135).
6286 return (cells * px * duration) / 3;
6287};
6288
6289Online.rememberLandCol = function (id, col)
6290{
6291 if (id == null || col == null || !isFinite(col))
6292 { return; }
6293 if (!this._pendingLandCol)
6294 { this._pendingLandCol = Object.create(null); }
6295 this._pendingLandCol[String(id)] = col | 0;
6296};
6297
6298/** Resolve the landing column for an incoming shot (t1126). */
6299Online.takeLandCol = function (incoming)
6300{
6301 if (!incoming)
6302 { return null; }
6303 if (incoming.land_col != null && isFinite(incoming.land_col))
6304 { return incoming.land_col | 0; }
6305 if (!this._pendingLandCol)
6306 { return null; }
6307 var keys = [];
6308 if (incoming.id != null)
6309 { keys.push(String(incoming.id)); }
6310 if (incoming.client_id)
6311 { keys.push(String(incoming.client_id)); }
6312 for (var i = 0; i < keys.length; i++)
6313 {
6314 if (this._pendingLandCol[keys[i]] != null)
6315 { return this._pendingLandCol[keys[i]]; }
6316 }
6317 return null;
6318};
6319
6320Online._miniCellSize = function (playerId)
6321{
6322 var el = this.miniElement(playerId);
6323 var canvas = el && el.querySelector('canvas');
6324 if (canvas)
6325 {
6326 var r = canvas.getBoundingClientRect();
6327 return Math.max(6, r.width / 10);
6328 }
6329 return 10;
6330};
6331
6332Online._fullTileSize = function ()
6333{
6334 if (typeof app !== 'undefined' && app.tile)
6335 { return app.tile; }
6336 return 40;
6337};
6338
6339Online._miniAnchor = function (playerId, dir)
6340{
6341 var el = this.miniElement(playerId);
6342 var canvas = el && (el.querySelector ? el.querySelector('canvas') : null);
6343 var box = canvas || el;
6344 if (!box)
6345 { return { x: window.innerWidth / 2, y: 48 }; }
6346 var r = box.getBoundingClientRect();
6347 if (dir === 'out')
6348 { return { x: r.left + r.width / 2, y: r.top + 4 }; }
6349 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
6350};
6351
6352Online._fieldTop = function (col)
6353{
6354 return this.fieldEntry(col);
6355};
6356
6357/**
6358 * Animate shot results. `locals` is a map of client_id → {col, y, color,
6359 * startX, startY, from_id} in viewport pixels.
6360 *
6361 * Visual-only: a smooth cubic that leaves the real cell, arcs around
6362 * the field, and dives into the landing column at the spawn pose
6363 * (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn
6364 * behind the player's field. A late-seen flight starts mid-arc via `age`.
6365 */
6366Online.spawnFlights = function (results, locals)
6367{
6368 locals = locals || this._flightLocals || {};
6369 var front = document.getElementById('flights');
6370 var back = document.getElementById('flights-back') || front;
6371 if (!front)
6372 { return; }
6373 if (!this._flightSeen)
6374 { this._flightSeen = Object.create(null); }
6375 if (!this._previewIds)
6376 { this._previewIds = Object.create(null); }
6377 var now = performance.now();
6378 var full = this._fullTileSize();
6379 for (var i = 0; i < results.length; i++)
6380 {
6381 var r = results[i];
6382 var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i)));
6383 if (this._flightSeen[sid])
6384 {
6385 if (this._previewIds[sid])
6386 {
6387 var existing = this._findFlight(sid);
6388 if (existing)
6389 {
6390 var meta0 = locals[r.client_id] || locals[sid] || {};
6391 this.retargetFlight(existing, r, meta0, now);
6392 }
6393 }
6394 continue;
6395 }
6396 this._flightSeen[sid] = now;
6397
6398 var meta = locals[r.client_id] || locals[sid] || {};
6399 var fromId = r.from_id || r.from_user || meta.from_id || null;
6400 var targetId = r.target_id != null ? r.target_id : r.to_user;
6401 var miss = !!r.miss;
6402 var kind = this.flightKind(fromId, targetId, miss);
6403 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
6404 if (r.age != null && isFinite(r.age) && r.age * 1000 >= duration)
6405 { continue; }
6406
6407 var landCol = null;
6408 if (r.land_col != null && isFinite(r.land_col))
6409 { landCol = r.land_col | 0; }
6410 else if (meta.land_col != null && isFinite(meta.land_col))
6411 { landCol = meta.land_col | 0; }
6412 else if (kind === 'enemy-to-player'
6413 && typeof app !== 'undefined' && app.core && app.core.pickGarbageColumn)
6414 { landCol = app.core.pickGarbageColumn(); }
6415 if (landCol != null)
6416 {
6417 this.rememberLandCol(sid, landCol);
6418 if (r.client_id)
6419 { this.rememberLandCol(r.client_id, landCol); }
6420 }
6421
6422 var startCol = meta.col != null ? meta.col : r.col;
6423 var startY = meta.y != null ? meta.y : r.y;
6424 var start;
6425 if (meta.startX != null && isFinite(meta.startX))
6426 { start = { x: meta.startX, y: meta.startY }; }
6427 else if (kind === 'player-to-enemy' || kind === 'player-miss')
6428 { start = this._flightStart(startCol, startY); }
6429 else if (startCol != null || startY != null)
6430 { start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 13); }
6431 else
6432 { start = this._miniAnchor(fromId, 'out'); }
6433
6434 var end;
6435 if (miss)
6436 { end = this._missEnd(start, kind === 'enemy-miss'); }
6437 else if (kind === 'enemy-to-player')
6438 { end = this.fieldEntry(landCol != null ? landCol : 4.5); }
6439 else
6440 { end = this._targetEnd(targetId, start, landCol); }
6441
6442 // Hits are ingested as grey garbage; draw them grey (t1130).
6443 // Misses keep the sender's colour — nothing is received.
6444 var flightColor = miss
6445 ? (r.color != null ? r.color : meta.color)
6446 : -1;
6447
6448 var startScale;
6449 var endScale;
6450 var mini = this._miniCellSize(fromId || targetId) / full;
6451 if (mini < 0.12)
6452 { mini = 0.2; }
6453 if (kind === 'player-to-enemy')
6454 {
6455 startScale = 1;
6456 endScale = mini;
6457 }
6458 else if (kind === 'enemy-to-player')
6459 {
6460 startScale = mini;
6461 endScale = 1;
6462 }
6463 else if (kind === 'enemy-to-enemy')
6464 {
6465 startScale = mini;
6466 endScale = mini;
6467 }
6468 else if (kind === 'enemy-miss')
6469 {
6470 startScale = mini;
6471 endScale = 0;
6472 }
6473 else
6474 {
6475 startScale = 1;
6476 endScale = 0;
6477 }
6478
6479 var layer = (kind === 'enemy-to-enemy' && back) ? back : front;
6480 var el = document.createElement('img');
6481 el.src = colorSpriteUrl(flightColor);
6482 el.alt = '';
6483 el.className = 'flight' + (kind === 'enemy-to-enemy' ? ' flight-behind' : '');
6484 el.style.width = full + 'px';
6485 el.style.height = full + 'px';
6486 layer.appendChild(el);
6487
6488 var t0 = now;
6489 if (r.age != null && isFinite(r.age) && r.age > 0)
6490 {
6491 var u0 = Math.min(0.95, (r.age * 1000) / duration);
6492 t0 = now - u0 * duration;
6493 }
6494 var height = miss
6495 ? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35))
6496 : this.arcHeight(start, end);
6497 var field = this.playerFieldRect();
6498 var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
6499 var clearance = Math.max(150, height * 0.55);
6500 var endSpeed = this._fallSpeedPx(field, duration / 1000);
6501 var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, {
6502 clearance: clearance
6503 });
6504 var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null;
6505 this._flights.push({
6506 el: el,
6507 start: start,
6508 end: end,
6509 ctrl: miss ? this._missCtrl(start, end) : null,
6510 height: height,
6511 t0: t0,
6512 duration: duration,
6513 easeRates: easeRates,
6514 spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120),
6515 miss: miss,
6516 kind: kind,
6517 startScale: startScale,
6518 endScale: endScale,
6519 angle: 0,
6520 id: sid,
6521 landCol: landCol,
6522 field: field,
6523 curve: curve,
6524 color: flightColor
6525 });
6526 }
6527 this._flightLocals = {};
6528};
6529
6530Online.rememberFlightLocal = function (shot, startX, startY)
6531{
6532 if (!this._flightLocals)
6533 { this._flightLocals = {}; }
6534 this._flightLocals[String(shot.id)] = {
6535 col: shot.col,
6536 y: shot.y,
6537 color: shot.color,
6538 startX: startX,
6539 startY: startY,
6540 from_id: shot.from_id,
6541 land_col: shot.land_col,
6542 vy: shot.vy
6543 };
6544};
6545
6546Online._flightStart = function (col, y)
6547{
6548 if (y == null || !isFinite(y))
6549 { y = 13; }
6550 return this.cellViewport(col == null ? 4.5 : col, y);
6551};
6552
6553Online._targetEnd = function (targetId, start, col)
6554{
6555 var el = targetId && this.miniElement(targetId);
6556 if (el)
6557 {
6558 // Slightly inside the mini, in the landing column (t1135).
6559 return this.miniCellViewport(targetId, col, 12);
6560 }
6561 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
6562};
6563
6564Online._missEnd = function (start, fromMini)
6565{
6566 var w = window.innerWidth || 800;
6567 var outward;
6568 if (start.x < w * 0.4)
6569 { outward = -(80 + Math.random() * w * 0.25); }
6570 else if (start.x > w * 0.6)
6571 { outward = (80 + Math.random() * w * 0.25); }
6572 else
6573 { outward = (Math.random() * 2 - 1) * w * 0.35; }
6574 var lift = fromMini ? (80 + Math.random() * 160) : (120 + Math.random() * 220);
6575 return { x: start.x + outward, y: start.y - lift };
6576};
6577
6578Online._missCtrl = function (start, end)
6579{
6580 return {
6581 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
6582 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
6583 };
6584};
6585
6586Online._hitCtrl = function (start, end)
6587{
6588 return {
6589 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
6590 y: (start.y + end.y) / 2 - 30
6591 };
6592};
6593
6594Online._findFlight = function (sid)
6595{
6596 sid = String(sid);
6597 if (!this._flights)
6598 { return null; }
6599 for (var i = 0; i < this._flights.length; i++)
6600 {
6601 if (String(this._flights[i].id) === sid)
6602 { return this._flights[i]; }
6603 }
6604 return null;
6605};
6606
6607/**
6608 * True once a block has really left the field, matching cullOffTop
6609 * (y ≥ height, default 13). Used so an arc never starts for a
6610 * rocket that only peaked near the top and fell back (t1137).
6611 */
6612Online.EXIT_Y = 13;
6613Online.hasLeftTheField = function (y, height)
6614{
6615 height = height == null ? this.EXIT_Y : height;
6616 return y != null && isFinite(y) && y >= height - 1e-9;
6617};
6618
6619/**
6620 * Start a flight only at the true exit (y ≥ 13). Callers that pass
6621 * a rocket still on the field are ignored, so a fallback never
6622 * shows a phantom arc (t1137). The start pose is the exit cell,
6623 * continuing upward; retargetFlight aims it at the real target
6624 * if a preview was used in the same frame as cull.
6625 */
6626Online.previewExit = function (info)
6627{
6628 if (!info || info.id == null)
6629 { return null; }
6630 if (!this.hasLeftTheField(info.y))
6631 { return null; }
6632 var sid = String(info.id);
6633 if (!this._flights)
6634 { this._flights = []; }
6635 if (!this._flightSeen)
6636 { this._flightSeen = Object.create(null); }
6637 if (!this._previewIds)
6638 { this._previewIds = Object.create(null); }
6639 if (this._previewIds[sid] || this._flightSeen[sid])
6640 { return; }
6641 var front = document.getElementById('flights');
6642 if (!front || !info.start)
6643 { return; }
6644 var start = info.start;
6645 var field = this.playerFieldRect();
6646 var clearance = 80;
6647 if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD)
6648 { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); }
6649 var apexY = (field ? field.top : start.y) - clearance;
6650 if (apexY < 8)
6651 { apexY = Math.max(8, start.y - 80); }
6652 var end = { x: start.x, y: apexY };
6653 var duration = this.FLIGHT_DURATION * 1000;
6654 var full = this._fullTileSize();
6655 var el = document.createElement('img');
6656 el.src = colorSpriteUrl(info.color);
6657 el.alt = '';
6658 el.className = 'flight';
6659 el.style.width = full + 'px';
6660 el.style.height = full + 'px';
6661 front.appendChild(el);
6662 var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION);
6663 var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, {
6664 clearance: clearance
6665 });
6666 var easeRates = this.flightEaseRates(curve, this.FLIGHT_DURATION, endSpeed);
6667 var now = performance.now();
6668 var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1;
6669 if (mini < 0.12)
6670 { mini = 0.2; }
6671 this._flights.push({
6672 el: el,
6673 start: start,
6674 end: end,
6675 ctrl: null,
6676 height: clearance,
6677 t0: now,
6678 duration: duration,
6679 spin: (Math.random() * 2 - 1) * 90,
6680 miss: false,
6681 kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy',
6682 startScale: mini,
6683 endScale: mini,
6684 angle: 0,
6685 id: sid,
6686 landCol: null,
6687 field: field,
6688 curve: curve,
6689 easeRates: easeRates,
6690 preview: true,
6691 color: info.color,
6692 from_id: info.from_id || null
6693 });
6694 this._previewIds[sid] = true;
6695 this._flightSeen[sid] = now;
6696};
6697
6698/** True while a field sprite should stay hidden — the flight is its visual. */
6699Online.hasExitVisual = function (id)
6700{
6701 if (id == null)
6702 { return false; }
6703 var sid = String(id);
6704 if (this._previewIds && this._previewIds[sid])
6705 { return true; }
6706 var f = this._findFlight(sid);
6707 if (!f || f.miss)
6708 { return false; }
6709 var raw = (performance.now() - f.t0) / f.duration;
6710 return raw < 0.4;
6711};
6712
6713/**
6714 * Once the shot is scored, pick up the preview at its current pose
6715 * and fly the rest of the way to the real end (no jump).
6716 */
6717Online.retargetFlight = function (f, r, meta, now)
6718{
6719 now = now || performance.now();
6720 meta = meta || {};
6721 var raw = (now - f.t0) / f.duration;
6722 if (raw < 0)
6723 { raw = 0; }
6724 if (raw > 0.95)
6725 { raw = 0.95; }
6726 var u = this.smoothParam(raw, 0.9, 0.9);
6727 var pt = f.curve
6728 ? this.curvePoint(f.curve, u)
6729 : { x: f.start.x, y: f.start.y };
6730 var curScale = f.startScale + (f.endScale - f.startScale) * u;
6731
6732 var fromId = r.from_id || r.from_user || meta.from_id || f.from_id || null;
6733 var targetId = r.target_id != null ? r.target_id : r.to_user;
6734 var miss = !!r.miss;
6735 var kind = this.flightKind(fromId, targetId, miss);
6736 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
6737
6738 var landCol = null;
6739 if (r.land_col != null && isFinite(r.land_col))
6740 { landCol = r.land_col | 0; }
6741 else if (meta.land_col != null && isFinite(meta.land_col))
6742 { landCol = meta.land_col | 0; }
6743 else if (f.landCol != null)
6744 { landCol = f.landCol; }
6745 if (landCol != null)
6746 { this.rememberLandCol(String(f.id), landCol); }
6747
6748 var end;
6749 if (miss)
6750 { end = this._missEnd(pt, kind === 'enemy-miss'); }
6751 else if (kind === 'enemy-to-player')
6752 { end = this.fieldEntry(landCol != null ? landCol : 4.5); }
6753 else
6754 { end = this._targetEnd(targetId, pt, landCol); }
6755
6756 var flightColor = miss
6757 ? (r.color != null ? r.color : meta.color)
6758 : -1;
6759 if (f.el && flightColor !== f.color)
6760 { f.el.src = colorSpriteUrl(flightColor); }
6761
6762 var full = this._fullTileSize();
6763 var mini = this._miniCellSize(fromId || targetId) / full;
6764 if (mini < 0.12)
6765 { mini = 0.2; }
6766 var endScale;
6767 if (kind === 'player-to-enemy')
6768 { endScale = mini; }
6769 else if (kind === 'enemy-to-player')
6770 { endScale = 1; }
6771 else if (kind === 'enemy-to-enemy')
6772 { endScale = mini; }
6773 else
6774 { endScale = 0; }
6775
6776 var field = this.playerFieldRect();
6777 var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy');
6778 var height = miss
6779 ? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35))
6780 : this.arcHeight(pt, end);
6781 var clearance = Math.max(150, height * 0.55);
6782 var endSpeed = this._fallSpeedPx(field, duration / 1000);
6783 var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, {
6784 clearance: clearance
6785 });
6786 var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null;
6787
6788 f.start = pt;
6789 f.end = end;
6790 f.t0 = now;
6791 f.duration = duration;
6792 f.curve = curve;
6793 f.easeRates = easeRates;
6794 f.ctrl = miss ? this._missCtrl(pt, end) : null;
6795 f.height = height;
6796 f.miss = miss;
6797 f.kind = kind;
6798 f.startScale = curScale;
6799 f.endScale = endScale;
6800 f.landCol = landCol;
6801 f.field = field;
6802 f.preview = false;
6803 f.color = flightColor;
6804 f.from_id = fromId;
6805 if (this._previewIds)
6806 { delete this._previewIds[String(f.id)]; }
6807
6808 if (kind === 'enemy-to-enemy' && f.el)
6809 {
6810 var back = document.getElementById('flights-back');
6811 if (back && f.el.parentNode !== back)
6812 {
6813 f.el.className = 'flight flight-behind';
6814 back.appendChild(f.el);
6815 }
6816 }
6817};
6818
6819/** Point and (optional) derivative of a flight at parameter u. */
6820Online.flightPointAt = function (f, u)
6821{
6822 if (!f)
6823 { return { x: 0, y: 0 }; }
6824 if (f.curve)
6825 { return this.curvePoint(f.curve, u); }
6826 if (f.miss && f.ctrl)
6827 {
6828 var e = u;
6829 var mt = 1 - e;
6830 return {
6831 x: mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x,
6832 y: mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y
6833 };
6834 }
6835 return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
6836};
6837
6838Online.pointAllowedOnArc = function (p, field, start, end, slop)
6839{
6840 if (!this.pointInFieldInterior(p.x, p.y, field, slop))
6841 { return true; }
6842 if (!field)
6843 { return true; }
6844 var w = (field.right - field.left) / 10;
6845 var corridor = w * 0.7;
6846 if (start && Math.abs(p.x - start.x) <= corridor)
6847 { return true; }
6848 if (end && Math.abs(p.x - end.x) <= corridor)
6849 { return true; }
6850 return false;
6851};
6852
6853Online.tickFlights = function (now)
6854{
6855 now = now || performance.now();
6856 var leftover = [];
6857 for (var i = 0; i < this._flights.length; i++)
6858 {
6859 var f = this._flights[i];
6860 var raw = (now - f.t0) / f.duration;
6861 if (raw >= 1)
6862 {
6863 if (f.el && f.el.parentNode)
6864 { f.el.parentNode.removeChild(f.el); }
6865 if (this._previewIds)
6866 { delete this._previewIds[String(f.id)]; }
6867 continue;
6868 }
6869 if (raw < 0)
6870 { raw = 0; }
6871 // Non-zero endpoint speed so the handoff matches fallSpeed (t1135/t1138).
6872 var v0 = (f.easeRates && f.easeRates.v0 != null) ? f.easeRates.v0 : 0.85;
6873 var v1 = (f.easeRates && f.easeRates.v1 != null) ? f.easeRates.v1 : 0.85;
6874 var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, v0, v1);
6875 var x, y;
6876 if (f.miss && f.ctrl)
6877 {
6878 var e = raw * raw;
6879 var mt = 1 - e;
6880 x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
6881 y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
6882 }
6883 else if (f.curve)
6884 {
6885 var pt = this.curvePoint(f.curve, u);
6886 x = pt.x;
6887 y = pt.y;
6888 }
6889 else
6890 {
6891 var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45);
6892 x = pt.x;
6893 y = pt.y;
6894 }
6895 var scale = f.startScale + (f.endScale - f.startScale) * u;
6896 if (f.miss)
6897 {
6898 var fadeU = raw * raw;
6899 scale = f.startScale * (1 - fadeU);
6900 }
6901 var angle = f.angle + f.spin * raw;
6902 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
6903 + angle + 'deg) scale(' + scale + ')';
6904 f.el.style.opacity = f.miss ? String(Math.max(0, 1 - raw * raw)) : '1';
6905 leftover.push(f);
6906 }
6907 this._flights = leftover;
6908 if (this._flightSeen)
6909 {
6910 var cutoff = now - 8000;
6911 var ids = Object.keys(this._flightSeen);
6912 for (var k = 0; k < ids.length; k++)
6913 {
6914 if (this._flightSeen[ids[k]] < cutoff)
6915 { delete this._flightSeen[ids[k]]; }
6916 }
6917 }
6918};
6919
6920Online.clearFlights = function ()
6921{
6922 for (var i = 0; i < this._flights.length; i++)
6923 {
6924 var el = this._flights[i].el;
6925 if (el && el.parentNode)
6926 { el.parentNode.removeChild(el); }
6927 }
6928 this._flights = [];
6929 this._flightLocals = {};
6930 this._flightSeen = Object.create(null);
6931 this._pendingLandCol = Object.create(null);
6932 this._previewIds = Object.create(null);
6933};
6934
6935if (typeof globalThis !== 'undefined')
6936{ globalThis.Online = Online; }
6937if (typeof module !== 'undefined' && module.exports)
6938{ module.exports = Online; }
6939
6940/*
6941 * End File:
6942 * /workspace/meteors/src/online.js
6943 */
6944
6945/*
6946 * Start File:
6947 * /workspace/meteors/src/offline.js
6948 */
6949'use strict';
6950
6951/**
6952 * Offline Strijd: a client-side single-player mode that plays like
6953 * multiplayer (shots, miss chance, opponent minis) against local bots
6954 * (t1119). Pure simulation — no server.
6955 */
6956
6957var Offline = (function ()
6958{
6959
6960var BOT_INTERVAL = 0.5;
6961var SKILL_START = 0.05;
6962var SKILL_STEP = 0.01;
6963var SKILL_CAP = 1;
6964var FLIGHT_DURATION = 1.2;
6965var ROUND_WON_DELAY = 1.5;
6966
6967/**
6968 * N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round.
6969 * Documented in docs/ASSUMPTIONS.md (t1119).
6970 */
6971function roundsAtOpponentCount (n)
6972{
6973 if (n <= 1)
6974 { return 1; }
6975 return n - 1;
6976}
6977
6978function skillForRound (round)
6979{
6980 var r = Math.max(1, Math.floor(Number(round) || 1));
6981 var pct = 5 + (r - 1);
6982 if (pct > 100)
6983 { pct = 100; }
6984 return pct / 100;
6985}
6986
6987function scheduleForRound (round)
6988{
6989 var r = Math.max(1, Math.floor(Number(round) || 1));
6990 var cursor = 1;
6991 var n = 1;
6992 for (;;)
6993 {
6994 var count = roundsAtOpponentCount(n);
6995 if (r < cursor + count)
6996 {
6997 return {
6998 round: r,
6999 opponents: n,
7000 skill: skillForRound(r),
7001 roundsAtLevel: count,
7002 indexInLevel: r - cursor + 1
7003 };
7004 }
7005 cursor += count;
7006 n++;
7007 if (n > 10000)
7008 {
7009 return {
7010 round: r,
7011 opponents: n,
7012 skill: SKILL_CAP,
7013 roundsAtLevel: roundsAtOpponentCount(n),
7014 indexInLevel: 1
7015 };
7016 }
7017 }
7018}
7019
7020function GameCoreCtor ()
7021{
7022 if (typeof GameCore !== 'undefined')
7023 { return GameCore; }
7024 if (typeof module !== 'undefined')
7025 { return require('./gameCore.js').GameCore; }
7026 return null;
7027}
7028
7029function PlanetMod ()
7030{
7031 if (typeof Planet !== 'undefined')
7032 { return Planet; }
7033 if (typeof module !== 'undefined')
7034 { return require('./planet.js'); }
7035 return null;
7036}
7037
7038/**
7039 * Integer-row colour grid of grounded (still / settling / locked)
7040 * blocks, including greys (color < 0) so a swap can shift them.
7041 */
7042function snapshotGrid (core)
7043{
7044 var width = core.width;
7045 var height = core.height;
7046 var grid = [];
7047 for (var c = 0; c < width; c++)
7048 {
7049 grid[c] = [];
7050 for (var r = 0; r < height; r++)
7051 { grid[c][r] = null; }
7052 }
7053 for (var i = 0; i < core.blocks.length; i++)
7054 {
7055 var b = core.blocks[i];
7056 if (!core.isGrounded(b))
7057 { continue; }
7058 var row = Math.round(b.y);
7059 if (row < 0 || row >= height || b.col < 0 || b.col >= width)
7060 { continue; }
7061 if (Math.abs(b.y - row) > 0.2)
7062 { continue; }
7063 grid[b.col][row] = b.color;
7064 }
7065 return grid;
7066}
7067
7068function cloneGrid (grid)
7069{
7070 var out = [];
7071 for (var c = 0; c < grid.length; c++)
7072 { out[c] = grid[c].slice(); }
7073 return out;
7074}
7075
7076/**
7077 * Apply swapToward's net result: the block at fromRow moves to toRow,
7078 * and the blocks it passed through each shift one cell toward fromRow.
7079 */
7080function applyColumnMove (grid, col, fromRow, toRow)
7081{
7082 if (fromRow === toRow)
7083 { return; }
7084 var moving = grid[col][fromRow];
7085 if (toRow > fromRow)
7086 {
7087 for (var y = fromRow; y < toRow; y++)
7088 { grid[col][y] = grid[col][y + 1]; }
7089 grid[col][toRow] = moving;
7090 }
7091 else
7092 {
7093 for (var y = fromRow; y > toRow; y--)
7094 { grid[col][y] = grid[col][y - 1]; }
7095 grid[col][toRow] = moving;
7096 }
7097}
7098
7099function hasMatch (grid, width, height)
7100{
7101 var c, r, run, prev;
7102 for (r = 0; r < height; r++)
7103 {
7104 run = 0;
7105 prev = null;
7106 for (c = 0; c < width; c++)
7107 {
7108 var color = grid[c][r];
7109 if (color != null && color >= 0 && color === prev)
7110 {
7111 run++;
7112 if (run >= 3)
7113 { return true; }
7114 }
7115 else
7116 {
7117 run = (color != null && color >= 0) ? 1 : 0;
7118 prev = (color != null && color >= 0) ? color : null;
7119 }
7120 }
7121 }
7122 for (c = 0; c < width; c++)
7123 {
7124 run = 0;
7125 prev = null;
7126 for (r = 0; r < height; r++)
7127 {
7128 var color = grid[c][r];
7129 if (color != null && color >= 0 && color === prev)
7130 {
7131 run++;
7132 if (run >= 3)
7133 { return true; }
7134 }
7135 else
7136 {
7137 run = (color != null && color >= 0) ? 1 : 0;
7138 prev = (color != null && color >= 0) ? color : null;
7139 }
7140 }
7141 }
7142 return false;
7143}
7144
7145/**
7146 * Contiguous segments of draggable, nearly-integer-y blocks in a
7147 * column. Gaps break a segment the same way swapToward stops at gaps.
7148 */
7149function contiguousSegments (core, col)
7150{
7151 if (!core.columnAllowsDrag(col))
7152 { return []; }
7153 var list = core.blocksInColumn(col).filter(function (b)
7154 {
7155 return core.isDraggableBlock(b);
7156 });
7157 list.sort(function (a, b) { return a.y - b.y; });
7158 var segs = [];
7159 var cur = [];
7160 for (var i = 0; i < list.length; i++)
7161 {
7162 var y = list[i].y;
7163 if (Math.abs(y - Math.round(y)) > 0.15)
7164 {
7165 if (cur.length)
7166 {
7167 segs.push(cur);
7168 cur = [];
7169 }
7170 continue;
7171 }
7172 if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15)
7173 {
7174 segs.push(cur);
7175 cur = [list[i]];
7176 }
7177 else
7178 { cur.push(list[i]); }
7179 }
7180 if (cur.length)
7181 { segs.push(cur); }
7182 return segs;
7183}
7184
7185/**
7186 * The shortest vertical move that would create a 3+ match, or null.
7187 * Ties break on lowest column, then lowest fromY, then lowest toY.
7188 */
7189function findBotMove (core)
7190{
7191 var grid = snapshotGrid(core);
7192 if (hasMatch(grid, core.width, core.height))
7193 { return null; }
7194 var best = null;
7195 for (var col = 0; col < core.width; col++)
7196 {
7197 var segs = contiguousSegments(core, col);
7198 for (var s = 0; s < segs.length; s++)
7199 {
7200 var seg = segs[s];
7201 if (seg.length < 2)
7202 { continue; }
7203 for (var i = 0; i < seg.length; i++)
7204 {
7205 var fromY = Math.round(seg[i].y);
7206 for (var j = 0; j < seg.length; j++)
7207 {
7208 if (i === j)
7209 { continue; }
7210 var toY = Math.round(seg[j].y);
7211 var dist = Math.abs(toY - fromY);
7212 if (best && dist > best.dist)
7213 { continue; }
7214 var trial = cloneGrid(grid);
7215 applyColumnMove(trial, col, fromY, toY);
7216 if (!hasMatch(trial, core.width, core.height))
7217 { continue; }
7218 var cand = {
7219 col: col,
7220 fromY: fromY,
7221 toY: toY,
7222 dist: dist,
7223 blockId: seg[i].id
7224 };
7225 if (!best || dist < best.dist
7226 || (dist === best.dist && col < best.col)
7227 || (dist === best.dist && col === best.col && fromY < best.fromY)
7228 || (dist === best.dist && col === best.col && fromY === best.fromY
7229 && toY < best.toY))
7230 { best = cand; }
7231 }
7232 }
7233 }
7234 }
7235 return best;
7236}
7237
7238function executeBotMove (core, move)
7239{
7240 if (!core || !move)
7241 { return false; }
7242 var list = core.blocksInColumn(move.col);
7243 var block = null;
7244 for (var i = 0; i < list.length; i++)
7245 {
7246 if (move.blockId != null && list[i].id === move.blockId)
7247 {
7248 block = list[i];
7249 break;
7250 }
7251 if (Math.abs(list[i].y - move.fromY) < 0.2)
7252 { block = list[i]; }
7253 }
7254 if (!block || !core.isDraggableBlock(block))
7255 { return false; }
7256 core.swapToward(block, move.toY);
7257 return true;
7258}
7259
7260/**
7261 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
7262 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
7263 */
7264function tryBotRoll (core, skill, rng)
7265{
7266 rng = rng || Math.random;
7267 var roll = rng();
7268 if (!(roll < skill))
7269 {
7270 return { rolled: true, success: false, moved: false, roll: roll, move: null };
7271 }
7272 var move = findBotMove(core);
7273 if (!move)
7274 {
7275 return { rolled: true, success: true, moved: false, roll: roll, move: null };
7276 }
7277 var ok = executeBotMove(core, move);
7278 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
7279}
7280
7281function pickPlanet (rng, P)
7282{
7283 var all = P.allPlanets();
7284 if (!all.length)
7285 { return P.defaultPlanet(); }
7286 var i = Math.floor(rng() * all.length) % all.length;
7287 return all[i];
7288}
7289
7290function OfflineBattle (opts)
7291{
7292 opts = opts || {};
7293 var P = PlanetMod();
7294 this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet());
7295 this.rng = opts.rng || Math.random;
7296 this.round = opts.round || 1;
7297 this.schedule = scheduleForRound(this.round);
7298 this.clock = 0;
7299 this.state = 'playing';
7300 this.pending = [];
7301 this.flightResults = [];
7302 this.shotLocals = [];
7303 this.bots = [];
7304 this.playerId = 'player';
7305 this._initBots();
7306}
7307
7308OfflineBattle.prototype._initBots = function ()
7309{
7310 var P = PlanetMod();
7311 var Ctor = GameCoreCtor();
7312 var n = this.schedule.opponents;
7313 this.bots = [];
7314 for (var i = 0; i < n; i++)
7315 {
7316 var planet = pickPlanet(this.rng, P);
7317 var miss = P.missChance(planet);
7318 var core = new Ctor(planet, this.rng, miss);
7319 this.bots.push({
7320 id: 'bot-' + (i + 1),
7321 name: 'Bot ' + (i + 1),
7322 planet: planet,
7323 core: core,
7324 eliminated: false,
7325 score: 0,
7326 aiAcc: 0
7327 });
7328 }
7329};
7330
7331OfflineBattle.prototype.aliveBots = function ()
7332{
7333 var out = [];
7334 for (var i = 0; i < this.bots.length; i++)
7335 {
7336 if (!this.bots[i].eliminated && this.bots[i].core
7337 && this.bots[i].core.state !== 'gameover')
7338 { out.push(this.bots[i]); }
7339 }
7340 return out;
7341};
7342
7343OfflineBattle.prototype.coreFor = function (id, playerCore)
7344{
7345 if (id === this.playerId)
7346 { return playerCore; }
7347 for (var i = 0; i < this.bots.length; i++)
7348 {
7349 if (this.bots[i].id === id)
7350 { return this.bots[i].core; }
7351 }
7352 return null;
7353};
7354
7355OfflineBattle.prototype._targetsFor = function (fromId, playerCore)
7356{
7357 var targets = [];
7358 if (fromId !== this.playerId && playerCore && playerCore.state === 'playing')
7359 { targets.push({ id: this.playerId, core: playerCore }); }
7360 for (var i = 0; i < this.bots.length; i++)
7361 {
7362 var bot = this.bots[i];
7363 if (bot.id === fromId || bot.eliminated)
7364 { continue; }
7365 if (bot.core && bot.core.state === 'playing')
7366 { targets.push({ id: bot.id, core: bot.core }); }
7367 }
7368 return targets;
7369};
7370
7371OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore)
7372{
7373 if (!core || !core.consumeOutgoingShots)
7374 { return; }
7375 var shots = core.consumeOutgoingShots();
7376 if (!shots.length)
7377 { return; }
7378 var P = PlanetMod();
7379 var missChance = (P && planet) ? P.missChance(planet) : 0.30;
7380 var targets = this._targetsFor(fromId, playerCore);
7381 for (var i = 0; i < shots.length; i++)
7382 {
7383 var shot = shots[i];
7384 var miss = targets.length === 0 || this.rng() < missChance;
7385 var target = null;
7386 if (!miss)
7387 {
7388 var idx = Math.floor(this.rng() * targets.length) % targets.length;
7389 target = targets[idx];
7390 }
7391 var clientId = fromId + '-' + shot.id + '-' + this.clock;
7392 var landCol = null;
7393 if (!miss && target && target.core && target.core.pickGarbageColumn)
7394 { landCol = target.core.pickGarbageColumn(); }
7395 var result = {
7396 client_id: clientId,
7397 miss: miss,
7398 target_id: target ? target.id : null,
7399 color: shot.color,
7400 flight_duration: FLIGHT_DURATION,
7401 from_id: fromId,
7402 col: shot.col,
7403 y: shot.y,
7404 land_col: landCol
7405 };
7406 this.flightResults.push(result);
7407 this.shotLocals.push({
7408 client_id: clientId,
7409 col: shot.col,
7410 y: shot.y,
7411 color: shot.color,
7412 from_id: fromId,
7413 land_col: landCol
7414 });
7415 if (!miss && target)
7416 {
7417 this.pending.push({
7418 at: this.clock + FLIGHT_DURATION,
7419 targetId: target.id,
7420 color: shot.color,
7421 fromId: fromId,
7422 landCol: landCol
7423 });
7424 }
7425 }
7426};
7427
7428OfflineBattle.prototype._deliver = function (playerCore)
7429{
7430 var keep = [];
7431 for (var i = 0; i < this.pending.length; i++)
7432 {
7433 var ev = this.pending[i];
7434 if (this.clock + 1e-9 < ev.at)
7435 {
7436 keep.push(ev);
7437 continue;
7438 }
7439 var core = this.coreFor(ev.targetId, playerCore);
7440 if (core && core.state === 'playing' && core.ingestGarbage)
7441 { core.ingestGarbage(ev.landCol); }
7442 }
7443 this.pending = keep;
7444};
7445
7446OfflineBattle.prototype.tick = function (dt, playerCore)
7447{
7448 this.flightResults = [];
7449 this.shotLocals = [];
7450 if (this.state !== 'playing')
7451 { return { flights: [], locals: [] }; }
7452 if (dt < 0)
7453 { dt = 0; }
7454 this.clock += dt;
7455
7456 var skill = this.schedule.skill;
7457 for (var i = 0; i < this.bots.length; i++)
7458 {
7459 var bot = this.bots[i];
7460 if (bot.eliminated)
7461 { continue; }
7462 if (bot.core.state === 'gameover')
7463 {
7464 bot.eliminated = true;
7465 bot.score = bot.core.score;
7466 continue;
7467 }
7468 bot.core.tick(dt);
7469 bot.score = bot.core.score;
7470 bot.aiAcc += dt;
7471 while (bot.aiAcc >= BOT_INTERVAL)
7472 {
7473 bot.aiAcc -= BOT_INTERVAL;
7474 if (bot.core.state === 'playing' && !bot.core.drag)
7475 { tryBotRoll(bot.core, skill, this.rng); }
7476 }
7477 }
7478
7479 this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore);
7480 for (var i = 0; i < this.bots.length; i++)
7481 {
7482 var bot = this.bots[i];
7483 if (bot.eliminated)
7484 { continue; }
7485 this._dispatchShots(bot.id, bot.core, bot.planet, playerCore);
7486 }
7487 this._deliver(playerCore);
7488
7489 for (var i = 0; i < this.bots.length; i++)
7490 {
7491 if (this.bots[i].core && this.bots[i].core.state === 'gameover')
7492 {
7493 this.bots[i].eliminated = true;
7494 this.bots[i].score = this.bots[i].core.score;
7495 }
7496 }
7497
7498 if (playerCore && playerCore.state === 'gameover')
7499 { this.state = 'lost'; }
7500 else if (this.aliveBots().length === 0 && this.bots.length > 0)
7501 { this.state = 'round_won'; }
7502
7503 return { flights: this.flightResults, locals: this.shotLocals };
7504};
7505
7506/**
7507 * Start the next round (fresh bots, new skill and opponent count).
7508 * The caller must also give the player a fresh GameCore.
7509 */
7510OfflineBattle.prototype.advanceRound = function ()
7511{
7512 this.round += 1;
7513 this.schedule = scheduleForRound(this.round);
7514 this.state = 'playing';
7515 this.pending = [];
7516 this.flightResults = [];
7517 this.shotLocals = [];
7518 this.clock = 0;
7519 this._initBots();
7520 return this.schedule;
7521};
7522
7523function createBattle (opts)
7524{
7525 return new OfflineBattle(opts);
7526}
7527
7528var api = {
7529 BOT_INTERVAL: BOT_INTERVAL,
7530 SKILL_START: SKILL_START,
7531 SKILL_STEP: SKILL_STEP,
7532 SKILL_CAP: SKILL_CAP,
7533 FLIGHT_DURATION: FLIGHT_DURATION,
7534 ROUND_WON_DELAY: ROUND_WON_DELAY,
7535 roundsAtOpponentCount: roundsAtOpponentCount,
7536 skillForRound: skillForRound,
7537 scheduleForRound: scheduleForRound,
7538 findBotMove: findBotMove,
7539 tryBotRoll: tryBotRoll,
7540 executeBotMove: executeBotMove,
7541 snapshotGrid: snapshotGrid,
7542 applyColumnMove: applyColumnMove,
7543 hasMatch: hasMatch,
7544 createBattle: createBattle,
7545 OfflineBattle: OfflineBattle
7546};
7547
7548if (typeof module !== 'undefined' && module.exports)
7549{ module.exports = api; }
7550else if (typeof globalThis !== 'undefined')
7551{ globalThis.Offline = api; }
7552
7553return api;
7554
7555})();
7556
7557if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined')
7558{ module.exports = Offline; }
7559
7560/*
7561 * End File:
7562 * /workspace/meteors/src/offline.js
7563 */
7564
7565/*
7566 * Start File:
7567 * /workspace/meteors/src/designer.js
7568 */
7569'use strict';
7570
7571/**
7572 * Planeetontwerper (t1139). Only available on the main menu when the
7573 * player is logged in. Talks to api.php through Online.
7574 */
7575var Designer = {
7576 openSlot: 0,
7577 editingId: null,
7578 slots: [null, null, null, null, null],
7579 dirty: false
7580};
7581
7582Designer._blocks = function ()
7583{
7584 if (typeof Blocks !== 'undefined')
7585 { return Blocks; }
7586 if (typeof require !== 'undefined')
7587 {
7588 try
7589 { return require('./blocks.js'); }
7590 catch (e)
7591 { return null; }
7592 }
7593 return null;
7594};
7595
7596Designer.defaultSlots = function ()
7597{
7598 var B = Designer._blocks();
7599 var all = B ? B.all() : [];
7600 var ids = [];
7601 for (var i = 0; i < 5 && i < all.length; i++)
7602 { ids.push(all[i].id); }
7603 return ids;
7604};
7605
7606Designer.points = function ()
7607{
7608 return (typeof Online !== 'undefined' && Online.lifetimePoints) || 0;
7609};
7610
7611Designer.blocks = function ()
7612{
7613 if (typeof Online !== 'undefined' && Online.blocks && Online.blocks.length)
7614 { return Online.blocks; }
7615 var B = Designer._blocks();
7616 if (B)
7617 { return B.present(Designer.points()); }
7618 return [];
7619};
7620
7621Designer.planets = function ()
7622{
7623 if (typeof Planet !== 'undefined' && Planet.customPlanets)
7624 { return Planet.customPlanets(); }
7625 return (typeof Online !== 'undefined' && Online.planets) || [];
7626};
7627
7628Designer.openList = function ()
7629{
7630 if (typeof Online === 'undefined' || !Online.me)
7631 { return; }
7632 if (typeof app !== 'undefined')
7633 { app.mode = 'designer'; }
7634 hideIf('menu');
7635 hideIf('planet-select');
7636 hideIf('online-panel');
7637 hideIf('designer-edit');
7638 showIf('designer');
7639 Designer.renderList();
7640};
7641
7642Designer.close = function ()
7643{
7644 hideIf('designer');
7645 hideIf('designer-edit');
7646 Designer.closeModal();
7647 if (typeof app !== 'undefined')
7648 { app.mode = 'menu'; }
7649 showIf('menu');
7650 if (typeof refreshMenuAccount === 'function')
7651 { refreshMenuAccount(); }
7652 if (typeof renderPlanetGrid === 'function')
7653 {
7654 renderPlanetGrid('planet-grid', false);
7655 renderPlanetGrid('lobby-planet-grid', true);
7656 }
7657};
7658
7659Designer.renderList = function ()
7660{
7661 var box = document.getElementById('designer-list');
7662 var pts = document.getElementById('designer-points');
7663 if (pts)
7664 { pts.textContent = String(Designer.points()); }
7665 if (!box)
7666 { return; }
7667 box.innerHTML = '';
7668 var planets = Designer.planets();
7669 if (!planets.length)
7670 {
7671 var empty = document.createElement('p');
7672 empty.className = 'hint';
7673 empty.textContent = 'Je hebt nog geen eigen planeten. Maak er een aan.';
7674 box.appendChild(empty);
7675 return;
7676 }
7677 for (var i = 0; i < planets.length; i++)
7678 {
7679 var pl = planets[i];
7680 if (typeof Planet !== 'undefined' && Planet.planetF
7681… afgekapt