BlueGit

projects-timfalken-com meteors

Files

meteors / build / game.js

game.js

game.js 127.7 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 FIELD_HEIGHT / jumpsToClear tiles —
260 * at 1, one jump from the floor clears the field; at 4, you need four.
261 * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall).
262 * After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s.
263 * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump).
264 * Time to reach the apex, independent of jump height.
265 *
266 * Jump-height multipliers (never explained in the game):
267 * A vertical match of 3 is 120 % of a horizontal row of 3.
268 * Each extra block beyond 3 adds 5 %.
269 *
270 * Power is the average of the three difficulty axes (0 easy .. 1 hard)
271 * and is shown as a percentage. Miss chance (stage 2) goes from 60 % at
272 * power 0 to 5 % at power 1.
273 */
274
275var FIELD_WIDTH = 10;
276var FIELD_HEIGHT = 13;
277
278function clamp (value, lo, hi)
279{
280 return Math.max(lo, Math.min(hi, value));
281}
282
283function defaultColors ()
284{
285 return [
286 { id: 0, name: 'ember', hex: '#e85d3a', shape: 'triangle', image: 'images/block-ember.png' },
287 { id: 1, name: 'aqua', hex: '#3db8e8', shape: 'circle', image: 'images/block-aqua.png' },
288 { id: 2, name: 'leaf', hex: '#4cbf4c', shape: 'square', image: 'images/block-leaf.png' },
289 { id: 3, name: 'sun', hex: '#f0c53a', shape: 'diamond', image: 'images/block-sun.png' },
290 { id: 4, name: 'orchid', hex: '#c45ad4', shape: 'star', image: 'images/block-orchid.png' }
291 ];
292}
293
294function createPlanet (opts)
295{
296 opts = opts || {};
297 var jumpsToClear = clamp(opts.jumpsToClear == null ? 2 : opts.jumpsToClear, 1, 4);
298 var fallTime = clamp(opts.fallTime == null ? 3 : opts.fallTime, 1, 5);
299 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
300 var colors = opts.colors || defaultColors();
301 var planet = {
302 id: opts.id || null,
303 name: opts.name || 'Terra',
304 people: opts.people || 'Terrans',
305 jumpsToClear: jumpsToClear,
306 fallTime: fallTime,
307 riseTime: riseTime,
308 colors: colors,
309 baseJumpHeight: FIELD_HEIGHT / jumpsToClear,
310 fallSpeed: FIELD_HEIGHT / fallTime,
311 // Time to ease from vy=0 at the apex to terminal fallSpeed.
312 // Shorter when air resistance is low (small fallTime).
313 apexEaseTime: 0.15 * fallTime,
314 fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime),
315 // Visual landing bounce: faster at low air resistance. Stage-3 params.
316 bounceDuration: 0.12 * fallTime,
317 bounceSquash: 0.16
318 };
319 return planet;
320}
321
322function loadCatalog ()
323{
324 if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
325 { return PLANET_CATALOG; }
326 if (typeof require !== 'undefined')
327 {
328 try
329 { return require('../server/lib/planets.json'); }
330 catch (e) {}
331 }
332 return { planets: [] };
333}
334
335function planetFromData (data)
336{
337 var planet = createPlanet({
338 name: data.name,
339 people: data.people,
340 jumpsToClear: data.jumpsToClear,
341 fallTime: data.fallTime,
342 riseTime: data.riseTime,
343 colors: data.colors
344 });
345 planet.id = data.id;
346 return planet;
347}
348
349function allPlanets ()
350{
351 var raw = loadCatalog().planets || [];
352 var out = [];
353 for (var i = 0; i < raw.length; i++)
354 { out.push(planetFromData(raw[i])); }
355 if (out.length === 0)
356 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
357 return out;
358}
359
360function planetById (id)
361{
362 var all = allPlanets();
363 for (var i = 0; i < all.length; i++)
364 {
365 if (all[i].id === id)
366 { return all[i]; }
367 }
368 return defaultPlanet();
369}
370
371function defaultPlanet ()
372{
373 var all = allPlanets();
374 for (var i = 0; i < all.length; i++)
375 {
376 if (all[i].id === 'terra')
377 { return all[i]; }
378 }
379 return all[0];
380}
381
382function formatStats (planet)
383{
384 var d = displayValues(planet);
385 return 'g ' + d.gravity.toFixed(2)
386 + ' d ' + d.density.toFixed(2)
387 + ' F ' + Math.round(d.newtons) + ' N'
388 + ' Power ' + d.power + '%';
389}
390
391function spriteKey (planet, colorIndex)
392{
393 var colors = planet && planet.colors;
394 var c = colors && colors[colorIndex];
395 if (!c)
396 { return 'gray'; }
397 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
398}
399
400/**
401 * Jump height in tiles for a match line.
402 * @param {object} planet
403 * @param {number} matchLength number of blocks in the line (>= 3)
404 * @param {boolean} vertical true for a vertical line
405 */
406function jumpHeight (planet, matchLength, vertical)
407{
408 var extra = Math.max(0, (matchLength | 0) - 3);
409 var multiplier = (vertical ? 1.2 : 1.0) + 0.05 * extra;
410 return planet.baseJumpHeight * multiplier;
411}
412
413/** Initial upward speed (tiles/s) so a jump of `height` peaks in riseTime. */
414function launchVelocity (planet, height)
415{
416 if (height <= 0)
417 { return 0; }
418 return (2 * height) / planet.riseTime;
419}
420
421/** Constant deceleration (tiles/s^2) paired with launchVelocity. */
422function launchDeceleration (planet, height)
423{
424 if (height <= 0)
425 { return 0; }
426 return (2 * height) / (planet.riseTime * planet.riseTime);
427}
428
429/**
430 * Difficulty power in 0..1. Higher is harder (and, in stage 2, a lower
431 * chance that a shot-off block misses the opponent).
432 */
433function power (planet)
434{
435 var gravity = (planet.jumpsToClear - 1) / 3;
436 var air = (5 - planet.fallTime) / 4;
437 var mass = (3 - planet.riseTime) / 2.5;
438 return (gravity + air + mass) / 3;
439}
440
441/** Maximum miss chance, used by the gameplay formula and the displayed Power. */
442var MAX_MISS_CHANCE = 0.60;
443var MIN_MISS_CHANCE = 0.05;
444
445/** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */
446function missChance (planet)
447{
448 return MAX_MISS_CHANCE - (MAX_MISS_CHANCE - MIN_MISS_CHANCE) * power(planet);
449}
450
451/**
452 * Displayed Power, as a 0–100 percentage. This is the complement of the
453 * miss chance against the maximum (60%): 0% miss → 100% Power, 60% miss
454 * → 0% Power. The gameplay power() and missChance() formulas are unchanged.
455 */
456function displayPower (planet)
457{
458 return Math.round((1 - missChance(planet) / MAX_MISS_CHANCE) * 100);
459}
460
461/**
462 * Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³),
463 * launch force (N), and displayed Power as a percentage. The numbers do
464 * not have to explain themselves.
465 */
466function displayValues (planet)
467{
468 var gravity = 9.81 * planet.jumpsToClear / 2;
469 var density = 0.25 + ((5 - planet.fallTime) / 4) * 1.60;
470 var newtons = 40 + ((planet.riseTime - 0.5) / 2.5) * 160;
471 return {
472 gravity: gravity,
473 density: density,
474 newtons: newtons,
475 power: displayPower(planet),
476 missChance: missChance(planet)
477 };
478}
479
480var Planet = {
481 FIELD_WIDTH: FIELD_WIDTH,
482 FIELD_HEIGHT: FIELD_HEIGHT,
483 COLOR_COUNT: 5,
484 SETTLE_TIME: 3,
485 SPAWN_INTERVAL: 1,
486 JUMP_VERTICAL_BONUS: 1.2,
487 JUMP_EXTRA_BLOCK: 0.05,
488 createPlanet: createPlanet,
489 defaultPlanet: defaultPlanet,
490 defaultColors: defaultColors,
491 allPlanets: allPlanets,
492 planetById: planetById,
493 planetFromData: planetFromData,
494 formatStats: formatStats,
495 spriteKey: spriteKey,
496 jumpHeight: jumpHeight,
497 launchVelocity: launchVelocity,
498 launchDeceleration: launchDeceleration,
499 MAX_MISS_CHANCE: MAX_MISS_CHANCE,
500 MIN_MISS_CHANCE: MIN_MISS_CHANCE,
501 power: power,
502 missChance: missChance,
503 displayPower: displayPower,
504 displayValues: displayValues
505};
506
507if (typeof module !== 'undefined' && module.exports)
508{ module.exports = Planet; }
509else if (typeof globalThis !== 'undefined')
510{ globalThis.Planet = Planet; }
511
512/*
513 * End File:
514 * /workspace/meteors/src/planet.js
515 */
516
517/*
518 * Start File:
519 * /workspace/meteors/src/easing.js
520 */
521'use strict';
522
523/**
524 * Easing curves matching Qt QEasingCurve defaults (the same values Tim's
525 * KWin Click Tween effect uses). Formulas and default parameters come from
526 * Qt 6's QEasingCurve and https://easings.net/.
527 *
528 * Source of the click/release defaults:
529 * /workspace/click-tween/settings.h (clickTime, releaseTime, easing names)
530 * /workspace/click-tween/clicktween.cpp (press scale 0.8, release scale 1.0)
531 * /workspace/click-tween/README.md
532 */
533
534/** Qt QEasingCurve default overshoot for InBack / OutBack / InOutBack. */
535var BACK_OVERSHOOT = 1.70158;
536
537/** Qt QEasingCurve default period and amplitude for Elastic curves. */
538var ELASTIC_PERIOD = 0.3;
539var ELASTIC_AMPLITUDE = 1.0;
540
541function clamp01 (t)
542{
543 if (t <= 0)
544 { return 0; }
545 if (t >= 1)
546 { return 1; }
547 return t;
548}
549
550/** easeOutBack: overshoots the end value, then settles. Qt / easings.net. */
551function easeOutBack (t)
552{
553 t = clamp01(t);
554 var c1 = BACK_OVERSHOOT;
555 var c3 = c1 + 1;
556 var u = t - 1;
557 return 1 + c3 * u * u * u + c1 * u * u;
558}
559
560/**
561 * easeOutElastic: decaying sine overshoot past the end value.
562 * Qt default amplitude 1, period 0.3 (equivalent to easings.net).
563 */
564function easeOutElastic (t)
565{
566 t = clamp01(t);
567 if (t === 0 || t === 1)
568 { return t; }
569 var p = ELASTIC_PERIOD;
570 var s = p / 4;
571 return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1;
572}
573
574function tween (from, to, t, ease)
575{
576 return from + (to - from) * ease(clamp01(t));
577}
578
579/**
580 * DEFAULT settings of Tim's KWin Click Tween
581 * (git.timfalken.com/timfa/click-tween).
582 *
583 * Press: shrink to 80% in 150 ms with easeOutBack, stay at 80% while held.
584 * Release: grow back to 100% in 720 ms with easeOutElastic.
585 * Mid-animation release starts from the current scale, like QVariantAnimation.
586 */
587var CLICK_TWEEN = {
588 pressScale: 0.8,
589 releaseScale: 1.0,
590 pressDuration: 0.150,
591 releaseDuration: 0.720,
592 pressEase: easeOutBack,
593 releaseEase: easeOutElastic,
594 backOvershoot: BACK_OVERSHOOT,
595 elasticPeriod: ELASTIC_PERIOD,
596 elasticAmplitude: ELASTIC_AMPLITUDE,
597 source: 'click-tween settings.h + clicktween.cpp (Qt QEasingCurve defaults)'
598};
599
600/**
601 * Visual landing bounce, u in 0..1. Subtle squash with a slight stretch
602 * on the other axis and a tiny upward rebound (in tiles, visual only).
603 */
604function bouncePose (u, squash)
605{
606 if (u <= 0 || u >= 1)
607 { return { sx: 1, sy: 1, dy: 0 }; }
608 var wave = Math.sin(Math.PI * u);
609 return {
610 sx: 1 + squash * 0.6 * wave,
611 sy: 1 - squash * wave,
612 dy: 0.07 * wave * (1 - u)
613 };
614}
615
616var Easing = {
617 BACK_OVERSHOOT: BACK_OVERSHOOT,
618 ELASTIC_PERIOD: ELASTIC_PERIOD,
619 ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE,
620 easeOutBack: easeOutBack,
621 easeOutElastic: easeOutElastic,
622 tween: tween,
623 CLICK_TWEEN: CLICK_TWEEN,
624 clamp01: clamp01,
625 bouncePose: bouncePose
626};
627
628if (typeof module !== 'undefined' && module.exports)
629{ module.exports = Easing; }
630else if (typeof globalThis !== 'undefined')
631{ globalThis.Easing = Easing; }
632
633/*
634 * End File:
635 * /workspace/meteors/src/easing.js
636 */
637
638/*
639 * Start File:
640 * /workspace/meteors/src/gameCore.js
641 */
642'use strict';
643
644/**
645 * Deterministic Meteors game core. No DOM, no rendering, no input devices.
646 * The view layer reads this state and translates pointer events into
647 * beginDrag / moveDrag / endDrag.
648 */
649
650var PlanetMod = (typeof require !== 'undefined' && typeof module !== 'undefined')
651 ? require('./planet.js')
652 : (typeof Planet !== 'undefined' ? Planet : globalThis.Planet);
653
654var COLOR_GRAY = -1;
655
656var STATE_STILL = 'still';
657var STATE_FALLING = 'falling';
658var STATE_FLYING = 'flying';
659var STATE_SETTLING = 'settling';
660var STATE_LOCKED = 'locked';
661var STATE_MANUAL = 'manual';
662
663var ALIGN_EPS = 0.15;
664var SUBSTEP = 1 / 120;
665var DRAG_LAUNCH_SLACK = 0.65;
666// Upward pull (tiles past the press point) that launches an already-topmost block.
667var LAUNCH_PULL = 0.35;
668// Minimal accumulated vertical pointer travel (tiles) to swap one step.
669// No hold delay: the first swap fires as soon as this distance is reached.
670var SWAP_DISTANCE = 0.25;
671// Fallback snap (tiles) when the press cell is empty: nearest block in the column.
672var SNAP_Y = 0.5;
673// Horizontal slop (tiles) for snapping to a neighbouring column on press.
674var HORIZONTAL_SLOP = 0.35;
675
676function UnionFind ()
677{
678 this.parent = Object.create(null);
679}
680
681UnionFind.prototype.add = function (id)
682{
683 if (this.parent[id] == null)
684 { this.parent[id] = id; }
685};
686
687UnionFind.prototype.find = function (id)
688{
689 if (this.parent[id] !== id)
690 { this.parent[id] = this.find(this.parent[id]); }
691 return this.parent[id];
692};
693
694UnionFind.prototype.union = function (a, b)
695{
696 this.add(a);
697 this.add(b);
698 var ra = this.find(a);
699 var rb = this.find(b);
700 if (ra !== rb)
701 { this.parent[rb] = ra; }
702};
703
704function GameCore (planet, rng)
705{
706 this.planet = planet || PlanetMod.defaultPlanet();
707 this.rng = rng || Math.random;
708 this.width = PlanetMod.FIELD_WIDTH;
709 this.height = PlanetMod.FIELD_HEIGHT;
710 this.blocks = [];
711 this.clusters = Object.create(null);
712 this.nextBlockId = 1;
713 this.nextClusterId = 1;
714 this.spawnTimer = 0;
715 this.spawnInterval = PlanetMod.SPAWN_INTERVAL;
716 this.settleTime = PlanetMod.SETTLE_TIME;
717 this.score = 0;
718 this.state = 'playing';
719 this.drag = null;
720 this.gameOverTime = 0;
721 this.outgoingShots = [];
722 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
723 this.missChance = optsMissChance(arguments);
724}
725
726function optsMissChance (args)
727{
728 // GameCore(planet, rng, missChance) — third arg is optional.
729 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
730 { return Math.max(0, Math.min(1, args[2])); }
731 var planet = args[0];
732 if (planet && typeof PlanetMod.missChance === 'function')
733 { return PlanetMod.missChance(planet); }
734 return GameCore.DEFAULT_MISS_CHANCE;
735}
736
737GameCore.COLOR_GRAY = COLOR_GRAY;
738GameCore.LAUNCH_PULL = LAUNCH_PULL;
739GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
740GameCore.SNAP_Y = SNAP_Y;
741GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
742GameCore.DEFAULT_MISS_CHANCE = 0.30;
743GameCore.STATE_STILL = STATE_STILL;
744GameCore.STATE_FALLING = STATE_FALLING;
745GameCore.STATE_FLYING = STATE_FLYING;
746GameCore.STATE_SETTLING = STATE_SETTLING;
747GameCore.STATE_LOCKED = STATE_LOCKED;
748GameCore.STATE_MANUAL = STATE_MANUAL;
749
750GameCore.prototype.randomColor = function ()
751{
752 return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length;
753};
754
755GameCore.prototype.createBlock = function (col, y, color, state)
756{
757 var block = {
758 id: this.nextBlockId++,
759 col: col,
760 y: y,
761 color: color,
762 state: state || STATE_STILL,
763 vy: 0,
764 clusterId: null,
765 settleTime: 0,
766 flame: false,
767 pushedClusters: null,
768 manualTarget: 0,
769 manualDecel: 0,
770 manualPhase: null,
771 bouncing: false,
772 bounceAge: 0
773 };
774 this.blocks.push(block);
775 return block;
776};
777
778GameCore.prototype.removeBlock = function (block)
779{
780 if (block.clusterId != null)
781 { this.leaveCluster(block); }
782 var index = this.blocks.indexOf(block);
783 if (index >= 0)
784 { this.blocks.splice(index, 1); }
785};
786
787GameCore.prototype.leaveCluster = function (block)
788{
789 var id = block.clusterId;
790 block.clusterId = null;
791 block.flame = false;
792 if (id == null || !this.clusters[id])
793 { return; }
794 var still = 0;
795 for (var i = 0; i < this.blocks.length; i++)
796 {
797 if (this.blocks[i].clusterId === id)
798 { still++; }
799 }
800 if (still === 0)
801 { delete this.clusters[id]; }
802};
803
804GameCore.prototype.blocksInColumn = function (col)
805{
806 var out = [];
807 for (var i = 0; i < this.blocks.length; i++)
808 {
809 if (this.blocks[i].col === col)
810 { out.push(this.blocks[i]); }
811 }
812 out.sort(function (a, b) { return a.y - b.y; });
813 return out;
814};
815
816GameCore.prototype.isGrounded = function (block)
817{
818 return block.state === STATE_STILL
819 || block.state === STATE_SETTLING
820 || block.state === STATE_LOCKED;
821};
822
823GameCore.prototype.stackTop = function (col, ignore)
824{
825 var top = 0;
826 for (var i = 0; i < this.blocks.length; i++)
827 {
828 var block = this.blocks[i];
829 if (block.col !== col)
830 { continue; }
831 if (ignore && ignore(block))
832 { continue; }
833 if (this.isGrounded(block))
834 {
835 var surface = block.y + 1;
836 if (surface > top)
837 { top = surface; }
838 }
839 }
840 return top;
841};
842
843GameCore.prototype.isColumnLocked = function (col)
844{
845 for (var i = 0; i < this.blocks.length; i++)
846 {
847 var block = this.blocks[i];
848 if (block.col === col && block.state === STATE_LOCKED)
849 { return true; }
850 }
851 return false;
852};
853
854GameCore.prototype.isColumnStill = function (col)
855{
856 if (this.isColumnLocked(col))
857 { return false; }
858 for (var i = 0; i < this.blocks.length; i++)
859 {
860 var block = this.blocks[i];
861 if (block.col !== col)
862 { continue; }
863 if (block.state === STATE_FLYING
864 || block.state === STATE_FALLING
865 || block.state === STATE_MANUAL
866 || block.state === STATE_SETTLING)
867 { return false; }
868 }
869 return true;
870};
871
872GameCore.prototype.groundedCount = function (col)
873{
874 var n = 0;
875 for (var i = 0; i < this.blocks.length; i++)
876 {
877 if (this.blocks[i].col === col && this.isGrounded(this.blocks[i]))
878 { n++; }
879 }
880 return n;
881};
882
883GameCore.prototype.blockAt = function (col, row)
884{
885 for (var i = 0; i < this.blocks.length; i++)
886 {
887 var block = this.blocks[i];
888 if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS)
889 { return block; }
890 }
891 return null;
892};
893
894GameCore.prototype.place = function (col, row, color, state)
895{
896 return this.createBlock(col, row, color, state || STATE_STILL);
897};
898
899GameCore.prototype.lockedColumnCount = function ()
900{
901 var n = 0;
902 for (var c = 0; c < this.width; c++)
903 {
904 if (this.isColumnLocked(c))
905 { n++; }
906 }
907 return n;
908};
909
910GameCore.prototype.startBounce = function (block)
911{
912 if (!block)
913 { return; }
914 block.bouncing = true;
915 block.bounceAge = 0;
916};
917
918GameCore.prototype.advanceBounces = function (dt)
919{
920 var duration = this.planet.bounceDuration;
921 for (var i = 0; i < this.blocks.length; i++)
922 {
923 var block = this.blocks[i];
924 if (!block.bouncing)
925 { continue; }
926 block.bounceAge += dt;
927 if (duration <= 0 || block.bounceAge >= duration)
928 {
929 block.bouncing = false;
930 block.bounceAge = duration;
931 }
932 }
933};
934
935/**
936 * True if `block` rests on the floor or on a solid (still / settling /
937 * locked) block immediately below it in the same column.
938 */
939GameCore.prototype.hasSupport = function (block)
940{
941 if (block.y <= 1e-9)
942 { return true; }
943 for (var i = 0; i < this.blocks.length; i++)
944 {
945 var other = this.blocks[i];
946 if (other === block || other.col !== block.col)
947 { continue; }
948 if (!this.isGrounded(other))
949 { continue; }
950 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
951 { return true; }
952 }
953 return false;
954};
955
956/** Highest flying block in this column whose top is at or below `block.y + 1`. */
957GameCore.prototype.highestFlyingBelow = function (block)
958{
959 var best = null;
960 for (var i = 0; i < this.blocks.length; i++)
961 {
962 var other = this.blocks[i];
963 if (other === block || other.col !== block.col)
964 { continue; }
965 if (other.state !== STATE_FLYING || other.clusterId == null)
966 { continue; }
967 var cluster = this.clusters[other.clusterId];
968 if (!cluster || cluster.phase === 'landed')
969 { continue; }
970 // The falling block is at or above this flyer (or already overlapping).
971 if (block.y + 1e-9 < other.y)
972 { continue; }
973 if (!best || other.y > best.y)
974 { best = other; }
975 }
976 return best;
977};
978
979GameCore.prototype.highestFallingBelow = function (block)
980{
981 var best = null;
982 for (var i = 0; i < this.blocks.length; i++)
983 {
984 var other = this.blocks[i];
985 if (other === block || other.col !== block.col)
986 { continue; }
987 if (other.state !== STATE_FALLING)
988 { continue; }
989 if (other.y > block.y - 1e-9)
990 { continue; }
991 if (!best || other.y > best.y)
992 { best = other; }
993 }
994 return best;
995};
996
997/**
998 * Make an unsupported still block start falling from rest, so it eases
999 * into fallSpeed under normal gravity. Skips the block being dragged.
1000 */
1001/**
1002 * Strip leftover launch / manual kinematics so a block that has just
1003 * become still or falling starts from rest. Used after a landed grey
1004 * cluster recolors, and whenever an unsupported still block drops.
1005 */
1006GameCore.prototype.clearFlightState = function (block)
1007{
1008 block.vy = 0;
1009 block.flame = false;
1010 block.manualPhase = null;
1011 block.manualTarget = null;
1012 block.manualDecel = 0;
1013 block.pushedClusters = null;
1014};
1015
1016GameCore.prototype.releaseUnsupported = function ()
1017{
1018 for (var i = 0; i < this.blocks.length; i++)
1019 {
1020 var block = this.blocks[i];
1021 if (block.state !== STATE_STILL)
1022 { continue; }
1023 if (this.drag && this.drag.blockId === block.id)
1024 { continue; }
1025 if (this.hasSupport(block))
1026 { continue; }
1027 this.leaveCluster(block);
1028 this.clearFlightState(block);
1029 block.state = STATE_FALLING;
1030 }
1031};
1032
1033GameCore.prototype.accelerateFall = function (block, dt)
1034{
1035 var target = -this.planet.fallSpeed;
1036 if (block.vy > target)
1037 { block.vy = Math.max(target, block.vy - this.planet.fallAccel * dt); }
1038 else
1039 { block.vy = target; }
1040};
1041
1042GameCore.prototype.landFallingBlock = function (block)
1043{
1044 block.vy = 0;
1045 block.flame = false;
1046 this.startBounce(block);
1047 if (block.color === COLOR_GRAY)
1048 {
1049 block.state = STATE_SETTLING;
1050 block.settleTime = 0;
1051 }
1052 else
1053 { block.state = STATE_STILL; }
1054};
1055
1056/**
1057 * Sit `block` on top of the flying cluster that `flyer` belongs to, and
1058 * carry it along as cargo (no flame). Returns true if attached.
1059 */
1060GameCore.prototype.attachToFlyingCluster = function (block, flyer)
1061{
1062 var cluster = this.clusters[flyer.clusterId];
1063 if (!cluster || cluster.phase === 'landed')
1064 { return false; }
1065 var roof = flyer.y + 1;
1066 for (var i = 0; i < this.blocks.length; i++)
1067 {
1068 var other = this.blocks[i];
1069 if (other === block || other.col !== block.col)
1070 { continue; }
1071 if (other.clusterId !== cluster.id)
1072 { continue; }
1073 if (other.y + 1 > roof)
1074 { roof = other.y + 1; }
1075 }
1076 var oldN = this.clusterMembers(cluster.id).length;
1077 var fallingVy = block.vy;
1078 block.y = roof;
1079 block.state = STATE_FLYING;
1080 block.clusterId = cluster.id;
1081 block.flame = false;
1082 block.settleTime = 0;
1083 // A cluster born from a thrown block averages in falling cargo
1084 // the same way two flying clusters merge (t1108). Other rockets
1085 // keep their velocity and just pick the cargo up.
1086 if (cluster.fromManual)
1087 {
1088 var newN = oldN + 1;
1089 cluster.vy = (cluster.vy * oldN + fallingVy) / newN;
1090 cluster.decel = ((cluster.decel || 0) * oldN) / newN;
1091 cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
1092 cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
1093 var members = this.clusterMembers(cluster.id);
1094 for (var m = 0; m < members.length; m++)
1095 { members[m].vy = cluster.vy; }
1096 }
1097 else
1098 { block.vy = cluster.vy; }
1099 return true;
1100};
1101
1102GameCore.prototype.catchFallingOntoCluster = function (cluster, members)
1103{
1104 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1105 { return; }
1106 // Snapshot falling blocks; attaching mutates state.
1107 var falling = [];
1108 for (var i = 0; i < this.blocks.length; i++)
1109 {
1110 if (this.blocks[i].state === STATE_FALLING)
1111 { falling.push(this.blocks[i]); }
1112 }
1113 for (var i = 0; i < falling.length; i++)
1114 {
1115 var block = falling[i];
1116 var flyer = null;
1117 for (var m = 0; m < members.length; m++)
1118 {
1119 var other = members[m];
1120 if (other.col !== block.col)
1121 { continue; }
1122 // Overlap or rest on this member's top.
1123 if (block.y < other.y + 1 + 1e-9 && block.y + 1 > other.y - 1e-9)
1124 {
1125 if (!flyer || other.y > flyer.y)
1126 { flyer = other; }
1127 }
1128 }
1129 if (flyer)
1130 { this.attachToFlyingCluster(block, flyer); }
1131 }
1132};
1133
1134GameCore.prototype.tick = function (dt)
1135{
1136 if (this.state === 'gameover')
1137 {
1138 this.gameOverTime += Math.max(0, dt);
1139 return;
1140 }
1141 if (dt <= 0)
1142 { return; }
1143 dt = Math.min(dt, 0.1);
1144
1145 this.spawnTimer += dt;
1146 while (this.spawnTimer >= this.spawnInterval)
1147 {
1148 this.spawnTimer -= this.spawnInterval;
1149 this.trySpawn();
1150 }
1151
1152 var left = dt;
1153 while (left > 1e-12)
1154 {
1155 var step = Math.min(SUBSTEP, left);
1156 this.integrateFalling(step);
1157 this.resolveFlyingMatches();
1158 this.integrateClusters(step);
1159 this.mergeFlyingClusters();
1160 this.integrateManual(step);
1161 this.mergeAnyManualFallingOverlaps();
1162 this.cullOffTop();
1163 left -= step;
1164 }
1165
1166 this.releaseUnsupported();
1167 this.advanceSettle(dt);
1168 // After a landed grey group is released, blocks that were sitting on
1169 // hanging members are still STILL (the earlier pass ran while those
1170 // members counted as support). Drop them from rest before matching,
1171 // so they cannot form a mid-air match and shoot off the top.
1172 this.releaseUnsupported();
1173 this.advanceBounces(dt);
1174 if (!this.drag)
1175 { this.resolveMatches(); }
1176 this.checkLocks();
1177 this.checkGameOver();
1178};
1179
1180/** Step a stretch of time in fixed substeps. Useful for tests. */
1181GameCore.prototype.step = function (seconds, dt)
1182{
1183 dt = dt || SUBSTEP;
1184 var t = 0;
1185 while (t < seconds - 1e-15)
1186 {
1187 var s = Math.min(dt, seconds - t);
1188 this.tick(s);
1189 t += s;
1190 }
1191};
1192
1193GameCore.prototype.trySpawn = function ()
1194{
1195 if (this.state !== 'playing')
1196 { return null; }
1197 var eligible = [];
1198 for (var col = 0; col < this.width; col++)
1199 {
1200 if (this.isColumnLocked(col))
1201 { continue; }
1202 if (this.groundedCount(col) >= this.height)
1203 { continue; }
1204 var alreadyFalling = false;
1205 var list = this.blocksInColumn(col);
1206 for (var i = 0; i < list.length; i++)
1207 {
1208 if (list[i].state === STATE_FALLING)
1209 {
1210 alreadyFalling = true;
1211 break;
1212 }
1213 }
1214 if (!alreadyFalling)
1215 { eligible.push(col); }
1216 }
1217 if (!eligible.length)
1218 { return null; }
1219 var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1220 var color = this.randomColor();
1221 var block = this.createBlock(col, this.height, color, STATE_FALLING);
1222 block.vy = -this.planet.fallSpeed;
1223 return block;
1224};
1225
1226GameCore.prototype.integrateFalling = function (dt)
1227{
1228 var falling = [];
1229 for (var i = 0; i < this.blocks.length; i++)
1230 {
1231 if (this.blocks[i].state === STATE_FALLING)
1232 { falling.push(this.blocks[i]); }
1233 }
1234 // Lowest first, so a stack of falling blocks rests on itself.
1235 falling.sort(function (a, b) { return a.y - b.y; });
1236 for (var i = 0; i < falling.length; i++)
1237 {
1238 var block = falling[i];
1239 if (block.state !== STATE_FALLING)
1240 { continue; }
1241 this.accelerateFall(block, dt);
1242 var nextY = block.y + block.vy * dt;
1243 var manual = this.manualInColumnHit(block, block.y, nextY);
1244 if (manual)
1245 {
1246 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
1247 continue;
1248 }
1249 var flyer = this.highestFlyingBelow(block);
1250 if (flyer && nextY <= flyer.y + 1 + 1e-9)
1251 {
1252 if (this.attachToFlyingCluster(block, flyer))
1253 { continue; }
1254 }
1255 var top = this.stackTop(block.col);
1256 var below = this.highestFallingBelow(block);
1257 if (below && below.y + 1 > top)
1258 { top = below.y + 1; }
1259 if (nextY <= top)
1260 {
1261 block.y = top;
1262 this.landFallingBlock(block);
1263 }
1264 else
1265 { block.y = nextY; }
1266 }
1267};
1268
1269GameCore.prototype.clusterMembers = function (clusterId)
1270{
1271 var out = [];
1272 for (var i = 0; i < this.blocks.length; i++)
1273 {
1274 if (this.blocks[i].clusterId === clusterId)
1275 { out.push(this.blocks[i]); }
1276 }
1277 return out;
1278};
1279
1280
1281/**
1282 * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a
1283 * jump of height H peaks at exactly H after riseTime. Returns dy.
1284 * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the
1285 * upward deceleration. After the apex, vy eases from 0 to -fallSpeed
1286 * at planet.fallAccel, then stays at terminal fallSpeed.
1287 */
1288GameCore.prototype.advanceJump = function (body, dt)
1289{
1290 var dy = 0;
1291 var left = dt;
1292 if (body.phase === 'up')
1293 {
1294 var decel = body.decel;
1295 var vy = body.vy;
1296 var tApex = decel > 1e-12 ? vy / decel : Infinity;
1297 if (tApex <= left + 1e-15)
1298 {
1299 dy += vy * tApex - 0.5 * decel * tApex * tApex;
1300 body.vy = 0;
1301 body.phase = 'down';
1302 left -= tApex;
1303 }
1304 else
1305 {
1306 var vyNew = vy - decel * left;
1307 dy += (vy + vyNew) * 0.5 * left;
1308 body.vy = vyNew;
1309 left = 0;
1310 }
1311 }
1312 if (body.phase === 'up' && body.vy <= 1e-10)
1313 {
1314 body.vy = 0;
1315 body.phase = 'down';
1316 }
1317 if (body.phase === 'down' && left > 0)
1318 {
1319 var target = -this.planet.fallSpeed;
1320 var accel = this.planet.fallAccel;
1321 if (accel < 1e-12)
1322 {
1323 body.vy = target;
1324 dy += body.vy * left;
1325 }
1326 else if (body.vy > target + 1e-12)
1327 {
1328 var tReach = (body.vy - target) / accel;
1329 if (tReach <= left + 1e-15)
1330 {
1331 dy += (body.vy + target) * 0.5 * tReach;
1332 body.vy = target;
1333 left -= tReach;
1334 dy += body.vy * left;
1335 }
1336 else
1337 {
1338 var vyNew = body.vy - accel * left;
1339 dy += (body.vy + vyNew) * 0.5 * left;
1340 body.vy = vyNew;
1341 }
1342 }
1343 else
1344 {
1345 body.vy = target;
1346 dy += body.vy * left;
1347 }
1348 }
1349 return dy;
1350};
1351
1352GameCore.prototype.integrateClusters = function (dt)
1353{
1354 var ids = Object.keys(this.clusters);
1355 for (var n = 0; n < ids.length; n++)
1356 {
1357 var cluster = this.clusters[ids[n]];
1358 if (!cluster)
1359 { continue; }
1360 var members = this.clusterMembers(cluster.id);
1361 if (!members.length)
1362 {
1363 delete this.clusters[cluster.id];
1364 continue;
1365 }
1366 if (cluster.phase === 'landed' || cluster.phase === 'hold')
1367 { continue; }
1368
1369 var dy = this.advanceJump(cluster, dt);
1370 for (var i = 0; i < members.length; i++)
1371 {
1372 members[i].y += dy;
1373 members[i].vy = cluster.vy;
1374 }
1375
1376 this.catchFallingOntoCluster(cluster, members);
1377 this.checkChainRelaunch(cluster);
1378
1379 if (cluster.phase === 'down' && this.clusters[cluster.id])
1380 { this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }
1381 }
1382};
1383
1384
1385/**
1386 * If two or more flying clusters overlap in the same column, merge them
1387 * into one cluster. Velocity (and deceleration and jumpHeight) is the
1388 * mass-weighted average by block count. Phase is 'up' when the merged
1389 * vy is positive, otherwise 'down'. Overlapping members in a column
1390 * are packed so the higher one sits flush on the lower.
1391 */
1392GameCore.prototype.mergeFlyingClusters = function ()
1393{
1394 var flying = [];
1395 var ids = Object.keys(this.clusters);
1396 for (var n = 0; n < ids.length; n++)
1397 {
1398 var cluster = this.clusters[ids[n]];
1399 if (!cluster)
1400 { continue; }
1401 if (cluster.phase === 'landed' || cluster.phase === 'hold')
1402 { continue; }
1403 flying.push(cluster);
1404 }
1405 if (flying.length < 2)
1406 { return; }
1407
1408 var uf = new UnionFind();
1409 for (var i = 0; i < flying.length; i++)
1410 { uf.add(flying[i].id); }
1411 for (var i = 0; i < flying.length; i++)
1412 {
1413 for (var j = i + 1; j < flying.length; j++)
1414 {
1415 if (this.flyingClustersOverlap(flying[i], flying[j]))
1416 { uf.union(flying[i].id, flying[j].id); }
1417 }
1418 }
1419
1420 var groups = Object.create(null);
1421 for (var i = 0; i < flying.length; i++)
1422 {
1423 var root = uf.find(flying[i].id);
1424 if (!groups[root])
1425 { groups[root] = []; }
1426 groups[root].push(flying[i]);
1427 }
1428 for (var root in groups)
1429 {
1430 if (groups[root].length >= 2)
1431 { this.mergeClusterGroup(groups[root]); }
1432 }
1433};
1434
1435GameCore.prototype.flyingClustersOverlap = function (a, b)
1436{
1437 var ma = this.clusterMembers(a.id);
1438 var mb = this.clusterMembers(b.id);
1439 for (var i = 0; i < ma.length; i++)
1440 {
1441 for (var j = 0; j < mb.length; j++)
1442 {
1443 if (ma[i].col !== mb[j].col)
1444 { continue; }
1445 if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)
1446 { return true; }
1447 }
1448 }
1449 return false;
1450};
1451
1452GameCore.prototype.mergeClusterGroup = function (clusters)
1453{
1454 clusters.sort(function (a, b) { return a.id - b.id; });
1455 var keep = clusters[0];
1456 var n = 0;
1457 var vySum = 0;
1458 var decelSum = 0;
1459 var hSum = 0;
1460 for (var c = 0; c < clusters.length; c++)
1461 {
1462 var mem = this.clusterMembers(clusters[c].id);
1463 var m = mem.length;
1464 n += m;
1465 vySum += clusters[c].vy * m;
1466 decelSum += (clusters[c].decel || 0) * m;
1467 hSum += (clusters[c].jumpHeight || 0) * m;
1468 }
1469 if (n === 0)
1470 { return; }
1471 keep.vy = vySum / n;
1472 keep.decel = decelSum / n;
1473 keep.jumpHeight = hSum / n;
1474 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
1475 for (var c = 0; c < clusters.length; c++)
1476 {
1477 var mem = this.clusterMembers(clusters[c].id);
1478 for (var i = 0; i < mem.length; i++)
1479 {
1480 mem[i].clusterId = keep.id;
1481 mem[i].vy = keep.vy;
1482 mem[i].state = STATE_FLYING;
1483 }
1484 if (clusters[c] !== keep)
1485 { delete this.clusters[clusters[c].id]; }
1486 }
1487 this.packClusterOverlaps(keep);
1488 this.checkChainRelaunch(keep);
1489 if (keep.phase === 'down' && this.clusters[keep.id])
1490 { this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
1491};
1492
1493GameCore.prototype.packClusterOverlaps = function (cluster)
1494{
1495 var members = this.clusterMembers(cluster.id);
1496 var byCol = Object.create(null);
1497 for (var i = 0; i < members.length; i++)
1498 {
1499 var col = members[i].col;
1500 if (!byCol[col])
1501 { byCol[col] = []; }
1502 byCol[col].push(members[i]);
1503 }
1504 var cols = Object.keys(byCol);
1505 for (var c = 0; c < cols.length; c++)
1506 {
1507 var list = byCol[cols[c]];
1508 list.sort(function (a, b) { return a.y - b.y; });
1509 for (var i = 1; i < list.length; i++)
1510 {
1511 var minY = list[i - 1].y + 1;
1512 if (list[i].y < minY - 1e-12)
1513 { list[i].y = minY; }
1514 }
1515 }
1516};
1517
1518GameCore.prototype.tryLandCluster = function (cluster, members)
1519{
1520 if (!members.length)
1521 { return; }
1522 var shift = 0;
1523 var hit = false;
1524 for (var i = 0; i < members.length; i++)
1525 {
1526 var block = members[i];
1527 var top = this.stackTop(block.col, function (other)
1528 {
1529 return other.clusterId === cluster.id;
1530 });
1531 if (block.y <= top + 1e-9)
1532 {
1533 hit = true;
1534 var need = top - block.y;
1535 if (need > shift)
1536 { shift = need; }
1537 }
1538 }
1539 if (!hit)
1540 { return; }
1541 // Lift the whole rigid body so the deepest contact sits flush.
1542 for (var i = 0; i < members.length; i++)
1543 { members[i].y += shift; }
1544 this.landCluster(cluster, members);
1545};
1546
1547/**
1548 * Land as a rigid group: relative positions are kept, so part of the
1549 * cluster may hang above a gap. Grey members start the 3s settle timer;
1550 * coloured cargo stays put with them until every grey has recolored.
1551 * Members that actually rest on the floor or on another block bounce.
1552 */
1553GameCore.prototype.landCluster = function (cluster, members)
1554{
1555 for (var i = 0; i < members.length; i++)
1556 {
1557 var block = members[i];
1558 block.vy = 0;
1559 block.flame = false;
1560 block.clusterId = cluster.id;
1561 if (block.color === COLOR_GRAY)
1562 {
1563 block.state = STATE_SETTLING;
1564 block.settleTime = 0;
1565 }
1566 else
1567 {
1568 // Cargo stays in the rigid group (not matchable) until release.
1569 block.state = STATE_SETTLING;
1570 block.settleTime = 0;
1571 }
1572 if (this.hasSupport(block))
1573 { this.startBounce(block); }
1574 }
1575 cluster.phase = 'landed';
1576 cluster.vy = 0;
1577};
1578
1579/**
1580 * After every grey in a landed cluster has recolored, let the group go.
1581 * Unsupported blocks fall individually from rest; supported ones stay.
1582 */
1583GameCore.prototype.releaseLandedCluster = function (cluster)
1584{
1585 var members = this.clusterMembers(cluster.id);
1586 var releasing = Object.create(null);
1587 for (var i = 0; i < members.length; i++)
1588 { releasing[members[i].id] = true; }
1589
1590 for (var i = 0; i < members.length; i++)
1591 {
1592 var block = members[i];
1593 if (block.color === COLOR_GRAY)
1594 {
1595 block.color = this.randomColor();
1596 block.settleTime = 0;
1597 }
1598 this.leaveCluster(block);
1599 // Always drop leftover launch / manual velocity. A stale upward
1600 // vy here is what sends blocks off the top "very fast" after
1601 // a grey group recolors.
1602 this.clearFlightState(block);
1603 // Support from outside the group (floor or a foreign block). Fellow
1604 // members that will also fall do not count, so a hanging stack
1605 // drops together without the top one staying put.
1606 var supported = this.hasSupportOutside(block, releasing);
1607 block.state = supported ? STATE_STILL : STATE_FALLING;
1608 }
1609 delete this.clusters[cluster.id];
1610};
1611
1612GameCore.prototype.hasSupportOutside = function (block, ignoreIds)
1613{
1614 if (block.y <= 1e-9)
1615 { return true; }
1616 for (var i = 0; i < this.blocks.length; i++)
1617 {
1618 var other = this.blocks[i];
1619 if (other === block || other.col !== block.col)
1620 { continue; }
1621 if (ignoreIds && ignoreIds[other.id])
1622 { continue; }
1623 if (!this.isGrounded(other))
1624 { continue; }
1625 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
1626 { return true; }
1627 }
1628 return false;
1629};
1630
1631GameCore.prototype.integrateManual = function (dt)
1632{
1633 for (var i = 0; i < this.blocks.length; i++)
1634 {
1635 var block = this.blocks[i];
1636 if (block.state !== STATE_MANUAL)
1637 { continue; }
1638
1639 if (block.manualPhase === 'up')
1640 {
1641 var oldY = block.y;
1642 var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
1643 var dy = this.advanceJump(proxy, dt);
1644 var nextY = oldY + dy;
1645 this.checkManualPush(block, oldY, Math.min(nextY, block.manualTarget));
1646 block.vy = proxy.vy;
1647 block.manualPhase = proxy.phase;
1648 block.y = Math.min(nextY, block.manualTarget);
1649 if (this.tryMergeManualWithFalling(block, oldY, block.y))
1650 { continue; }
1651 if (block.y >= block.manualTarget - 1e-12)
1652 {
1653 block.y = block.manualTarget;
1654 block.vy = 0;
1655 block.manualPhase = 'down';
1656 }
1657 if (block.y > this.height - 1)
1658 {
1659 block.y = this.height - 1;
1660 block.vy = 0;
1661 block.manualPhase = 'down';
1662 }
1663 }
1664
1665 if (block.manualPhase === 'down')
1666 {
1667 var proxy = { phase: 'down', vy: block.vy, decel: 0 };
1668 var dy = this.advanceJump(proxy, dt);
1669 block.vy = proxy.vy;
1670 var nextY = block.y + dy;
1671 var top = this.stackTop(block.col);
1672 if (nextY <= top)
1673 {
1674 block.y = top;
1675 block.state = STATE_STILL;
1676 block.vy = 0;
1677 block.manualPhase = null;
1678 block.flame = false;
1679 this.startBounce(block);
1680 }
1681 else
1682 {
1683 block.y = Math.min(nextY, this.height - 1);
1684 if (this.tryMergeManualWithFalling(block, block.y - dy, block.y))
1685 { continue; }
1686 }
1687 }
1688 }
1689};
1690
1691/**
1692 * If the manual throw (or its path this step) hits falling blocks, merge
1693 * them into a flying cluster with mass-weighted velocity, the same rule
1694 * as two flying clusters colliding (t1108). Returns true if merged.
1695 */
1696GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
1697{
1698 if (!manual || manual.state !== STATE_MANUAL)
1699 { return false; }
1700 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
1701 if (!hits.length)
1702 { return false; }
1703 this.mergeManualWithFalling(manual, hits);
1704 return true;
1705};
1706
1707GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
1708{
1709 var lo = Math.min(oldY, newY);
1710 var hi = Math.max(oldY, newY) + 1;
1711 for (var i = 0; i < this.blocks.length; i++)
1712 {
1713 var other = this.blocks[i];
1714 if (other === falling || other.col !== falling.col)
1715 { continue; }
1716 if (other.state !== STATE_MANUAL)
1717 { continue; }
1718 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1719 { return other; }
1720 }
1721 return null;
1722};
1723
1724GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
1725{
1726 var lo = Math.min(oldY, newY);
1727 var hi = Math.max(oldY, newY) + 1;
1728 var hits = [];
1729 for (var i = 0; i < this.blocks.length; i++)
1730 {
1731 var other = this.blocks[i];
1732 if (other === manual || other.col !== manual.col)
1733 { continue; }
1734 if (other.state !== STATE_FALLING)
1735 { continue; }
1736 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1737 { hits.push(other); }
1738 }
1739 if (!hits.length)
1740 { return hits; }
1741 return this.contiguousFallingInColumn(manual.col, manual, hits);
1742};
1743
1744/**
1745 * Every falling block in `col` that overlaps `anchor` or a hit already
1746 * in `seed`, plus a contiguous falling stack sitting on them.
1747 */
1748GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
1749{
1750 var falling = [];
1751 for (var i = 0; i < this.blocks.length; i++)
1752 {
1753 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
1754 { falling.push(this.blocks[i]); }
1755 }
1756 falling.sort(function (a, b) { return a.y - b.y; });
1757 var include = Object.create(null);
1758 var queue = [];
1759 function enqueue (b)
1760 {
1761 if (!b || include[b.id])
1762 { return; }
1763 include[b.id] = true;
1764 queue.push(b);
1765 }
1766 if (seed)
1767 {
1768 for (var s = 0; s < seed.length; s++)
1769 { enqueue(seed[s]); }
1770 }
1771 // Also include falling that already overlap the anchor.
1772 if (anchor)
1773 {
1774 for (var i = 0; i < falling.length; i++)
1775 {
1776 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
1777 { enqueue(falling[i]); }
1778 }
1779 }
1780 for (var q = 0; q < queue.length; q++)
1781 {
1782 var a = queue[q];
1783 for (var i = 0; i < falling.length; i++)
1784 {
1785 var b = falling[i];
1786 if (include[b.id])
1787 { continue; }
1788 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
1789 { enqueue(b); }
1790 }
1791 }
1792 var out = [];
1793 for (var i = 0; i < falling.length; i++)
1794 {
1795 if (include[falling[i].id])
1796 { out.push(falling[i]); }
1797 }
1798 return out;
1799};
1800
1801/**
1802 * Merge a thrown (manual) block with falling blocks into one flying
1803 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
1804 * averages by block count, identical to mergeClusterGroup. The thrown
1805 * block stops being manual and the group follows normal cluster physics.
1806 * fromManual marks the cluster so later falling cargo also averages in.
1807 */
1808GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
1809{
1810 if (!manual || manual.state !== STATE_MANUAL)
1811 { return null; }
1812 var blocks = [manual];
1813 for (var i = 0; i < fallingList.length; i++)
1814 {
1815 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
1816 { blocks.push(fallingList[i]); }
1817 }
1818 if (blocks.length < 2)
1819 { return null; }
1820 var n = blocks.length;
1821 var vySum = 0;
1822 var decelSum = 0;
1823 var hSum = 0;
1824 for (var i = 0; i < n; i++)
1825 {
1826 var b = blocks[i];
1827 vySum += b.vy;
1828 if (b === manual)
1829 {
1830 decelSum += manual.manualDecel || 0;
1831 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
1832 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
1833 }
1834 }
1835 var cluster = {
1836 id: this.nextClusterId++,
1837 jumpHeight: hSum / n,
1838 vy: vySum / n,
1839 decel: decelSum / n,
1840 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
1841 fromManual: true
1842 };
1843 this.clusters[cluster.id] = cluster;
1844 for (var i = 0; i < n; i++)
1845 {
1846 var b = blocks[i];
1847 b.clusterId = cluster.id;
1848 b.state = STATE_FLYING;
1849 b.vy = cluster.vy;
1850 b.flame = b.color === COLOR_GRAY;
1851 b.manualPhase = null;
1852 b.manualTarget = null;
1853 b.manualDecel = 0;
1854 b.manualJumpHeight = 0;
1855 b.pushedClusters = null;
1856 b.settleTime = 0;
1857 }
1858 if (this.drag && this.drag.blockId === manual.id)
1859 { this.drag = null; }
1860 this.packClusterOverlaps(cluster);
1861 this.checkChainRelaunch(cluster);
1862 return cluster;
1863};
1864
1865/** Safety net: any remaining manual/falling overlaps after the substep. */
1866GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
1867{
1868 var manuals = [];
1869 for (var i = 0; i < this.blocks.length; i++)
1870 {
1871 if (this.blocks[i].state === STATE_MANUAL)
1872 { manuals.push(this.blocks[i]); }
1873 }
1874 for (var m = 0; m < manuals.length; m++)
1875 {
1876 var manual = manuals[m];
1877 if (manual.state !== STATE_MANUAL)
1878 { continue; }
1879 var hits = this.contiguousFallingInColumn(manual.col, manual);
1880 if (hits.length)
1881 { this.mergeManualWithFalling(manual, hits); }
1882 }
1883};
1884
1885GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1886{
1887 if (!manual.pushedClusters)
1888 { manual.pushedClusters = Object.create(null); }
1889
1890 var manualTopOld = oldY + 1;
1891 var manualTopNew = nextY + 1;
1892 var low = Math.min(oldY, nextY);
1893 var high = Math.max(oldY, nextY) + 1;
1894
1895 for (var i = 0; i < this.blocks.length; i++)
1896 {
1897 var other = this.blocks[i];
1898 if (other === manual)
1899 { continue; }
1900 if (other.col !== manual.col)
1901 { continue; }
1902 if (other.state !== STATE_FLYING || other.clusterId == null)
1903 { continue; }
1904 if (manual.pushedClusters[other.clusterId])
1905 { continue; }
1906 var otherBot = other.y;
1907 var otherTop = other.y + 1;
1908 var overlapping = otherBot < high + 1e-9 && otherTop > low - 1e-9;
1909 var crossing = manualTopOld <= otherBot + 1e-9 && manualTopNew >= otherBot - 1e-9;
1910 if (overlapping || crossing)
1911 {
1912 if (this.pushClusterColumn(other.clusterId, manual.col))
1913 {
1914 manual.pushedClusters[other.clusterId] = true;
1915 return;
1916 }
1917 }
1918 }
1919};
1920
1921
1922/**
1923 * Push every flying block of the cluster that sits in `col` one tile up.
1924 * Other columns stay put (they remain linked). Then look for a new
1925 * same-color line of 3+ in the flying cluster; if there is one, those
1926 * blocks turn gray, join the link, and the whole cluster re-launches
1927 * with the same jump height from its current position.
1928 */
1929GameCore.prototype.pushClusterColumn = function (clusterId, col)
1930{
1931 var cluster = this.clusters[clusterId];
1932 if (!cluster)
1933 { return false; }
1934 var members = this.clusterMembers(clusterId);
1935 for (var i = 0; i < members.length; i++)
1936 {
1937 if (members[i].col === col)
1938 { members[i].y += 1; }
1939 }
1940 this.cullOffTop();
1941 if (!this.clusters[clusterId])
1942 { return true; }
1943 this.checkChainRelaunch(cluster);
1944 return true;
1945};
1946
1947/**
1948 * After a cargo attach or a cluster merge (or any other mid-air state
1949 * change), turn spontaneous lines of 3+ into rockets and give the whole
1950 * already-flying cluster an extra launch from its current position —
1951 * the same re-launch as a player push that completes a row.
1952 */
1953GameCore.prototype.resolveFlyingMatches = function ()
1954{
1955 var ids = Object.keys(this.clusters);
1956 for (var n = 0; n < ids.length; n++)
1957 {
1958 var cluster = this.clusters[ids[n]];
1959 if (!cluster || cluster.phase === 'landed')
1960 { continue; }
1961 this.checkChainRelaunch(cluster);
1962 }
1963};
1964
1965GameCore.prototype.checkChainRelaunch = function (cluster)
1966{
1967 if (!this.clusters[cluster.id])
1968 { return; }
1969 var lines = this.findFlyingMatchLines(cluster.id);
1970 if (!lines.length)
1971 { return; }
1972 var newly = [];
1973 var seen = Object.create(null);
1974 for (var i = 0; i < lines.length; i++)
1975 {
1976 for (var j = 0; j < lines[i].blocks.length; j++)
1977 {
1978 var block = lines[i].blocks[j];
1979 if (seen[block.id])
1980 { continue; }
1981 seen[block.id] = true;
1982 newly.push(block);
1983 }
1984 }
1985 for (var i = 0; i < newly.length; i++)
1986 {
1987 var block = newly[i];
1988 block.color = COLOR_GRAY;
1989 block.flame = true;
1990 block.clusterId = cluster.id;
1991 block.state = STATE_FLYING;
1992 }
1993 this.relaunchCluster(cluster, cluster.jumpHeight);
1994};
1995
1996GameCore.prototype.relaunchCluster = function (cluster, height)
1997{
1998 cluster.jumpHeight = height;
1999 cluster.vy = PlanetMod.launchVelocity(this.planet, height);
2000 cluster.decel = PlanetMod.launchDeceleration(this.planet, height);
2001 cluster.phase = 'up';
2002 var members = this.clusterMembers(cluster.id);
2003 for (var i = 0; i < members.length; i++)
2004 {
2005 members[i].vy = cluster.vy;
2006 members[i].state = STATE_FLYING;
2007 if (members[i].color === COLOR_GRAY)
2008 { members[i].flame = true; }
2009 }
2010};
2011
2012GameCore.prototype.startManualLaunch = function (block)
2013{
2014 var target = this.height - 1;
2015 var height = Math.max(0.05, target - block.y);
2016 this.leaveCluster(block);
2017 block.state = STATE_MANUAL;
2018 block.pushedClusters = Object.create(null);
2019 block.manualTarget = target;
2020 block.manualPhase = 'up';
2021 block.manualJumpHeight = height;
2022 block.vy = PlanetMod.launchVelocity(this.planet, height);
2023 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
2024 block.flame = false;
2025 if (this.drag && this.drag.blockId === block.id)
2026 { this.drag = null; }
2027};
2028
2029GameCore.prototype.cullOffTop = function ()
2030{
2031 var gone = [];
2032 for (var i = 0; i < this.blocks.length; i++)
2033 {
2034 var block = this.blocks[i];
2035 if (block.state === STATE_MANUAL)
2036 {
2037 if (block.y > this.height - 1)
2038 { block.y = this.height - 1; }
2039 continue;
2040 }
2041 if (block.y >= this.height - 1e-9)
2042 { gone.push(block); }
2043 }
2044 for (var i = 0; i < gone.length; i++)
2045 {
2046 var block = gone[i];
2047 this.outgoingShots.push({
2048 id: block.id,
2049 color: block.color,
2050 col: block.col,
2051 y: block.y
2052 });
2053 this.score += 1;
2054 this.removeBlock(block);
2055 }
2056};
2057
2058GameCore.prototype.consumeOutgoingShots = function ()
2059{
2060 var shots = this.outgoingShots;
2061 this.outgoingShots = [];
2062 return shots;
2063};
2064
2065/**
2066 * A compact field picture for the multiplayer snapshot (miniatures).
2067 * Includes every block's col, y, color, state and flame.
2068 */
2069GameCore.prototype.fieldSnapshot = function ()
2070{
2071 var blocks = [];
2072 for (var i = 0; i < this.blocks.length; i++)
2073 {
2074 var b = this.blocks[i];
2075 blocks.push({
2076 id: b.id,
2077 col: b.col,
2078 y: Math.round(b.y * 1000) / 1000,
2079 color: b.color,
2080 state: b.state,
2081 flame: !!b.flame
2082 });
2083 }
2084 return {
2085 score: this.score,
2086 state: this.state,
2087 width: this.width,
2088 height: this.height,
2089 locked: this.lockedColumnCount(),
2090 blocks: blocks
2091 };
2092};
2093
2094/**
2095 * Incoming garbage from another player: a dark-grey block that falls
2096 * normally from the top of an open column. After landing it uses the
2097 * usual 3s settle and then a random colour (landFallingBlock).
2098 * `col` is optional; a random eligible column is used otherwise.
2099 * Returns the new block, or null if every column is locked or full.
2100 */
2101GameCore.prototype.ingestGarbage = function (col)
2102{
2103 if (this.state !== 'playing')
2104 { return null; }
2105 var chosen = null;
2106 if (col != null && col >= 0 && col < this.width
2107 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
2108 { chosen = col | 0; }
2109 else
2110 {
2111 var eligible = [];
2112 for (var c = 0; c < this.width; c++)
2113 {
2114 if (this.isColumnLocked(c))
2115 { continue; }
2116 if (this.groundedCount(c) >= this.height)
2117 { continue; }
2118 eligible.push(c);
2119 }
2120 if (!eligible.length)
2121 { return null; }
2122 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2123 }
2124 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2125 block.vy = -this.planet.fallSpeed;
2126 block.flame = false;
2127 return block;
2128};
2129
2130GameCore.prototype.advanceSettle = function (dt)
2131{
2132 for (var i = 0; i < this.blocks.length; i++)
2133 {
2134 var block = this.blocks[i];
2135 if (block.state !== STATE_SETTLING)
2136 { continue; }
2137 var inLanded = block.clusterId != null
2138 && this.clusters[block.clusterId]
2139 && this.clusters[block.clusterId].phase === 'landed';
2140 if (block.color === COLOR_GRAY)
2141 {
2142 block.settleTime += dt;
2143 if (block.settleTime >= this.settleTime)
2144 {
2145 block.color = this.randomColor();
2146 block.settleTime = 0;
2147 block.flame = false;
2148 if (inLanded)
2149 {
2150 // Stay in the rigid group; releaseLandedCluster runs below.
2151 block.state = STATE_SETTLING;
2152 }
2153 else
2154 {
2155 this.leaveCluster(block);
2156 this.clearFlightState(block);
2157 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2158 }
2159 }
2160 }
2161 else if (!inLanded)
2162 {
2163 // Coloured settling that is not in a landed cluster (shouldn't
2164 // normally happen): just become still or fall, from rest.
2165 this.leaveCluster(block);
2166 this.clearFlightState(block);
2167 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2168 }
2169 }
2170
2171 var ids = Object.keys(this.clusters);
2172 for (var n = 0; n < ids.length; n++)
2173 {
2174 var cluster = this.clusters[ids[n]];
2175 if (!cluster || cluster.phase !== 'landed')
2176 { continue; }
2177 var members = this.clusterMembers(cluster.id);
2178 var greySettling = false;
2179 for (var i = 0; i < members.length; i++)
2180 {
2181 if (members[i].color === COLOR_GRAY && members[i].state === STATE_SETTLING)
2182 { greySettling = true; }
2183 }
2184 if (!greySettling)
2185 { this.releaseLandedCluster(cluster); }
2186 }
2187};
2188
2189GameCore.prototype.findMatchLines = function ()
2190{
2191 var candidates = [];
2192 for (var i = 0; i < this.blocks.length; i++)
2193 {
2194 var block = this.blocks[i];
2195 // Coloured cargo in a just-landed cluster (SETTLING) can match
2196 // with already-resting blocks immediately (t1110). Greys have no
2197 // colour and wait until they recolor; after release they are STILL.
2198 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
2199 && block.color >= 0)
2200 { candidates.push(block); }
2201 }
2202 return this.collectLines(candidates, true);
2203};
2204
2205GameCore.prototype.findFlyingMatchLines = function (clusterId)
2206{
2207 var candidates = [];
2208 for (var i = 0; i < this.blocks.length; i++)
2209 {
2210 var block = this.blocks[i];
2211 if (block.clusterId === clusterId && block.color >= 0
2212 && (block.state === STATE_FLYING))
2213 { candidates.push(block); }
2214 }
2215 return this.collectLines(candidates, false);
2216};
2217
2218GameCore.prototype.collectLines = function (candidates, snapInteger)
2219{
2220 var lines = [];
2221 if (!candidates.length)
2222 { return lines; }
2223
2224 var byRow = Object.create(null);
2225 for (var i = 0; i < candidates.length; i++)
2226 {
2227 var block = candidates[i];
2228 var row = Math.round(block.y);
2229 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
2230 { continue; }
2231 if (!byRow[row])
2232 { byRow[row] = []; }
2233 byRow[row].push(block);
2234 }
2235 var rows = Object.keys(byRow);
2236 for (var r = 0; r < rows.length; r++)
2237 {
2238 var list = byRow[rows[r]];
2239 list.sort(function (a, b) { return a.col - b.col; });
2240 this.pushRuns(lines, list, false, function (a, b)
2241 {
2242 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
2243 });
2244 }
2245
2246 var byCol = Object.create(null);
2247 for (var i = 0; i < candidates.length; i++)
2248 {
2249 var block = candidates[i];
2250 if (!byCol[block.col])
2251 { byCol[block.col] = []; }
2252 byCol[block.col].push(block);
2253 }
2254 var cols = Object.keys(byCol);
2255 for (var c = 0; c < cols.length; c++)
2256 {
2257 var list = byCol[cols[c]];
2258 list.sort(function (a, b) { return a.y - b.y; });
2259 this.pushRuns(lines, list, true, function (a, b)
2260 {
2261 return a.color === b.color && a.color >= 0
2262 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
2263 });
2264 }
2265 return lines;
2266};
2267
2268GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
2269{
2270 var start = 0;
2271 for (var i = 1; i <= list.length; i++)
2272 {
2273 var same = i < list.length && adjacent(list[i - 1], list[i]);
2274 if (!same)
2275 {
2276 var length = i - start;
2277 if (length >= 3)
2278 {
2279 lines.push({
2280 blocks: list.slice(start, i),
2281 length: length,
2282 vertical: vertical
2283 });
2284 }
2285 start = i;
2286 }
2287 }
2288};
2289
2290GameCore.prototype.resolveMatches = function ()
2291{
2292 if (this.state !== 'playing' || this.drag)
2293 { return []; }
2294 var lines = this.findMatchLines();
2295 if (!lines.length)
2296 { return []; }
2297
2298 var uf = new UnionFind();
2299 var blockById = Object.create(null);
2300 for (var i = 0; i < lines.length; i++)
2301 {
2302 var line = lines[i];
2303 for (var j = 0; j < line.blocks.length; j++)
2304 {
2305 uf.add(line.blocks[j].id);
2306 blockById[line.blocks[j].id] = line.blocks[j];
2307 if (j > 0)
2308 { uf.union(line.blocks[0].id, line.blocks[j].id); }
2309 }
2310 }
2311 var matched = [];
2312 var seen = Object.create(null);
2313 for (var id in blockById)
2314 {
2315 if (!seen[id])
2316 {
2317 seen[id] = true;
2318 matched.push(blockById[id]);
2319 }
2320 }
2321 for (var i = 0; i < matched.length; i++)
2322 {
2323 for (var j = i + 1; j < matched.length; j++)
2324 {
2325 if (matched[i].col === matched[j].col)
2326 { uf.union(matched[i].id, matched[j].id); }
2327 }
2328 }
2329
2330 var groups = Object.create(null);
2331 for (var i = 0; i < matched.length; i++)
2332 {
2333 var root = uf.find(matched[i].id);
2334 if (!groups[root])
2335 { groups[root] = []; }
2336 groups[root].push(matched[i]);
2337 }
2338
2339 var launched = [];
2340 for (var root in groups)
2341 {
2342 var group = groups[root];
2343 var height = 0;
2344 for (var i = 0; i < lines.length; i++)
2345 {
2346 var line = lines[i];
2347 var overlaps = false;
2348 for (var j = 0; j < line.blocks.length; j++)
2349 {
2350 for (var k = 0; k < group.length; k++)
2351 {
2352 if (line.blocks[j].id === group[k].id)
2353 { overlaps = true; }
2354 }
2355 }
2356 if (overlaps)
2357 {
2358 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
2359 if (h > height)
2360 { height = h; }
2361 }
2362 }
2363 this.launchCluster(group, height);
2364 launched.push({ blocks: group, jumpHeight: height });
2365 }
2366 return launched;
2367};
2368
2369/**
2370 * Gray the matched blocks, take everything sitting on top of them in
2371 * those columns, link them, and launch with jump height `height`.
2372 */
2373GameCore.prototype.launchCluster = function (matchedBlocks, height)
2374{
2375 var lowestInCol = Object.create(null);
2376 var matchedIds = Object.create(null);
2377 for (var i = 0; i < matchedBlocks.length; i++)
2378 {
2379 var block = matchedBlocks[i];
2380 matchedIds[block.id] = true;
2381 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
2382 { lowestInCol[block.col] = block.y; }
2383 }
2384
2385 var clusterId = this.nextClusterId++;
2386 var cluster = {
2387 id: clusterId,
2388 jumpHeight: height,
2389 vy: PlanetMod.launchVelocity(this.planet, height),
2390 decel: PlanetMod.launchDeceleration(this.planet, height),
2391 phase: 'up'
2392 };
2393 this.clusters[clusterId] = cluster;
2394
2395 var riders = [];
2396 var cols = Object.keys(lowestInCol);
2397 for (var c = 0; c < cols.length; c++)
2398 {
2399 var col = +cols[c];
2400 var lowest = lowestInCol[col];
2401 var list = this.blocksInColumn(col);
2402 for (var i = 0; i < list.length; i++)
2403 {
2404 var block = list[i];
2405 if (!this.isGrounded(block) && block.state !== STATE_STILL)
2406 {
2407 if (block.state !== STATE_SETTLING)
2408 { continue; }
2409 }
2410 if (block.y + ALIGN_EPS >= lowest)
2411 { riders.push(block); }
2412 }
2413 }
2414
2415 for (var i = 0; i < riders.length; i++)
2416 {
2417 var block = riders[i];
2418 var isMatch = !!matchedIds[block.id];
2419 if (isMatch || block.color === COLOR_GRAY)
2420 {
2421 block.color = COLOR_GRAY;
2422 block.flame = true;
2423 }
2424 else
2425 { block.flame = false; }
2426 block.state = STATE_FLYING;
2427 block.clusterId = clusterId;
2428 block.vy = cluster.vy;
2429 block.settleTime = 0;
2430 }
2431 return cluster;
2432};
2433
2434GameCore.prototype.checkLocks = function ()
2435{
2436 for (var col = 0; col < this.width; col++)
2437 {
2438 if (this.isColumnLocked(col))
2439 { continue; }
2440 if (this.groundedCount(col) < this.height)
2441 { continue; }
2442 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
2443 var filled = true;
2444 for (var row = 0; row < this.height; row++)
2445 {
2446 var block = this.blockAt(col, row);
2447 if (!block || !this.isGrounded(block))
2448 {
2449 filled = false;
2450 break;
2451 }
2452 }
2453 if (!filled)
2454 { continue; }
2455 var list = this.blocksInColumn(col);
2456 for (var i = 0; i < list.length; i++)
2457 {
2458 var block = list[i];
2459 if (!this.isGrounded(block))
2460 { continue; }
2461 block.state = STATE_LOCKED;
2462 block.color = COLOR_GRAY;
2463 block.flame = false;
2464 block.vy = 0;
2465 block.settleTime = 0;
2466 if (block.clusterId != null)
2467 { this.leaveCluster(block); }
2468 }
2469 }
2470};
2471
2472GameCore.prototype.checkGameOver = function ()
2473{
2474 if (this.state !== 'playing')
2475 { return; }
2476 for (var col = 0; col < this.width; col++)
2477 {
2478 if (!this.isColumnLocked(col))
2479 { return; }
2480 }
2481 this.state = 'gameover';
2482 this.gameOverTime = 0;
2483 this.drag = null;
2484};
2485
2486/* ---------- dragging -------------------------------------------------- */
2487
2488GameCore.prototype.beginDrag = function (col, y)
2489{
2490 if (this.state !== 'playing')
2491 { return false; }
2492 var block = this.snapDragBlock(col, y);
2493 if (!block)
2494 { return false; }
2495 var top = this.columnStackTopRow(block.col);
2496 var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
2497 this.drag = {
2498 blockId: block.id,
2499 pointerY: y,
2500 startY: y,
2501 accum: 0,
2502 launchIntent: false,
2503 startedAsTop: startedAsTop
2504 };
2505 return true;
2506};
2507
2508/**
2509 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
2510 * floor(col), floor(y); any press inside that cell — corners, padding,
2511 * gaps between sprites, a visually tweened or bouncing sprite — grabs
2512 * the block that occupies it. This uses simulation cells, not the drawn
2513 * sprite bounds. If no block sits in that cell (mid-animation, a block
2514 * whose y is off the integer), fall back to the nearest grabbable block
2515 * in the same column within SNAP_Y (about half a tile). A small
2516 * horizontal slop still consults a neighbouring column when the press
2517 * is near the edge and the primary cell is empty.
2518 */
2519GameCore.prototype.snapDragBlock = function (col, y)
2520{
2521 var raw = col;
2522 var c0 = Math.floor(raw + 1e-9);
2523 var row = Math.floor(y + 1e-9);
2524 var frac = raw - c0;
2525
2526 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
2527 {
2528 var exact = this.draggableInCell(c0, row);
2529 if (exact)
2530 { return exact; }
2531 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
2532 if (near)
2533 { return near; }
2534 }
2535
2536 // Primary cell empty: allow a small horizontal slop into a neighbour.
2537 var neighbours = [];
2538 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
2539 { neighbours.push(c0 - 1); }
2540 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
2541 { neighbours.push(c0 + 1); }
2542 var best = null;
2543 var bestDist = Infinity;
2544 for (var n = 0; n < neighbours.length; n++)
2545 {
2546 var cc = neighbours[n];
2547 if (!this.columnAllowsDrag(cc))
2548 { continue; }
2549 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
2550 if (!hit)
2551 { continue; }
2552 var dist = this.pointerDistToBlock(hit, raw, y);
2553 if (dist < bestDist)
2554 {
2555 bestDist = dist;
2556 best = hit;
2557 }
2558 }
2559 return best;
2560};
2561
2562/** The draggable block that occupies grid cell (col, row), if any. */
2563GameCore.prototype.draggableInCell = function (col, row)
2564{
2565 var best = null;
2566 var bestOverlap = 0;
2567 var list = this.blocksInColumn(col);
2568 for (var i = 0; i < list.length; i++)
2569 {
2570 var block = list[i];
2571 if (!this.isDraggableBlock(block))
2572 { continue; }
2573 var lo = Math.max(block.y, row);
2574 var hi = Math.min(block.y + 1, row + 1);
2575 var overlap = hi - lo;
2576 if (overlap > bestOverlap + 1e-12)
2577 {
2578 bestOverlap = overlap;
2579 best = block;
2580 }
2581 }
2582 if (best && bestOverlap > 1e-9)
2583 { return best; }
2584 return null;
2585};
2586
2587/** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
2588GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
2589{
2590 var best = null;
2591 var bestDist = Infinity;
2592 var list = this.blocksInColumn(col);
2593 for (var i = 0; i < list.length; i++)
2594 {
2595 var block = list[i];
2596 if (!this.isDraggableBlock(block))
2597 { continue; }
2598 var dist = this.pointerDistToBlock(block, col + 0.5, y);
2599 if (dist < bestDist)
2600 {
2601 bestDist = dist;
2602 best = block;
2603 }
2604 }
2605 if (!best || bestDist > maxDist)
2606 { return null; }
2607 return best;
2608};
2609
2610GameCore.prototype.pointerDistToBlock = function (block, col, y)
2611{
2612 var dx;
2613 if (col >= block.col && col < block.col + 1)
2614 { dx = 0; }
2615 else if (col < block.col)
2616 { dx = block.col - col; }
2617 else
2618 { dx = col - (block.col + 1); }
2619 var dy;
2620 if (y >= block.y && y < block.y + 1)
2621 { dy = 0; }
2622 else if (y < block.y)
2623 { dy = block.y - y; }
2624 else
2625 { dy = y - (block.y + 1); }
2626 return Math.sqrt(dx * dx + dy * dy);
2627};
2628
2629GameCore.prototype.moveDrag = function (y)
2630{
2631 if (!this.drag)
2632 { return; }
2633 var block = this.blockById(this.drag.blockId);
2634 if (!block || !this.isDraggableBlock(block))
2635 {
2636 this.drag = null;
2637 return;
2638 }
2639 if (!this.columnAllowsDrag(block.col))
2640 {
2641 this.drag = null;
2642 return;
2643 }
2644 this.drag.pointerY = y;
2645 // 1:1 tracking: the target row is the one under the pointer, clamped
2646 // to the still stack. Swap step by step with each neighbour, and stop
2647 // exactly there. When the pointer stops, nothing else moves.
2648 // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
2649 // used to jump a full cell on a short pull, and one large event
2650 // could walk the entire column (the "jumps all the way" bug).
2651 var top = this.columnStackTopRow(block.col);
2652 var bottom = this.columnStackBottomRow(block.col);
2653 var target = Math.floor(y + 1e-12);
2654 if (bottom < 0)
2655 { bottom = 0; }
2656 if (target < bottom)
2657 { target = bottom; }
2658 if (target > top)
2659 { target = top; }
2660 this.swapToward(block, target);
2661
2662 top = this.columnStackTopRow(block.col);
2663 var isTop = Math.abs(block.y - top) < ALIGN_EPS;
2664 if (this.drag.startedAsTop)
2665 {
2666 // Already the topmost block: pulling upward past its own position
2667 // (LAUNCH_PULL tiles above the press point) starts a manual jump.
2668 this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL);
2669 }
2670 else
2671 {
2672 // Started mid-stack: swap first, and only launch once the pointer
2673 // is pulled into the empty space above the (new) top.
2674 this.drag.launchIntent = isTop && (y > top + 1 + 0.25);
2675 }
2676};
2677
2678/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
2679GameCore.prototype.swapOne = function (block, dir)
2680{
2681 var neighbor = this.blockAt(block.col, block.y + dir);
2682 if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
2683 {
2684 this.swapBlocks(block, neighbor);
2685 return true;
2686 }
2687 return false;
2688};
2689
2690GameCore.prototype.endDrag = function ()
2691{
2692 if (!this.drag)
2693 { return; }
2694 var block = this.blockById(this.drag.blockId);
2695 var launch = this.drag.launchIntent;
2696 this.drag = null;
2697 if (launch && block && block.state === STATE_STILL)
2698 { this.startManualLaunch(block); }
2699 else
2700 { this.resolveMatches(); }
2701};
2702
2703GameCore.prototype.blockById = function (id)
2704{
2705 for (var i = 0; i < this.blocks.length; i++)
2706 {
2707 if (this.blocks[i].id === id)
2708 { return this.blocks[i]; }
2709 }
2710 return null;
2711};
2712
2713GameCore.prototype.columnStackTopRow = function (col)
2714{
2715 var top = -1;
2716 var list = this.blocksInColumn(col);
2717 for (var i = 0; i < list.length; i++)
2718 {
2719 if (this.isGrounded(list[i]) && list[i].y > top)
2720 { top = list[i].y; }
2721 }
2722 return top;
2723};
2724
2725GameCore.prototype.columnStackBottomRow = function (col)
2726{
2727 var bottom = Infinity;
2728 var list = this.blocksInColumn(col);
2729 for (var i = 0; i < list.length; i++)
2730 {
2731 if (this.isGrounded(list[i]) && list[i].y < bottom)
2732 { bottom = list[i].y; }
2733 }
2734 return bottom === Infinity ? 0 : bottom;
2735};
2736
2737GameCore.prototype.swapToward = function (block, targetY)
2738{
2739 var guard = 0;
2740 while (guard++ < this.height + 2)
2741 {
2742 var current = block.y;
2743 if (targetY > current + 0.5)
2744 {
2745 var above = this.blockAt(block.col, current + 1);
2746 if (above && this.isGrounded(above) && above !== block)
2747 { this.swapBlocks(block, above); }
2748 else
2749 { break; }
2750 }
2751 else if (targetY < current - 0.5)
2752 {
2753 var below = this.blockAt(block.col, current - 1);
2754 if (below && this.isGrounded(below) && below !== block)
2755 { this.swapBlocks(block, below); }
2756 else
2757 { break; }
2758 }
2759 else
2760 { break; }
2761 }
2762};
2763
2764GameCore.prototype.swapBlocks = function (a, b)
2765{
2766 var y = a.y;
2767 a.y = b.y;
2768 b.y = y;
2769 this.transferLandedMembership(a, b);
2770};
2771
2772/**
2773 * A landed cluster (grey rockets or linked cargo resting on the ground)
2774 * is a swappable part of the contiguous grounded stack. Flying, falling
2775 * and manual blocks are not. A locked column is not.
2776 */
2777GameCore.prototype.isDraggableBlock = function (block)
2778{
2779 if (!block)
2780 { return false; }
2781 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
2782 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
2783 { return false; }
2784 if (block.clusterId != null)
2785 {
2786 var cluster = this.clusters[block.clusterId];
2787 // Flying (rising / descending) clusters stay non-draggable.
2788 if (cluster && cluster.phase !== 'landed')
2789 { return false; }
2790 }
2791 return block.state === STATE_STILL || block.state === STATE_SETTLING;
2792};
2793
2794/**
2795 * The grounded contiguous stack in this column can be dragged, even if a
2796 * flying cluster or a falling spawn occupies the air above it. Only a
2797 * locked column is blocked as a whole.
2798 */
2799GameCore.prototype.columnAllowsDrag = function (col)
2800{
2801 return !this.isColumnLocked(col);
2802};
2803
2804GameCore.prototype.landedClusterId = function (block)
2805{
2806 if (!block || block.clusterId == null)
2807 { return null; }
2808 var cluster = this.clusters[block.clusterId];
2809 if (!cluster || cluster.phase !== 'landed')
2810 { return null; }
2811 return block.clusterId;
2812};
2813
2814/**
2815 * After a swap: leaving a landed cluster clears membership; joining one
2816 * makes the block part of that rigid group. Same-cluster swaps only
2817 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
2818 */
2819GameCore.prototype.transferLandedMembership = function (a, b)
2820{
2821 var ca = this.landedClusterId(a);
2822 var cb = this.landedClusterId(b);
2823 if (ca === cb)
2824 { return; }
2825 // Join first so leaveCluster does not delete a cluster that still
2826 // has the incoming member.
2827 this.applyLandedMembership(b, ca);
2828 this.applyLandedMembership(a, cb);
2829};
2830
2831GameCore.prototype.applyLandedMembership = function (block, clusterId)
2832{
2833 if (clusterId == null)
2834 {
2835 var wasGrey = block.color === COLOR_GRAY;
2836 var wasSettling = block.state === STATE_SETTLING;
2837 this.leaveCluster(block);
2838 if (wasGrey && wasSettling)
2839 {
2840 // Keep settling and recolor on its own, same remaining timer.
2841 block.state = STATE_SETTLING;
2842 }
2843 else if (wasSettling)
2844 {
2845 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2846 }
2847 return;
2848 }
2849 if (!this.clusters[clusterId])
2850 { return; }
2851 block.clusterId = clusterId;
2852 block.flame = false;
2853 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
2854 { block.state = STATE_SETTLING; }
2855};
2856
2857/**
2858 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
2859 * Returns the moved block, or null if the column does not allow a drag.
2860 */
2861GameCore.prototype.swapTo = function (col, fromRow, toRow)
2862{
2863 if (!this.columnAllowsDrag(col))
2864 { return null; }
2865 var block = this.blockAt(col, fromRow);
2866 if (!block)
2867 { return null; }
2868 this.swapToward(block, toRow);
2869 return block;
2870};
2871
2872/**
2873 * Test helper: a compact picture of grounded/falling/flying blocks.
2874 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
2875 * L locked, f falling, m manual, . empty. Flying colored blocks use
2876 * their color with a marker in `flying`.
2877 */
2878GameCore.prototype.snapshot = function ()
2879{
2880 var grid = [];
2881 for (var r = 0; r < this.height; r++)
2882 {
2883 var row = [];
2884 for (var c = 0; c < this.width; c++)
2885 { row.push('.'); }
2886 grid.push(row);
2887 }
2888 var airborne = [];
2889 for (var i = 0; i < this.blocks.length; i++)
2890 {
2891 var block = this.blocks[i];
2892 var ch;
2893 if (block.state === STATE_LOCKED)
2894 { ch = 'L'; }
2895 else if (block.color === COLOR_GRAY)
2896 { ch = 'g'; }
2897 else
2898 { ch = String(block.color); }
2899 if (this.isGrounded(block) || block.state === STATE_FALLING)
2900 {
2901 var row = Math.round(block.y);
2902 if (row >= 0 && row < this.height)
2903 { grid[row][block.col] = ch; }
2904 }
2905 else
2906 {
2907 airborne.push({
2908 id: block.id,
2909 col: block.col,
2910 y: block.y,
2911 color: block.color,
2912 state: block.state,
2913 clusterId: block.clusterId,
2914 flame: block.flame,
2915 vy: block.vy
2916 });
2917 }
2918 }
2919 var lines = [];
2920 for (var r = this.height - 1; r >= 0; r--)
2921 { lines.push(grid[r].join('')); }
2922 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
2923};
2924
2925var GameCoreAPI = {
2926 GameCore: GameCore,
2927 COLOR_GRAY: COLOR_GRAY,
2928 STATE_STILL: STATE_STILL,
2929 STATE_FALLING: STATE_FALLING,
2930 STATE_FLYING: STATE_FLYING,
2931 STATE_SETTLING: STATE_SETTLING,
2932 STATE_LOCKED: STATE_LOCKED,
2933 STATE_MANUAL: STATE_MANUAL
2934};
2935
2936if (typeof module !== 'undefined' && module.exports)
2937{ module.exports = GameCoreAPI; }
2938else if (typeof globalThis !== 'undefined')
2939{
2940 globalThis.GameCore = GameCore;
2941 globalThis.GameCoreAPI = GameCoreAPI;
2942}
2943
2944/*
2945 * End File:
2946 * /workspace/meteors/src/gameCore.js
2947 */
2948
2949/*
2950 * Start File:
2951 * /workspace/meteors/src/online.js
2952 */
2953'use strict';
2954
2955/**
2956 * Online play: talks to api.php (cookie session), polls lobby and game
2957 * state, and draws opponent miniatures plus flying-block tweens.
2958 * Real-time sync is not required; a 0.75 s poll is enough.
2959 */
2960
2961var Online = {
2962 POLL_MS: 750,
2963 DEFAULT_MISS_CHANCE: 0.30,
2964 FLIGHT_DURATION: 1.2,
2965 configured: false,
2966 local: false,
2967 csrf: '',
2968 me: null,
2969 lobby: null,
2970 incoming: [],
2971 shotResults: [],
2972 error: '',
2973 _timer: null,
2974 _pendingShots: [],
2975 _flights: [],
2976 _lastStatus: null,
2977 onChange: null,
2978 onGameStart: null,
2979 onIncoming: null,
2980 onFinished: null,
2981 onLobbyReturn: null
2982};
2983
2984Online._headers = function (json)
2985{
2986 var h = { 'Accept': 'application/json' };
2987 if (json)
2988 { h['Content-Type'] = 'application/json'; }
2989 if (this.csrf)
2990 { h['X-CSRF-Token'] = this.csrf; }
2991 return h;
2992};
2993
2994Online._apply = function (data)
2995{
2996 if (!data)
2997 { return; }
2998 if (typeof data.configured === 'boolean')
2999 { this.configured = data.configured; }
3000 if (typeof data.local === 'boolean')
3001 { this.local = data.local; }
3002 if (data.csrf)
3003 { this.csrf = data.csrf; }
3004 if (data.me !== undefined)
3005 { this.me = data.me; }
3006 if (data.lobby !== undefined)
3007 { this.lobby = data.lobby; }
3008 if (data.incoming)
3009 { this.incoming = data.incoming; }
3010 if (data.shot_results)
3011 { this.shotResults = data.shot_results; }
3012 if (data.miss_chance_default != null)
3013 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
3014 if (data.flight_duration != null)
3015 { this.FLIGHT_DURATION = data.flight_duration; }
3016 if (data.error)
3017 { this.error = data.error; }
3018 else if (data.ok)
3019 { this.error = ''; }
3020};
3021
3022Online.request = function (action, body)
3023{
3024 var self = this;
3025 var isGet = action === 'me' || action === '';
3026 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
3027 var opts = {
3028 method: isGet && !body ? 'GET' : 'POST',
3029 credentials: 'same-origin',
3030 headers: this._headers(!!body || !isGet)
3031 };
3032 if (opts.method === 'POST')
3033 {
3034 var payload = body ? Object.assign({ action: action }, body) : { action: action };
3035 opts.body = JSON.stringify(payload);
3036 }
3037 return fetch(url, opts).then(function (res)
3038 {
3039 return res.json().then(function (data)
3040 {
3041 data = data || {};
3042 if (!res.ok && !data.error)
3043 { data.error = 'De server gaf ' + res.status; data.ok = false; }
3044 self._apply(data);
3045 return data;
3046 }, function ()
3047 {
3048 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
3049 self.error = fail.error;
3050 return fail;
3051 });
3052 }).catch(function (err)
3053 {
3054 var fail = { ok: false, error: 'Geen verbinding met de server.' };
3055 self.error = fail.error;
3056 return fail;
3057 });
3058};
3059
3060Online.refresh = function ()
3061{
3062 return this.request('me');
3063};
3064
3065Online.testLogin = function (who)
3066{
3067 return this.request('test_login', { user: who });
3068};
3069
3070Online.createLobby = function (planetId)
3071{
3072 return this.request('lobby_create', {
3073 miss_chance: this.DEFAULT_MISS_CHANCE,
3074 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
3075 });
3076};
3077
3078Online.joinLobby = function (code, planetId)
3079{
3080 return this.request('lobby_join', {
3081 code: code,
3082 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
3083 });
3084};
3085
3086Online.setPlanet = function (planetId)
3087{
3088 return this.request('lobby_set_planet', { planet_id: planetId });
3089};
3090
3091Online.leaveLobby = function ()
3092{
3093 return this.request('lobby_leave');
3094};
3095
3096Online.setReady = function (ready)
3097{
3098 return this.request('lobby_ready', { ready: !!ready });
3099};
3100
3101Online.startGame = function ()
3102{
3103 var self = this;
3104 var prev = this.lobby && this.lobby.status;
3105 return this.request('lobby_start').then(function (data)
3106 {
3107 self._handleTransitions(prev, data);
3108 return data;
3109 });
3110};
3111
3112Online.queueShots = function (shots)
3113{
3114 for (var i = 0; i < shots.length; i++)
3115 {
3116 this._pendingShots.push({
3117 client_id: String(shots[i].id),
3118 color: shots[i].color,
3119 col: shots[i].col,
3120 y: shots[i].y
3121 });
3122 }
3123};
3124
3125Online.poll = function (opts)
3126{
3127 opts = opts || {};
3128 var body = {};
3129 if (opts.snapshot)
3130 { body.snapshot = opts.snapshot; }
3131 if (opts.score != null)
3132 { body.score = opts.score; }
3133 if (opts.eliminated)
3134 { body.eliminated = true; }
3135 if (this._pendingShots.length)
3136 {
3137 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
3138 }
3139 var self = this;
3140 var prevStatus = this.lobby && this.lobby.status;
3141 return this.request('poll', body).then(function (data)
3142 {
3143 self._handleTransitions(prevStatus, data);
3144 if (self.onChange)
3145 { self.onChange(self); }
3146 return data;
3147 });
3148};
3149
3150Online._handleTransitions = function (prevStatus, data)
3151{
3152 var lobby = this.lobby;
3153 var status = lobby && lobby.status;
3154 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
3155 { this.onGameStart(lobby); }
3156 if (data && data.incoming && data.incoming.length && this.onIncoming)
3157 { this.onIncoming(data.incoming); }
3158 if (data && data.shot_results && data.shot_results.length)
3159 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
3160 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
3161 { this.onFinished(lobby); }
3162 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
3163 { this.onLobbyReturn(lobby); }
3164};
3165
3166Online.startPolling = function (getPayload)
3167{
3168 this.stopPolling();
3169 var self = this;
3170 var tick = function ()
3171 {
3172 var payload = getPayload ? getPayload() : {};
3173 self.poll(payload);
3174 };
3175 tick();
3176 this._timer = setInterval(tick, this.POLL_MS);
3177};
3178
3179Online.stopPolling = function ()
3180{
3181 if (this._timer)
3182 {
3183 clearInterval(this._timer);
3184 this._timer = null;
3185 }
3186};
3187
3188Online.loginUrl = function ()
3189{
3190 return 'auth.php';
3191};
3192
3193Online.logoutUrl = function ()
3194{
3195 return 'logout.php';
3196};
3197
3198Online.opponents = function ()
3199{
3200 if (!this.lobby || !this.lobby.players)
3201 { return []; }
3202 return this.lobby.players.filter(function (p) { return !p.is_me; });
3203};
3204
3205Online.aliveOpponents = function ()
3206{
3207 return this.opponents().filter(function (p) { return !p.eliminated; });
3208};
3209
3210Online.mePlayer = function ()
3211{
3212 if (!this.lobby || !this.lobby.players)
3213 { return null; }
3214 for (var i = 0; i < this.lobby.players.length; i++)
3215 {
3216 if (this.lobby.players[i].is_me)
3217 { return this.lobby.players[i]; }
3218 }
3219 return null;
3220};
3221
3222/* ---------- miniatures --------------------------------------------- */
3223
3224Online.renderMinis = function (container)
3225{
3226 if (!container)
3227 { return; }
3228 var opponents = this.opponents();
3229 var existing = {};
3230 var kids = container.querySelectorAll('[data-player]');
3231 for (var i = 0; i < kids.length; i++)
3232 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
3233
3234 var seen = Object.create(null);
3235 for (var i = 0; i < opponents.length; i++)
3236 {
3237 var p = opponents[i];
3238 seen[p.id] = true;
3239 var el = existing[p.id];
3240 if (!el)
3241 {
3242 el = document.createElement('div');
3243 el.className = 'mini';
3244 el.setAttribute('data-player', p.id);
3245 el.innerHTML = '<div class="mini-name"></div>'
3246 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
3247 + '<div class="mini-meta"></div>';
3248 container.appendChild(el);
3249 }
3250 el.classList.toggle('eliminated', !!p.eliminated);
3251 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
3252 el.querySelector('.mini-meta').textContent = p.eliminated
3253 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
3254 : ('Punten ' + (p.score || 0));
3255 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
3256 }
3257 for (var id in existing)
3258 {
3259 if (!seen[id])
3260 { existing[id].remove(); }
3261 }
3262};
3263
3264var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
3265
3266function miniColor (planet, color)
3267{
3268 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
3269 { return planet.colors[color].hex; }
3270 return MINI_COLORS[color] || '#888';
3271}
3272
3273
3274Online._drawMini = function (canvas, snapshot, planet)
3275{
3276 if (!canvas)
3277 { return; }
3278 var ctx = canvas.getContext('2d');
3279 var w = 10;
3280 var h = 13;
3281 var tw = canvas.width / w;
3282 var th = canvas.height / h;
3283 ctx.fillStyle = '#0c1020';
3284 ctx.fillRect(0, 0, canvas.width, canvas.height);
3285 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
3286 ctx.lineWidth = 1;
3287 for (var c = 0; c <= w; c++)
3288 {
3289 ctx.beginPath();
3290 ctx.moveTo(c * tw + 0.5, 0);
3291 ctx.lineTo(c * tw + 0.5, canvas.height);
3292 ctx.stroke();
3293 }
3294 for (var r = 0; r <= h; r++)
3295 {
3296 ctx.beginPath();
3297 ctx.moveTo(0, r * th + 0.5);
3298 ctx.lineTo(canvas.width, r * th + 0.5);
3299 ctx.stroke();
3300 }
3301 if (!snapshot || !snapshot.blocks)
3302 { return; }
3303 var blocks = snapshot.blocks;
3304 for (var i = 0; i < blocks.length; i++)
3305 {
3306 var b = blocks[i];
3307 var x = b.col * tw;
3308 var y = canvas.height - (b.y + 1) * th;
3309 if (b.state === 'locked')
3310 { ctx.fillStyle = '#3a3d4a'; }
3311 else if (b.color < 0)
3312 { ctx.fillStyle = '#5a5d66'; }
3313 else
3314 { ctx.fillStyle = miniColor(planet, b.color); }
3315 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
3316 }
3317};
3318
3319Online.miniElement = function (playerId)
3320{
3321 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
3322};
3323
3324/* ---------- flight tweens ------------------------------------------ */
3325
3326function colorSpriteUrl (color, planetId)
3327{
3328 if (color < 0)
3329 { return 'images/block-gray.png'; }
3330 var planet = null;
3331 if (typeof Planet !== 'undefined')
3332 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
3333 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
3334 { return planet.colors[color].image; }
3335 return 'images/block-gray.png';
3336}
3337
3338/**
3339 * Animate shot results. `locals` is a map of client_id → {col, y, color,
3340 * startX, startY} in viewport pixels, filled by the view just after
3341 * consumeOutgoingShots.
3342 */
3343Online.spawnFlights = function (results, locals)
3344{
3345 locals = locals || this._flightLocals || {};
3346 var layer = document.getElementById('flights');
3347 if (!layer)
3348 { return; }
3349 for (var i = 0; i < results.length; i++)
3350 {
3351 var r = results[i];
3352 var meta = locals[r.client_id] || {};
3353 var start = this._flightStart(meta.col);
3354 var end;
3355 var miss = !!r.miss;
3356 if (miss)
3357 { end = this._missEnd(start); }
3358 else
3359 { end = this._targetEnd(r.target_id, start); }
3360 var el = document.createElement('img');
3361 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
3362 el.alt = '';
3363 el.className = 'flight';
3364 layer.appendChild(el);
3365 var spin = (Math.random() * 2 - 1) * 720;
3366 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
3367 this._flights.push({
3368 el: el,
3369 start: start,
3370 end: end,
3371 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
3372 t0: performance.now(),
3373 duration: duration,
3374 spin: spin,
3375 miss: miss,
3376 angle: Math.random() * 360
3377 });
3378 }
3379 this._flightLocals = {};
3380};
3381
3382Online.rememberFlightLocal = function (shot, startX, startY)
3383{
3384 if (!this._flightLocals)
3385 { this._flightLocals = {}; }
3386 this._flightLocals[String(shot.id)] = {
3387 col: shot.col,
3388 y: shot.y,
3389 color: shot.color,
3390 startX: startX,
3391 startY: startY
3392 };
3393};
3394
3395Online._flightStart = function (col)
3396{
3397 var field = document.querySelector('canvas');
3398 var appRef = typeof app !== 'undefined' ? app : null;
3399 if (appRef && appRef.scene && appRef.scene.canvas)
3400 {
3401 var canvas = appRef.scene.canvas;
3402 var rect = canvas.getBoundingClientRect();
3403 var c = col == null ? 4.5 : col;
3404 return {
3405 x: rect.left + (c + 0.5) * (rect.width / 10),
3406 y: rect.top + 4
3407 };
3408 }
3409 if (field)
3410 {
3411 var rect = field.getBoundingClientRect();
3412 return { x: rect.left + rect.width / 2, y: rect.top };
3413 }
3414 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
3415};
3416
3417Online._targetEnd = function (targetId, start)
3418{
3419 var el = targetId && this.miniElement(targetId);
3420 if (el)
3421 {
3422 var r = el.getBoundingClientRect();
3423 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
3424 }
3425 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
3426};
3427
3428Online._missEnd = function (start)
3429{
3430 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
3431 return {
3432 x: start.x + dx,
3433 y: start.y - (120 + Math.random() * 220)
3434 };
3435};
3436
3437Online._missCtrl = function (start, end)
3438{
3439 return {
3440 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
3441 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
3442 };
3443};
3444
3445Online._hitCtrl = function (start, end)
3446{
3447 return {
3448 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
3449 y: (start.y + end.y) / 2 - 30
3450 };
3451};
3452
3453Online.tickFlights = function (now)
3454{
3455 now = now || performance.now();
3456 var leftover = [];
3457 for (var i = 0; i < this._flights.length; i++)
3458 {
3459 var f = this._flights[i];
3460 var u = (now - f.t0) / f.duration;
3461 if (u >= 1)
3462 {
3463 if (f.el && f.el.parentNode)
3464 { f.el.parentNode.removeChild(f.el); }
3465 continue;
3466 }
3467 // Quadratic bezier, ease-in so they feel like they recede.
3468 var e = u * u;
3469 var mt = 1 - e;
3470 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
3471 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
3472 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
3473 var angle = f.angle + f.spin * u;
3474 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
3475 + angle + 'deg) scale(' + scale + ')';
3476 f.el.style.opacity = f.miss ? String(1 - e) : '1';
3477 leftover.push(f);
3478 }
3479 this._flights = leftover;
3480};
3481
3482Online.clearFlights = function ()
3483{
3484 for (var i = 0; i < this._flights.length; i++)
3485 {
3486 var el = this._flights[i].el;
3487 if (el && el.parentNode)
3488 { el.parentNode.removeChild(el); }
3489 }
3490 this._flights = [];
3491 this._flightLocals = {};
3492};
3493
3494if (typeof globalThis !== 'undefined')
3495{ globalThis.Online = Online; }
3496if (typeof module !== 'undefined' && module.exports)
3497{ module.exports = Online; }
3498
3499/*
3500 * End File:
3501 * /workspace/meteors/src/online.js
3502 */
3503
3504/*
3505 * Start File:
3506 * /workspace/meteors/src/main.js
3507 */
3508'use strict';
3509
3510/**
3511 * View and input for Meteors. The simulation lives in GameCore; this file
3512 * only draws it, scales it to the viewport, and translates pointer events
3513 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
3514 * through Online (src/online.js) and the same GameCore.
3515 */
3516
3517function planetImages ()
3518{
3519 var list = [
3520 { name: 'gray', url: 'images/block-gray.png' },
3521 { name: 'locked', url: 'images/block-locked.png' },
3522 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
3523 { name: 'cell', url: 'images/cell.png' },
3524 { name: 'pixel', url: 'images/pixel.png' },
3525 // Keep the original Terra placeholders as aliases (Tim may still have them).
3526 { name: 'ember', url: 'images/block-ember.png' },
3527 { name: 'aqua', url: 'images/block-aqua.png' },
3528 { name: 'leaf', url: 'images/block-leaf.png' },
3529 { name: 'sun', url: 'images/block-sun.png' },
3530 { name: 'orchid', url: 'images/block-orchid.png' }
3531 ];
3532 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
3533 for (var i = 0; i < planets.length; i++)
3534 {
3535 var pl = planets[i];
3536 for (var c = 0; c < pl.colors.length; c++)
3537 {
3538 list.push({
3539 name: Planet.spriteKey(pl, c),
3540 url: pl.colors[c].image
3541 });
3542 }
3543 }
3544 return list;
3545}
3546
3547var IMAGES = planetImages();
3548var GAME_OVER_DELAY = 2;
3549
3550var game = new Game();
3551var app = {
3552 mode: 'menu',
3553 core: null,
3554 scene: null,
3555 manager: null,
3556 planet: null,
3557 lastScore: 0,
3558 tile: 48,
3559 fieldX: 0,
3560 fieldY: 0,
3561 fieldW: 0,
3562 fieldH: 0,
3563 hudH: 56,
3564 sprites: Object.create(null),
3565 flames: Object.create(null),
3566 cells: [],
3567 pointerId: null,
3568 pointerType: null,
3569 activeTouchId: null,
3570 debugDrag: false,
3571 gameOverShown: false,
3572 selectTween: null,
3573 online: false,
3574 eliminatedReported: false,
3575 spectating: false,
3576 miniH: 0,
3577 selectedPlanetId: 'terra',
3578 planetSelectContext: 'solo'
3579};
3580
3581window.onload = function ()
3582{
3583 app.debugDrag = isDragDebugEnabled();
3584 var play = document.getElementById('btn-play');
3585 play.addEventListener('click', onPlay);
3586 play.addEventListener('pointerup', function (e)
3587 {
3588 // A touch-friendly path: some mobile browsers swallow the click
3589 // after a slightly sloppy tap. Ignore the following click.
3590 if (e.pointerType === 'touch' || e.pointerType === 'pen')
3591 {
3592 e.preventDefault();
3593 onPlay();
3594 }
3595 });
3596
3597 game.preloadImagesThenStart(IMAGES, function ()
3598 {
3599 if (game.images.flame && game.images.flame.addAnimationCycle)
3600 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
3601 });
3602
3603 bindOnlineUi();
3604 bindPlanetSelect();
3605 restoreSelectedPlanet();
3606};
3607
3608function onPlay ()
3609{
3610 if (app.mode === 'playing')
3611 { return; }
3612 openPlanetSelect('solo');
3613}
3614
3615function startPlay (opts)
3616{
3617 opts = opts || {};
3618 hideEl('menu');
3619 hideEl('game-over');
3620 hideEl('online-panel');
3621 hideEl('spectator');
3622 hideEl('podium');
3623 hideEl('planet-select');
3624 showEl('hud');
3625
3626 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
3627 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
3628 var miss = opts.missChance;
3629 if (typeof miss !== 'number' || !isFinite(miss))
3630 { miss = planetMod.missChance(app.planet); }
3631 app.core = new GameCore(app.planet, Math.random, miss);
3632 app.mode = 'playing';
3633 app.online = !!opts.online;
3634 app.gameOverShown = false;
3635 app.eliminatedReported = false;
3636 app.spectating = false;
3637 app.sprites = Object.create(null);
3638 app.flames = Object.create(null);
3639 app.cells = [];
3640 app.pointerId = null;
3641 app.selectTween = null;
3642
3643 layout();
3644 if (app.scene)
3645 {
3646 app.scene.destroy();
3647 app.scene = null;
3648 }
3649 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
3650 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
3651 app.scene.renderBackground = true;
3652 game.loadScene(app.scene);
3653
3654 buildCells();
3655 app.manager = app.scene.addObject(makeManager());
3656 if (!app.spectating)
3657 { bindPointer(app.scene.canvas); }
3658 refreshHud();
3659 if (app.online)
3660 { showEl('minis'); }
3661 else
3662 { hideEl('minis'); }
3663}
3664
3665function teardownPlay ()
3666{
3667 unbindPointer();
3668 if (app.scene)
3669 {
3670 app.scene.destroy();
3671 app.scene = null;
3672 }
3673 app.manager = null;
3674 app.core = null;
3675 app.sprites = Object.create(null);
3676 app.flames = Object.create(null);
3677 app.cells = [];
3678 app.selectTween = null;
3679 app.pointerId = null;
3680 app.gameOverShown = false;
3681 hideEl('hud');
3682 hideEl('game-over');
3683 hideEl('spectator');
3684 hideEl('minis');
3685 if (typeof Online !== 'undefined')
3686 { Online.clearFlights(); }
3687}
3688
3689function returnToMenu ()
3690{
3691 if (app.online && typeof Online !== 'undefined')
3692 {
3693 // Online matches do not dump you back to the solo menu:
3694 // elimination becomes spectating; a finished match shows the podium.
3695 return;
3696 }
3697 teardownPlay();
3698 app.mode = 'menu';
3699 app.online = false;
3700 hideEl('planet-select');
3701 showEl('menu');
3702 var last = document.getElementById('last-score');
3703 if (app.lastScore > 0)
3704 {
3705 last.hidden = false;
3706 last.querySelector('strong').textContent = String(app.lastScore);
3707 }
3708}
3709
3710function buildCells ()
3711{
3712 if (!app.scene)
3713 { return; }
3714 var img = game.images.cell;
3715 for (var row = 0; row < 13; row++)
3716 {
3717 for (var col = 0; col < 10; col++)
3718 {
3719 var obj = new GameObject(0, 0, img, 0);
3720 placeTile(obj, col, row);
3721 obj.renderer.alpha = 0.9;
3722 app.scene.addObject(obj);
3723 app.cells.push(obj);
3724 }
3725 }
3726}
3727
3728function placeTile (obj, col, y)
3729{
3730 var t = app.tile;
3731 obj.transform.position.x = col * t + t / 2;
3732 obj.transform.position.y = app.fieldH - (y + 0.5) * t;
3733 obj.transform.size = { x: t, y: t };
3734}
3735
3736function layoutIfNeeded ()
3737{
3738 if (app.core && app.core.drag)
3739 { return; }
3740 var vw = window.innerWidth || 320;
3741 var vh = window.innerHeight || 480;
3742 if (app._layoutVw === vw && app._layoutVh === vh && app.scene && app.tile)
3743 { return; }
3744 layout();
3745}
3746
3747function layout ()
3748{
3749 if (app.core && app.core.drag)
3750 { return; }
3751 var vw = window.innerWidth || 320;
3752 var vh = window.innerHeight || 480;
3753 app._layoutVw = vw;
3754 app._layoutVh = vh;
3755 var safeTop = 0;
3756 try
3757 {
3758 // env(safe-area) is a CSS thing; keep a conservative HUD height.
3759 safeTop = 0;
3760 }
3761 catch (e) { /* ignore */ }
3762 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
3763 app.miniH = 0;
3764 if (app.online)
3765 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
3766 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
3767 var availW = Math.max(80, vw - margin * 2);
3768 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
3769 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
3770 app.fieldW = app.tile * 10;
3771 app.fieldH = app.tile * 13;
3772 app.fieldX = Math.floor((vw - app.fieldW) / 2);
3773 var topBand = app.hudH + app.miniH;
3774 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
3775 if (app.fieldY < topBand)
3776 { app.fieldY = topBand; }
3777 var minis = document.getElementById('minis');
3778 if (minis)
3779 {
3780 minis.style.top = app.hudH + 'px';
3781 minis.style.maxHeight = app.miniH + 'px';
3782 }
3783
3784 if (app.scene)
3785 {
3786 app.scene.position.x = app.fieldX;
3787 app.scene.position.y = app.fieldY;
3788 app.scene.size.x = app.fieldW;
3789 app.scene.size.y = app.fieldH;
3790 }
3791}
3792
3793function spriteFor (block)
3794{
3795 if (block.state === 'locked')
3796 { return game.images.locked; }
3797 if (block.color < 0)
3798 { return game.images.gray; }
3799 var key = Planet.spriteKey(app.planet, block.color);
3800 return game.images[key] || game.images.gray;
3801}
3802
3803function syncSprites ()
3804{
3805 if (!app.core || !app.scene)
3806 { return; }
3807 var seen = Object.create(null);
3808 var blocks = app.core.blocks;
3809 for (var i = 0; i < blocks.length; i++)
3810 {
3811 var block = blocks[i];
3812 seen[block.id] = true;
3813 var obj = app.sprites[block.id];
3814 if (!obj)
3815 {
3816 obj = new GameObject(0, 0, spriteFor(block), 2);
3817 app.scene.addObject(obj);
3818 app.sprites[block.id] = obj;
3819 }
3820 obj.renderer.sprite = spriteFor(block);
3821 placeTile(obj, block.col, block.y);
3822 applyBlockVisual(obj, block);
3823 obj.renderer.visible = true;
3824 obj.renderer.alpha = 1;
3825
3826 if (block.flame)
3827 {
3828 var flame = app.flames[block.id];
3829 if (!flame)
3830 {
3831 flame = new GameObject(0, 0, game.images.flame, 1);
3832 flame.renderer.setAnimation('burn', 0, 0.08);
3833 app.scene.addObject(flame);
3834 app.flames[block.id] = flame;
3835 }
3836 flame.renderer.visible = true;
3837 var t = app.tile;
3838 // 3x as large (length and width, t1110). Keep the top of the
3839 // flame at the same overlap into the block so the extra length
3840 // extends downward under the rocket.
3841 var flameW = t * 0.85 * 3;
3842 var flameH = t * 0.85 * 3;
3843 var origCenter = app.fieldH - block.y * t + t * 0.15;
3844 var origTop = origCenter - (t * 0.85) / 2;
3845 flame.transform.position.x = block.col * t + t / 2;
3846 flame.transform.position.y = origTop + flameH / 2;
3847 flame.transform.size = { x: flameW, y: flameH };
3848 }
3849 else if (app.flames[block.id])
3850 { app.flames[block.id].renderer.visible = false; }
3851 }
3852
3853 var ids = Object.keys(app.sprites);
3854 for (var i = 0; i < ids.length; i++)
3855 {
3856 if (!seen[ids[i]])
3857 {
3858 app.sprites[ids[i]].destroy();
3859 delete app.sprites[ids[i]];
3860 if (app.flames[ids[i]])
3861 {
3862 app.flames[ids[i]].destroy();
3863 delete app.flames[ids[i]];
3864 }
3865 }
3866 }
3867}
3868
3869function applyBlockVisual (obj, block)
3870{
3871 var t = app.tile;
3872 var sx = 1;
3873 var sy = 1;
3874 var dy = 0;
3875 if (block.bouncing && app.planet && app.planet.bounceDuration > 0
3876 && typeof Easing !== 'undefined' && Easing.bouncePose)
3877 {
3878 var u = block.bounceAge / app.planet.bounceDuration;
3879 var pose = Easing.bouncePose(u, app.planet.bounceSquash);
3880 sx = pose.sx;
3881 sy = pose.sy;
3882 dy = pose.dy;
3883 }
3884 var sel = 1;
3885 var tw = app.selectTween;
3886 if (tw && tw.blockId === block.id && tw.phase !== 'idle')
3887 { sel = tw.scale; }
3888 obj.transform.size = { x: t * sx * sel, y: t * sy * sel };
3889 if (dy)
3890 { obj.transform.position.y -= dy * t; }
3891}
3892
3893function clickTween ()
3894{
3895 return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null;
3896}
3897
3898function startPressTween (blockId)
3899{
3900 var c = clickTween();
3901 if (!c)
3902 { return; }
3903 var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1;
3904 app.selectTween = {
3905 blockId: blockId,
3906 from: from,
3907 to: c.pressScale,
3908 t: 0,
3909 duration: c.pressDuration,
3910 ease: c.pressEase,
3911 scale: from,
3912 phase: 'press'
3913 };
3914}
3915
3916function startReleaseTween ()
3917{
3918 var c = clickTween();
3919 var tw = app.selectTween;
3920 if (!c || !tw || tw.phase === 'idle')
3921 { return; }
3922 app.selectTween = {
3923 blockId: tw.blockId,
3924 from: tw.scale,
3925 to: c.releaseScale,
3926 t: 0,
3927 duration: c.releaseDuration,
3928 ease: c.releaseEase,
3929 scale: tw.scale,
3930 phase: 'release'
3931 };
3932}
3933
3934function updateSelectTween (dt)
3935{
3936 var tw = app.selectTween;
3937 if (!tw || tw.phase === 'idle' || tw.phase === 'hold')
3938 { return; }
3939 tw.t += dt;
3940 var u = tw.duration > 0 ? tw.t / tw.duration : 1;
3941 if (u >= 1)
3942 {
3943 tw.scale = tw.to;
3944 tw.t = tw.duration;
3945 if (tw.phase === 'press')
3946 { tw.phase = 'hold'; }
3947 else
3948 {
3949 tw.phase = 'idle';
3950 tw.scale = 1;
3951 tw.blockId = null;
3952 }
3953 return;
3954 }
3955 var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack);
3956 tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u;
3957}
3958
3959function refreshHud ()
3960{
3961 if (!app.core)
3962 { return; }
3963 document.getElementById('score').textContent = String(app.core.score);
3964 var planet = app.planet;
3965 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
3966 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
3967}
3968
3969function makeManager ()
3970{
3971 var obj = new GameObject(0, 0, game.images.pixel, 0);
3972 obj.renderer.visible = false;
3973 var base = obj.update.bind(obj);
3974 obj.update = function (dt)
3975 {
3976 base(dt);
3977 tickView(dt);
3978 };
3979 return obj;
3980}
3981
3982function tickView (dt)
3983{
3984 if (app.mode !== 'playing' || !app.core)
3985 { return; }
3986
3987 // Never resize the canvas mid-drag: a URL-bar hide would move the
3988 // field under the finger and jump the target row. Also skip work
3989 // when the viewport has not actually changed.
3990 if (!(app.core && app.core.drag))
3991 { layoutIfNeeded(); }
3992 for (var i = 0; i < app.cells.length; i++)
3993 {
3994 var col = i % 10;
3995 var row = Math.floor(i / 10);
3996 placeTile(app.cells[i], col, row);
3997 }
3998
3999 app.core.tick(dt);
4000 updateSelectTween(dt);
4001 syncSprites();
4002 refreshHud();
4003 tickOnline(dt);
4004
4005 if (app.core.state === 'gameover' && !app.gameOverShown)
4006 {
4007 app.gameOverShown = true;
4008 app.lastScore = app.core.score;
4009 document.getElementById('go-score').textContent = String(app.lastScore);
4010 if (app.online)
4011 { onOnlineEliminated(); }
4012 else
4013 { showEl('game-over'); }
4014 }
4015 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
4016 { returnToMenu(); }
4017}
4018
4019/* ---------- pointer input (mouse + touch) --------------------------- */
4020/*
4021 * Mouse uses Pointer Events. Touch uses Touch Events as the authority:
4022 * on a real phone, pointer clientX/Y can disagree with the visual
4023 * finger (zoomed visual viewport, gesture takeover, capture cancel)
4024 * while changedTouches stays correct. When a touch is active, pointer
4025 * move/up/cancel are ignored so a poisoned pointer coordinate cannot
4026 * walk the block to the top or bottom of the stack (t1106).
4027 *
4028 * After a down we also listen on the document, so a drag that leaves
4029 * the canvas (needed to launch a block at the top of a full column)
4030 * still reaches moveDrag. We do not call setPointerCapture: on mobile
4031 * that is often cancelled when the browser takes the gesture, which
4032 * would fire pointercancel mid-drag.
4033 *
4034 * A non-passive document touchstart/touchmove preventDefault during
4035 * play stops scrolling, rubber-banding and the pointercancel that
4036 * follows. pointercancel / touchcancel end the drag without launch.
4037 *
4038 * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay.
4039 */
4040
4041var boundCanvas = null;
4042var windowListening = false;
4043var touchListening = false;
4044var lastDragDebug = null;
4045
4046function isDragDebugEnabled ()
4047{
4048 try
4049 {
4050 var q = window.location && window.location.search;
4051 if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q))
4052 { return true; }
4053 if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1')
4054 { return true; }
4055 }
4056 catch (err) { /* ignore */ }
4057 return false;
4058}
4059
4060function eventClient (e)
4061{
4062 var t = null;
4063 if (e.changedTouches && e.changedTouches.length)
4064 { t = e.changedTouches[0]; }
4065 else if (e.touches && e.touches.length)
4066 { t = e.touches[0]; }
4067 if (t)
4068 { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; }
4069 if (e.clientX != null && e.clientY != null)
4070 { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; }
4071 return null;
4072}
4073
4074function addWindowPointer ()
4075{
4076 if (windowListening)
4077 { return; }
4078 window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false });
4079 window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false });
4080 window.addEventListener('pointercancel', onPointerCancel, { capture: true, passive: false });
4081 windowListening = true;
4082}
4083
4084function removeWindowPointer ()
4085{
4086 if (!windowListening)
4087 { return; }
4088 window.removeEventListener('pointermove', onPointerMove, { capture: true });
4089 window.removeEventListener('pointerup', onPointerUp, { capture: true });
4090 window.removeEventListener('pointercancel', onPointerCancel, { capture: true });
4091 windowListening = false;
4092}
4093
4094function addTouchListeners ()
4095{
4096 if (touchListening)
4097 { return; }
4098 var opts = { capture: true, passive: false };
4099 document.addEventListener('touchstart', onTouchStart, opts);
4100 document.addEventListener('touchmove', onTouchMove, opts);
4101 document.addEventListener('touchend', onTouchEnd, opts);
4102 document.addEventListener('touchcancel', onTouchCancel, opts);
4103 touchListening = true;
4104}
4105
4106function removeTouchListeners ()
4107{
4108 if (!touchListening)
4109 { return; }
4110 var opts = { capture: true };
4111 document.removeEventListener('touchstart', onTouchStart, opts);
4112 document.removeEventListener('touchmove', onTouchMove, opts);
4113 document.removeEventListener('touchend', onTouchEnd, opts);
4114 document.removeEventListener('touchcancel', onTouchCancel, opts);
4115 touchListening = false;
4116}
4117
4118function bindPointer (canvas)
4119{
4120 unbindPointer();
4121 boundCanvas = canvas;
4122 canvas.addEventListener('pointerdown', onPointerDown, { passive: false });
4123 canvas.style.touchAction = 'none';
4124 canvas.style.position = 'fixed';
4125 canvas.style.cursor = 'pointer';
4126 canvas.style.webkitUserSelect = 'none';
4127 canvas.style.userSelect = 'none';
4128 addTouchListeners();
4129 if (app.debugDrag)
4130 { ensureDragDebugOverlay(); }
4131}
4132
4133function unbindPointer ()
4134{
4135 removeWindowPointer();
4136 removeTouchListeners();
4137 if (boundCanvas)
4138 { boundCanvas.removeEventListener('pointerdown', onPointerDown); }
4139 boundCanvas = null;
4140 app.pointerId = null;
4141 app.pointerType = null;
4142 app.activeTouchId = null;
4143}
4144
4145function fieldFromEvent (e)
4146{
4147 var canvas = app.scene && app.scene.canvas;
4148 if (!canvas)
4149 { return null; }
4150 var rect = canvas.getBoundingClientRect();
4151 if (rect.width <= 0 || rect.height <= 0)
4152 { return null; }
4153 var pt = eventClient(e);
4154 if (!pt)
4155 { return null; }
4156 // Map through the CSS box only. Using canvas.width / app.tile would
4157 // scale the pointer by the backing-store ratio whenever that differs
4158 // from the layout size (high-DPR devices), so a short finger move
4159 // would look like a long swipe.
4160 var width = Planet.FIELD_WIDTH;
4161 var height = Planet.FIELD_HEIGHT;
4162 var col = ((pt.x - rect.left) / rect.width) * width;
4163 var fieldY = (1 - (pt.y - rect.top) / rect.height) * height;
4164 return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect };
4165}
4166
4167function playingForDrag ()
4168{
4169 return app.core && app.core.state === 'playing';
4170}
4171
4172function startDragFromEvent (e)
4173{
4174 var pos = fieldFromEvent(e);
4175 if (!pos)
4176 { return; }
4177 if (app.core.drag)
4178 {
4179 app.core.moveDrag(pos.y);
4180 logDragDebug(e, pos, 'move-already');
4181 return;
4182 }
4183 if (app.core.beginDrag(pos.col, pos.y) && app.core.drag)
4184 { startPressTween(app.core.drag.blockId); }
4185 logDragDebug(e, pos, 'down');
4186}
4187
4188function moveDragFromEvent (e)
4189{
4190 if (!app.core || !app.core.drag)
4191 { return; }
4192 var pos = fieldFromEvent(e);
4193 if (pos)
4194 { app.core.moveDrag(pos.y); }
4195 logDragDebug(e, pos, 'move');
4196}
4197
4198function finishDrag (opts)
4199{
4200 opts = opts || {};
4201 app.pointerId = null;
4202 app.pointerType = null;
4203 app.activeTouchId = null;
4204 removeWindowPointer();
4205 if (boundCanvas)
4206 {
4207 try
4208 {
4209 if (opts.pointerId != null && boundCanvas.releasePointerCapture)
4210 { boundCanvas.releasePointerCapture(opts.pointerId); }
4211 }
4212 catch (err) { /* ignore */ }
4213 }
4214 startReleaseTween();
4215 if (app.core && app.core.drag)
4216 {
4217 if (opts.noLaunch)
4218 { app.core.drag.launchIntent = false; }
4219 app.core.endDrag();
4220 }
4221 else if (app.core)
4222 { app.core.endDrag(); }
4223 logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up');
4224}
4225
4226function onPointerDown (e)
4227{
4228 if (!playingForDrag())
4229 { return; }
4230 if (app.pointerId != null && e.pointerId !== app.pointerId)
4231 { return; }
4232 if (e.preventDefault)
4233 { e.preventDefault(); }
4234 app.pointerId = e.pointerId;
4235 app.pointerType = e.pointerType || 'mouse';
4236 addWindowPointer();
4237 // If a touch is already in charge, do not reset the grab from pointerdown.
4238 if (app.activeTouchId != null)
4239 { return; }
4240 startDragFromEvent(e);
4241}
4242
4243function onPointerMove (e)
4244{
4245 if (app.pointerId == null || e.pointerId !== app.pointerId)
4246 { return; }
4247 if (!app.core || !app.core.drag)
4248 { return; }
4249 // Touch coordinates are the authority; ignore pointer moves for a
4250 // live touch so a wrong clientY cannot walk the whole column.
4251 // Only skip when touchstart has actually arrived — some environments
4252 // deliver touch-pointer events without a TouchEvent stream.
4253 if (app.activeTouchId != null)
4254 {
4255 if (e.preventDefault)
4256 { e.preventDefault(); }
4257 logDragDebug(e, fieldFromEvent(e), 'pointer-ignored');
4258 return;
4259 }
4260 if (e.preventDefault)
4261 { e.preventDefault(); }
4262 moveDragFromEvent(e);
4263}
4264
4265function onPointerUp (e)
4266{
4267 if (app.pointerId == null)
4268 { return; }
4269 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
4270 { return; }
4271 if (app.activeTouchId != null)
4272 {
4273 // touchend will finish the drag.
4274 if (e && e.preventDefault)
4275 { e.preventDefault(); }
4276 logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored');
4277 return;
4278 }
4279 if (e && e.preventDefault)
4280 { e.preventDefault(); }
4281 finishDrag({ pointerId: e && e.pointerId });
4282}
4283
4284function onPointerCancel (e)
4285{
4286 if (app.pointerId == null)
4287 { return; }
4288 if (e && e.pointerId != null && e.pointerId !== app.pointerId)
4289 { return; }
4290 if (app.activeTouchId != null)
4291 {
4292 if (e && e.preventDefault)
4293 { e.preventDefault(); }
4294 logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored');
4295 return;
4296 }
4297 if (e && e.preventDefault)
4298 { e.preventDefault(); }
4299 // A cancelled gesture is not a launch pull.
4300 finishDrag({ pointerId: e && e.pointerId, noLaunch: true });
4301}
4302
4303function touchById (list, id)
4304{
4305 if (!list)
4306 { return null; }
4307 for (var i = 0; i < list.length; i++)
4308 {
4309 if (list[i].identifier === id)
4310 { return list[i]; }
4311 }
4312 return null;
4313}
4314
4315function onTouchStart (e)
4316{
4317 if (!playingForDrag())
4318 { return; }
4319 if (app.activeTouchId != null)
4320 {
4321 if (e.preventDefault)
4322 { e.preventDefault(); }
4323 return;
4324 }
4325 var t = e.changedTouches && e.changedTouches[0];
4326 if (!t)
4327 { return; }
4328 if (e.preventDefault)
4329 { e.preventDefault(); }
4330 app.activeTouchId = t.identifier;
4331 addWindowPointer();
4332 startDragFromEvent(e);
4333}
4334
4335function onTouchMove (e)
4336{
4337 if (app.activeTouchId == null)
4338 { return; }
4339 if (!touchById(e.changedTouches, app.activeTouchId)
4340 && !touchById(e.touches, app.activeTouchId))
4341 { return; }
4342 if (e.preventDefault)
4343 { e.preventDefault(); }
4344 moveDragFromEvent(e);
4345}
4346
4347function onTouchEnd (e)
4348{
4349 if (app.activeTouchId == null)
4350 { return; }
4351 if (!touchById(e.changedTouches, app.activeTouchId))
4352 { return; }
4353 if (e.preventDefault)
4354 { e.preventDefault(); }
4355 finishDrag({});
4356}
4357
4358function onTouchCancel (e)
4359{
4360 if (app.activeTouchId == null)
4361 { return; }
4362 if (!touchById(e.changedTouches, app.activeTouchId))
4363 { return; }
4364 if (e.preventDefault)
4365 { e.preventDefault(); }
4366 finishDrag({ noLaunch: true });
4367}
4368
4369function ensureDragDebugOverlay ()
4370{
4371 if (document.getElementById('drag-debug'))
4372 { return; }
4373 var el = document.createElement('div');
4374 el.id = 'drag-debug';
4375 el.setAttribute('aria-live', 'polite');
4376 document.body.appendChild(el);
4377}
4378
4379function logDragDebug (e, pos, phase)
4380{
4381 if (!app.debugDrag)
4382 { return; }
4383 ensureDragDebugOverlay();
4384 var el = document.getElementById('drag-debug');
4385 if (!el)
4386 { return; }
4387 var block = null;
4388 if (app.core && app.core.drag)
4389 { block = app.core.blockById(app.core.drag.blockId); }
4390 var pt = e ? eventClient(e) : null;
4391 var evType = e ? e.type : phase;
4392 var info = {
4393 phase: phase,
4394 ev: evType,
4395 src: pos && pos.src,
4396 fieldY: pos && Math.round(pos.y * 100) / 100,
4397 col: pos && Math.round(pos.col * 100) / 100,
4398 cy: pt && Math.round(pt.y * 10) / 10,
4399 blockY: block && Math.round(block.y * 100) / 100,
4400 target: block && Math.floor((pos && pos.y) + 1e-12),
4401 launch: app.core && app.core.drag && app.core.drag.launchIntent,
4402 touchId: app.activeTouchId,
4403 pid: app.pointerId,
4404 ptype: app.pointerType
4405 };
4406 lastDragDebug = info;
4407 el.textContent = 'drag ' + phase
4408 + ' ev=' + evType
4409 + ' src=' + (info.src || '-')
4410 + ' y=' + (info.fieldY != null ? info.fieldY : '-')
4411 + ' → ' + (info.target != null ? info.target : '-')
4412 + ' block=' + (info.blockY != null ? info.blockY : '-')
4413 + (info.launch ? ' LAUNCH' : '')
4414 + ' tId=' + info.touchId
4415 + ' pId=' + info.pid;
4416 el.hidden = false;
4417}
4418
4419
4420function hideEl (id)
4421{
4422 document.getElementById(id).hidden = true;
4423}
4424
4425function showEl (id)
4426{
4427 document.getElementById(id).hidden = false;
4428}
4429
4430window.addEventListener('resize', function ()
4431{
4432 if (app.mode === 'playing')
4433 { layout(); }
4434});
4435
4436window.addEventListener('orientationchange', function ()
4437{
4438 setTimeout(function ()
4439 {
4440 if (app.mode === 'playing')
4441 { layout(); }
4442 }, 120);
4443});
4444
4445/* ---------- online play (stage 2) ---------------------------------- */
4446
4447function tickOnline (dt)
4448{
4449 if (!app.online || typeof Online === 'undefined')
4450 { return; }
4451 if (app.core)
4452 {
4453 var shots = app.core.consumeOutgoingShots();
4454 for (var i = 0; i < shots.length; i++)
4455 {
4456 var s = shots[i];
4457 var start = fieldToViewport(s.col, s.y + 1);
4458 Online.rememberFlightLocal(s, start.x, start.y);
4459 }
4460 Online.queueShots(shots);
4461 }
4462 Online.tickFlights();
4463 Online.renderMinis(document.getElementById('minis'));
4464}
4465
4466function fieldToViewport (col, fieldY)
4467{
4468 var canvas = app.scene && app.scene.canvas;
4469 if (!canvas)
4470 { return { x: window.innerWidth / 2, y: 40 }; }
4471 var rect = canvas.getBoundingClientRect();
4472 var x = rect.left + ((col + 0.5) / 10) * rect.width;
4473 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
4474 return { x: x, y: y };
4475}
4476
4477function onlinePayload ()
4478{
4479 if (!app.online || !app.core)
4480 { return {}; }
4481 return {
4482 snapshot: app.core.fieldSnapshot(),
4483 score: app.core.score,
4484 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
4485 };
4486}
4487
4488function onOnlineEliminated ()
4489{
4490 app.eliminatedReported = true;
4491 app.spectating = true;
4492 unbindPointer();
4493 hideEl('game-over');
4494 var lobby = typeof Online !== 'undefined' && Online.lobby;
4495 if (lobby && lobby.status === 'finished')
4496 {
4497 showPodium(lobby);
4498 return;
4499 }
4500 showEl('spectator');
4501}
4502
4503function showPodium (lobby)
4504{
4505 hideEl('spectator');
4506 hideEl('game-over');
4507 hideEl('online-panel');
4508 showEl('podium');
4509 var list = document.getElementById('podium-list');
4510 list.innerHTML = '';
4511 var ranks = (lobby && lobby.rankings) || [];
4512 for (var i = 0; i < ranks.length; i++)
4513 {
4514 var r = ranks[i];
4515 var li = document.createElement('li');
4516 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
4517 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
4518 list.appendChild(li);
4519 }
4520 var hint = document.getElementById('podium-hint');
4521 var secs = (lobby && lobby.podium_seconds) || 5;
4522 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
4523}
4524
4525function startOnlineMatch ()
4526{
4527 if (app.mode === 'playing' && app.online)
4528 { return; }
4529 var planet = Planet.planetById(selectedPlanetId());
4530 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
4531 if (me && me.planet && me.planet.id)
4532 { planet = Planet.planetById(me.planet.id); }
4533 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
4534 if (typeof Online !== 'undefined')
4535 { Online.startPolling(onlinePayload); }
4536}
4537
4538function leaveOnlineMatch (goMenu)
4539{
4540 if (typeof Online !== 'undefined')
4541 {
4542 Online.stopPolling();
4543 Online.leaveLobby();
4544 Online.clearFlights();
4545 }
4546 teardownPlay();
4547 app.online = false;
4548 if (goMenu)
4549 {
4550 app.mode = 'menu';
4551 showEl('menu');
4552 }
4553 else
4554 {
4555 app.mode = 'online';
4556 openOnlinePanel();
4557 }
4558}
4559
4560function bindOnlineUi ()
4561{
4562 var onlineBtn = document.getElementById('btn-online');
4563 if (!onlineBtn)
4564 { return; }
4565 onlineBtn.addEventListener('click', function ()
4566 { openOnlinePanel(); });
4567
4568 var backs = document.querySelectorAll('[data-back-menu]');
4569 for (var i = 0; i < backs.length; i++)
4570 {
4571 backs[i].addEventListener('click', function ()
4572 {
4573 if (typeof Online !== 'undefined')
4574 { Online.stopPolling(); }
4575 hideEl('online-panel');
4576 app.mode = 'menu';
4577 app.online = false;
4578 showEl('menu');
4579 });
4580 }
4581
4582 document.getElementById('btn-create').addEventListener('click', function ()
4583 {
4584 Online.createLobby().then(function (data)
4585 {
4586 if (data && data.ok)
4587 {
4588 renderOnline();
4589 Online.startPolling(onlinePayload);
4590 }
4591 else
4592 { renderOnline(); }
4593 });
4594 });
4595
4596 document.getElementById('join-form').addEventListener('submit', function (e)
4597 {
4598 e.preventDefault();
4599 var code = (document.getElementById('join-code').value || '').trim();
4600 if (!code)
4601 { return; }
4602 Online.joinLobby(code).then(function ()
4603 {
4604 renderOnline();
4605 if (Online.lobby)
4606 { Online.startPolling(onlinePayload); }
4607 });
4608 });
4609
4610 document.getElementById('btn-ready').addEventListener('click', function ()
4611 {
4612 var me = Online.mePlayer();
4613 Online.setReady(!(me && me.ready)).then(renderOnline);
4614 });
4615
4616 document.getElementById('btn-start').addEventListener('click', function ()
4617 {
4618 Online.startGame().then(function (data)
4619 {
4620 if (data && data.ok)
4621 { startOnlineMatch(); }
4622 else
4623 { renderOnline(); }
4624 });
4625 });
4626
4627 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
4628 {
4629 Online.leaveLobby().then(function ()
4630 {
4631 Online.stopPolling();
4632 renderOnline();
4633 });
4634 });
4635
4636 document.getElementById('btn-copy-code').addEventListener('click', function ()
4637 {
4638 var code = document.getElementById('lobby-code').textContent;
4639 if (navigator.clipboard && navigator.clipboard.writeText)
4640 { navigator.clipboard.writeText(code); }
4641 });
4642
4643 document.getElementById('btn-spectate').addEventListener('click', function ()
4644 {
4645 hideEl('spectator');
4646 app.spectating = true;
4647 });
4648
4649 document.getElementById('btn-leave-game').addEventListener('click', function ()
4650 { leaveOnlineMatch(false); });
4651
4652 if (typeof Online !== 'undefined')
4653 {
4654 Online.onChange = function ()
4655 { renderOnline(); };
4656 Online.onGameStart = function ()
4657 { startOnlineMatch(); };
4658 Online.onIncoming = function (incoming)
4659 {
4660 if (!app.core || app.core.state !== 'playing')
4661 { return; }
4662 for (var i = 0; i < incoming.length; i++)
4663 { app.core.ingestGarbage(); }
4664 };
4665 Online.onFinished = function (lobby)
4666 { showPodium(lobby); };
4667 Online.onLobbyReturn = function (lobby)
4668 {
4669 teardownPlay();
4670 app.online = false;
4671 app.mode = 'online';
4672 hideEl('podium');
4673 showEl('online-panel');
4674 renderOnline();
4675 Online.startPolling(onlinePayload);
4676 };
4677 }
4678
4679 var params = new URLSearchParams(window.location.search);
4680 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
4681 { openOnlinePanel(); }
4682}
4683
4684function openOnlinePanel ()
4685{
4686 hideEl('menu');
4687 hideEl('game-over');
4688 hideEl('podium');
4689 hideEl('spectator');
4690 hideEl('planet-select');
4691 showEl('online-panel');
4692 app.mode = 'online';
4693 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
4694 if (typeof Online === 'undefined')
4695 {
4696 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
4697 showOnly('online-unconfigured');
4698 return;
4699 }
4700 Online.refresh().then(function (data)
4701 {
4702 if (!data || data.ok === false)
4703 {
4704 var msg = (data && data.error) || 'Geen verbinding met de server.';
4705 showOnlineError(msg + ' Je kunt wel alleen spelen.');
4706 if (data && data.configured === false)
4707 { showOnly('online-unconfigured'); }
4708 else
4709 { showOnly('online-login'); }
4710 document.getElementById('btn-login').style.display = 'none';
4711 return;
4712 }
4713 renderOnline();
4714 if (Online.lobby)
4715 { Online.startPolling(onlinePayload); }
4716 });
4717}
4718
4719function setOnlineStatus (text)
4720{
4721 var el = document.getElementById('online-status');
4722 if (el)
4723 { el.textContent = text; }
4724}
4725
4726function showOnlineError (text)
4727{
4728 var el = document.getElementById('online-error');
4729 if (!el)
4730 { return; }
4731 if (!text)
4732 {
4733 el.hidden = true;
4734 el.textContent = '';
4735 return;
4736 }
4737 el.hidden = false;
4738 el.textContent = text;
4739}
4740
4741function showOnly (id)
4742{
4743 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
4744 for (var i = 0; i < ids.length; i++)
4745 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
4746}
4747
4748function renderOnline ()
4749{
4750 if (typeof Online === 'undefined')
4751 { return; }
4752 if (app.mode === 'playing' && app.online)
4753 {
4754 Online.renderMinis(document.getElementById('minis'));
4755 if (Online.lobby && Online.lobby.status === 'finished')
4756 { showPodium(Online.lobby); }
4757 return;
4758 }
4759 showOnlineError(Online.error);
4760 if (!Online.configured && !Online.me && !Online.local)
4761 {
4762 setOnlineStatus('Online spelen is nog niet ingesteld.');
4763 showOnly('online-unconfigured');
4764 return;
4765 }
4766 if (!Online.me)
4767 {
4768 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
4769 showOnly('online-login');
4770 document.getElementById('btn-login').style.display = '';
4771 document.getElementById('btn-login').href = Online.loginUrl();
4772 document.getElementById('local-login').hidden = !Online.local;
4773 return;
4774 }
4775 if (Online.lobby)
4776 {
4777 setOnlineStatus('Lobby');
4778 showOnly('online-lobby');
4779 document.getElementById('lobby-me-name').textContent = Online.me.name;
4780 document.getElementById('lobby-code').textContent = Online.lobby.code;
4781 var list = document.getElementById('lobby-players');
4782 list.innerHTML = '';
4783 var players = Online.lobby.players || [];
4784 for (var i = 0; i < players.length; i++)
4785 {
4786 var p = players[i];
4787 var li = document.createElement('li');
4788 if (p.is_me)
4789 { li.classList.add('you'); }
4790 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
4791 var state = p.ready ? 'Gereed' : 'Wacht…';
4792 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
4793 li.innerHTML = '<span>' + escapeText(label)
4794 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
4795 + '</span><span class="'
4796 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
4797 list.appendChild(li);
4798 }
4799 renderPlanetGrid('lobby-planet-grid', true);
4800 var me = Online.mePlayer();
4801 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
4802 var start = document.getElementById('btn-start');
4803 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
4804 start.disabled = !Online.lobby.can_start;
4805 var hint = document.getElementById('lobby-hint');
4806 if (Online.lobby.status === 'playing')
4807 { hint.textContent = 'Het spel start…'; }
4808 else if (players.length < 2)
4809 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
4810 else if (!Online.lobby.all_ready)
4811 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
4812 else if (Online.lobby.can_start)
4813 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
4814 else
4815 { hint.textContent = 'Wachten tot de host start.'; }
4816 return;
4817 }
4818 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
4819 showOnly('online-home');
4820 document.getElementById('me-name').textContent = Online.me.name;
4821 document.getElementById('local-login').hidden = !Online.local;
4822}
4823
4824function escapeText (s)
4825{
4826 return String(s)
4827 .replace(/&/g, '&amp;')
4828 .replace(/</g, '&lt;')
4829 .replace(/>/g, '&gt;')
4830 .replace(/"/g, '&quot;');
4831}
4832
4833
4834function selectedPlanetId ()
4835{
4836 if (app.selectedPlanetId)
4837 { return app.selectedPlanetId; }
4838 return 'terra';
4839}
4840
4841function restoreSelectedPlanet ()
4842{
4843 var id = 'terra';
4844 try
4845 { id = localStorage.getItem('meteors-planet') || 'terra'; }
4846 catch (e) {}
4847 setSelectedPlanet(id, true);
4848}
4849
4850function setSelectedPlanet (id, silent)
4851{
4852 var all = Planet.allPlanets();
4853 var found = null;
4854 for (var i = 0; i < all.length; i++)
4855 {
4856 if (all[i].id === id)
4857 { found = all[i]; break; }
4858 }
4859 if (!found)
4860 { found = Planet.defaultPlanet(); }
4861 app.selectedPlanetId = found.id;
4862 try
4863 { localStorage.setItem('meteors-planet', found.id); }
4864 catch (e) {}
4865 if (!silent)
4866 {
4867 var grid = document.getElementById('planet-grid');
4868 if (grid && !grid.hidden && grid.children.length)
4869 { renderPlanetGrid('planet-grid', false); }
4870 var lobby = document.getElementById('lobby-planet-grid');
4871 if (lobby && lobby.children.length)
4872 { renderPlanetGrid('lobby-planet-grid', true); }
4873 }
4874 return found;
4875}
4876
4877function openPlanetSelect (context)
4878{
4879 if (app.mode === 'playing')
4880 { return; }
4881 app.planetSelectContext = context || 'solo';
4882 app.mode = 'planet-select';
4883 hideEl('menu');
4884 hideEl('online-panel');
4885 hideEl('game-over');
4886 showEl('planet-select');
4887 renderPlanetGrid('planet-grid', false);
4888 var go = document.getElementById('btn-planet-go');
4889 if (go)
4890 { go.textContent = 'Spelen'; }
4891}
4892
4893function renderPlanetGrid (containerId, compact)
4894{
4895 var grid = document.getElementById(containerId);
4896 if (!grid)
4897 { return; }
4898 var current = selectedPlanetId();
4899 var all = Planet.allPlanets();
4900 grid.innerHTML = '';
4901 if (compact)
4902 { grid.classList.add('compact'); }
4903 for (var i = 0; i < all.length; i++)
4904 {
4905 var pl = all[i];
4906 var btn = document.createElement('button');
4907 btn.type = 'button';
4908 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
4909 btn.setAttribute('role', 'listitem');
4910 btn.dataset.planet = pl.id;
4911 var swatches = '';
4912 for (var c = 0; c < pl.colors.length; c++)
4913 {
4914 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
4915 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
4916 }
4917 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
4918 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
4919 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
4920 + '<div class="planet-swatches">' + swatches + '</div>';
4921 btn.addEventListener('click', (function (id, isCompact)
4922 {
4923 return function ()
4924 { onPlanetPicked(id, isCompact); };
4925 })(pl.id, !!compact));
4926 grid.appendChild(btn);
4927 }
4928}
4929
4930function onPlanetPicked (id, fromLobby)
4931{
4932 setSelectedPlanet(id);
4933 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
4934 {
4935 Online.setPlanet(id).then(function ()
4936 { renderOnline(); });
4937 }
4938 else
4939 {
4940 renderPlanetGrid('planet-grid', false);
4941 }
4942}
4943
4944function confirmPlanetSelect ()
4945{
4946 var planet = setSelectedPlanet(selectedPlanetId());
4947 hideEl('planet-select');
4948 if (app.planetSelectContext === 'online')
4949 {
4950 openOnlinePanel();
4951 return;
4952 }
4953 startPlay({ planet: planet });
4954}
4955
4956function cancelPlanetSelect ()
4957{
4958 hideEl('planet-select');
4959 app.mode = 'menu';
4960 showEl('menu');
4961}
4962
4963function bindPlanetSelect ()
4964{
4965 var go = document.getElementById('btn-planet-go');
4966 var back = document.getElementById('btn-planet-back');
4967 if (go)
4968 {
4969 go.addEventListener('click', confirmPlanetSelect);
4970 }
4971 if (back)
4972 {
4973 back.addEventListener('click', cancelPlanetSelect);
4974 }
4975}
4976
4977/*
4978 * End File:
4979 * /workspace/meteors/src/main.js
4980 */