BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

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