BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

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