BlueGit

projects-timfalken-com meteors

Files

meteors / build / game.js

game.js

game.js 177.0 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;
190
191/*
192 * Start File:
193 * /workspace/meteors/src/rng.js
194 */
195'use strict';
196
197/**
198 * Seedable mulberry32 RNG, so the game core stays deterministic in tests
199 * and (later) for multiplayer replays.
200 */
201function createRng (seed)
202{
203 var a = (seed >>> 0) || 1;
204 return function rng ()
205 {
206 a |= 0;
207 a = a + 0x6D2B79F5 | 0;
208 var t = Math.imul(a ^ a >>> 15, 1 | a);
209 t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
210 return ((t ^ t >>> 14) >>> 0) / 4294967296;
211 };
212}
213
214function pickIndex (rng, count)
215{
216 var n = count | 0;
217 if (n <= 0)
218 { return 0; }
219 return Math.floor(rng() * n) % n;
220}
221
222function pickFrom (rng, list)
223{
224 if (!list || !list.length)
225 { return undefined; }
226 return list[pickIndex(rng, list.length)];
227}
228
229var Rng = {
230 create: createRng,
231 pickIndex: pickIndex,
232 pickFrom: pickFrom
233};
234
235if (typeof module !== 'undefined' && module.exports)
236{ module.exports = Rng; }
237else if (typeof globalThis !== 'undefined')
238{ globalThis.Rng = Rng; }
239
240/*
241 * End File:
242 * /workspace/meteors/src/rng.js
243 */
244
245/*
246 * Start File:
247 * /workspace/meteors/src/planet.js
248 */
249'use strict';
250
251/**
252 * Planet physics and visuals for Meteors.
253 *
254 * Stage 1 uses a single default planet. Stage 3 lets the player pick a
255 * planet; the numbers and jump-height rules are already applied here so
256 * that later planets only need new data, not new physics code.
257 *
258 * Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump).
259 * A horizontal match of 3 jumps JUMP_HEIGHT_SCALE * FIELD_HEIGHT
260 * / jumpsToClear tiles (JUMP_HEIGHT_SCALE is 1.5 since t1119: the
261 * minimum jump is 50% higher). At gravity 1 that is 19.5 tiles, so
262 * one jump from the floor clears the 13-tile field with room to spare;
263 * at 4 you still need more than one jump, but each is 50% taller.
264 * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
265 * After a jump peaks, blocks float down at DESCENT_SPEED_SCALE *
266 * FIELD_HEIGHT / fallTime tiles/s (DESCENT_SPEED_SCALE is 0.5 since
267 * t1122: all descent speeds are halved). Relative differences between
268 * planets (1 / fallTime) are unchanged. Upward launch is not affected.
269 * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
270 * Time to reach the apex, independent of jump height.
271 *
272 * Jump-height multipliers (never explained in the game):
273 * A vertical match of 3 is 120 % of a horizontal row of 3.
274 * Each extra block beyond 3 adds 5 %.
275 *
276 * Power is the average of the three difficulty axes (0 easy .. 1 hard)
277 * and is shown as a percentage. Miss chance (stage 2) goes from 60 % at
278 * power 0 to 5 % at power 1.
279 */
280
281var FIELD_WIDTH = 10;
282var FIELD_HEIGHT = 13;
283/** t1119: every match jump (the gravity-applied minimum and the
284 * vertical / extra-block bonuses derived from it) is 50% higher. */
285var JUMP_HEIGHT_SCALE = 1.5;
286/** t1122: every descent speed is halved. Terminal fallSpeed, spawn
287 * fall, unsupported / released / cargo fall, and the post-apex
288 * float-down all use this scale. Upward launch is unchanged. */
289var DESCENT_SPEED_SCALE = 0.5;
290
291
292function clamp (value, lo, hi)
293{
294 return Math.max(lo, Math.min(hi, value));
295}
296
297function defaultColors ()
298{
299 return [
300 { id: 0, name: 'ember', hex: '#e85d3a', shape: 'triangle', image: 'images/block-ember.png' },
301 { id: 1, name: 'aqua', hex: '#3db8e8', shape: 'circle', image: 'images/block-aqua.png' },
302 { id: 2, name: 'leaf', hex: '#4cbf4c', shape: 'square', image: 'images/block-leaf.png' },
303 { id: 3, name: 'sun', hex: '#f0c53a', shape: 'diamond', image: 'images/block-sun.png' },
304 { id: 4, name: 'orchid', hex: '#c45ad4', shape: 'star', image: 'images/block-orchid.png' }
305 ];
306}
307
308function createPlanet (opts)
309{
310 opts = opts || {};
311 var jumpsToClear = clamp(opts.jumpsToClear == null ? 2 : opts.jumpsToClear, 1, 4);
312 var fallTime = clamp(opts.fallTime == null ? 3 : opts.fallTime, 1, 5);
313 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
314 var colors = opts.colors || defaultColors();
315 var planet = {
316 id: opts.id || null,
317 name: opts.name || 'Terra',
318 people: opts.people || 'Terrans',
319 jumpsToClear: jumpsToClear,
320 fallTime: fallTime,
321 riseTime: riseTime,
322 colors: colors,
323 baseJumpHeight: JUMP_HEIGHT_SCALE * FIELD_HEIGHT / jumpsToClear,
324 fallSpeed: DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime,
325 // Time to ease from vy=0 at the apex to terminal fallSpeed.
326 // Shorter when air resistance is low (small fallTime). The ease
327 // duration is unchanged; fallAccel scales with the halved
328 // fallSpeed so the ease still lasts apexEaseTime seconds.
329 apexEaseTime: 0.15 * fallTime,
330 fallAccel: (DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
331 // Visual landing bounce: faster at low air resistance. Stage-3 params.
332 bounceDuration: 0.12 * fallTime,
333 bounceSquash: 0.16
334 };
335 return planet;
336}
337
338function loadCatalog ()
339{
340 if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
341 { return PLANET_CATALOG; }
342 if (typeof require !== 'undefined')
343 {
344 try
345 { return require('../server/lib/planets.json'); }
346 catch (e) {}
347 }
348 return { planets: [] };
349}
350
351function planetFromData (data)
352{
353 var planet = createPlanet({
354 name: data.name,
355 people: data.people,
356 jumpsToClear: data.jumpsToClear,
357 fallTime: data.fallTime,
358 riseTime: data.riseTime,
359 colors: data.colors
360 });
361 planet.id = data.id;
362 return planet;
363}
364
365function allPlanets ()
366{
367 var raw = loadCatalog().planets || [];
368 var out = [];
369 for (var i = 0; i < raw.length; i++)
370 { out.push(planetFromData(raw[i])); }
371 if (out.length === 0)
372 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
373 return out;
374}
375
376function planetById (id)
377{
378 var all = allPlanets();
379 for (var i = 0; i < all.length; i++)
380 {
381 if (all[i].id === id)
382 { return all[i]; }
383 }
384 return defaultPlanet();
385}
386
387function defaultPlanet ()
388{
389 var all = allPlanets();
390 for (var i = 0; i < all.length; i++)
391 {
392 if (all[i].id === 'terra')
393 { return all[i]; }
394 }
395 return all[0];
396}
397
398function formatStats (planet)
399{
400 var d = displayValues(planet);
401 return 'g ' + d.gravity.toFixed(2)
402 + ' d ' + d.density.toFixed(2)
403 + ' F ' + Math.round(d.newtons) + ' N'
404 + ' Power ' + d.power + '%';
405}
406
407function spriteKey (planet, colorIndex)
408{
409 var colors = planet && planet.colors;
410 var c = colors && colors[colorIndex];
411 if (!c)
412 { return 'gray'; }
413 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
414}
415
416/**
417 * Jump height in tiles for a match line.
418 * @param {object} planet
419 * @param {number} matchLength number of blocks in the line (>= 3)
420 * @param {boolean} vertical true for a vertical line
421 */
422function jumpHeight (planet, matchLength, vertical)
423{
424 var extra = Math.max(0, (matchLength | 0) - 3);
425 var multiplier = (vertical ? 1.2 : 1.0) + 0.05 * extra;
426 return planet.baseJumpHeight * multiplier;
427}
428
429/** Initial upward speed (tiles/s) so a jump of `height` peaks in riseTime. */
430function launchVelocity (planet, height)
431{
432 if (height <= 0)
433 { return 0; }
434 return (2 * height) / planet.riseTime;
435}
436
437/** Constant deceleration (tiles/s^2) paired with launchVelocity. */
438function launchDeceleration (planet, height)
439{
440 if (height <= 0)
441 { return 0; }
442 return (2 * height) / (planet.riseTime * planet.riseTime);
443}
444
445/**
446 * Difficulty power in 0..1. Higher is harder (and, in stage 2, a lower
447 * chance that a shot-off block misses the opponent).
448 */
449function power (planet)
450{
451 var gravity = (planet.jumpsToClear - 1) / 3;
452 var air = (5 - planet.fallTime) / 4;
453 var mass = (3 - planet.riseTime) / 2.5;
454 return (gravity + air + mass) / 3;
455}
456
457/** Maximum miss chance, used by the gameplay formula and the displayed Power. */
458var MAX_MISS_CHANCE = 0.60;
459var MIN_MISS_CHANCE = 0.05;
460
461/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */
462function missChance (planet)
463{
464 return MAX_MISS_CHANCE - (MAX_MISS_CHANCE - MIN_MISS_CHANCE) * power(planet);
465}
466
467/**
468 * Displayed Power, as a 0–100 percentage. This is the complement of the
469 * miss chance against the maximum (60%): 0% miss → 100% Power, 60% miss
470 * → 0% Power. The gameplay power() and missChance() formulas are unchanged.
471 */
472function displayPower (planet)
473{
474 return Math.round((1 - missChance(planet) / MAX_MISS_CHANCE) * 100);
475}
476
477/**
478 * Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),
479 * launch force (N), and displayed Power as a percentage. The numbers do
480 * not have to explain themselves.
481 */
482function displayValues (planet)
483{
484 var gravity = 9.81 * planet.jumpsToClear / 2;
485 var density = 0.25 + ((5 - planet.fallTime) / 4) * 1.60;
486 var newtons = 40 + ((planet.riseTime - 0.5) / 2.5) * 160;
487 return {
488 gravity: gravity,
489 density: density,
490 newtons: newtons,
491 power: displayPower(planet),
492 missChance: missChance(planet)
493 };
494}
495
496var Planet = {
497 FIELD_WIDTH: FIELD_WIDTH,
498 FIELD_HEIGHT: FIELD_HEIGHT,
499 JUMP_HEIGHT_SCALE: JUMP_HEIGHT_SCALE,
500 DESCENT_SPEED_SCALE: DESCENT_SPEED_SCALE,
501 COLOR_COUNT: 5,
502 SETTLE_TIME: 3,
503 SPAWN_INTERVAL: 1,
504 JUMP_VERTICAL_BONUS: 1.2,
505 JUMP_EXTRA_BLOCK: 0.05,
506 createPlanet: createPlanet,
507 defaultPlanet: defaultPlanet,
508 defaultColors: defaultColors,
509 allPlanets: allPlanets,
510 planetById: planetById,
511 planetFromData: planetFromData,
512 formatStats: formatStats,
513 spriteKey: spriteKey,
514 jumpHeight: jumpHeight,
515 launchVelocity: launchVelocity,
516 launchDeceleration: launchDeceleration,
517 MAX_MISS_CHANCE: MAX_MISS_CHANCE,
518 MIN_MISS_CHANCE: MIN_MISS_CHANCE,
519 power: power,
520 missChance: missChance,
521 displayPower: displayPower,
522 displayValues: displayValues
523};
524
525if (typeof module !== 'undefined' && module.exports)
526{ module.exports = Planet; }
527else if (typeof globalThis !== 'undefined')
528{ globalThis.Planet = Planet; }
529
530/*
531 * End File:
532 * /workspace/meteors/src/planet.js
533 */
534
535/*
536 * Start File:
537 * /workspace/meteors/src/easing.js
538 */
539'use strict';
540
541/**
542 * Easing curves matching Qt QEasingCurve defaults (the same values Tim's
543 * KWin Click Tween effect uses). Formulas and default parameters come from
544 * Qt 6's QEasingCurve and https://easings.net/.
545 *
546 * Source of the click/release defaults:
547 * /workspace/click-tween/settings.h (clickTime, releaseTime, easing names)
548 * /workspace/click-tween/clicktween.cpp (press scale 0.8, release scale 1.0)
549 * /workspace/click-tween/README.md
550 */
551
552/** Qt QEasingCurve default overshoot for InBack / OutBack / InOutBack. */
553var BACK_OVERSHOOT = 1.70158;
554
555/** Qt QEasingCurve default period and amplitude for Elastic curves. */
556var ELASTIC_PERIOD = 0.3;
557var ELASTIC_AMPLITUDE = 1.0;
558
559function clamp01 (t)
560{
561 if (t <= 0)
562 { return 0; }
563 if (t >= 1)
564 { return 1; }
565 return t;
566}
567
568/** easeOutBack: overshoots the end value, then settles. Qt / easings.net. */
569function easeOutBack (t)
570{
571 t = clamp01(t);
572 var c1 = BACK_OVERSHOOT;
573 var c3 = c1 + 1;
574 var u = t - 1;
575 return 1 + c3 * u * u * u + c1 * u * u;
576}
577
578/**
579 * easeOutElastic: decaying sine overshoot past the end value.
580 * Qt default amplitude 1, period 0.3 (equivalent to easings.net).
581 */
582function easeOutElastic (t)
583{
584 t = clamp01(t);
585 if (t === 0 || t === 1)
586 { return t; }
587 var p = ELASTIC_PERIOD;
588 var s = p / 4;
589 return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
590}
591
592/** easeOutCubic: 1 − (1−t)³. Smooth, no overshoot (easings.net). */
593function easeOutCubic (t)
594{
595 t = clamp01(t);
596 var u = 1 - t;
597 return 1 - u * u * u;
598}
599
600function tween (from, to, t, ease)
601{
602 return from + (to - from) * ease(clamp01(t));
603}
604
605/**
606 * Visual-only block swap tween (t1121). Game logic and the grid update
607 * immediately; this only moves the displaced sprite. 100 ms sits in the
608 * requested 80–120 ms range.
609 */
610var SWAP_TWEEN = {
611 duration: 0.100,
612 ease: easeOutCubic
613};
614
615/**
616 * DEFAULT settings of Tim's KWin Click Tween
617 * (git.timfalken.com/timfa/click-tween).
618 *
619 * Press: shrink to 80% in 150 ms with easeOutBack, stay at 80% while held.
620 * Release: grow back to 100% in 720 ms with easeOutElastic.
621 * Mid-animation release starts from the current scale, like QVariantAnimation.
622 */
623var CLICK_TWEEN = {
624 pressScale: 0.8,
625 releaseScale: 1.0,
626 pressDuration: 0.150,
627 releaseDuration: 0.720,
628 pressEase: easeOutBack,
629 releaseEase: easeOutElastic,
630 backOvershoot: BACK_OVERSHOOT,
631 elasticPeriod: ELASTIC_PERIOD,
632 elasticAmplitude: ELASTIC_AMPLITUDE,
633 source: 'click-tween settings.h + clicktween.cpp (Qt QEasingCurve defaults)'
634};
635
636/**
637 * Visual landing bounce, u in 0..1. Subtle squash with a slight stretch
638 * on the other axis and a tiny upward rebound (in tiles, visual only).
639 */
640function bouncePose (u, squash)
641{
642 if (u <= 0 || u >= 1)
643 { return { sx: 1, sy: 1, dy: 0 }; }
644 var wave = Math.sin(Math.PI * u);
645 return {
646 sx: 1 + squash * 0.6 * wave,
647 sy: 1 - squash * wave,
648 dy: 0.07 * wave * (1 - u)
649 };
650}
651
652var Easing = {
653 BACK_OVERSHOOT: BACK_OVERSHOOT,
654 ELASTIC_PERIOD: ELASTIC_PERIOD,
655 ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,
656 easeOutBack: easeOutBack,
657 easeOutElastic: easeOutElastic,
658 easeOutCubic: easeOutCubic,
659 tween: tween,
660 CLICK_TWEEN: CLICK_TWEEN,
661 SWAP_TWEEN: SWAP_TWEEN,
662 clamp01: clamp01,
663 bouncePose: bouncePose
664};
665
666if (typeof module !== 'undefined' && module.exports)
667{ module.exports = Easing; }
668else if (typeof globalThis !== 'undefined')
669{ globalThis.Easing = Easing; }
670
671/*
672 * End File:
673 * /workspace/meteors/src/easing.js
674 */
675
676/*
677 * Start File:
678 * /workspace/meteors/src/gameCore.js
679 */
680'use strict';
681
682/**
683 * Deterministic Meteors game core. No DOM, no rendering, no input devices.
684 * The view layer reads this state and translates pointer events into
685 * beginDrag / moveDrag / endDrag.
686 */
687
688var PlanetMod = (typeof require !== 'undefined' && typeof module !== 'undefined')
689 ? require('./planet.js')
690 : (typeof Planet !== 'undefined' ? Planet : globalThis.Planet);
691
692var COLOR_GRAY = -1;
693
694var STATE_STILL = 'still';
695var STATE_FALLING = 'falling';
696var STATE_FLYING = 'flying';
697var STATE_SETTLING = 'settling';
698var STATE_LOCKED = 'locked';
699var STATE_MANUAL = 'manual';
700
701var ALIGN_EPS = 0.15;
702var SUBSTEP = 1 / 120;
703var DRAG_LAUNCH_SLACK = 0.65;
704// Upward pull (tiles past the press point) that launches an already-topmost block.
705var LAUNCH_PULL = 0.35;
706// Minimal accumulated vertical pointer travel (tiles) to swap one step.
707// No hold delay: the first swap fires as soon as this distance is reached.
708var SWAP_DISTANCE = 0.25;
709// Fallback snap (tiles) when the press cell is empty: nearest block in the column.
710var SNAP_Y = 0.5;
711// Horizontal slop (tiles) for snapping to a neighbouring column on press.
712var HORIZONTAL_SLOP = 0.35;
713/** t1120: additive jump bonus per landing-chain step. A landing that
714 * immediately makes a match launches at (1 + 0.25 * chain) times the
715 * usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */
716var LANDING_CHAIN_BONUS = 0.25;
717/** t1123: a column pulses red at or above this many grounded rows
718 * (10 of 13 is just over 70%). */
719var COLUMN_WARN_ROWS = 10;
720
721function UnionFind ()
722{
723 this.parent = Object.create(null);
724}
725
726UnionFind.prototype.add = function (id)
727{
728 if (this.parent[id] == null)
729 { this.parent[id] = id; }
730};
731
732UnionFind.prototype.find = function (id)
733{
734 if (this.parent[id] !== id)
735 { this.parent[id] = this.find(this.parent[id]); }
736 return this.parent[id];
737};
738
739UnionFind.prototype.union = function (a, b)
740{
741 this.add(a);
742 this.add(b);
743 var ra = this.find(a);
744 var rb = this.find(b);
745 if (ra !== rb)
746 { this.parent[rb] = ra; }
747};
748
749function GameCore (planet, rng)
750{
751 this.planet = planet || PlanetMod.defaultPlanet();
752 this.rng = rng || Math.random;
753 this.width = PlanetMod.FIELD_WIDTH;
754 this.height = PlanetMod.FIELD_HEIGHT;
755 this.blocks = [];
756 this.clusters = Object.create(null);
757 this.nextBlockId = 1;
758 this.nextClusterId = 1;
759 this.spawnTimer = 0;
760 this.spawnInterval = PlanetMod.SPAWN_INTERVAL;
761 this.settleTime = PlanetMod.SETTLE_TIME;
762 this.score = 0;
763 this.state = 'playing';
764 this.drag = null;
765 this.gameOverTime = 0;
766 this.outgoingShots = [];
767 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
768 this.missChance = optsMissChance(arguments);
769 // t1112: invariant checker. strictInvariants throws (tests);
770 // debugInvariants records violations for the ?debug overlay.
771 this.strictInvariants = false;
772 this.debugInvariants = false;
773 this.lastInvariantViolations = [];
774 // t1121: visual-only swap events, consumed by the view each frame.
775 this.swapEvents = [];
776 // t1120: last landing-chain indicator { chain, bonusPct }, or null.
777 this.lastChainIndicator = null;
778}
779
780function optsMissChance (args)
781{
782 // GameCore(planet, rng, missChance) — third arg is optional.
783 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
784 { return Math.max(0, Math.min(1, args[2])); }
785 var planet = args[0];
786 if (planet && typeof PlanetMod.missChance === 'function')
787 { return PlanetMod.missChance(planet); }
788 return GameCore.DEFAULT_MISS_CHANCE;
789}
790
791GameCore.COLOR_GRAY = COLOR_GRAY;
792GameCore.LAUNCH_PULL = LAUNCH_PULL;
793GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
794GameCore.SNAP_Y = SNAP_Y;
795GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
796GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS;
797GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS;
798GameCore.DEFAULT_MISS_CHANCE = 0.30;
799GameCore.STATE_STILL = STATE_STILL;
800GameCore.STATE_FALLING = STATE_FALLING;
801GameCore.STATE_FLYING = STATE_FLYING;
802GameCore.STATE_SETTLING = STATE_SETTLING;
803GameCore.STATE_LOCKED = STATE_LOCKED;
804GameCore.STATE_MANUAL = STATE_MANUAL;
805
806GameCore.prototype.randomColor = function ()
807{
808 return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length;
809};
810
811GameCore.prototype.createBlock = function (col, y, color, state)
812{
813 var block = {
814 id: this.nextBlockId++,
815 col: col,
816 y: y,
817 color: color,
818 state: state || STATE_STILL,
819 vy: 0,
820 clusterId: null,
821 settleTime: 0,
822 flame: false,
823 pushedClusters: null,
824 manualTarget: 0,
825 manualDecel: 0,
826 manualPhase: null,
827 bouncing: false,
828 bounceAge: 0
829 };
830 this.blocks.push(block);
831 return block;
832};
833
834GameCore.prototype.removeBlock = function (block)
835{
836 if (block.clusterId != null)
837 { this.leaveCluster(block); }
838 var index = this.blocks.indexOf(block);
839 if (index >= 0)
840 { this.blocks.splice(index, 1); }
841};
842
843GameCore.prototype.leaveCluster = function (block)
844{
845 var id = block.clusterId;
846 block.clusterId = null;
847 block.flame = false;
848 if (id == null || !this.clusters[id])
849 { return; }
850 var still = 0;
851 for (var i = 0; i < this.blocks.length; i++)
852 {
853 if (this.blocks[i].clusterId === id)
854 { still++; }
855 }
856 if (still === 0)
857 { delete this.clusters[id]; }
858};
859
860GameCore.prototype.blocksInColumn = function (col)
861{
862 var out = [];
863 for (var i = 0; i < this.blocks.length; i++)
864 {
865 if (this.blocks[i].col === col)
866 { out.push(this.blocks[i]); }
867 }
868 out.sort(function (a, b) { return a.y - b.y; });
869 return out;
870};
871
872GameCore.prototype.isGrounded = function (block)
873{
874 return block.state === STATE_STILL
875 || block.state === STATE_SETTLING
876 || block.state === STATE_LOCKED;
877};
878
879/**
880 * Highest grounded landing surface in `col`. If `belowY` is given, only
881 * blocks strictly below that y count — a hanging still block above a
882 * gap must never pull a falling or thrown block upward through the gap.
883 */
884GameCore.prototype.stackTop = function (col, ignore, belowY)
885{
886 var top = 0;
887 for (var i = 0; i < this.blocks.length; i++)
888 {
889 var block = this.blocks[i];
890 if (block.col !== col)
891 { continue; }
892 if (ignore && ignore(block))
893 { continue; }
894 if (belowY != null && block.y + 1e-9 >= belowY)
895 { continue; }
896 if (this.isGrounded(block))
897 {
898 var surface = block.y + 1;
899 if (surface > top)
900 { top = surface; }
901 }
902 }
903 return top;
904};
905
906GameCore.prototype.isColumnLocked = function (col)
907{
908 for (var i = 0; i < this.blocks.length; i++)
909 {
910 var block = this.blocks[i];
911 if (block.col === col && block.state === STATE_LOCKED)
912 { return true; }
913 }
914 return false;
915};
916
917GameCore.prototype.isColumnStill = function (col)
918{
919 if (this.isColumnLocked(col))
920 { return false; }
921 for (var i = 0; i < this.blocks.length; i++)
922 {
923 var block = this.blocks[i];
924 if (block.col !== col)
925 { continue; }
926 if (block.state === STATE_FLYING
927 || block.state === STATE_FALLING
928 || block.state === STATE_MANUAL
929 || block.state === STATE_SETTLING)
930 { return false; }
931 }
932 return true;
933};
934
935GameCore.prototype.groundedCount = function (col)
936{
937 var n = 0;
938 for (var i = 0; i < this.blocks.length; i++)
939 {
940 if (this.blocks[i].col === col && this.isGrounded(this.blocks[i]))
941 { n++; }
942 }
943 return n;
944};
945
946GameCore.prototype.columnNeedsWarn = function (col)
947{
948 return this.groundedCount(col) >= COLUMN_WARN_ROWS;
949};
950
951/**
952 * Which columns of a field snapshot should pulse (t1123). Flying,
953 * falling and manual (airborne) blocks do not count: they are
954 * temporary and would flicker the warning. Still, settling and
955 * locked (grounded) blocks do.
956 */
957GameCore.warnColumnsFromSnapshot = function (snapshot, threshold)
958{
959 threshold = threshold == null ? COLUMN_WARN_ROWS : threshold;
960 var width = (snapshot && snapshot.width) || 10;
961 var flags = [];
962 var counts = [];
963 for (var c = 0; c < width; c++)
964 {
965 counts[c] = 0;
966 flags[c] = false;
967 }
968 var blocks = (snapshot && snapshot.blocks) || [];
969 for (var i = 0; i < blocks.length; i++)
970 {
971 var b = blocks[i];
972 if (b.col < 0 || b.col >= width)
973 { continue; }
974 if (b.state === 'still' || b.state === 'settling' || b.state === 'locked')
975 { counts[b.col]++; }
976 }
977 for (var c = 0; c < width; c++)
978 { flags[c] = counts[c] >= threshold; }
979 return flags;
980};
981
982GameCore.columnWarnPulse = function (timeSec)
983{
984 // Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player
985 // field and opponent / bot minis so they pulse in sync.
986 var t = timeSec;
987 if (t == null)
988 {
989 t = (typeof performance !== 'undefined' && performance.now)
990 ? performance.now() / 1000
991 : Date.now() / 1000;
992 }
993 return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55));
994};
995
996GameCore.prototype.blockAt = function (col, row)
997{
998 for (var i = 0; i < this.blocks.length; i++)
999 {
1000 var block = this.blocks[i];
1001 if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS)
1002 { return block; }
1003 }
1004 return null;
1005};
1006
1007GameCore.prototype.place = function (col, row, color, state)
1008{
1009 return this.createBlock(col, row, color, state || STATE_STILL);
1010};
1011
1012GameCore.prototype.lockedColumnCount = function ()
1013{
1014 var n = 0;
1015 for (var c = 0; c < this.width; c++)
1016 {
1017 if (this.isColumnLocked(c))
1018 { n++; }
1019 }
1020 return n;
1021};
1022
1023GameCore.prototype.startBounce = function (block)
1024{
1025 if (!block)
1026 { return; }
1027 block.bouncing = true;
1028 block.bounceAge = 0;
1029};
1030
1031GameCore.prototype.advanceBounces = function (dt)
1032{
1033 var duration = this.planet.bounceDuration;
1034 for (var i = 0; i < this.blocks.length; i++)
1035 {
1036 var block = this.blocks[i];
1037 if (!block.bouncing)
1038 { continue; }
1039 block.bounceAge += dt;
1040 if (duration <= 0 || block.bounceAge >= duration)
1041 {
1042 block.bouncing = false;
1043 block.bounceAge = duration;
1044 }
1045 }
1046};
1047
1048/**
1049 * True if `block` rests on the floor or on a solid (still / settling /
1050 * locked) block immediately below it in the same column.
1051 */
1052GameCore.prototype.hasSupport = function (block)
1053{
1054 if (block.y <= 1e-9)
1055 { return true; }
1056 for (var i = 0; i < this.blocks.length; i++)
1057 {
1058 var other = this.blocks[i];
1059 if (other === block || other.col !== block.col)
1060 { continue; }
1061 if (!this.isGrounded(other))
1062 { continue; }
1063 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
1064 { return true; }
1065 }
1066 return false;
1067};
1068
1069/** Highest flying block in this column whose top is at or below `block.y + 1`. */
1070GameCore.prototype.highestFlyingBelow = function (block)
1071{
1072 var best = null;
1073 for (var i = 0; i < this.blocks.length; i++)
1074 {
1075 var other = this.blocks[i];
1076 if (other === block || other.col !== block.col)
1077 { continue; }
1078 if (other.state !== STATE_FLYING || other.clusterId == null)
1079 { continue; }
1080 var cluster = this.clusters[other.clusterId];
1081 if (!cluster || cluster.phase === 'landed')
1082 { continue; }
1083 // The falling block is at or above this flyer (or already overlapping).
1084 if (block.y + 1e-9 < other.y)
1085 { continue; }
1086 if (!best || other.y > best.y)
1087 { best = other; }
1088 }
1089 return best;
1090};
1091
1092GameCore.prototype.highestFallingBelow = function (block)
1093{
1094 var best = null;
1095 for (var i = 0; i < this.blocks.length; i++)
1096 {
1097 var other = this.blocks[i];
1098 if (other === block || other.col !== block.col)
1099 { continue; }
1100 if (other.state !== STATE_FALLING)
1101 { continue; }
1102 if (other.y > block.y - 1e-9)
1103 { continue; }
1104 if (!best || other.y > best.y)
1105 { best = other; }
1106 }
1107 return best;
1108};
1109
1110/**
1111 * Make an unsupported still block start falling from rest, so it eases
1112 * into fallSpeed under normal gravity. Skips the block being dragged.
1113 */
1114/**
1115 * Strip leftover launch / manual kinematics so a block that has just
1116 * become still or falling starts from rest. Used after a landed grey
1117 * cluster recolors, and whenever an unsupported still block drops.
1118 */
1119GameCore.prototype.clearFlightState = function (block)
1120{
1121 block.vy = 0;
1122 block.flame = false;
1123 block.manualPhase = null;
1124 block.manualTarget = null;
1125 block.manualDecel = 0;
1126 block.pushedClusters = null;
1127};
1128
1129GameCore.prototype.releaseUnsupported = function ()
1130{
1131 // Repeat until stable: a still sitting on a still that itself just
1132 // became falling must also drop. Two fixed passes are not enough
1133 // for a chain of hanging blocks (t1112).
1134 var guard = 0;
1135 var changed = true;
1136 while (changed && guard++ < this.height + 2)
1137 {
1138 changed = false;
1139 for (var i = 0; i < this.blocks.length; i++)
1140 {
1141 var block = this.blocks[i];
1142 if (block.state !== STATE_STILL)
1143 { continue; }
1144 if (this.drag && this.drag.blockId === block.id)
1145 { continue; }
1146 if (this.hasSupport(block))
1147 { continue; }
1148 this.leaveCluster(block);
1149 this.clearFlightState(block);
1150 block.state = STATE_FALLING;
1151 changed = true;
1152 }
1153 }
1154};
1155
1156GameCore.prototype.accelerateFall = function (block, dt)
1157{
1158 var target = -this.planet.fallSpeed;
1159 if (block.vy > target)
1160 { block.vy = Math.max(target, block.vy - this.planet.fallAccel * dt); }
1161 else
1162 { block.vy = target; }
1163};
1164
1165GameCore.prototype.landFallingBlock = function (block)
1166{
1167 block.vy = 0;
1168 block.flame = false;
1169 this.startBounce(block);
1170 if (block.color === COLOR_GRAY)
1171 {
1172 block.state = STATE_SETTLING;
1173 block.settleTime = 0;
1174 }
1175 else
1176 { block.state = STATE_STILL; }
1177};
1178
1179/**
1180 * Sit `block` on top of the flying cluster that `flyer` belongs to, and
1181 * carry it along as cargo (no flame). Returns true if attached.
1182 */
1183GameCore.prototype.attachToFlyingCluster = function (block, flyer)
1184{
1185 var cluster = this.clusters[flyer.clusterId];
1186 if (!cluster || cluster.phase === 'landed')
1187 { return false; }
1188 this.prepareClusterBody(cluster);
1189 var maxOff = null;
1190 var members = this.clusterMembers(cluster.id);
1191 for (var i = 0; i < members.length; i++)
1192 {
1193 if (members[i].col !== block.col)
1194 { continue; }
1195 if (maxOff == null || members[i].clusterOffset > maxOff)
1196 { maxOff = members[i].clusterOffset; }
1197 }
1198 var oldN = members.length;
1199 var fallingVy = block.vy;
1200 if (block.clusterId != null && block.clusterId !== cluster.id)
1201 { this.leaveCluster(block); }
1202 block.state = STATE_FLYING;
1203 block.clusterId = cluster.id;
1204 block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1;
1205 block.flame = false;
1206 block.settleTime = 0;
1207 block.manualPhase = null;
1208 block.manualTarget = null;
1209 block.manualDecel = 0;
1210 block.pushedClusters = null;
1211 // A cluster born from a thrown block averages in falling cargo
1212 // the same way two flying clusters merge (t1108). Other rockets
1213 // keep their velocity and just pick the cargo up.
1214 if (cluster.fromManual)
1215 {
1216 var newN = oldN + 1;
1217 cluster.vy = (cluster.vy * oldN + fallingVy) / newN;
1218 cluster.decel = ((cluster.decel || 0) * oldN) / newN;
1219 cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
1220 cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
1221 }
1222 this.syncClusterMembers(cluster);
1223 return true;
1224};
1225
1226GameCore.prototype.catchFallingOntoCluster = function (cluster, members)
1227{
1228 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1229 { return; }
1230 // Snapshot falling blocks; attaching mutates state.
1231 var falling = [];
1232 for (var i = 0; i < this.blocks.length; i++)
1233 {
1234 if (this.blocks[i].state === STATE_FALLING)
1235 { falling.push(this.blocks[i]); }
1236 }
1237 for (var i = 0; i < falling.length; i++)
1238 {
1239 var block = falling[i];
1240 var flyer = null;
1241 for (var m = 0; m < members.length; m++)
1242 {
1243 var other = members[m];
1244 if (other.col !== block.col)
1245 { continue; }
1246 // Overlap or rest on this member's top.
1247 if (block.y < other.y + 1 + 1e-9 && block.y + 1 > other.y - 1e-9)
1248 {
1249 if (!flyer || other.y > flyer.y)
1250 { flyer = other; }
1251 }
1252 }
1253 if (flyer)
1254 { this.attachToFlyingCluster(block, flyer); }
1255 }
1256};
1257
1258GameCore.prototype.tick = function (dt)
1259{
1260 if (this.state === 'gameover')
1261 {
1262 this.gameOverTime += Math.max(0, dt);
1263 return;
1264 }
1265 if (dt <= 0)
1266 { return; }
1267 dt = Math.min(dt, 0.1);
1268
1269 this.spawnTimer += dt;
1270 while (this.spawnTimer >= this.spawnInterval)
1271 {
1272 this.spawnTimer -= this.spawnInterval;
1273 this.trySpawn();
1274 }
1275
1276 var left = dt;
1277 while (left > 1e-12)
1278 {
1279 var step = Math.min(SUBSTEP, left);
1280 this.snapshotPrevY();
1281 this.integrateFalling(step);
1282 this.resolveFlyingMatches();
1283 this.integrateClusters(step);
1284 this.mergeFlyingClusters();
1285 this.integrateManual(step);
1286 this.mergeAnyManualFallingOverlaps();
1287 this.resolveAirborneCollisions();
1288 this.cullOffTop();
1289 left -= step;
1290 }
1291
1292 this.releaseUnsupported();
1293 this.advanceSettle(dt);
1294 // After a landed grey group is released, blocks that were sitting on
1295 // hanging members are still STILL (the earlier pass ran while those
1296 // members counted as support). Drop them from rest before matching,
1297 // so they cannot form a mid-air match and shoot off the top.
1298 this.releaseUnsupported();
1299 this.advanceBounces(dt);
1300 if (!this.drag)
1301 { this.resolveMatches(); }
1302 this.checkLocks();
1303 this.checkGameOver();
1304 this.assertInvariants('tick');
1305};
1306
1307/** Step a stretch of time in fixed substeps. Useful for tests. */
1308GameCore.prototype.step = function (seconds, dt)
1309{
1310 dt = dt || SUBSTEP;
1311 var t = 0;
1312 while (t < seconds - 1e-15)
1313 {
1314 var s = Math.min(dt, seconds - t);
1315 this.tick(s);
1316 t += s;
1317 }
1318};
1319
1320GameCore.prototype.trySpawn = function ()
1321{
1322 if (this.state !== 'playing')
1323 { return null; }
1324 var eligible = [];
1325 for (var col = 0; col < this.width; col++)
1326 {
1327 if (this.isColumnLocked(col))
1328 { continue; }
1329 if (this.groundedCount(col) >= this.height)
1330 { continue; }
1331 var alreadyFalling = false;
1332 var list = this.blocksInColumn(col);
1333 for (var i = 0; i < list.length; i++)
1334 {
1335 if (list[i].state === STATE_FALLING)
1336 {
1337 alreadyFalling = true;
1338 break;
1339 }
1340 }
1341 if (!alreadyFalling)
1342 { eligible.push(col); }
1343 }
1344 if (!eligible.length)
1345 { return null; }
1346 var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1347 var color = this.randomColor();
1348 var block = this.createBlock(col, this.height, color, STATE_FALLING);
1349 block.vy = -this.planet.fallSpeed;
1350 return block;
1351};
1352
1353GameCore.prototype.integrateFalling = function (dt)
1354{
1355 var falling = [];
1356 for (var i = 0; i < this.blocks.length; i++)
1357 {
1358 if (this.blocks[i].state === STATE_FALLING)
1359 { falling.push(this.blocks[i]); }
1360 }
1361 // Lowest first, so a stack of falling blocks rests on itself.
1362 falling.sort(function (a, b) { return a.y - b.y; });
1363 for (var i = 0; i < falling.length; i++)
1364 {
1365 var block = falling[i];
1366 if (block.state !== STATE_FALLING)
1367 { continue; }
1368 this.accelerateFall(block, dt);
1369 var nextY = block.y + block.vy * dt;
1370 var manual = this.manualInColumnHit(block, block.y, nextY);
1371 if (manual)
1372 {
1373 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
1374 continue;
1375 }
1376 var flyer = this.highestFlyingBelow(block);
1377 if (flyer && nextY <= flyer.y + 1 + 1e-9)
1378 {
1379 if (this.attachToFlyingCluster(block, flyer))
1380 { continue; }
1381 }
1382 var top = this.stackTop(block.col, null, block.y);
1383 var below = this.highestFallingBelow(block);
1384 if (below && below.y + 1 > top)
1385 { top = below.y + 1; }
1386 if (nextY <= top)
1387 {
1388 block.y = top;
1389 this.landFallingBlock(block);
1390 }
1391 else
1392 { block.y = nextY; }
1393 }
1394};
1395
1396GameCore.prototype.clusterMembers = function (clusterId)
1397{
1398 var out = [];
1399 for (var i = 0; i < this.blocks.length; i++)
1400 {
1401 if (this.blocks[i].clusterId === clusterId)
1402 { out.push(this.blocks[i]); }
1403 }
1404 return out;
1405};
1406
1407
1408/**
1409 * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a
1410 * jump of height H peaks at exactly H after riseTime. Returns dy.
1411 * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the
1412 * upward deceleration. After the apex, vy eases from 0 to -fallSpeed
1413 * at planet.fallAccel, then stays at terminal fallSpeed.
1414 */
1415GameCore.prototype.advanceJump = function (body, dt)
1416{
1417 var dy = 0;
1418 var left = dt;
1419 if (body.phase === 'up')
1420 {
1421 var decel = body.decel;
1422 var vy = body.vy;
1423 var tApex = decel > 1e-12 ? vy / decel : Infinity;
1424 if (tApex <= left + 1e-15)
1425 {
1426 dy += vy * tApex - 0.5 * decel * tApex * tApex;
1427 body.vy = 0;
1428 body.phase = 'down';
1429 left -= tApex;
1430 }
1431 else
1432 {
1433 var vyNew = vy - decel * left;
1434 dy += (vy + vyNew) * 0.5 * left;
1435 body.vy = vyNew;
1436 left = 0;
1437 }
1438 }
1439 if (body.phase === 'up' && body.vy <= 1e-10)
1440 {
1441 body.vy = 0;
1442 body.phase = 'down';
1443 }
1444 if (body.phase === 'down' && left > 0)
1445 {
1446 var target = -this.planet.fallSpeed;
1447 var accel = this.planet.fallAccel;
1448 if (accel < 1e-12)
1449 {
1450 body.vy = target;
1451 dy += body.vy * left;
1452 }
1453 else if (body.vy > target + 1e-12)
1454 {
1455 var tReach = (body.vy - target) / accel;
1456 if (tReach <= left + 1e-15)
1457 {
1458 dy += (body.vy + target) * 0.5 * tReach;
1459 body.vy = target;
1460 left -= tReach;
1461 dy += body.vy * left;
1462 }
1463 else
1464 {
1465 var vyNew = body.vy - accel * left;
1466 dy += (body.vy + vyNew) * 0.5 * left;
1467 body.vy = vyNew;
1468 }
1469 }
1470 else
1471 {
1472 body.vy = target;
1473 dy += body.vy * left;
1474 }
1475 }
1476 return dy;
1477};
1478
1479GameCore.prototype.integrateClusters = function (dt)
1480{
1481 var ids = Object.keys(this.clusters);
1482 for (var n = 0; n < ids.length; n++)
1483 {
1484 var cluster = this.clusters[ids[n]];
1485 if (!cluster)
1486 { continue; }
1487 var members = this.clusterMembers(cluster.id);
1488 if (!members.length)
1489 {
1490 delete this.clusters[cluster.id];
1491 continue;
1492 }
1493 if (cluster.phase === 'landed' || cluster.phase === 'hold')
1494 { continue; }
1495
1496 this.prepareClusterBody(cluster);
1497 var dy = this.advanceJump(cluster, dt);
1498 cluster.anchorY += dy;
1499 this.syncClusterMembers(cluster);
1500
1501 this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id));
1502 this.checkChainRelaunch(cluster);
1503
1504 if (cluster.phase === 'down' && this.clusters[cluster.id])
1505 { this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }
1506 }
1507};
1508
1509
1510/**
1511 * If two or more flying clusters overlap in the same column, merge them
1512 * into one cluster. Velocity (and deceleration and jumpHeight) is the
1513 * mass-weighted average by block count. Phase is 'up' when the merged
1514 * vy is positive, otherwise 'down'. Overlapping members in a column
1515 * are packed so the higher one sits flush on the lower.
1516 */
1517GameCore.prototype.mergeFlyingClusters = function ()
1518{
1519 var flying = [];
1520 var ids = Object.keys(this.clusters);
1521 for (var n = 0; n < ids.length; n++)
1522 {
1523 var cluster = this.clusters[ids[n]];
1524 if (!cluster)
1525 { continue; }
1526 if (cluster.phase === 'landed' || cluster.phase === 'hold')
1527 { continue; }
1528 flying.push(cluster);
1529 }
1530 if (flying.length < 2)
1531 { return; }
1532
1533 var uf = new UnionFind();
1534 for (var i = 0; i < flying.length; i++)
1535 { uf.add(flying[i].id); }
1536 for (var i = 0; i < flying.length; i++)
1537 {
1538 for (var j = i + 1; j < flying.length; j++)
1539 {
1540 if (this.flyingClustersOverlap(flying[i], flying[j]))
1541 { uf.union(flying[i].id, flying[j].id); }
1542 }
1543 }
1544
1545 var groups = Object.create(null);
1546 for (var i = 0; i < flying.length; i++)
1547 {
1548 var root = uf.find(flying[i].id);
1549 if (!groups[root])
1550 { groups[root] = []; }
1551 groups[root].push(flying[i]);
1552 }
1553 for (var root in groups)
1554 {
1555 if (groups[root].length >= 2)
1556 { this.mergeClusterGroup(groups[root]); }
1557 }
1558};
1559
1560GameCore.prototype.flyingClustersOverlap = function (a, b)
1561{
1562 var ma = this.clusterMembers(a.id);
1563 var mb = this.clusterMembers(b.id);
1564 for (var i = 0; i < ma.length; i++)
1565 {
1566 for (var j = 0; j < mb.length; j++)
1567 {
1568 if (ma[i].col !== mb[j].col)
1569 { continue; }
1570 if (this.sweptIntervalsOverlap(ma[i], mb[j]))
1571 { return true; }
1572 }
1573 }
1574 return false;
1575};
1576
1577/**
1578 * Swept [y, y+1) of two blocks this substep, using _prevY when present.
1579 * Catches pairs that crossed without sharing a cell at either endpoint.
1580 */
1581GameCore.prototype.sweptIntervalsOverlap = function (a, b)
1582{
1583 var a0 = (a._prevY != null) ? a._prevY : a.y;
1584 var a1 = a.y;
1585 var b0 = (b._prevY != null) ? b._prevY : b.y;
1586 var b1 = b.y;
1587 var aLo = Math.min(a0, a1);
1588 var aHi = Math.max(a0, a1) + 1;
1589 var bLo = Math.min(b0, b1);
1590 var bHi = Math.max(b0, b1) + 1;
1591 return aLo < bHi - 1e-9 && bLo < aHi - 1e-9;
1592};
1593
1594GameCore.prototype.mergeClusterGroup = function (clusters)
1595{
1596 clusters.sort(function (a, b) { return a.id - b.id; });
1597 var keep = clusters[0];
1598 var n = 0;
1599 var vySum = 0;
1600 var decelSum = 0;
1601 var hSum = 0;
1602 for (var c = 0; c < clusters.length; c++)
1603 {
1604 var mem = this.clusterMembers(clusters[c].id);
1605 var m = mem.length;
1606 n += m;
1607 vySum += clusters[c].vy * m;
1608 decelSum += (clusters[c].decel || 0) * m;
1609 hSum += (clusters[c].jumpHeight || 0) * m;
1610 }
1611 if (n === 0)
1612 { return; }
1613 keep.vy = vySum / n;
1614 keep.decel = decelSum / n;
1615 keep.jumpHeight = hSum / n;
1616 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
1617 var maxChain = 0;
1618 for (var c = 0; c < clusters.length; c++)
1619 {
1620 var ch = clusters[c].landingChain || 0;
1621 if (ch > maxChain)
1622 { maxChain = ch; }
1623 }
1624 keep.landingChain = maxChain;
1625 for (var c = 0; c < clusters.length; c++)
1626 {
1627 var mem = this.clusterMembers(clusters[c].id);
1628 for (var i = 0; i < mem.length; i++)
1629 {
1630 mem[i].clusterId = keep.id;
1631 mem[i].vy = keep.vy;
1632 mem[i].state = STATE_FLYING;
1633 }
1634 if (clusters[c] !== keep)
1635 { delete this.clusters[clusters[c].id]; }
1636 }
1637 this.prepareClusterBody(keep);
1638 this.checkChainRelaunch(keep);
1639 if (keep.phase === 'down' && this.clusters[keep.id])
1640 { this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
1641};
1642
1643GameCore.prototype.packClusterOverlaps = function (cluster)
1644{
1645 var members = this.clusterMembers(cluster.id);
1646 var byCol = Object.create(null);
1647 for (var i = 0; i < members.length; i++)
1648 {
1649 var col = members[i].col;
1650 if (!byCol[col])
1651 { byCol[col] = []; }
1652 byCol[col].push(members[i]);
1653 }
1654 var cols = Object.keys(byCol);
1655 for (var c = 0; c < cols.length; c++)
1656 {
1657 var list = byCol[cols[c]];
1658 list.sort(function (a, b) { return a.y - b.y; });
1659 for (var i = 1; i < list.length; i++)
1660 {
1661 var minY = list[i - 1].y + 1;
1662 if (list[i].y < minY - 1e-12)
1663 { list[i].y = minY; }
1664 }
1665 }
1666};
1667
1668
1669/**
1670 * Derive integer cell offsets from current member positions and a
1671 * single anchorY, packing overlaps in each column while preserving
1672 * order (lower y stays lower; ties break on id). Then sync.
1673 * Flying clusters are one rigid body: one y, one vy, integer offsets.
1674 */
1675GameCore.prototype.prepareClusterBody = function (cluster)
1676{
1677 if (!cluster)
1678 { return; }
1679 var members = this.clusterMembers(cluster.id);
1680 if (!members.length)
1681 { return; }
1682 this.rebuildClusterOffsets(cluster, members);
1683};
1684
1685GameCore.prototype.rebuildClusterOffsets = function (cluster, members)
1686{
1687 members = members || this.clusterMembers(cluster.id);
1688 if (!members.length)
1689 { return; }
1690 var byCol = Object.create(null);
1691 for (var i = 0; i < members.length; i++)
1692 {
1693 var col = members[i].col;
1694 if (!byCol[col])
1695 { byCol[col] = []; }
1696 byCol[col].push(members[i]);
1697 }
1698 var minY = Infinity;
1699 for (var i = 0; i < members.length; i++)
1700 {
1701 if (members[i].y < minY)
1702 { minY = members[i].y; }
1703 }
1704 if (cluster.anchorY == null || !isFinite(cluster.anchorY))
1705 { cluster.anchorY = minY; }
1706 var cols = Object.keys(byCol);
1707 for (var c = 0; c < cols.length; c++)
1708 {
1709 var list = byCol[cols[c]];
1710 list.sort(function (a, b)
1711 {
1712 if (a.y !== b.y)
1713 { return a.y - b.y; }
1714 return a.id - b.id;
1715 });
1716 var prevOff = -Infinity;
1717 for (var i = 0; i < list.length; i++)
1718 {
1719 var off = Math.round(list[i].y - cluster.anchorY);
1720 if (off <= prevOff)
1721 { off = prevOff + 1; }
1722 list[i].clusterOffset = off;
1723 prevOff = off;
1724 }
1725 }
1726 // Re-base so the lowest offset is 0, keeping relative integers.
1727 var minOff = Infinity;
1728 for (var i = 0; i < members.length; i++)
1729 {
1730 if (members[i].clusterOffset < minOff)
1731 { minOff = members[i].clusterOffset; }
1732 }
1733 if (minOff !== 0 && isFinite(minOff))
1734 {
1735 cluster.anchorY += minOff;
1736 for (var i = 0; i < members.length; i++)
1737 { members[i].clusterOffset -= minOff; }
1738 }
1739 this.syncClusterMembers(cluster);
1740};
1741
1742GameCore.prototype.syncClusterMembers = function (cluster)
1743{
1744 if (!cluster)
1745 { return; }
1746 var members = this.clusterMembers(cluster.id);
1747 if (cluster.anchorY == null)
1748 {
1749 var minY = Infinity;
1750 for (var i = 0; i < members.length; i++)
1751 {
1752 if (members[i].y < minY)
1753 { minY = members[i].y; }
1754 }
1755 cluster.anchorY = isFinite(minY) ? minY : 0;
1756 }
1757 for (var i = 0; i < members.length; i++)
1758 {
1759 var block = members[i];
1760 if (block.clusterOffset == null)
1761 { block.clusterOffset = Math.round(block.y - cluster.anchorY); }
1762 block.y = cluster.anchorY + block.clusterOffset;
1763 if (cluster.phase !== 'landed')
1764 { block.vy = cluster.vy; }
1765 }
1766};
1767
1768GameCore.prototype.snapshotPrevY = function ()
1769{
1770 for (var i = 0; i < this.blocks.length; i++)
1771 { this.blocks[i]._prevY = this.blocks[i].y; }
1772};
1773
1774/**
1775 * Safety net after the specific integrates: any remaining mid-air
1776 * overlap or swept crossing is resolved with the same rules, then
1777 * every flying cluster is rebuilt as a rigid body. Repeats a few
1778 * times because one attach can create a new contact.
1779 */
1780GameCore.prototype.resolveAirborneCollisions = function ()
1781{
1782 var guard = 0;
1783 while (guard++ < this.height + 4)
1784 {
1785 var changed = false;
1786
1787 // Manual vs falling / cluster / manual.
1788 var manuals = [];
1789 for (var i = 0; i < this.blocks.length; i++)
1790 {
1791 if (this.blocks[i].state === STATE_MANUAL)
1792 { manuals.push(this.blocks[i]); }
1793 }
1794 manuals.sort(function (a, b) { return b.y - a.y; });
1795 for (var m = 0; m < manuals.length; m++)
1796 {
1797 var manual = manuals[m];
1798 if (manual.state !== STATE_MANUAL)
1799 { continue; }
1800 var oldY = (manual._prevY != null) ? manual._prevY : manual.y;
1801 if (this.resolveManualCollisions(manual, oldY, manual.y))
1802 { changed = true; }
1803 }
1804
1805 // Falling vs flying (sit on the roof).
1806 for (var i = 0; i < this.blocks.length; i++)
1807 {
1808 var block = this.blocks[i];
1809 if (block.state !== STATE_FALLING)
1810 { continue; }
1811 var flyer = this.highestFlyingBelow(block);
1812 if (!flyer)
1813 {
1814 // Also a flyer whose swept path crosses this falling block.
1815 flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y);
1816 }
1817 if (flyer && this.sweptIntervalsOverlap(block, flyer))
1818 {
1819 if (this.attachToFlyingCluster(block, flyer))
1820 { changed = true; }
1821 }
1822 }
1823
1824 // Cluster vs cluster (swept, including after a column push).
1825 var before = Object.keys(this.clusters).length;
1826 this.mergeFlyingClusters();
1827 if (Object.keys(this.clusters).length !== before)
1828 { changed = true; }
1829
1830 // Rebuild every flying body so offsets stay integer and unique.
1831 var ids = Object.keys(this.clusters);
1832 for (var n = 0; n < ids.length; n++)
1833 {
1834 var cluster = this.clusters[ids[n]];
1835 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1836 { continue; }
1837 this.prepareClusterBody(cluster);
1838 }
1839
1840 if (!changed)
1841 { break; }
1842 }
1843};
1844
1845/**
1846 * Invariant checker (t1112). No two blocks occupy the same cell or
1847 * overlap their [y, y+1) intervals. Flying-cluster members are
1848 * grid-aligned to a single anchor. Returns a list of violation
1849 * strings (empty if clean).
1850 */
1851GameCore.prototype.checkInvariants = function ()
1852{
1853 var issues = [];
1854 var byCol = Object.create(null);
1855 var ids = Object.create(null);
1856 for (var i = 0; i < this.blocks.length; i++)
1857 {
1858 var block = this.blocks[i];
1859 if (ids[block.id])
1860 { issues.push('duplicate id ' + block.id); }
1861 ids[block.id] = true;
1862 if (!byCol[block.col])
1863 { byCol[block.col] = []; }
1864 byCol[block.col].push(block);
1865 if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet
1866 && block.color >= this.planet.colors.length))
1867 { issues.push('block ' + block.id + ' has invalid color ' + block.color); }
1868 }
1869 var cols = Object.keys(byCol);
1870 for (var c = 0; c < cols.length; c++)
1871 {
1872 var list = byCol[cols[c]];
1873 list.sort(function (a, b)
1874 {
1875 if (a.y !== b.y)
1876 { return a.y - b.y; }
1877 return a.id - b.id;
1878 });
1879 for (var i = 0; i < list.length; i++)
1880 {
1881 var a = list[i];
1882 if (i > 0)
1883 {
1884 var prev = list[i - 1];
1885 if (a.y < prev.y + 1 - 1e-6)
1886 {
1887 issues.push('overlap col=' + a.col
1888 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)
1889 + ' gap=' + (a.y - prev.y));
1890 }
1891 var cellA = Math.floor(a.y + 1e-9);
1892 var cellP = Math.floor(prev.y + 1e-9);
1893 if (cellA === cellP)
1894 {
1895 issues.push('duplicate cell col=' + a.col + ' row=' + cellA
1896 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a));
1897 }
1898 }
1899 }
1900 }
1901 var cids = Object.keys(this.clusters);
1902 for (var n = 0; n < cids.length; n++)
1903 {
1904 var cluster = this.clusters[cids[n]];
1905 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1906 { continue; }
1907 var mem = this.clusterMembers(cluster.id);
1908 var seenOff = Object.create(null);
1909 for (var i = 0; i < mem.length; i++)
1910 {
1911 var b = mem[i];
1912 if (cluster.anchorY != null && b.clusterOffset != null)
1913 {
1914 var expected = cluster.anchorY + b.clusterOffset;
1915 if (Math.abs(b.y - expected) > 1e-6)
1916 {
1917 issues.push('cluster ' + cluster.id + ' member ' + b.id
1918 + ' y=' + b.y + ' != anchor+off ' + expected);
1919 }
1920 if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9)
1921 {
1922 issues.push('cluster ' + cluster.id + ' member ' + b.id
1923 + ' non-integer offset ' + b.clusterOffset);
1924 }
1925 var key = b.col + ':' + b.clusterOffset;
1926 if (seenOff[key])
1927 {
1928 issues.push('cluster ' + cluster.id + ' duplicate offset ' + key);
1929 }
1930 seenOff[key] = true;
1931 }
1932 }
1933 }
1934 return issues;
1935};
1936
1937GameCore.prototype._invBlock = function (b)
1938{
1939 return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y='
1940 + (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')';
1941};
1942
1943GameCore.prototype.assertInvariants = function (label)
1944{
1945 if (!this.strictInvariants && !this.debugInvariants)
1946 { return; }
1947 var issues = this.checkInvariants();
1948 this.lastInvariantViolations = issues;
1949 if (!issues.length)
1950 { return; }
1951 var msg = 'physics invariants failed'
1952 + (label ? ' at ' + label : '')
1953 + ':\n ' + issues.join('\n ')
1954 + '\n' + (this.snapshot ? this.snapshot().picture : '');
1955 if (this.strictInvariants)
1956 { throw new Error(msg); }
1957};
1958
1959GameCore.prototype.tryLandCluster = function (cluster, members)
1960{
1961 if (!members.length)
1962 { return; }
1963 var shift = 0;
1964 var hit = false;
1965 for (var i = 0; i < members.length; i++)
1966 {
1967 var block = members[i];
1968 var top = this.stackTop(block.col, function (other)
1969 {
1970 return other.clusterId === cluster.id;
1971 }, block.y);
1972 if (block.y <= top + 1e-9)
1973 {
1974 hit = true;
1975 var need = top - block.y;
1976 if (need > shift)
1977 { shift = need; }
1978 }
1979 }
1980 if (!hit)
1981 { return; }
1982 // Lift the whole rigid body so the deepest contact sits flush.
1983 this.prepareClusterBody(cluster);
1984 cluster.anchorY += shift;
1985 this.syncClusterMembers(cluster);
1986 this.landCluster(cluster, this.clusterMembers(cluster.id));
1987};
1988
1989/**
1990 * Land as a rigid group: relative positions are kept, so part of the
1991 * cluster may hang above a gap. Grey members start the 3s settle timer;
1992 * coloured cargo stays put with them until every grey has recolored.
1993 * Members that actually rest on the floor or on another block bounce.
1994 */
1995GameCore.prototype.landCluster = function (cluster, members)
1996{
1997 for (var i = 0; i < members.length; i++)
1998 {
1999 var block = members[i];
2000 block.vy = 0;
2001 block.flame = false;
2002 block.clusterId = cluster.id;
2003 if (block.color === COLOR_GRAY)
2004 {
2005 block.state = STATE_SETTLING;
2006 block.settleTime = 0;
2007 }
2008 else
2009 {
2010 // Cargo stays in the rigid group (not matchable) until release.
2011 block.state = STATE_SETTLING;
2012 block.settleTime = 0;
2013 }
2014 if (this.hasSupport(block))
2015 { this.startBounce(block); }
2016 }
2017 cluster.phase = 'landed';
2018 cluster.vy = 0;
2019 cluster.landedPending = true;
2020 if (cluster.landingChain == null)
2021 { cluster.landingChain = 0; }
2022};
2023
2024/**
2025 * After every grey in a landed cluster has recolored, let the group go.
2026 * Unsupported blocks fall individually from rest; supported ones stay.
2027 */
2028GameCore.prototype.releaseLandedCluster = function (cluster)
2029{
2030 var members = this.clusterMembers(cluster.id);
2031 var releasing = Object.create(null);
2032 for (var i = 0; i < members.length; i++)
2033 { releasing[members[i].id] = true; }
2034
2035 for (var i = 0; i < members.length; i++)
2036 {
2037 var block = members[i];
2038 if (block.color === COLOR_GRAY)
2039 {
2040 block.color = this.randomColor();
2041 block.settleTime = 0;
2042 }
2043 // Persist the chain across release so a post-recolor match in
2044 // this same tick still gets the landing bonus (t1120).
2045 block.justLanded = !!cluster.landedPending;
2046 block.landingChain = cluster.landingChain || 0;
2047 this.leaveCluster(block);
2048 // Always drop leftover launch / manual velocity. A stale upward
2049 // vy here is what sends blocks off the top "very fast" after
2050 // a grey group recolors.
2051 this.clearFlightState(block);
2052 // Support from outside the group (floor or a foreign block). Fellow
2053 // members that will also fall do not count, so a hanging stack
2054 // drops together without the top one staying put.
2055 var supported = this.hasSupportOutside(block, releasing);
2056 block.state = supported ? STATE_STILL : STATE_FALLING;
2057 }
2058 delete this.clusters[cluster.id];
2059};
2060
2061GameCore.prototype.hasSupportOutside = function (block, ignoreIds)
2062{
2063 if (block.y <= 1e-9)
2064 { return true; }
2065 for (var i = 0; i < this.blocks.length; i++)
2066 {
2067 var other = this.blocks[i];
2068 if (other === block || other.col !== block.col)
2069 { continue; }
2070 if (ignoreIds && ignoreIds[other.id])
2071 { continue; }
2072 if (!this.isGrounded(other))
2073 { continue; }
2074 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
2075 { return true; }
2076 }
2077 return false;
2078};
2079
2080GameCore.prototype.integrateManual = function (dt)
2081{
2082 for (var i = 0; i < this.blocks.length; i++)
2083 {
2084 var block = this.blocks[i];
2085 if (block.state !== STATE_MANUAL)
2086 { continue; }
2087
2088 if (block.manualPhase === 'up')
2089 {
2090 var oldY = block.y;
2091 var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
2092 var dy = this.advanceJump(proxy, dt);
2093 var nextY = oldY + dy;
2094 block.vy = proxy.vy;
2095 block.manualPhase = proxy.phase;
2096 if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget)))
2097 { continue; }
2098 block.y = Math.min(nextY, block.manualTarget);
2099 if (block.y >= block.manualTarget - 1e-12)
2100 {
2101 block.y = block.manualTarget;
2102 block.vy = 0;
2103 block.manualPhase = 'down';
2104 }
2105 if (block.y > this.height - 1)
2106 {
2107 block.y = this.height - 1;
2108 block.vy = 0;
2109 block.manualPhase = 'down';
2110 }
2111 }
2112
2113 if (block.manualPhase === 'down')
2114 {
2115 var proxy = { phase: 'down', vy: block.vy, decel: 0 };
2116 var dy = this.advanceJump(proxy, dt);
2117 block.vy = proxy.vy;
2118 var nextY = block.y + dy;
2119 var top = this.stackTop(block.col, null, block.y);
2120 if (nextY <= top)
2121 {
2122 block.y = top;
2123 block.state = STATE_STILL;
2124 block.vy = 0;
2125 block.manualPhase = null;
2126 block.flame = false;
2127 this.startBounce(block);
2128 }
2129 else
2130 {
2131 var downNext = Math.min(nextY, this.height - 1);
2132 if (this.resolveManualCollisions(block, block.y, downNext))
2133 { continue; }
2134 block.y = downNext;
2135 }
2136 }
2137 }
2138};
2139
2140/**
2141 * If the manual throw (or its path this step) hits falling blocks, merge
2142 * them into a flying cluster with mass-weighted velocity, the same rule
2143 * as two flying clusters colliding (t1108). Returns true if merged.
2144 */
2145GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
2146{
2147 if (!manual || manual.state !== STATE_MANUAL)
2148 { return false; }
2149 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
2150 if (!hits.length)
2151 { return false; }
2152 this.mergeManualWithFalling(manual, hits);
2153 return true;
2154};
2155
2156GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
2157{
2158 var lo = Math.min(oldY, newY);
2159 var hi = Math.max(oldY, newY) + 1;
2160 for (var i = 0; i < this.blocks.length; i++)
2161 {
2162 var other = this.blocks[i];
2163 if (other === falling || other.col !== falling.col)
2164 { continue; }
2165 if (other.state !== STATE_MANUAL)
2166 { continue; }
2167 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
2168 { return other; }
2169 }
2170 return null;
2171};
2172
2173GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
2174{
2175 var lo = Math.min(oldY, newY);
2176 var hi = Math.max(oldY, newY) + 1;
2177 var hits = [];
2178 for (var i = 0; i < this.blocks.length; i++)
2179 {
2180 var other = this.blocks[i];
2181 if (other === manual || other.col !== manual.col)
2182 { continue; }
2183 if (other.state !== STATE_FALLING)
2184 { continue; }
2185 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
2186 { hits.push(other); }
2187 }
2188 if (!hits.length)
2189 { return hits; }
2190 return this.contiguousFallingInColumn(manual.col, manual, hits);
2191};
2192
2193/**
2194 * Every falling block in `col` that overlaps `anchor` or a hit already
2195 * in `seed`, plus a contiguous falling stack sitting on them.
2196 */
2197GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
2198{
2199 var falling = [];
2200 for (var i = 0; i < this.blocks.length; i++)
2201 {
2202 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
2203 { falling.push(this.blocks[i]); }
2204 }
2205 falling.sort(function (a, b) { return a.y - b.y; });
2206 var include = Object.create(null);
2207 var queue = [];
2208 function enqueue (b)
2209 {
2210 if (!b || include[b.id])
2211 { return; }
2212 include[b.id] = true;
2213 queue.push(b);
2214 }
2215 if (seed)
2216 {
2217 for (var s = 0; s < seed.length; s++)
2218 { enqueue(seed[s]); }
2219 }
2220 // Also include falling that already overlap the anchor.
2221 if (anchor)
2222 {
2223 for (var i = 0; i < falling.length; i++)
2224 {
2225 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
2226 { enqueue(falling[i]); }
2227 }
2228 }
2229 for (var q = 0; q < queue.length; q++)
2230 {
2231 var a = queue[q];
2232 for (var i = 0; i < falling.length; i++)
2233 {
2234 var b = falling[i];
2235 if (include[b.id])
2236 { continue; }
2237 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
2238 { enqueue(b); }
2239 }
2240 }
2241 var out = [];
2242 for (var i = 0; i < falling.length; i++)
2243 {
2244 if (include[falling[i].id])
2245 { out.push(falling[i]); }
2246 }
2247 return out;
2248};
2249
2250/**
2251 * Merge a thrown (manual) block with falling blocks into one flying
2252 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
2253 * averages by block count, identical to mergeClusterGroup. The thrown
2254 * block stops being manual and the group follows normal cluster physics.
2255 * fromManual marks the cluster so later falling cargo also averages in.
2256 */
2257GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
2258{
2259 if (!manual || manual.state !== STATE_MANUAL)
2260 { return null; }
2261 var blocks = [manual];
2262 for (var i = 0; i < fallingList.length; i++)
2263 {
2264 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
2265 { blocks.push(fallingList[i]); }
2266 }
2267 if (blocks.length < 2)
2268 { return null; }
2269 var n = blocks.length;
2270 var vySum = 0;
2271 var decelSum = 0;
2272 var hSum = 0;
2273 for (var i = 0; i < n; i++)
2274 {
2275 var b = blocks[i];
2276 vySum += b.vy;
2277 if (b === manual)
2278 {
2279 decelSum += manual.manualDecel || 0;
2280 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
2281 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
2282 }
2283 }
2284 var cluster = {
2285 id: this.nextClusterId++,
2286 jumpHeight: hSum / n,
2287 vy: vySum / n,
2288 decel: decelSum / n,
2289 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
2290 fromManual: true
2291 };
2292 this.clusters[cluster.id] = cluster;
2293 for (var i = 0; i < n; i++)
2294 {
2295 var b = blocks[i];
2296 b.clusterId = cluster.id;
2297 b.state = STATE_FLYING;
2298 b.vy = cluster.vy;
2299 b.flame = b.color === COLOR_GRAY;
2300 b.manualPhase = null;
2301 b.manualTarget = null;
2302 b.manualDecel = 0;
2303 b.manualJumpHeight = 0;
2304 b.pushedClusters = null;
2305 b.settleTime = 0;
2306 }
2307 if (this.drag && this.drag.blockId === manual.id)
2308 { this.drag = null; }
2309 this.prepareClusterBody(cluster);
2310 this.checkChainRelaunch(cluster);
2311 return cluster;
2312};
2313
2314/** Safety net: any remaining manual/falling overlaps after the substep. */
2315GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
2316{
2317 var manuals = [];
2318 for (var i = 0; i < this.blocks.length; i++)
2319 {
2320 if (this.blocks[i].state === STATE_MANUAL)
2321 { manuals.push(this.blocks[i]); }
2322 }
2323 for (var m = 0; m < manuals.length; m++)
2324 {
2325 var manual = manuals[m];
2326 if (manual.state !== STATE_MANUAL)
2327 { continue; }
2328 var hits = this.contiguousFallingInColumn(manual.col, manual);
2329 if (hits.length)
2330 { this.mergeManualWithFalling(manual, hits); }
2331 }
2332};
2333
2334/**
2335 * Resolve collisions of a thrown (manual) block along [oldY, nextY].
2336 * Falling blocks merge (t1108). A flying cluster is pushed one cell up
2337 * in the hit column and the shot attaches at the bottom (t1111).
2338 * Another thrown block is promoted to a 1-block cluster and then the
2339 * same attach-at-bottom rule applies. Returns true if `manual` is no
2340 * longer in the MANUAL state.
2341 */
2342GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY)
2343{
2344 if (!manual || manual.state !== STATE_MANUAL)
2345 { return true; }
2346
2347 var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY);
2348 if (fallingHits.length)
2349 {
2350 this.mergeManualWithFalling(manual, fallingHits);
2351 return manual.state !== STATE_MANUAL;
2352 }
2353
2354 var flyer = this.flyingHitOnManualPath(manual, oldY, nextY);
2355 if (flyer)
2356 {
2357 var cluster = this.clusters[flyer.clusterId];
2358 if (cluster && cluster.phase !== 'landed')
2359 {
2360 if (nextY + 1e-12 < oldY)
2361 { this.attachToFlyingCluster(manual, flyer); }
2362 else
2363 { this.attachShotUnderCluster(manual, cluster, manual.col); }
2364 return manual.state !== STATE_MANUAL;
2365 }
2366 }
2367
2368 var other = this.manualHitOnManualPath(manual, oldY, nextY);
2369 if (other)
2370 {
2371 var host = this.promoteManualToCluster(other);
2372 if (host)
2373 {
2374 if (nextY + 1e-12 < oldY)
2375 { this.attachToFlyingCluster(manual, other); }
2376 else
2377 { this.attachShotUnderCluster(manual, host, manual.col); }
2378 return manual.state !== STATE_MANUAL;
2379 }
2380 }
2381 return false;
2382};
2383
2384/** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */
2385GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY)
2386{
2387 var lo = Math.min(oldY, nextY);
2388 var hi = Math.max(oldY, nextY) + 1;
2389 var best = null;
2390 var bestY = Infinity;
2391 for (var i = 0; i < this.blocks.length; i++)
2392 {
2393 var other = this.blocks[i];
2394 if (other === manual || other.col !== manual.col)
2395 { continue; }
2396 if (other.state !== STATE_FLYING || other.clusterId == null)
2397 { continue; }
2398 var cluster = this.clusters[other.clusterId];
2399 if (!cluster || cluster.phase === 'landed')
2400 { continue; }
2401 var o0 = (other._prevY != null) ? other._prevY : other.y;
2402 var o1 = other.y;
2403 var oLo = Math.min(o0, o1);
2404 var oHi = Math.max(o0, o1) + 1;
2405 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
2406 {
2407 if (other.y < bestY)
2408 {
2409 bestY = other.y;
2410 best = other;
2411 }
2412 }
2413 }
2414 return best;
2415};
2416
2417/** Another thrown block in the same column on the path (prefer the lower). */
2418GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY)
2419{
2420 var lo = Math.min(oldY, nextY);
2421 var hi = Math.max(oldY, nextY) + 1;
2422 var best = null;
2423 for (var i = 0; i < this.blocks.length; i++)
2424 {
2425 var other = this.blocks[i];
2426 if (other === manual || other.col !== manual.col)
2427 { continue; }
2428 if (other.state !== STATE_MANUAL)
2429 { continue; }
2430 var o0 = (other._prevY != null) ? other._prevY : other.y;
2431 var o1 = other.y;
2432 var oLo = Math.min(o0, o1);
2433 var oHi = Math.max(o0, o1) + 1;
2434 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
2435 {
2436 if (!best || other.y < best.y)
2437 { best = other; }
2438 }
2439 }
2440 return best;
2441};
2442
2443/**
2444 * t1111: push every member of `cluster` in `col` up by one cell, then
2445 * attach `manual` at the bottom of that column, grid-aligned, as part
2446 * of the cluster. The cluster keeps its velocity; the shot takes it.
2447 * Other columns are untouched. Same rule for every successive shot.
2448 */
2449GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col)
2450{
2451 if (!manual || !cluster || !this.clusters[cluster.id])
2452 { return false; }
2453 if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id)
2454 {
2455 // Already belonging elsewhere: leave first.
2456 if (manual.clusterId != null)
2457 { this.leaveCluster(manual); }
2458 }
2459 this.prepareClusterBody(cluster);
2460 var members = this.clusterMembers(cluster.id);
2461 var minOff = null;
2462 for (var i = 0; i < members.length; i++)
2463 {
2464 if (members[i].col !== col)
2465 { continue; }
2466 if (minOff == null || members[i].clusterOffset < minOff)
2467 { minOff = members[i].clusterOffset; }
2468 }
2469 if (minOff == null)
2470 { minOff = 0; }
2471 else
2472 {
2473 for (var i = 0; i < members.length; i++)
2474 {
2475 if (members[i].col === col)
2476 { members[i].clusterOffset += 1; }
2477 }
2478 }
2479 if (this.drag && this.drag.blockId === manual.id)
2480 { this.drag = null; }
2481 manual.clusterId = cluster.id;
2482 manual.clusterOffset = minOff;
2483 manual.state = STATE_FLYING;
2484 manual.flame = manual.color === COLOR_GRAY;
2485 manual.settleTime = 0;
2486 manual.manualPhase = null;
2487 manual.manualTarget = null;
2488 manual.manualDecel = 0;
2489 manual.manualJumpHeight = 0;
2490 manual.pushedClusters = null;
2491 this.syncClusterMembers(cluster);
2492 this.cullOffTop();
2493 if (this.clusters[cluster.id])
2494 { this.checkChainRelaunch(cluster); }
2495 return true;
2496};
2497
2498/**
2499 * Turn a lone thrown block into a 1-block flying cluster so a later
2500 * shot can use the t1111 attach-at-bottom rule. A single throw stays
2501 * MANUAL (and is capped at the top of the field) until it collides.
2502 */
2503GameCore.prototype.promoteManualToCluster = function (manual)
2504{
2505 if (!manual)
2506 { return null; }
2507 if (manual.state === STATE_FLYING && manual.clusterId != null)
2508 {
2509 var existing = this.clusters[manual.clusterId];
2510 if (existing && existing.phase !== 'landed')
2511 { return existing; }
2512 }
2513 if (manual.state !== STATE_MANUAL)
2514 { return null; }
2515 var height = manual.manualJumpHeight != null ? manual.manualJumpHeight
2516 : Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y);
2517 var cluster = {
2518 id: this.nextClusterId++,
2519 jumpHeight: height,
2520 vy: manual.vy,
2521 decel: manual.manualDecel || 0,
2522 phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up',
2523 fromManual: true,
2524 anchorY: manual.y
2525 };
2526 this.clusters[cluster.id] = cluster;
2527 manual.state = STATE_FLYING;
2528 manual.clusterId = cluster.id;
2529 manual.clusterOffset = 0;
2530 manual.flame = manual.color === COLOR_GRAY;
2531 manual.settleTime = 0;
2532 manual.manualPhase = null;
2533 manual.manualTarget = null;
2534 manual.manualDecel = 0;
2535 manual.manualJumpHeight = 0;
2536 manual.pushedClusters = null;
2537 this.syncClusterMembers(cluster);
2538 return cluster;
2539};
2540
2541/** Kept for older tests / call sites: push a cluster column by one cell. */
2542GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
2543{
2544 return this.resolveManualCollisions(manual, oldY, nextY);
2545};
2546
2547
2548/**
2549 * Push every flying block of the cluster that sits in `col` one tile up.
2550 * Other columns stay put (they remain linked). Then look for a new
2551 * same-color line of 3+ in the flying cluster; if there is one, those
2552 * blocks turn gray, join the link, and the whole cluster re-launches
2553 * with the same jump height from its current position.
2554 */
2555GameCore.prototype.pushClusterColumn = function (clusterId, col)
2556{
2557 var cluster = this.clusters[clusterId];
2558 if (!cluster)
2559 { return false; }
2560 var members = this.clusterMembers(clusterId);
2561 for (var i = 0; i < members.length; i++)
2562 {
2563 if (members[i].col === col)
2564 { members[i].y += 1; }
2565 }
2566 this.cullOffTop();
2567 if (!this.clusters[clusterId])
2568 { return true; }
2569 this.checkChainRelaunch(cluster);
2570 return true;
2571};
2572
2573/**
2574 * After a cargo attach or a cluster merge (or any other mid-air state
2575 * change), turn spontaneous lines of 3+ into rockets and give the whole
2576 * already-flying cluster an extra launch from its current position —
2577 * the same re-launch as a player push that completes a row.
2578 */
2579GameCore.prototype.resolveFlyingMatches = function ()
2580{
2581 var ids = Object.keys(this.clusters);
2582 for (var n = 0; n < ids.length; n++)
2583 {
2584 var cluster = this.clusters[ids[n]];
2585 if (!cluster || cluster.phase === 'landed')
2586 { continue; }
2587 this.checkChainRelaunch(cluster);
2588 }
2589};
2590
2591GameCore.prototype.checkChainRelaunch = function (cluster)
2592{
2593 if (!this.clusters[cluster.id])
2594 { return; }
2595 var lines = this.findFlyingMatchLines(cluster.id);
2596 if (!lines.length)
2597 { return; }
2598 var newly = [];
2599 var seen = Object.create(null);
2600 for (var i = 0; i < lines.length; i++)
2601 {
2602 for (var j = 0; j < lines[i].blocks.length; j++)
2603 {
2604 var block = lines[i].blocks[j];
2605 if (seen[block.id])
2606 { continue; }
2607 seen[block.id] = true;
2608 newly.push(block);
2609 }
2610 }
2611 for (var i = 0; i < newly.length; i++)
2612 {
2613 var block = newly[i];
2614 block.color = COLOR_GRAY;
2615 block.flame = true;
2616 block.clusterId = cluster.id;
2617 block.state = STATE_FLYING;
2618 }
2619 this.relaunchCluster(cluster, cluster.jumpHeight);
2620};
2621
2622GameCore.prototype.relaunchCluster = function (cluster, height)
2623{
2624 cluster.jumpHeight = height;
2625 cluster.vy = PlanetMod.launchVelocity(this.planet, height);
2626 cluster.decel = PlanetMod.launchDeceleration(this.planet, height);
2627 cluster.phase = 'up';
2628 var members = this.clusterMembers(cluster.id);
2629 for (var i = 0; i < members.length; i++)
2630 {
2631 members[i].vy = cluster.vy;
2632 members[i].state = STATE_FLYING;
2633 if (members[i].color === COLOR_GRAY)
2634 { members[i].flame = true; }
2635 }
2636};
2637
2638GameCore.prototype.startManualLaunch = function (block)
2639{
2640 var target = this.height - 1;
2641 var height = Math.max(0.05, target - block.y);
2642 this.leaveCluster(block);
2643 block.state = STATE_MANUAL;
2644 block.pushedClusters = Object.create(null);
2645 block.manualTarget = target;
2646 block.manualPhase = 'up';
2647 block.manualJumpHeight = height;
2648 block.vy = PlanetMod.launchVelocity(this.planet, height);
2649 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
2650 block.flame = false;
2651 if (this.drag && this.drag.blockId === block.id)
2652 { this.drag = null; }
2653};
2654
2655GameCore.prototype.cullOffTop = function ()
2656{
2657 var gone = [];
2658 for (var i = 0; i < this.blocks.length; i++)
2659 {
2660 var block = this.blocks[i];
2661 if (block.state === STATE_MANUAL)
2662 {
2663 if (block.y > this.height - 1)
2664 { block.y = this.height - 1; }
2665 continue;
2666 }
2667 if (block.y >= this.height - 1e-9)
2668 { gone.push(block); }
2669 }
2670 for (var i = 0; i < gone.length; i++)
2671 {
2672 var block = gone[i];
2673 this.outgoingShots.push({
2674 id: block.id,
2675 color: block.color,
2676 col: block.col,
2677 y: block.y
2678 });
2679 this.score += 1;
2680 this.removeBlock(block);
2681 }
2682};
2683
2684GameCore.prototype.consumeOutgoingShots = function ()
2685{
2686 var shots = this.outgoingShots;
2687 this.outgoingShots = [];
2688 return shots;
2689};
2690
2691/**
2692 * A compact field picture for the multiplayer snapshot (miniatures).
2693 * Includes every block's col, y, color, state and flame.
2694 */
2695GameCore.prototype.fieldSnapshot = function ()
2696{
2697 var blocks = [];
2698 for (var i = 0; i < this.blocks.length; i++)
2699 {
2700 var b = this.blocks[i];
2701 blocks.push({
2702 id: b.id,
2703 col: b.col,
2704 y: Math.round(b.y * 1000) / 1000,
2705 color: b.color,
2706 state: b.state,
2707 flame: !!b.flame
2708 });
2709 }
2710 return {
2711 score: this.score,
2712 state: this.state,
2713 width: this.width,
2714 height: this.height,
2715 locked: this.lockedColumnCount(),
2716 blocks: blocks
2717 };
2718};
2719
2720/**
2721 * Incoming garbage from another player: a dark-grey block that falls
2722 * normally from the top of an open column. After landing it uses the
2723 * usual 3s settle and then a random colour (landFallingBlock).
2724 * `col` is optional; a random eligible column is used otherwise.
2725 * Returns the new block, or null if every column is locked or full.
2726 */
2727GameCore.prototype.ingestGarbage = function (col)
2728{
2729 if (this.state !== 'playing')
2730 { return null; }
2731 var chosen = null;
2732 if (col != null && col >= 0 && col < this.width
2733 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
2734 { chosen = col | 0; }
2735 else
2736 {
2737 var eligible = [];
2738 for (var c = 0; c < this.width; c++)
2739 {
2740 if (this.isColumnLocked(c))
2741 { continue; }
2742 if (this.groundedCount(c) >= this.height)
2743 { continue; }
2744 eligible.push(c);
2745 }
2746 if (!eligible.length)
2747 { return null; }
2748 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2749 }
2750 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2751 block.vy = -this.planet.fallSpeed;
2752 block.flame = false;
2753 return block;
2754};
2755
2756GameCore.prototype.advanceSettle = function (dt)
2757{
2758 for (var i = 0; i < this.blocks.length; i++)
2759 {
2760 var block = this.blocks[i];
2761 if (block.state !== STATE_SETTLING)
2762 { continue; }
2763 var inLanded = block.clusterId != null
2764 && this.clusters[block.clusterId]
2765 && this.clusters[block.clusterId].phase === 'landed';
2766 if (block.color === COLOR_GRAY)
2767 {
2768 block.settleTime += dt;
2769 if (block.settleTime >= this.settleTime)
2770 {
2771 block.color = this.randomColor();
2772 block.settleTime = 0;
2773 block.flame = false;
2774 if (inLanded)
2775 {
2776 // Stay in the rigid group; releaseLandedCluster runs below.
2777 block.state = STATE_SETTLING;
2778 }
2779 else
2780 {
2781 this.leaveCluster(block);
2782 this.clearFlightState(block);
2783 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2784 }
2785 }
2786 }
2787 else if (!inLanded)
2788 {
2789 // Coloured settling that is not in a landed cluster (shouldn't
2790 // normally happen): just become still or fall, from rest.
2791 this.leaveCluster(block);
2792 this.clearFlightState(block);
2793 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2794 }
2795 }
2796
2797 var ids = Object.keys(this.clusters);
2798 for (var n = 0; n < ids.length; n++)
2799 {
2800 var cluster = this.clusters[ids[n]];
2801 if (!cluster || cluster.phase !== 'landed')
2802 { continue; }
2803 var members = this.clusterMembers(cluster.id);
2804 var greySettling = false;
2805 for (var i = 0; i < members.length; i++)
2806 {
2807 if (members[i].color === COLOR_GRAY && members[i].state === STATE_SETTLING)
2808 { greySettling = true; }
2809 }
2810 if (!greySettling)
2811 { this.releaseLandedCluster(cluster); }
2812 }
2813};
2814
2815GameCore.prototype.findMatchLines = function ()
2816{
2817 var candidates = [];
2818 for (var i = 0; i < this.blocks.length; i++)
2819 {
2820 var block = this.blocks[i];
2821 // Coloured cargo in a just-landed cluster (SETTLING) can match
2822 // with already-resting blocks immediately (t1110). Greys have no
2823 // colour and wait until they recolor; after release they are STILL.
2824 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
2825 && block.color >= 0)
2826 { candidates.push(block); }
2827 }
2828 return this.collectLines(candidates, true);
2829};
2830
2831GameCore.prototype.findFlyingMatchLines = function (clusterId)
2832{
2833 var candidates = [];
2834 for (var i = 0; i < this.blocks.length; i++)
2835 {
2836 var block = this.blocks[i];
2837 if (block.clusterId === clusterId && block.color >= 0
2838 && (block.state === STATE_FLYING))
2839 { candidates.push(block); }
2840 }
2841 return this.collectLines(candidates, false);
2842};
2843
2844GameCore.prototype.collectLines = function (candidates, snapInteger)
2845{
2846 var lines = [];
2847 if (!candidates.length)
2848 { return lines; }
2849
2850 var byRow = Object.create(null);
2851 for (var i = 0; i < candidates.length; i++)
2852 {
2853 var block = candidates[i];
2854 var row = Math.round(block.y);
2855 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
2856 { continue; }
2857 if (!byRow[row])
2858 { byRow[row] = []; }
2859 byRow[row].push(block);
2860 }
2861 var rows = Object.keys(byRow);
2862 for (var r = 0; r < rows.length; r++)
2863 {
2864 var list = byRow[rows[r]];
2865 list.sort(function (a, b) { return a.col - b.col; });
2866 this.pushRuns(lines, list, false, function (a, b)
2867 {
2868 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
2869 });
2870 }
2871
2872 var byCol = Object.create(null);
2873 for (var i = 0; i < candidates.length; i++)
2874 {
2875 var block = candidates[i];
2876 if (!byCol[block.col])
2877 { byCol[block.col] = []; }
2878 byCol[block.col].push(block);
2879 }
2880 var cols = Object.keys(byCol);
2881 for (var c = 0; c < cols.length; c++)
2882 {
2883 var list = byCol[cols[c]];
2884 list.sort(function (a, b) { return a.y - b.y; });
2885 this.pushRuns(lines, list, true, function (a, b)
2886 {
2887 return a.color === b.color && a.color >= 0
2888 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
2889 });
2890 }
2891 return lines;
2892};
2893
2894GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
2895{
2896 var start = 0;
2897 for (var i = 1; i <= list.length; i++)
2898 {
2899 var same = i < list.length && adjacent(list[i - 1], list[i]);
2900 if (!same)
2901 {
2902 var length = i - start;
2903 if (length >= 3)
2904 {
2905 lines.push({
2906 blocks: list.slice(start, i),
2907 length: length,
2908 vertical: vertical
2909 });
2910 }
2911 start = i;
2912 }
2913 }
2914};
2915
2916GameCore.prototype.resolveMatches = function ()
2917{
2918 if (this.state !== 'playing' || this.drag)
2919 { return []; }
2920 var lines = this.findMatchLines();
2921 if (!lines.length)
2922 {
2923 this.finishLandingChains([]);
2924 return [];
2925 }
2926
2927 var uf = new UnionFind();
2928 var blockById = Object.create(null);
2929 for (var i = 0; i < lines.length; i++)
2930 {
2931 var line = lines[i];
2932 for (var j = 0; j < line.blocks.length; j++)
2933 {
2934 uf.add(line.blocks[j].id);
2935 blockById[line.blocks[j].id] = line.blocks[j];
2936 if (j > 0)
2937 { uf.union(line.blocks[0].id, line.blocks[j].id); }
2938 }
2939 }
2940 var matched = [];
2941 var seen = Object.create(null);
2942 for (var id in blockById)
2943 {
2944 if (!seen[id])
2945 {
2946 seen[id] = true;
2947 matched.push(blockById[id]);
2948 }
2949 }
2950 for (var i = 0; i < matched.length; i++)
2951 {
2952 for (var j = i + 1; j < matched.length; j++)
2953 {
2954 if (matched[i].col === matched[j].col)
2955 { uf.union(matched[i].id, matched[j].id); }
2956 }
2957 }
2958
2959 var groups = Object.create(null);
2960 for (var i = 0; i < matched.length; i++)
2961 {
2962 var root = uf.find(matched[i].id);
2963 if (!groups[root])
2964 { groups[root] = []; }
2965 groups[root].push(matched[i]);
2966 }
2967
2968 var launched = [];
2969 for (var root in groups)
2970 {
2971 var group = groups[root];
2972 var height = 0;
2973 for (var i = 0; i < lines.length; i++)
2974 {
2975 var line = lines[i];
2976 var overlaps = false;
2977 for (var j = 0; j < line.blocks.length; j++)
2978 {
2979 for (var k = 0; k < group.length; k++)
2980 {
2981 if (line.blocks[j].id === group[k].id)
2982 { overlaps = true; }
2983 }
2984 }
2985 if (overlaps)
2986 {
2987 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
2988 if (h > height)
2989 { height = h; }
2990 }
2991 }
2992 var chain = this.landingChainFor(group);
2993 var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;
2994 height *= bonusMul;
2995 this.launchCluster(group, height, { landingChain: chain });
2996 launched.push({
2997 blocks: group,
2998 jumpHeight: height,
2999 landingChain: chain,
3000 chainBonus: bonusMul
3001 });
3002 }
3003 this.finishLandingChains(launched);
3004 this.updateChainIndicator(launched);
3005 return launched;
3006};
3007
3008/**
3009 * Gray the matched blocks, take everything sitting on top of them in
3010 * those columns, link them, and launch with jump height `height`.
3011 */
3012GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)
3013{
3014 opts = opts || {};
3015 var lowestInCol = Object.create(null);
3016 var matchedIds = Object.create(null);
3017 for (var i = 0; i < matchedBlocks.length; i++)
3018 {
3019 var block = matchedBlocks[i];
3020 matchedIds[block.id] = true;
3021 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
3022 { lowestInCol[block.col] = block.y; }
3023 }
3024
3025 var clusterId = this.nextClusterId++;
3026 var cluster = {
3027 id: clusterId,
3028 jumpHeight: height,
3029 vy: PlanetMod.launchVelocity(this.planet, height),
3030 decel: PlanetMod.launchDeceleration(this.planet, height),
3031 phase: 'up',
3032 landingChain: opts.landingChain || 0,
3033 landedPending: false
3034 };
3035 this.clusters[clusterId] = cluster;
3036
3037 var riders = [];
3038 var cols = Object.keys(lowestInCol);
3039 for (var c = 0; c < cols.length; c++)
3040 {
3041 var col = +cols[c];
3042 var lowest = lowestInCol[col];
3043 var list = this.blocksInColumn(col);
3044 for (var i = 0; i < list.length; i++)
3045 {
3046 var block = list[i];
3047 if (!this.isGrounded(block) && block.state !== STATE_STILL)
3048 {
3049 if (block.state !== STATE_SETTLING)
3050 { continue; }
3051 }
3052 if (block.y + ALIGN_EPS >= lowest)
3053 { riders.push(block); }
3054 }
3055 }
3056
3057 for (var i = 0; i < riders.length; i++)
3058 {
3059 var block = riders[i];
3060 var isMatch = !!matchedIds[block.id];
3061 if (isMatch || block.color === COLOR_GRAY)
3062 {
3063 block.color = COLOR_GRAY;
3064 block.flame = true;
3065 }
3066 else
3067 { block.flame = false; }
3068 block.state = STATE_FLYING;
3069 block.clusterId = clusterId;
3070 block.vy = cluster.vy;
3071 block.settleTime = 0;
3072 }
3073 this.prepareClusterBody(cluster);
3074 return cluster;
3075};
3076
3077GameCore.prototype.checkLocks = function ()
3078{
3079 for (var col = 0; col < this.width; col++)
3080 {
3081 if (this.isColumnLocked(col))
3082 { continue; }
3083 if (this.groundedCount(col) < this.height)
3084 { continue; }
3085 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
3086 var filled = true;
3087 for (var row = 0; row < this.height; row++)
3088 {
3089 var block = this.blockAt(col, row);
3090 if (!block || !this.isGrounded(block))
3091 {
3092 filled = false;
3093 break;
3094 }
3095 }
3096 if (!filled)
3097 { continue; }
3098 var list = this.blocksInColumn(col);
3099 for (var i = 0; i < list.length; i++)
3100 {
3101 var block = list[i];
3102 if (!this.isGrounded(block))
3103 { continue; }
3104 block.state = STATE_LOCKED;
3105 block.color = COLOR_GRAY;
3106 block.flame = false;
3107 block.vy = 0;
3108 block.settleTime = 0;
3109 if (block.clusterId != null)
3110 { this.leaveCluster(block); }
3111 }
3112 }
3113};
3114
3115GameCore.prototype.checkGameOver = function ()
3116{
3117 if (this.state !== 'playing')
3118 { return; }
3119 for (var col = 0; col < this.width; col++)
3120 {
3121 if (!this.isColumnLocked(col))
3122 { return; }
3123 }
3124 this.state = 'gameover';
3125 this.gameOverTime = 0;
3126 this.drag = null;
3127};
3128
3129/* ---------- dragging -------------------------------------------------- */
3130
3131GameCore.prototype.beginDrag = function (col, y)
3132{
3133 if (this.state !== 'playing')
3134 { return false; }
3135 var block = this.snapDragBlock(col, y);
3136 if (!block)
3137 { return false; }
3138 var top = this.columnStackTopRow(block.col);
3139 var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
3140 this.drag = {
3141 blockId: block.id,
3142 pointerY: y,
3143 startY: y,
3144 accum: 0,
3145 launchIntent: false,
3146 startedAsTop: startedAsTop
3147 };
3148 return true;
3149};
3150
3151/**
3152 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
3153 * floor(col), floor(y); any press inside that cell — corners, padding,
3154 * gaps between sprites, a visually tweened or bouncing sprite — grabs
3155 * the block that occupies it. This uses simulation cells, not the drawn
3156 * sprite bounds. If no block sits in that cell (mid-animation, a block
3157 * whose y is off the integer), fall back to the nearest grabbable block
3158 * in the same column within SNAP_Y (about half a tile). A small
3159 * horizontal slop still consults a neighbouring column when the press
3160 * is near the edge and the primary cell is empty.
3161 */
3162GameCore.prototype.snapDragBlock = function (col, y)
3163{
3164 var raw = col;
3165 var c0 = Math.floor(raw + 1e-9);
3166 var row = Math.floor(y + 1e-9);
3167 var frac = raw - c0;
3168
3169 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
3170 {
3171 var exact = this.draggableInCell(c0, row);
3172 if (exact)
3173 { return exact; }
3174 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
3175 if (near)
3176 { return near; }
3177 }
3178
3179 // Primary cell empty: allow a small horizontal slop into a neighbour.
3180 var neighbours = [];
3181 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
3182 { neighbours.push(c0 - 1); }
3183 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
3184 { neighbours.push(c0 + 1); }
3185 var best = null;
3186 var bestDist = Infinity;
3187 for (var n = 0; n < neighbours.length; n++)
3188 {
3189 var cc = neighbours[n];
3190 if (!this.columnAllowsDrag(cc))
3191 { continue; }
3192 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
3193 if (!hit)
3194 { continue; }
3195 var dist = this.pointerDistToBlock(hit, raw, y);
3196 if (dist < bestDist)
3197 {
3198 bestDist = dist;
3199 best = hit;
3200 }
3201 }
3202 return best;
3203};
3204
3205/** The draggable block that occupies grid cell (col, row), if any. */
3206GameCore.prototype.draggableInCell = function (col, row)
3207{
3208 var best = null;
3209 var bestOverlap = 0;
3210 var list = this.blocksInColumn(col);
3211 for (var i = 0; i < list.length; i++)
3212 {
3213 var block = list[i];
3214 if (!this.isDraggableBlock(block))
3215 { continue; }
3216 var lo = Math.max(block.y, row);
3217 var hi = Math.min(block.y + 1, row + 1);
3218 var overlap = hi - lo;
3219 if (overlap > bestOverlap + 1e-12)
3220 {
3221 bestOverlap = overlap;
3222 best = block;
3223 }
3224 }
3225 if (best && bestOverlap > 1e-9)
3226 { return best; }
3227 return null;
3228};
3229
3230/** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
3231GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
3232{
3233 var best = null;
3234 var bestDist = Infinity;
3235 var list = this.blocksInColumn(col);
3236 for (var i = 0; i < list.length; i++)
3237 {
3238 var block = list[i];
3239 if (!this.isDraggableBlock(block))
3240 { continue; }
3241 var dist = this.pointerDistToBlock(block, col + 0.5, y);
3242 if (dist < bestDist)
3243 {
3244 bestDist = dist;
3245 best = block;
3246 }
3247 }
3248 if (!best || bestDist > maxDist)
3249 { return null; }
3250 return best;
3251};
3252
3253GameCore.prototype.pointerDistToBlock = function (block, col, y)
3254{
3255 var dx;
3256 if (col >= block.col && col < block.col + 1)
3257 { dx = 0; }
3258 else if (col < block.col)
3259 { dx = block.col - col; }
3260 else
3261 { dx = col - (block.col + 1); }
3262 var dy;
3263 if (y >= block.y && y < block.y + 1)
3264 { dy = 0; }
3265 else if (y < block.y)
3266 { dy = block.y - y; }
3267 else
3268 { dy = y - (block.y + 1); }
3269 return Math.sqrt(dx * dx + dy * dy);
3270};
3271
3272GameCore.prototype.moveDrag = function (y)
3273{
3274 if (!this.drag)
3275 { return; }
3276 var block = this.blockById(this.drag.blockId);
3277 if (!block || !this.isDraggableBlock(block))
3278 {
3279 this.drag = null;
3280 return;
3281 }
3282 if (!this.columnAllowsDrag(block.col))
3283 {
3284 this.drag = null;
3285 return;
3286 }
3287 this.drag.pointerY = y;
3288 // 1:1 tracking: the target row is the one under the pointer, clamped
3289 // to the still stack. Swap step by step with each neighbour, and stop
3290 // exactly there. When the pointer stops, nothing else moves.
3291 // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
3292 // used to jump a full cell on a short pull, and one large event
3293 // could walk the entire column (the "jumps all the way" bug).
3294 var top = this.columnStackTopRow(block.col);
3295 var bottom = this.columnStackBottomRow(block.col);
3296 var target = Math.floor(y + 1e-12);
3297 if (bottom < 0)
3298 { bottom = 0; }
3299 if (target < bottom)
3300 { target = bottom; }
3301 if (target > top)
3302 { target = top; }
3303 this.swapToward(block, target);
3304
3305 top = this.columnStackTopRow(block.col);
3306 var isTop = Math.abs(block.y - top) < ALIGN_EPS;
3307 if (this.drag.startedAsTop)
3308 {
3309 // Already the topmost block: pulling upward past its own position
3310 // (LAUNCH_PULL tiles above the press point) starts a manual jump.
3311 this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL);
3312 }
3313 else
3314 {
3315 // Started mid-stack: swap first, and only launch once the pointer
3316 // is pulled into the empty space above the (new) top.
3317 this.drag.launchIntent = isTop && (y > top + 1 + 0.25);
3318 }
3319};
3320
3321/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
3322GameCore.prototype.swapOne = function (block, dir)
3323{
3324 var neighbor = this.blockAt(block.col, block.y + dir);
3325 if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
3326 {
3327 this.swapBlocks(block, neighbor);
3328 return true;
3329 }
3330 return false;
3331};
3332
3333GameCore.prototype.endDrag = function ()
3334{
3335 if (!this.drag)
3336 { return; }
3337 var block = this.blockById(this.drag.blockId);
3338 var launch = this.drag.launchIntent;
3339 this.drag = null;
3340 if (launch && block && block.state === STATE_STILL)
3341 { this.startManualLaunch(block); }
3342 else
3343 { this.resolveMatches(); }
3344};
3345
3346GameCore.prototype.blockById = function (id)
3347{
3348 for (var i = 0; i < this.blocks.length; i++)
3349 {
3350 if (this.blocks[i].id === id)
3351 { return this.blocks[i]; }
3352 }
3353 return null;
3354};
3355
3356GameCore.prototype.columnStackTopRow = function (col)
3357{
3358 var top = -1;
3359 var list = this.blocksInColumn(col);
3360 for (var i = 0; i < list.length; i++)
3361 {
3362 if (this.isGrounded(list[i]) && list[i].y > top)
3363 { top = list[i].y; }
3364 }
3365 return top;
3366};
3367
3368GameCore.prototype.columnStackBottomRow = function (col)
3369{
3370 var bottom = Infinity;
3371 var list = this.blocksInColumn(col);
3372 for (var i = 0; i < list.length; i++)
3373 {
3374 if (this.isGrounded(list[i]) && list[i].y < bottom)
3375 { bottom = list[i].y; }
3376 }
3377 return bottom === Infinity ? 0 : bottom;
3378};
3379
3380GameCore.prototype.swapToward = function (block, targetY)
3381{
3382 var guard = 0;
3383 while (guard++ < this.height + 2)
3384 {
3385 var current = block.y;
3386 if (targetY > current + 0.5)
3387 {
3388 var above = this.blockAt(block.col, current + 1);
3389 if (above && this.isGrounded(above) && above !== block)
3390 { this.swapBlocks(block, above); }
3391 else
3392 { break; }
3393 }
3394 else if (targetY < current - 0.5)
3395 {
3396 var below = this.blockAt(block.col, current - 1);
3397 if (below && this.isGrounded(below) && below !== block)
3398 { this.swapBlocks(block, below); }
3399 else
3400 { break; }
3401 }
3402 else
3403 { break; }
3404 }
3405};
3406
3407GameCore.prototype.swapBlocks = function (a, b)
3408{
3409 var ay = a.y;
3410 var by = b.y;
3411 a.y = by;
3412 b.y = ay;
3413 this.transferLandedMembership(a, b);
3414 if (!this.swapEvents)
3415 { this.swapEvents = []; }
3416 this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });
3417 this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });
3418};
3419
3420GameCore.prototype.consumeSwapEvents = function ()
3421{
3422 var ev = this.swapEvents || [];
3423 this.swapEvents = [];
3424 return ev;
3425};
3426
3427/**
3428 * Highest landing-chain counter among just-landed members of this
3429 * match group, plus one. Returns 0 when the match did not come from
3430 * a cluster landing (player/bot swap, mid-air, etc.).
3431 */
3432GameCore.prototype.landingChainFor = function (group)
3433{
3434 var maxChain = 0;
3435 var fromLanding = false;
3436 for (var i = 0; i < group.length; i++)
3437 {
3438 var block = group[i];
3439 if (block.justLanded)
3440 {
3441 fromLanding = true;
3442 if ((block.landingChain || 0) > maxChain)
3443 { maxChain = block.landingChain || 0; }
3444 }
3445 if (block.clusterId != null)
3446 {
3447 var cluster = this.clusters[block.clusterId];
3448 if (cluster && cluster.landedPending)
3449 {
3450 fromLanding = true;
3451 if ((cluster.landingChain || 0) > maxChain)
3452 { maxChain = cluster.landingChain || 0; }
3453 }
3454 }
3455 }
3456 if (!fromLanding)
3457 { return 0; }
3458 return maxChain + 1;
3459};
3460
3461/**
3462 * After resolveMatches: clear the landing-pending flag and reset the
3463 * chain on landings that did not make a match. A cluster that is still
3464 * settling (greys not yet recolored) keeps landedPending so a later
3465 * post-recolor match in this same landing still gets the bonus.
3466 */
3467GameCore.prototype.finishLandingChains = function (launched)
3468{
3469 var launchedIds = Object.create(null);
3470 launched = launched || [];
3471 for (var i = 0; i < launched.length; i++)
3472 {
3473 var blocks = launched[i].blocks || [];
3474 for (var j = 0; j < blocks.length; j++)
3475 { launchedIds[blocks[j].id] = true; }
3476 }
3477
3478 for (var i = 0; i < this.blocks.length; i++)
3479 {
3480 var block = this.blocks[i];
3481 if (!block.justLanded)
3482 { continue; }
3483 if (!launchedIds[block.id])
3484 { block.landingChain = 0; }
3485 block.justLanded = false;
3486 }
3487
3488 var ids = Object.keys(this.clusters);
3489 for (var c = 0; c < ids.length; c++)
3490 {
3491 var cluster = this.clusters[ids[c]];
3492 if (!cluster || !cluster.landedPending)
3493 { continue; }
3494 var members = this.clusterMembers(cluster.id);
3495 var anyLaunched = false;
3496 var stillSettling = false;
3497 for (var i = 0; i < members.length; i++)
3498 {
3499 if (launchedIds[members[i].id])
3500 { anyLaunched = true; }
3501 if (members[i].state === STATE_SETTLING)
3502 { stillSettling = true; }
3503 }
3504 if (anyLaunched)
3505 {
3506 cluster.landingChain = 0;
3507 cluster.landedPending = false;
3508 }
3509 else if (!stillSettling)
3510 {
3511 // Released leftovers or a fully-still landed group that
3512 // already had its match opportunity and missed it.
3513 cluster.landingChain = 0;
3514 cluster.landedPending = false;
3515 }
3516 // else: still settling, no match yet — keep landedPending.
3517 }
3518};
3519
3520GameCore.prototype.updateChainIndicator = function (launched)
3521{
3522 var maxChain = 0;
3523 for (var i = 0; i < launched.length; i++)
3524 {
3525 var ch = launched[i].landingChain || 0;
3526 if (ch > maxChain)
3527 { maxChain = ch; }
3528 }
3529 if (maxChain >= 1)
3530 {
3531 this.lastChainIndicator = {
3532 chain: maxChain,
3533 bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)
3534 };
3535 return;
3536 }
3537 if (!this.hasActiveLandingChain())
3538 { this.lastChainIndicator = null; }
3539};
3540
3541GameCore.prototype.hasActiveLandingChain = function ()
3542{
3543 var ids = Object.keys(this.clusters);
3544 for (var i = 0; i < ids.length; i++)
3545 {
3546 var cluster = this.clusters[ids[i]];
3547 if (cluster && (cluster.landingChain || 0) >= 1
3548 && cluster.phase !== 'landed')
3549 { return true; }
3550 }
3551 return false;
3552};
3553
3554/**
3555 * A landed cluster (grey rockets or linked cargo resting on the ground)
3556 * is a swappable part of the contiguous grounded stack. Flying, falling
3557 * and manual blocks are not. A locked column is not.
3558 */
3559GameCore.prototype.isDraggableBlock = function (block)
3560{
3561 if (!block)
3562 { return false; }
3563 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
3564 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
3565 { return false; }
3566 if (block.clusterId != null)
3567 {
3568 var cluster = this.clusters[block.clusterId];
3569 // Flying (rising / descending) clusters stay non-draggable.
3570 if (cluster && cluster.phase !== 'landed')
3571 { return false; }
3572 }
3573 return block.state === STATE_STILL || block.state === STATE_SETTLING;
3574};
3575
3576/**
3577 * The grounded contiguous stack in this column can be dragged, even if a
3578 * flying cluster or a falling spawn occupies the air above it. Only a
3579 * locked column is blocked as a whole.
3580 */
3581GameCore.prototype.columnAllowsDrag = function (col)
3582{
3583 return !this.isColumnLocked(col);
3584};
3585
3586GameCore.prototype.landedClusterId = function (block)
3587{
3588 if (!block || block.clusterId == null)
3589 { return null; }
3590 var cluster = this.clusters[block.clusterId];
3591 if (!cluster || cluster.phase !== 'landed')
3592 { return null; }
3593 return block.clusterId;
3594};
3595
3596/**
3597 * After a swap: leaving a landed cluster clears membership; joining one
3598 * makes the block part of that rigid group. Same-cluster swaps only
3599 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
3600 */
3601GameCore.prototype.transferLandedMembership = function (a, b)
3602{
3603 var ca = this.landedClusterId(a);
3604 var cb = this.landedClusterId(b);
3605 if (ca === cb)
3606 { return; }
3607 // Join first so leaveCluster does not delete a cluster that still
3608 // has the incoming member.
3609 this.applyLandedMembership(b, ca);
3610 this.applyLandedMembership(a, cb);
3611};
3612
3613GameCore.prototype.applyLandedMembership = function (block, clusterId)
3614{
3615 if (clusterId == null)
3616 {
3617 var wasGrey = block.color === COLOR_GRAY;
3618 var wasSettling = block.state === STATE_SETTLING;
3619 this.leaveCluster(block);
3620 if (wasGrey && wasSettling)
3621 {
3622 // Keep settling and recolor on its own, same remaining timer.
3623 block.state = STATE_SETTLING;
3624 }
3625 else if (wasSettling)
3626 {
3627 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
3628 }
3629 return;
3630 }
3631 if (!this.clusters[clusterId])
3632 { return; }
3633 block.clusterId = clusterId;
3634 block.flame = false;
3635 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
3636 { block.state = STATE_SETTLING; }
3637};
3638
3639/**
3640 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
3641 * Returns the moved block, or null if the column does not allow a drag.
3642 */
3643GameCore.prototype.swapTo = function (col, fromRow, toRow)
3644{
3645 if (!this.columnAllowsDrag(col))
3646 { return null; }
3647 var block = this.blockAt(col, fromRow);
3648 if (!block)
3649 { return null; }
3650 this.swapToward(block, toRow);
3651 return block;
3652};
3653
3654/**
3655 * Test helper: a compact picture of grounded/falling/flying blocks.
3656 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
3657 * L locked, f falling, m manual, . empty. Flying colored blocks use
3658 * their color with a marker in `flying`.
3659 */
3660GameCore.prototype.snapshot = function ()
3661{
3662 var grid = [];
3663 for (var r = 0; r < this.height; r++)
3664 {
3665 var row = [];
3666 for (var c = 0; c < this.width; c++)
3667 { row.push('.'); }
3668 grid.push(row);
3669 }
3670 var airborne = [];
3671 for (var i = 0; i < this.blocks.length; i++)
3672 {
3673 var block = this.blocks[i];
3674 var ch;
3675 if (block.state === STATE_LOCKED)
3676 { ch = 'L'; }
3677 else if (block.color === COLOR_GRAY)
3678 { ch = 'g'; }
3679 else
3680 { ch = String(block.color); }
3681 if (this.isGrounded(block) || block.state === STATE_FALLING)
3682 {
3683 var row = Math.round(block.y);
3684 if (row >= 0 && row < this.height)
3685 { grid[row][block.col] = ch; }
3686 }
3687 else
3688 {
3689 airborne.push({
3690 id: block.id,
3691 col: block.col,
3692 y: block.y,
3693 color: block.color,
3694 state: block.state,
3695 clusterId: block.clusterId,
3696 flame: block.flame,
3697 vy: block.vy
3698 });
3699 }
3700 }
3701 var lines = [];
3702 for (var r = this.height - 1; r >= 0; r--)
3703 { lines.push(grid[r].join('')); }
3704 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
3705};
3706
3707var GameCoreAPI = {
3708 GameCore: GameCore,
3709 COLOR_GRAY: COLOR_GRAY,
3710 STATE_STILL: STATE_STILL,
3711 STATE_FALLING: STATE_FALLING,
3712 STATE_FLYING: STATE_FLYING,
3713 STATE_SETTLING: STATE_SETTLING,
3714 STATE_LOCKED: STATE_LOCKED,
3715 STATE_MANUAL: STATE_MANUAL
3716};
3717
3718if (typeof module !== 'undefined' && module.exports)
3719{ module.exports = GameCoreAPI; }
3720else if (typeof globalThis !== 'undefined')
3721{
3722 globalThis.GameCore = GameCore;
3723 globalThis.GameCoreAPI = GameCoreAPI;
3724}
3725
3726/*
3727 * End File:
3728 * /workspace/meteors/src/gameCore.js
3729 */
3730
3731/*
3732 * Start File:
3733 * /workspace/meteors/src/online.js
3734 */
3735'use strict';
3736
3737/**
3738 * Online play: talks to api.php (cookie session), polls lobby and game
3739 * state, and draws opponent miniatures plus flying-block tweens.
3740 * Real-time sync is not required; a 0.75 s poll is enough.
3741 */
3742
3743var Online = {
3744 POLL_MS: 750,
3745 DEFAULT_MISS_CHANCE: 0.30,
3746 FLIGHT_DURATION: 1.2,
3747 configured: false,
3748 local: false,
3749 csrf: '',
3750 me: null,
3751 lobby: null,
3752 incoming: [],
3753 shotResults: [],
3754 error: '',
3755 _timer: null,
3756 _pendingShots: [],
3757 _flights: [],
3758 _lastStatus: null,
3759 onChange: null,
3760 onGameStart: null,
3761 onIncoming: null,
3762 onFinished: null,
3763 onLobbyReturn: null
3764};
3765
3766Online._headers = function (json)
3767{
3768 var h = { 'Accept': 'application/json' };
3769 if (json)
3770 { h['Content-Type'] = 'application/json'; }
3771 if (this.csrf)
3772 { h['X-CSRF-Token'] = this.csrf; }
3773 return h;
3774};
3775
3776Online._apply = function (data)
3777{
3778 if (!data)
3779 { return; }
3780 if (typeof data.configured === 'boolean')
3781 { this.configured = data.configured; }
3782 if (typeof data.local === 'boolean')
3783 { this.local = data.local; }
3784 if (data.csrf)
3785 { this.csrf = data.csrf; }
3786 if (data.me !== undefined)
3787 { this.me = data.me; }
3788 if (data.lobby !== undefined)
3789 { this.lobby = data.lobby; }
3790 if (data.incoming)
3791 { this.incoming = data.incoming; }
3792 if (data.shot_results)
3793 { this.shotResults = data.shot_results; }
3794 if (data.miss_chance_default != null)
3795 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
3796 if (data.flight_duration != null)
3797 { this.FLIGHT_DURATION = data.flight_duration; }
3798 if (data.error)
3799 { this.error = data.error; }
3800 else if (data.ok)
3801 { this.error = ''; }
3802};
3803
3804Online.request = function (action, body)
3805{
3806 var self = this;
3807 var isGet = action === 'me' || action === '';
3808 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
3809 var opts = {
3810 method: isGet && !body ? 'GET' : 'POST',
3811 credentials: 'same-origin',
3812 headers: this._headers(!!body || !isGet)
3813 };
3814 if (opts.method === 'POST')
3815 {
3816 var payload = body ? Object.assign({ action: action }, body) : { action: action };
3817 opts.body = JSON.stringify(payload);
3818 }
3819 return fetch(url, opts).then(function (res)
3820 {
3821 return res.json().then(function (data)
3822 {
3823 data = data || {};
3824 if (!res.ok && !data.error)
3825 { data.error = 'De server gaf ' + res.status; data.ok = false; }
3826 self._apply(data);
3827 return data;
3828 }, function ()
3829 {
3830 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
3831 self.error = fail.error;
3832 return fail;
3833 });
3834 }).catch(function (err)
3835 {
3836 var fail = { ok: false, error: 'Geen verbinding met de server.' };
3837 self.error = fail.error;
3838 return fail;
3839 });
3840};
3841
3842Online.refresh = function ()
3843{
3844 return this.request('me');
3845};
3846
3847Online.testLogin = function (who)
3848{
3849 return this.request('test_login', { user: who });
3850};
3851
3852Online.createLobby = function (planetId)
3853{
3854 return this.request('lobby_create', {
3855 miss_chance: this.DEFAULT_MISS_CHANCE,
3856 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
3857 });
3858};
3859
3860Online.joinLobby = function (code, planetId)
3861{
3862 return this.request('lobby_join', {
3863 code: code,
3864 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
3865 });
3866};
3867
3868Online.setPlanet = function (planetId)
3869{
3870 return this.request('lobby_set_planet', { planet_id: planetId });
3871};
3872
3873Online.leaveLobby = function ()
3874{
3875 return this.request('lobby_leave');
3876};
3877
3878Online.setReady = function (ready)
3879{
3880 return this.request('lobby_ready', { ready: !!ready });
3881};
3882
3883Online.startGame = function ()
3884{
3885 var self = this;
3886 var prev = this.lobby && this.lobby.status;
3887 return this.request('lobby_start').then(function (data)
3888 {
3889 self._handleTransitions(prev, data);
3890 return data;
3891 });
3892};
3893
3894Online.queueShots = function (shots)
3895{
3896 for (var i = 0; i < shots.length; i++)
3897 {
3898 this._pendingShots.push({
3899 client_id: String(shots[i].id),
3900 color: shots[i].color,
3901 col: shots[i].col,
3902 y: shots[i].y
3903 });
3904 }
3905};
3906
3907Online.poll = function (opts)
3908{
3909 opts = opts || {};
3910 var body = {};
3911 if (opts.snapshot)
3912 { body.snapshot = opts.snapshot; }
3913 if (opts.score != null)
3914 { body.score = opts.score; }
3915 if (opts.eliminated)
3916 { body.eliminated = true; }
3917 if (this._pendingShots.length)
3918 {
3919 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
3920 }
3921 var self = this;
3922 var prevStatus = this.lobby && this.lobby.status;
3923 return this.request('poll', body).then(function (data)
3924 {
3925 self._handleTransitions(prevStatus, data);
3926 if (self.onChange)
3927 { self.onChange(self); }
3928 return data;
3929 });
3930};
3931
3932Online._handleTransitions = function (prevStatus, data)
3933{
3934 var lobby = this.lobby;
3935 var status = lobby && lobby.status;
3936 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
3937 { this.onGameStart(lobby); }
3938 if (data && data.incoming && data.incoming.length && this.onIncoming)
3939 { this.onIncoming(data.incoming); }
3940 if (data && data.shot_results && data.shot_results.length)
3941 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
3942 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
3943 { this.onFinished(lobby); }
3944 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
3945 { this.onLobbyReturn(lobby); }
3946};
3947
3948Online.startPolling = function (getPayload)
3949{
3950 this.stopPolling();
3951 var self = this;
3952 var tick = function ()
3953 {
3954 var payload = getPayload ? getPayload() : {};
3955 self.poll(payload);
3956 };
3957 tick();
3958 this._timer = setInterval(tick, this.POLL_MS);
3959};
3960
3961Online.stopPolling = function ()
3962{
3963 if (this._timer)
3964 {
3965 clearInterval(this._timer);
3966 this._timer = null;
3967 }
3968};
3969
3970Online.loginUrl = function ()
3971{
3972 return 'auth.php';
3973};
3974
3975Online.logoutUrl = function ()
3976{
3977 return 'logout.php';
3978};
3979
3980Online.opponents = function ()
3981{
3982 if (!this.lobby || !this.lobby.players)
3983 { return []; }
3984 return this.lobby.players.filter(function (p) { return !p.is_me; });
3985};
3986
3987Online.aliveOpponents = function ()
3988{
3989 return this.opponents().filter(function (p) { return !p.eliminated; });
3990};
3991
3992Online.mePlayer = function ()
3993{
3994 if (!this.lobby || !this.lobby.players)
3995 { return null; }
3996 for (var i = 0; i < this.lobby.players.length; i++)
3997 {
3998 if (this.lobby.players[i].is_me)
3999 { return this.lobby.players[i]; }
4000 }
4001 return null;
4002};
4003
4004/* ---------- miniatures --------------------------------------------- */
4005
4006Online.renderMinis = function (container)
4007{
4008 if (!container)
4009 { return; }
4010 var opponents = this.opponents();
4011 var existing = {};
4012 var kids = container.querySelectorAll('[data-player]');
4013 for (var i = 0; i < kids.length; i++)
4014 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
4015
4016 var seen = Object.create(null);
4017 for (var i = 0; i < opponents.length; i++)
4018 {
4019 var p = opponents[i];
4020 seen[p.id] = true;
4021 var el = existing[p.id];
4022 if (!el)
4023 {
4024 el = document.createElement('div');
4025 el.className = 'mini';
4026 el.setAttribute('data-player', p.id);
4027 el.innerHTML = '<div class="mini-name"></div>'
4028 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
4029 + '<div class="mini-meta"></div>';
4030 container.appendChild(el);
4031 }
4032 el.classList.toggle('eliminated', !!p.eliminated);
4033 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
4034 el.querySelector('.mini-meta').textContent = p.eliminated
4035 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
4036 : ('Punten ' + (p.score || 0));
4037 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
4038 }
4039 for (var id in existing)
4040 {
4041 if (!seen[id])
4042 { existing[id].remove(); }
4043 }
4044};
4045
4046var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
4047
4048function miniColor (planet, color)
4049{
4050 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
4051 { return planet.colors[color].hex; }
4052 return MINI_COLORS[color] || '#888';
4053}
4054
4055
4056Online._drawMini = function (canvas, snapshot, planet)
4057{
4058 if (!canvas)
4059 { return; }
4060 var ctx = canvas.getContext('2d');
4061 var w = 10;
4062 var h = 13;
4063 var tw = canvas.width / w;
4064 var th = canvas.height / h;
4065 ctx.fillStyle = '#0c1020';
4066 ctx.fillRect(0, 0, canvas.width, canvas.height);
4067 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
4068 ctx.lineWidth = 1;
4069 for (var c = 0; c <= w; c++)
4070 {
4071 ctx.beginPath();
4072 ctx.moveTo(c * tw + 0.5, 0);
4073 ctx.lineTo(c * tw + 0.5, canvas.height);
4074 ctx.stroke();
4075 }
4076 for (var r = 0; r <= h; r++)
4077 {
4078 ctx.beginPath();
4079 ctx.moveTo(0, r * th + 0.5);
4080 ctx.lineTo(canvas.width, r * th + 0.5);
4081 ctx.stroke();
4082 }
4083 if (!snapshot || !snapshot.blocks)
4084 { return; }
4085 // t1123: cheap sine pulse behind blocks of nearly-full columns.
4086 if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot)
4087 {
4088 var warns = GameCore.warnColumnsFromSnapshot(snapshot);
4089 var pulse = GameCore.columnWarnPulse();
4090 for (var wc = 0; wc < warns.length; wc++)
4091 {
4092 if (!warns[wc])
4093 { continue; }
4094 ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')';
4095 ctx.fillRect(wc * tw, 0, tw, canvas.height);
4096 }
4097 }
4098 var blocks = snapshot.blocks;
4099 for (var i = 0; i < blocks.length; i++)
4100 {
4101 var b = blocks[i];
4102 var x = b.col * tw;
4103 var y = canvas.height - (b.y + 1) * th;
4104 if (b.state === 'locked')
4105 { ctx.fillStyle = '#3a3d4a'; }
4106 else if (b.color < 0)
4107 { ctx.fillStyle = '#5a5d66'; }
4108 else
4109 { ctx.fillStyle = miniColor(planet, b.color); }
4110 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
4111 }
4112};
4113
4114Online.miniElement = function (playerId)
4115{
4116 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
4117};
4118
4119/* ---------- flight tweens ------------------------------------------ */
4120
4121function colorSpriteUrl (color, planetId)
4122{
4123 if (color < 0)
4124 { return 'images/block-gray.png'; }
4125 var planet = null;
4126 if (typeof Planet !== 'undefined')
4127 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
4128 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
4129 { return planet.colors[color].image; }
4130 return 'images/block-gray.png';
4131}
4132
4133/**
4134 * Animate shot results. `locals` is a map of client_id → {col, y, color,
4135 * startX, startY} in viewport pixels, filled by the view just after
4136 * consumeOutgoingShots.
4137 */
4138Online.spawnFlights = function (results, locals)
4139{
4140 locals = locals || this._flightLocals || {};
4141 var layer = document.getElementById('flights');
4142 if (!layer)
4143 { return; }
4144 for (var i = 0; i < results.length; i++)
4145 {
4146 var r = results[i];
4147 var meta = locals[r.client_id] || {};
4148 var start = this._flightStart(meta.col);
4149 var end;
4150 var miss = !!r.miss;
4151 if (miss)
4152 { end = this._missEnd(start); }
4153 else
4154 { end = this._targetEnd(r.target_id, start); }
4155 var el = document.createElement('img');
4156 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
4157 el.alt = '';
4158 el.className = 'flight';
4159 layer.appendChild(el);
4160 var spin = (Math.random() * 2 - 1) * 720;
4161 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
4162 this._flights.push({
4163 el: el,
4164 start: start,
4165 end: end,
4166 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
4167 t0: performance.now(),
4168 duration: duration,
4169 spin: spin,
4170 miss: miss,
4171 angle: Math.random() * 360
4172 });
4173 }
4174 this._flightLocals = {};
4175};
4176
4177Online.rememberFlightLocal = function (shot, startX, startY)
4178{
4179 if (!this._flightLocals)
4180 { this._flightLocals = {}; }
4181 this._flightLocals[String(shot.id)] = {
4182 col: shot.col,
4183 y: shot.y,
4184 color: shot.color,
4185 startX: startX,
4186 startY: startY
4187 };
4188};
4189
4190Online._flightStart = function (col)
4191{
4192 var field = document.querySelector('canvas');
4193 var appRef = typeof app !== 'undefined' ? app : null;
4194 if (appRef && appRef.scene && appRef.scene.canvas)
4195 {
4196 var canvas = appRef.scene.canvas;
4197 var rect = canvas.getBoundingClientRect();
4198 var c = col == null ? 4.5 : col;
4199 return {
4200 x: rect.left + (c + 0.5) * (rect.width / 10),
4201 y: rect.top + 4
4202 };
4203 }
4204 if (field)
4205 {
4206 var rect = field.getBoundingClientRect();
4207 return { x: rect.left + rect.width / 2, y: rect.top };
4208 }
4209 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
4210};
4211
4212Online._targetEnd = function (targetId, start)
4213{
4214 var el = targetId && this.miniElement(targetId);
4215 if (el)
4216 {
4217 var r = el.getBoundingClientRect();
4218 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
4219 }
4220 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
4221};
4222
4223Online._missEnd = function (start)
4224{
4225 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
4226 return {
4227 x: start.x + dx,
4228 y: start.y - (120 + Math.random() * 220)
4229 };
4230};
4231
4232Online._missCtrl = function (start, end)
4233{
4234 return {
4235 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
4236 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
4237 };
4238};
4239
4240Online._hitCtrl = function (start, end)
4241{
4242 return {
4243 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
4244 y: (start.y + end.y) / 2 - 30
4245 };
4246};
4247
4248Online.tickFlights = function (now)
4249{
4250 now = now || performance.now();
4251 var leftover = [];
4252 for (var i = 0; i < this._flights.length; i++)
4253 {
4254 var f = this._flights[i];
4255 var u = (now - f.t0) / f.duration;
4256 if (u >= 1)
4257 {
4258 if (f.el && f.el.parentNode)
4259 { f.el.parentNode.removeChild(f.el); }
4260 continue;
4261 }
4262 // Quadratic bezier, ease-in so they feel like they recede.
4263 var e = u * u;
4264 var mt = 1 - e;
4265 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
4266 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
4267 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
4268 var angle = f.angle + f.spin * u;
4269 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
4270 + angle + 'deg) scale(' + scale + ')';
4271 f.el.style.opacity = f.miss ? String(1 - e) : '1';
4272 leftover.push(f);
4273 }
4274 this._flights = leftover;
4275};
4276
4277Online.clearFlights = function ()
4278{
4279 for (var i = 0; i < this._flights.length; i++)
4280 {
4281 var el = this._flights[i].el;
4282 if (el && el.parentNode)
4283 { el.parentNode.removeChild(el); }
4284 }
4285 this._flights = [];
4286 this._flightLocals = {};
4287};
4288
4289if (typeof globalThis !== 'undefined')
4290{ globalThis.Online = Online; }
4291if (typeof module !== 'undefined' && module.exports)
4292{ module.exports = Online; }
4293
4294/*
4295 * End File:
4296 * /workspace/meteors/src/online.js
4297 */
4298
4299/*
4300 * Start File:
4301 * /workspace/meteors/src/offline.js
4302 */
4303'use strict';
4304
4305/**
4306 * Offline Strijd: a client-side single-player mode that plays like
4307 * multiplayer (shots, miss chance, opponent minis) against local bots
4308 * (t1119). Pure simulation — no server.
4309 */
4310
4311var Offline = (function ()
4312{
4313
4314var BOT_INTERVAL = 0.5;
4315var SKILL_START = 0.05;
4316var SKILL_STEP = 0.01;
4317var SKILL_CAP = 1;
4318var FLIGHT_DURATION = 1.2;
4319var ROUND_WON_DELAY = 1.5;
4320
4321/**
4322 * N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round.
4323 * Documented in docs/ASSUMPTIONS.md (t1119).
4324 */
4325function roundsAtOpponentCount (n)
4326{
4327 if (n <= 1)
4328 { return 1; }
4329 return n - 1;
4330}
4331
4332function skillForRound (round)
4333{
4334 var r = Math.max(1, Math.floor(Number(round) || 1));
4335 var pct = 5 + (r - 1);
4336 if (pct > 100)
4337 { pct = 100; }
4338 return pct / 100;
4339}
4340
4341function scheduleForRound (round)
4342{
4343 var r = Math.max(1, Math.floor(Number(round) || 1));
4344 var cursor = 1;
4345 var n = 1;
4346 for (;;)
4347 {
4348 var count = roundsAtOpponentCount(n);
4349 if (r < cursor + count)
4350 {
4351 return {
4352 round: r,
4353 opponents: n,
4354 skill: skillForRound(r),
4355 roundsAtLevel: count,
4356 indexInLevel: r - cursor + 1
4357 };
4358 }
4359 cursor += count;
4360 n++;
4361 if (n > 10000)
4362 {
4363 return {
4364 round: r,
4365 opponents: n,
4366 skill: SKILL_CAP,
4367 roundsAtLevel: roundsAtOpponentCount(n),
4368 indexInLevel: 1
4369 };
4370 }
4371 }
4372}
4373
4374function GameCoreCtor ()
4375{
4376 if (typeof GameCore !== 'undefined')
4377 { return GameCore; }
4378 if (typeof module !== 'undefined')
4379 { return require('./gameCore.js').GameCore; }
4380 return null;
4381}
4382
4383function PlanetMod ()
4384{
4385 if (typeof Planet !== 'undefined')
4386 { return Planet; }
4387 if (typeof module !== 'undefined')
4388 { return require('./planet.js'); }
4389 return null;
4390}
4391
4392/**
4393 * Integer-row colour grid of grounded (still / settling / locked)
4394 * blocks, including greys (color < 0) so a swap can shift them.
4395 */
4396function snapshotGrid (core)
4397{
4398 var width = core.width;
4399 var height = core.height;
4400 var grid = [];
4401 for (var c = 0; c < width; c++)
4402 {
4403 grid[c] = [];
4404 for (var r = 0; r < height; r++)
4405 { grid[c][r] = null; }
4406 }
4407 for (var i = 0; i < core.blocks.length; i++)
4408 {
4409 var b = core.blocks[i];
4410 if (!core.isGrounded(b))
4411 { continue; }
4412 var row = Math.round(b.y);
4413 if (row < 0 || row >= height || b.col < 0 || b.col >= width)
4414 { continue; }
4415 if (Math.abs(b.y - row) > 0.2)
4416 { continue; }
4417 grid[b.col][row] = b.color;
4418 }
4419 return grid;
4420}
4421
4422function cloneGrid (grid)
4423{
4424 var out = [];
4425 for (var c = 0; c < grid.length; c++)
4426 { out[c] = grid[c].slice(); }
4427 return out;
4428}
4429
4430/**
4431 * Apply swapToward's net result: the block at fromRow moves to toRow,
4432 * and the blocks it passed through each shift one cell toward fromRow.
4433 */
4434function applyColumnMove (grid, col, fromRow, toRow)
4435{
4436 if (fromRow === toRow)
4437 { return; }
4438 var moving = grid[col][fromRow];
4439 if (toRow > fromRow)
4440 {
4441 for (var y = fromRow; y < toRow; y++)
4442 { grid[col][y] = grid[col][y + 1]; }
4443 grid[col][toRow] = moving;
4444 }
4445 else
4446 {
4447 for (var y = fromRow; y > toRow; y--)
4448 { grid[col][y] = grid[col][y - 1]; }
4449 grid[col][toRow] = moving;
4450 }
4451}
4452
4453function hasMatch (grid, width, height)
4454{
4455 var c, r, run, prev;
4456 for (r = 0; r < height; r++)
4457 {
4458 run = 0;
4459 prev = null;
4460 for (c = 0; c < width; c++)
4461 {
4462 var color = grid[c][r];
4463 if (color != null && color >= 0 && color === prev)
4464 {
4465 run++;
4466 if (run >= 3)
4467 { return true; }
4468 }
4469 else
4470 {
4471 run = (color != null && color >= 0) ? 1 : 0;
4472 prev = (color != null && color >= 0) ? color : null;
4473 }
4474 }
4475 }
4476 for (c = 0; c < width; c++)
4477 {
4478 run = 0;
4479 prev = null;
4480 for (r = 0; r < height; r++)
4481 {
4482 var color = grid[c][r];
4483 if (color != null && color >= 0 && color === prev)
4484 {
4485 run++;
4486 if (run >= 3)
4487 { return true; }
4488 }
4489 else
4490 {
4491 run = (color != null && color >= 0) ? 1 : 0;
4492 prev = (color != null && color >= 0) ? color : null;
4493 }
4494 }
4495 }
4496 return false;
4497}
4498
4499/**
4500 * Contiguous segments of draggable, nearly-integer-y blocks in a
4501 * column. Gaps break a segment the same way swapToward stops at gaps.
4502 */
4503function contiguousSegments (core, col)
4504{
4505 if (!core.columnAllowsDrag(col))
4506 { return []; }
4507 var list = core.blocksInColumn(col).filter(function (b)
4508 {
4509 return core.isDraggableBlock(b);
4510 });
4511 list.sort(function (a, b) { return a.y - b.y; });
4512 var segs = [];
4513 var cur = [];
4514 for (var i = 0; i < list.length; i++)
4515 {
4516 var y = list[i].y;
4517 if (Math.abs(y - Math.round(y)) > 0.15)
4518 {
4519 if (cur.length)
4520 {
4521 segs.push(cur);
4522 cur = [];
4523 }
4524 continue;
4525 }
4526 if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15)
4527 {
4528 segs.push(cur);
4529 cur = [list[i]];
4530 }
4531 else
4532 { cur.push(list[i]); }
4533 }
4534 if (cur.length)
4535 { segs.push(cur); }
4536 return segs;
4537}
4538
4539/**
4540 * The shortest vertical move that would create a 3+ match, or null.
4541 * Ties break on lowest column, then lowest fromY, then lowest toY.
4542 */
4543function findBotMove (core)
4544{
4545 var grid = snapshotGrid(core);
4546 if (hasMatch(grid, core.width, core.height))
4547 { return null; }
4548 var best = null;
4549 for (var col = 0; col < core.width; col++)
4550 {
4551 var segs = contiguousSegments(core, col);
4552 for (var s = 0; s < segs.length; s++)
4553 {
4554 var seg = segs[s];
4555 if (seg.length < 2)
4556 { continue; }
4557 for (var i = 0; i < seg.length; i++)
4558 {
4559 var fromY = Math.round(seg[i].y);
4560 for (var j = 0; j < seg.length; j++)
4561 {
4562 if (i === j)
4563 { continue; }
4564 var toY = Math.round(seg[j].y);
4565 var dist = Math.abs(toY - fromY);
4566 if (best && dist > best.dist)
4567 { continue; }
4568 var trial = cloneGrid(grid);
4569 applyColumnMove(trial, col, fromY, toY);
4570 if (!hasMatch(trial, core.width, core.height))
4571 { continue; }
4572 var cand = {
4573 col: col,
4574 fromY: fromY,
4575 toY: toY,
4576 dist: dist,
4577 blockId: seg[i].id
4578 };
4579 if (!best || dist < best.dist
4580 || (dist === best.dist && col < best.col)
4581 || (dist === best.dist && col === best.col && fromY < best.fromY)
4582 || (dist === best.dist && col === best.col && fromY === best.fromY
4583 && toY < best.toY))
4584 { best = cand; }
4585 }
4586 }
4587 }
4588 }
4589 return best;
4590}
4591
4592function executeBotMove (core, move)
4593{
4594 if (!core || !move)
4595 { return false; }
4596 var list = core.blocksInColumn(move.col);
4597 var block = null;
4598 for (var i = 0; i < list.length; i++)
4599 {
4600 if (move.blockId != null && list[i].id === move.blockId)
4601 {
4602 block = list[i];
4603 break;
4604 }
4605 if (Math.abs(list[i].y - move.fromY) < 0.2)
4606 { block = list[i]; }
4607 }
4608 if (!block || !core.isDraggableBlock(block))
4609 { return false; }
4610 core.swapToward(block, move.toY);
4611 return true;
4612}
4613
4614/**
4615 * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill.
4616 * At skill 0 the bot never moves; at skill 1 it always looks for a move.
4617 */
4618function tryBotRoll (core, skill, rng)
4619{
4620 rng = rng || Math.random;
4621 var roll = rng();
4622 if (!(roll < skill))
4623 {
4624 return { rolled: true, success: false, moved: false, roll: roll, move: null };
4625 }
4626 var move = findBotMove(core);
4627 if (!move)
4628 {
4629 return { rolled: true, success: true, moved: false, roll: roll, move: null };
4630 }
4631 var ok = executeBotMove(core, move);
4632 return { rolled: true, success: true, moved: !!ok, roll: roll, move: move };
4633}
4634
4635function pickPlanet (rng, P)
4636{
4637 var all = P.allPlanets();
4638 if (!all.length)
4639 { return P.defaultPlanet(); }
4640 var i = Math.floor(rng() * all.length) % all.length;
4641 return all[i];
4642}
4643
4644function OfflineBattle (opts)
4645{
4646 opts = opts || {};
4647 var P = PlanetMod();
4648 this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet());
4649 this.rng = opts.rng || Math.random;
4650 this.round = opts.round || 1;
4651 this.schedule = scheduleForRound(this.round);
4652 this.clock = 0;
4653 this.state = 'playing';
4654 this.pending = [];
4655 this.flightResults = [];
4656 this.shotLocals = [];
4657 this.bots = [];
4658 this.playerId = 'player';
4659 this._initBots();
4660}
4661
4662OfflineBattle.prototype._initBots = function ()
4663{
4664 var P = PlanetMod();
4665 var Ctor = GameCoreCtor();
4666 var n = this.schedule.opponents;
4667 this.bots = [];
4668 for (var i = 0; i < n; i++)
4669 {
4670 var planet = pickPlanet(this.rng, P);
4671 var miss = P.missChance(planet);
4672 var core = new Ctor(planet, this.rng, miss);
4673 this.bots.push({
4674 id: 'bot-' + (i + 1),
4675 name: 'Bot ' + (i + 1),
4676 planet: planet,
4677 core: core,
4678 eliminated: false,
4679 score: 0,
4680 aiAcc: 0
4681 });
4682 }
4683};
4684
4685OfflineBattle.prototype.aliveBots = function ()
4686{
4687 var out = [];
4688 for (var i = 0; i < this.bots.length; i++)
4689 {
4690 if (!this.bots[i].eliminated && this.bots[i].core
4691 && this.bots[i].core.state !== 'gameover')
4692 { out.push(this.bots[i]); }
4693 }
4694 return out;
4695};
4696
4697OfflineBattle.prototype.coreFor = function (id, playerCore)
4698{
4699 if (id === this.playerId)
4700 { return playerCore; }
4701 for (var i = 0; i < this.bots.length; i++)
4702 {
4703 if (this.bots[i].id === id)
4704 { return this.bots[i].core; }
4705 }
4706 return null;
4707};
4708
4709OfflineBattle.prototype._targetsFor = function (fromId, playerCore)
4710{
4711 var targets = [];
4712 if (fromId !== this.playerId && playerCore && playerCore.state === 'playing')
4713 { targets.push({ id: this.playerId, core: playerCore }); }
4714 for (var i = 0; i < this.bots.length; i++)
4715 {
4716 var bot = this.bots[i];
4717 if (bot.id === fromId || bot.eliminated)
4718 { continue; }
4719 if (bot.core && bot.core.state === 'playing')
4720 { targets.push({ id: bot.id, core: bot.core }); }
4721 }
4722 return targets;
4723};
4724
4725OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore)
4726{
4727 if (!core || !core.consumeOutgoingShots)
4728 { return; }
4729 var shots = core.consumeOutgoingShots();
4730 if (!shots.length)
4731 { return; }
4732 var P = PlanetMod();
4733 var missChance = (P && planet) ? P.missChance(planet) : 0.30;
4734 var targets = this._targetsFor(fromId, playerCore);
4735 for (var i = 0; i < shots.length; i++)
4736 {
4737 var shot = shots[i];
4738 var miss = targets.length === 0 || this.rng() < missChance;
4739 var target = null;
4740 if (!miss)
4741 {
4742 var idx = Math.floor(this.rng() * targets.length) % targets.length;
4743 target = targets[idx];
4744 }
4745 var clientId = fromId + '-' + shot.id + '-' + this.clock;
4746 var result = {
4747 client_id: clientId,
4748 miss: miss,
4749 target_id: target ? target.id : null,
4750 color: shot.color,
4751 flight_duration: FLIGHT_DURATION,
4752 from_id: fromId,
4753 col: shot.col,
4754 y: shot.y
4755 };
4756 this.flightResults.push(result);
4757 this.shotLocals.push({
4758 client_id: clientId,
4759 col: shot.col,
4760 y: shot.y,
4761 color: shot.color,
4762 from_id: fromId
4763 });
4764 if (!miss && target)
4765 {
4766 this.pending.push({
4767 at: this.clock + FLIGHT_DURATION,
4768 targetId: target.id,
4769 color: shot.color,
4770 fromId: fromId
4771 });
4772 }
4773 }
4774};
4775
4776OfflineBattle.prototype._deliver = function (playerCore)
4777{
4778 var keep = [];
4779 for (var i = 0; i < this.pending.length; i++)
4780 {
4781 var ev = this.pending[i];
4782 if (this.clock + 1e-9 < ev.at)
4783 {
4784 keep.push(ev);
4785 continue;
4786 }
4787 var core = this.coreFor(ev.targetId, playerCore);
4788 if (core && core.state === 'playing' && core.ingestGarbage)
4789 { core.ingestGarbage(); }
4790 }
4791 this.pending = keep;
4792};
4793
4794OfflineBattle.prototype.tick = function (dt, playerCore)
4795{
4796 this.flightResults = [];
4797 this.shotLocals = [];
4798 if (this.state !== 'playing')
4799 { return { flights: [], locals: [] }; }
4800 if (dt < 0)
4801 { dt = 0; }
4802 this.clock += dt;
4803
4804 var skill = this.schedule.skill;
4805 for (var i = 0; i < this.bots.length; i++)
4806 {
4807 var bot = this.bots[i];
4808 if (bot.eliminated)
4809 { continue; }
4810 if (bot.core.state === 'gameover')
4811 {
4812 bot.eliminated = true;
4813 bot.score = bot.core.score;
4814 continue;
4815 }
4816 bot.core.tick(dt);
4817 bot.score = bot.core.score;
4818 bot.aiAcc += dt;
4819 while (bot.aiAcc >= BOT_INTERVAL)
4820 {
4821 bot.aiAcc -= BOT_INTERVAL;
4822 if (bot.core.state === 'playing' && !bot.core.drag)
4823 { tryBotRoll(bot.core, skill, this.rng); }
4824 }
4825 }
4826
4827 this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore);
4828 for (var i = 0; i < this.bots.length; i++)
4829 {
4830 var bot = this.bots[i];
4831 if (bot.eliminated)
4832 { continue; }
4833 this._dispatchShots(bot.id, bot.core, bot.planet, playerCore);
4834 }
4835 this._deliver(playerCore);
4836
4837 for (var i = 0; i < this.bots.length; i++)
4838 {
4839 if (this.bots[i].core && this.bots[i].core.state === 'gameover')
4840 {
4841 this.bots[i].eliminated = true;
4842 this.bots[i].score = this.bots[i].core.score;
4843 }
4844 }
4845
4846 if (playerCore && playerCore.state === 'gameover')
4847 { this.state = 'lost'; }
4848 else if (this.aliveBots().length === 0 && this.bots.length > 0)
4849 { this.state = 'round_won'; }
4850
4851 return { flights: this.flightResults, locals: this.shotLocals };
4852};
4853
4854/**
4855 * Start the next round (fresh bots, new skill and opponent count).
4856 * The caller must also give the player a fresh GameCore.
4857 */
4858OfflineBattle.prototype.advanceRound = function ()
4859{
4860 this.round += 1;
4861 this.schedule = scheduleForRound(this.round);
4862 this.state = 'playing';
4863 this.pending = [];
4864 this.flightResults = [];
4865 this.shotLocals = [];
4866 this.clock = 0;
4867 this._initBots();
4868 return this.schedule;
4869};
4870
4871function createBattle (opts)
4872{
4873 return new OfflineBattle(opts);
4874}
4875
4876var api = {
4877 BOT_INTERVAL: BOT_INTERVAL,
4878 SKILL_START: SKILL_START,
4879 SKILL_STEP: SKILL_STEP,
4880 SKILL_CAP: SKILL_CAP,
4881 FLIGHT_DURATION: FLIGHT_DURATION,
4882 ROUND_WON_DELAY: ROUND_WON_DELAY,
4883 roundsAtOpponentCount: roundsAtOpponentCount,
4884 skillForRound: skillForRound,
4885 scheduleForRound: scheduleForRound,
4886 findBotMove: findBotMove,
4887 tryBotRoll: tryBotRoll,
4888 executeBotMove: executeBotMove,
4889 snapshotGrid: snapshotGrid,
4890 applyColumnMove: applyColumnMove,
4891 hasMatch: hasMatch,
4892 createBattle: createBattle,
4893 OfflineBattle: OfflineBattle
4894};
4895
4896if (typeof module !== 'undefined' && module.exports)
4897{ module.exports = api; }
4898else if (typeof globalThis !== 'undefined')
4899{ globalThis.Offline = api; }
4900
4901return api;
4902
4903})();
4904
4905if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined')
4906{ module.exports = Offline; }
4907
4908/*
4909 * End File:
4910 * /workspace/meteors/src/offline.js
4911 */
4912
4913/*
4914 * Start File:
4915 * /workspace/meteors/src/main.js
4916 */
4917'use strict';
4918
4919/**
4920 * View and input for Meteors. The simulation lives in GameCore; this file
4921 * only draws it, scales it to the viewport, and translates pointer events
4922 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
4923 * through Online (src/online.js) and the same GameCore. Offline Strijd
4924 * (t1119) uses Offline (src/offline.js) against local bots.
4925 */
4926
4927function planetImages ()
4928{
4929 var list = [
4930 { name: 'gray', url: 'images/block-gray.png' },
4931 { name: 'locked', url: 'images/block-locked.png' },
4932 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
4933 { name: 'cell', url: 'images/cell.png' },
4934 { name: 'pixel', url: 'images/pixel.png' },
4935 { name: 'columnWarn', url: 'images/column-warn.png' },
4936 // Keep the original Terra placeholders as aliases (Tim may still have them).
4937 { name: 'ember', url: 'images/block-ember.png' },
4938 { name: 'aqua', url: 'images/block-aqua.png' },
4939 { name: 'leaf', url: 'images/block-leaf.png' },
4940 { name: 'sun', url: 'images/block-sun.png' },
4941 { name: 'orchid', url: 'images/block-orchid.png' }
4942 ];
4943 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
4944 for (var i = 0; i < planets.length; i++)
4945 {
4946 var pl = planets[i];
4947 for (var c = 0; c < pl.colors.length; c++)
4948 {
4949 list.push({
4950 name: Planet.spriteKey(pl, c),
4951 url: pl.colors[c].image
4952 });
4953 }
4954 }
4955 return list;
4956}
4957
4958var IMAGES = planetImages();
4959var GAME_OVER_DELAY = 2;
4960
4961var game = new Game();
4962var app = {
4963 mode: 'menu',
4964 core: null,
4965 scene: null,
4966 manager: null,
4967 planet: null,
4968 lastScore: 0,
4969 tile: 48,
4970 fieldX: 0,
4971 fieldY: 0,
4972 fieldW: 0,
4973 fieldH: 0,
4974 hudH: 56,
4975 sprites: Object.create(null),
4976 flames: Object.create(null),
4977 cells: [],
4978 pointerId: null,
4979 pointerType: null,
4980 activeTouchId: null,
4981 debugDrag: false,
4982 debugPhysics: false,
4983 gameOverShown: false,
4984 selectTween: null,
4985 online: false,
4986 eliminatedReported: false,
4987 spectating: false,
4988 miniH: 0,
4989 selectedPlanetId: 'terra',
4990 planetSelectContext: 'solo',
4991 offline: false,
4992 battle: null,
4993 swapTweens: null,
4994 columnWarn: null,
4995 warnClock: 0,
4996 miniAcc: 0,
4997 offlineResultShown: false,
4998 roundWonDelay: 0,
4999 roundWonHandled: false
5000};
5001
5002window.onload = function ()
5003{
5004 app.debugDrag = isDragDebugEnabled();
5005 app.debugPhysics = isPhysicsDebugEnabled();
5006 var play = document.getElementById('btn-play');
5007 play.addEventListener('click', onPlay);
5008 play.addEventListener('pointerup', function (e)
5009 {
5010 // A touch-friendly path: some mobile browsers swallow the click
5011 // after a slightly sloppy tap. Ignore the following click.
5012 if (e.pointerType === 'touch' || e.pointerType === 'pen')
5013 {
5014 e.preventDefault();
5015 onPlay();
5016 }
5017 });
5018
5019 game.preloadImagesThenStart(IMAGES, function ()
5020 {
5021 if (game.images.flame && game.images.flame.addAnimationCycle)
5022 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
5023 });
5024
5025 bindOnlineUi();
5026 bindOfflineUi();
5027 bindPlanetSelect();
5028 restoreSelectedPlanet();
5029};
5030
5031function onPlay ()
5032{
5033 if (app.mode === 'playing')
5034 { return; }
5035 openPlanetSelect('solo');
5036}
5037
5038function startPlay (opts)
5039{
5040 opts = opts || {};
5041 hideEl('menu');
5042 hideEl('game-over');
5043 hideEl('online-panel');
5044 hideEl('spectator');
5045 hideEl('podium');
5046 hideEl('planet-select');
5047 hideEl('offline-result');
5048 showEl('hud');
5049
5050 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
5051 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
5052 var miss = opts.missChance;
5053 if (typeof miss !== 'number' || !isFinite(miss))
5054 { miss = planetMod.missChance(app.planet); }
5055 app.core = new GameCore(app.planet, Math.random, miss);
5056 if (app.debugPhysics)
5057 { app.core.debugInvariants = true; }
5058 app.mode = 'playing';
5059 app.online = !!opts.online;
5060 app.offline = !!opts.offline;
5061 app.gameOverShown = false;
5062 app.eliminatedReported = false;
5063 app.spectating = false;
5064 app.sprites = Object.create(null);
5065 app.flames = Object.create(null);
5066 app.cells = [];
5067 app.pointerId = null;
5068 app.selectTween = null;
5069 app.swapTweens = Object.create(null);
5070 app.columnWarn = [];
5071 app.warnClock = 0;
5072 app.miniAcc = 1; // draw minis on the first frame
5073 app.offlineResultShown = false;
5074 if (!opts.keepBattle)
5075 {
5076 app.roundWonDelay = 0;
5077 app.roundWonHandled = false;
5078 }
5079 if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined')
5080 {
5081 app.battle = Offline.createBattle({
5082 playerPlanet: app.planet,
5083 rng: Math.random,
5084 round: opts.round || 1
5085 });
5086 }
5087
5088 layout();
5089 if (app.scene)
5090 {
5091 app.scene.destroy();
5092 app.scene = null;
5093 }
5094 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
5095 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
5096 app.scene.renderBackground = true;
5097 game.loadScene(app.scene);
5098
5099 buildCells();
5100 app.manager = app.scene.addObject(makeManager());
5101 if (!app.spectating)
5102 { bindPointer(app.scene.canvas); }
5103 refreshHud();
5104 if (app.online || app.offline)
5105 { showEl('minis'); }
5106 else
5107 { hideEl('minis'); }
5108 buildColumnWarn();
5109 refreshOfflineHud();
5110 refreshChainIndicator();
5111}
5112
5113function teardownPlay ()
5114{
5115 unbindPointer();
5116 if (app.scene)
5117 {
5118 app.scene.destroy();
5119 app.scene = null;
5120 }
5121 app.manager = null;
5122 app.core = null;
5123 app.sprites = Object.create(null);
5124 app.flames = Object.create(null);
5125 app.cells = [];
5126 app.selectTween = null;
5127 app.swapTweens = Object.create(null);
5128 app.columnWarn = [];
5129 app.pointerId = null;
5130 app.gameOverShown = false;
5131 hideEl('hud');
5132 hideEl('game-over');
5133 hideEl('spectator');
5134 hideEl('minis');
5135 hideEl('offline-result');
5136 hideOfflineHud();
5137 hideChainIndicator();
5138 if (typeof Online !== 'undefined')
5139 { Online.clearFlights(); }
5140 if (!app._keepBattleOnTeardown)
5141 {
5142 app.battle = null;
5143 app.offline = false;
5144 }
5145 app._keepBattleOnTeardown = false;
5146}
5147
5148function returnToMenu ()
5149{
5150 if (app.online && typeof Online !== 'undefined')
5151 {
5152 // Online matches do not dump you back to the solo menu:
5153 // elimination becomes spectating; a finished match shows the podium.
5154 return;
5155 }
5156 teardownPlay();
5157 app.mode = 'menu';
5158 app.online = false;
5159 app.offline = false;
5160 app.battle = null;
5161 hideEl('planet-select');
5162 showEl('menu');
5163 var last = document.getElementById('last-score');
5164 if (app.lastScore > 0)
5165 {
5166 last.hidden = false;
5167 last.querySelector('strong').textContent = String(app.lastScore);
5168 }
5169}
5170
5171function buildCells ()
5172{
5173 if (!app.scene)
5174 { return; }
5175 var img = game.images.cell;
5176 for (var row = 0; row < 13; row++)
5177 {
5178 for (var col = 0; col < 10; col++)
5179 {
5180 var obj = new GameObject(0, 0, img, 0);
5181 placeTile(obj, col, row);
5182 obj.renderer.alpha = 0.9;
5183 app.scene.addObject(obj);
5184 app.cells.push(obj);
5185 }
5186 }
5187}
5188
5189function placeTile (obj, col, y)
5190{
5191 var t = app.tile;
5192 obj.transform.position.x = col * t + t / 2;
5193 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
5194 obj.transform.size = { x: t, y: t };
5195}
5196
5197function layoutIfNeeded ()
5198{
5199 if (app.core && app.core.drag)
5200 { return; }
5201 var vw = window.innerWidth || 320;
5202 var vh = window.innerHeight || 480;
5203 if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
5204 { return; }
5205 layout();
5206}
5207
5208function layout ()
5209{
5210 if (app.core && app.core.drag)
5211 { return; }
5212 var vw = window.innerWidth || 320;
5213 var vh = window.innerHeight || 480;
5214 app._layoutVw = vw;
5215 app._layoutVh = vh;
5216 var safeTop = 0;
5217 try
5218 {
5219 // env(safe-area) is a CSS thing; keep a conservative HUD height.
5220 safeTop = 0;
5221 }
5222 catch (e) { /* ignore */ }
5223 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
5224 app.miniH = 0;
5225 if (app.online || app.offline)
5226 {
5227 var nBots = (app.battle && app.battle.bots) ? app.battle.bots.length : 2;
5228 var share = nBots > 6 ? 0.26 : 0.20;
5229 app.miniH = Math.min(nBots > 6 ? 180 : 150, Math.max(86, Math.round(vh * share)));
5230 }
5231 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
5232 var availW = Math.max(80, vw - margin * 2);
5233 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
5234 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
5235 app.fieldW = app.tile * 10;
5236 app.fieldH = app.tile * 13;
5237 app.fieldX = Math.floor((vw - app.fieldW) / 2);
5238 var topBand = app.hudH + app.miniH;
5239 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
5240 if (app.fieldY < topBand)
5241 { app.fieldY = topBand; }
5242 var minis = document.getElementById('minis');
5243 if (minis)
5244 {
5245 minis.style.top = app.hudH + 'px';
5246 minis.style.maxHeight = app.miniH + 'px';
5247 }
5248
5249 if (app.scene)
5250 {
5251 app.scene.position.x = app.fieldX;
5252 app.scene.position.y = app.fieldY;
5253 app.scene.size.x = app.fieldW;
5254 app.scene.size.y = app.fieldH;
5255 }
5256}
5257
5258function spriteFor (block)
5259{
5260 if (block.state === 'locked')
5261 { return game.images.locked; }
5262 if (block.color < 0)
5263 { return game.images.gray; }
5264 var key = Planet.spriteKey(app.planet, block.color);
5265 return game.images[key] || game.images.gray;
5266}
5267
5268function syncSprites (dt)
5269{
5270 if (!app.core || !app.scene)
5271 { return; }
5272 dt = dt || 0;
5273 consumeAndStartSwapTweens();
5274 advanceSwapTweens(dt);
5275 var seen = Object.create(null);
5276 var blocks = app.core.blocks;
5277 for (var i = 0; i < blocks.length; i++)
5278 {
5279 var block = blocks[i];
5280 seen[block.id] = true;
5281 var obj = app.sprites[block.id];
5282 if (!obj)
5283 {
5284 obj = new GameObject(0, 0, spriteFor(block), 2);
5285 app.scene.addObject(obj);
5286 app.sprites[block.id] = obj;
5287 }
5288 obj.renderer.sprite = spriteFor(block);
5289 placeTile(obj, block.col, blockVisualY(block));
5290 applyBlockVisual(obj, block);
5291 obj.renderer.visible = true;
5292 obj.renderer.alpha = 1;
5293
5294 if (block.flame)
5295 {
5296 var flame = app.flames[block.id];
5297 if (!flame)
5298 {
5299 flame = new GameObject(0, 0, game.images.flame, 1);
5300 flame.renderer.setAnimation('burn', 0, 0.08);
5301 app.scene.addObject(flame);
5302 app.flames[block.id] = flame;
5303 }
5304 flame.renderer.visible = true;
5305 var t = app.tile;
5306 // 3x as large (length and width, t1110). Keep the top of the
5307 // flame at the same overlap into the block so the extra length
5308 // extends downward under the rocket.
5309 var flameW = t * 0.85 * 3;
5310 var flameH = t * 0.85 * 3;
5311 var origCenter = app.fieldH - block.y * t + t * 0.15;
5312 var origTop = origCenter - (t * 0.85) / 2;
5313 flame.transform.position.x = block.col * t + t / 2;
5314 flame.transform.position.y = origTop + flameH / 2;
5315 flame.transform.size = { x: flameW, y: flameH };
5316 }
5317 else if (app.flames[block.id])
5318 { app.flames[block.id].renderer.visible = false; }
5319 }
5320
5321 var ids = Object.keys(app.sprites);
5322 for (var i = 0; i < ids.length; i++)
5323 {
5324 if (!seen[ids[i]])
5325 {
5326 app.sprites[ids[i]].destroy();
5327 delete app.sprites[ids[i]];
5328 if (app.flames[ids[i]])
5329 {
5330 app.flames[ids[i]].destroy();
5331 delete app.flames[ids[i]];
5332 }
5333 }
5334 }
5335}
5336
5337function applyBlockVisual (obj, block)
5338{
5339 var t = app.tile;
5340 var sx = 1;
5341 var sy = 1;
5342 var dy = 0;
5343 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
5344 && typeof Easing !== 'undefined' && Easing.bouncePose)
5345 {
5346 var u = block.bounceAge / app.planet.bounceDuration;
5347 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
5348 sx = pose.sx;
5349 sy = pose.sy;
5350 dy = pose.dy;
5351 }
5352 var sel = 1;
5353 var tw = app.selectTween;
5354 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
5355 { sel = tw.scale; }
5356 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
5357 if (dy)
5358 { obj.transform.position.y -= dy * t; }
5359}
5360
5361function clickTween ()
5362{
5363 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
5364}
5365
5366function startPressTween (blockId)
5367{
5368 var c = clickTween();
5369 if (!c)
5370 { return; }
5371 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
5372 app.selectTween = {
5373 blockId: blockId,
5374 from: from,
5375 to: c.pressScale,
5376 t: 0,
5377 duration: c.pressDuration,
5378 ease: c.pressEase,
5379 scale: from,
5380 phase: 'press'
5381 };
5382}
5383
5384function startReleaseTween ()
5385{
5386 var c = clickTween();
5387 var tw = app.selectTween;
5388 if (!c || !tw || tw.phase === 'idle')
5389 { return; }
5390 app.selectTween = {
5391 blockId: tw.blockId,
5392 from: tw.scale,
5393 to: c.releaseScale,
5394 t: 0,
5395 duration: c.releaseDuration,
5396 ease: c.releaseEase,
5397 scale: tw.scale,
5398 phase: 'release'
5399 };
5400}
5401
5402function updateSelectTween (dt)
5403{
5404 var tw = app.selectTween;
5405 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
5406 { return; }
5407 tw.t += dt;
5408 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
5409 if (u >= 1)
5410 {
5411 tw.scale = tw.to;
5412 tw.t = tw.duration;
5413 if (tw.phase === 'press')
5414 { tw.phase = 'hold'; }
5415 else
5416 {
5417 tw.phase = 'idle';
5418 tw.scale = 1;
5419 tw.blockId = null;
5420 }
5421 return;
5422 }
5423 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
5424 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
5425}
5426
5427
5428/* ---------- visual-only swap tween (t1121) -------------------------- */
5429
5430function swapTweenSpec ()
5431{
5432 if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN)
5433 { return Easing.SWAP_TWEEN; }
5434 return { duration: 0.100, ease: null };
5435}
5436
5437function swapEase (u)
5438{
5439 if (typeof Easing !== 'undefined' && Easing.easeOutCubic)
5440 { return Easing.easeOutCubic(u); }
5441 var v = 1 - Math.max(0, Math.min(1, u));
5442 return 1 - v * v * v;
5443}
5444
5445function tweenVisualY (tw)
5446{
5447 var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1;
5448 return tw.fromY + (tw.toY - tw.fromY) * swapEase(u);
5449}
5450
5451/**
5452 * Consume GameCore swap events. The currently dragged block is skipped
5453 * (it follows the pointer). A block that is mid-tween and is swapped
5454 * again restarts from its current visual y, so rapid swaps chain
5455 * smoothly without snapping.
5456 */
5457function consumeAndStartSwapTweens ()
5458{
5459 if (!app.core || !app.core.consumeSwapEvents)
5460 { return; }
5461 if (!app.swapTweens)
5462 { app.swapTweens = Object.create(null); }
5463 var ev = app.core.consumeSwapEvents();
5464 if (!ev.length)
5465 { return; }
5466 var dragId = app.core.drag && app.core.drag.blockId;
5467 var duration = swapTweenSpec().duration;
5468 for (var i = 0; i < ev.length; i++)
5469 {
5470 var e = ev[i];
5471 if (e.id === dragId)
5472 {
5473 delete app.swapTweens[e.id];
5474 continue;
5475 }
5476 var fromY = e.fromY;
5477 var existing = app.swapTweens[e.id];
5478 if (existing)
5479 { fromY = tweenVisualY(existing); }
5480 app.swapTweens[e.id] = {
5481 fromY: fromY,
5482 toY: e.toY,
5483 age: 0,
5484 duration: duration
5485 };
5486 }
5487}
5488
5489function advanceSwapTweens (dt)
5490{
5491 if (!app.swapTweens)
5492 { return; }
5493 var ids = Object.keys(app.swapTweens);
5494 for (var i = 0; i < ids.length; i++)
5495 {
5496 var tw = app.swapTweens[ids[i]];
5497 tw.age += dt;
5498 if (tw.age >= tw.duration)
5499 { delete app.swapTweens[ids[i]]; }
5500 }
5501}
5502
5503function blockVisualY (block)
5504{
5505 if (!app.swapTweens)
5506 { return block.y; }
5507 var dragId = app.core && app.core.drag && app.core.drag.blockId;
5508 if (block.id === dragId)
5509 { return block.y; }
5510 var tw = app.swapTweens[block.id];
5511 if (!tw)
5512 { return block.y; }
5513 return tweenVisualY(tw);
5514}
5515
5516function refreshHud ()
5517{
5518 if (!app.core)
5519 { return; }
5520 document.getElementById('score').textContent = String(app.core.score);
5521 var planet = app.planet;
5522 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
5523 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
5524}
5525
5526function makeManager ()
5527{
5528 var obj = new GameObject(0, 0, game.images.pixel, 0);
5529 obj.renderer.visible = false;
5530 var base = obj.update.bind(obj);
5531 obj.update = function (dt)
5532 {
5533 base(dt);
5534 tickView(dt);
5535 };
5536 return obj;
5537}
5538
5539function tickView (dt)
5540{
5541 if (app.mode !== 'playing' || !app.core)
5542 { return; }
5543
5544 // Never resize the canvas mid-drag: a URL-bar hide would move the
5545 // field under the finger and jump the target row. Also skip work
5546 // when the viewport has not actually changed.
5547 if (!(app.core && app.core.drag))
5548 { layoutIfNeeded(); }
5549 for (var i = 0; i < app.cells.length; i++)
5550 {
5551 var col = i % 10;
5552 var row = Math.floor(i / 10);
5553 placeTile(app.cells[i], col, row);
5554 }
5555
5556 app.core.tick(dt);
5557 if (app.offline && app.battle)
5558 { tickOffline(dt); }
5559 updateSelectTween(dt);
5560 syncSprites(dt);
5561 updateColumnWarn(dt);
5562 refreshHud();
5563 refreshOfflineHud();
5564 refreshChainIndicator();
5565 tickOnline(dt);
5566 if (app.debugPhysics)
5567 { logPhysicsDebug(); }
5568
5569 if (app.core.state === 'gameover' && !app.gameOverShown)
5570 {
5571 app.gameOverShown = true;
5572 app.lastScore = app.core.score;
5573 document.getElementById('go-score').textContent = String(app.lastScore);
5574 if (app.online)
5575 { onOnlineEliminated(); }
5576 else if (app.offline)
5577 { /* Offline result is shown from tickOffline. */ }
5578 else
5579 { showEl('game-over'); }
5580 }
5581 if (!app.online && !app.offline && app.core.state === 'gameover'
5582 && app.core.gameOverTime >= GAME_OVER_DELAY)
5583 { returnToMenu(); }
5584}
5585
5586/* ---------- pointer input (mouse + touch) --------------------------- */
5587/*
5588 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
5589 * on a real phone, pointer clientX/Y can disagree with the visual
5590 * finger (zoomed visual viewport, gesture takeover, capture cancel)
5591 * while changedTouches stays correct. When a touch is active, pointer
5592 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
5593 * walk the block to the top or bottom of the stack (t1106).
5594 *
5595 * After a down we also listen on the document, so a drag that leaves
5596 * the canvas (needed to launch a block at the top of a full column)
5597 * still reaches moveDrag. We do not call setPointerCapture: on mobile
5598 * that is often cancelled when the browser takes the gesture, which
5599 * would fire pointercancel mid-drag.
5600 *
5601 * A non-passive document touchstart/touchmove preventDefault during
5602 * play stops scrolling, rubber-banding and the pointercancel that
5603 * follows. pointercancel / touchcancel end the drag without launch.
5604 *
5605 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
5606 */
5607
5608var boundCanvas = null;
5609var windowListening = false;
5610var touchListening = false;
5611var lastDragDebug = null;
5612
5613function isDragDebugEnabled ()
5614{
5615 try
5616 {
5617 var q = window.location && window.location.search;
5618 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
5619 { return true; }
5620 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
5621 { return true; }
5622 }
5623 catch (err) { /* ignore */ }
5624 return false;
5625}
5626
5627/** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */
5628function isPhysicsDebugEnabled ()
5629{
5630 try
5631 {
5632 var q = window.location && window.location.search;
5633 if (q && /(?:\?|&)debug(?:=|&|$)/.test(q))
5634 { return true; }
5635 if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1'
5636 || window.localStorage.getItem('meteors-debug-drag') === '1'))
5637 { return true; }
5638 }
5639 catch (err) { /* ignore */ }
5640 return false;
5641}
5642
5643function eventClient (e)
5644{
5645 var t = null;
5646 if (e.changedTouches && e.changedTouches.length)
5647 { t = e.changedTouches[0]; }
5648 else if (e.touches && e.touches.length)
5649 { t = e.touches[0]; }
5650 if (t)
5651 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
5652 if (e.clientX != null && e.clientY != null)
5653 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
5654 return null;
5655}
5656
5657function addWindowPointer ()
5658{
5659 if (windowListening)
5660 { return; }
5661 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
5662 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
5663 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
5664 windowListening = true;
5665}
5666
5667function removeWindowPointer ()
5668{
5669 if (!windowListening)
5670 { return; }
5671 window.removeEventListener('pointermove', onPointerMove, { capture: true });
5672 window.removeEventListener('pointerup', onPointerUp, { capture: true });
5673 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
5674 windowListening = false;
5675}
5676
5677function addTouchListeners ()
5678{
5679 if (touchListening)
5680 { return; }
5681 var opts = { capture: true, passive: false };
5682 document.addEventListener('touchstart', onTouchStart, opts);
5683 document.addEventListener('touchmove', onTouchMove, opts);
5684 document.addEventListener('touchend', onTouchEnd, opts);
5685 document.addEventListener('touchcancel', onTouchCancel, opts);
5686 touchListening = true;
5687}
5688
5689function removeTouchListeners ()
5690{
5691 if (!touchListening)
5692 { return; }
5693 var opts = { capture: true };
5694 document.removeEventListener('touchstart', onTouchStart, opts);
5695 document.removeEventListener('touchmove', onTouchMove, opts);
5696 document.removeEventListener('touchend', onTouchEnd, opts);
5697 document.removeEventListener('touchcancel', onTouchCancel, opts);
5698 touchListening = false;
5699}
5700
5701function bindPointer (canvas)
5702{
5703 unbindPointer();
5704 boundCanvas = canvas;
5705 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
5706 canvas.style.touchAction = 'none';
5707 canvas.style.position = 'fixed';
5708 canvas.style.cursor = 'pointer';
5709 canvas.style.webkitUserSelect = 'none';
5710 canvas.style.userSelect = 'none';
5711 addTouchListeners();
5712 if (app.debugDrag)
5713 { ensureDragDebugOverlay(); }
5714}
5715
5716function unbindPointer ()
5717{
5718 removeWindowPointer();
5719 removeTouchListeners();
5720 if (boundCanvas)
5721 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
5722 boundCanvas = null;
5723 app.pointerId = null;
5724 app.pointerType = null;
5725 app.activeTouchId = null;
5726}
5727
5728function fieldFromEvent (e)
5729{
5730 var canvas = app.scene && app.scene.canvas;
5731 if (!canvas)
5732 { return null; }
5733 var rect = canvas.getBoundingClientRect();
5734 if (rect.width <= 0 || rect.height <= 0)
5735 { return null; }
5736 var pt = eventClient(e);
5737 if (!pt)
5738 { return null; }
5739 // Map through the CSS box only. Using canvas.width / app.tile would
5740 // scale the pointer by the backing-store ratio whenever that differs
5741 // from the layout size (high-DPR devices), so a short finger move
5742 // would look like a long swipe.
5743 var width = Planet.FIELD_WIDTH;
5744 var height = Planet.FIELD_HEIGHT;
5745 var col = ((pt.x - rect.left) / rect.width) * width;
5746 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
5747 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
5748}
5749
5750function playingForDrag ()
5751{
5752 return app.core && app.core.state === 'playing';
5753}
5754
5755function startDragFromEvent (e)
5756{
5757 var pos = fieldFromEvent(e);
5758 if (!pos)
5759 { return; }
5760 if (app.core.drag)
5761 {
5762 app.core.moveDrag(pos.y);
5763 logDragDebug(e, pos, 'move-already');
5764 return;
5765 }
5766 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
5767 { startPressTween(app.core.drag.blockId); }
5768 logDragDebug(e, pos, 'down');
5769}
5770
5771function moveDragFromEvent (e)
5772{
5773 if (!app.core || !app.core.drag)
5774 { return; }
5775 var pos = fieldFromEvent(e);
5776 if (pos)
5777 { app.core.moveDrag(pos.y); }
5778 logDragDebug(e, pos, 'move');
5779}
5780
5781function finishDrag (opts)
5782{
5783 opts = opts || {};
5784 app.pointerId = null;
5785 app.pointerType = null;
5786 app.activeTouchId = null;
5787 removeWindowPointer();
5788 if (boundCanvas)
5789 {
5790 try
5791 {
5792 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
5793 { boundCanvas.releasePointerCapture(opts.pointerId); }
5794 }
5795 catch (err) { /* ignore */ }
5796 }
5797 startReleaseTween();
5798 if (app.core && app.core.drag)
5799 {
5800 if (opts.noLaunch)
5801 { app.core.drag.launchIntent = false; }
5802 app.core.endDrag();
5803 }
5804 else if (app.core)
5805 { app.core.endDrag(); }
5806 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
5807}
5808
5809function onPointerDown (e)
5810{
5811 if (!playingForDrag())
5812 { return; }
5813 if (app.pointerId != null && e.pointerId !== app.pointerId)
5814 { return; }
5815 if (e.preventDefault)
5816 { e.preventDefault(); }
5817 app.pointerId = e.pointerId;
5818 app.pointerType = e.pointerType || 'mouse';
5819 addWindowPointer();
5820 // If a touch is already in charge, do not reset the grab from pointerdown.
5821 if (app.activeTouchId != null)
5822 { return; }
5823 startDragFromEvent(e);
5824}
5825
5826function onPointerMove (e)
5827{
5828 if (app.pointerId == null || e.pointerId !== app.pointerId)
5829 { return; }
5830 if (!app.core || !app.core.drag)
5831 { return; }
5832 // Touch coordinates are the authority; ignore pointer moves for a
5833 // live touch so a wrong clientY cannot walk the whole column.
5834 // Only skip when touchstart has actually arrived — some environments
5835 // deliver touch-pointer events without a TouchEvent stream.
5836 if (app.activeTouchId != null)
5837 {
5838 if (e.preventDefault)
5839 { e.preventDefault(); }
5840 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
5841 return;
5842 }
5843 if (e.preventDefault)
5844 { e.preventDefault(); }
5845 moveDragFromEvent(e);
5846}
5847
5848function onPointerUp (e)
5849{
5850 if (app.pointerId == null)
5851 { return; }
5852 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
5853 { return; }
5854 if (app.activeTouchId != null)
5855 {
5856 // touchend will finish the drag.
5857 if (e && e.preventDefault)
5858 { e.preventDefault(); }
5859 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
5860 return;
5861 }
5862 if (e && e.preventDefault)
5863 { e.preventDefault(); }
5864 finishDrag({ pointerId: e && e.pointerId });
5865}
5866
5867function onPointerCancel (e)
5868{
5869 if (app.pointerId == null)
5870 { return; }
5871 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
5872 { return; }
5873 if (app.activeTouchId != null)
5874 {
5875 if (e && e.preventDefault)
5876 { e.preventDefault(); }
5877 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
5878 return;
5879 }
5880 if (e && e.preventDefault)
5881 { e.preventDefault(); }
5882 // A cancelled gesture is not a launch pull.
5883 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
5884}
5885
5886function touchById (list, id)
5887{
5888 if (!list)
5889 { return null; }
5890 for (var i = 0; i < list.length; i++)
5891 {
5892 if (list[i].identifier === id)
5893 { return list[i]; }
5894 }
5895 return null;
5896}
5897
5898function onTouchStart (e)
5899{
5900 if (!playingForDrag())
5901 { return; }
5902 if (app.activeTouchId != null)
5903 {
5904 if (e.preventDefault)
5905 { e.preventDefault(); }
5906 return;
5907 }
5908 var t = e.changedTouches && e.changedTouches[0];
5909 if (!t)
5910 { return; }
5911 if (e.preventDefault)
5912 { e.preventDefault(); }
5913 app.activeTouchId = t.identifier;
5914 addWindowPointer();
5915 startDragFromEvent(e);
5916}
5917
5918function onTouchMove (e)
5919{
5920 if (app.activeTouchId == null)
5921 { return; }
5922 if (!touchById(e.changedTouches, app.activeTouchId)
5923 && !touchById(e.touches, app.activeTouchId))
5924 { return; }
5925 if (e.preventDefault)
5926 { e.preventDefault(); }
5927 moveDragFromEvent(e);
5928}
5929
5930function onTouchEnd (e)
5931{
5932 if (app.activeTouchId == null)
5933 { return; }
5934 if (!touchById(e.changedTouches, app.activeTouchId))
5935 { return; }
5936 if (e.preventDefault)
5937 { e.preventDefault(); }
5938 finishDrag({});
5939}
5940
5941function onTouchCancel (e)
5942{
5943 if (app.activeTouchId == null)
5944 { return; }
5945 if (!touchById(e.changedTouches, app.activeTouchId))
5946 { return; }
5947 if (e.preventDefault)
5948 { e.preventDefault(); }
5949 finishDrag({ noLaunch: true });
5950}
5951
5952function logPhysicsDebug ()
5953{
5954 if (!app.debugPhysics || !app.core)
5955 { return; }
5956 ensureDragDebugOverlay();
5957 var el = document.getElementById('drag-debug');
5958 if (!el)
5959 { return; }
5960 var issues = app.core.lastInvariantViolations || [];
5961 var flying = 0;
5962 var manuals = 0;
5963 var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0;
5964 for (var i = 0; i < app.core.blocks.length; i++)
5965 {
5966 if (app.core.blocks[i].state === 'flying')
5967 { flying++; }
5968 if (app.core.blocks[i].state === 'manual')
5969 { manuals++; }
5970 }
5971 var status = issues.length
5972 ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n'))
5973 : ('physics ok blocks=' + app.core.blocks.length
5974 + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters);
5975 // Keep any live drag line above the physics status.
5976 var dragLine = '';
5977 if (app.debugDrag && lastDragDebug)
5978 {
5979 dragLine = el.textContent && el.textContent.indexOf('drag ') === 0
5980 ? el.textContent.split('\n')[0] + '\n'
5981 : '';
5982 }
5983 el.textContent = dragLine + status;
5984 el.hidden = false;
5985 el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8';
5986}
5987
5988function ensureDragDebugOverlay ()
5989{
5990 if (document.getElementById('drag-debug'))
5991 { return; }
5992 var el = document.createElement('div');
5993 el.id = 'drag-debug';
5994 el.setAttribute('aria-live', 'polite');
5995 document.body.appendChild(el);
5996}
5997
5998function logDragDebug (e, pos, phase)
5999{
6000 if (!app.debugDrag)
6001 { return; }
6002 ensureDragDebugOverlay();
6003 var el = document.getElementById('drag-debug');
6004 if (!el)
6005 { return; }
6006 var block = null;
6007 if (app.core && app.core.drag)
6008 { block = app.core.blockById(app.core.drag.blockId); }
6009 var pt = e ? eventClient(e) : null;
6010 var evType = e ? e.type : phase;
6011 var info = {
6012 phase: phase,
6013 ev: evType,
6014 src: pos && pos.src,
6015 fieldY: pos && Math.round(pos.y * 100) / 100,
6016 col: pos && Math.round(pos.col * 100) / 100,
6017 cy: pt && Math.round(pt.y * 10) / 10,
6018 blockY: block && Math.round(block.y * 100) / 100,
6019 target: block && Math.floor((pos && pos.y) + 1e-12),
6020 launch: app.core && app.core.drag && app.core.drag.launchIntent,
6021 touchId: app.activeTouchId,
6022 pid: app.pointerId,
6023 ptype: app.pointerType
6024 };
6025 lastDragDebug = info;
6026 el.textContent = 'drag ' + phase
6027 + ' ev=' + evType
6028 + ' src=' + (info.src || '-')
6029 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
6030 + ' → ' + (info.target != null ? info.target : '-')
6031 + ' block=' + (info.blockY != null ? info.blockY : '-')
6032 + (info.launch ? ' LAUNCH' : '')
6033 + ' tId=' + info.touchId
6034 + ' pId=' + info.pid;
6035 el.hidden = false;
6036}
6037
6038
6039function hideEl (id)
6040{
6041 document.getElementById(id).hidden = true;
6042}
6043
6044function showEl (id)
6045{
6046 document.getElementById(id).hidden = false;
6047}
6048
6049window.addEventListener('resize', function ()
6050{
6051 if (app.mode === 'playing')
6052 { layout(); }
6053});
6054
6055window.addEventListener('orientationchange', function ()
6056{
6057 setTimeout(function ()
6058 {
6059 if (app.mode === 'playing')
6060 { layout(); }
6061 }, 120);
6062});
6063
6064/* ---------- online play (stage 2) ---------------------------------- */
6065
6066function tickOnline (dt)
6067{
6068 if (!app.online || typeof Online === 'undefined')
6069 { return; }
6070 if (app.core)
6071 {
6072 var shots = app.core.consumeOutgoingShots();
6073 for (var i = 0; i < shots.length; i++)
6074 {
6075 var s = shots[i];
6076 var start = fieldToViewport(s.col, s.y + 1);
6077 Online.rememberFlightLocal(s, start.x, start.y);
6078 }
6079 Online.queueShots(shots);
6080 }
6081 Online.tickFlights();
6082 Online.renderMinis(document.getElementById('minis'));
6083}
6084
6085
6086/* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */
6087
6088function bindOfflineUi ()
6089{
6090 var btn = document.getElementById('btn-offline');
6091 if (btn)
6092 {
6093 btn.addEventListener('click', onOffline);
6094 btn.addEventListener('pointerup', function (e)
6095 {
6096 if (e.pointerType === 'touch' || e.pointerType === 'pen')
6097 {
6098 e.preventDefault();
6099 onOffline();
6100 }
6101 });
6102 }
6103 var back = document.getElementById('btn-offline-menu');
6104 if (back)
6105 {
6106 back.addEventListener('click', function ()
6107 {
6108 teardownPlay();
6109 app.mode = 'menu';
6110 app.offline = false;
6111 app.battle = null;
6112 hideEl('offline-result');
6113 showEl('menu');
6114 });
6115 }
6116}
6117
6118function onOffline ()
6119{
6120 openPlanetSelect('offline');
6121}
6122
6123function tickOffline (dt)
6124{
6125 if (!app.battle || !app.core || typeof Offline === 'undefined')
6126 { return; }
6127
6128 if (app.battle.state === 'round_won')
6129 {
6130 if (!app.roundWonHandled)
6131 {
6132 app.roundWonHandled = true;
6133 app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5;
6134 }
6135 app.roundWonDelay -= dt;
6136 if (app.roundWonDelay <= 0)
6137 { startNextOfflineRound(); }
6138 updateOfflineMinis(dt, true);
6139 return;
6140 }
6141
6142 var result = app.battle.tick(dt, app.core);
6143 if (result && result.flights && result.flights.length
6144 && typeof Online !== 'undefined' && Online.spawnFlights)
6145 {
6146 var locals = Object.create(null);
6147 var list = result.locals || [];
6148 for (var i = 0; i < list.length; i++)
6149 {
6150 var s = list[i];
6151 var start;
6152 if (s.from_id === 'player')
6153 { start = fieldToViewport(s.col, s.y + 1); }
6154 else
6155 { start = miniViewportCenter(s.from_id); }
6156 locals[s.client_id] = {
6157 col: s.col,
6158 y: s.y,
6159 color: s.color,
6160 startX: start.x,
6161 startY: start.y
6162 };
6163 }
6164 Online.spawnFlights(result.flights, locals);
6165 }
6166 if (typeof Online !== 'undefined' && Online.tickFlights)
6167 { Online.tickFlights(); }
6168 updateOfflineMinis(dt, false);
6169
6170 if (app.battle.state === 'lost' && !app.offlineResultShown)
6171 { showOfflineResult(); }
6172}
6173
6174function startNextOfflineRound ()
6175{
6176 if (!app.battle)
6177 { return; }
6178 app.battle.advanceRound();
6179 app.roundWonHandled = false;
6180 app.roundWonDelay = 0;
6181 app._keepBattleOnTeardown = true;
6182 // Tear down the current scene then start a fresh player field,
6183 // keeping the same battle (already advanced).
6184 var planet = app.battle.playerPlanet;
6185 app._keepBattleOnTeardown = true;
6186 teardownPlay();
6187 app.offline = true;
6188 app.battle = app.battle; // kept
6189 startPlay({ planet: planet, offline: true, keepBattle: true });
6190}
6191
6192function showOfflineResult ()
6193{
6194 app.offlineResultShown = true;
6195 var battle = app.battle;
6196 var reached = document.getElementById('offline-reached');
6197 if (reached)
6198 { reached.textContent = String(battle.round); }
6199 var detail = document.getElementById('offline-result-detail');
6200 if (detail)
6201 {
6202 var sch = battle.schedule;
6203 var n = sch.opponents;
6204 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
6205 detail.textContent = 'Je speelde tegen ' + n + ' ' + noun
6206 + ' met skill ' + Math.round(sch.skill * 100) + '%.';
6207 }
6208 hideEl('game-over');
6209 showEl('offline-result');
6210}
6211
6212function refreshOfflineHud ()
6213{
6214 var el = document.getElementById('offline-hud');
6215 if (!el)
6216 { return; }
6217 if (!(app.offline && app.battle && app.mode === 'playing'))
6218 {
6219 el.hidden = true;
6220 return;
6221 }
6222 el.hidden = false;
6223 var sch = app.battle.schedule;
6224 var n = sch.opponents;
6225 var noun = n === 1 ? 'tegenstander' : 'tegenstanders';
6226 var r = document.getElementById('offline-round');
6227 var o = document.getElementById('offline-opponents');
6228 var s = document.getElementById('offline-skill');
6229 if (r)
6230 { r.textContent = 'Ronde ' + sch.round; }
6231 if (o)
6232 { o.textContent = n + ' ' + noun; }
6233 if (s)
6234 { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; }
6235}
6236
6237function hideOfflineHud ()
6238{
6239 var el = document.getElementById('offline-hud');
6240 if (el)
6241 { el.hidden = true; }
6242}
6243
6244function refreshChainIndicator ()
6245{
6246 var el = document.getElementById('chain-indicator');
6247 if (!el)
6248 { return; }
6249 var info = app.core && app.core.lastChainIndicator;
6250 var active = app.core && app.core.hasActiveLandingChain
6251 && app.core.hasActiveLandingChain();
6252 // Show only while a chained cluster is still in the air.
6253 if (!info || info.chain < 1 || app.mode !== 'playing' || !active)
6254 {
6255 el.hidden = true;
6256 return;
6257 }
6258 el.hidden = false;
6259 el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%';
6260}
6261
6262function hideChainIndicator ()
6263{
6264 var el = document.getElementById('chain-indicator');
6265 if (el)
6266 { el.hidden = true; }
6267}
6268
6269function miniViewportCenter (botId)
6270{
6271 var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas');
6272 if (!el)
6273 { return { x: window.innerWidth / 2, y: 40 }; }
6274 var rect = el.getBoundingClientRect();
6275 return { x: rect.left + rect.width / 2, y: rect.bottom };
6276}
6277
6278function offlineMiniSize (n)
6279{
6280 if (n >= 10)
6281 { return { w: 40, h: 52 }; }
6282 if (n >= 6)
6283 { return { w: 56, h: 73 }; }
6284 return { w: 80, h: 104 };
6285}
6286
6287function updateOfflineMinis (dt, force)
6288{
6289 app.miniAcc = (app.miniAcc || 0) + dt;
6290 if (!force && app.miniAcc < 0.1)
6291 { return; }
6292 app.miniAcc = 0;
6293 renderOfflineMinis();
6294}
6295
6296function renderOfflineMinis ()
6297{
6298 var container = document.getElementById('minis');
6299 if (!container || !app.battle)
6300 { return; }
6301 var bots = app.battle.bots;
6302 var size = offlineMiniSize(bots.length);
6303 container.classList.toggle('crowded', bots.length > 5);
6304 var existing = {};
6305 var kids = container.querySelectorAll('[data-player]');
6306 for (var i = 0; i < kids.length; i++)
6307 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
6308 var seen = Object.create(null);
6309 for (var i = 0; i < bots.length; i++)
6310 {
6311 var bot = bots[i];
6312 seen[bot.id] = true;
6313 var el = existing[bot.id];
6314 if (!el)
6315 {
6316 el = document.createElement('div');
6317 el.className = 'mini';
6318 el.setAttribute('data-player', bot.id);
6319 el.innerHTML = '<div class="mini-name"></div>'
6320 + '<canvas class="mini-canvas" width="' + size.w
6321 + '" height="' + size.h + '"></canvas>'
6322 + '<div class="mini-meta"></div>';
6323 container.appendChild(el);
6324 }
6325 var canvas = el.querySelector('canvas');
6326 if (canvas && (canvas.width !== size.w || canvas.height !== size.h))
6327 {
6328 canvas.width = size.w;
6329 canvas.height = size.h;
6330 }
6331 el.classList.toggle('eliminated', !!bot.eliminated);
6332 var planetName = bot.planet && bot.planet.name ? bot.planet.name : '';
6333 el.querySelector('.mini-name').textContent = bot.name
6334 + (planetName ? ' · ' + planetName : '');
6335 el.querySelector('.mini-meta').textContent = bot.eliminated
6336 ? 'Uit'
6337 : ('Punten ' + (bot.score || 0));
6338 var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] };
6339 if (typeof Online !== 'undefined' && Online._drawMini)
6340 { Online._drawMini(canvas, snap, bot.planet); }
6341 }
6342 for (var id in existing)
6343 {
6344 if (!seen[id])
6345 { existing[id].remove(); }
6346 }
6347}
6348
6349function buildColumnWarn ()
6350{
6351 app.columnWarn = [];
6352 if (!app.scene)
6353 { return; }
6354 var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null;
6355 if (!img)
6356 { return; }
6357 for (var c = 0; c < 10; c++)
6358 {
6359 var obj = new GameObject(0, 0, img, 0);
6360 obj.renderer.alpha = 0;
6361 obj.renderer.visible = false;
6362 app.scene.addObject(obj);
6363 app.columnWarn.push(obj);
6364 }
6365 updateColumnWarn(0);
6366}
6367
6368function updateColumnWarn (dt)
6369{
6370 if (!app.columnWarn || !app.core)
6371 { return; }
6372 app.warnClock = (app.warnClock || 0) + (dt || 0);
6373 var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse)
6374 ? GameCore.columnWarnPulse(app.warnClock)
6375 : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575));
6376 var t = app.tile;
6377 for (var c = 0; c < app.columnWarn.length; c++)
6378 {
6379 var obj = app.columnWarn[c];
6380 var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c);
6381 obj.renderer.visible = !!on;
6382 obj.renderer.alpha = on ? pulse : 0;
6383 if (t)
6384 {
6385 obj.transform.position.x = c * t + t / 2;
6386 obj.transform.position.y = app.fieldH / 2;
6387 obj.transform.size = { x: t, y: app.fieldH };
6388 }
6389 }
6390}
6391
6392function fieldToViewport (col, fieldY)
6393{
6394 var canvas = app.scene && app.scene.canvas;
6395 if (!canvas)
6396 { return { x: window.innerWidth / 2, y: 40 }; }
6397 var rect = canvas.getBoundingClientRect();
6398 var x = rect.left + ((col + 0.5) / 10) * rect.width;
6399 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
6400 return { x: x, y: y };
6401}
6402
6403function onlinePayload ()
6404{
6405 if (!app.online || !app.core)
6406 { return {}; }
6407 return {
6408 snapshot: app.core.fieldSnapshot(),
6409 score: app.core.score,
6410 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
6411 };
6412}
6413
6414function onOnlineEliminated ()
6415{
6416 app.eliminatedReported = true;
6417 app.spectating = true;
6418 unbindPointer();
6419 hideEl('game-over');
6420 var lobby = typeof Online !== 'undefined' && Online.lobby;
6421 if (lobby && lobby.status === 'finished')
6422 {
6423 showPodium(lobby);
6424 return;
6425 }
6426 showEl('spectator');
6427}
6428
6429function showPodium (lobby)
6430{
6431 hideEl('spectator');
6432 hideEl('game-over');
6433 hideEl('online-panel');
6434 showEl('podium');
6435 var list = document.getElementById('podium-list');
6436 list.innerHTML = '';
6437 var ranks = (lobby && lobby.rankings) || [];
6438 for (var i = 0; i < ranks.length; i++)
6439 {
6440 var r = ranks[i];
6441 var li = document.createElement('li');
6442 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
6443 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
6444 list.appendChild(li);
6445 }
6446 var hint = document.getElementById('podium-hint');
6447 var secs = (lobby && lobby.podium_seconds) || 5;
6448 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
6449}
6450
6451function startOnlineMatch ()
6452{
6453 if (app.mode === 'playing' && app.online)
6454 { return; }
6455 var planet = Planet.planetById(selectedPlanetId());
6456 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
6457 if (me && me.planet && me.planet.id)
6458 { planet = Planet.planetById(me.planet.id); }
6459 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
6460 if (typeof Online !== 'undefined')
6461 { Online.startPolling(onlinePayload); }
6462}
6463
6464function leaveOnlineMatch (goMenu)
6465{
6466 if (typeof Online !== 'undefined')
6467 {
6468 Online.stopPolling();
6469 Online.leaveLobby();
6470 Online.clearFlights();
6471 }
6472 teardownPlay();
6473 app.online = false;
6474 if (goMenu)
6475 {
6476 app.mode = 'menu';
6477 showEl('menu');
6478 }
6479 else
6480 {
6481 app.mode = 'online';
6482 openOnlinePanel();
6483 }
6484}
6485
6486function bindOnlineUi ()
6487{
6488 var onlineBtn = document.getElementById('btn-online');
6489 if (!onlineBtn)
6490 { return; }
6491 onlineBtn.addEventListener('click', function ()
6492 { openOnlinePanel(); });
6493
6494 var backs = document.querySelectorAll('[data-back-menu]');
6495 for (var i = 0; i < backs.length; i++)
6496 {
6497 backs[i].addEventListener('click', function ()
6498 {
6499 if (typeof Online !== 'undefined')
6500 { Online.stopPolling(); }
6501 hideEl('online-panel');
6502 app.mode = 'menu';
6503 app.online = false;
6504 showEl('menu');
6505 });
6506 }
6507
6508 document.getElementById('btn-create').addEventListener('click', function ()
6509 {
6510 Online.createLobby().then(function (data)
6511 {
6512 if (data && data.ok)
6513 {
6514 renderOnline();
6515 Online.startPolling(onlinePayload);
6516 }
6517 else
6518 { renderOnline(); }
6519 });
6520 });
6521
6522 document.getElementById('join-form').addEventListener('submit', function (e)
6523 {
6524 e.preventDefault();
6525 var code = (document.getElementById('join-code').value || '').trim();
6526 if (!code)
6527 { return; }
6528 Online.joinLobby(code).then(function ()
6529 {
6530 renderOnline();
6531 if (Online.lobby)
6532 { Online.startPolling(onlinePayload); }
6533 });
6534 });
6535
6536 document.getElementById('btn-ready').addEventListener('click', function ()
6537 {
6538 var me = Online.mePlayer();
6539 Online.setReady(!(me && me.ready)).then(renderOnline);
6540 });
6541
6542 document.getElementById('btn-start').addEventListener('click', function ()
6543 {
6544 Online.startGame().then(function (data)
6545 {
6546 if (data && data.ok)
6547 { startOnlineMatch(); }
6548 else
6549 { renderOnline(); }
6550 });
6551 });
6552
6553 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
6554 {
6555 Online.leaveLobby().then(function ()
6556 {
6557 Online.stopPolling();
6558 renderOnline();
6559 });
6560 });
6561
6562 document.getElementById('btn-copy-code').addEventListener('click', function ()
6563 {
6564 var code = document.getElementById('lobby-code').textContent;
6565 if (navigator.clipboard && navigator.clipboard.writeText)
6566 { navigator.clipboard.writeText(code); }
6567 });
6568
6569 document.getElementById('btn-spectate').addEventListener('click', function ()
6570 {
6571 hideEl('spectator');
6572 app.spectating = true;
6573 });
6574
6575 document.getElementById('btn-leave-game').addEventListener('click', function ()
6576 { leaveOnlineMatch(false); });
6577
6578 if (typeof Online !== 'undefined')
6579 {
6580 Online.onChange = function ()
6581 { renderOnline(); };
6582 Online.onGameStart = function ()
6583 { startOnlineMatch(); };
6584 Online.onIncoming = function (incoming)
6585 {
6586 if (!app.core || app.core.state !== 'playing')
6587 { return; }
6588 for (var i = 0; i < incoming.length; i++)
6589 { app.core.ingestGarbage(); }
6590 };
6591 Online.onFinished = function (lobby)
6592 { showPodium(lobby); };
6593 Online.onLobbyReturn = function (lobby)
6594 {
6595 teardownPlay();
6596 app.online = false;
6597 app.mode = 'online';
6598 hideEl('podium');
6599 showEl('online-panel');
6600 renderOnline();
6601 Online.startPolling(onlinePayload);
6602 };
6603 }
6604
6605 var params = new URLSearchParams(window.location.search);
6606 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
6607 { openOnlinePanel(); }
6608}
6609
6610function openOnlinePanel ()
6611{
6612 hideEl('menu');
6613 hideEl('game-over');
6614 hideEl('podium');
6615 hideEl('spectator');
6616 hideEl('planet-select');
6617 showEl('online-panel');
6618 app.mode = 'online';
6619 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
6620 if (typeof Online === 'undefined')
6621 {
6622 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
6623 showOnly('online-unconfigured');
6624 return;
6625 }
6626 Online.refresh().then(function (data)
6627 {
6628 if (!data || data.ok === false)
6629 {
6630 var msg = (data && data.error) || 'Geen verbinding met de server.';
6631 showOnlineError(msg + ' Je kunt wel alleen spelen.');
6632 if (data && data.configured === false)
6633 { showOnly('online-unconfigured'); }
6634 else
6635 { showOnly('online-login'); }
6636 document.getElementById('btn-login').style.display = 'none';
6637 return;
6638 }
6639 renderOnline();
6640 if (Online.lobby)
6641 { Online.startPolling(onlinePayload); }
6642 });
6643}
6644
6645function setOnlineStatus (text)
6646{
6647 var el = document.getElementById('online-status');
6648 if (el)
6649 { el.textContent = text; }
6650}
6651
6652function showOnlineError (text)
6653{
6654 var el = document.getElementById('online-error');
6655 if (!el)
6656 { return; }
6657 if (!text)
6658 {
6659 el.hidden = true;
6660 el.textContent = '';
6661 return;
6662 }
6663 el.hidden = false;
6664 el.textContent = text;
6665}
6666
6667function showOnly (id)
6668{
6669 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
6670 for (var i = 0; i < ids.length; i++)
6671 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
6672}
6673
6674function renderOnline ()
6675{
6676 if (typeof Online === 'undefined')
6677 { return; }
6678 if (app.mode === 'playing' && app.online)
6679 {
6680 Online.renderMinis(document.getElementById('minis'));
6681 if (Online.lobby && Online.lobby.status === 'finished')
6682 { showPodium(Online.lobby); }
6683 return;
6684 }
6685 showOnlineError(Online.error);
6686 if (!Online.configured && !Online.me && !Online.local)
6687 {
6688 setOnlineStatus('Online spelen is nog niet ingesteld.');
6689 showOnly('online-unconfigured');
6690 return;
6691 }
6692 if (!Online.me)
6693 {
6694 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
6695 showOnly('online-login');
6696 document.getElementById('btn-login').style.display = '';
6697 document.getElementById('btn-login').href = Online.loginUrl();
6698 document.getElementById('local-login').hidden = !Online.local;
6699 return;
6700 }
6701 if (Online.lobby)
6702 {
6703 setOnlineStatus('Lobby');
6704 showOnly('online-lobby');
6705 document.getElementById('lobby-me-name').textContent = Online.me.name;
6706 document.getElementById('lobby-code').textContent = Online.lobby.code;
6707 var list = document.getElementById('lobby-players');
6708 list.innerHTML = '';
6709 var players = Online.lobby.players || [];
6710 for (var i = 0; i < players.length; i++)
6711 {
6712 var p = players[i];
6713 var li = document.createElement('li');
6714 if (p.is_me)
6715 { li.classList.add('you'); }
6716 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
6717 var state = p.ready ? 'Gereed' : 'Wacht…';
6718 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
6719 li.innerHTML = '<span>' + escapeText(label)
6720 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
6721 + '</span><span class="'
6722 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
6723 list.appendChild(li);
6724 }
6725 renderPlanetGrid('lobby-planet-grid', true);
6726 var me = Online.mePlayer();
6727 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
6728 var start = document.getElementById('btn-start');
6729 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
6730 start.disabled = !Online.lobby.can_start;
6731 var hint = document.getElementById('lobby-hint');
6732 if (Online.lobby.status === 'playing')
6733 { hint.textContent = 'Het spel start…'; }
6734 else if (players.length < 2)
6735 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
6736 else if (!Online.lobby.all_ready)
6737 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
6738 else if (Online.lobby.can_start)
6739 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
6740 else
6741 { hint.textContent = 'Wachten tot de host start.'; }
6742 return;
6743 }
6744 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
6745 showOnly('online-home');
6746 document.getElementById('me-name').textContent = Online.me.name;
6747 document.getElementById('local-login').hidden = !Online.local;
6748}
6749
6750function escapeText (s)
6751{
6752 return String(s)
6753 .replace(/&/g, '&amp;')
6754 .replace(/</g, '&lt;')
6755 .replace(/>/g, '&gt;')
6756 .replace(/"/g, '&quot;');
6757}
6758
6759
6760function selectedPlanetId ()
6761{
6762 if (app.selectedPlanetId)
6763 { return app.selectedPlanetId; }
6764 return 'terra';
6765}
6766
6767function restoreSelectedPlanet ()
6768{
6769 var id = 'terra';
6770 try
6771 { id = localStorage.getItem('meteors-planet') || 'terra'; }
6772 catch (e) {}
6773 setSelectedPlanet(id, true);
6774}
6775
6776function setSelectedPlanet (id, silent)
6777{
6778 var all = Planet.allPlanets();
6779 var found = null;
6780 for (var i = 0; i < all.length; i++)
6781 {
6782 if (all[i].id === id)
6783 { found = all[i]; break; }
6784 }
6785 if (!found)
6786 { found = Planet.defaultPlanet(); }
6787 app.selectedPlanetId = found.id;
6788 try
6789 { localStorage.setItem('meteors-planet', found.id); }
6790 catch (e) {}
6791 if (!silent)
6792 {
6793 var grid = document.getElementById('planet-grid');
6794 if (grid && !grid.hidden && grid.children.length)
6795 { renderPlanetGrid('planet-grid', false); }
6796 var lobby = document.getElementById('lobby-planet-grid');
6797 if (lobby && lobby.children.length)
6798 { renderPlanetGrid('lobby-planet-grid', true); }
6799 }
6800 return found;
6801}
6802
6803function openPlanetSelect (context)
6804{
6805 if (app.mode === 'playing')
6806 { return; }
6807 app.planetSelectContext = context || 'solo';
6808 app.mode = 'planet-select';
6809 hideEl('menu');
6810 hideEl('online-panel');
6811 hideEl('game-over');
6812 showEl('planet-select');
6813 renderPlanetGrid('planet-grid', false);
6814 var go = document.getElementById('btn-planet-go');
6815 if (go)
6816 { go.textContent = 'Spelen'; }
6817}
6818
6819function renderPlanetGrid (containerId, compact)
6820{
6821 var grid = document.getElementById(containerId);
6822 if (!grid)
6823 { return; }
6824 var current = selectedPlanetId();
6825 var all = Planet.allPlanets();
6826 grid.innerHTML = '';
6827 if (compact)
6828 { grid.classList.add('compact'); }
6829 for (var i = 0; i < all.length; i++)
6830 {
6831 var pl = all[i];
6832 var btn = document.createElement('button');
6833 btn.type = 'button';
6834 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
6835 btn.setAttribute('role', 'listitem');
6836 btn.dataset.planet = pl.id;
6837 var swatches = '';
6838 for (var c = 0; c < pl.colors.length; c++)
6839 {
6840 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
6841 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
6842 }
6843 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
6844 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
6845 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
6846 + '<div class="planet-swatches">' + swatches + '</div>';
6847 btn.addEventListener('click', (function (id, isCompact)
6848 {
6849 return function ()
6850 { onPlanetPicked(id, isCompact); };
6851 })(pl.id, !!compact));
6852 grid.appendChild(btn);
6853 }
6854}
6855
6856function onPlanetPicked (id, fromLobby)
6857{
6858 setSelectedPlanet(id);
6859 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
6860 {
6861 Online.setPlanet(id).then(function ()
6862 { renderOnline(); });
6863 }
6864 else
6865 {
6866 renderPlanetGrid('planet-grid', false);
6867 }
6868}
6869
6870function confirmPlanetSelect ()
6871{
6872 var planet = setSelectedPlanet(selectedPlanetId());
6873 hideEl('planet-select');
6874 if (app.planetSelectContext === 'online')
6875 {
6876 openOnlinePanel();
6877 return;
6878 }
6879 if (app.planetSelectContext === 'offline')
6880 {
6881 startPlay({ planet: planet, offline: true });
6882 return;
6883 }
6884 startPlay({ planet: planet });
6885}
6886
6887function cancelPlanetSelect ()
6888{
6889 hideEl('planet-select');
6890 app.mode = 'menu';
6891 showEl('menu');
6892}
6893
6894function bindPlanetSelect ()
6895{
6896 var go = document.getElementById('btn-planet-go');
6897 var back = document.getElementById('btn-planet-back');
6898 if (go)
6899 {
6900 go.addEventListener('click', confirmPlanetSelect);
6901 }
6902 if (back)
6903 {
6904 back.addEventListener('click', cancelPlanetSelect);
6905 }
6906}
6907
6908/*
6909 * End File:
6910 * /workspace/meteors/src/main.js
6911 */