BlueGit

projects-timfalken-com meteors

Files

meteors / build / game.js

game.js

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