BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

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