BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

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