BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

gameCore.js 46.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// Grab a still block if the pointer is at most this far (tiles) from it.
31var SNAP_Y = 0.65;
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}
84
85function optsMissChance (args)
86{
87 // GameCore(planet, rng, missChance) — third arg is optional.
88 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
89 { return Math.max(0, Math.min(1, args[2])); }
90 var planet = args[0];
91 if (planet && typeof PlanetMod.missChance === 'function')
92 { return PlanetMod.missChance(planet); }
93 return GameCore.DEFAULT_MISS_CHANCE;
94}
95
96GameCore.COLOR_GRAY = COLOR_GRAY;
97GameCore.LAUNCH_PULL = LAUNCH_PULL;
98GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
99GameCore.SNAP_Y = SNAP_Y;
100GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
101GameCore.DEFAULT_MISS_CHANCE = 0.30;
102GameCore.STATE_STILL = STATE_STILL;
103GameCore.STATE_FALLING = STATE_FALLING;
104GameCore.STATE_FLYING = STATE_FLYING;
105GameCore.STATE_SETTLING = STATE_SETTLING;
106GameCore.STATE_LOCKED = STATE_LOCKED;
107GameCore.STATE_MANUAL = STATE_MANUAL;
108
109GameCore.prototype.randomColor = function ()
110{
111 return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length;
112};
113
114GameCore.prototype.createBlock = function (col, y, color, state)
115{
116 var block = {
117 id: this.nextBlockId++,
118 col: col,
119 y: y,
120 color: color,
121 state: state || STATE_STILL,
122 vy: 0,
123 clusterId: null,
124 settleTime: 0,
125 flame: false,
126 pushedClusters: null,
127 manualTarget: 0,
128 manualDecel: 0,
129 manualPhase: null,
130 bouncing: false,
131 bounceAge: 0
132 };
133 this.blocks.push(block);
134 return block;
135};
136
137GameCore.prototype.removeBlock = function (block)
138{
139 if (block.clusterId != null)
140 { this.leaveCluster(block); }
141 var index = this.blocks.indexOf(block);
142 if (index >= 0)
143 { this.blocks.splice(index, 1); }
144};
145
146GameCore.prototype.leaveCluster = function (block)
147{
148 var id = block.clusterId;
149 block.clusterId = null;
150 block.flame = false;
151 if (id == null || !this.clusters[id])
152 { return; }
153 var still = 0;
154 for (var i = 0; i < this.blocks.length; i++)
155 {
156 if (this.blocks[i].clusterId === id)
157 { still++; }
158 }
159 if (still === 0)
160 { delete this.clusters[id]; }
161};
162
163GameCore.prototype.blocksInColumn = function (col)
164{
165 var out = [];
166 for (var i = 0; i < this.blocks.length; i++)
167 {
168 if (this.blocks[i].col === col)
169 { out.push(this.blocks[i]); }
170 }
171 out.sort(function (a, b) { return a.y - b.y; });
172 return out;
173};
174
175GameCore.prototype.isGrounded = function (block)
176{
177 return block.state === STATE_STILL
178 || block.state === STATE_SETTLING
179 || block.state === STATE_LOCKED;
180};
181
182GameCore.prototype.stackTop = function (col, ignore)
183{
184 var top = 0;
185 for (var i = 0; i < this.blocks.length; i++)
186 {
187 var block = this.blocks[i];
188 if (block.col !== col)
189 { continue; }
190 if (ignore && ignore(block))
191 { continue; }
192 if (this.isGrounded(block))
193 {
194 var surface = block.y + 1;
195 if (surface > top)
196 { top = surface; }
197 }
198 }
199 return top;
200};
201
202GameCore.prototype.isColumnLocked = function (col)
203{
204 for (var i = 0; i < this.blocks.length; i++)
205 {
206 var block = this.blocks[i];
207 if (block.col === col && block.state === STATE_LOCKED)
208 { return true; }
209 }
210 return false;
211};
212
213GameCore.prototype.isColumnStill = function (col)
214{
215 if (this.isColumnLocked(col))
216 { return false; }
217 for (var i = 0; i < this.blocks.length; i++)
218 {
219 var block = this.blocks[i];
220 if (block.col !== col)
221 { continue; }
222 if (block.state === STATE_FLYING
223 || block.state === STATE_FALLING
224 || block.state === STATE_MANUAL
225 || block.state === STATE_SETTLING)
226 { return false; }
227 }
228 return true;
229};
230
231GameCore.prototype.groundedCount = function (col)
232{
233 var n = 0;
234 for (var i = 0; i < this.blocks.length; i++)
235 {
236 if (this.blocks[i].col === col && this.isGrounded(this.blocks[i]))
237 { n++; }
238 }
239 return n;
240};
241
242GameCore.prototype.blockAt = function (col, row)
243{
244 for (var i = 0; i < this.blocks.length; i++)
245 {
246 var block = this.blocks[i];
247 if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS)
248 { return block; }
249 }
250 return null;
251};
252
253GameCore.prototype.place = function (col, row, color, state)
254{
255 return this.createBlock(col, row, color, state || STATE_STILL);
256};
257
258GameCore.prototype.lockedColumnCount = function ()
259{
260 var n = 0;
261 for (var c = 0; c < this.width; c++)
262 {
263 if (this.isColumnLocked(c))
264 { n++; }
265 }
266 return n;
267};
268
269GameCore.prototype.startBounce = function (block)
270{
271 if (!block)
272 { return; }
273 block.bouncing = true;
274 block.bounceAge = 0;
275};
276
277GameCore.prototype.advanceBounces = function (dt)
278{
279 var duration = this.planet.bounceDuration;
280 for (var i = 0; i < this.blocks.length; i++)
281 {
282 var block = this.blocks[i];
283 if (!block.bouncing)
284 { continue; }
285 block.bounceAge += dt;
286 if (duration <= 0 || block.bounceAge >= duration)
287 {
288 block.bouncing = false;
289 block.bounceAge = duration;
290 }
291 }
292};
293
294/**
295 * True if `block` rests on the floor or on a solid (still / settling /
296 * locked) block immediately below it in the same column.
297 */
298GameCore.prototype.hasSupport = function (block)
299{
300 if (block.y <= 1e-9)
301 { return true; }
302 for (var i = 0; i < this.blocks.length; i++)
303 {
304 var other = this.blocks[i];
305 if (other === block || other.col !== block.col)
306 { continue; }
307 if (!this.isGrounded(other))
308 { continue; }
309 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
310 { return true; }
311 }
312 return false;
313};
314
315/** Highest flying block in this column whose top is at or below `block.y + 1`. */
316GameCore.prototype.highestFlyingBelow = function (block)
317{
318 var best = null;
319 for (var i = 0; i < this.blocks.length; i++)
320 {
321 var other = this.blocks[i];
322 if (other === block || other.col !== block.col)
323 { continue; }
324 if (other.state !== STATE_FLYING || other.clusterId == null)
325 { continue; }
326 var cluster = this.clusters[other.clusterId];
327 if (!cluster || cluster.phase === 'landed')
328 { continue; }
329 // The falling block is at or above this flyer (or already overlapping).
330 if (block.y + 1e-9 < other.y)
331 { continue; }
332 if (!best || other.y > best.y)
333 { best = other; }
334 }
335 return best;
336};
337
338GameCore.prototype.highestFallingBelow = function (block)
339{
340 var best = null;
341 for (var i = 0; i < this.blocks.length; i++)
342 {
343 var other = this.blocks[i];
344 if (other === block || other.col !== block.col)
345 { continue; }
346 if (other.state !== STATE_FALLING)
347 { continue; }
348 if (other.y > block.y - 1e-9)
349 { continue; }
350 if (!best || other.y > best.y)
351 { best = other; }
352 }
353 return best;
354};
355
356/**
357 * Make an unsupported still block start falling from rest, so it eases
358 * into fallSpeed under normal gravity. Skips the block being dragged.
359 */
360/**
361 * Strip leftover launch / manual kinematics so a block that has just
362 * become still or falling starts from rest. Used after a landed grey
363 * cluster recolors, and whenever an unsupported still block drops.
364 */
365GameCore.prototype.clearFlightState = function (block)
366{
367 block.vy = 0;
368 block.flame = false;
369 block.manualPhase = null;
370 block.manualTarget = null;
371 block.manualDecel = 0;
372 block.pushedClusters = null;
373};
374
375GameCore.prototype.releaseUnsupported = function ()
376{
377 for (var i = 0; i < this.blocks.length; i++)
378 {
379 var block = this.blocks[i];
380 if (block.state !== STATE_STILL)
381 { continue; }
382 if (this.drag && this.drag.blockId === block.id)
383 { continue; }
384 if (this.hasSupport(block))
385 { continue; }
386 this.leaveCluster(block);
387 this.clearFlightState(block);
388 block.state = STATE_FALLING;
389 }
390};
391
392GameCore.prototype.accelerateFall = function (block, dt)
393{
394 var target = -this.planet.fallSpeed;
395 if (block.vy > target)
396 { block.vy = Math.max(target, block.vy - this.planet.fallAccel * dt); }
397 else
398 { block.vy = target; }
399};
400
401GameCore.prototype.landFallingBlock = function (block)
402{
403 block.vy = 0;
404 block.flame = false;
405 this.startBounce(block);
406 if (block.color === COLOR_GRAY)
407 {
408 block.state = STATE_SETTLING;
409 block.settleTime = 0;
410 }
411 else
412 { block.state = STATE_STILL; }
413};
414
415/**
416 * Sit `block` on top of the flying cluster that `flyer` belongs to, and
417 * carry it along as cargo (no flame). Returns true if attached.
418 */
419GameCore.prototype.attachToFlyingCluster = function (block, flyer)
420{
421 var cluster = this.clusters[flyer.clusterId];
422 if (!cluster || cluster.phase === 'landed')
423 { return false; }
424 var roof = flyer.y + 1;
425 for (var i = 0; i < this.blocks.length; i++)
426 {
427 var other = this.blocks[i];
428 if (other === block || other.col !== block.col)
429 { continue; }
430 if (other.clusterId !== cluster.id)
431 { continue; }
432 if (other.y + 1 > roof)
433 { roof = other.y + 1; }
434 }
435 block.y = roof;
436 block.state = STATE_FLYING;
437 block.clusterId = cluster.id;
438 block.vy = cluster.vy;
439 block.flame = false;
440 block.settleTime = 0;
441 return true;
442};
443
444GameCore.prototype.catchFallingOntoCluster = function (cluster, members)
445{
446 if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold')
447 { return; }
448 // Snapshot falling blocks; attaching mutates state.
449 var falling = [];
450 for (var i = 0; i < this.blocks.length; i++)
451 {
452 if (this.blocks[i].state === STATE_FALLING)
453 { falling.push(this.blocks[i]); }
454 }
455 for (var i = 0; i < falling.length; i++)
456 {
457 var block = falling[i];
458 var flyer = null;
459 for (var m = 0; m < members.length; m++)
460 {
461 var other = members[m];
462 if (other.col !== block.col)
463 { continue; }
464 // Overlap or rest on this member's top.
465 if (block.y < other.y + 1 + 1e-9 && block.y + 1 > other.y - 1e-9)
466 {
467 if (!flyer || other.y > flyer.y)
468 { flyer = other; }
469 }
470 }
471 if (flyer)
472 { this.attachToFlyingCluster(block, flyer); }
473 }
474};
475
476GameCore.prototype.tick = function (dt)
477{
478 if (this.state === 'gameover')
479 {
480 this.gameOverTime += Math.max(0, dt);
481 return;
482 }
483 if (dt <= 0)
484 { return; }
485 dt = Math.min(dt, 0.1);
486
487 this.spawnTimer += dt;
488 while (this.spawnTimer >= this.spawnInterval)
489 {
490 this.spawnTimer -= this.spawnInterval;
491 this.trySpawn();
492 }
493
494 var left = dt;
495 while (left > 1e-12)
496 {
497 var step = Math.min(SUBSTEP, left);
498 this.integrateFalling(step);
499 this.resolveFlyingMatches();
500 this.integrateClusters(step);
501 this.mergeFlyingClusters();
502 this.integrateManual(step);
503 this.cullOffTop();
504 left -= step;
505 }
506
507 this.releaseUnsupported();
508 this.advanceSettle(dt);
509 // After a landed grey group is released, blocks that were sitting on
510 // hanging members are still STILL (the earlier pass ran while those
511 // members counted as support). Drop them from rest before matching,
512 // so they cannot form a mid-air match and shoot off the top.
513 this.releaseUnsupported();
514 this.advanceBounces(dt);
515 if (!this.drag)
516 { this.resolveMatches(); }
517 this.checkLocks();
518 this.checkGameOver();
519};
520
521/** Step a stretch of time in fixed substeps. Useful for tests. */
522GameCore.prototype.step = function (seconds, dt)
523{
524 dt = dt || SUBSTEP;
525 var t = 0;
526 while (t < seconds - 1e-15)
527 {
528 var s = Math.min(dt, seconds - t);
529 this.tick(s);
530 t += s;
531 }
532};
533
534GameCore.prototype.trySpawn = function ()
535{
536 if (this.state !== 'playing')
537 { return null; }
538 var eligible = [];
539 for (var col = 0; col < this.width; col++)
540 {
541 if (this.isColumnLocked(col))
542 { continue; }
543 if (this.groundedCount(col) >= this.height)
544 { continue; }
545 var alreadyFalling = false;
546 var list = this.blocksInColumn(col);
547 for (var i = 0; i < list.length; i++)
548 {
549 if (list[i].state === STATE_FALLING)
550 {
551 alreadyFalling = true;
552 break;
553 }
554 }
555 if (!alreadyFalling)
556 { eligible.push(col); }
557 }
558 if (!eligible.length)
559 { return null; }
560 var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
561 var color = this.randomColor();
562 var block = this.createBlock(col, this.height, color, STATE_FALLING);
563 block.vy = -this.planet.fallSpeed;
564 return block;
565};
566
567GameCore.prototype.integrateFalling = function (dt)
568{
569 var falling = [];
570 for (var i = 0; i < this.blocks.length; i++)
571 {
572 if (this.blocks[i].state === STATE_FALLING)
573 { falling.push(this.blocks[i]); }
574 }
575 // Lowest first, so a stack of falling blocks rests on itself.
576 falling.sort(function (a, b) { return a.y - b.y; });
577 for (var i = 0; i < falling.length; i++)
578 {
579 var block = falling[i];
580 if (block.state !== STATE_FALLING)
581 { continue; }
582 this.accelerateFall(block, dt);
583 var nextY = block.y + block.vy * dt;
584 var flyer = this.highestFlyingBelow(block);
585 if (flyer && nextY <= flyer.y + 1 + 1e-9)
586 {
587 if (this.attachToFlyingCluster(block, flyer))
588 { continue; }
589 }
590 var top = this.stackTop(block.col);
591 var below = this.highestFallingBelow(block);
592 if (below && below.y + 1 > top)
593 { top = below.y + 1; }
594 if (nextY <= top)
595 {
596 block.y = top;
597 this.landFallingBlock(block);
598 }
599 else
600 { block.y = nextY; }
601 }
602};
603
604GameCore.prototype.clusterMembers = function (clusterId)
605{
606 var out = [];
607 for (var i = 0; i < this.blocks.length; i++)
608 {
609 if (this.blocks[i].clusterId === clusterId)
610 { out.push(this.blocks[i]); }
611 }
612 return out;
613};
614
615
616/**
617 * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a
618 * jump of height H peaks at exactly H after riseTime. Returns dy.
619 * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the
620 * upward deceleration. After the apex, vy eases from 0 to -fallSpeed
621 * at planet.fallAccel, then stays at terminal fallSpeed.
622 */
623GameCore.prototype.advanceJump = function (body, dt)
624{
625 var dy = 0;
626 var left = dt;
627 if (body.phase === 'up')
628 {
629 var decel = body.decel;
630 var vy = body.vy;
631 var tApex = decel > 1e-12 ? vy / decel : Infinity;
632 if (tApex <= left + 1e-15)
633 {
634 dy += vy * tApex - 0.5 * decel * tApex * tApex;
635 body.vy = 0;
636 body.phase = 'down';
637 left -= tApex;
638 }
639 else
640 {
641 var vyNew = vy - decel * left;
642 dy += (vy + vyNew) * 0.5 * left;
643 body.vy = vyNew;
644 left = 0;
645 }
646 }
647 if (body.phase === 'up' && body.vy <= 1e-10)
648 {
649 body.vy = 0;
650 body.phase = 'down';
651 }
652 if (body.phase === 'down' && left > 0)
653 {
654 var target = -this.planet.fallSpeed;
655 var accel = this.planet.fallAccel;
656 if (accel < 1e-12)
657 {
658 body.vy = target;
659 dy += body.vy * left;
660 }
661 else if (body.vy > target + 1e-12)
662 {
663 var tReach = (body.vy - target) / accel;
664 if (tReach <= left + 1e-15)
665 {
666 dy += (body.vy + target) * 0.5 * tReach;
667 body.vy = target;
668 left -= tReach;
669 dy += body.vy * left;
670 }
671 else
672 {
673 var vyNew = body.vy - accel * left;
674 dy += (body.vy + vyNew) * 0.5 * left;
675 body.vy = vyNew;
676 }
677 }
678 else
679 {
680 body.vy = target;
681 dy += body.vy * left;
682 }
683 }
684 return dy;
685};
686
687GameCore.prototype.integrateClusters = function (dt)
688{
689 var ids = Object.keys(this.clusters);
690 for (var n = 0; n < ids.length; n++)
691 {
692 var cluster = this.clusters[ids[n]];
693 if (!cluster)
694 { continue; }
695 var members = this.clusterMembers(cluster.id);
696 if (!members.length)
697 {
698 delete this.clusters[cluster.id];
699 continue;
700 }
701 if (cluster.phase === 'landed' || cluster.phase === 'hold')
702 { continue; }
703
704 var dy = this.advanceJump(cluster, dt);
705 for (var i = 0; i < members.length; i++)
706 {
707 members[i].y += dy;
708 members[i].vy = cluster.vy;
709 }
710
711 this.catchFallingOntoCluster(cluster, members);
712 this.checkChainRelaunch(cluster);
713
714 if (cluster.phase === 'down' && this.clusters[cluster.id])
715 { this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); }
716 }
717};
718
719
720/**
721 * If two or more flying clusters overlap in the same column, merge them
722 * into one cluster. Velocity (and deceleration and jumpHeight) is the
723 * mass-weighted average by block count. Phase is 'up' when the merged
724 * vy is positive, otherwise 'down'. Overlapping members in a column
725 * are packed so the higher one sits flush on the lower.
726 */
727GameCore.prototype.mergeFlyingClusters = function ()
728{
729 var flying = [];
730 var ids = Object.keys(this.clusters);
731 for (var n = 0; n < ids.length; n++)
732 {
733 var cluster = this.clusters[ids[n]];
734 if (!cluster)
735 { continue; }
736 if (cluster.phase === 'landed' || cluster.phase === 'hold')
737 { continue; }
738 flying.push(cluster);
739 }
740 if (flying.length < 2)
741 { return; }
742
743 var uf = new UnionFind();
744 for (var i = 0; i < flying.length; i++)
745 { uf.add(flying[i].id); }
746 for (var i = 0; i < flying.length; i++)
747 {
748 for (var j = i + 1; j < flying.length; j++)
749 {
750 if (this.flyingClustersOverlap(flying[i], flying[j]))
751 { uf.union(flying[i].id, flying[j].id); }
752 }
753 }
754
755 var groups = Object.create(null);
756 for (var i = 0; i < flying.length; i++)
757 {
758 var root = uf.find(flying[i].id);
759 if (!groups[root])
760 { groups[root] = []; }
761 groups[root].push(flying[i]);
762 }
763 for (var root in groups)
764 {
765 if (groups[root].length >= 2)
766 { this.mergeClusterGroup(groups[root]); }
767 }
768};
769
770GameCore.prototype.flyingClustersOverlap = function (a, b)
771{
772 var ma = this.clusterMembers(a.id);
773 var mb = this.clusterMembers(b.id);
774 for (var i = 0; i < ma.length; i++)
775 {
776 for (var j = 0; j < mb.length; j++)
777 {
778 if (ma[i].col !== mb[j].col)
779 { continue; }
780 if (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9)
781 { return true; }
782 }
783 }
784 return false;
785};
786
787GameCore.prototype.mergeClusterGroup = function (clusters)
788{
789 clusters.sort(function (a, b) { return a.id - b.id; });
790 var keep = clusters[0];
791 var n = 0;
792 var vySum = 0;
793 var decelSum = 0;
794 var hSum = 0;
795 for (var c = 0; c < clusters.length; c++)
796 {
797 var mem = this.clusterMembers(clusters[c].id);
798 var m = mem.length;
799 n += m;
800 vySum += clusters[c].vy * m;
801 decelSum += (clusters[c].decel || 0) * m;
802 hSum += (clusters[c].jumpHeight || 0) * m;
803 }
804 if (n === 0)
805 { return; }
806 keep.vy = vySum / n;
807 keep.decel = decelSum / n;
808 keep.jumpHeight = hSum / n;
809 keep.phase = keep.vy > 1e-10 ? 'up' : 'down';
810 for (var c = 0; c < clusters.length; c++)
811 {
812 var mem = this.clusterMembers(clusters[c].id);
813 for (var i = 0; i < mem.length; i++)
814 {
815 mem[i].clusterId = keep.id;
816 mem[i].vy = keep.vy;
817 mem[i].state = STATE_FLYING;
818 }
819 if (clusters[c] !== keep)
820 { delete this.clusters[clusters[c].id]; }
821 }
822 this.packClusterOverlaps(keep);
823 this.checkChainRelaunch(keep);
824 if (keep.phase === 'down' && this.clusters[keep.id])
825 { this.tryLandCluster(keep, this.clusterMembers(keep.id)); }
826};
827
828GameCore.prototype.packClusterOverlaps = function (cluster)
829{
830 var members = this.clusterMembers(cluster.id);
831 var byCol = Object.create(null);
832 for (var i = 0; i < members.length; i++)
833 {
834 var col = members[i].col;
835 if (!byCol[col])
836 { byCol[col] = []; }
837 byCol[col].push(members[i]);
838 }
839 var cols = Object.keys(byCol);
840 for (var c = 0; c < cols.length; c++)
841 {
842 var list = byCol[cols[c]];
843 list.sort(function (a, b) { return a.y - b.y; });
844 for (var i = 1; i < list.length; i++)
845 {
846 var minY = list[i - 1].y + 1;
847 if (list[i].y < minY - 1e-12)
848 { list[i].y = minY; }
849 }
850 }
851};
852
853GameCore.prototype.tryLandCluster = function (cluster, members)
854{
855 if (!members.length)
856 { return; }
857 var shift = 0;
858 var hit = false;
859 for (var i = 0; i < members.length; i++)
860 {
861 var block = members[i];
862 var top = this.stackTop(block.col, function (other)
863 {
864 return other.clusterId === cluster.id;
865 });
866 if (block.y <= top + 1e-9)
867 {
868 hit = true;
869 var need = top - block.y;
870 if (need > shift)
871 { shift = need; }
872 }
873 }
874 if (!hit)
875 { return; }
876 // Lift the whole rigid body so the deepest contact sits flush.
877 for (var i = 0; i < members.length; i++)
878 { members[i].y += shift; }
879 this.landCluster(cluster, members);
880};
881
882/**
883 * Land as a rigid group: relative positions are kept, so part of the
884 * cluster may hang above a gap. Grey members start the 3s settle timer;
885 * coloured cargo stays put with them until every grey has recolored.
886 * Members that actually rest on the floor or on another block bounce.
887 */
888GameCore.prototype.landCluster = function (cluster, members)
889{
890 for (var i = 0; i < members.length; i++)
891 {
892 var block = members[i];
893 block.vy = 0;
894 block.flame = false;
895 block.clusterId = cluster.id;
896 if (block.color === COLOR_GRAY)
897 {
898 block.state = STATE_SETTLING;
899 block.settleTime = 0;
900 }
901 else
902 {
903 // Cargo stays in the rigid group (not matchable) until release.
904 block.state = STATE_SETTLING;
905 block.settleTime = 0;
906 }
907 if (this.hasSupport(block))
908 { this.startBounce(block); }
909 }
910 cluster.phase = 'landed';
911 cluster.vy = 0;
912};
913
914/**
915 * After every grey in a landed cluster has recolored, let the group go.
916 * Unsupported blocks fall individually from rest; supported ones stay.
917 */
918GameCore.prototype.releaseLandedCluster = function (cluster)
919{
920 var members = this.clusterMembers(cluster.id);
921 var releasing = Object.create(null);
922 for (var i = 0; i < members.length; i++)
923 { releasing[members[i].id] = true; }
924
925 for (var i = 0; i < members.length; i++)
926 {
927 var block = members[i];
928 if (block.color === COLOR_GRAY)
929 {
930 block.color = this.randomColor();
931 block.settleTime = 0;
932 }
933 this.leaveCluster(block);
934 // Always drop leftover launch / manual velocity. A stale upward
935 // vy here is what sends blocks off the top "very fast" after
936 // a grey group recolors.
937 this.clearFlightState(block);
938 // Support from outside the group (floor or a foreign block). Fellow
939 // members that will also fall do not count, so a hanging stack
940 // drops together without the top one staying put.
941 var supported = this.hasSupportOutside(block, releasing);
942 block.state = supported ? STATE_STILL : STATE_FALLING;
943 }
944 delete this.clusters[cluster.id];
945};
946
947GameCore.prototype.hasSupportOutside = function (block, ignoreIds)
948{
949 if (block.y <= 1e-9)
950 { return true; }
951 for (var i = 0; i < this.blocks.length; i++)
952 {
953 var other = this.blocks[i];
954 if (other === block || other.col !== block.col)
955 { continue; }
956 if (ignoreIds && ignoreIds[other.id])
957 { continue; }
958 if (!this.isGrounded(other))
959 { continue; }
960 if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS)
961 { return true; }
962 }
963 return false;
964};
965
966GameCore.prototype.integrateManual = function (dt)
967{
968 for (var i = 0; i < this.blocks.length; i++)
969 {
970 var block = this.blocks[i];
971 if (block.state !== STATE_MANUAL)
972 { continue; }
973
974 if (block.manualPhase === 'up')
975 {
976 var oldY = block.y;
977 var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel };
978 var dy = this.advanceJump(proxy, dt);
979 var nextY = oldY + dy;
980 this.checkManualPush(block, oldY, Math.min(nextY, block.manualTarget));
981 block.vy = proxy.vy;
982 block.manualPhase = proxy.phase;
983 block.y = Math.min(nextY, block.manualTarget);
984 if (block.y >= block.manualTarget - 1e-12)
985 {
986 block.y = block.manualTarget;
987 block.vy = 0;
988 block.manualPhase = 'down';
989 }
990 if (block.y > this.height - 1)
991 {
992 block.y = this.height - 1;
993 block.vy = 0;
994 block.manualPhase = 'down';
995 }
996 }
997
998 if (block.manualPhase === 'down')
999 {
1000 var proxy = { phase: 'down', vy: block.vy, decel: 0 };
1001 var dy = this.advanceJump(proxy, dt);
1002 block.vy = proxy.vy;
1003 var nextY = block.y + dy;
1004 var top = this.stackTop(block.col);
1005 if (nextY <= top)
1006 {
1007 block.y = top;
1008 block.state = STATE_STILL;
1009 block.vy = 0;
1010 block.manualPhase = null;
1011 block.flame = false;
1012 this.startBounce(block);
1013 }
1014 else
1015 {
1016 block.y = Math.min(nextY, this.height - 1);
1017 }
1018 }
1019 }
1020};
1021
1022GameCore.prototype.checkManualPush = function (manual, oldY, nextY)
1023{
1024 if (!manual.pushedClusters)
1025 { manual.pushedClusters = Object.create(null); }
1026
1027 var manualTopOld = oldY + 1;
1028 var manualTopNew = nextY + 1;
1029 var low = Math.min(oldY, nextY);
1030 var high = Math.max(oldY, nextY) + 1;
1031
1032 for (var i = 0; i < this.blocks.length; i++)
1033 {
1034 var other = this.blocks[i];
1035 if (other === manual)
1036 { continue; }
1037 if (other.col !== manual.col)
1038 { continue; }
1039 if (other.state !== STATE_FLYING || other.clusterId == null)
1040 { continue; }
1041 if (manual.pushedClusters[other.clusterId])
1042 { continue; }
1043 var otherBot = other.y;
1044 var otherTop = other.y + 1;
1045 var overlapping = otherBot < high + 1e-9 && otherTop > low - 1e-9;
1046 var crossing = manualTopOld <= otherBot + 1e-9 && manualTopNew >= otherBot - 1e-9;
1047 if (overlapping || crossing)
1048 {
1049 if (this.pushClusterColumn(other.clusterId, manual.col))
1050 {
1051 manual.pushedClusters[other.clusterId] = true;
1052 return;
1053 }
1054 }
1055 }
1056};
1057
1058
1059/**
1060 * Push every flying block of the cluster that sits in `col` one tile up.
1061 * Other columns stay put (they remain linked). Then look for a new
1062 * same-color line of 3+ in the flying cluster; if there is one, those
1063 * blocks turn gray, join the link, and the whole cluster re-launches
1064 * with the same jump height from its current position.
1065 */
1066GameCore.prototype.pushClusterColumn = function (clusterId, col)
1067{
1068 var cluster = this.clusters[clusterId];
1069 if (!cluster)
1070 { return false; }
1071 var members = this.clusterMembers(clusterId);
1072 for (var i = 0; i < members.length; i++)
1073 {
1074 if (members[i].col === col)
1075 { members[i].y += 1; }
1076 }
1077 this.cullOffTop();
1078 if (!this.clusters[clusterId])
1079 { return true; }
1080 this.checkChainRelaunch(cluster);
1081 return true;
1082};
1083
1084/**
1085 * After a cargo attach or a cluster merge (or any other mid-air state
1086 * change), turn spontaneous lines of 3+ into rockets and give the whole
1087 * already-flying cluster an extra launch from its current position —
1088 * the same re-launch as a player push that completes a row.
1089 */
1090GameCore.prototype.resolveFlyingMatches = function ()
1091{
1092 var ids = Object.keys(this.clusters);
1093 for (var n = 0; n < ids.length; n++)
1094 {
1095 var cluster = this.clusters[ids[n]];
1096 if (!cluster || cluster.phase === 'landed')
1097 { continue; }
1098 this.checkChainRelaunch(cluster);
1099 }
1100};
1101
1102GameCore.prototype.checkChainRelaunch = function (cluster)
1103{
1104 if (!this.clusters[cluster.id])
1105 { return; }
1106 var lines = this.findFlyingMatchLines(cluster.id);
1107 if (!lines.length)
1108 { return; }
1109 var newly = [];
1110 var seen = Object.create(null);
1111 for (var i = 0; i < lines.length; i++)
1112 {
1113 for (var j = 0; j < lines[i].blocks.length; j++)
1114 {
1115 var block = lines[i].blocks[j];
1116 if (seen[block.id])
1117 { continue; }
1118 seen[block.id] = true;
1119 newly.push(block);
1120 }
1121 }
1122 for (var i = 0; i < newly.length; i++)
1123 {
1124 var block = newly[i];
1125 block.color = COLOR_GRAY;
1126 block.flame = true;
1127 block.clusterId = cluster.id;
1128 block.state = STATE_FLYING;
1129 }
1130 this.relaunchCluster(cluster, cluster.jumpHeight);
1131};
1132
1133GameCore.prototype.relaunchCluster = function (cluster, height)
1134{
1135 cluster.jumpHeight = height;
1136 cluster.vy = PlanetMod.launchVelocity(this.planet, height);
1137 cluster.decel = PlanetMod.launchDeceleration(this.planet, height);
1138 cluster.phase = 'up';
1139 var members = this.clusterMembers(cluster.id);
1140 for (var i = 0; i < members.length; i++)
1141 {
1142 members[i].vy = cluster.vy;
1143 members[i].state = STATE_FLYING;
1144 if (members[i].color === COLOR_GRAY)
1145 { members[i].flame = true; }
1146 }
1147};
1148
1149GameCore.prototype.startManualLaunch = function (block)
1150{
1151 var target = this.height - 1;
1152 var height = Math.max(0.05, target - block.y);
1153 block.state = STATE_MANUAL;
1154 block.pushedClusters = Object.create(null);
1155 block.manualTarget = target;
1156 block.manualPhase = 'up';
1157 block.vy = PlanetMod.launchVelocity(this.planet, height);
1158 block.manualDecel = PlanetMod.launchDeceleration(this.planet, height);
1159 block.flame = false;
1160 if (this.drag && this.drag.blockId === block.id)
1161 { this.drag = null; }
1162};
1163
1164GameCore.prototype.cullOffTop = function ()
1165{
1166 var gone = [];
1167 for (var i = 0; i < this.blocks.length; i++)
1168 {
1169 var block = this.blocks[i];
1170 if (block.state === STATE_MANUAL)
1171 {
1172 if (block.y > this.height - 1)
1173 { block.y = this.height - 1; }
1174 continue;
1175 }
1176 if (block.y >= this.height - 1e-9)
1177 { gone.push(block); }
1178 }
1179 for (var i = 0; i < gone.length; i++)
1180 {
1181 var block = gone[i];
1182 this.outgoingShots.push({
1183 id: block.id,
1184 color: block.color,
1185 col: block.col,
1186 y: block.y
1187 });
1188 this.score += 1;
1189 this.removeBlock(block);
1190 }
1191};
1192
1193GameCore.prototype.consumeOutgoingShots = function ()
1194{
1195 var shots = this.outgoingShots;
1196 this.outgoingShots = [];
1197 return shots;
1198};
1199
1200/**
1201 * A compact field picture for the multiplayer snapshot (miniatures).
1202 * Includes every block's col, y, color, state and flame.
1203 */
1204GameCore.prototype.fieldSnapshot = function ()
1205{
1206 var blocks = [];
1207 for (var i = 0; i < this.blocks.length; i++)
1208 {
1209 var b = this.blocks[i];
1210 blocks.push({
1211 id: b.id,
1212 col: b.col,
1213 y: Math.round(b.y * 1000) / 1000,
1214 color: b.color,
1215 state: b.state,
1216 flame: !!b.flame
1217 });
1218 }
1219 return {
1220 score: this.score,
1221 state: this.state,
1222 width: this.width,
1223 height: this.height,
1224 locked: this.lockedColumnCount(),
1225 blocks: blocks
1226 };
1227};
1228
1229/**
1230 * Incoming garbage from another player: a dark-grey block that falls
1231 * normally from the top of an open column. After landing it uses the
1232 * usual 3s settle and then a random colour (landFallingBlock).
1233 * `col` is optional; a random eligible column is used otherwise.
1234 * Returns the new block, or null if every column is locked or full.
1235 */
1236GameCore.prototype.ingestGarbage = function (col)
1237{
1238 if (this.state !== 'playing')
1239 { return null; }
1240 var chosen = null;
1241 if (col != null && col >= 0 && col < this.width
1242 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
1243 { chosen = col | 0; }
1244 else
1245 {
1246 var eligible = [];
1247 for (var c = 0; c < this.width; c++)
1248 {
1249 if (this.isColumnLocked(c))
1250 { continue; }
1251 if (this.groundedCount(c) >= this.height)
1252 { continue; }
1253 eligible.push(c);
1254 }
1255 if (!eligible.length)
1256 { return null; }
1257 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1258 }
1259 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
1260 block.vy = -this.planet.fallSpeed;
1261 block.flame = false;
1262 return block;
1263};
1264
1265GameCore.prototype.advanceSettle = function (dt)
1266{
1267 for (var i = 0; i < this.blocks.length; i++)
1268 {
1269 var block = this.blocks[i];
1270 if (block.state !== STATE_SETTLING)
1271 { continue; }
1272 var inLanded = block.clusterId != null
1273 && this.clusters[block.clusterId]
1274 && this.clusters[block.clusterId].phase === 'landed';
1275 if (block.color === COLOR_GRAY)
1276 {
1277 block.settleTime += dt;
1278 if (block.settleTime >= this.settleTime)
1279 {
1280 block.color = this.randomColor();
1281 block.settleTime = 0;
1282 block.flame = false;
1283 if (inLanded)
1284 {
1285 // Stay in the rigid group; releaseLandedCluster runs below.
1286 block.state = STATE_SETTLING;
1287 }
1288 else
1289 {
1290 this.leaveCluster(block);
1291 this.clearFlightState(block);
1292 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
1293 }
1294 }
1295 }
1296 else if (!inLanded)
1297 {
1298 // Coloured settling that is not in a landed cluster (shouldn't
1299 // normally happen): just become still or fall, from rest.
1300 this.leaveCluster(block);
1301 this.clearFlightState(block);
1302 block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING;
1303 }
1304 }
1305
1306 var ids = Object.keys(this.clusters);
1307 for (var n = 0; n < ids.length; n++)
1308 {
1309 var cluster = this.clusters[ids[n]];
1310 if (!cluster || cluster.phase !== 'landed')
1311 { continue; }
1312 var members = this.clusterMembers(cluster.id);
1313 var greySettling = false;
1314 for (var i = 0; i < members.length; i++)
1315 {
1316 if (members[i].color === COLOR_GRAY && members[i].state === STATE_SETTLING)
1317 { greySettling = true; }
1318 }
1319 if (!greySettling)
1320 { this.releaseLandedCluster(cluster); }
1321 }
1322};
1323
1324GameCore.prototype.findMatchLines = function ()
1325{
1326 var candidates = [];
1327 for (var i = 0; i < this.blocks.length; i++)
1328 {
1329 var block = this.blocks[i];
1330 if (block.state === STATE_STILL && block.color >= 0)
1331 { candidates.push(block); }
1332 }
1333 return this.collectLines(candidates, true);
1334};
1335
1336GameCore.prototype.findFlyingMatchLines = function (clusterId)
1337{
1338 var candidates = [];
1339 for (var i = 0; i < this.blocks.length; i++)
1340 {
1341 var block = this.blocks[i];
1342 if (block.clusterId === clusterId && block.color >= 0
1343 && (block.state === STATE_FLYING))
1344 { candidates.push(block); }
1345 }
1346 return this.collectLines(candidates, false);
1347};
1348
1349GameCore.prototype.collectLines = function (candidates, snapInteger)
1350{
1351 var lines = [];
1352 if (!candidates.length)
1353 { return lines; }
1354
1355 var byRow = Object.create(null);
1356 for (var i = 0; i < candidates.length; i++)
1357 {
1358 var block = candidates[i];
1359 var row = Math.round(block.y);
1360 if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5))
1361 { continue; }
1362 if (!byRow[row])
1363 { byRow[row] = []; }
1364 byRow[row].push(block);
1365 }
1366 var rows = Object.keys(byRow);
1367 for (var r = 0; r < rows.length; r++)
1368 {
1369 var list = byRow[rows[r]];
1370 list.sort(function (a, b) { return a.col - b.col; });
1371 this.pushRuns(lines, list, false, function (a, b)
1372 {
1373 return a.color === b.color && a.col === b.col - 1 && a.color >= 0;
1374 });
1375 }
1376
1377 var byCol = Object.create(null);
1378 for (var i = 0; i < candidates.length; i++)
1379 {
1380 var block = candidates[i];
1381 if (!byCol[block.col])
1382 { byCol[block.col] = []; }
1383 byCol[block.col].push(block);
1384 }
1385 var cols = Object.keys(byCol);
1386 for (var c = 0; c < cols.length; c++)
1387 {
1388 var list = byCol[cols[c]];
1389 list.sort(function (a, b) { return a.y - b.y; });
1390 this.pushRuns(lines, list, true, function (a, b)
1391 {
1392 return a.color === b.color && a.color >= 0
1393 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS;
1394 });
1395 }
1396 return lines;
1397};
1398
1399GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent)
1400{
1401 var start = 0;
1402 for (var i = 1; i <= list.length; i++)
1403 {
1404 var same = i < list.length && adjacent(list[i - 1], list[i]);
1405 if (!same)
1406 {
1407 var length = i - start;
1408 if (length >= 3)
1409 {
1410 lines.push({
1411 blocks: list.slice(start, i),
1412 length: length,
1413 vertical: vertical
1414 });
1415 }
1416 start = i;
1417 }
1418 }
1419};
1420
1421GameCore.prototype.resolveMatches = function ()
1422{
1423 if (this.state !== 'playing' || this.drag)
1424 { return []; }
1425 var lines = this.findMatchLines();
1426 if (!lines.length)
1427 { return []; }
1428
1429 var uf = new UnionFind();
1430 var blockById = Object.create(null);
1431 for (var i = 0; i < lines.length; i++)
1432 {
1433 var line = lines[i];
1434 for (var j = 0; j < line.blocks.length; j++)
1435 {
1436 uf.add(line.blocks[j].id);
1437 blockById[line.blocks[j].id] = line.blocks[j];
1438 if (j > 0)
1439 { uf.union(line.blocks[0].id, line.blocks[j].id); }
1440 }
1441 }
1442 var matched = [];
1443 var seen = Object.create(null);
1444 for (var id in blockById)
1445 {
1446 if (!seen[id])
1447 {
1448 seen[id] = true;
1449 matched.push(blockById[id]);
1450 }
1451 }
1452 for (var i = 0; i < matched.length; i++)
1453 {
1454 for (var j = i + 1; j < matched.length; j++)
1455 {
1456 if (matched[i].col === matched[j].col)
1457 { uf.union(matched[i].id, matched[j].id); }
1458 }
1459 }
1460
1461 var groups = Object.create(null);
1462 for (var i = 0; i < matched.length; i++)
1463 {
1464 var root = uf.find(matched[i].id);
1465 if (!groups[root])
1466 { groups[root] = []; }
1467 groups[root].push(matched[i]);
1468 }
1469
1470 var launched = [];
1471 for (var root in groups)
1472 {
1473 var group = groups[root];
1474 var height = 0;
1475 for (var i = 0; i < lines.length; i++)
1476 {
1477 var line = lines[i];
1478 var overlaps = false;
1479 for (var j = 0; j < line.blocks.length; j++)
1480 {
1481 for (var k = 0; k < group.length; k++)
1482 {
1483 if (line.blocks[j].id === group[k].id)
1484 { overlaps = true; }
1485 }
1486 }
1487 if (overlaps)
1488 {
1489 var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical);
1490 if (h > height)
1491 { height = h; }
1492 }
1493 }
1494 this.launchCluster(group, height);
1495 launched.push({ blocks: group, jumpHeight: height });
1496 }
1497 return launched;
1498};
1499
1500/**
1501 * Gray the matched blocks, take everything sitting on top of them in
1502 * those columns, link them, and launch with jump height `height`.
1503 */
1504GameCore.prototype.launchCluster = function (matchedBlocks, height)
1505{
1506 var lowestInCol = Object.create(null);
1507 var matchedIds = Object.create(null);
1508 for (var i = 0; i < matchedBlocks.length; i++)
1509 {
1510 var block = matchedBlocks[i];
1511 matchedIds[block.id] = true;
1512 if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col])
1513 { lowestInCol[block.col] = block.y; }
1514 }
1515
1516 var clusterId = this.nextClusterId++;
1517 var cluster = {
1518 id: clusterId,
1519 jumpHeight: height,
1520 vy: PlanetMod.launchVelocity(this.planet, height),
1521 decel: PlanetMod.launchDeceleration(this.planet, height),
1522 phase: 'up'
1523 };
1524 this.clusters[clusterId] = cluster;
1525
1526 var riders = [];
1527 var cols = Object.keys(lowestInCol);
1528 for (var c = 0; c < cols.length; c++)
1529 {
1530 var col = +cols[c];
1531 var lowest = lowestInCol[col];
1532 var list = this.blocksInColumn(col);
1533 for (var i = 0; i < list.length; i++)
1534 {
1535 var block = list[i];
1536 if (!this.isGrounded(block) && block.state !== STATE_STILL)
1537 {
1538 if (block.state !== STATE_SETTLING)
1539 { continue; }
1540 }
1541 if (block.y + ALIGN_EPS >= lowest)
1542 { riders.push(block); }
1543 }
1544 }
1545
1546 for (var i = 0; i < riders.length; i++)
1547 {
1548 var block = riders[i];
1549 var isMatch = !!matchedIds[block.id];
1550 if (isMatch || block.color === COLOR_GRAY)
1551 {
1552 block.color = COLOR_GRAY;
1553 block.flame = true;
1554 }
1555 else
1556 { block.flame = false; }
1557 block.state = STATE_FLYING;
1558 block.clusterId = clusterId;
1559 block.vy = cluster.vy;
1560 block.settleTime = 0;
1561 }
1562 return cluster;
1563};
1564
1565GameCore.prototype.checkLocks = function ()
1566{
1567 for (var col = 0; col < this.width; col++)
1568 {
1569 if (this.isColumnLocked(col))
1570 { continue; }
1571 if (this.groundedCount(col) < this.height)
1572 { continue; }
1573 // Must fill the column from floor to top: 13 grounded blocks at y 0..12.
1574 var filled = true;
1575 for (var row = 0; row < this.height; row++)
1576 {
1577 var block = this.blockAt(col, row);
1578 if (!block || !this.isGrounded(block))
1579 {
1580 filled = false;
1581 break;
1582 }
1583 }
1584 if (!filled)
1585 { continue; }
1586 var list = this.blocksInColumn(col);
1587 for (var i = 0; i < list.length; i++)
1588 {
1589 var block = list[i];
1590 if (!this.isGrounded(block))
1591 { continue; }
1592 block.state = STATE_LOCKED;
1593 block.color = COLOR_GRAY;
1594 block.flame = false;
1595 block.vy = 0;
1596 block.settleTime = 0;
1597 if (block.clusterId != null)
1598 { this.leaveCluster(block); }
1599 }
1600 }
1601};
1602
1603GameCore.prototype.checkGameOver = function ()
1604{
1605 if (this.state !== 'playing')
1606 { return; }
1607 for (var col = 0; col < this.width; col++)
1608 {
1609 if (!this.isColumnLocked(col))
1610 { return; }
1611 }
1612 this.state = 'gameover';
1613 this.gameOverTime = 0;
1614 this.drag = null;
1615};
1616
1617/* ---------- dragging -------------------------------------------------- */
1618
1619GameCore.prototype.beginDrag = function (col, y)
1620{
1621 if (this.state !== 'playing')
1622 { return false; }
1623 var block = this.snapDragBlock(col, y);
1624 if (!block)
1625 { return false; }
1626 var top = this.columnStackTopRow(block.col);
1627 var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS;
1628 this.drag = {
1629 blockId: block.id,
1630 pointerY: y,
1631 startY: y,
1632 accum: 0,
1633 launchIntent: false,
1634 startedAsTop: startedAsTop
1635 };
1636 return true;
1637};
1638
1639/**
1640 * Instant grab: the nearest still, coloured block to (col, y), allowing
1641 * a small vertical miss and a horizontal slop into a neighbouring
1642 * column. `col` may be fractional (pointer x in tiles). No hold delay.
1643 */
1644GameCore.prototype.snapDragBlock = function (col, y)
1645{
1646 var raw = col;
1647 var c0 = Math.floor(raw + 1e-9);
1648 var frac = raw - c0;
1649 var candidates = [];
1650 if (c0 >= 0 && c0 < this.width)
1651 { candidates.push(c0); }
1652 // Only consult a neighbour when the pointer is actually near the edge
1653 // (a whole-number col, as in unit tests, stays in that column).
1654 if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0)
1655 { candidates.push(c0 - 1); }
1656 if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width)
1657 { candidates.push(c0 + 1); }
1658
1659 var best = null;
1660 var bestDist = Infinity;
1661 for (var c = 0; c < candidates.length; c++)
1662 {
1663 var cc = candidates[c];
1664 if (!this.isColumnStill(cc))
1665 { continue; }
1666 var list = this.blocksInColumn(cc);
1667 for (var i = 0; i < list.length; i++)
1668 {
1669 var block = list[i];
1670 if (block.state !== STATE_STILL || block.color < 0)
1671 { continue; }
1672 var dist = this.pointerDistToBlock(block, raw, y);
1673 // Prefer the column the pointer is actually in on a tie.
1674 if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0))
1675 {
1676 bestDist = dist;
1677 best = block;
1678 }
1679 }
1680 }
1681 if (!best || bestDist > SNAP_Y)
1682 { return null; }
1683 return best;
1684};
1685
1686GameCore.prototype.pointerDistToBlock = function (block, col, y)
1687{
1688 var dx;
1689 if (col >= block.col && col < block.col + 1)
1690 { dx = 0; }
1691 else if (col < block.col)
1692 { dx = block.col - col; }
1693 else
1694 { dx = col - (block.col + 1); }
1695 var dy;
1696 if (y >= block.y && y < block.y + 1)
1697 { dy = 0; }
1698 else if (y < block.y)
1699 { dy = block.y - y; }
1700 else
1701 { dy = y - (block.y + 1); }
1702 return Math.sqrt(dx * dx + dy * dy);
1703};
1704
1705GameCore.prototype.moveDrag = function (y)
1706{
1707 if (!this.drag)
1708 { return; }
1709 var block = this.blockById(this.drag.blockId);
1710 if (!block || block.state !== STATE_STILL)
1711 {
1712 this.drag = null;
1713 return;
1714 }
1715 if (!this.isColumnStill(block.col))
1716 {
1717 this.drag = null;
1718 return;
1719 }
1720 this.drag.pointerY = y;
1721 // 1:1 tracking: the target row is the one under the pointer, clamped
1722 // to the still stack. Swap step by step with each neighbour, and stop
1723 // exactly there. When the pointer stops, nothing else moves.
1724 // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold
1725 // used to jump a full cell on a short pull, and one large event
1726 // could walk the entire column (the "jumps all the way" bug).
1727 var top = this.columnStackTopRow(block.col);
1728 var bottom = this.columnStackBottomRow(block.col);
1729 var target = Math.floor(y + 1e-12);
1730 if (bottom < 0)
1731 { bottom = 0; }
1732 if (target < bottom)
1733 { target = bottom; }
1734 if (target > top)
1735 { target = top; }
1736 this.swapToward(block, target);
1737
1738 top = this.columnStackTopRow(block.col);
1739 var isTop = Math.abs(block.y - top) < ALIGN_EPS;
1740 if (this.drag.startedAsTop)
1741 {
1742 // Already the topmost block: pulling upward past its own position
1743 // (LAUNCH_PULL tiles above the press point) starts a manual jump.
1744 this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL);
1745 }
1746 else
1747 {
1748 // Started mid-stack: swap first, and only launch once the pointer
1749 // is pulled into the empty space above the (new) top.
1750 this.drag.launchIntent = isTop && (y > top + 1 + 0.25);
1751 }
1752};
1753
1754/** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */
1755GameCore.prototype.swapOne = function (block, dir)
1756{
1757 var neighbor = this.blockAt(block.col, block.y + dir);
1758 if (neighbor && this.isGrounded(neighbor) && neighbor !== block)
1759 {
1760 this.swapBlocks(block, neighbor);
1761 return true;
1762 }
1763 return false;
1764};
1765
1766GameCore.prototype.endDrag = function ()
1767{
1768 if (!this.drag)
1769 { return; }
1770 var block = this.blockById(this.drag.blockId);
1771 var launch = this.drag.launchIntent;
1772 this.drag = null;
1773 if (launch && block && block.state === STATE_STILL)
1774 { this.startManualLaunch(block); }
1775 else
1776 { this.resolveMatches(); }
1777};
1778
1779GameCore.prototype.blockById = function (id)
1780{
1781 for (var i = 0; i < this.blocks.length; i++)
1782 {
1783 if (this.blocks[i].id === id)
1784 { return this.blocks[i]; }
1785 }
1786 return null;
1787};
1788
1789GameCore.prototype.columnStackTopRow = function (col)
1790{
1791 var top = -1;
1792 var list = this.blocksInColumn(col);
1793 for (var i = 0; i < list.length; i++)
1794 {
1795 if (this.isGrounded(list[i]) && list[i].y > top)
1796 { top = list[i].y; }
1797 }
1798 return top;
1799};
1800
1801GameCore.prototype.columnStackBottomRow = function (col)
1802{
1803 var bottom = Infinity;
1804 var list = this.blocksInColumn(col);
1805 for (var i = 0; i < list.length; i++)
1806 {
1807 if (this.isGrounded(list[i]) && list[i].y < bottom)
1808 { bottom = list[i].y; }
1809 }
1810 return bottom === Infinity ? 0 : bottom;
1811};
1812
1813GameCore.prototype.swapToward = function (block, targetY)
1814{
1815 var guard = 0;
1816 while (guard++ < this.height + 2)
1817 {
1818 var current = block.y;
1819 if (targetY > current + 0.5)
1820 {
1821 var above = this.blockAt(block.col, current + 1);
1822 if (above && this.isGrounded(above) && above !== block)
1823 { this.swapBlocks(block, above); }
1824 else
1825 { break; }
1826 }
1827 else if (targetY < current - 0.5)
1828 {
1829 var below = this.blockAt(block.col, current - 1);
1830 if (below && this.isGrounded(below) && below !== block)
1831 { this.swapBlocks(block, below); }
1832 else
1833 { break; }
1834 }
1835 else
1836 { break; }
1837 }
1838};
1839
1840GameCore.prototype.swapBlocks = function (a, b)
1841{
1842 var y = a.y;
1843 a.y = b.y;
1844 b.y = y;
1845};
1846
1847/**
1848 * Test helper: stepwise-swap the block at (col, fromRow) to toRow.
1849 * Returns the moved block, or null if the column is not still.
1850 */
1851GameCore.prototype.swapTo = function (col, fromRow, toRow)
1852{
1853 if (!this.isColumnStill(col))
1854 { return null; }
1855 var block = this.blockAt(col, fromRow);
1856 if (!block)
1857 { return null; }
1858 this.swapToward(block, toRow);
1859 return block;
1860};
1861
1862/**
1863 * Test helper: a compact picture of grounded/falling/flying blocks.
1864 * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling,
1865 * L locked, f falling, m manual, . empty. Flying colored blocks use
1866 * their color with a marker in `flying`.
1867 */
1868GameCore.prototype.snapshot = function ()
1869{
1870 var grid = [];
1871 for (var r = 0; r < this.height; r++)
1872 {
1873 var row = [];
1874 for (var c = 0; c < this.width; c++)
1875 { row.push('.'); }
1876 grid.push(row);
1877 }
1878 var airborne = [];
1879 for (var i = 0; i < this.blocks.length; i++)
1880 {
1881 var block = this.blocks[i];
1882 var ch;
1883 if (block.state === STATE_LOCKED)
1884 { ch = 'L'; }
1885 else if (block.color === COLOR_GRAY)
1886 { ch = 'g'; }
1887 else
1888 { ch = String(block.color); }
1889 if (this.isGrounded(block) || block.state === STATE_FALLING)
1890 {
1891 var row = Math.round(block.y);
1892 if (row >= 0 && row < this.height)
1893 { grid[row][block.col] = ch; }
1894 }
1895 else
1896 {
1897 airborne.push({
1898 id: block.id,
1899 col: block.col,
1900 y: block.y,
1901 color: block.color,
1902 state: block.state,
1903 clusterId: block.clusterId,
1904 flame: block.flame,
1905 vy: block.vy
1906 });
1907 }
1908 }
1909 var lines = [];
1910 for (var r = this.height - 1; r >= 0; r--)
1911 { lines.push(grid[r].join('')); }
1912 return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state };
1913};
1914
1915var GameCoreAPI = {
1916 GameCore: GameCore,
1917 COLOR_GRAY: COLOR_GRAY,
1918 STATE_STILL: STATE_STILL,
1919 STATE_FALLING: STATE_FALLING,
1920 STATE_FLYING: STATE_FLYING,
1921 STATE_SETTLING: STATE_SETTLING,
1922 STATE_LOCKED: STATE_LOCKED,
1923 STATE_MANUAL: STATE_MANUAL
1924};
1925
1926if (typeof module !== 'undefined' && module.exports)
1927{ module.exports = GameCoreAPI; }
1928else if (typeof globalThis !== 'undefined')
1929{
1930 globalThis.GameCore = GameCore;
1931 globalThis.GameCoreAPI = GameCoreAPI;
1932}