BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

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