BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

gameCore.js 78.0 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
641GameCore.prototype.trySpawn = function ()
642{
643 if (this.state !== 'playing')
644 { return null; }
645 var eligible = [];
646 for (var col = 0; col < this.width; col++)
647 {
648 if (this.isColumnLocked(col))
649 { continue; }
650 if (this.groundedCount(col) >= this.height)
651 { continue; }
652 var alreadyFalling = false;
653 var list = this.blocksInColumn(col);
654 for (var i = 0; i < list.length; i++)
655 {
656 if (list[i].state === STATE_FALLING)
657 {
658 alreadyFalling = true;
659 break;
660 }
661 }
662 if (!alreadyFalling)
663 { eligible.push(col); }
664 }
665 if (!eligible.length)
666 { return null; }
667 var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
668 var color = this.randomColor();
669 var block = this.createBlock(col, this.height, color, STATE_FALLING);
670 block.vy = -this.planet.fallSpeed;
671 return block;
672};
673
674GameCore.prototype.integrateFalling = function (dt)
675{
676 var falling = [];
677 for (var i = 0; i < this.blocks.length; i++)
678 {
679 if (this.blocks[i].state === STATE_FALLING)
680 { falling.push(this.blocks[i]); }
681 }
682 // Lowest first, so a stack of falling blocks rests on itself.
683 falling.sort(function (a, b) { return a.y - b.y; });
684 for (var i = 0; i < falling.length; i++)
685 {
686 var block = falling[i];
687 if (block.state !== STATE_FALLING)
688 { continue; }
689 this.accelerateFall(block, dt);
690 var nextY = block.y + block.vy * dt;
691 var manual = this.manualInColumnHit(block, block.y, nextY);
692 if (manual)
693 {
694 this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block]));
695 continue;
696 }
697 var flyer = this.highestFlyingBelow(block);
698 if (flyer && nextY <= flyer.y + 1 + 1e-9)
699 {
700 if (this.attachToFlyingCluster(block, flyer))
701 { continue; }
702 }
703 var top = this.stackTop(block.col, null, block.y);
704 var below = this.highestFallingBelow(block);
705 if (below && below.y + 1 > top)
706 { top = below.y + 1; }
707 if (nextY <= top)
708 {
709 block.y = top;
710 this.landFallingBlock(block);
711 }
712 else
713 { block.y = nextY; }
714 }
715};
716
717GameCore.prototype.clusterMembers = function (clusterId)
718{
719 var out = [];
720 for (var i = 0; i < this.blocks.length; i++)
721 {
722 if (this.blocks[i].clusterId === clusterId)
723 { out.push(this.blocks[i]); }
724 }
725 return out;
726};
727
728
729/**
730 * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a
731 * jump of height H peaks at exactly H after riseTime. Returns dy.
732 * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the
733 * upward deceleration. After the apex, vy eases from 0 to -fallSpeed
734 * at planet.fallAccel, then stays at terminal fallSpeed.
735 */
736GameCore.prototype.advanceJump = function (body, dt)
737{
738 var dy = 0;
739 var left = dt;
740 if (body.phase === 'up')
741 {
742 var decel = body.decel;
743 var vy = body.vy;
744 var tApex = decel > 1e-12 ? vy / decel : Infinity;
745 if (tApex <= left + 1e-15)
746 {
747 dy += vy * tApex - 0.5 * decel * tApex * tApex;
748 body.vy = 0;
749 body.phase = 'down';
750 left -= tApex;
751 }
752 else
753 {
754 var vyNew = vy - decel * left;
755 dy += (vy + vyNew) * 0.5 * left;
756 body.vy = vyNew;
757 left = 0;
758 }
759 }
760 if (body.phase === 'up' && body.vy <= 1e-10)
761 {
762 body.vy = 0;
763 body.phase = 'down';
764 }
765 if (body.phase === 'down' && left > 0)
766 {
767 var target = -this.planet.fallSpeed;
768 var accel = this.planet.fallAccel;
769 if (accel < 1e-12)
770 {
771 body.vy = target;
772 dy += body.vy * left;
773 }
774 else if (body.vy > target + 1e-12)
775 {
776 var tReach = (body.vy - target) / accel;
777 if (tReach <= left + 1e-15)
778 {
779 dy += (body.vy + target) * 0.5 * tReach;
780 body.vy = target;
781 left -= tReach;
782 dy += body.vy * left;
783 }
784 else
785 {
786 var vyNew = body.vy - accel * left;
787 dy += (body.vy + vyNew) * 0.5 * left;
788 body.vy = vyNew;
789 }
790 }
791 else
792 {
793 body.vy = target;
794 dy += body.vy * left;
795 }
796 }
797 return dy;
798};
799
800GameCore.prototype.integrateClusters = function (dt)
801{
802 var ids = Object.keys(this.clusters);
803 for (var n = 0; n < ids.length; n++)
804 {
805 var cluster = this.clusters[ids[n]];
806 if (!cluster)
807 { continue; }
808 var members = this.clusterMembers(cluster.id);
809 if (!members.length)
810 {
811 delete this.clusters[cluster.id];
812 continue;
813 }
814 if (cluster.phase === 'landed' || cluster.phase === 'hold')
815 { continue; }
816
817 this.prepareClusterBody(cluster);
818 var dy = this.advanceJump(cluster, dt);
819 cluster.anchorY += dy;
820 this.syncClusterMembers(cluster);
821
822 this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id));
823 this.checkChainRelaunch(cluster);
824
825 if (cluster.phase === 'down' && this.clusters[cluster.id])
826 { this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }
827 }
828};
829
830
831/**
832 * If two or more flying clusters overlap in the same column, merge them
833 * into one cluster. Velocity (and deceleration and jumpHeight) is the
834 * mass-weighted average by block count. Phase is 'up' when the merged
835 * vy is positive, otherwise 'down'. Overlapping members in a column
836 * are packed so the higher one sits flush on the lower.
837 */
838GameCore.prototype.mergeFlyingClusters = function ()
839{
840 var flying = [];
841 var ids = Object.keys(this.clusters);
842 for (var n = 0; n < ids.length; n++)
843 {
844 var cluster = this.clusters[ids[n]];
845 if (!cluster)
846 { continue; }
847 if (cluster.phase === 'landed' || cluster.phase === 'hold')
848 { continue; }
849 flying.push(cluster);
850 }
851 if (flying.length < 2)
852 { return; }
853
854 var uf = new UnionFind();
855 for (var i = 0; i < flying.length; i++)
856 { uf.add(flying[i].id); }
857 for (var i = 0; i < flying.length; i++)
858 {
859 for (var j = i + 1; j < flying.length; j++)
860 {
861 if (this.flyingClustersOverlap(flying[i], flying[j]))
862 { uf.union(flying[i].id, flying[j].id); }
863 }
864 }
865
866 var groups = Object.create(null);
867 for (var i = 0; i < flying.length; i++)
868 {
869 var root = uf.find(flying[i].id);
870 if (!groups[root])
871 { groups[root] = []; }
872 groups[root].push(flying[i]);
873 }
874 for (var root in groups)
875 {
876 if (groups[root].length >= 2)
877 { this.mergeClusterGroup(groups[root]); }
878 }
879};
880
881GameCore.prototype.flyingClustersOverlap = function (a, b)
882{
883 var ma = this.clusterMembers(a.id);
884 var mb = this.clusterMembers(b.id);
885 for (var i = 0; i < ma.length; i++)
886 {
887 for (var j = 0; j < mb.length; j++)
888 {
889 if (ma[i].col !== mb[j].col)
890 { continue; }
891 if (this.sweptIntervalsOverlap(ma[i], mb[j]))
892 { return true; }
893 }
894 }
895 return false;
896};
897
898/**
899 * Swept [y, y+1) of two blocks this substep, using _prevY when present.
900 * Catches pairs that crossed without sharing a cell at either endpoint.
901 */
902GameCore.prototype.sweptIntervalsOverlap = function (a, b)
903{
904 var a0 = (a._prevY != null) ? a._prevY : a.y;
905 var a1 = a.y;
906 var b0 = (b._prevY != null) ? b._prevY : b.y;
907 var b1 = b.y;
908 var aLo = Math.min(a0, a1);
909 var aHi = Math.max(a0, a1) + 1;
910 var bLo = Math.min(b0, b1);
911 var bHi = Math.max(b0, b1) + 1;
912 return aLo < bHi - 1e-9 && bLo < aHi - 1e-9;
913};
914
915GameCore.prototype.mergeClusterGroup = function (clusters)
916{
917 clusters.sort(function (a, b) { return a.id - b.id; });
918 var keep = clusters[0];
919 var n = 0;
920 var vySum = 0;
921 var decelSum = 0;
922 var hSum = 0;
923 for (var c = 0; c < clusters.length; c++)
924 {
925 var mem = this.clusterMembers(clusters[c].id);
926 var m = mem.length;
927 n += m;
928 vySum += clusters[c].vy * m;
929 decelSum += (clusters[c].decel || 0) * m;
930 hSum += (clusters[c].jumpHeight || 0) * m;
931 }
932 if (n === 0)
933 { return; }
934 keep.vy = vySum / n;
935 keep.decel = decelSum / n;
936 keep.jumpHeight = hSum / n;
937 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
938 var maxChain = 0;
939 for (var c = 0; c < clusters.length; c++)
940 {
941 var ch = clusters[c].landingChain || 0;
942 if (ch > maxChain)
943 { maxChain = ch; }
944 }
945 keep.landingChain = maxChain;
946 for (var c = 0; c < clusters.length; c++)
947 {
948 var mem = this.clusterMembers(clusters[c].id);
949 for (var i = 0; i < mem.length; i++)
950 {
951 mem[i].clusterId = keep.id;
952 mem[i].vy = keep.vy;
953 mem[i].state = STATE_FLYING;
954 }
955 if (clusters[c] !== keep)
956 { delete this.clusters[clusters[c].id]; }
957 }
958 this.prepareClusterBody(keep);
959 this.checkChainRelaunch(keep);
960 if (keep.phase === 'down' && this.clusters[keep.id])
961 { this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
962};
963
964GameCore.prototype.packClusterOverlaps = function (cluster)
965{
966 var members = this.clusterMembers(cluster.id);
967 var byCol = Object.create(null);
968 for (var i = 0; i < members.length; i++)
969 {
970 var col = members[i].col;
971 if (!byCol[col])
972 { byCol[col] = []; }
973 byCol[col].push(members[i]);
974 }
975 var cols = Object.keys(byCol);
976 for (var c = 0; c < cols.length; c++)
977 {
978 var list = byCol[cols[c]];
979 list.sort(function (a, b) { return a.y - b.y; });
980 for (var i = 1; i < list.length; i++)
981 {
982 var minY = list[i - 1].y + 1;
983 if (list[i].y < minY - 1e-12)
984 { list[i].y = minY; }
985 }
986 }
987};
988
989
990/**
991 * Derive integer cell offsets from current member positions and a
992 * single anchorY, packing overlaps in each column while preserving
993 * order (lower y stays lower; ties break on id). Then sync.
994 * Flying clusters are one rigid body: one y, one vy, integer offsets.
995 */
996GameCore.prototype.prepareClusterBody = function (cluster)
997{
998 if (!cluster)
999 { return; }
1000 var members = this.clusterMembers(cluster.id);
1001 if (!members.length)
1002 { return; }
1003 this.rebuildClusterOffsets(cluster, members);
1004};
1005
1006GameCore.prototype.rebuildClusterOffsets = function (cluster, members)
1007{
1008 members = members || this.clusterMembers(cluster.id);
1009 if (!members.length)
1010 { return; }
1011 var byCol = Object.create(null);
1012 for (var i = 0; i < members.length; i++)
1013 {
1014 var col = members[i].col;
1015 if (!byCol[col])
1016 { byCol[col] = []; }
1017 byCol[col].push(members[i]);
1018 }
1019 var minY = Infinity;
1020 for (var i = 0; i < members.length; i++)
1021 {
1022 if (members[i].y < minY)
1023 { minY = members[i].y; }
1024 }
1025 if (cluster.anchorY == null || !isFinite(cluster.anchorY))
1026 { cluster.anchorY = minY; }
1027 var cols = Object.keys(byCol);
1028 for (var c = 0; c < cols.length; c++)
1029 {
1030 var list = byCol[cols[c]];
1031 list.sort(function (a, b)
1032 {
1033 if (a.y !== b.y)
1034 { return a.y - b.y; }
1035 return a.id - b.id;
1036 });
1037 var prevOff = -Infinity;
1038 for (var i = 0; i < list.length; i++)
1039 {
1040 var off = Math.round(list[i].y - cluster.anchorY);
1041 if (off <= prevOff)
1042 { off = prevOff + 1; }
1043 list[i].clusterOffset = off;
1044 prevOff = off;
1045 }
1046 }
1047 // Re-base so the lowest offset is 0, keeping relative integers.
1048 var minOff = Infinity;
1049 for (var i = 0; i < members.length; i++)
1050 {
1051 if (members[i].clusterOffset < minOff)
1052 { minOff = members[i].clusterOffset; }
1053 }
1054 if (minOff !== 0 && isFinite(minOff))
1055 {
1056 cluster.anchorY += minOff;
1057 for (var i = 0; i < members.length; i++)
1058 { members[i].clusterOffset -= minOff; }
1059 }
1060 this.syncClusterMembers(cluster);
1061};
1062
1063GameCore.prototype.syncClusterMembers = function (cluster)
1064{
1065 if (!cluster)
1066 { return; }
1067 var members = this.clusterMembers(cluster.id);
1068 if (cluster.anchorY == null)
1069 {
1070 var minY = Infinity;
1071 for (var i = 0; i < members.length; i++)
1072 {
1073 if (members[i].y < minY)
1074 { minY = members[i].y; }
1075 }
1076 cluster.anchorY = isFinite(minY) ? minY : 0;
1077 }
1078 for (var i = 0; i < members.length; i++)
1079 {
1080 var block = members[i];
1081 if (block.clusterOffset == null)
1082 { block.clusterOffset = Math.round(block.y - cluster.anchorY); }
1083 block.y = cluster.anchorY + block.clusterOffset;
1084 if (cluster.phase !== 'landed')
1085 { block.vy = cluster.vy; }
1086 }
1087};
1088
1089GameCore.prototype.snapshotPrevY = function ()
1090{
1091 for (var i = 0; i < this.blocks.length; i++)
1092 { this.blocks[i]._prevY = this.blocks[i].y; }
1093};
1094
1095/**
1096 * Safety net after the specific integrates: any remaining mid-air
1097 * overlap or swept crossing is resolved with the same rules, then
1098 * every flying cluster is rebuilt as a rigid body. Repeats a few
1099 * times because one attach can create a new contact.
1100 */
1101GameCore.prototype.resolveAirborneCollisions = function ()
1102{
1103 var guard = 0;
1104 while (guard++ < this.height + 4)
1105 {
1106 var changed = false;
1107
1108 // Manual vs falling / cluster / manual.
1109 var manuals = [];
1110 for (var i = 0; i < this.blocks.length; i++)
1111 {
1112 if (this.blocks[i].state === STATE_MANUAL)
1113 { manuals.push(this.blocks[i]); }
1114 }
1115 manuals.sort(function (a, b) { return b.y - a.y; });
1116 for (var m = 0; m < manuals.length; m++)
1117 {
1118 var manual = manuals[m];
1119 if (manual.state !== STATE_MANUAL)
1120 { continue; }
1121 var oldY = (manual._prevY != null) ? manual._prevY : manual.y;
1122 if (this.resolveManualCollisions(manual, oldY, manual.y))
1123 { changed = true; }
1124 }
1125
1126 // Falling vs flying (sit on the roof).
1127 for (var i = 0; i < this.blocks.length; i++)
1128 {
1129 var block = this.blocks[i];
1130 if (block.state !== STATE_FALLING)
1131 { continue; }
1132 var flyer = this.highestFlyingBelow(block);
1133 if (!flyer)
1134 {
1135 // Also a flyer whose swept path crosses this falling block.
1136 flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y);
1137 }
1138 if (flyer && this.sweptIntervalsOverlap(block, flyer))
1139 {
1140 if (this.attachToFlyingCluster(block, flyer))
1141 { changed = true; }
1142 }
1143 }
1144
1145 // Cluster vs cluster (swept, including after a column push).
1146 var before = Object.keys(this.clusters).length;
1147 this.mergeFlyingClusters();
1148 if (Object.keys(this.clusters).length !== before)
1149 { changed = true; }
1150
1151 // Rebuild every flying body so offsets stay integer and unique.
1152 var ids = Object.keys(this.clusters);
1153 for (var n = 0; n < ids.length; n++)
1154 {
1155 var cluster = this.clusters[ids[n]];
1156 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1157 { continue; }
1158 this.prepareClusterBody(cluster);
1159 }
1160
1161 if (!changed)
1162 { break; }
1163 }
1164};
1165
1166/**
1167 * Invariant checker (t1112). No two blocks occupy the same cell or
1168 * overlap their [y, y+1) intervals. Flying-cluster members are
1169 * grid-aligned to a single anchor. Returns a list of violation
1170 * strings (empty if clean).
1171 */
1172GameCore.prototype.checkInvariants = function ()
1173{
1174 var issues = [];
1175 var byCol = Object.create(null);
1176 var ids = Object.create(null);
1177 for (var i = 0; i < this.blocks.length; i++)
1178 {
1179 var block = this.blocks[i];
1180 if (ids[block.id])
1181 { issues.push('duplicate id ' + block.id); }
1182 ids[block.id] = true;
1183 if (!byCol[block.col])
1184 { byCol[block.col] = []; }
1185 byCol[block.col].push(block);
1186 if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet
1187 && block.color >= this.planet.colors.length))
1188 { issues.push('block ' + block.id + ' has invalid color ' + block.color); }
1189 }
1190 var cols = Object.keys(byCol);
1191 for (var c = 0; c < cols.length; c++)
1192 {
1193 var list = byCol[cols[c]];
1194 list.sort(function (a, b)
1195 {
1196 if (a.y !== b.y)
1197 { return a.y - b.y; }
1198 return a.id - b.id;
1199 });
1200 for (var i = 0; i < list.length; i++)
1201 {
1202 var a = list[i];
1203 if (i > 0)
1204 {
1205 var prev = list[i - 1];
1206 if (a.y < prev.y + 1 - 1e-6)
1207 {
1208 issues.push('overlap col=' + a.col
1209 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)
1210 + ' gap=' + (a.y - prev.y));
1211 }
1212 var cellA = Math.floor(a.y + 1e-9);
1213 var cellP = Math.floor(prev.y + 1e-9);
1214 if (cellA === cellP)
1215 {
1216 issues.push('duplicate cell col=' + a.col + ' row=' + cellA
1217 + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a));
1218 }
1219 }
1220 }
1221 }
1222 var cids = Object.keys(this.clusters);
1223 for (var n = 0; n < cids.length; n++)
1224 {
1225 var cluster = this.clusters[cids[n]];
1226 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
1227 { continue; }
1228 var mem = this.clusterMembers(cluster.id);
1229 var seenOff = Object.create(null);
1230 for (var i = 0; i < mem.length; i++)
1231 {
1232 var b = mem[i];
1233 if (cluster.anchorY != null && b.clusterOffset != null)
1234 {
1235 var expected = cluster.anchorY + b.clusterOffset;
1236 if (Math.abs(b.y - expected) > 1e-6)
1237 {
1238 issues.push('cluster ' + cluster.id + ' member ' + b.id
1239 + ' y=' + b.y + ' != anchor+off ' + expected);
1240 }
1241 if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9)
1242 {
1243 issues.push('cluster ' + cluster.id + ' member ' + b.id
1244 + ' non-integer offset ' + b.clusterOffset);
1245 }
1246 var key = b.col + ':' + b.clusterOffset;
1247 if (seenOff[key])
1248 {
1249 issues.push('cluster ' + cluster.id + ' duplicate offset ' + key);
1250 }
1251 seenOff[key] = true;
1252 }
1253 }
1254 }
1255 return issues;
1256};
1257
1258GameCore.prototype._invBlock = function (b)
1259{
1260 return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y='
1261 + (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')';
1262};
1263
1264GameCore.prototype.assertInvariants = function (label)
1265{
1266 if (!this.strictInvariants && !this.debugInvariants)
1267 { return; }
1268 var issues = this.checkInvariants();
1269 this.lastInvariantViolations = issues;
1270 if (!issues.length)
1271 { return; }
1272 var msg = 'physics invariants failed'
1273 + (label ? ' at ' + label : '')
1274 + ':\n ' + issues.join('\n ')
1275 + '\n' + (this.snapshot ? this.snapshot().picture : '');
1276 if (this.strictInvariants)
1277 { throw new Error(msg); }
1278};
1279
1280GameCore.prototype.tryLandCluster = function (cluster, members)
1281{
1282 if (!members.length)
1283 { return; }
1284 var shift = 0;
1285 var hit = false;
1286 for (var i = 0; i < members.length; i++)
1287 {
1288 var block = members[i];
1289 var top = this.stackTop(block.col, function (other)
1290 {
1291 return other.clusterId === cluster.id;
1292 }, block.y);
1293 if (block.y <= top + 1e-9)
1294 {
1295 hit = true;
1296 var need = top - block.y;
1297 if (need > shift)
1298 { shift = need; }
1299 }
1300 }
1301 if (!hit)
1302 { return; }
1303 // Lift the whole rigid body so the deepest contact sits flush.
1304 this.prepareClusterBody(cluster);
1305 cluster.anchorY += shift;
1306 this.syncClusterMembers(cluster);
1307 this.landCluster(cluster, this.clusterMembers(cluster.id));
1308};
1309
1310/**
1311 * Land as a rigid group: relative positions are kept, so part of the
1312 * cluster may hang above a gap. Grey members start the 3s settle timer;
1313 * coloured cargo stays put with them until every grey has recolored.
1314 * Members that actually rest on the floor or on another block bounce.
1315 */
1316GameCore.prototype.landCluster = function (cluster, members)
1317{
1318 for (var i = 0; i < members.length; i++)
1319 {
1320 var block = members[i];
1321 block.vy = 0;
1322 block.flame = false;
1323 block.clusterId = cluster.id;
1324 if (block.color === COLOR_GRAY)
1325 {
1326 block.state = STATE_SETTLING;
1327 block.settleTime = 0;
1328 }
1329 else
1330 {
1331 // Cargo stays in the rigid group (not matchable) until release.
1332 block.state = STATE_SETTLING;
1333 block.settleTime = 0;
1334 }
1335 if (this.hasSupport(block))
1336 { this.startBounce(block); }
1337 }
1338 cluster.phase = 'landed';
1339 cluster.vy = 0;
1340 cluster.landedPending = true;
1341 if (cluster.landingChain == null)
1342 { cluster.landingChain = 0; }
1343};
1344
1345/**
1346 * After every grey in a landed cluster has recolored, let the group go.
1347 * Unsupported blocks fall individually from rest; supported ones stay.
1348 */
1349GameCore.prototype.releaseLandedCluster = function (cluster)
1350{
1351 var members = this.clusterMembers(cluster.id);
1352 var releasing = Object.create(null);
1353 for (var i = 0; i < members.length; i++)
1354 { releasing[members[i].id] = true; }
1355
1356 for (var i = 0; i < members.length; i++)
1357 {
1358 var block = members[i];
1359 if (block.color === COLOR_GRAY)
1360 {
1361 block.color = this.randomColor();
1362 block.settleTime = 0;
1363 }
1364 // Persist the chain across release so a post-recolor match in
1365 // this same tick still gets the landing bonus (t1120).
1366 block.justLanded = !!cluster.landedPending;
1367 block.landingChain = cluster.landingChain || 0;
1368 this.leaveCluster(block);
1369 // Always drop leftover launch / manual velocity. A stale upward
1370 // vy here is what sends blocks off the top "very fast" after
1371 // a grey group recolors.
1372 this.clearFlightState(block);
1373 // Support from outside the group (floor or a foreign block). Fellow
1374 // members that will also fall do not count, so a hanging stack
1375 // drops together without the top one staying put.
1376 var supported = this.hasSupportOutside(block, releasing);
1377 block.state = supported ? STATE_STILL : STATE_FALLING;
1378 }
1379 delete this.clusters[cluster.id];
1380};
1381
1382GameCore.prototype.hasSupportOutside = function (block, ignoreIds)
1383{
1384 if (block.y <= 1e-9)
1385 { return true; }
1386 for (var i = 0; i < this.blocks.length; i++)
1387 {
1388 var other = this.blocks[i];
1389 if (other === block || other.col !== block.col)
1390 { continue; }
1391 if (ignoreIds && ignoreIds[other.id])
1392 { continue; }
1393 if (!this.isGrounded(other))
1394 { continue; }
1395 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
1396 { return true; }
1397 }
1398 return false;
1399};
1400
1401GameCore.prototype.integrateManual = function (dt)
1402{
1403 for (var i = 0; i < this.blocks.length; i++)
1404 {
1405 var block = this.blocks[i];
1406 if (block.state !== STATE_MANUAL)
1407 { continue; }
1408
1409 if (block.manualPhase === 'up')
1410 {
1411 var oldY = block.y;
1412 var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
1413 var dy = this.advanceJump(proxy, dt);
1414 var nextY = oldY + dy;
1415 block.vy = proxy.vy;
1416 block.manualPhase = proxy.phase;
1417 if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget)))
1418 { continue; }
1419 block.y = Math.min(nextY, block.manualTarget);
1420 if (block.y >= block.manualTarget - 1e-12)
1421 {
1422 block.y = block.manualTarget;
1423 block.vy = 0;
1424 block.manualPhase = 'down';
1425 }
1426 if (block.y > this.height - 1)
1427 {
1428 block.y = this.height - 1;
1429 block.vy = 0;
1430 block.manualPhase = 'down';
1431 }
1432 }
1433
1434 if (block.manualPhase === 'down')
1435 {
1436 var proxy = { phase: 'down', vy: block.vy, decel: 0 };
1437 var dy = this.advanceJump(proxy, dt);
1438 block.vy = proxy.vy;
1439 var nextY = block.y + dy;
1440 var top = this.stackTop(block.col, null, block.y);
1441 if (nextY <= top)
1442 {
1443 block.y = top;
1444 block.state = STATE_STILL;
1445 block.vy = 0;
1446 block.manualPhase = null;
1447 block.flame = false;
1448 this.startBounce(block);
1449 }
1450 else
1451 {
1452 var downNext = Math.min(nextY, this.height - 1);
1453 if (this.resolveManualCollisions(block, block.y, downNext))
1454 { continue; }
1455 block.y = downNext;
1456 }
1457 }
1458 }
1459};
1460
1461/**
1462 * If the manual throw (or its path this step) hits falling blocks, merge
1463 * them into a flying cluster with mass-weighted velocity, the same rule
1464 * as two flying clusters colliding (t1108). Returns true if merged.
1465 */
1466GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY)
1467{
1468 if (!manual || manual.state !== STATE_MANUAL)
1469 { return false; }
1470 var hits = this.fallingHitsOnManualPath(manual, oldY, newY);
1471 if (!hits.length)
1472 { return false; }
1473 this.mergeManualWithFalling(manual, hits);
1474 return true;
1475};
1476
1477GameCore.prototype.manualInColumnHit = function (falling, oldY, newY)
1478{
1479 var lo = Math.min(oldY, newY);
1480 var hi = Math.max(oldY, newY) + 1;
1481 for (var i = 0; i < this.blocks.length; i++)
1482 {
1483 var other = this.blocks[i];
1484 if (other === falling || other.col !== falling.col)
1485 { continue; }
1486 if (other.state !== STATE_MANUAL)
1487 { continue; }
1488 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1489 { return other; }
1490 }
1491 return null;
1492};
1493
1494GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY)
1495{
1496 var lo = Math.min(oldY, newY);
1497 var hi = Math.max(oldY, newY) + 1;
1498 var hits = [];
1499 for (var i = 0; i < this.blocks.length; i++)
1500 {
1501 var other = this.blocks[i];
1502 if (other === manual || other.col !== manual.col)
1503 { continue; }
1504 if (other.state !== STATE_FALLING)
1505 { continue; }
1506 if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9)
1507 { hits.push(other); }
1508 }
1509 if (!hits.length)
1510 { return hits; }
1511 return this.contiguousFallingInColumn(manual.col, manual, hits);
1512};
1513
1514/**
1515 * Every falling block in `col` that overlaps `anchor` or a hit already
1516 * in `seed`, plus a contiguous falling stack sitting on them.
1517 */
1518GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed)
1519{
1520 var falling = [];
1521 for (var i = 0; i < this.blocks.length; i++)
1522 {
1523 if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING)
1524 { falling.push(this.blocks[i]); }
1525 }
1526 falling.sort(function (a, b) { return a.y - b.y; });
1527 var include = Object.create(null);
1528 var queue = [];
1529 function enqueue (b)
1530 {
1531 if (!b || include[b.id])
1532 { return; }
1533 include[b.id] = true;
1534 queue.push(b);
1535 }
1536 if (seed)
1537 {
1538 for (var s = 0; s < seed.length; s++)
1539 { enqueue(seed[s]); }
1540 }
1541 // Also include falling that already overlap the anchor.
1542 if (anchor)
1543 {
1544 for (var i = 0; i < falling.length; i++)
1545 {
1546 if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9)
1547 { enqueue(falling[i]); }
1548 }
1549 }
1550 for (var q = 0; q < queue.length; q++)
1551 {
1552 var a = queue[q];
1553 for (var i = 0; i < falling.length; i++)
1554 {
1555 var b = falling[i];
1556 if (include[b.id])
1557 { continue; }
1558 if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9)
1559 { enqueue(b); }
1560 }
1561 }
1562 var out = [];
1563 for (var i = 0; i < falling.length; i++)
1564 {
1565 if (include[falling[i].id])
1566 { out.push(falling[i]); }
1567 }
1568 return out;
1569};
1570
1571/**
1572 * Merge a thrown (manual) block with falling blocks into one flying
1573 * cluster. Velocity, deceleration and jumpHeight are the mass-weighted
1574 * averages by block count, identical to mergeClusterGroup. The thrown
1575 * block stops being manual and the group follows normal cluster physics.
1576 * fromManual marks the cluster so later falling cargo also averages in.
1577 */
1578GameCore.prototype.mergeManualWithFalling = function (manual, fallingList)
1579{
1580 if (!manual || manual.state !== STATE_MANUAL)
1581 { return null; }
1582 var blocks = [manual];
1583 for (var i = 0; i < fallingList.length; i++)
1584 {
1585 if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0)
1586 { blocks.push(fallingList[i]); }
1587 }
1588 if (blocks.length < 2)
1589 { return null; }
1590 var n = blocks.length;
1591 var vySum = 0;
1592 var decelSum = 0;
1593 var hSum = 0;
1594 for (var i = 0; i < n; i++)
1595 {
1596 var b = blocks[i];
1597 vySum += b.vy;
1598 if (b === manual)
1599 {
1600 decelSum += manual.manualDecel || 0;
1601 hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight
1602 : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y);
1603 }
1604 }
1605 var cluster = {
1606 id: this.nextClusterId++,
1607 jumpHeight: hSum / n,
1608 vy: vySum / n,
1609 decel: decelSum / n,
1610 phase: (vySum / n) > 1e-10 ? 'up' : 'down',
1611 fromManual: true
1612 };
1613 this.clusters[cluster.id] = cluster;
1614 for (var i = 0; i < n; i++)
1615 {
1616 var b = blocks[i];
1617 b.clusterId = cluster.id;
1618 b.state = STATE_FLYING;
1619 b.vy = cluster.vy;
1620 b.flame = b.color === COLOR_GRAY;
1621 b.manualPhase = null;
1622 b.manualTarget = null;
1623 b.manualDecel = 0;
1624 b.manualJumpHeight = 0;
1625 b.pushedClusters = null;
1626 b.settleTime = 0;
1627 }
1628 if (this.drag && this.drag.blockId === manual.id)
1629 { this.drag = null; }
1630 this.prepareClusterBody(cluster);
1631 this.checkChainRelaunch(cluster);
1632 return cluster;
1633};
1634
1635/** Safety net: any remaining manual/falling overlaps after the substep. */
1636GameCore.prototype.mergeAnyManualFallingOverlaps = function ()
1637{
1638 var manuals = [];
1639 for (var i = 0; i < this.blocks.length; i++)
1640 {
1641 if (this.blocks[i].state === STATE_MANUAL)
1642 { manuals.push(this.blocks[i]); }
1643 }
1644 for (var m = 0; m < manuals.length; m++)
1645 {
1646 var manual = manuals[m];
1647 if (manual.state !== STATE_MANUAL)
1648 { continue; }
1649 var hits = this.contiguousFallingInColumn(manual.col, manual);
1650 if (hits.length)
1651 { this.mergeManualWithFalling(manual, hits); }
1652 }
1653};
1654
1655/**
1656 * Resolve collisions of a thrown (manual) block along [oldY, nextY].
1657 * Falling blocks merge (t1108). A flying cluster is pushed one cell up
1658 * in the hit column and the shot attaches at the bottom (t1111).
1659 * Another thrown block is promoted to a 1-block cluster and then the
1660 * same attach-at-bottom rule applies. Returns true if `manual` is no
1661 * longer in the MANUAL state.
1662 */
1663GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY)
1664{
1665 if (!manual || manual.state !== STATE_MANUAL)
1666 { return true; }
1667
1668 var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY);
1669 if (fallingHits.length)
1670 {
1671 this.mergeManualWithFalling(manual, fallingHits);
1672 return manual.state !== STATE_MANUAL;
1673 }
1674
1675 var flyer = this.flyingHitOnManualPath(manual, oldY, nextY);
1676 if (flyer)
1677 {
1678 var cluster = this.clusters[flyer.clusterId];
1679 if (cluster && cluster.phase !== 'landed')
1680 {
1681 if (nextY + 1e-12 < oldY)
1682 { this.attachToFlyingCluster(manual, flyer); }
1683 else
1684 { this.attachShotUnderCluster(manual, cluster, manual.col); }
1685 return manual.state !== STATE_MANUAL;
1686 }
1687 }
1688
1689 var other = this.manualHitOnManualPath(manual, oldY, nextY);
1690 if (other)
1691 {
1692 var host = this.promoteManualToCluster(other);
1693 if (host)
1694 {
1695 if (nextY + 1e-12 < oldY)
1696 { this.attachToFlyingCluster(manual, other); }
1697 else
1698 { this.attachShotUnderCluster(manual, host, manual.col); }
1699 return manual.state !== STATE_MANUAL;
1700 }
1701 }
1702 return false;
1703};
1704
1705/** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */
1706GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY)
1707{
1708 var lo = Math.min(oldY, nextY);
1709 var hi = Math.max(oldY, nextY) + 1;
1710 var best = null;
1711 var bestY = Infinity;
1712 for (var i = 0; i < this.blocks.length; i++)
1713 {
1714 var other = this.blocks[i];
1715 if (other === manual || other.col !== manual.col)
1716 { continue; }
1717 if (other.state !== STATE_FLYING || other.clusterId == null)
1718 { continue; }
1719 var cluster = this.clusters[other.clusterId];
1720 if (!cluster || cluster.phase === 'landed')
1721 { continue; }
1722 var o0 = (other._prevY != null) ? other._prevY : other.y;
1723 var o1 = other.y;
1724 var oLo = Math.min(o0, o1);
1725 var oHi = Math.max(o0, o1) + 1;
1726 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
1727 {
1728 if (other.y < bestY)
1729 {
1730 bestY = other.y;
1731 best = other;
1732 }
1733 }
1734 }
1735 return best;
1736};
1737
1738/** Another thrown block in the same column on the path (prefer the lower). */
1739GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY)
1740{
1741 var lo = Math.min(oldY, nextY);
1742 var hi = Math.max(oldY, nextY) + 1;
1743 var best = null;
1744 for (var i = 0; i < this.blocks.length; i++)
1745 {
1746 var other = this.blocks[i];
1747 if (other === manual || other.col !== manual.col)
1748 { continue; }
1749 if (other.state !== STATE_MANUAL)
1750 { continue; }
1751 var o0 = (other._prevY != null) ? other._prevY : other.y;
1752 var o1 = other.y;
1753 var oLo = Math.min(o0, o1);
1754 var oHi = Math.max(o0, o1) + 1;
1755 if (lo < oHi - 1e-9 && oLo < hi - 1e-9)
1756 {
1757 if (!best || other.y < best.y)
1758 { best = other; }
1759 }
1760 }
1761 return best;
1762};
1763
1764/**
1765 * t1111: push every member of `cluster` in `col` up by one cell, then
1766 * attach `manual` at the bottom of that column, grid-aligned, as part
1767 * of the cluster. The cluster keeps its velocity; the shot takes it.
1768 * Other columns are untouched. Same rule for every successive shot.
1769 */
1770GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col)
1771{
1772 if (!manual || !cluster || !this.clusters[cluster.id])
1773 { return false; }
1774 if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id)
1775 {
1776 // Already belonging elsewhere: leave first.
1777 if (manual.clusterId != null)
1778 { this.leaveCluster(manual); }
1779 }
1780 this.prepareClusterBody(cluster);
1781 var members = this.clusterMembers(cluster.id);
1782 var minOff = null;
1783 for (var i = 0; i < members.length; i++)
1784 {
1785 if (members[i].col !== col)
1786 { continue; }
1787 if (minOff == null || members[i].clusterOffset < minOff)
1788 { minOff = members[i].clusterOffset; }
1789 }
1790 if (minOff == null)
1791 { minOff = 0; }
1792 else
1793 {
1794 for (var i = 0; i < members.length; i++)
1795 {
1796 if (members[i].col === col)
1797 { members[i].clusterOffset += 1; }
1798 }
1799 }
1800 if (this.drag && this.drag.blockId === manual.id)
1801 { this.drag = null; }
1802 manual.clusterId = cluster.id;
1803 manual.clusterOffset = minOff;
1804 manual.state = STATE_FLYING;
1805 manual.flame = manual.color === COLOR_GRAY;
1806 manual.settleTime = 0;
1807 manual.manualPhase = null;
1808 manual.manualTarget = null;
1809 manual.manualDecel = 0;
1810 manual.manualJumpHeight = 0;
1811 manual.pushedClusters = null;
1812 this.syncClusterMembers(cluster);
1813 this.cullOffTop();
1814 if (this.clusters[cluster.id])
1815 { this.checkChainRelaunch(cluster); }
1816 return true;
1817};
1818
1819/**
1820 * Turn a lone thrown block into a 1-block flying cluster so a later
1821 * shot can use the t1111 attach-at-bottom rule. A single throw stays
1822 * MANUAL (and is capped at the top of the field) until it collides.
1823 */
1824GameCore.prototype.promoteManualToCluster = function (manual)
1825{
1826 if (!manual)
1827 { return null; }
1828 if (manual.state === STATE_FLYING && manual.clusterId != null)
1829 {
1830 var existing = this.clusters[manual.clusterId];
1831 if (existing && existing.phase !== 'landed')
1832 { return existing; }
1833 }
1834 if (manual.state !== STATE_MANUAL)
1835 { return null; }
1836 var height = manual.manualJumpHeight != null ? manual.manualJumpHeight
1837 : Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y);
1838 var cluster = {
1839 id: this.nextClusterId++,
1840 jumpHeight: height,
1841 vy: manual.vy,
1842 decel: manual.manualDecel || 0,
1843 phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up',
1844 fromManual: true,
1845 anchorY: manual.y
1846 };
1847 this.clusters[cluster.id] = cluster;
1848 manual.state = STATE_FLYING;
1849 manual.clusterId = cluster.id;
1850 manual.clusterOffset = 0;
1851 manual.flame = manual.color === COLOR_GRAY;
1852 manual.settleTime = 0;
1853 manual.manualPhase = null;
1854 manual.manualTarget = null;
1855 manual.manualDecel = 0;
1856 manual.manualJumpHeight = 0;
1857 manual.pushedClusters = null;
1858 this.syncClusterMembers(cluster);
1859 return cluster;
1860};
1861
1862/** Kept for older tests / call sites: push a cluster column by one cell. */
1863GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1864{
1865 return this.resolveManualCollisions(manual, oldY, nextY);
1866};
1867
1868
1869/**
1870 * Push every flying block of the cluster that sits in `col` one tile up.
1871 * Other columns stay put (they remain linked). Then look for a new
1872 * same-color line of 3+ in the flying cluster; if there is one, those
1873 * blocks turn gray, join the link, and the whole cluster re-launches
1874 * with the same jump height from its current position.
1875 */
1876GameCore.prototype.pushClusterColumn = function (clusterId, col)
1877{
1878 var cluster = this.clusters[clusterId];
1879 if (!cluster)
1880 { return false; }
1881 var members = this.clusterMembers(clusterId);
1882 for (var i = 0; i < members.length; i++)
1883 {
1884 if (members[i].col === col)
1885 { members[i].y += 1; }
1886 }
1887 this.cullOffTop();
1888 if (!this.clusters[clusterId])
1889 { return true; }
1890 this.checkChainRelaunch(cluster);
1891 return true;
1892};
1893
1894/**
1895 * After a cargo attach or a cluster merge (or any other mid-air state
1896 * change), turn spontaneous lines of 3+ into rockets and give the whole
1897 * already-flying cluster an extra launch from its current position —
1898 * the same re-launch as a player push that completes a row.
1899 */
1900GameCore.prototype.resolveFlyingMatches = function ()
1901{
1902 var ids = Object.keys(this.clusters);
1903 for (var n = 0; n < ids.length; n++)
1904 {
1905 var cluster = this.clusters[ids[n]];
1906 if (!cluster || cluster.phase === 'landed')
1907 { continue; }
1908 this.checkChainRelaunch(cluster);
1909 }
1910};
1911
1912GameCore.prototype.checkChainRelaunch = function (cluster)
1913{
1914 if (!this.clusters[cluster.id])
1915 { return; }
1916 var lines = this.findFlyingMatchLines(cluster.id);
1917 if (!lines.length)
1918 { return; }
1919 var newly = [];
1920 var seen = Object.create(null);
1921 for (var i = 0; i < lines.length; i++)
1922 {
1923 for (var j = 0; j < lines[i].blocks.length; j++)
1924 {
1925 var block = lines[i].blocks[j];
1926 if (seen[block.id])
1927 { continue; }
1928 seen[block.id] = true;
1929 newly.push(block);
1930 }
1931 }
1932 for (var i = 0; i < newly.length; i++)
1933 {
1934 var block = newly[i];
1935 block.color = COLOR_GRAY;
1936 block.flame = true;
1937 block.clusterId = cluster.id;
1938 block.state = STATE_FLYING;
1939 }
1940 this.relaunchCluster(cluster, cluster.jumpHeight);
1941};
1942
1943GameCore.prototype.relaunchCluster = function (cluster, height)
1944{
1945 cluster.jumpHeight = height;
1946 cluster.vy = PlanetMod.launchVelocity(this.planet, height);
1947 cluster.decel = PlanetMod.launchDeceleration(this.planet, height);
1948 cluster.phase = 'up';
1949 var members = this.clusterMembers(cluster.id);
1950 for (var i = 0; i < members.length; i++)
1951 {
1952 members[i].vy = cluster.vy;
1953 members[i].state = STATE_FLYING;
1954 if (members[i].color === COLOR_GRAY)
1955 { members[i].flame = true; }
1956 }
1957};
1958
1959GameCore.prototype.startManualLaunch = function (block)
1960{
1961 var target = this.height - 1;
1962 var height = Math.max(0.05, target - block.y);
1963 this.leaveCluster(block);
1964 block.state = STATE_MANUAL;
1965 block.pushedClusters = Object.create(null);
1966 block.manualTarget = target;
1967 block.manualPhase = 'up';
1968 block.manualJumpHeight = height;
1969 block.vy = PlanetMod.launchVelocity(this.planet, height);
1970 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
1971 block.flame = false;
1972 if (this.drag && this.drag.blockId === block.id)
1973 { this.drag = null; }
1974};
1975
1976GameCore.prototype.cullOffTop = function ()
1977{
1978 var gone = [];
1979 for (var i = 0; i < this.blocks.length; i++)
1980 {
1981 var block = this.blocks[i];
1982 if (block.state === STATE_MANUAL)
1983 {
1984 if (block.y > this.height - 1)
1985 { block.y = this.height - 1; }
1986 continue;
1987 }
1988 if (block.y >= this.height - 1e-9)
1989 { gone.push(block); }
1990 }
1991 for (var i = 0; i < gone.length; i++)
1992 {
1993 var block = gone[i];
1994 this.outgoingShots.push({
1995 id: block.id,
1996 color: block.color,
1997 col: block.col,
1998 y: block.y
1999 });
2000 this.score += 1;
2001 this.removeBlock(block);
2002 }
2003};
2004
2005GameCore.prototype.consumeOutgoingShots = function ()
2006{
2007 var shots = this.outgoingShots;
2008 this.outgoingShots = [];
2009 return shots;
2010};
2011
2012/**
2013 * A compact field picture for the multiplayer snapshot (miniatures).
2014 * Includes every block's col, y, color, state and flame.
2015 */
2016GameCore.prototype.fieldSnapshot = function ()
2017{
2018 var blocks = [];
2019 for (var i = 0; i < this.blocks.length; i++)
2020 {
2021 var b = this.blocks[i];
2022 blocks.push({
2023 id: b.id,
2024 col: b.col,
2025 y: Math.round(b.y * 1000) / 1000,
2026 color: b.color,
2027 state: b.state,
2028 flame: !!b.flame
2029 });
2030 }
2031 return {
2032 score: this.score,
2033 state: this.state,
2034 width: this.width,
2035 height: this.height,
2036 locked: this.lockedColumnCount(),
2037 blocks: blocks
2038 };
2039};
2040
2041/**
2042 * Incoming garbage from another player: a dark-grey block that falls
2043 * normally from the top of an open column. After landing it uses the
2044 * usual 3s settle and then a random colour (landFallingBlock).
2045 * `col` is optional; a random eligible column is used otherwise.
2046 * Returns the new block, or null if every column is locked or full.
2047 */
2048GameCore.prototype.ingestGarbage = function (col)
2049{
2050 if (this.state !== 'playing')
2051 { return null; }
2052 var chosen = null;
2053 if (col != null && col >= 0 && col < this.width
2054 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
2055 { chosen = col | 0; }
2056 else
2057 {
2058 var eligible = [];
2059 for (var c = 0; c < this.width; c++)
2060 {
2061 if (this.isColumnLocked(c))
2062 { continue; }
2063 if (this.groundedCount(c) >= this.height)
2064 { continue; }
2065 eligible.push(c);
2066 }
2067 if (!eligible.length)
2068 { return null; }
2069 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2070 }
2071 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2072 block.vy = -this.planet.fallSpeed;
2073 block.flame = false;
2074 return block;
2075};
2076
2077GameCore.prototype.advanceSettle = function (dt)
2078{
2079 for (var i = 0; i < this.blocks.length; i++)
2080 {
2081 var block = this.blocks[i];
2082 if (block.state !== STATE_SETTLING)
2083 { continue; }
2084 var inLanded = block.clusterId != null
2085 && this.clusters[block.clusterId]
2086 && this.clusters[block.clusterId].phase === 'landed';
2087 if (block.color === COLOR_GRAY)
2088 {
2089 block.settleTime += dt;
2090 if (block.settleTime >= this.settleTime)
2091 {
2092 block.color = this.randomColor();
2093 block.settleTime = 0;
2094 block.flame = false;
2095 if (inLanded)
2096 {
2097 // Stay in the rigid group; releaseLandedCluster runs below.
2098 block.state = STATE_SETTLING;
2099 }
2100 else
2101 {
2102 this.leaveCluster(block);
2103 this.clearFlightState(block);
2104 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2105 }
2106 }
2107 }
2108 else if (!inLanded)
2109 {
2110 // Coloured settling that is not in a landed cluster (shouldn't
2111 // normally happen): just become still or fall, from rest.
2112 this.leaveCluster(block);
2113 this.clearFlightState(block);
2114 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2115 }
2116 }
2117
2118 var ids = Object.keys(this.clusters);
2119 for (var n = 0; n < ids.length; n++)
2120 {
2121 var cluster = this.clusters[ids[n]];
2122 if (!cluster || cluster.phase !== 'landed')
2123 { continue; }
2124 var members = this.clusterMembers(cluster.id);
2125 var greySettling = false;
2126 for (var i = 0; i < members.length; i++)
2127 {
2128 if (members[i].color === COLOR_GRAY && members[i].state === STATE_SETTLING)
2129 { greySettling = true; }
2130 }
2131 if (!greySettling)
2132 { this.releaseLandedCluster(cluster); }
2133 }
2134};
2135
2136GameCore.prototype.findMatchLines = function ()
2137{
2138 var candidates = [];
2139 for (var i = 0; i < this.blocks.length; i++)
2140 {
2141 var block = this.blocks[i];
2142 // Coloured cargo in a just-landed cluster (SETTLING) can match
2143 // with already-resting blocks immediately (t1110). Greys have no
2144 // colour and wait until they recolor; after release they are STILL.
2145 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
2146 && block.color >= 0)
2147 { candidates.push(block); }
2148 }
2149 return this.collectLines(candidates, true);
2150};
2151
2152GameCore.prototype.findFlyingMatchLines = function (clusterId)
2153{
2154 var candidates = [];
2155 for (var i = 0; i < this.blocks.length; i++)
2156 {
2157 var block = this.blocks[i];
2158 if (block.clusterId === clusterId && block.color >= 0
2159 && (block.state === STATE_FLYING))
2160 { candidates.push(block); }
2161 }
2162 return this.collectLines(candidates, false);
2163};
2164
2165GameCore.prototype.collectLines = function (candidates, snapInteger)
2166{
2167 var lines = [];
2168 if (!candidates.length)
2169 { return lines; }
2170
2171 var byRow = Object.create(null);
2172 for (var i = 0; i < candidates.length; i++)
2173 {
2174 var block = candidates[i];
2175 var row = Math.round(block.y);
2176 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
2177 { continue; }
2178 if (!byRow[row])
2179 { byRow[row] = []; }
2180 byRow[row].push(block);
2181 }
2182 var rows = Object.keys(byRow);
2183 for (var r = 0; r < rows.length; r++)
2184 {
2185 var list = byRow[rows[r]];
2186 list.sort(function (a, b) { return a.col - b.col; });
2187 this.pushRuns(lines, list, false, function (a, b)
2188 {
2189 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
2190 });
2191 }
2192
2193 var byCol = Object.create(null);
2194 for (var i = 0; i < candidates.length; i++)
2195 {
2196 var block = candidates[i];
2197 if (!byCol[block.col])
2198 { byCol[block.col] = []; }
2199 byCol[block.col].push(block);
2200 }
2201 var cols = Object.keys(byCol);
2202 for (var c = 0; c < cols.length; c++)
2203 {
2204 var list = byCol[cols[c]];
2205 list.sort(function (a, b) { return a.y - b.y; });
2206 this.pushRuns(lines, list, true, function (a, b)
2207 {
2208 return a.color === b.color && a.color >= 0
2209 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
2210 });
2211 }
2212 return lines;
2213};
2214
2215GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
2216{
2217 var start = 0;
2218 for (var i = 1; i <= list.length; i++)
2219 {
2220 var same = i < list.length && adjacent(list[i - 1], list[i]);
2221 if (!same)
2222 {
2223 var length = i - start;
2224 if (length >= 3)
2225 {
2226 lines.push({
2227 blocks: list.slice(start, i),
2228 length: length,
2229 vertical: vertical
2230 });
2231 }
2232 start = i;
2233 }
2234 }
2235};
2236
2237GameCore.prototype.resolveMatches = function ()
2238{
2239 if (this.state !== 'playing' || this.drag)
2240 { return []; }
2241 var lines = this.findMatchLines();
2242 if (!lines.length)
2243 {
2244 this.finishLandingChains([]);
2245 return [];
2246 }
2247
2248 var uf = new UnionFind();
2249 var blockById = Object.create(null);
2250 for (var i = 0; i < lines.length; i++)
2251 {
2252 var line = lines[i];
2253 for (var j = 0; j < line.blocks.length; j++)
2254 {
2255 uf.add(line.blocks[j].id);
2256 blockById[line.blocks[j].id] = line.blocks[j];
2257 if (j > 0)
2258 { uf.union(line.blocks[0].id, line.blocks[j].id); }
2259 }
2260 }
2261 var matched = [];
2262 var seen = Object.create(null);
2263 for (var id in blockById)
2264 {
2265 if (!seen[id])
2266 {
2267 seen[id] = true;
2268 matched.push(blockById[id]);
2269 }
2270 }
2271 for (var i = 0; i < matched.length; i++)
2272 {
2273 for (var j = i + 1; j < matched.length; j++)
2274 {
2275 if (matched[i].col === matched[j].col)
2276 { uf.union(matched[i].id, matched[j].id); }
2277 }
2278 }
2279
2280 var groups = Object.create(null);
2281 for (var i = 0; i < matched.length; i++)
2282 {
2283 var root = uf.find(matched[i].id);
2284 if (!groups[root])
2285 { groups[root] = []; }
2286 groups[root].push(matched[i]);
2287 }
2288
2289 var launched = [];
2290 for (var root in groups)
2291 {
2292 var group = groups[root];
2293 var height = 0;
2294 for (var i = 0; i < lines.length; i++)
2295 {
2296 var line = lines[i];
2297 var overlaps = false;
2298 for (var j = 0; j < line.blocks.length; j++)
2299 {
2300 for (var k = 0; k < group.length; k++)
2301 {
2302 if (line.blocks[j].id === group[k].id)
2303 { overlaps = true; }
2304 }
2305 }
2306 if (overlaps)
2307 {
2308 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
2309 if (h > height)
2310 { height = h; }
2311 }
2312 }
2313 var chain = this.landingChainFor(group);
2314 var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;
2315 height *= bonusMul;
2316 this.launchCluster(group, height, { landingChain: chain });
2317 launched.push({
2318 blocks: group,
2319 jumpHeight: height,
2320 landingChain: chain,
2321 chainBonus: bonusMul
2322 });
2323 }
2324 this.finishLandingChains(launched);
2325 this.updateChainIndicator(launched);
2326 return launched;
2327};
2328
2329/**
2330 * Gray the matched blocks, take everything sitting on top of them in
2331 * those columns, link them, and launch with jump height `height`.
2332 */
2333GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)
2334{
2335 opts = opts || {};
2336 var lowestInCol = Object.create(null);
2337 var matchedIds = Object.create(null);
2338 for (var i = 0; i < matchedBlocks.length; i++)
2339 {
2340 var block = matchedBlocks[i];
2341 matchedIds[block.id] = true;
2342 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
2343 { lowestInCol[block.col] = block.y; }
2344 }
2345
2346 var clusterId = this.nextClusterId++;
2347 var cluster = {
2348 id: clusterId,
2349 jumpHeight: height,
2350 vy: PlanetMod.launchVelocity(this.planet, height),
2351 decel: PlanetMod.launchDeceleration(this.planet, height),
2352 phase: 'up',
2353 landingChain: opts.landingChain || 0,
2354 landedPending: false
2355 };
2356 this.clusters[clusterId] = cluster;
2357
2358 var riders = [];
2359 var cols = Object.keys(lowestInCol);
2360 for (var c = 0; c < cols.length; c++)
2361 {
2362 var col = +cols[c];
2363 var lowest = lowestInCol[col];
2364 var list = this.blocksInColumn(col);
2365 for (var i = 0; i < list.length; i++)
2366 {
2367 var block = list[i];
2368 if (!this.isGrounded(block) && block.state !== STATE_STILL)
2369 {
2370 if (block.state !== STATE_SETTLING)
2371 { continue; }
2372 }
2373 if (block.y + ALIGN_EPS >= lowest)
2374 { riders.push(block); }
2375 }
2376 }
2377
2378 for (var i = 0; i < riders.length; i++)
2379 {
2380 var block = riders[i];
2381 var isMatch = !!matchedIds[block.id];
2382 if (isMatch || block.color === COLOR_GRAY)
2383 {
2384 block.color = COLOR_GRAY;
2385 block.flame = true;
2386 }
2387 else
2388 { block.flame = false; }
2389 block.state = STATE_FLYING;
2390 block.clusterId = clusterId;
2391 block.vy = cluster.vy;
2392 block.settleTime = 0;
2393 }
2394 this.prepareClusterBody(cluster);
2395 return cluster;
2396};
2397
2398GameCore.prototype.checkLocks = function ()
2399{
2400 for (var col = 0; col < this.width; col++)
2401 {
2402 if (this.isColumnLocked(col))
2403 { continue; }
2404 if (this.groundedCount(col) < this.height)
2405 { continue; }
2406 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
2407 var filled = true;
2408 for (var row = 0; row < this.height; row++)
2409 {
2410 var block = this.blockAt(col, row);
2411 if (!block || !this.isGrounded(block))
2412 {
2413 filled = false;
2414 break;
2415 }
2416 }
2417 if (!filled)
2418 { continue; }
2419 var list = this.blocksInColumn(col);
2420 for (var i = 0; i < list.length; i++)
2421 {
2422 var block = list[i];
2423 if (!this.isGrounded(block))
2424 { continue; }
2425 block.state = STATE_LOCKED;
2426 block.color = COLOR_GRAY;
2427 block.flame = false;
2428 block.vy = 0;
2429 block.settleTime = 0;
2430 if (block.clusterId != null)
2431 { this.leaveCluster(block); }
2432 }
2433 }
2434};
2435
2436GameCore.prototype.checkGameOver = function ()
2437{
2438 if (this.state !== 'playing')
2439 { return; }
2440 for (var col = 0; col < this.width; col++)
2441 {
2442 if (!this.isColumnLocked(col))
2443 { return; }
2444 }
2445 this.state = 'gameover';
2446 this.gameOverTime = 0;
2447 this.drag = null;
2448};
2449
2450/* ---------- dragging -------------------------------------------------- */
2451
2452GameCore.prototype.beginDrag = function (col, y)
2453{
2454 if (this.state !== 'playing')
2455 { return false; }
2456 var block = this.snapDragBlock(col, y);
2457 if (!block)
2458 { return false; }
2459 var top = this.columnStackTopRow(block.col);
2460 var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
2461 this.drag = {
2462 blockId: block.id,
2463 pointerY: y,
2464 startY: y,
2465 accum: 0,
2466 launchIntent: false,
2467 startedAsTop: startedAsTop
2468 };
2469 return true;
2470};
2471
2472/**
2473 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
2474 * floor(col), floor(y); any press inside that cell — corners, padding,
2475 * gaps between sprites, a visually tweened or bouncing sprite — grabs
2476 * the block that occupies it. This uses simulation cells, not the drawn
2477 * sprite bounds. If no block sits in that cell (mid-animation, a block
2478 * whose y is off the integer), fall back to the nearest grabbable block
2479 * in the same column within SNAP_Y (about half a tile). A small
2480 * horizontal slop still consults a neighbouring column when the press
2481 * is near the edge and the primary cell is empty.
2482 */
2483GameCore.prototype.snapDragBlock = function (col, y)
2484{
2485 var raw = col;
2486 var c0 = Math.floor(raw + 1e-9);
2487 var row = Math.floor(y + 1e-9);
2488 var frac = raw - c0;
2489
2490 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
2491 {
2492 var exact = this.draggableInCell(c0, row);
2493 if (exact)
2494 { return exact; }
2495 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
2496 if (near)
2497 { return near; }
2498 }
2499
2500 // Primary cell empty: allow a small horizontal slop into a neighbour.
2501 var neighbours = [];
2502 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
2503 { neighbours.push(c0 - 1); }
2504 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
2505 { neighbours.push(c0 + 1); }
2506 var best = null;
2507 var bestDist = Infinity;
2508 for (var n = 0; n < neighbours.length; n++)
2509 {
2510 var cc = neighbours[n];
2511 if (!this.columnAllowsDrag(cc))
2512 { continue; }
2513 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
2514 if (!hit)
2515 { continue; }
2516 var dist = this.pointerDistToBlock(hit, raw, y);
2517 if (dist < bestDist)
2518 {
2519 bestDist = dist;
2520 best = hit;
2521 }
2522 }
2523 return best;
2524};
2525
2526/** The draggable block that occupies grid cell (col, row), if any. */
2527GameCore.prototype.draggableInCell = function (col, row)
2528{
2529 var best = null;
2530 var bestOverlap = 0;
2531 var list = this.blocksInColumn(col);
2532 for (var i = 0; i < list.length; i++)
2533 {
2534 var block = list[i];
2535 if (!this.isDraggableBlock(block))
2536 { continue; }
2537 var lo = Math.max(block.y, row);
2538 var hi = Math.min(block.y + 1, row + 1);
2539 var overlap = hi - lo;
2540 if (overlap > bestOverlap + 1e-12)
2541 {
2542 bestOverlap = overlap;
2543 best = block;
2544 }
2545 }
2546 if (best && bestOverlap > 1e-9)
2547 { return best; }
2548 return null;
2549};
2550
2551/** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
2552GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
2553{
2554 var best = null;
2555 var bestDist = Infinity;
2556 var list = this.blocksInColumn(col);
2557 for (var i = 0; i < list.length; i++)
2558 {
2559 var block = list[i];
2560 if (!this.isDraggableBlock(block))
2561 { continue; }
2562 var dist = this.pointerDistToBlock(block, col + 0.5, y);
2563 if (dist < bestDist)
2564 {
2565 bestDist = dist;
2566 best = block;
2567 }
2568 }
2569 if (!best || bestDist > maxDist)
2570 { return null; }
2571 return best;
2572};
2573
2574GameCore.prototype.pointerDistToBlock = function (block, col, y)
2575{
2576 var dx;
2577 if (col >= block.col && col < block.col + 1)
2578 { dx = 0; }
2579 else if (col < block.col)
2580 { dx = block.col - col; }
2581 else
2582 { dx = col - (block.col + 1); }
2583 var dy;
2584 if (y >= block.y && y < block.y + 1)
2585 { dy = 0; }
2586 else if (y < block.y)
2587 { dy = block.y - y; }
2588 else
2589 { dy = y - (block.y + 1); }
2590 return Math.sqrt(dx * dx + dy * dy);
2591};
2592
2593GameCore.prototype.moveDrag = function (y)
2594{
2595 if (!this.drag)
2596 { return; }
2597 var block = this.blockById(this.drag.blockId);
2598 if (!block || !this.isDraggableBlock(block))
2599 {
2600 this.drag = null;
2601 return;
2602 }
2603 if (!this.columnAllowsDrag(block.col))
2604 {
2605 this.drag = null;
2606 return;
2607 }
2608 this.drag.pointerY = y;
2609 // 1:1 tracking: the target row is the one under the pointer, clamped
2610 // to the still stack. Swap step by step with each neighbour, and stop
2611 // exactly there. When the pointer stops, nothing else moves.
2612 // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
2613 // used to jump a full cell on a short pull, and one large event
2614 // could walk the entire column (the "jumps all the way" bug).
2615 var top = this.columnStackTopRow(block.col);
2616 var bottom = this.columnStackBottomRow(block.col);
2617 var target = Math.floor(y + 1e-12);
2618 if (bottom < 0)
2619 { bottom = 0; }
2620 if (target < bottom)
2621 { target = bottom; }
2622 if (target > top)
2623 { target = top; }
2624 this.swapToward(block, target);
2625
2626 top = this.columnStackTopRow(block.col);
2627 var isTop = Math.abs(block.y - top) < ALIGN_EPS;
2628 if (this.drag.startedAsTop)
2629 {
2630 // Already the topmost block: pulling upward past its own position
2631 // (LAUNCH_PULL tiles above the press point) starts a manual jump.
2632 this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL);
2633 }
2634 else
2635 {
2636 // Started mid-stack: swap first, and only launch once the pointer
2637 // is pulled into the empty space above the (new) top.
2638 this.drag.launchIntent = isTop && (y > top + 1 + 0.25);
2639 }
2640};
2641
2642/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
2643GameCore.prototype.swapOne = function (block, dir)
2644{
2645 var neighbor = this.blockAt(block.col, block.y + dir);
2646 if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
2647 {
2648 this.swapBlocks(block, neighbor);
2649 return true;
2650 }
2651 return false;
2652};
2653
2654GameCore.prototype.endDrag = function ()
2655{
2656 if (!this.drag)
2657 { return; }
2658 var block = this.blockById(this.drag.blockId);
2659 var launch = this.drag.launchIntent;
2660 this.drag = null;
2661 if (launch && block && block.state === STATE_STILL)
2662 { this.startManualLaunch(block); }
2663 else
2664 { this.resolveMatches(); }
2665};
2666
2667GameCore.prototype.blockById = function (id)
2668{
2669 for (var i = 0; i < this.blocks.length; i++)
2670 {
2671 if (this.blocks[i].id === id)
2672 { return this.blocks[i]; }
2673 }
2674 return null;
2675};
2676
2677GameCore.prototype.columnStackTopRow = function (col)
2678{
2679 var top = -1;
2680 var list = this.blocksInColumn(col);
2681 for (var i = 0; i < list.length; i++)
2682 {
2683 if (this.isGrounded(list[i]) && list[i].y > top)
2684 { top = list[i].y; }
2685 }
2686 return top;
2687};
2688
2689GameCore.prototype.columnStackBottomRow = function (col)
2690{
2691 var bottom = Infinity;
2692 var list = this.blocksInColumn(col);
2693 for (var i = 0; i < list.length; i++)
2694 {
2695 if (this.isGrounded(list[i]) && list[i].y < bottom)
2696 { bottom = list[i].y; }
2697 }
2698 return bottom === Infinity ? 0 : bottom;
2699};
2700
2701GameCore.prototype.swapToward = function (block, targetY)
2702{
2703 var guard = 0;
2704 while (guard++ < this.height + 2)
2705 {
2706 var current = block.y;
2707 if (targetY > current + 0.5)
2708 {
2709 var above = this.blockAt(block.col, current + 1);
2710 if (above && this.isGrounded(above) && above !== block)
2711 { this.swapBlocks(block, above); }
2712 else
2713 { break; }
2714 }
2715 else if (targetY < current - 0.5)
2716 {
2717 var below = this.blockAt(block.col, current - 1);
2718 if (below && this.isGrounded(below) && below !== block)
2719 { this.swapBlocks(block, below); }
2720 else
2721 { break; }
2722 }
2723 else
2724 { break; }
2725 }
2726};
2727
2728GameCore.prototype.swapBlocks = function (a, b)
2729{
2730 var ay = a.y;
2731 var by = b.y;
2732 a.y = by;
2733 b.y = ay;
2734 this.transferLandedMembership(a, b);
2735 if (!this.swapEvents)
2736 { this.swapEvents = []; }
2737 this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });
2738 this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });
2739};
2740
2741GameCore.prototype.consumeSwapEvents = function ()
2742{
2743 var ev = this.swapEvents || [];
2744 this.swapEvents = [];
2745 return ev;
2746};
2747
2748/**
2749 * Highest landing-chain counter among just-landed members of this
2750 * match group, plus one. Returns 0 when the match did not come from
2751 * a cluster landing (player/bot swap, mid-air, etc.).
2752 */
2753GameCore.prototype.landingChainFor = function (group)
2754{
2755 var maxChain = 0;
2756 var fromLanding = false;
2757 for (var i = 0; i < group.length; i++)
2758 {
2759 var block = group[i];
2760 if (block.justLanded)
2761 {
2762 fromLanding = true;
2763 if ((block.landingChain || 0) > maxChain)
2764 { maxChain = block.landingChain || 0; }
2765 }
2766 if (block.clusterId != null)
2767 {
2768 var cluster = this.clusters[block.clusterId];
2769 if (cluster && cluster.landedPending)
2770 {
2771 fromLanding = true;
2772 if ((cluster.landingChain || 0) > maxChain)
2773 { maxChain = cluster.landingChain || 0; }
2774 }
2775 }
2776 }
2777 if (!fromLanding)
2778 { return 0; }
2779 return maxChain + 1;
2780};
2781
2782/**
2783 * After resolveMatches: clear the landing-pending flag and reset the
2784 * chain on landings that did not make a match. A cluster that is still
2785 * settling (greys not yet recolored) keeps landedPending so a later
2786 * post-recolor match in this same landing still gets the bonus.
2787 */
2788GameCore.prototype.finishLandingChains = function (launched)
2789{
2790 var launchedIds = Object.create(null);
2791 launched = launched || [];
2792 for (var i = 0; i < launched.length; i++)
2793 {
2794 var blocks = launched[i].blocks || [];
2795 for (var j = 0; j < blocks.length; j++)
2796 { launchedIds[blocks[j].id] = true; }
2797 }
2798
2799 for (var i = 0; i < this.blocks.length; i++)
2800 {
2801 var block = this.blocks[i];
2802 if (!block.justLanded)
2803 { continue; }
2804 if (!launchedIds[block.id])
2805 { block.landingChain = 0; }
2806 block.justLanded = false;
2807 }
2808
2809 var ids = Object.keys(this.clusters);
2810 for (var c = 0; c < ids.length; c++)
2811 {
2812 var cluster = this.clusters[ids[c]];
2813 if (!cluster || !cluster.landedPending)
2814 { continue; }
2815 var members = this.clusterMembers(cluster.id);
2816 var anyLaunched = false;
2817 var stillSettling = false;
2818 for (var i = 0; i < members.length; i++)
2819 {
2820 if (launchedIds[members[i].id])
2821 { anyLaunched = true; }
2822 if (members[i].state === STATE_SETTLING)
2823 { stillSettling = true; }
2824 }
2825 if (anyLaunched)
2826 {
2827 cluster.landingChain = 0;
2828 cluster.landedPending = false;
2829 }
2830 else if (!stillSettling)
2831 {
2832 // Released leftovers or a fully-still landed group that
2833 // already had its match opportunity and missed it.
2834 cluster.landingChain = 0;
2835 cluster.landedPending = false;
2836 }
2837 // else: still settling, no match yet — keep landedPending.
2838 }
2839};
2840
2841GameCore.prototype.updateChainIndicator = function (launched)
2842{
2843 var maxChain = 0;
2844 for (var i = 0; i < launched.length; i++)
2845 {
2846 var ch = launched[i].landingChain || 0;
2847 if (ch > maxChain)
2848 { maxChain = ch; }
2849 }
2850 if (maxChain >= 1)
2851 {
2852 this.lastChainIndicator = {
2853 chain: maxChain,
2854 bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)
2855 };
2856 return;
2857 }
2858 if (!this.hasActiveLandingChain())
2859 { this.lastChainIndicator = null; }
2860};
2861
2862GameCore.prototype.hasActiveLandingChain = function ()
2863{
2864 var ids = Object.keys(this.clusters);
2865 for (var i = 0; i < ids.length; i++)
2866 {
2867 var cluster = this.clusters[ids[i]];
2868 if (cluster && (cluster.landingChain || 0) >= 1
2869 && cluster.phase !== 'landed')
2870 { return true; }
2871 }
2872 return false;
2873};
2874
2875/**
2876 * A landed cluster (grey rockets or linked cargo resting on the ground)
2877 * is a swappable part of the contiguous grounded stack. Flying, falling
2878 * and manual blocks are not. A locked column is not.
2879 */
2880GameCore.prototype.isDraggableBlock = function (block)
2881{
2882 if (!block)
2883 { return false; }
2884 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
2885 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
2886 { return false; }
2887 if (block.clusterId != null)
2888 {
2889 var cluster = this.clusters[block.clusterId];
2890 // Flying (rising / descending) clusters stay non-draggable.
2891 if (cluster && cluster.phase !== 'landed')
2892 { return false; }
2893 }
2894 return block.state === STATE_STILL || block.state === STATE_SETTLING;
2895};
2896
2897/**
2898 * The grounded contiguous stack in this column can be dragged, even if a
2899 * flying cluster or a falling spawn occupies the air above it. Only a
2900 * locked column is blocked as a whole.
2901 */
2902GameCore.prototype.columnAllowsDrag = function (col)
2903{
2904 return !this.isColumnLocked(col);
2905};
2906
2907GameCore.prototype.landedClusterId = function (block)
2908{
2909 if (!block || block.clusterId == null)
2910 { return null; }
2911 var cluster = this.clusters[block.clusterId];
2912 if (!cluster || cluster.phase !== 'landed')
2913 { return null; }
2914 return block.clusterId;
2915};
2916
2917/**
2918 * After a swap: leaving a landed cluster clears membership; joining one
2919 * makes the block part of that rigid group. Same-cluster swaps only
2920 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
2921 */
2922GameCore.prototype.transferLandedMembership = function (a, b)
2923{
2924 var ca = this.landedClusterId(a);
2925 var cb = this.landedClusterId(b);
2926 if (ca === cb)
2927 { return; }
2928 // Join first so leaveCluster does not delete a cluster that still
2929 // has the incoming member.
2930 this.applyLandedMembership(b, ca);
2931 this.applyLandedMembership(a, cb);
2932};
2933
2934GameCore.prototype.applyLandedMembership = function (block, clusterId)
2935{
2936 if (clusterId == null)
2937 {
2938 var wasGrey = block.color === COLOR_GRAY;
2939 var wasSettling = block.state === STATE_SETTLING;
2940 this.leaveCluster(block);
2941 if (wasGrey && wasSettling)
2942 {
2943 // Keep settling and recolor on its own, same remaining timer.
2944 block.state = STATE_SETTLING;
2945 }
2946 else if (wasSettling)
2947 {
2948 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2949 }
2950 return;
2951 }
2952 if (!this.clusters[clusterId])
2953 { return; }
2954 block.clusterId = clusterId;
2955 block.flame = false;
2956 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
2957 { block.state = STATE_SETTLING; }
2958};
2959
2960/**
2961 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
2962 * Returns the moved block, or null if the column does not allow a drag.
2963 */
2964GameCore.prototype.swapTo = function (col, fromRow, toRow)
2965{
2966 if (!this.columnAllowsDrag(col))
2967 { return null; }
2968 var block = this.blockAt(col, fromRow);
2969 if (!block)
2970 { return null; }
2971 this.swapToward(block, toRow);
2972 return block;
2973};
2974
2975/**
2976 * Test helper: a compact picture of grounded/falling/flying blocks.
2977 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
2978 * L locked, f falling, m manual, . empty. Flying colored blocks use
2979 * their color with a marker in `flying`.
2980 */
2981GameCore.prototype.snapshot = function ()
2982{
2983 var grid = [];
2984 for (var r = 0; r < this.height; r++)
2985 {
2986 var row = [];
2987 for (var c = 0; c < this.width; c++)
2988 { row.push('.'); }
2989 grid.push(row);
2990 }
2991 var airborne = [];
2992 for (var i = 0; i < this.blocks.length; i++)
2993 {
2994 var block = this.blocks[i];
2995 var ch;
2996 if (block.state === STATE_LOCKED)
2997 { ch = 'L'; }
2998 else if (block.color === COLOR_GRAY)
2999 { ch = 'g'; }
3000 else
3001 { ch = String(block.color); }
3002 if (this.isGrounded(block) || block.state === STATE_FALLING)
3003 {
3004 var row = Math.round(block.y);
3005 if (row >= 0 && row < this.height)
3006 { grid[row][block.col] = ch; }
3007 }
3008 else
3009 {
3010 airborne.push({
3011 id: block.id,
3012 col: block.col,
3013 y: block.y,
3014 color: block.color,
3015 state: block.state,
3016 clusterId: block.clusterId,
3017 flame: block.flame,
3018 vy: block.vy
3019 });
3020 }
3021 }
3022 var lines = [];
3023 for (var r = this.height - 1; r >= 0; r--)
3024 { lines.push(grid[r].join('')); }
3025 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
3026};
3027
3028var GameCoreAPI = {
3029 GameCore: GameCore,
3030 COLOR_GRAY: COLOR_GRAY,
3031 STATE_STILL: STATE_STILL,
3032 STATE_FALLING: STATE_FALLING,
3033 STATE_FLYING: STATE_FLYING,
3034 STATE_SETTLING: STATE_SETTLING,
3035 STATE_LOCKED: STATE_LOCKED,
3036 STATE_MANUAL: STATE_MANUAL
3037};
3038
3039if (typeof module !== 'undefined' && module.exports)
3040{ module.exports = GameCoreAPI; }
3041else if (typeof globalThis !== 'undefined')
3042{
3043 globalThis.GameCore = GameCore;
3044 globalThis.GameCoreAPI = GameCoreAPI;
3045}