BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

gameCore.js 82.3 KiB Download Raw
1'use strict';
2
3/**
4 * Deterministic Meteors game core. No DOM, no rendering, no input devices.
5 * The view layer reads this state and translates pointer events into
6 * beginDrag / moveDrag / endDrag.
7 */
8
9var PlanetMod = (typeof require !== 'undefined' && typeof module !== 'undefined')
10 ? require('./planet.js')
11 : (typeof Planet !== 'undefined' ? Planet : globalThis.Planet);
12
13var COLOR_GRAY = -1;
14
15var STATE_STILL = 'still';
16var STATE_FALLING = 'falling';
17var STATE_FLYING = 'flying';
18var STATE_SETTLING = 'settling';
19var STATE_LOCKED = 'locked';
20var STATE_MANUAL = 'manual';
21
22var ALIGN_EPS = 0.15;
23var SUBSTEP = 1 / 120;
24var DRAG_LAUNCH_SLACK = 0.65;
25// Upward pull (tiles past the press point) that launches an already-topmost block.
26var LAUNCH_PULL = 0.35;
27// Minimal accumulated vertical pointer travel (tiles) to swap one step.
28// No hold delay: the first swap fires as soon as this distance is reached.
29var SWAP_DISTANCE = 0.25;
30// Fallback snap (tiles) when the press cell is empty: nearest block in the column.
31var SNAP_Y = 0.5;
32// Horizontal slop (tiles) for snapping to a neighbouring column on press.
33var HORIZONTAL_SLOP = 0.35;
34/** t1120: additive jump bonus per landing-chain step. A landing that
35 * immediately makes a match launches at (1 + 0.25 * chain) times the
36 * usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */
37var LANDING_CHAIN_BONUS = 0.25;
38/** t1123: a column pulses red at or above this many grounded rows
39 * (10 of 13 is just over 70%). */
40var COLUMN_WARN_ROWS = 10;
41
42function UnionFind ()
43{
44 this.parent = Object.create(null);
45}
46
47UnionFind.prototype.add = function (id)
48{
49 if (this.parent[id] == null)
50 { this.parent[id] = id; }
51};
52
53UnionFind.prototype.find = function (id)
54{
55 if (this.parent[id] !== id)
56 { this.parent[id] = this.find(this.parent[id]); }
57 return this.parent[id];
58};
59
60UnionFind.prototype.union = function (a, b)
61{
62 this.add(a);
63 this.add(b);
64 var ra = this.find(a);
65 var rb = this.find(b);
66 if (ra !== rb)
67 { this.parent[rb] = ra; }
68};
69
70function GameCore (planet, rng)
71{
72 this.planet = planet || PlanetMod.defaultPlanet();
73 this.rng = rng || Math.random;
74 this.width = PlanetMod.FIELD_WIDTH;
75 this.height = PlanetMod.FIELD_HEIGHT;
76 this.blocks = [];
77 this.clusters = Object.create(null);
78 this.nextBlockId = 1;
79 this.nextClusterId = 1;
80 this.spawnTimer = 0;
81 this.spawnInterval = PlanetMod.SPAWN_INTERVAL;
82 this.settleTime = PlanetMod.SETTLE_TIME;
83 this.score = 0;
84 this.state = 'playing';
85 this.drag = null;
86 this.gameOverTime = 0;
87 this.outgoingShots = [];
88 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
89 this.missChance = optsMissChance(arguments);
90 // t1112: invariant checker. strictInvariants throws (tests);
91 // debugInvariants records violations for the ?debug overlay.
92 this.strictInvariants = false;
93 this.debugInvariants = false;
94 this.lastInvariantViolations = [];
95 // t1121: visual-only swap events, consumed by the view each frame.
96 this.swapEvents = [];
97 // t1120: last landing-chain indicator { chain, bonusPct }, or null.
98 this.lastChainIndicator = null;
99}
100
101function optsMissChance (args)
102{
103 // GameCore(planet, rng, missChance) — third arg is optional.
104 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
105 { return Math.max(0, Math.min(1, args[2])); }
106 var planet = args[0];
107 if (planet && typeof PlanetMod.missChance === 'function')
108 { return PlanetMod.missChance(planet); }
109 return GameCore.DEFAULT_MISS_CHANCE;
110}
111
112GameCore.COLOR_GRAY = COLOR_GRAY;
113GameCore.LAUNCH_PULL = LAUNCH_PULL;
114GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
115GameCore.SNAP_Y = SNAP_Y;
116GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
117GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS;
118GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS;
119GameCore.DEFAULT_MISS_CHANCE = 0.30;
120GameCore.STATE_STILL = STATE_STILL;
121GameCore.STATE_FALLING = STATE_FALLING;
122GameCore.STATE_FLYING = STATE_FLYING;
123GameCore.STATE_SETTLING = STATE_SETTLING;
124GameCore.STATE_LOCKED = STATE_LOCKED;
125GameCore.STATE_MANUAL = STATE_MANUAL;
126
127GameCore.prototype.randomColor = function ()
128{
129 return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length;
130};
131
132GameCore.prototype.createBlock = function (col, y, color, state)
133{
134 var block = {
135 id: this.nextBlockId++,
136 col: col,
137 y: y,
138 color: color,
139 state: state || STATE_STILL,
140 vy: 0,
141 clusterId: null,
142 settleTime: 0,
143 flame: false,
144 pushedClusters: null,
145 manualTarget: 0,
146 manualDecel: 0,
147 manualPhase: null,
148 bouncing: false,
149 bounceAge: 0
150 };
151 this.blocks.push(block);
152 return block;
153};
154
155GameCore.prototype.removeBlock = function (block)
156{
157 if (block.clusterId != null)
158 { this.leaveCluster(block); }
159 var index = this.blocks.indexOf(block);
160 if (index >= 0)
161 { this.blocks.splice(index, 1); }
162};
163
164GameCore.prototype.leaveCluster = function (block)
165{
166 var id = block.clusterId;
167 block.clusterId = null;
168 block.flame = false;
169 if (id == null || !this.clusters[id])
170 { return; }
171 var still = 0;
172 for (var i = 0; i < this.blocks.length; i++)
173 {
174 if (this.blocks[i].clusterId === id)
175 { still++; }
176 }
177 if (still === 0)
178 { delete this.clusters[id]; }
179};
180
181GameCore.prototype.blocksInColumn = function (col)
182{
183 var out = [];
184 for (var i = 0; i < this.blocks.length; i++)
185 {
186 if (this.blocks[i].col === col)
187 { out.push(this.blocks[i]); }
188 }
189 out.sort(function (a, b) { return a.y - b.y; });
190 return out;
191};
192
193GameCore.prototype.isGrounded = function (block)
194{
195 return block.state === STATE_STILL
196 || block.state === STATE_SETTLING
197 || block.state === STATE_LOCKED;
198};
199
200/**
201 * Highest grounded landing surface in `col`. If `belowY` is given, only
202 * blocks strictly below that y count — a hanging still block above a
203 * gap must never pull a falling or thrown block upward through the gap.
204 */
205GameCore.prototype.stackTop = function (col, ignore, belowY)
206{
207 var top = 0;
208 for (var i = 0; i < this.blocks.length; i++)
209 {
210 var block = this.blocks[i];
211 if (block.col !== col)
212 { continue; }
213 if (ignore && ignore(block))
214 { continue; }
215 if (belowY != null && block.y + 1e-9 >= belowY)
216 { continue; }
217 if (this.isGrounded(block))
218 {
219 var surface = block.y + 1;
220 if (surface > top)
221 { top = surface; }
222 }
223 }
224 return top;
225};
226
227GameCore.prototype.isColumnLocked = function (col)
228{
229 for (var i = 0; i < this.blocks.length; i++)
230 {
231 var block = this.blocks[i];
232 if (block.col === col && block.state === STATE_LOCKED)
233 { return true; }
234 }
235 return false;
236};
237
238GameCore.prototype.isColumnStill = function (col)
239{
240 if (this.isColumnLocked(col))
241 { return false; }
242 for (var i = 0; i < this.blocks.length; i++)
243 {
244 var block = this.blocks[i];
245 if (block.col !== col)
246 { continue; }
247 if (block.state === STATE_FLYING
248 || block.state === STATE_FALLING
249 || block.state === STATE_MANUAL
250 || block.state === STATE_SETTLING)
251 { return false; }
252 }
253 return true;
254};
255
256GameCore.prototype.groundedCount = function (col)
257{
258 var n = 0;
259 for (var i = 0; i < this.blocks.length; i++)
260 {
261 if (this.blocks[i].col === col && this.isGrounded(this.blocks[i]))
262 { n++; }
263 }
264 return n;
265};
266
267GameCore.prototype.columnNeedsWarn = function (col)
268{
269 return this.groundedCount(col) >= COLUMN_WARN_ROWS;
270};
271
272/**
273 * Which columns of a field snapshot should pulse (t1123). Flying,
274 * falling and manual (airborne) blocks do not count: they are
275 * temporary and would flicker the warning. Still, settling and
276 * locked (grounded) blocks do.
277 */
278GameCore.warnColumnsFromSnapshot = function (snapshot, threshold)
279{
280 threshold = threshold == null ? COLUMN_WARN_ROWS : threshold;
281 var width = (snapshot && snapshot.width) || 10;
282 var flags = [];
283 var counts = [];
284 for (var c = 0; c < width; c++)
285 {
286 counts[c] = 0;
287 flags[c] = false;
288 }
289 var blocks = (snapshot && snapshot.blocks) || [];
290 for (var i = 0; i < blocks.length; i++)
291 {
292 var b = blocks[i];
293 if (b.col < 0 || b.col >= width)
294 { continue; }
295 if (b.state === 'still' || b.state === 'settling' || b.state === 'locked')
296 { counts[b.col]++; }
297 }
298 for (var c = 0; c < width; c++)
299 { flags[c] = counts[c] >= threshold; }
300 return flags;
301};
302
303GameCore.columnWarnPulse = function (timeSec)
304{
305 // Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player
306 // field and opponent / bot minis so they pulse in sync.
307 var t = timeSec;
308 if (t == null)
309 {
310 t = (typeof performance !== 'undefined' && performance.now)
311 ? performance.now() / 1000
312 : Date.now() / 1000;
313 }
314 return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55));
315};
316
317GameCore.prototype.blockAt = function (col, row)
318{
319 for (var i = 0; i < this.blocks.length; i++)
320 {
321 var block = this.blocks[i];
322 if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS)
323 { return block; }
324 }
325 return null;
326};
327
328GameCore.prototype.place = function (col, row, color, state)
329{
330 return this.createBlock(col, row, color, state || STATE_STILL);
331};
332
333GameCore.prototype.lockedColumnCount = function ()
334{
335 var n = 0;
336 for (var c = 0; c < this.width; c++)
337 {
338 if (this.isColumnLocked(c))
339 { n++; }
340 }
341 return n;
342};
343
344GameCore.prototype.startBounce = function (block)
345{
346 if (!block)
347 { return; }
348 block.bouncing = true;
349 block.bounceAge = 0;
350};
351
352GameCore.prototype.advanceBounces = function (dt)
353{
354 var duration = this.planet.bounceDuration;
355 for (var i = 0; i < this.blocks.length; i++)
356 {
357 var block = this.blocks[i];
358 if (!block.bouncing)
359 { continue; }
360 block.bounceAge += dt;
361 if (duration <= 0 || block.bounceAge >= duration)
362 {
363 block.bouncing = false;
364 block.bounceAge = duration;
365 }
366 }
367};
368
369/**
370 * True if `block` rests on the floor or on a solid (still / settling /
371 * locked) block immediately below it in the same column.
372 */
373GameCore.prototype.hasSupport = function (block)
374{
375 if (block.y <= 1e-9)
376 { return true; }
377 for (var i = 0; i < this.blocks.length; i++)
378 {
379 var other = this.blocks[i];
380 if (other === block || other.col !== block.col)
381 { continue; }
382 if (!this.isGrounded(other))
383 { continue; }
384 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
385 { return true; }
386 }
387 return false;
388};
389
390/** Highest flying block in this column whose top is at or below `block.y + 1`. */
391GameCore.prototype.highestFlyingBelow = function (block)
392{
393 var best = null;
394 for (var i = 0; i < this.blocks.length; i++)
395 {
396 var other = this.blocks[i];
397 if (other === block || other.col !== block.col)
398 { continue; }
399 if (other.state !== STATE_FLYING || other.clusterId == null)
400 { continue; }
401 var cluster = this.clusters[other.clusterId];
402 if (!cluster || cluster.phase === 'landed')
403 { continue; }
404 // The falling block is at or above this flyer (or already overlapping).
405 if (block.y + 1e-9 < other.y)
406 { continue; }
407 if (!best || other.y > best.y)
408 { best = other; }
409 }
410 return best;
411};
412
413GameCore.prototype.highestFallingBelow = function (block)
414{
415 var best = null;
416 for (var i = 0; i < this.blocks.length; i++)
417 {
418 var other = this.blocks[i];
419 if (other === block || other.col !== block.col)
420 { continue; }
421 if (other.state !== STATE_FALLING)
422 { continue; }
423 if (other.y > block.y - 1e-9)
424 { continue; }
425 if (!best || other.y > best.y)
426 { best = other; }
427 }
428 return best;
429};
430
431/**
432 * Make an unsupported still block start falling from rest, so it eases
433 * into fallSpeed under normal gravity. Skips the block being dragged.
434 */
435/**
436 * Strip leftover launch / manual kinematics so a block that has just
437 * become still or falling starts from rest. Used after a landed grey
438 * cluster recolors, and whenever an unsupported still block drops.
439 */
440GameCore.prototype.clearFlightState = function (block)
441{
442 block.vy = 0;
443 block.flame = false;
444 block.manualPhase = null;
445 block.manualTarget = null;
446 block.manualDecel = 0;
447 block.pushedClusters = null;
448};
449
450GameCore.prototype.releaseUnsupported = function ()
451{
452 // Repeat until stable: a still sitting on a still that itself just
453 // became falling must also drop. Two fixed passes are not enough
454 // for a chain of hanging blocks (t1112).
455 var guard = 0;
456 var changed = true;
457 while (changed && guard++ < this.height + 2)
458 {
459 changed = false;
460 for (var i = 0; i < this.blocks.length; i++)
461 {
462 var block = this.blocks[i];
463 if (block.state !== STATE_STILL)
464 { continue; }
465 if (this.drag && this.drag.blockId === block.id)
466 { continue; }
467 if (this.hasSupport(block))
468 { continue; }
469 this.leaveCluster(block);
470 this.clearFlightState(block);
471 block.state = STATE_FALLING;
472 changed = true;
473 }
474 }
475};
476
477GameCore.prototype.accelerateFall = function (block, dt)
478{
479 var target = -this.planet.fallSpeed;
480 if (block.vy > target)
481 { block.vy = Math.max(target, block.vy - this.planet.fallAccel * dt); }
482 else
483 { block.vy = target; }
484};
485
486GameCore.prototype.landFallingBlock = function (block)
487{
488 block.vy = 0;
489 block.flame = false;
490 this.startBounce(block);
491 if (block.color === COLOR_GRAY)
492 {
493 block.state = STATE_SETTLING;
494 block.settleTime = 0;
495 }
496 else
497 { block.state = STATE_STILL; }
498};
499
500/**
501 * Sit `block` on top of the flying cluster that `flyer` belongs to, and
502 * carry it along as cargo (no flame). Returns true if attached.
503 */
504GameCore.prototype.attachToFlyingCluster = function (block, flyer)
505{
506 var cluster = this.clusters[flyer.clusterId];
507 if (!cluster || cluster.phase === 'landed')
508 { return false; }
509 this.prepareClusterBody(cluster);
510 var maxOff = null;
511 var members = this.clusterMembers(cluster.id);
512 for (var i = 0; i < members.length; i++)
513 {
514 if (members[i].col !== block.col)
515 { continue; }
516 if (maxOff == null || members[i].clusterOffset > maxOff)
517 { maxOff = members[i].clusterOffset; }
518 }
519 var oldN = members.length;
520 var fallingVy = block.vy;
521 if (block.clusterId != null && block.clusterId !== cluster.id)
522 { this.leaveCluster(block); }
523 block.state = STATE_FLYING;
524 block.clusterId = cluster.id;
525 block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1;
526 block.flame = false;
527 block.settleTime = 0;
528 block.manualPhase = null;
529 block.manualTarget = null;
530 block.manualDecel = 0;
531 block.pushedClusters = null;
532 // A cluster born from a thrown block averages in falling cargo
533 // the same way two flying clusters merge (t1108). Other rockets
534 // keep their velocity and just pick the cargo up.
535 if (cluster.fromManual)
536 {
537 var newN = oldN + 1;
538 cluster.vy = (cluster.vy * oldN + fallingVy) / newN;
539 cluster.decel = ((cluster.decel || 0) * oldN) / newN;
540 cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN;
541 cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down';
542 }
543 this.syncClusterMembers(cluster);
544 return true;
545};
546
547GameCore.prototype.catchFallingOntoCluster = function (cluster, members)
548{
549 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
550 { return; }
551 // Snapshot falling blocks; attaching mutates state.
552 var falling = [];
553 for (var i = 0; i < this.blocks.length; i++)
554 {
555 if (this.blocks[i].state === STATE_FALLING)
556 { falling.push(this.blocks[i]); }
557 }
558 for (var i = 0; i < falling.length; i++)
559 {
560 var block = falling[i];
561 var flyer = null;
562 for (var m = 0; m < members.length; m++)
563 {
564 var other = members[m];
565 if (other.col !== block.col)
566 { continue; }
567 // Overlap or rest on this member's top.
568 if (block.y < other.y + 1 + 1e-9 && block.y + 1 > other.y - 1e-9)
569 {
570 if (!flyer || other.y > flyer.y)
571 { flyer = other; }
572 }
573 }
574 if (flyer)
575 { this.attachToFlyingCluster(block, flyer); }
576 }
577};
578
579GameCore.prototype.tick = function (dt)
580{
581 if (this.state === 'gameover')
582 {
583 this.gameOverTime += Math.max(0, dt);
584 return;
585 }
586 if (dt <= 0)
587 { return; }
588 dt = Math.min(dt, 0.1);
589
590 this.spawnTimer += dt;
591 while (this.spawnTimer >= this.spawnInterval)
592 {
593 this.spawnTimer -= this.spawnInterval;
594 this.trySpawn();
595 }
596
597 var left = dt;
598 while (left > 1e-12)
599 {
600 var step = Math.min(SUBSTEP, left);
601 this.snapshotPrevY();
602 this.integrateFalling(step);
603 this.resolveFlyingMatches();
604 this.integrateClusters(step);
605 this.mergeFlyingClusters();
606 this.integrateManual(step);
607 this.mergeAnyManualFallingOverlaps();
608 this.resolveAirborneCollisions();
609 this.cullOffTop();
610 left -= step;
611 }
612
613 this.releaseUnsupported();
614 this.advanceSettle(dt);
615 // After a landed grey group is released, blocks that were sitting on
616 // hanging members are still STILL (the earlier pass ran while those
617 // members counted as support). Drop them from rest before matching,
618 // so they cannot form a mid-air match and shoot off the top.
619 this.releaseUnsupported();
620 this.advanceBounces(dt);
621 if (!this.drag)
622 { this.resolveMatches(); }
623 this.checkLocks();
624 this.checkGameOver();
625 this.assertInvariants('tick');
626};
627
628/** Step a stretch of time in fixed substeps. Useful for tests. */
629GameCore.prototype.step = function (seconds, dt)
630{
631 dt = dt || SUBSTEP;
632 var t = 0;
633 while (t < seconds - 1e-15)
634 {
635 var s = Math.min(dt, seconds - t);
636 this.tick(s);
637 t += s;
638 }
639};
640
641/** Share of the field height a rising stack must pass (t1184). */
642GameCore.DEPART_SHARE = 0.75;
643
644/**
645 * Columns with a rising rocket stack that will certainly leave the
646 * screen (t1184). A flying cluster counts when it is still going up,
647 * its highest block is past DEPART_SHARE of the field height, its apex
648 * (y + vy^2 / (2 * decel)) is at or above the top, and nothing grounded
649 * hangs above it in its columns. Every column that stack occupies is
650 * departing: newly spawned blocks and received garbage pick another
651 * column (t1185/t1186). Returns { col: true }.
652 */
653GameCore.prototype.departingColumns = function ()
654{
655 var out = Object.create(null);
656 var H = this.height;
657 var ids = Object.keys(this.clusters);
658 for (var n = 0; n < ids.length; n++)
659 {
660 var cluster = this.clusters[ids[n]];
661 if (!cluster || cluster.phase !== 'up' || !(cluster.vy > 1e-9))
662 { continue; }
663 var members = this.clusterMembers(cluster.id);
664 if (!members.length)
665 { continue; }
666 var top = -Infinity;
667 var lowest = Object.create(null);
668 for (var i = 0; i < members.length; i++)
669 {
670 var m = members[i];
671 if (m.state !== STATE_FLYING)
672 { continue; }
673 if (m.y > top)
674 { top = m.y; }
675 if (lowest[m.col] == null || m.y < lowest[m.col])
676 { lowest[m.col] = m.y; }
677 }
678 if (top < this.DEPART_LINE())
679 { continue; }
680 var decel = cluster.decel || 0;
681 var rise = decel > 1e-12 ? (cluster.vy * cluster.vy) / (2 * decel) : Infinity;
682 if (top + rise < H - 1e-9)
683 { continue; }
684 var blocked = false;
685 for (var col in lowest)
686 {
687 var c = col | 0;
688 for (var j = 0; j < this.blocks.length; j++)
689 {
690 var b = this.blocks[j];
691 if (b.col === c && b.clusterId !== cluster.id && this.isGrounded(b) && b.y > lowest[col])
692 {
693 blocked = true;
694 break;
695 }
696 }
697 if (blocked)
698 { break; }
699 }
700 if (blocked)
701 { continue; }
702 // t1185/t1186: every column the departing stack occupies is off
703 // limits; new and received blocks pick another column.
704 for (var col2 in lowest)
705 { out[col2 | 0] = true; }
706 }
707 return out;
708};
709
710/** Height (tiles from the ground) a rising stack must pass: 75% of the field. */
711GameCore.prototype.DEPART_LINE = function ()
712{
713 return this.height * GameCore.DEPART_SHARE;
714};
715
716GameCore.prototype.trySpawn = function ()
717{
718 if (this.state !== 'playing')
719 { return null; }
720 var eligible = [];
721 var departing = this.departingColumns();
722 for (var col = 0; col < this.width; col++)
723 {
724 if (this.isColumnLocked(col))
725 { continue; }
726 if (this.groundedCount(col) >= this.height)
727 { continue; }
728 // t1184: never drop a new block onto a stack that is leaving.
729 if (departing[col])
730 { continue; }
731 var alreadyFalling = false;
732 var list = this.blocksInColumn(col);
733 for (var i = 0; i < list.length; i++)
734 {
735 if (list[i].state === STATE_FALLING)
736 {
737 alreadyFalling = true;
738 break;
739 }
740 }
741 if (!alreadyFalling)
742 { eligible.push(col); }
743 }
744 if (!eligible.length)
745 { return null; }
746 var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
747 var color = this.randomColor();
748 var block = this.createBlock(col, this.height, color, STATE_FALLING);
749 block.vy = -this.planet.fallSpeed;
750 this.speedUpSpawning();
751 return block;
752};
753
754/** Each spawned block shrinks the spawn interval by 0.3% (t1187 / t1188). */
755GameCore.SPAWN_SPEEDUP = 0.997;
756/** The spawn interval never goes below this (seconds, t1187). */
757GameCore.SPAWN_INTERVAL_MIN = 0.1;
758
759/**
760 * After every real spawn: spawnInterval *= SPAWN_SPEEDUP, floored at
761 * SPAWN_INTERVAL_MIN. Starts at PlanetMod.SPAWN_INTERVAL (1 s) for every
762 * new core, i.e. every game and every round, for players and bots alike.
763 * Reaches the floor after ~767 spawns (~5 min of continuous play).
764 */
765GameCore.prototype.speedUpSpawning = function ()
766{
767 var next = this.spawnInterval * GameCore.SPAWN_SPEEDUP;
768 this.spawnInterval = Math.max(GameCore.SPAWN_INTERVAL_MIN, next);
769 return this.spawnInterval;
770};
771
772GameCore.prototype.integrateFalling = function (dt)
773{
774 var falling = [];
775 for (var i = 0; i < this.blocks.length; i++)
776 {
777 if (this.blocks[i].state === STATE_FALLING)
778 { falling.push(this.blocks[i]); }
779 }
780 // Lowest first, so a stack of falling blocks rests on itself.
781 falling.sort(function (a, b) { return a.y - b.y; });
782 for (var i = 0; i < falling.length; i++)
783 {
784 var block = falling[i];
785 if (block.state !== STATE_FALLING)
786 { continue; }
787 this.accelerateFall(block, dt);
788 var nextY = block.y + block.vy * dt;
789 var manual = this.manualInColumnHit(block, block.y, nextY);
790 if (manual)
791 {
792 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
793 continue;
794 }
795 var flyer = this.highestFlyingBelow(block);
796 if (flyer && nextY <= flyer.y + 1 + 1e-9)
797 {
798 if (this.attachToFlyingCluster(block, flyer))
799 { continue; }
800 }
801 var top = this.stackTop(block.col, null, block.y);
802 var below = this.highestFallingBelow(block);
803 if (below && below.y + 1 > top)
804 { top = below.y + 1; }
805 if (nextY <= top)
806 {
807 block.y = top;
808 this.landFallingBlock(block);
809 }
810 else
811 { block.y = nextY; }
812 }
813};
814
815GameCore.prototype.clusterMembers = function (clusterId)
816{
817 var out = [];
818 for (var i = 0; i < this.blocks.length; i++)
819 {
820 if (this.blocks[i].clusterId === clusterId)
821 { out.push(this.blocks[i]); }
822 }
823 return out;
824};
825
826
827/**
828 * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a
829 * jump of height H peaks at exactly H after riseTime. Returns dy.
830 * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the
831 * upward deceleration. After the apex, vy eases from 0 to the
832 * terminal descent speed at the matching accel, then stays there.
833 * Flying clusters (forCluster) use the halved cluster float-down
834 * (t1122 / t1124); manual jumps use the full single-block fallSpeed.
835 */
836GameCore.prototype.descentParams = function (forCluster)
837{
838 var p = this.planet;
839 if (forCluster)
840 {
841 return {
842 fallSpeed: p.clusterFallSpeed,
843 fallAccel: p.clusterFallAccel
844 };
845 }
846 return { fallSpeed: p.fallSpeed, fallAccel: p.fallAccel };
847};
848
849GameCore.prototype.advanceJump = function (body, dt, forCluster)
850{
851 var dy = 0;
852 var left = dt;
853 if (body.phase === 'up')
854 {
855 var decel = body.decel;
856 var vy = body.vy;
857 var tApex = decel > 1e-12 ? vy / decel : Infinity;
858 if (tApex <= left + 1e-15)
859 {
860 dy += vy * tApex - 0.5 * decel * tApex * tApex;
861 body.vy = 0;
862 body.phase = 'down';
863 left -= tApex;
864 }
865 else
866 {
867 var vyNew = vy - decel * left;
868 dy += (vy + vyNew) * 0.5 * left;
869 body.vy = vyNew;
870 left = 0;
871 }
872 }
873 if (body.phase === 'up' && body.vy <= 1e-10)
874 {
875 body.vy = 0;
876 body.phase = 'down';
877 }
878 if (body.phase === 'down' && left > 0)
879 {
880 var desc = this.descentParams(forCluster);
881 var target = -desc.fallSpeed;
882 var accel = desc.fallAccel;
883 if (accel < 1e-12)
884 {
885 body.vy = target;
886 dy += body.vy * left;
887 }
888 else if (body.vy > target + 1e-12)
889 {
890 var tReach = (body.vy - target) / accel;
891 if (tReach <= left + 1e-15)
892 {
893 dy += (body.vy + target) * 0.5 * tReach;
894 body.vy = target;
895 left -= tReach;
896 dy += body.vy * left;
897 }
898 else
899 {
900 var vyNew = body.vy - accel * left;
901 dy += (body.vy + vyNew) * 0.5 * left;
902 body.vy = vyNew;
903 }
904 }
905 else
906 {
907 body.vy = target;
908 dy += body.vy * left;
909 }
910 }
911 return dy;
912};
913
914GameCore.prototype.integrateClusters = function (dt)
915{
916 var ids = Object.keys(this.clusters);
917 for (var n = 0; n < ids.length; n++)
918 {
919 var cluster = this.clusters[ids[n]];
920 if (!cluster)
921 { continue; }
922 var members = this.clusterMembers(cluster.id);
923 if (!members.length)
924 {
925 delete this.clusters[cluster.id];
926 continue;
927 }
928 if (cluster.phase === 'landed' || cluster.phase === 'hold')
929 { continue; }
930
931 this.prepareClusterBody(cluster);
932 var dy = this.advanceJump(cluster, dt, true);
933 cluster.anchorY += dy;
934 this.syncClusterMembers(cluster);
935
936 this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id));
937 this.checkChainRelaunch(cluster);
938
939 if (cluster.phase === 'down' && this.clusters[cluster.id])
940 { this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }
941 }
942};
943
944
945/**
946 * If two or more flying clusters overlap in the same column, merge them
947 * into one cluster. Velocity (and deceleration and jumpHeight) is the
948 * mass-weighted average by block count. Phase is 'up' when the merged
949 * vy is positive, otherwise 'down'. Overlapping members in a column
950 * are packed so the higher one sits flush on the lower.
951 */
952GameCore.prototype.mergeFlyingClusters = function ()
953{
954 var flying = [];
955 var ids = Object.keys(this.clusters);
956 for (var n = 0; n < ids.length; n++)
957 {
958 var cluster = this.clusters[ids[n]];
959 if (!cluster)
960 { continue; }
961 if (cluster.phase === 'landed' || cluster.phase === 'hold')
962 { continue; }
963 flying.push(cluster);
964 }
965 if (flying.length < 2)
966 { return; }
967
968 var uf = new UnionFind();
969 for (var i = 0; i < flying.length; i++)
970 { uf.add(flying[i].id); }
971 for (var i = 0; i < flying.length; i++)
972 {
973 for (var j = i + 1; j < flying.length; j++)
974 {
975 if (this.flyingClustersOverlap(flying[i], flying[j]))
976 { uf.union(flying[i].id, flying[j].id); }
977 }
978 }
979
980 var groups = Object.create(null);
981 for (var i = 0; i < flying.length; i++)
982 {
983 var root = uf.find(flying[i].id);
984 if (!groups[root])
985 { groups[root] = []; }
986 groups[root].push(flying[i]);
987 }
988 for (var root in groups)
989 {
990 if (groups[root].length >= 2)
991 { this.mergeClusterGroup(groups[root]); }
992 }
993};
994
995GameCore.prototype.flyingClustersOverlap = function (a, b)
996{
997 var ma = this.clusterMembers(a.id);
998 var mb = this.clusterMembers(b.id);
999 for (var i = 0; i < ma.length; i++)
1000 {
1001 for (var j = 0; j < mb.length; j++)
1002 {
1003 if (ma[i].col !== mb[j].col)
1004 { continue; }
1005 if (this.sweptIntervalsOverlap(ma[i], mb[j]))
1006 { return true; }
1007 }
1008 }
1009 return false;
1010};
1011
1012/**
1013 * Swept [y, y+1) of two blocks this substep, using _prevY when present.
1014 * Catches pairs that crossed without sharing a cell at either endpoint.
1015 */
1016GameCore.prototype.sweptIntervalsOverlap = function (a, b)
1017{
1018 var a0 = (a._prevY != null) ? a._prevY : a.y;
1019 var a1 = a.y;
1020 var b0 = (b._prevY != null) ? b._prevY : b.y;
1021 var b1 = b.y;
1022 var aLo = Math.min(a0, a1);
1023 var aHi = Math.max(a0, a1) + 1;
1024 var bLo = Math.min(b0, b1);
1025 var bHi = Math.max(b0, b1) + 1;
1026 return aLo < bHi - 1e-9 && bLo < aHi - 1e-9;
1027};
1028
1029GameCore.prototype.mergeClusterGroup = function (clusters)
1030{
1031 clusters.sort(function (a, b) { return a.id - b.id; });
1032 var keep = clusters[0];
1033 var n = 0;
1034 var vySum = 0;
1035 var decelSum = 0;
1036 var hSum = 0;
1037 for (var c = 0; c < clusters.length; c++)
1038 {
1039 var mem = this.clusterMembers(clusters[c].id);
1040 var m = mem.length;
1041 n += m;
1042 vySum += clusters[c].vy * m;
1043 decelSum += (clusters[c].decel || 0) * m;
1044 hSum += (clusters[c].jumpHeight || 0) * m;
1045 }
1046 if (n === 0)
1047 { return; }
1048 keep.vy = vySum / n;
1049 keep.decel = decelSum / n;
1050 keep.jumpHeight = hSum / n;
1051 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
1052 var maxChain = 0;
1053 for (var c = 0; c < clusters.length; c++)
1054 {
1055 var ch = clusters[c].landingChain || 0;
1056 if (ch > maxChain)
1057 { maxChain = ch; }
1058 }
1059 keep.landingChain = maxChain;
1060 for (var c = 0; c < clusters.length; c++)
1061 {
1062 var mem = this.clusterMembers(clusters[c].id);
1063 for (var i = 0; i < mem.length; i++)
1064 {
1065 mem[i].clusterId = keep.id;
1066 mem[i].vy = keep.vy;
1067 mem[i].state = STATE_FLYING;
1068 }
1069 if (clusters[c] !== keep)
1070 { delete this.clusters[clusters[c].id]; }
1071 }
1072 this.prepareClusterBody(keep);
1073 this.checkChainRelaunch(keep);
1074 if (keep.phase === 'down' && this.clusters[keep.id])
1075 { this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
1076};
1077
1078GameCore.prototype.packClusterOverlaps = function (cluster)
1079{
1080 var members = this.clusterMembers(cluster.id);
1081 var byCol = Object.create(null);
1082 for (var i = 0; i < members.length; i++)
1083 {
1084 var col = members[i].col;
1085 if (!byCol[col])
1086 { byCol[col] = []; }
1087 byCol[col].push(members[i]);
1088 }
1089 var cols = Object.keys(byCol);
1090 for (var c = 0; c < cols.length; c++)
1091 {
1092 var list = byCol[cols[c]];
1093 list.sort(function (a, b) { return a.y - b.y; });
1094 for (var i = 1; i < list.length; i++)
1095 {
1096 var minY = list[i - 1].y + 1;
1097 if (list[i].y < minY - 1e-12)
1098 { list[i].y = minY; }
1099 }
1100 }
1101};
1102
1103
1104/**
1105 * Derive integer cell offsets from current member positions and a
1106 * single anchorY, packing overlaps in each column while preserving
1107 * order (lower y stays lower; ties break on id). Then sync.
1108 * Flying clusters are one rigid body: one y, one vy, integer offsets.
1109 */
1110GameCore.prototype.prepareClusterBody = function (cluster)
1111{
1112 if (!cluster)
1113 { return; }
1114 var members = this.clusterMembers(cluster.id);
1115 if (!members.length)
1116 { return; }
1117 this.rebuildClusterOffsets(cluster, members);
1118};
1119
1120GameCore.prototype.rebuildClusterOffsets = function (cluster, members)
1121{
1122 members = members || this.clusterMembers(cluster.id);
1123 if (!members.length)
1124 { return; }
1125 var byCol = Object.create(null);
1126 for (var i = 0; i < members.length; i++)
1127 {
1128 var col = members[i].col;
1129 if (!byCol[col])
1130 { byCol[col] = []; }
1131 byCol[col].push(members[i]);
1132 }
1133 var minY = Infinity;
1134 for (var i = 0; i < members.length; i++)
1135 {
1136 if (members[i].y < minY)
1137 { minY = members[i].y; }
1138 }
1139 if (cluster.anchorY == null || !isFinite(cluster.anchorY))
1140 { cluster.anchorY = minY; }
1141 var cols = Object.keys(byCol);
1142 for (var c = 0; c < cols.length; c++)
1143 {
1144 var list = byCol[cols[c]];
1145 list.sort(function (a, b)
1146 {
1147 if (a.y !== b.y)
1148 { return a.y - b.y; }
1149 return a.id - b.id;
1150 });
1151 var prevOff = -Infinity;
1152 for (var i = 0; i < list.length; i++)
1153 {
1154 var off = Math.round(list[i].y - cluster.anchorY);
1155 if (off <= prevOff)
1156 { off = prevOff + 1; }
1157 list[i].clusterOffset = off;
1158 prevOff = off;
1159 }
1160 }
1161 // Re-base so the lowest offset is 0, keeping relative integers.
1162 var minOff = Infinity;
1163 for (var i = 0; i < members.length; i++)
1164 {
1165 if (members[i].clusterOffset < minOff)
1166 { minOff = members[i].clusterOffset; }
1167 }
1168 if (minOff !== 0 && isFinite(minOff))
1169 {
1170 cluster.anchorY += minOff;
1171 for (var i = 0; i < members.length; i++)
1172 { members[i].clusterOffset -= minOff; }
1173 }
1174 this.syncClusterMembers(cluster);
1175};
1176
1177GameCore.prototype.syncClusterMembers = function (cluster)
1178{
1179 if (!cluster)
1180 { return; }
1181 var members = this.clusterMembers(cluster.id);
1182 if (cluster.anchorY == null)
1183 {
1184 var minY = Infinity;
1185 for (var i = 0; i < members.length; i++)
1186 {
1187 if (members[i].y < minY)
1188 { minY = members[i].y; }
1189 }
1190 cluster.anchorY = isFinite(minY) ? minY : 0;
1191 }
1192 for (var i = 0; i < members.length; i++)
1193 {
1194 var block = members[i];
1195 if (block.clusterOffset == null)
1196 { block.clusterOffset = Math.round(block.y - cluster.anchorY); }
1197 block.y = cluster.anchorY + block.clusterOffset;
1198 if (cluster.phase !== 'landed')
1199 { block.vy = cluster.vy; }
1200 }
1201};
1202
1203GameCore.prototype.snapshotPrevY = function ()
1204{
1205 for (var i = 0; i < this.blocks.length; i++)
1206 { this.blocks[i]._prevY = this.blocks[i].y; }
1207};
1208
1209/**
1210 * Safety net after the specific integrates: any remaining mid-air
1211 * overlap or swept crossing is resolved with the same rules, then
1212 * every flying cluster is rebuilt as a rigid body. Repeats a few
1213 * times because one attach can create a new contact.
1214 */
1215GameCore.prototype.resolveAirborneCollisions = function ()
1216{
1217 var guard = 0;
1218 while (guard++ < this.height + 4)
1219 {
1220 var changed = false;
1221
1222 // Manual vs falling / cluster / manual.
1223 var manuals = [];
1224 for (var i = 0; i < this.blocks.length; i++)
1225 {
1226 if (this.blocks[i].state === STATE_MANUAL)
1227 { manuals.push(this.blocks[i]); }
1228 }
1229 manuals.sort(function (a, b) { return b.y - a.y; });
1230 for (var m = 0; m < manuals.length; m++)
1231 {
1232 var manual = manuals[m];
1233 if (manual.state !== STATE_MANUAL)
1234 { continue; }
1235 var oldY = (manual._prevY != null) ? manual._prevY : manual.y;
1236 if (this.resolveManualCollisions(manual, oldY, manual.y))
1237 { changed = true; }
1238 }
1239
1240 // Falling vs flying (sit on the roof).
1241 for (var i = 0; i < this.blocks.length; i++)
1242 {
1243 var block = this.blocks[i];
1244 if (block.state !== STATE_FALLING)
1245 { continue; }
1246 var flyer = this.highestFlyingBelow(block);
1247 if (!flyer)
1248 {
1249 // Also a flyer whose swept path crosses this falling block.
1250 flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y);
1251 }
1252 if (flyer && this.sweptIntervalsOverlap(block, flyer))
1253 {
1254 if (this.attachToFlyingCluster(block, flyer))
1255 { changed = true; }
1256 }
1257 }
1258
1259 // Cluster vs cluster (swept, including after a column push).
1260 var before = Object.keys(this.clusters).length;
1261 this.mergeFlyingClusters();
1262 if (Object.keys(this.clusters).length !== before)
1263 { changed = true; }
1264
1265 // Rebuild every flying body so offsets stay integer and unique.
1266 var ids = Object.keys(this.clusters);
1267 for (var n = 0; n < ids.length; n++)
1268 {
1269 var cluster = this.clusters[ids[n]];
1270 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1271 { continue; }
1272 this.prepareClusterBody(cluster);
1273 }
1274
1275 if (!changed)
1276 { break; }
1277 }
1278};
1279
1280/**
1281 * Invariant checker (t1112). No two blocks occupy the same cell or
1282 * overlap their [y, y+1) intervals. Flying-cluster members are
1283 * grid-aligned to a single anchor. Returns a list of violation
1284 * strings (empty if clean).
1285 */
1286GameCore.prototype.checkInvariants = function ()
1287{
1288 var issues = [];
1289 var byCol = Object.create(null);
1290 var ids = Object.create(null);
1291 for (var i = 0; i < this.blocks.length; i++)
1292 {
1293 var block = this.blocks[i];
1294 if (ids[block.id])
1295 { issues.push('duplicate id ' + block.id); }
1296 ids[block.id] = true;
1297 if (!byCol[block.col])
1298 { byCol[block.col] = []; }
1299 byCol[block.col].push(block);
1300 if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet
1301 && block.color >= this.planet.colors.length))
1302 { issues.push('block ' + block.id + ' has invalid color ' + block.color); }
1303 }
1304 var cols = Object.keys(byCol);
1305 for (var c = 0; c < cols.length; c++)
1306 {
1307 var list = byCol[cols[c]];
1308 list.sort(function (a, b)
1309 {
1310 if (a.y !== b.y)
1311 { return a.y - b.y; }
1312 return a.id - b.id;
1313 });
1314 for (var i = 0; i < list.length; i++)
1315 {
1316 var a = list[i];
1317 if (i > 0)
1318 {
1319 var prev = list[i - 1];
1320 if (a.y < prev.y + 1 - 1e-6)
1321 {
1322 issues.push('overlap col=' + a.col
1323 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)
1324 + ' gap=' + (a.y - prev.y));
1325 }
1326 var cellA = Math.floor(a.y + 1e-9);
1327 var cellP = Math.floor(prev.y + 1e-9);
1328 if (cellA === cellP)
1329 {
1330 issues.push('duplicate cell col=' + a.col + ' row=' + cellA
1331 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a));
1332 }
1333 }
1334 }
1335 }
1336 var cids = Object.keys(this.clusters);
1337 for (var n = 0; n < cids.length; n++)
1338 {
1339 var cluster = this.clusters[cids[n]];
1340 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1341 { continue; }
1342 var mem = this.clusterMembers(cluster.id);
1343 var seenOff = Object.create(null);
1344 for (var i = 0; i < mem.length; i++)
1345 {
1346 var b = mem[i];
1347 if (cluster.anchorY != null && b.clusterOffset != null)
1348 {
1349 var expected = cluster.anchorY + b.clusterOffset;
1350 if (Math.abs(b.y - expected) > 1e-6)
1351 {
1352 issues.push('cluster ' + cluster.id + ' member ' + b.id
1353 + ' y=' + b.y + ' != anchor+off ' + expected);
1354 }
1355 if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9)
1356 {
1357 issues.push('cluster ' + cluster.id + ' member ' + b.id
1358 + ' non-integer offset ' + b.clusterOffset);
1359 }
1360 var key = b.col + ':' + b.clusterOffset;
1361 if (seenOff[key])
1362 {
1363 issues.push('cluster ' + cluster.id + ' duplicate offset ' + key);
1364 }
1365 seenOff[key] = true;
1366 }
1367 }
1368 }
1369 return issues;
1370};
1371
1372GameCore.prototype._invBlock = function (b)
1373{
1374 return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y='
1375 + (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')';
1376};
1377
1378GameCore.prototype.assertInvariants = function (label)
1379{
1380 if (!this.strictInvariants && !this.debugInvariants)
1381 { return; }
1382 var issues = this.checkInvariants();
1383 this.lastInvariantViolations = issues;
1384 if (!issues.length)
1385 { return; }
1386 var msg = 'physics invariants failed'
1387 + (label ? ' at ' + label : '')
1388 + ':\n ' + issues.join('\n ')
1389 + '\n' + (this.snapshot ? this.snapshot().picture : '');
1390 if (this.strictInvariants)
1391 { throw new Error(msg); }
1392};
1393
1394GameCore.prototype.tryLandCluster = function (cluster, members)
1395{
1396 if (!members.length)
1397 { return; }
1398 var shift = 0;
1399 var hit = false;
1400 for (var i = 0; i < members.length; i++)
1401 {
1402 var block = members[i];
1403 var top = this.stackTop(block.col, function (other)
1404 {
1405 return other.clusterId === cluster.id;
1406 }, block.y);
1407 if (block.y <= top + 1e-9)
1408 {
1409 hit = true;
1410 var need = top - block.y;
1411 if (need > shift)
1412 { shift = need; }
1413 }
1414 }
1415 if (!hit)
1416 { return; }
1417 // Lift the whole rigid body so the deepest contact sits flush.
1418 this.prepareClusterBody(cluster);
1419 cluster.anchorY += shift;
1420 this.syncClusterMembers(cluster);
1421 this.landCluster(cluster, this.clusterMembers(cluster.id));
1422};
1423
1424/**
1425 * Land as a rigid group: relative positions are kept, so part of the
1426 * cluster may hang above a gap. Grey members start the 3s settle timer;
1427 * coloured cargo stays put with them until every grey has recolored.
1428 * Members that actually rest on the floor or on another block bounce.
1429 */
1430GameCore.prototype.landCluster = function (cluster, members)
1431{
1432 for (var i = 0; i < members.length; i++)
1433 {
1434 var block = members[i];
1435 block.vy = 0;
1436 block.flame = false;
1437 block.clusterId = cluster.id;
1438 if (block.color === COLOR_GRAY)
1439 {
1440 block.state = STATE_SETTLING;
1441 block.settleTime = 0;
1442 }
1443 else
1444 {
1445 // Cargo stays in the rigid group (not matchable) until release.
1446 block.state = STATE_SETTLING;
1447 block.settleTime = 0;
1448 }
1449 if (this.hasSupport(block))
1450 { this.startBounce(block); }
1451 }
1452 cluster.phase = 'landed';
1453 cluster.vy = 0;
1454 cluster.landedPending = true;
1455 if (cluster.landingChain == null)
1456 { cluster.landingChain = 0; }
1457};
1458
1459/**
1460 * After every grey in a landed cluster has recolored, let the group go.
1461 * Unsupported blocks fall individually from rest; supported ones stay.
1462 */
1463GameCore.prototype.releaseLandedCluster = function (cluster)
1464{
1465 var members = this.clusterMembers(cluster.id);
1466 var releasing = Object.create(null);
1467 for (var i = 0; i < members.length; i++)
1468 { releasing[members[i].id] = true; }
1469
1470 for (var i = 0; i < members.length; i++)
1471 {
1472 var block = members[i];
1473 if (block.color === COLOR_GRAY)
1474 {
1475 block.color = this.randomColor();
1476 block.settleTime = 0;
1477 }
1478 // Persist the chain across release so a post-recolor match in
1479 // this same tick still gets the landing bonus (t1120).
1480 block.justLanded = !!cluster.landedPending;
1481 block.landingChain = cluster.landingChain || 0;
1482 this.leaveCluster(block);
1483 // Always drop leftover launch / manual velocity. A stale upward
1484 // vy here is what sends blocks off the top "very fast" after
1485 // a grey group recolors.
1486 this.clearFlightState(block);
1487 // Support from outside the group (floor or a foreign block). Fellow
1488 // members that will also fall do not count, so a hanging stack
1489 // drops together without the top one staying put.
1490 var supported = this.hasSupportOutside(block, releasing);
1491 block.state = supported ? STATE_STILL : STATE_FALLING;
1492 }
1493 delete this.clusters[cluster.id];
1494};
1495
1496GameCore.prototype.hasSupportOutside = function (block, ignoreIds)
1497{
1498 if (block.y <= 1e-9)
1499 { return true; }
1500 for (var i = 0; i < this.blocks.length; i++)
1501 {
1502 var other = this.blocks[i];
1503 if (other === block || other.col !== block.col)
1504 { continue; }
1505 if (ignoreIds && ignoreIds[other.id])
1506 { continue; }
1507 if (!this.isGrounded(other))
1508 { continue; }
1509 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
1510 { return true; }
1511 }
1512 return false;
1513};
1514
1515GameCore.prototype.integrateManual = function (dt)
1516{
1517 for (var i = 0; i < this.blocks.length; i++)
1518 {
1519 var block = this.blocks[i];
1520 if (block.state !== STATE_MANUAL)
1521 { continue; }
1522
1523 if (block.manualPhase === 'up')
1524 {
1525 var oldY = block.y;
1526 var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
1527 var dy = this.advanceJump(proxy, dt);
1528 var nextY = oldY + dy;
1529 block.vy = proxy.vy;
1530 block.manualPhase = proxy.phase;
1531 if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget)))
1532 { continue; }
1533 block.y = Math.min(nextY, block.manualTarget);
1534 if (block.y >= block.manualTarget - 1e-12)
1535 {
1536 block.y = block.manualTarget;
1537 block.vy = 0;
1538 block.manualPhase = 'down';
1539 }
1540 if (block.y > this.height - 1)
1541 {
1542 block.y = this.height - 1;
1543 block.vy = 0;
1544 block.manualPhase = 'down';
1545 }
1546 }
1547
1548 if (block.manualPhase === 'down')
1549 {
1550 var proxy = { phase: 'down', vy: block.vy, decel: 0 };
1551 var dy = this.advanceJump(proxy, dt);
1552 block.vy = proxy.vy;
1553 var nextY = block.y + dy;
1554 var top = this.stackTop(block.col, null, block.y);
1555 if (nextY <= top)
1556 {
1557 block.y = top;
1558 block.state = STATE_STILL;
1559 block.vy = 0;
1560 block.manualPhase = null;
1561 block.flame = false;
1562 this.startBounce(block);
1563 }
1564 else
1565 {
1566 var downNext = Math.min(nextY, this.height - 1);
1567 if (this.resolveManualCollisions(block, block.y, downNext))
1568 { continue; }
1569 block.y = downNext;
1570 }
1571 }
1572 }
1573};
1574
1575/**
1576 * If the manual throw (or its path this step) hits falling blocks, merge
1577 * them into a flying cluster with mass-weighted velocity, the same rule
1578 * as two flying clusters colliding (t1108). Returns true if merged.
1579 */
1580GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
1581{
1582 if (!manual || manual.state !== STATE_MANUAL)
1583 { return false; }
1584 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
1585 if (!hits.length)
1586 { return false; }
1587 this.mergeManualWithFalling(manual, hits);
1588 return true;
1589};
1590
1591GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
1592{
1593 var lo = Math.min(oldY, newY);
1594 var hi = Math.max(oldY, newY) + 1;
1595 for (var i = 0; i < this.blocks.length; i++)
1596 {
1597 var other = this.blocks[i];
1598 if (other === falling || other.col !== falling.col)
1599 { continue; }
1600 if (other.state !== STATE_MANUAL)
1601 { continue; }
1602 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1603 { return other; }
1604 }
1605 return null;
1606};
1607
1608GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
1609{
1610 var lo = Math.min(oldY, newY);
1611 var hi = Math.max(oldY, newY) + 1;
1612 var hits = [];
1613 for (var i = 0; i < this.blocks.length; i++)
1614 {
1615 var other = this.blocks[i];
1616 if (other === manual || other.col !== manual.col)
1617 { continue; }
1618 if (other.state !== STATE_FALLING)
1619 { continue; }
1620 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1621 { hits.push(other); }
1622 }
1623 if (!hits.length)
1624 { return hits; }
1625 return this.contiguousFallingInColumn(manual.col, manual, hits);
1626};
1627
1628/**
1629 * Every falling block in `col` that overlaps `anchor` or a hit already
1630 * in `seed`, plus a contiguous falling stack sitting on them.
1631 */
1632GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
1633{
1634 var falling = [];
1635 for (var i = 0; i < this.blocks.length; i++)
1636 {
1637 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
1638 { falling.push(this.blocks[i]); }
1639 }
1640 falling.sort(function (a, b) { return a.y - b.y; });
1641 var include = Object.create(null);
1642 var queue = [];
1643 function enqueue (b)
1644 {
1645 if (!b || include[b.id])
1646 { return; }
1647 include[b.id] = true;
1648 queue.push(b);
1649 }
1650 if (seed)
1651 {
1652 for (var s = 0; s < seed.length; s++)
1653 { enqueue(seed[s]); }
1654 }
1655 // Also include falling that already overlap the anchor.
1656 if (anchor)
1657 {
1658 for (var i = 0; i < falling.length; i++)
1659 {
1660 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
1661 { enqueue(falling[i]); }
1662 }
1663 }
1664 for (var q = 0; q < queue.length; q++)
1665 {
1666 var a = queue[q];
1667 for (var i = 0; i < falling.length; i++)
1668 {
1669 var b = falling[i];
1670 if (include[b.id])
1671 { continue; }
1672 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
1673 { enqueue(b); }
1674 }
1675 }
1676 var out = [];
1677 for (var i = 0; i < falling.length; i++)
1678 {
1679 if (include[falling[i].id])
1680 { out.push(falling[i]); }
1681 }
1682 return out;
1683};
1684
1685/**
1686 * Merge a thrown (manual) block with falling blocks into one flying
1687 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
1688 * averages by block count, identical to mergeClusterGroup. The thrown
1689 * block stops being manual and the group follows normal cluster physics.
1690 * fromManual marks the cluster so later falling cargo also averages in.
1691 */
1692GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
1693{
1694 if (!manual || manual.state !== STATE_MANUAL)
1695 { return null; }
1696 var blocks = [manual];
1697 for (var i = 0; i < fallingList.length; i++)
1698 {
1699 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
1700 { blocks.push(fallingList[i]); }
1701 }
1702 if (blocks.length < 2)
1703 { return null; }
1704 var n = blocks.length;
1705 var vySum = 0;
1706 var decelSum = 0;
1707 var hSum = 0;
1708 for (var i = 0; i < n; i++)
1709 {
1710 var b = blocks[i];
1711 vySum += b.vy;
1712 if (b === manual)
1713 {
1714 decelSum += manual.manualDecel || 0;
1715 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
1716 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
1717 }
1718 }
1719 var cluster = {
1720 id: this.nextClusterId++,
1721 jumpHeight: hSum / n,
1722 vy: vySum / n,
1723 decel: decelSum / n,
1724 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
1725 fromManual: true
1726 };
1727 this.clusters[cluster.id] = cluster;
1728 for (var i = 0; i < n; i++)
1729 {
1730 var b = blocks[i];
1731 b.clusterId = cluster.id;
1732 b.state = STATE_FLYING;
1733 b.vy = cluster.vy;
1734 b.flame = b.color === COLOR_GRAY;
1735 b.manualPhase = null;
1736 b.manualTarget = null;
1737 b.manualDecel = 0;
1738 b.manualJumpHeight = 0;
1739 b.pushedClusters = null;
1740 b.settleTime = 0;
1741 }
1742 if (this.drag && this.drag.blockId === manual.id)
1743 { this.drag = null; }
1744 this.prepareClusterBody(cluster);
1745 this.checkChainRelaunch(cluster);
1746 return cluster;
1747};
1748
1749/** Safety net: any remaining manual/falling overlaps after the substep. */
1750GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
1751{
1752 var manuals = [];
1753 for (var i = 0; i < this.blocks.length; i++)
1754 {
1755 if (this.blocks[i].state === STATE_MANUAL)
1756 { manuals.push(this.blocks[i]); }
1757 }
1758 for (var m = 0; m < manuals.length; m++)
1759 {
1760 var manual = manuals[m];
1761 if (manual.state !== STATE_MANUAL)
1762 { continue; }
1763 var hits = this.contiguousFallingInColumn(manual.col, manual);
1764 if (hits.length)
1765 { this.mergeManualWithFalling(manual, hits); }
1766 }
1767};
1768
1769/**
1770 * Resolve collisions of a thrown (manual) block along [oldY, nextY].
1771 * Falling blocks merge (t1108). A flying cluster is pushed one cell up
1772 * in the hit column and the shot attaches at the bottom (t1111).
1773 * Another thrown block is promoted to a 1-block cluster and then the
1774 * same attach-at-bottom rule applies. Returns true if `manual` is no
1775 * longer in the MANUAL state.
1776 */
1777GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY)
1778{
1779 if (!manual || manual.state !== STATE_MANUAL)
1780 { return true; }
1781
1782 var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY);
1783 if (fallingHits.length)
1784 {
1785 this.mergeManualWithFalling(manual, fallingHits);
1786 return manual.state !== STATE_MANUAL;
1787 }
1788
1789 var flyer = this.flyingHitOnManualPath(manual, oldY, nextY);
1790 if (flyer)
1791 {
1792 var cluster = this.clusters[flyer.clusterId];
1793 if (cluster && cluster.phase !== 'landed')
1794 {
1795 if (nextY + 1e-12 < oldY)
1796 { this.attachToFlyingCluster(manual, flyer); }
1797 else
1798 { this.attachShotUnderCluster(manual, cluster, manual.col); }
1799 return manual.state !== STATE_MANUAL;
1800 }
1801 }
1802
1803 var other = this.manualHitOnManualPath(manual, oldY, nextY);
1804 if (other)
1805 {
1806 var host = this.promoteManualToCluster(other);
1807 if (host)
1808 {
1809 if (nextY + 1e-12 < oldY)
1810 { this.attachToFlyingCluster(manual, other); }
1811 else
1812 { this.attachShotUnderCluster(manual, host, manual.col); }
1813 return manual.state !== STATE_MANUAL;
1814 }
1815 }
1816 return false;
1817};
1818
1819/** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */
1820GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY)
1821{
1822 var lo = Math.min(oldY, nextY);
1823 var hi = Math.max(oldY, nextY) + 1;
1824 var best = null;
1825 var bestY = Infinity;
1826 for (var i = 0; i < this.blocks.length; i++)
1827 {
1828 var other = this.blocks[i];
1829 if (other === manual || other.col !== manual.col)
1830 { continue; }
1831 if (other.state !== STATE_FLYING || other.clusterId == null)
1832 { continue; }
1833 var cluster = this.clusters[other.clusterId];
1834 if (!cluster || cluster.phase === 'landed')
1835 { continue; }
1836 var o0 = (other._prevY != null) ? other._prevY : other.y;
1837 var o1 = other.y;
1838 var oLo = Math.min(o0, o1);
1839 var oHi = Math.max(o0, o1) + 1;
1840 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
1841 {
1842 if (other.y < bestY)
1843 {
1844 bestY = other.y;
1845 best = other;
1846 }
1847 }
1848 }
1849 return best;
1850};
1851
1852/** Another thrown block in the same column on the path (prefer the lower). */
1853GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY)
1854{
1855 var lo = Math.min(oldY, nextY);
1856 var hi = Math.max(oldY, nextY) + 1;
1857 var best = null;
1858 for (var i = 0; i < this.blocks.length; i++)
1859 {
1860 var other = this.blocks[i];
1861 if (other === manual || other.col !== manual.col)
1862 { continue; }
1863 if (other.state !== STATE_MANUAL)
1864 { continue; }
1865 var o0 = (other._prevY != null) ? other._prevY : other.y;
1866 var o1 = other.y;
1867 var oLo = Math.min(o0, o1);
1868 var oHi = Math.max(o0, o1) + 1;
1869 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
1870 {
1871 if (!best || other.y < best.y)
1872 { best = other; }
1873 }
1874 }
1875 return best;
1876};
1877
1878/**
1879 * t1111: push every member of `cluster` in `col` up by one cell, then
1880 * attach `manual` at the bottom of that column, grid-aligned, as part
1881 * of the cluster. The cluster keeps its velocity; the shot takes it.
1882 * Other columns are untouched. Same rule for every successive shot.
1883 */
1884GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col)
1885{
1886 if (!manual || !cluster || !this.clusters[cluster.id])
1887 { return false; }
1888 if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id)
1889 {
1890 // Already belonging elsewhere: leave first.
1891 if (manual.clusterId != null)
1892 { this.leaveCluster(manual); }
1893 }
1894 this.prepareClusterBody(cluster);
1895 var members = this.clusterMembers(cluster.id);
1896 var minOff = null;
1897 for (var i = 0; i < members.length; i++)
1898 {
1899 if (members[i].col !== col)
1900 { continue; }
1901 if (minOff == null || members[i].clusterOffset < minOff)
1902 { minOff = members[i].clusterOffset; }
1903 }
1904 if (minOff == null)
1905 { minOff = 0; }
1906 else
1907 {
1908 for (var i = 0; i < members.length; i++)
1909 {
1910 if (members[i].col === col)
1911 { members[i].clusterOffset += 1; }
1912 }
1913 }
1914 if (this.drag && this.drag.blockId === manual.id)
1915 { this.drag = null; }
1916 manual.clusterId = cluster.id;
1917 manual.clusterOffset = minOff;
1918 manual.state = STATE_FLYING;
1919 manual.flame = manual.color === COLOR_GRAY;
1920 manual.settleTime = 0;
1921 manual.manualPhase = null;
1922 manual.manualTarget = null;
1923 manual.manualDecel = 0;
1924 manual.manualJumpHeight = 0;
1925 manual.pushedClusters = null;
1926 this.syncClusterMembers(cluster);
1927 this.cullOffTop();
1928 if (this.clusters[cluster.id])
1929 { this.checkChainRelaunch(cluster); }
1930 return true;
1931};
1932
1933/**
1934 * Turn a lone thrown block into a 1-block flying cluster so a later
1935 * shot can use the t1111 attach-at-bottom rule. A single throw stays
1936 * MANUAL (and is capped at the top of the field) until it collides.
1937 */
1938GameCore.prototype.promoteManualToCluster = function (manual)
1939{
1940 if (!manual)
1941 { return null; }
1942 if (manual.state === STATE_FLYING && manual.clusterId != null)
1943 {
1944 var existing = this.clusters[manual.clusterId];
1945 if (existing && existing.phase !== 'landed')
1946 { return existing; }
1947 }
1948 if (manual.state !== STATE_MANUAL)
1949 { return null; }
1950 var height = manual.manualJumpHeight != null ? manual.manualJumpHeight
1951 : Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y);
1952 var cluster = {
1953 id: this.nextClusterId++,
1954 jumpHeight: height,
1955 vy: manual.vy,
1956 decel: manual.manualDecel || 0,
1957 phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up',
1958 fromManual: true,
1959 anchorY: manual.y
1960 };
1961 this.clusters[cluster.id] = cluster;
1962 manual.state = STATE_FLYING;
1963 manual.clusterId = cluster.id;
1964 manual.clusterOffset = 0;
1965 manual.flame = manual.color === COLOR_GRAY;
1966 manual.settleTime = 0;
1967 manual.manualPhase = null;
1968 manual.manualTarget = null;
1969 manual.manualDecel = 0;
1970 manual.manualJumpHeight = 0;
1971 manual.pushedClusters = null;
1972 this.syncClusterMembers(cluster);
1973 return cluster;
1974};
1975
1976/** Kept for older tests / call sites: push a cluster column by one cell. */
1977GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1978{
1979 return this.resolveManualCollisions(manual, oldY, nextY);
1980};
1981
1982
1983/**
1984 * Push every flying block of the cluster that sits in `col` one tile up.
1985 * Other columns stay put (they remain linked). Then look for a new
1986 * same-color line of 3+ in the flying cluster; if there is one, those
1987 * blocks turn gray, join the link, and the whole cluster re-launches
1988 * with the same jump height from its current position.
1989 */
1990GameCore.prototype.pushClusterColumn = function (clusterId, col)
1991{
1992 var cluster = this.clusters[clusterId];
1993 if (!cluster)
1994 { return false; }
1995 var members = this.clusterMembers(clusterId);
1996 for (var i = 0; i < members.length; i++)
1997 {
1998 if (members[i].col === col)
1999 { members[i].y += 1; }
2000 }
2001 this.cullOffTop();
2002 if (!this.clusters[clusterId])
2003 { return true; }
2004 this.checkChainRelaunch(cluster);
2005 return true;
2006};
2007
2008/**
2009 * After a cargo attach or a cluster merge (or any other mid-air state
2010 * change), turn spontaneous lines of 3+ into rockets and give the whole
2011 * already-flying cluster an extra launch from its current position —
2012 * the same re-launch as a player push that completes a row.
2013 */
2014GameCore.prototype.resolveFlyingMatches = function ()
2015{
2016 var ids = Object.keys(this.clusters);
2017 for (var n = 0; n < ids.length; n++)
2018 {
2019 var cluster = this.clusters[ids[n]];
2020 if (!cluster || cluster.phase === 'landed')
2021 { continue; }
2022 this.checkChainRelaunch(cluster);
2023 }
2024};
2025
2026GameCore.prototype.checkChainRelaunch = function (cluster)
2027{
2028 if (!this.clusters[cluster.id])
2029 { return; }
2030 var lines = this.findFlyingMatchLines(cluster.id);
2031 if (!lines.length)
2032 { return; }
2033 var newly = [];
2034 var seen = Object.create(null);
2035 for (var i = 0; i < lines.length; i++)
2036 {
2037 for (var j = 0; j < lines[i].blocks.length; j++)
2038 {
2039 var block = lines[i].blocks[j];
2040 if (seen[block.id])
2041 { continue; }
2042 seen[block.id] = true;
2043 newly.push(block);
2044 }
2045 }
2046 for (var i = 0; i < newly.length; i++)
2047 {
2048 var block = newly[i];
2049 block.color = COLOR_GRAY;
2050 block.flame = true;
2051 block.clusterId = cluster.id;
2052 block.state = STATE_FLYING;
2053 }
2054 this.relaunchCluster(cluster, cluster.jumpHeight);
2055};
2056
2057GameCore.prototype.relaunchCluster = function (cluster, height)
2058{
2059 cluster.jumpHeight = height;
2060 cluster.vy = PlanetMod.launchVelocity(this.planet, height);
2061 cluster.decel = PlanetMod.launchDeceleration(this.planet, height);
2062 cluster.phase = 'up';
2063 var members = this.clusterMembers(cluster.id);
2064 for (var i = 0; i < members.length; i++)
2065 {
2066 members[i].vy = cluster.vy;
2067 members[i].state = STATE_FLYING;
2068 if (members[i].color === COLOR_GRAY)
2069 { members[i].flame = true; }
2070 }
2071};
2072
2073GameCore.prototype.startManualLaunch = function (block)
2074{
2075 var target = this.height - 1;
2076 var height = Math.max(0.05, target - block.y);
2077 this.leaveCluster(block);
2078 block.state = STATE_MANUAL;
2079 block.pushedClusters = Object.create(null);
2080 block.manualTarget = target;
2081 block.manualPhase = 'up';
2082 block.manualJumpHeight = height;
2083 block.vy = PlanetMod.launchVelocity(this.planet, height);
2084 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
2085 block.flame = false;
2086 if (this.drag && this.drag.blockId === block.id)
2087 { this.drag = null; }
2088};
2089
2090GameCore.prototype.cullOffTop = function ()
2091{
2092 var gone = [];
2093 for (var i = 0; i < this.blocks.length; i++)
2094 {
2095 var block = this.blocks[i];
2096 if (block.state === STATE_MANUAL)
2097 {
2098 if (block.y > this.height - 1)
2099 { block.y = this.height - 1; }
2100 continue;
2101 }
2102 if (block.y >= this.height - 1e-9)
2103 { gone.push(block); }
2104 }
2105 for (var i = 0; i < gone.length; i++)
2106 {
2107 var block = gone[i];
2108 this.outgoingShots.push({
2109 id: block.id,
2110 color: block.color,
2111 col: block.col,
2112 y: block.y,
2113 vy: block.vy
2114 });
2115 this.score += 1;
2116 this.removeBlock(block);
2117 }
2118};
2119
2120GameCore.prototype.consumeOutgoingShots = function ()
2121{
2122 var shots = this.outgoingShots;
2123 this.outgoingShots = [];
2124 return shots;
2125};
2126
2127/**
2128 * A compact field picture for the multiplayer snapshot (miniatures).
2129 * Includes every block's col, y, color, state and flame.
2130 */
2131GameCore.prototype.fieldSnapshot = function ()
2132{
2133 var blocks = [];
2134 for (var i = 0; i < this.blocks.length; i++)
2135 {
2136 var b = this.blocks[i];
2137 blocks.push({
2138 id: b.id,
2139 col: b.col,
2140 y: Math.round(b.y * 1000) / 1000,
2141 color: b.color,
2142 state: b.state,
2143 flame: !!b.flame
2144 });
2145 }
2146 return {
2147 score: this.score,
2148 state: this.state,
2149 width: this.width,
2150 height: this.height,
2151 locked: this.lockedColumnCount(),
2152 blocks: blocks
2153 };
2154};
2155
2156/**
2157 * Incoming garbage from another player: a dark-grey block that falls
2158 * normally from the top of an open column. After landing it uses the
2159 * usual 3s settle and then a random colour (landFallingBlock).
2160 * `col` is optional; a random eligible column is used otherwise.
2161 * Returns the new block, or null if every column is locked or full.
2162 */
2163/**
2164 * Open columns a garbage block can fall into (not locked, not full).
2165 */
2166GameCore.prototype.eligibleGarbageColumns = function ()
2167{
2168 var eligible = [];
2169 for (var c = 0; c < this.width; c++)
2170 {
2171 if (this.isColumnLocked(c))
2172 { continue; }
2173 if (this.groundedCount(c) >= this.height)
2174 { continue; }
2175 eligible.push(c);
2176 }
2177 return eligible;
2178};
2179
2180/**
2181 * Choose a garbage column. If `preferred` is still open, it wins;
2182 * otherwise a random eligible column (t1126). Returns null if none.
2183 */
2184GameCore.prototype.pickGarbageColumn = function (preferred)
2185{
2186 var eligible = this.eligibleGarbageColumns();
2187 if (!eligible.length)
2188 { return null; }
2189 // t1184: skip columns whose rocket stack is certainly leaving; only
2190 // if every open column is departing, fall back so no garbage is lost.
2191 var departing = this.departingColumns();
2192 var staying = [];
2193 for (var k = 0; k < eligible.length; k++)
2194 {
2195 if (!departing[eligible[k]])
2196 { staying.push(eligible[k]); }
2197 }
2198 if (staying.length)
2199 { eligible = staying; }
2200 if (preferred != null && isFinite(preferred))
2201 {
2202 var want = preferred | 0;
2203 for (var i = 0; i < eligible.length; i++)
2204 {
2205 if (eligible[i] === want)
2206 { return want; }
2207 }
2208 }
2209 return eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2210};
2211
2212GameCore.prototype.ingestGarbage = function (col)
2213{
2214 if (this.state !== 'playing')
2215 { return null; }
2216 var chosen = this.pickGarbageColumn(col);
2217 if (chosen == null)
2218 { return null; }
2219 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2220 block.vy = -this.planet.fallSpeed;
2221 block.flame = false;
2222 return block;
2223};
2224
2225GameCore.prototype.advanceSettle = function (dt)
2226{
2227 for (var i = 0; i < this.blocks.length; i++)
2228 {
2229 var block = this.blocks[i];
2230 if (block.state !== STATE_SETTLING)
2231 { continue; }
2232 var inLanded = block.clusterId != null
2233 && this.clusters[block.clusterId]
2234 && this.clusters[block.clusterId].phase === 'landed';
2235 if (block.color === COLOR_GRAY)
2236 {
2237 block.settleTime += dt;
2238 if (block.settleTime >= this.settleTime)
2239 {
2240 block.color = this.randomColor();
2241 block.settleTime = 0;
2242 block.flame = false;
2243 if (inLanded)
2244 {
2245 // Stay in the rigid group; releaseLandedCluster runs below.
2246 block.state = STATE_SETTLING;
2247 }
2248 else
2249 {
2250 this.leaveCluster(block);
2251 this.clearFlightState(block);
2252 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2253 }
2254 }
2255 }
2256 else if (!inLanded)
2257 {
2258 // Coloured settling that is not in a landed cluster (shouldn't
2259 // normally happen): just become still or fall, from rest.
2260 this.leaveCluster(block);
2261 this.clearFlightState(block);
2262 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2263 }
2264 }
2265
2266 var ids = Object.keys(this.clusters);
2267 for (var n = 0; n < ids.length; n++)
2268 {
2269 var cluster = this.clusters[ids[n]];
2270 if (!cluster || cluster.phase !== 'landed')
2271 { continue; }
2272 var members = this.clusterMembers(cluster.id);
2273 var greySettling = false;
2274 for (var i = 0; i < members.length; i++)
2275 {
2276 if (members[i].color === COLOR_GRAY && members[i].state === STATE_SETTLING)
2277 { greySettling = true; }
2278 }
2279 if (!greySettling)
2280 { this.releaseLandedCluster(cluster); }
2281 }
2282};
2283
2284GameCore.prototype.findMatchLines = function ()
2285{
2286 var candidates = [];
2287 for (var i = 0; i < this.blocks.length; i++)
2288 {
2289 var block = this.blocks[i];
2290 // Coloured cargo in a just-landed cluster (SETTLING) can match
2291 // with already-resting blocks immediately (t1110). Greys have no
2292 // colour and wait until they recolor; after release they are STILL.
2293 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
2294 && block.color >= 0)
2295 { candidates.push(block); }
2296 }
2297 return this.collectLines(candidates, true);
2298};
2299
2300GameCore.prototype.findFlyingMatchLines = function (clusterId)
2301{
2302 var candidates = [];
2303 for (var i = 0; i < this.blocks.length; i++)
2304 {
2305 var block = this.blocks[i];
2306 if (block.clusterId === clusterId && block.color >= 0
2307 && (block.state === STATE_FLYING))
2308 { candidates.push(block); }
2309 }
2310 return this.collectLines(candidates, false);
2311};
2312
2313GameCore.prototype.collectLines = function (candidates, snapInteger)
2314{
2315 var lines = [];
2316 if (!candidates.length)
2317 { return lines; }
2318
2319 var byRow = Object.create(null);
2320 for (var i = 0; i < candidates.length; i++)
2321 {
2322 var block = candidates[i];
2323 var row = Math.round(block.y);
2324 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
2325 { continue; }
2326 if (!byRow[row])
2327 { byRow[row] = []; }
2328 byRow[row].push(block);
2329 }
2330 var rows = Object.keys(byRow);
2331 for (var r = 0; r < rows.length; r++)
2332 {
2333 var list = byRow[rows[r]];
2334 list.sort(function (a, b) { return a.col - b.col; });
2335 this.pushRuns(lines, list, false, function (a, b)
2336 {
2337 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
2338 });
2339 }
2340
2341 var byCol = Object.create(null);
2342 for (var i = 0; i < candidates.length; i++)
2343 {
2344 var block = candidates[i];
2345 if (!byCol[block.col])
2346 { byCol[block.col] = []; }
2347 byCol[block.col].push(block);
2348 }
2349 var cols = Object.keys(byCol);
2350 for (var c = 0; c < cols.length; c++)
2351 {
2352 var list = byCol[cols[c]];
2353 list.sort(function (a, b) { return a.y - b.y; });
2354 this.pushRuns(lines, list, true, function (a, b)
2355 {
2356 return a.color === b.color && a.color >= 0
2357 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
2358 });
2359 }
2360 return lines;
2361};
2362
2363GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
2364{
2365 var start = 0;
2366 for (var i = 1; i <= list.length; i++)
2367 {
2368 var same = i < list.length && adjacent(list[i - 1], list[i]);
2369 if (!same)
2370 {
2371 var length = i - start;
2372 if (length >= 3)
2373 {
2374 lines.push({
2375 blocks: list.slice(start, i),
2376 length: length,
2377 vertical: vertical
2378 });
2379 }
2380 start = i;
2381 }
2382 }
2383};
2384
2385GameCore.prototype.resolveMatches = function ()
2386{
2387 if (this.state !== 'playing' || this.drag)
2388 { return []; }
2389 var lines = this.findMatchLines();
2390 if (!lines.length)
2391 {
2392 this.finishLandingChains([]);
2393 return [];
2394 }
2395
2396 var uf = new UnionFind();
2397 var blockById = Object.create(null);
2398 for (var i = 0; i < lines.length; i++)
2399 {
2400 var line = lines[i];
2401 for (var j = 0; j < line.blocks.length; j++)
2402 {
2403 uf.add(line.blocks[j].id);
2404 blockById[line.blocks[j].id] = line.blocks[j];
2405 if (j > 0)
2406 { uf.union(line.blocks[0].id, line.blocks[j].id); }
2407 }
2408 }
2409 var matched = [];
2410 var seen = Object.create(null);
2411 for (var id in blockById)
2412 {
2413 if (!seen[id])
2414 {
2415 seen[id] = true;
2416 matched.push(blockById[id]);
2417 }
2418 }
2419 for (var i = 0; i < matched.length; i++)
2420 {
2421 for (var j = i + 1; j < matched.length; j++)
2422 {
2423 if (matched[i].col === matched[j].col)
2424 { uf.union(matched[i].id, matched[j].id); }
2425 }
2426 }
2427
2428 var groups = Object.create(null);
2429 for (var i = 0; i < matched.length; i++)
2430 {
2431 var root = uf.find(matched[i].id);
2432 if (!groups[root])
2433 { groups[root] = []; }
2434 groups[root].push(matched[i]);
2435 }
2436
2437 var launched = [];
2438 for (var root in groups)
2439 {
2440 var group = groups[root];
2441 var height = 0;
2442 for (var i = 0; i < lines.length; i++)
2443 {
2444 var line = lines[i];
2445 var overlaps = false;
2446 for (var j = 0; j < line.blocks.length; j++)
2447 {
2448 for (var k = 0; k < group.length; k++)
2449 {
2450 if (line.blocks[j].id === group[k].id)
2451 { overlaps = true; }
2452 }
2453 }
2454 if (overlaps)
2455 {
2456 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
2457 if (h > height)
2458 { height = h; }
2459 }
2460 }
2461 var chain = this.landingChainFor(group);
2462 var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;
2463 height *= bonusMul;
2464 this.launchCluster(group, height, { landingChain: chain });
2465 launched.push({
2466 blocks: group,
2467 jumpHeight: height,
2468 landingChain: chain,
2469 chainBonus: bonusMul
2470 });
2471 }
2472 this.finishLandingChains(launched);
2473 this.updateChainIndicator(launched);
2474 return launched;
2475};
2476
2477/**
2478 * Gray the matched blocks, take everything sitting on top of them in
2479 * those columns, link them, and launch with jump height `height`.
2480 */
2481GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)
2482{
2483 opts = opts || {};
2484 var lowestInCol = Object.create(null);
2485 var matchedIds = Object.create(null);
2486 for (var i = 0; i < matchedBlocks.length; i++)
2487 {
2488 var block = matchedBlocks[i];
2489 matchedIds[block.id] = true;
2490 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
2491 { lowestInCol[block.col] = block.y; }
2492 }
2493
2494 var clusterId = this.nextClusterId++;
2495 var cluster = {
2496 id: clusterId,
2497 jumpHeight: height,
2498 vy: PlanetMod.launchVelocity(this.planet, height),
2499 decel: PlanetMod.launchDeceleration(this.planet, height),
2500 phase: 'up',
2501 landingChain: opts.landingChain || 0,
2502 landedPending: false
2503 };
2504 this.clusters[clusterId] = cluster;
2505
2506 var riders = [];
2507 var cols = Object.keys(lowestInCol);
2508 for (var c = 0; c < cols.length; c++)
2509 {
2510 var col = +cols[c];
2511 var lowest = lowestInCol[col];
2512 var list = this.blocksInColumn(col);
2513 for (var i = 0; i < list.length; i++)
2514 {
2515 var block = list[i];
2516 if (!this.isGrounded(block) && block.state !== STATE_STILL)
2517 {
2518 if (block.state !== STATE_SETTLING)
2519 { continue; }
2520 }
2521 if (block.y + ALIGN_EPS >= lowest)
2522 { riders.push(block); }
2523 }
2524 }
2525
2526 for (var i = 0; i < riders.length; i++)
2527 {
2528 var block = riders[i];
2529 var isMatch = !!matchedIds[block.id];
2530 if (isMatch || block.color === COLOR_GRAY)
2531 {
2532 block.color = COLOR_GRAY;
2533 block.flame = true;
2534 }
2535 else
2536 { block.flame = false; }
2537 block.state = STATE_FLYING;
2538 block.clusterId = clusterId;
2539 block.vy = cluster.vy;
2540 block.settleTime = 0;
2541 }
2542 this.prepareClusterBody(cluster);
2543 return cluster;
2544};
2545
2546GameCore.prototype.checkLocks = function ()
2547{
2548 for (var col = 0; col < this.width; col++)
2549 {
2550 if (this.isColumnLocked(col))
2551 { continue; }
2552 if (this.groundedCount(col) < this.height)
2553 { continue; }
2554 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
2555 var filled = true;
2556 for (var row = 0; row < this.height; row++)
2557 {
2558 var block = this.blockAt(col, row);
2559 if (!block || !this.isGrounded(block))
2560 {
2561 filled = false;
2562 break;
2563 }
2564 }
2565 if (!filled)
2566 { continue; }
2567 var list = this.blocksInColumn(col);
2568 for (var i = 0; i < list.length; i++)
2569 {
2570 var block = list[i];
2571 if (!this.isGrounded(block))
2572 { continue; }
2573 block.state = STATE_LOCKED;
2574 block.color = COLOR_GRAY;
2575 block.flame = false;
2576 block.vy = 0;
2577 block.settleTime = 0;
2578 if (block.clusterId != null)
2579 { this.leaveCluster(block); }
2580 }
2581 }
2582};
2583
2584GameCore.prototype.checkGameOver = function ()
2585{
2586 if (this.state !== 'playing')
2587 { return; }
2588 for (var col = 0; col < this.width; col++)
2589 {
2590 if (!this.isColumnLocked(col))
2591 { return; }
2592 }
2593 this.state = 'gameover';
2594 this.gameOverTime = 0;
2595 this.drag = null;
2596};
2597
2598/* ---------- dragging -------------------------------------------------- */
2599
2600GameCore.prototype.beginDrag = function (col, y)
2601{
2602 if (this.state !== 'playing')
2603 { return false; }
2604 var block = this.snapDragBlock(col, y);
2605 if (!block)
2606 { return false; }
2607 var top = this.columnStackTopRow(block.col);
2608 var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
2609 this.drag = {
2610 blockId: block.id,
2611 pointerY: y,
2612 startY: y,
2613 accum: 0,
2614 launchIntent: false,
2615 startedAsTop: startedAsTop
2616 };
2617 return true;
2618};
2619
2620/**
2621 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
2622 * floor(col), floor(y); any press inside that cell — corners, padding,
2623 * gaps between sprites, a visually tweened or bouncing sprite — grabs
2624 * the block that occupies it. This uses simulation cells, not the drawn
2625 * sprite bounds. If no block sits in that cell (mid-animation, a block
2626 * whose y is off the integer), fall back to the nearest grabbable block
2627 * in the same column within SNAP_Y (about half a tile). A small
2628 * horizontal slop still consults a neighbouring column when the press
2629 * is near the edge and the primary cell is empty.
2630 */
2631GameCore.prototype.snapDragBlock = function (col, y)
2632{
2633 var raw = col;
2634 var c0 = Math.floor(raw + 1e-9);
2635 var row = Math.floor(y + 1e-9);
2636 var frac = raw - c0;
2637
2638 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
2639 {
2640 var exact = this.draggableInCell(c0, row);
2641 if (exact)
2642 { return exact; }
2643 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
2644 if (near)
2645 { return near; }
2646 }
2647
2648 // Primary cell empty: allow a small horizontal slop into a neighbour.
2649 var neighbours = [];
2650 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
2651 { neighbours.push(c0 - 1); }
2652 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
2653 { neighbours.push(c0 + 1); }
2654 var best = null;
2655 var bestDist = Infinity;
2656 for (var n = 0; n < neighbours.length; n++)
2657 {
2658 var cc = neighbours[n];
2659 if (!this.columnAllowsDrag(cc))
2660 { continue; }
2661 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
2662 if (!hit)
2663 { continue; }
2664 var dist = this.pointerDistToBlock(hit, raw, y);
2665 if (dist < bestDist)
2666 {
2667 bestDist = dist;
2668 best = hit;
2669 }
2670 }
2671 return best;
2672};
2673
2674/** The draggable block that occupies grid cell (col, row), if any. */
2675GameCore.prototype.draggableInCell = function (col, row)
2676{
2677 var best = null;
2678 var bestOverlap = 0;
2679 var list = this.blocksInColumn(col);
2680 for (var i = 0; i < list.length; i++)
2681 {
2682 var block = list[i];
2683 if (!this.isDraggableBlock(block))
2684 { continue; }
2685 var lo = Math.max(block.y, row);
2686 var hi = Math.min(block.y + 1, row + 1);
2687 var overlap = hi - lo;
2688 if (overlap > bestOverlap + 1e-12)
2689 {
2690 bestOverlap = overlap;
2691 best = block;
2692 }
2693 }
2694 if (best && bestOverlap > 1e-9)
2695 { return best; }
2696 return null;
2697};
2698
2699/** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
2700GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
2701{
2702 var best = null;
2703 var bestDist = Infinity;
2704 var list = this.blocksInColumn(col);
2705 for (var i = 0; i < list.length; i++)
2706 {
2707 var block = list[i];
2708 if (!this.isDraggableBlock(block))
2709 { continue; }
2710 var dist = this.pointerDistToBlock(block, col + 0.5, y);
2711 if (dist < bestDist)
2712 {
2713 bestDist = dist;
2714 best = block;
2715 }
2716 }
2717 if (!best || bestDist > maxDist)
2718 { return null; }
2719 return best;
2720};
2721
2722GameCore.prototype.pointerDistToBlock = function (block, col, y)
2723{
2724 var dx;
2725 if (col >= block.col && col < block.col + 1)
2726 { dx = 0; }
2727 else if (col < block.col)
2728 { dx = block.col - col; }
2729 else
2730 { dx = col - (block.col + 1); }
2731 var dy;
2732 if (y >= block.y && y < block.y + 1)
2733 { dy = 0; }
2734 else if (y < block.y)
2735 { dy = block.y - y; }
2736 else
2737 { dy = y - (block.y + 1); }
2738 return Math.sqrt(dx * dx + dy * dy);
2739};
2740
2741GameCore.prototype.moveDrag = function (y)
2742{
2743 if (!this.drag)
2744 { return; }
2745 var block = this.blockById(this.drag.blockId);
2746 if (!block || !this.isDraggableBlock(block))
2747 {
2748 this.drag = null;
2749 return;
2750 }
2751 if (!this.columnAllowsDrag(block.col))
2752 {
2753 this.drag = null;
2754 return;
2755 }
2756 this.drag.pointerY = y;
2757 // 1:1 tracking: the target row is the one under the pointer, clamped
2758 // to the still stack. Swap step by step with each neighbour, and stop
2759 // exactly there. When the pointer stops, nothing else moves.
2760 // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
2761 // used to jump a full cell on a short pull, and one large event
2762 // could walk the entire column (the "jumps all the way" bug).
2763 var top = this.columnStackTopRow(block.col);
2764 var bottom = this.columnStackBottomRow(block.col);
2765 var target = Math.floor(y + 1e-12);
2766 if (bottom < 0)
2767 { bottom = 0; }
2768 if (target < bottom)
2769 { target = bottom; }
2770 if (target > top)
2771 { target = top; }
2772 this.swapToward(block, target);
2773
2774 top = this.columnStackTopRow(block.col);
2775 var isTop = Math.abs(block.y - top) < ALIGN_EPS;
2776 if (this.drag.startedAsTop)
2777 {
2778 // Already the topmost block: pulling upward past its own position
2779 // (LAUNCH_PULL tiles above the press point) starts a manual jump.
2780 this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL);
2781 }
2782 else
2783 {
2784 // Started mid-stack: swap first, and only launch once the pointer
2785 // is pulled into the empty space above the (new) top.
2786 this.drag.launchIntent = isTop && (y > top + 1 + 0.25);
2787 }
2788};
2789
2790/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
2791GameCore.prototype.swapOne = function (block, dir)
2792{
2793 var neighbor = this.blockAt(block.col, block.y + dir);
2794 if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
2795 {
2796 this.swapBlocks(block, neighbor);
2797 return true;
2798 }
2799 return false;
2800};
2801
2802GameCore.prototype.endDrag = function ()
2803{
2804 if (!this.drag)
2805 { return; }
2806 var block = this.blockById(this.drag.blockId);
2807 var launch = this.drag.launchIntent;
2808 this.drag = null;
2809 if (launch && block && block.state === STATE_STILL)
2810 { this.startManualLaunch(block); }
2811 else
2812 { this.resolveMatches(); }
2813};
2814
2815GameCore.prototype.blockById = function (id)
2816{
2817 for (var i = 0; i < this.blocks.length; i++)
2818 {
2819 if (this.blocks[i].id === id)
2820 { return this.blocks[i]; }
2821 }
2822 return null;
2823};
2824
2825GameCore.prototype.columnStackTopRow = function (col)
2826{
2827 var top = -1;
2828 var list = this.blocksInColumn(col);
2829 for (var i = 0; i < list.length; i++)
2830 {
2831 if (this.isGrounded(list[i]) && list[i].y > top)
2832 { top = list[i].y; }
2833 }
2834 return top;
2835};
2836
2837GameCore.prototype.columnStackBottomRow = function (col)
2838{
2839 var bottom = Infinity;
2840 var list = this.blocksInColumn(col);
2841 for (var i = 0; i < list.length; i++)
2842 {
2843 if (this.isGrounded(list[i]) && list[i].y < bottom)
2844 { bottom = list[i].y; }
2845 }
2846 return bottom === Infinity ? 0 : bottom;
2847};
2848
2849GameCore.prototype.swapToward = function (block, targetY)
2850{
2851 var guard = 0;
2852 while (guard++ < this.height + 2)
2853 {
2854 var current = block.y;
2855 if (targetY > current + 0.5)
2856 {
2857 var above = this.blockAt(block.col, current + 1);
2858 if (above && this.isGrounded(above) && above !== block)
2859 { this.swapBlocks(block, above); }
2860 else
2861 { break; }
2862 }
2863 else if (targetY < current - 0.5)
2864 {
2865 var below = this.blockAt(block.col, current - 1);
2866 if (below && this.isGrounded(below) && below !== block)
2867 { this.swapBlocks(block, below); }
2868 else
2869 { break; }
2870 }
2871 else
2872 { break; }
2873 }
2874};
2875
2876GameCore.prototype.swapBlocks = function (a, b)
2877{
2878 var ay = a.y;
2879 var by = b.y;
2880 a.y = by;
2881 b.y = ay;
2882 this.transferLandedMembership(a, b);
2883 if (!this.swapEvents)
2884 { this.swapEvents = []; }
2885 this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });
2886 this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });
2887};
2888
2889GameCore.prototype.consumeSwapEvents = function ()
2890{
2891 var ev = this.swapEvents || [];
2892 this.swapEvents = [];
2893 return ev;
2894};
2895
2896/**
2897 * Highest landing-chain counter among just-landed members of this
2898 * match group, plus one. Returns 0 when the match did not come from
2899 * a cluster landing (player/bot swap, mid-air, etc.).
2900 */
2901GameCore.prototype.landingChainFor = function (group)
2902{
2903 var maxChain = 0;
2904 var fromLanding = false;
2905 for (var i = 0; i < group.length; i++)
2906 {
2907 var block = group[i];
2908 if (block.justLanded)
2909 {
2910 fromLanding = true;
2911 if ((block.landingChain || 0) > maxChain)
2912 { maxChain = block.landingChain || 0; }
2913 }
2914 if (block.clusterId != null)
2915 {
2916 var cluster = this.clusters[block.clusterId];
2917 if (cluster && cluster.landedPending)
2918 {
2919 fromLanding = true;
2920 if ((cluster.landingChain || 0) > maxChain)
2921 { maxChain = cluster.landingChain || 0; }
2922 }
2923 }
2924 }
2925 if (!fromLanding)
2926 { return 0; }
2927 return maxChain + 1;
2928};
2929
2930/**
2931 * After resolveMatches: clear the landing-pending flag and reset the
2932 * chain on landings that did not make a match. A cluster that is still
2933 * settling (greys not yet recolored) keeps landedPending so a later
2934 * post-recolor match in this same landing still gets the bonus.
2935 */
2936GameCore.prototype.finishLandingChains = function (launched)
2937{
2938 var launchedIds = Object.create(null);
2939 launched = launched || [];
2940 for (var i = 0; i < launched.length; i++)
2941 {
2942 var blocks = launched[i].blocks || [];
2943 for (var j = 0; j < blocks.length; j++)
2944 { launchedIds[blocks[j].id] = true; }
2945 }
2946
2947 for (var i = 0; i < this.blocks.length; i++)
2948 {
2949 var block = this.blocks[i];
2950 if (!block.justLanded)
2951 { continue; }
2952 if (!launchedIds[block.id])
2953 { block.landingChain = 0; }
2954 block.justLanded = false;
2955 }
2956
2957 var ids = Object.keys(this.clusters);
2958 for (var c = 0; c < ids.length; c++)
2959 {
2960 var cluster = this.clusters[ids[c]];
2961 if (!cluster || !cluster.landedPending)
2962 { continue; }
2963 var members = this.clusterMembers(cluster.id);
2964 var anyLaunched = false;
2965 var stillSettling = false;
2966 for (var i = 0; i < members.length; i++)
2967 {
2968 if (launchedIds[members[i].id])
2969 { anyLaunched = true; }
2970 if (members[i].state === STATE_SETTLING)
2971 { stillSettling = true; }
2972 }
2973 if (anyLaunched)
2974 {
2975 cluster.landingChain = 0;
2976 cluster.landedPending = false;
2977 }
2978 else if (!stillSettling)
2979 {
2980 // Released leftovers or a fully-still landed group that
2981 // already had its match opportunity and missed it.
2982 cluster.landingChain = 0;
2983 cluster.landedPending = false;
2984 }
2985 // else: still settling, no match yet — keep landedPending.
2986 }
2987};
2988
2989GameCore.prototype.updateChainIndicator = function (launched)
2990{
2991 var maxChain = 0;
2992 for (var i = 0; i < launched.length; i++)
2993 {
2994 var ch = launched[i].landingChain || 0;
2995 if (ch > maxChain)
2996 { maxChain = ch; }
2997 }
2998 if (maxChain >= 1)
2999 {
3000 this.lastChainIndicator = {
3001 chain: maxChain,
3002 bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)
3003 };
3004 return;
3005 }
3006 if (!this.hasActiveLandingChain())
3007 { this.lastChainIndicator = null; }
3008};
3009
3010GameCore.prototype.hasActiveLandingChain = function ()
3011{
3012 var ids = Object.keys(this.clusters);
3013 for (var i = 0; i < ids.length; i++)
3014 {
3015 var cluster = this.clusters[ids[i]];
3016 if (cluster && (cluster.landingChain || 0) >= 1
3017 && cluster.phase !== 'landed')
3018 { return true; }
3019 }
3020 return false;
3021};
3022
3023/**
3024 * A landed cluster (grey rockets or linked cargo resting on the ground)
3025 * is a swappable part of the contiguous grounded stack. Flying, falling
3026 * and manual blocks are not. A locked column is not.
3027 */
3028GameCore.prototype.isDraggableBlock = function (block)
3029{
3030 if (!block)
3031 { return false; }
3032 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
3033 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
3034 { return false; }
3035 if (block.clusterId != null)
3036 {
3037 var cluster = this.clusters[block.clusterId];
3038 // Flying (rising / descending) clusters stay non-draggable.
3039 if (cluster && cluster.phase !== 'landed')
3040 { return false; }
3041 }
3042 return block.state === STATE_STILL || block.state === STATE_SETTLING;
3043};
3044
3045/**
3046 * The grounded contiguous stack in this column can be dragged, even if a
3047 * flying cluster or a falling spawn occupies the air above it. Only a
3048 * locked column is blocked as a whole.
3049 */
3050GameCore.prototype.columnAllowsDrag = function (col)
3051{
3052 return !this.isColumnLocked(col);
3053};
3054
3055GameCore.prototype.landedClusterId = function (block)
3056{
3057 if (!block || block.clusterId == null)
3058 { return null; }
3059 var cluster = this.clusters[block.clusterId];
3060 if (!cluster || cluster.phase !== 'landed')
3061 { return null; }
3062 return block.clusterId;
3063};
3064
3065/**
3066 * After a swap: leaving a landed cluster clears membership; joining one
3067 * makes the block part of that rigid group. Same-cluster swaps only
3068 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
3069 */
3070GameCore.prototype.transferLandedMembership = function (a, b)
3071{
3072 var ca = this.landedClusterId(a);
3073 var cb = this.landedClusterId(b);
3074 if (ca === cb)
3075 { return; }
3076 // Join first so leaveCluster does not delete a cluster that still
3077 // has the incoming member.
3078 this.applyLandedMembership(b, ca);
3079 this.applyLandedMembership(a, cb);
3080};
3081
3082GameCore.prototype.applyLandedMembership = function (block, clusterId)
3083{
3084 if (clusterId == null)
3085 {
3086 var wasGrey = block.color === COLOR_GRAY;
3087 var wasSettling = block.state === STATE_SETTLING;
3088 this.leaveCluster(block);
3089 if (wasGrey && wasSettling)
3090 {
3091 // Keep settling and recolor on its own, same remaining timer.
3092 block.state = STATE_SETTLING;
3093 }
3094 else if (wasSettling)
3095 {
3096 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
3097 }
3098 return;
3099 }
3100 if (!this.clusters[clusterId])
3101 { return; }
3102 block.clusterId = clusterId;
3103 block.flame = false;
3104 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
3105 { block.state = STATE_SETTLING; }
3106};
3107
3108/**
3109 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
3110 * Returns the moved block, or null if the column does not allow a drag.
3111 */
3112GameCore.prototype.swapTo = function (col, fromRow, toRow)
3113{
3114 if (!this.columnAllowsDrag(col))
3115 { return null; }
3116 var block = this.blockAt(col, fromRow);
3117 if (!block)
3118 { return null; }
3119 this.swapToward(block, toRow);
3120 return block;
3121};
3122
3123/**
3124 * Test helper: a compact picture of grounded/falling/flying blocks.
3125 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
3126 * L locked, f falling, m manual, . empty. Flying colored blocks use
3127 * their color with a marker in `flying`.
3128 */
3129GameCore.prototype.snapshot = function ()
3130{
3131 var grid = [];
3132 for (var r = 0; r < this.height; r++)
3133 {
3134 var row = [];
3135 for (var c = 0; c < this.width; c++)
3136 { row.push('.'); }
3137 grid.push(row);
3138 }
3139 var airborne = [];
3140 for (var i = 0; i < this.blocks.length; i++)
3141 {
3142 var block = this.blocks[i];
3143 var ch;
3144 if (block.state === STATE_LOCKED)
3145 { ch = 'L'; }
3146 else if (block.color === COLOR_GRAY)
3147 { ch = 'g'; }
3148 else
3149 { ch = String(block.color); }
3150 if (this.isGrounded(block) || block.state === STATE_FALLING)
3151 {
3152 var row = Math.round(block.y);
3153 if (row >= 0 && row < this.height)
3154 { grid[row][block.col] = ch; }
3155 }
3156 else
3157 {
3158 airborne.push({
3159 id: block.id,
3160 col: block.col,
3161 y: block.y,
3162 color: block.color,
3163 state: block.state,
3164 clusterId: block.clusterId,
3165 flame: block.flame,
3166 vy: block.vy
3167 });
3168 }
3169 }
3170 var lines = [];
3171 for (var r = this.height - 1; r >= 0; r--)
3172 { lines.push(grid[r].join('')); }
3173 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
3174};
3175
3176var GameCoreAPI = {
3177 GameCore: GameCore,
3178 COLOR_GRAY: COLOR_GRAY,
3179 STATE_STILL: STATE_STILL,
3180 STATE_FALLING: STATE_FALLING,
3181 STATE_FLYING: STATE_FLYING,
3182 STATE_SETTLING: STATE_SETTLING,
3183 STATE_LOCKED: STATE_LOCKED,
3184 STATE_MANUAL: STATE_MANUAL
3185};
3186
3187if (typeof module !== 'undefined' && module.exports)
3188{ module.exports = GameCoreAPI; }
3189else if (typeof globalThis !== 'undefined')
3190{
3191 globalThis.GameCore = GameCore;
3192 globalThis.GameCoreAPI = GameCoreAPI;
3193}