BlueGit

projects-timfalken-com meteors

Files

meteors / src / gameCore.js

gameCore.js

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