BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

gameCore.js 78.9 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 vy: block.vy
2016 });
2017 this.score += 1;
2018 this.removeBlock(block);
2019 }
2020};
2021
2022GameCore.prototype.consumeOutgoingShots = function ()
2023{
2024 var shots = this.outgoingShots;
2025 this.outgoingShots = [];
2026 return shots;
2027};
2028
2029/**
2030 * A compact field picture for the multiplayer snapshot (miniatures).
2031 * Includes every block's col, y, color, state and flame.
2032 */
2033GameCore.prototype.fieldSnapshot = function ()
2034{
2035 var blocks = [];
2036 for (var i = 0; i < this.blocks.length; i++)
2037 {
2038 var b = this.blocks[i];
2039 blocks.push({
2040 id: b.id,
2041 col: b.col,
2042 y: Math.round(b.y * 1000) / 1000,
2043 color: b.color,
2044 state: b.state,
2045 flame: !!b.flame
2046 });
2047 }
2048 return {
2049 score: this.score,
2050 state: this.state,
2051 width: this.width,
2052 height: this.height,
2053 locked: this.lockedColumnCount(),
2054 blocks: blocks
2055 };
2056};
2057
2058/**
2059 * Incoming garbage from another player: a dark-grey block that falls
2060 * normally from the top of an open column. After landing it uses the
2061 * usual 3s settle and then a random colour (landFallingBlock).
2062 * `col` is optional; a random eligible column is used otherwise.
2063 * Returns the new block, or null if every column is locked or full.
2064 */
2065/**
2066 * Open columns a garbage block can fall into (not locked, not full).
2067 */
2068GameCore.prototype.eligibleGarbageColumns = function ()
2069{
2070 var eligible = [];
2071 for (var c = 0; c < this.width; c++)
2072 {
2073 if (this.isColumnLocked(c))
2074 { continue; }
2075 if (this.groundedCount(c) >= this.height)
2076 { continue; }
2077 eligible.push(c);
2078 }
2079 return eligible;
2080};
2081
2082/**
2083 * Choose a garbage column. If `preferred` is still open, it wins;
2084 * otherwise a random eligible column (t1126). Returns null if none.
2085 */
2086GameCore.prototype.pickGarbageColumn = function (preferred)
2087{
2088 var eligible = this.eligibleGarbageColumns();
2089 if (!eligible.length)
2090 { return null; }
2091 if (preferred != null && isFinite(preferred))
2092 {
2093 var want = preferred | 0;
2094 for (var i = 0; i < eligible.length; i++)
2095 {
2096 if (eligible[i] === want)
2097 { return want; }
2098 }
2099 }
2100 return eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
2101};
2102
2103GameCore.prototype.ingestGarbage = function (col)
2104{
2105 if (this.state !== 'playing')
2106 { return null; }
2107 var chosen = this.pickGarbageColumn(col);
2108 if (chosen == null)
2109 { return null; }
2110 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
2111 block.vy = -this.planet.fallSpeed;
2112 block.flame = false;
2113 return block;
2114};
2115
2116GameCore.prototype.advanceSettle = function (dt)
2117{
2118 for (var i = 0; i < this.blocks.length; i++)
2119 {
2120 var block = this.blocks[i];
2121 if (block.state !== STATE_SETTLING)
2122 { continue; }
2123 var inLanded = block.clusterId != null
2124 && this.clusters[block.clusterId]
2125 && this.clusters[block.clusterId].phase === 'landed';
2126 if (block.color === COLOR_GRAY)
2127 {
2128 block.settleTime += dt;
2129 if (block.settleTime >= this.settleTime)
2130 {
2131 block.color = this.randomColor();
2132 block.settleTime = 0;
2133 block.flame = false;
2134 if (inLanded)
2135 {
2136 // Stay in the rigid group; releaseLandedCluster runs below.
2137 block.state = STATE_SETTLING;
2138 }
2139 else
2140 {
2141 this.leaveCluster(block);
2142 this.clearFlightState(block);
2143 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2144 }
2145 }
2146 }
2147 else if (!inLanded)
2148 {
2149 // Coloured settling that is not in a landed cluster (shouldn't
2150 // normally happen): just become still or fall, from rest.
2151 this.leaveCluster(block);
2152 this.clearFlightState(block);
2153 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2154 }
2155 }
2156
2157 var ids = Object.keys(this.clusters);
2158 for (var n = 0; n < ids.length; n++)
2159 {
2160 var cluster = this.clusters[ids[n]];
2161 if (!cluster || cluster.phase !== 'landed')
2162 { continue; }
2163 var members = this.clusterMembers(cluster.id);
2164 var greySettling = false;
2165 for (var i = 0; i < members.length; i++)
2166 {
2167 if (members[i].color === COLOR_GRAY && members[i].state === STATE_SETTLING)
2168 { greySettling = true; }
2169 }
2170 if (!greySettling)
2171 { this.releaseLandedCluster(cluster); }
2172 }
2173};
2174
2175GameCore.prototype.findMatchLines = function ()
2176{
2177 var candidates = [];
2178 for (var i = 0; i < this.blocks.length; i++)
2179 {
2180 var block = this.blocks[i];
2181 // Coloured cargo in a just-landed cluster (SETTLING) can match
2182 // with already-resting blocks immediately (t1110). Greys have no
2183 // colour and wait until they recolor; after release they are STILL.
2184 if ((block.state === STATE_STILL || block.state === STATE_SETTLING)
2185 && block.color >= 0)
2186 { candidates.push(block); }
2187 }
2188 return this.collectLines(candidates, true);
2189};
2190
2191GameCore.prototype.findFlyingMatchLines = function (clusterId)
2192{
2193 var candidates = [];
2194 for (var i = 0; i < this.blocks.length; i++)
2195 {
2196 var block = this.blocks[i];
2197 if (block.clusterId === clusterId && block.color >= 0
2198 && (block.state === STATE_FLYING))
2199 { candidates.push(block); }
2200 }
2201 return this.collectLines(candidates, false);
2202};
2203
2204GameCore.prototype.collectLines = function (candidates, snapInteger)
2205{
2206 var lines = [];
2207 if (!candidates.length)
2208 { return lines; }
2209
2210 var byRow = Object.create(null);
2211 for (var i = 0; i < candidates.length; i++)
2212 {
2213 var block = candidates[i];
2214 var row = Math.round(block.y);
2215 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
2216 { continue; }
2217 if (!byRow[row])
2218 { byRow[row] = []; }
2219 byRow[row].push(block);
2220 }
2221 var rows = Object.keys(byRow);
2222 for (var r = 0; r < rows.length; r++)
2223 {
2224 var list = byRow[rows[r]];
2225 list.sort(function (a, b) { return a.col - b.col; });
2226 this.pushRuns(lines, list, false, function (a, b)
2227 {
2228 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
2229 });
2230 }
2231
2232 var byCol = Object.create(null);
2233 for (var i = 0; i < candidates.length; i++)
2234 {
2235 var block = candidates[i];
2236 if (!byCol[block.col])
2237 { byCol[block.col] = []; }
2238 byCol[block.col].push(block);
2239 }
2240 var cols = Object.keys(byCol);
2241 for (var c = 0; c < cols.length; c++)
2242 {
2243 var list = byCol[cols[c]];
2244 list.sort(function (a, b) { return a.y - b.y; });
2245 this.pushRuns(lines, list, true, function (a, b)
2246 {
2247 return a.color === b.color && a.color >= 0
2248 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
2249 });
2250 }
2251 return lines;
2252};
2253
2254GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
2255{
2256 var start = 0;
2257 for (var i = 1; i <= list.length; i++)
2258 {
2259 var same = i < list.length && adjacent(list[i - 1], list[i]);
2260 if (!same)
2261 {
2262 var length = i - start;
2263 if (length >= 3)
2264 {
2265 lines.push({
2266 blocks: list.slice(start, i),
2267 length: length,
2268 vertical: vertical
2269 });
2270 }
2271 start = i;
2272 }
2273 }
2274};
2275
2276GameCore.prototype.resolveMatches = function ()
2277{
2278 if (this.state !== 'playing' || this.drag)
2279 { return []; }
2280 var lines = this.findMatchLines();
2281 if (!lines.length)
2282 {
2283 this.finishLandingChains([]);
2284 return [];
2285 }
2286
2287 var uf = new UnionFind();
2288 var blockById = Object.create(null);
2289 for (var i = 0; i < lines.length; i++)
2290 {
2291 var line = lines[i];
2292 for (var j = 0; j < line.blocks.length; j++)
2293 {
2294 uf.add(line.blocks[j].id);
2295 blockById[line.blocks[j].id] = line.blocks[j];
2296 if (j > 0)
2297 { uf.union(line.blocks[0].id, line.blocks[j].id); }
2298 }
2299 }
2300 var matched = [];
2301 var seen = Object.create(null);
2302 for (var id in blockById)
2303 {
2304 if (!seen[id])
2305 {
2306 seen[id] = true;
2307 matched.push(blockById[id]);
2308 }
2309 }
2310 for (var i = 0; i < matched.length; i++)
2311 {
2312 for (var j = i + 1; j < matched.length; j++)
2313 {
2314 if (matched[i].col === matched[j].col)
2315 { uf.union(matched[i].id, matched[j].id); }
2316 }
2317 }
2318
2319 var groups = Object.create(null);
2320 for (var i = 0; i < matched.length; i++)
2321 {
2322 var root = uf.find(matched[i].id);
2323 if (!groups[root])
2324 { groups[root] = []; }
2325 groups[root].push(matched[i]);
2326 }
2327
2328 var launched = [];
2329 for (var root in groups)
2330 {
2331 var group = groups[root];
2332 var height = 0;
2333 for (var i = 0; i < lines.length; i++)
2334 {
2335 var line = lines[i];
2336 var overlaps = false;
2337 for (var j = 0; j < line.blocks.length; j++)
2338 {
2339 for (var k = 0; k < group.length; k++)
2340 {
2341 if (line.blocks[j].id === group[k].id)
2342 { overlaps = true; }
2343 }
2344 }
2345 if (overlaps)
2346 {
2347 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
2348 if (h > height)
2349 { height = h; }
2350 }
2351 }
2352 var chain = this.landingChainFor(group);
2353 var bonusMul = 1 + LANDING_CHAIN_BONUS * chain;
2354 height *= bonusMul;
2355 this.launchCluster(group, height, { landingChain: chain });
2356 launched.push({
2357 blocks: group,
2358 jumpHeight: height,
2359 landingChain: chain,
2360 chainBonus: bonusMul
2361 });
2362 }
2363 this.finishLandingChains(launched);
2364 this.updateChainIndicator(launched);
2365 return launched;
2366};
2367
2368/**
2369 * Gray the matched blocks, take everything sitting on top of them in
2370 * those columns, link them, and launch with jump height `height`.
2371 */
2372GameCore.prototype.launchCluster = function (matchedBlocks, height, opts)
2373{
2374 opts = opts || {};
2375 var lowestInCol = Object.create(null);
2376 var matchedIds = Object.create(null);
2377 for (var i = 0; i < matchedBlocks.length; i++)
2378 {
2379 var block = matchedBlocks[i];
2380 matchedIds[block.id] = true;
2381 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
2382 { lowestInCol[block.col] = block.y; }
2383 }
2384
2385 var clusterId = this.nextClusterId++;
2386 var cluster = {
2387 id: clusterId,
2388 jumpHeight: height,
2389 vy: PlanetMod.launchVelocity(this.planet, height),
2390 decel: PlanetMod.launchDeceleration(this.planet, height),
2391 phase: 'up',
2392 landingChain: opts.landingChain || 0,
2393 landedPending: false
2394 };
2395 this.clusters[clusterId] = cluster;
2396
2397 var riders = [];
2398 var cols = Object.keys(lowestInCol);
2399 for (var c = 0; c < cols.length; c++)
2400 {
2401 var col = +cols[c];
2402 var lowest = lowestInCol[col];
2403 var list = this.blocksInColumn(col);
2404 for (var i = 0; i < list.length; i++)
2405 {
2406 var block = list[i];
2407 if (!this.isGrounded(block) && block.state !== STATE_STILL)
2408 {
2409 if (block.state !== STATE_SETTLING)
2410 { continue; }
2411 }
2412 if (block.y + ALIGN_EPS >= lowest)
2413 { riders.push(block); }
2414 }
2415 }
2416
2417 for (var i = 0; i < riders.length; i++)
2418 {
2419 var block = riders[i];
2420 var isMatch = !!matchedIds[block.id];
2421 if (isMatch || block.color === COLOR_GRAY)
2422 {
2423 block.color = COLOR_GRAY;
2424 block.flame = true;
2425 }
2426 else
2427 { block.flame = false; }
2428 block.state = STATE_FLYING;
2429 block.clusterId = clusterId;
2430 block.vy = cluster.vy;
2431 block.settleTime = 0;
2432 }
2433 this.prepareClusterBody(cluster);
2434 return cluster;
2435};
2436
2437GameCore.prototype.checkLocks = function ()
2438{
2439 for (var col = 0; col < this.width; col++)
2440 {
2441 if (this.isColumnLocked(col))
2442 { continue; }
2443 if (this.groundedCount(col) < this.height)
2444 { continue; }
2445 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
2446 var filled = true;
2447 for (var row = 0; row < this.height; row++)
2448 {
2449 var block = this.blockAt(col, row);
2450 if (!block || !this.isGrounded(block))
2451 {
2452 filled = false;
2453 break;
2454 }
2455 }
2456 if (!filled)
2457 { continue; }
2458 var list = this.blocksInColumn(col);
2459 for (var i = 0; i < list.length; i++)
2460 {
2461 var block = list[i];
2462 if (!this.isGrounded(block))
2463 { continue; }
2464 block.state = STATE_LOCKED;
2465 block.color = COLOR_GRAY;
2466 block.flame = false;
2467 block.vy = 0;
2468 block.settleTime = 0;
2469 if (block.clusterId != null)
2470 { this.leaveCluster(block); }
2471 }
2472 }
2473};
2474
2475GameCore.prototype.checkGameOver = function ()
2476{
2477 if (this.state !== 'playing')
2478 { return; }
2479 for (var col = 0; col < this.width; col++)
2480 {
2481 if (!this.isColumnLocked(col))
2482 { return; }
2483 }
2484 this.state = 'gameover';
2485 this.gameOverTime = 0;
2486 this.drag = null;
2487};
2488
2489/* ---------- dragging -------------------------------------------------- */
2490
2491GameCore.prototype.beginDrag = function (col, y)
2492{
2493 if (this.state !== 'playing')
2494 { return false; }
2495 var block = this.snapDragBlock(col, y);
2496 if (!block)
2497 { return false; }
2498 var top = this.columnStackTopRow(block.col);
2499 var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
2500 this.drag = {
2501 blockId: block.id,
2502 pointerY: y,
2503 startY: y,
2504 accum: 0,
2505 launchIntent: false,
2506 startedAsTop: startedAsTop
2507 };
2508 return true;
2509};
2510
2511/**
2512 * Instant grab, cell-based (t1109). The press is mapped to the grid cell
2513 * floor(col), floor(y); any press inside that cell — corners, padding,
2514 * gaps between sprites, a visually tweened or bouncing sprite — grabs
2515 * the block that occupies it. This uses simulation cells, not the drawn
2516 * sprite bounds. If no block sits in that cell (mid-animation, a block
2517 * whose y is off the integer), fall back to the nearest grabbable block
2518 * in the same column within SNAP_Y (about half a tile). A small
2519 * horizontal slop still consults a neighbouring column when the press
2520 * is near the edge and the primary cell is empty.
2521 */
2522GameCore.prototype.snapDragBlock = function (col, y)
2523{
2524 var raw = col;
2525 var c0 = Math.floor(raw + 1e-9);
2526 var row = Math.floor(y + 1e-9);
2527 var frac = raw - c0;
2528
2529 if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0))
2530 {
2531 var exact = this.draggableInCell(c0, row);
2532 if (exact)
2533 { return exact; }
2534 var near = this.nearestDraggableInColumn(c0, y, SNAP_Y);
2535 if (near)
2536 { return near; }
2537 }
2538
2539 // Primary cell empty: allow a small horizontal slop into a neighbour.
2540 var neighbours = [];
2541 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
2542 { neighbours.push(c0 - 1); }
2543 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
2544 { neighbours.push(c0 + 1); }
2545 var best = null;
2546 var bestDist = Infinity;
2547 for (var n = 0; n < neighbours.length; n++)
2548 {
2549 var cc = neighbours[n];
2550 if (!this.columnAllowsDrag(cc))
2551 { continue; }
2552 var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y);
2553 if (!hit)
2554 { continue; }
2555 var dist = this.pointerDistToBlock(hit, raw, y);
2556 if (dist < bestDist)
2557 {
2558 bestDist = dist;
2559 best = hit;
2560 }
2561 }
2562 return best;
2563};
2564
2565/** The draggable block that occupies grid cell (col, row), if any. */
2566GameCore.prototype.draggableInCell = function (col, row)
2567{
2568 var best = null;
2569 var bestOverlap = 0;
2570 var list = this.blocksInColumn(col);
2571 for (var i = 0; i < list.length; i++)
2572 {
2573 var block = list[i];
2574 if (!this.isDraggableBlock(block))
2575 { continue; }
2576 var lo = Math.max(block.y, row);
2577 var hi = Math.min(block.y + 1, row + 1);
2578 var overlap = hi - lo;
2579 if (overlap > bestOverlap + 1e-12)
2580 {
2581 bestOverlap = overlap;
2582 best = block;
2583 }
2584 }
2585 if (best && bestOverlap > 1e-9)
2586 { return best; }
2587 return null;
2588};
2589
2590/** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */
2591GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist)
2592{
2593 var best = null;
2594 var bestDist = Infinity;
2595 var list = this.blocksInColumn(col);
2596 for (var i = 0; i < list.length; i++)
2597 {
2598 var block = list[i];
2599 if (!this.isDraggableBlock(block))
2600 { continue; }
2601 var dist = this.pointerDistToBlock(block, col + 0.5, y);
2602 if (dist < bestDist)
2603 {
2604 bestDist = dist;
2605 best = block;
2606 }
2607 }
2608 if (!best || bestDist > maxDist)
2609 { return null; }
2610 return best;
2611};
2612
2613GameCore.prototype.pointerDistToBlock = function (block, col, y)
2614{
2615 var dx;
2616 if (col >= block.col && col < block.col + 1)
2617 { dx = 0; }
2618 else if (col < block.col)
2619 { dx = block.col - col; }
2620 else
2621 { dx = col - (block.col + 1); }
2622 var dy;
2623 if (y >= block.y && y < block.y + 1)
2624 { dy = 0; }
2625 else if (y < block.y)
2626 { dy = block.y - y; }
2627 else
2628 { dy = y - (block.y + 1); }
2629 return Math.sqrt(dx * dx + dy * dy);
2630};
2631
2632GameCore.prototype.moveDrag = function (y)
2633{
2634 if (!this.drag)
2635 { return; }
2636 var block = this.blockById(this.drag.blockId);
2637 if (!block || !this.isDraggableBlock(block))
2638 {
2639 this.drag = null;
2640 return;
2641 }
2642 if (!this.columnAllowsDrag(block.col))
2643 {
2644 this.drag = null;
2645 return;
2646 }
2647 this.drag.pointerY = y;
2648 // 1:1 tracking: the target row is the one under the pointer, clamped
2649 // to the still stack. Swap step by step with each neighbour, and stop
2650 // exactly there. When the pointer stops, nothing else moves.
2651 // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
2652 // used to jump a full cell on a short pull, and one large event
2653 // could walk the entire column (the "jumps all the way" bug).
2654 var top = this.columnStackTopRow(block.col);
2655 var bottom = this.columnStackBottomRow(block.col);
2656 var target = Math.floor(y + 1e-12);
2657 if (bottom < 0)
2658 { bottom = 0; }
2659 if (target < bottom)
2660 { target = bottom; }
2661 if (target > top)
2662 { target = top; }
2663 this.swapToward(block, target);
2664
2665 top = this.columnStackTopRow(block.col);
2666 var isTop = Math.abs(block.y - top) < ALIGN_EPS;
2667 if (this.drag.startedAsTop)
2668 {
2669 // Already the topmost block: pulling upward past its own position
2670 // (LAUNCH_PULL tiles above the press point) starts a manual jump.
2671 this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL);
2672 }
2673 else
2674 {
2675 // Started mid-stack: swap first, and only launch once the pointer
2676 // is pulled into the empty space above the (new) top.
2677 this.drag.launchIntent = isTop && (y > top + 1 + 0.25);
2678 }
2679};
2680
2681/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
2682GameCore.prototype.swapOne = function (block, dir)
2683{
2684 var neighbor = this.blockAt(block.col, block.y + dir);
2685 if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
2686 {
2687 this.swapBlocks(block, neighbor);
2688 return true;
2689 }
2690 return false;
2691};
2692
2693GameCore.prototype.endDrag = function ()
2694{
2695 if (!this.drag)
2696 { return; }
2697 var block = this.blockById(this.drag.blockId);
2698 var launch = this.drag.launchIntent;
2699 this.drag = null;
2700 if (launch && block && block.state === STATE_STILL)
2701 { this.startManualLaunch(block); }
2702 else
2703 { this.resolveMatches(); }
2704};
2705
2706GameCore.prototype.blockById = function (id)
2707{
2708 for (var i = 0; i < this.blocks.length; i++)
2709 {
2710 if (this.blocks[i].id === id)
2711 { return this.blocks[i]; }
2712 }
2713 return null;
2714};
2715
2716GameCore.prototype.columnStackTopRow = function (col)
2717{
2718 var top = -1;
2719 var list = this.blocksInColumn(col);
2720 for (var i = 0; i < list.length; i++)
2721 {
2722 if (this.isGrounded(list[i]) && list[i].y > top)
2723 { top = list[i].y; }
2724 }
2725 return top;
2726};
2727
2728GameCore.prototype.columnStackBottomRow = function (col)
2729{
2730 var bottom = Infinity;
2731 var list = this.blocksInColumn(col);
2732 for (var i = 0; i < list.length; i++)
2733 {
2734 if (this.isGrounded(list[i]) && list[i].y < bottom)
2735 { bottom = list[i].y; }
2736 }
2737 return bottom === Infinity ? 0 : bottom;
2738};
2739
2740GameCore.prototype.swapToward = function (block, targetY)
2741{
2742 var guard = 0;
2743 while (guard++ < this.height + 2)
2744 {
2745 var current = block.y;
2746 if (targetY > current + 0.5)
2747 {
2748 var above = this.blockAt(block.col, current + 1);
2749 if (above && this.isGrounded(above) && above !== block)
2750 { this.swapBlocks(block, above); }
2751 else
2752 { break; }
2753 }
2754 else if (targetY < current - 0.5)
2755 {
2756 var below = this.blockAt(block.col, current - 1);
2757 if (below && this.isGrounded(below) && below !== block)
2758 { this.swapBlocks(block, below); }
2759 else
2760 { break; }
2761 }
2762 else
2763 { break; }
2764 }
2765};
2766
2767GameCore.prototype.swapBlocks = function (a, b)
2768{
2769 var ay = a.y;
2770 var by = b.y;
2771 a.y = by;
2772 b.y = ay;
2773 this.transferLandedMembership(a, b);
2774 if (!this.swapEvents)
2775 { this.swapEvents = []; }
2776 this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col });
2777 this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col });
2778};
2779
2780GameCore.prototype.consumeSwapEvents = function ()
2781{
2782 var ev = this.swapEvents || [];
2783 this.swapEvents = [];
2784 return ev;
2785};
2786
2787/**
2788 * Highest landing-chain counter among just-landed members of this
2789 * match group, plus one. Returns 0 when the match did not come from
2790 * a cluster landing (player/bot swap, mid-air, etc.).
2791 */
2792GameCore.prototype.landingChainFor = function (group)
2793{
2794 var maxChain = 0;
2795 var fromLanding = false;
2796 for (var i = 0; i < group.length; i++)
2797 {
2798 var block = group[i];
2799 if (block.justLanded)
2800 {
2801 fromLanding = true;
2802 if ((block.landingChain || 0) > maxChain)
2803 { maxChain = block.landingChain || 0; }
2804 }
2805 if (block.clusterId != null)
2806 {
2807 var cluster = this.clusters[block.clusterId];
2808 if (cluster && cluster.landedPending)
2809 {
2810 fromLanding = true;
2811 if ((cluster.landingChain || 0) > maxChain)
2812 { maxChain = cluster.landingChain || 0; }
2813 }
2814 }
2815 }
2816 if (!fromLanding)
2817 { return 0; }
2818 return maxChain + 1;
2819};
2820
2821/**
2822 * After resolveMatches: clear the landing-pending flag and reset the
2823 * chain on landings that did not make a match. A cluster that is still
2824 * settling (greys not yet recolored) keeps landedPending so a later
2825 * post-recolor match in this same landing still gets the bonus.
2826 */
2827GameCore.prototype.finishLandingChains = function (launched)
2828{
2829 var launchedIds = Object.create(null);
2830 launched = launched || [];
2831 for (var i = 0; i < launched.length; i++)
2832 {
2833 var blocks = launched[i].blocks || [];
2834 for (var j = 0; j < blocks.length; j++)
2835 { launchedIds[blocks[j].id] = true; }
2836 }
2837
2838 for (var i = 0; i < this.blocks.length; i++)
2839 {
2840 var block = this.blocks[i];
2841 if (!block.justLanded)
2842 { continue; }
2843 if (!launchedIds[block.id])
2844 { block.landingChain = 0; }
2845 block.justLanded = false;
2846 }
2847
2848 var ids = Object.keys(this.clusters);
2849 for (var c = 0; c < ids.length; c++)
2850 {
2851 var cluster = this.clusters[ids[c]];
2852 if (!cluster || !cluster.landedPending)
2853 { continue; }
2854 var members = this.clusterMembers(cluster.id);
2855 var anyLaunched = false;
2856 var stillSettling = false;
2857 for (var i = 0; i < members.length; i++)
2858 {
2859 if (launchedIds[members[i].id])
2860 { anyLaunched = true; }
2861 if (members[i].state === STATE_SETTLING)
2862 { stillSettling = true; }
2863 }
2864 if (anyLaunched)
2865 {
2866 cluster.landingChain = 0;
2867 cluster.landedPending = false;
2868 }
2869 else if (!stillSettling)
2870 {
2871 // Released leftovers or a fully-still landed group that
2872 // already had its match opportunity and missed it.
2873 cluster.landingChain = 0;
2874 cluster.landedPending = false;
2875 }
2876 // else: still settling, no match yet — keep landedPending.
2877 }
2878};
2879
2880GameCore.prototype.updateChainIndicator = function (launched)
2881{
2882 var maxChain = 0;
2883 for (var i = 0; i < launched.length; i++)
2884 {
2885 var ch = launched[i].landingChain || 0;
2886 if (ch > maxChain)
2887 { maxChain = ch; }
2888 }
2889 if (maxChain >= 1)
2890 {
2891 this.lastChainIndicator = {
2892 chain: maxChain,
2893 bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100)
2894 };
2895 return;
2896 }
2897 if (!this.hasActiveLandingChain())
2898 { this.lastChainIndicator = null; }
2899};
2900
2901GameCore.prototype.hasActiveLandingChain = function ()
2902{
2903 var ids = Object.keys(this.clusters);
2904 for (var i = 0; i < ids.length; i++)
2905 {
2906 var cluster = this.clusters[ids[i]];
2907 if (cluster && (cluster.landingChain || 0) >= 1
2908 && cluster.phase !== 'landed')
2909 { return true; }
2910 }
2911 return false;
2912};
2913
2914/**
2915 * A landed cluster (grey rockets or linked cargo resting on the ground)
2916 * is a swappable part of the contiguous grounded stack. Flying, falling
2917 * and manual blocks are not. A locked column is not.
2918 */
2919GameCore.prototype.isDraggableBlock = function (block)
2920{
2921 if (!block)
2922 { return false; }
2923 if (block.state === STATE_LOCKED || block.state === STATE_FLYING
2924 || block.state === STATE_FALLING || block.state === STATE_MANUAL)
2925 { return false; }
2926 if (block.clusterId != null)
2927 {
2928 var cluster = this.clusters[block.clusterId];
2929 // Flying (rising / descending) clusters stay non-draggable.
2930 if (cluster && cluster.phase !== 'landed')
2931 { return false; }
2932 }
2933 return block.state === STATE_STILL || block.state === STATE_SETTLING;
2934};
2935
2936/**
2937 * The grounded contiguous stack in this column can be dragged, even if a
2938 * flying cluster or a falling spawn occupies the air above it. Only a
2939 * locked column is blocked as a whole.
2940 */
2941GameCore.prototype.columnAllowsDrag = function (col)
2942{
2943 return !this.isColumnLocked(col);
2944};
2945
2946GameCore.prototype.landedClusterId = function (block)
2947{
2948 if (!block || block.clusterId == null)
2949 { return null; }
2950 var cluster = this.clusters[block.clusterId];
2951 if (!cluster || cluster.phase !== 'landed')
2952 { return null; }
2953 return block.clusterId;
2954};
2955
2956/**
2957 * After a swap: leaving a landed cluster clears membership; joining one
2958 * makes the block part of that rigid group. Same-cluster swaps only
2959 * exchange positions. See docs/ASSUMPTIONS.md (t1107).
2960 */
2961GameCore.prototype.transferLandedMembership = function (a, b)
2962{
2963 var ca = this.landedClusterId(a);
2964 var cb = this.landedClusterId(b);
2965 if (ca === cb)
2966 { return; }
2967 // Join first so leaveCluster does not delete a cluster that still
2968 // has the incoming member.
2969 this.applyLandedMembership(b, ca);
2970 this.applyLandedMembership(a, cb);
2971};
2972
2973GameCore.prototype.applyLandedMembership = function (block, clusterId)
2974{
2975 if (clusterId == null)
2976 {
2977 var wasGrey = block.color === COLOR_GRAY;
2978 var wasSettling = block.state === STATE_SETTLING;
2979 this.leaveCluster(block);
2980 if (wasGrey && wasSettling)
2981 {
2982 // Keep settling and recolor on its own, same remaining timer.
2983 block.state = STATE_SETTLING;
2984 }
2985 else if (wasSettling)
2986 {
2987 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
2988 }
2989 return;
2990 }
2991 if (!this.clusters[clusterId])
2992 { return; }
2993 block.clusterId = clusterId;
2994 block.flame = false;
2995 if (block.state === STATE_STILL || block.state === STATE_SETTLING)
2996 { block.state = STATE_SETTLING; }
2997};
2998
2999/**
3000 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
3001 * Returns the moved block, or null if the column does not allow a drag.
3002 */
3003GameCore.prototype.swapTo = function (col, fromRow, toRow)
3004{
3005 if (!this.columnAllowsDrag(col))
3006 { return null; }
3007 var block = this.blockAt(col, fromRow);
3008 if (!block)
3009 { return null; }
3010 this.swapToward(block, toRow);
3011 return block;
3012};
3013
3014/**
3015 * Test helper: a compact picture of grounded/falling/flying blocks.
3016 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
3017 * L locked, f falling, m manual, . empty. Flying colored blocks use
3018 * their color with a marker in `flying`.
3019 */
3020GameCore.prototype.snapshot = function ()
3021{
3022 var grid = [];
3023 for (var r = 0; r < this.height; r++)
3024 {
3025 var row = [];
3026 for (var c = 0; c < this.width; c++)
3027 { row.push('.'); }
3028 grid.push(row);
3029 }
3030 var airborne = [];
3031 for (var i = 0; i < this.blocks.length; i++)
3032 {
3033 var block = this.blocks[i];
3034 var ch;
3035 if (block.state === STATE_LOCKED)
3036 { ch = 'L'; }
3037 else if (block.color === COLOR_GRAY)
3038 { ch = 'g'; }
3039 else
3040 { ch = String(block.color); }
3041 if (this.isGrounded(block) || block.state === STATE_FALLING)
3042 {
3043 var row = Math.round(block.y);
3044 if (row >= 0 && row < this.height)
3045 { grid[row][block.col] = ch; }
3046 }
3047 else
3048 {
3049 airborne.push({
3050 id: block.id,
3051 col: block.col,
3052 y: block.y,
3053 color: block.color,
3054 state: block.state,
3055 clusterId: block.clusterId,
3056 flame: block.flame,
3057 vy: block.vy
3058 });
3059 }
3060 }
3061 var lines = [];
3062 for (var r = this.height - 1; r >= 0; r--)
3063 { lines.push(grid[r].join('')); }
3064 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
3065};
3066
3067var GameCoreAPI = {
3068 GameCore: GameCore,
3069 COLOR_GRAY: COLOR_GRAY,
3070 STATE_STILL: STATE_STILL,
3071 STATE_FALLING: STATE_FALLING,
3072 STATE_FLYING: STATE_FLYING,
3073 STATE_SETTLING: STATE_SETTLING,
3074 STATE_LOCKED: STATE_LOCKED,
3075 STATE_MANUAL: STATE_MANUAL
3076};
3077
3078if (typeof module !== 'undefined' && module.exports)
3079{ module.exports = GameCoreAPI; }
3080else if (typeof globalThis !== 'undefined')
3081{
3082 globalThis.GameCore = GameCore;
3083 globalThis.GameCoreAPI = GameCoreAPI;
3084}