BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

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