'use strict'; /** * Deterministic Meteors game core. No DOM, no rendering, no input devices. * The view layer reads this state and translates pointer events into * beginDrag / moveDrag / endDrag. */ var PlanetMod = (typeof require !== 'undefined' && typeof module !== 'undefined') ? require('./planet.js') : (typeof Planet !== 'undefined' ? Planet : globalThis.Planet); var COLOR_GRAY = -1; var STATE_STILL = 'still'; var STATE_FALLING = 'falling'; var STATE_FLYING = 'flying'; var STATE_SETTLING = 'settling'; var STATE_LOCKED = 'locked'; var STATE_MANUAL = 'manual'; var ALIGN_EPS = 0.15; var SUBSTEP = 1 / 120; var DRAG_LAUNCH_SLACK = 0.65; // Upward pull (tiles past the press point) that launches an already-topmost block. var LAUNCH_PULL = 0.35; // Minimal accumulated vertical pointer travel (tiles) to swap one step. // No hold delay: the first swap fires as soon as this distance is reached. var SWAP_DISTANCE = 0.25; // Fallback snap (tiles) when the press cell is empty: nearest block in the column. var SNAP_Y = 0.5; // Horizontal slop (tiles) for snapping to a neighbouring column on press. var HORIZONTAL_SLOP = 0.35; /** t1120: additive jump bonus per landing-chain step. A landing that * immediately makes a match launches at (1 + 0.25 * chain) times the * usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */ var LANDING_CHAIN_BONUS = 0.25; /** t1123: a column pulses red at or above this many grounded rows * (10 of 13 is just over 70%). */ var COLUMN_WARN_ROWS = 10; function UnionFind () { this.parent = Object.create(null); } UnionFind.prototype.add = function (id) { if (this.parent[id] == null) { this.parent[id] = id; } }; UnionFind.prototype.find = function (id) { if (this.parent[id] !== id) { this.parent[id] = this.find(this.parent[id]); } return this.parent[id]; }; UnionFind.prototype.union = function (a, b) { this.add(a); this.add(b); var ra = this.find(a); var rb = this.find(b); if (ra !== rb) { this.parent[rb] = ra; } }; function GameCore (planet, rng) { this.planet = planet || PlanetMod.defaultPlanet(); this.rng = rng || Math.random; this.width = PlanetMod.FIELD_WIDTH; this.height = PlanetMod.FIELD_HEIGHT; this.blocks = []; this.clusters = Object.create(null); this.nextBlockId = 1; this.nextClusterId = 1; this.spawnTimer = 0; this.spawnInterval = PlanetMod.SPAWN_INTERVAL; this.settleTime = PlanetMod.SETTLE_TIME; this.score = 0; this.state = 'playing'; this.drag = null; this.gameOverTime = 0; this.outgoingShots = []; // Stage-2 default; stage 3 replaces this with Planet.missChance (Power). this.missChance = optsMissChance(arguments); // t1112: invariant checker. strictInvariants throws (tests); // debugInvariants records violations for the ?debug overlay. this.strictInvariants = false; this.debugInvariants = false; this.lastInvariantViolations = []; // t1121: visual-only swap events, consumed by the view each frame. this.swapEvents = []; // t1120: last landing-chain indicator { chain, bonusPct }, or null. this.lastChainIndicator = null; } function optsMissChance (args) { // GameCore(planet, rng, missChance) — third arg is optional. if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2])) { return Math.max(0, Math.min(1, args[2])); } var planet = args[0]; if (planet && typeof PlanetMod.missChance === 'function') { return PlanetMod.missChance(planet); } return GameCore.DEFAULT_MISS_CHANCE; } GameCore.COLOR_GRAY = COLOR_GRAY; GameCore.LAUNCH_PULL = LAUNCH_PULL; GameCore.SWAP_DISTANCE = SWAP_DISTANCE; GameCore.SNAP_Y = SNAP_Y; GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP; GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS; GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS; GameCore.DEFAULT_MISS_CHANCE = 0.30; GameCore.STATE_STILL = STATE_STILL; GameCore.STATE_FALLING = STATE_FALLING; GameCore.STATE_FLYING = STATE_FLYING; GameCore.STATE_SETTLING = STATE_SETTLING; GameCore.STATE_LOCKED = STATE_LOCKED; GameCore.STATE_MANUAL = STATE_MANUAL; GameCore.prototype.randomColor = function () { return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length; }; GameCore.prototype.createBlock = function (col, y, color, state) { var block = { id: this.nextBlockId++, col: col, y: y, color: color, state: state || STATE_STILL, vy: 0, clusterId: null, settleTime: 0, flame: false, pushedClusters: null, manualTarget: 0, manualDecel: 0, manualPhase: null, bouncing: false, bounceAge: 0 }; this.blocks.push(block); return block; }; GameCore.prototype.removeBlock = function (block) { if (block.clusterId != null) { this.leaveCluster(block); } var index = this.blocks.indexOf(block); if (index >= 0) { this.blocks.splice(index, 1); } }; GameCore.prototype.leaveCluster = function (block) { var id = block.clusterId; block.clusterId = null; block.flame = false; if (id == null || !this.clusters[id]) { return; } var still = 0; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].clusterId === id) { still++; } } if (still === 0) { delete this.clusters[id]; } }; GameCore.prototype.blocksInColumn = function (col) { var out = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].col === col) { out.push(this.blocks[i]); } } out.sort(function (a, b) { return a.y - b.y; }); return out; }; GameCore.prototype.isGrounded = function (block) { return block.state === STATE_STILL || block.state === STATE_SETTLING || block.state === STATE_LOCKED; }; /** * Highest grounded landing surface in `col`. If `belowY` is given, only * blocks strictly below that y count — a hanging still block above a * gap must never pull a falling or thrown block upward through the gap. */ GameCore.prototype.stackTop = function (col, ignore, belowY) { var top = 0; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.col !== col) { continue; } if (ignore && ignore(block)) { continue; } if (belowY != null && block.y + 1e-9 >= belowY) { continue; } if (this.isGrounded(block)) { var surface = block.y + 1; if (surface > top) { top = surface; } } } return top; }; GameCore.prototype.isColumnLocked = function (col) { for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.col === col && block.state === STATE_LOCKED) { return true; } } return false; }; GameCore.prototype.isColumnStill = function (col) { if (this.isColumnLocked(col)) { return false; } for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.col !== col) { continue; } if (block.state === STATE_FLYING || block.state === STATE_FALLING || block.state === STATE_MANUAL || block.state === STATE_SETTLING) { return false; } } return true; }; GameCore.prototype.groundedCount = function (col) { var n = 0; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].col === col && this.isGrounded(this.blocks[i])) { n++; } } return n; }; GameCore.prototype.columnNeedsWarn = function (col) { return this.groundedCount(col) >= COLUMN_WARN_ROWS; }; /** * Which columns of a field snapshot should pulse (t1123). Flying, * falling and manual (airborne) blocks do not count: they are * temporary and would flicker the warning. Still, settling and * locked (grounded) blocks do. */ GameCore.warnColumnsFromSnapshot = function (snapshot, threshold) { threshold = threshold == null ? COLUMN_WARN_ROWS : threshold; var width = (snapshot && snapshot.width) || 10; var flags = []; var counts = []; for (var c = 0; c < width; c++) { counts[c] = 0; flags[c] = false; } var blocks = (snapshot && snapshot.blocks) || []; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; if (b.col < 0 || b.col >= width) { continue; } if (b.state === 'still' || b.state === 'settling' || b.state === 'locked') { counts[b.col]++; } } for (var c = 0; c < width; c++) { flags[c] = counts[c] >= threshold; } return flags; }; GameCore.columnWarnPulse = function (timeSec) { // Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player // field and opponent / bot minis so they pulse in sync. var t = timeSec; if (t == null) { t = (typeof performance !== 'undefined' && performance.now) ? performance.now() / 1000 : Date.now() / 1000; } return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55)); }; GameCore.prototype.blockAt = function (col, row) { for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS) { return block; } } return null; }; GameCore.prototype.place = function (col, row, color, state) { return this.createBlock(col, row, color, state || STATE_STILL); }; GameCore.prototype.lockedColumnCount = function () { var n = 0; for (var c = 0; c < this.width; c++) { if (this.isColumnLocked(c)) { n++; } } return n; }; GameCore.prototype.startBounce = function (block) { if (!block) { return; } block.bouncing = true; block.bounceAge = 0; }; GameCore.prototype.advanceBounces = function (dt) { var duration = this.planet.bounceDuration; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (!block.bouncing) { continue; } block.bounceAge += dt; if (duration <= 0 || block.bounceAge >= duration) { block.bouncing = false; block.bounceAge = duration; } } }; /** * True if `block` rests on the floor or on a solid (still / settling / * locked) block immediately below it in the same column. */ GameCore.prototype.hasSupport = function (block) { if (block.y <= 1e-9) { return true; } for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === block || other.col !== block.col) { continue; } if (!this.isGrounded(other)) { continue; } if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS) { return true; } } return false; }; /** Highest flying block in this column whose top is at or below `block.y + 1`. */ GameCore.prototype.highestFlyingBelow = function (block) { var best = null; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === block || other.col !== block.col) { continue; } if (other.state !== STATE_FLYING || other.clusterId == null) { continue; } var cluster = this.clusters[other.clusterId]; if (!cluster || cluster.phase === 'landed') { continue; } // The falling block is at or above this flyer (or already overlapping). if (block.y + 1e-9 < other.y) { continue; } if (!best || other.y > best.y) { best = other; } } return best; }; GameCore.prototype.highestFallingBelow = function (block) { var best = null; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === block || other.col !== block.col) { continue; } if (other.state !== STATE_FALLING) { continue; } if (other.y > block.y - 1e-9) { continue; } if (!best || other.y > best.y) { best = other; } } return best; }; /** * Make an unsupported still block start falling from rest, so it eases * into fallSpeed under normal gravity. Skips the block being dragged. */ /** * Strip leftover launch / manual kinematics so a block that has just * become still or falling starts from rest. Used after a landed grey * cluster recolors, and whenever an unsupported still block drops. */ GameCore.prototype.clearFlightState = function (block) { block.vy = 0; block.flame = false; block.manualPhase = null; block.manualTarget = null; block.manualDecel = 0; block.pushedClusters = null; }; GameCore.prototype.releaseUnsupported = function () { // Repeat until stable: a still sitting on a still that itself just // became falling must also drop. Two fixed passes are not enough // for a chain of hanging blocks (t1112). var guard = 0; var changed = true; while (changed && guard++ < this.height + 2) { changed = false; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.state !== STATE_STILL) { continue; } if (this.drag && this.drag.blockId === block.id) { continue; } if (this.hasSupport(block)) { continue; } this.leaveCluster(block); this.clearFlightState(block); block.state = STATE_FALLING; changed = true; } } }; GameCore.prototype.accelerateFall = function (block, dt) { var target = -this.planet.fallSpeed; if (block.vy > target) { block.vy = Math.max(target, block.vy - this.planet.fallAccel * dt); } else { block.vy = target; } }; GameCore.prototype.landFallingBlock = function (block) { block.vy = 0; block.flame = false; this.startBounce(block); if (block.color === COLOR_GRAY) { block.state = STATE_SETTLING; block.settleTime = 0; } else { block.state = STATE_STILL; } }; /** * Sit `block` on top of the flying cluster that `flyer` belongs to, and * carry it along as cargo (no flame). Returns true if attached. */ GameCore.prototype.attachToFlyingCluster = function (block, flyer) { var cluster = this.clusters[flyer.clusterId]; if (!cluster || cluster.phase === 'landed') { return false; } this.prepareClusterBody(cluster); var maxOff = null; var members = this.clusterMembers(cluster.id); for (var i = 0; i < members.length; i++) { if (members[i].col !== block.col) { continue; } if (maxOff == null || members[i].clusterOffset > maxOff) { maxOff = members[i].clusterOffset; } } var oldN = members.length; var fallingVy = block.vy; if (block.clusterId != null && block.clusterId !== cluster.id) { this.leaveCluster(block); } block.state = STATE_FLYING; block.clusterId = cluster.id; block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1; block.flame = false; block.settleTime = 0; block.manualPhase = null; block.manualTarget = null; block.manualDecel = 0; block.pushedClusters = null; // A cluster born from a thrown block averages in falling cargo // the same way two flying clusters merge (t1108). Other rockets // keep their velocity and just pick the cargo up. if (cluster.fromManual) { var newN = oldN + 1; cluster.vy = (cluster.vy * oldN + fallingVy) / newN; cluster.decel = ((cluster.decel || 0) * oldN) / newN; cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN; cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down'; } this.syncClusterMembers(cluster); return true; }; GameCore.prototype.catchFallingOntoCluster = function (cluster, members) { if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold') { return; } // Snapshot falling blocks; attaching mutates state. var falling = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].state === STATE_FALLING) { falling.push(this.blocks[i]); } } for (var i = 0; i < falling.length; i++) { var block = falling[i]; var flyer = null; for (var m = 0; m < members.length; m++) { var other = members[m]; if (other.col !== block.col) { continue; } // Overlap or rest on this member's top. if (block.y < other.y + 1 + 1e-9 && block.y + 1 > other.y - 1e-9) { if (!flyer || other.y > flyer.y) { flyer = other; } } } if (flyer) { this.attachToFlyingCluster(block, flyer); } } }; GameCore.prototype.tick = function (dt) { if (this.state === 'gameover') { this.gameOverTime += Math.max(0, dt); return; } if (dt <= 0) { return; } dt = Math.min(dt, 0.1); this.spawnTimer += dt; while (this.spawnTimer >= this.spawnInterval) { this.spawnTimer -= this.spawnInterval; this.trySpawn(); } var left = dt; while (left > 1e-12) { var step = Math.min(SUBSTEP, left); this.snapshotPrevY(); this.integrateFalling(step); this.resolveFlyingMatches(); this.integrateClusters(step); this.mergeFlyingClusters(); this.integrateManual(step); this.mergeAnyManualFallingOverlaps(); this.resolveAirborneCollisions(); this.cullOffTop(); left -= step; } this.releaseUnsupported(); this.advanceSettle(dt); // After a landed grey group is released, blocks that were sitting on // hanging members are still STILL (the earlier pass ran while those // members counted as support). Drop them from rest before matching, // so they cannot form a mid-air match and shoot off the top. this.releaseUnsupported(); this.advanceBounces(dt); if (!this.drag) { this.resolveMatches(); } this.checkLocks(); this.checkGameOver(); this.assertInvariants('tick'); }; /** Step a stretch of time in fixed substeps. Useful for tests. */ GameCore.prototype.step = function (seconds, dt) { dt = dt || SUBSTEP; var t = 0; while (t < seconds - 1e-15) { var s = Math.min(dt, seconds - t); this.tick(s); t += s; } }; GameCore.prototype.trySpawn = function () { if (this.state !== 'playing') { return null; } var eligible = []; for (var col = 0; col < this.width; col++) { if (this.isColumnLocked(col)) { continue; } if (this.groundedCount(col) >= this.height) { continue; } var alreadyFalling = false; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { if (list[i].state === STATE_FALLING) { alreadyFalling = true; break; } } if (!alreadyFalling) { eligible.push(col); } } if (!eligible.length) { return null; } var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length]; var color = this.randomColor(); var block = this.createBlock(col, this.height, color, STATE_FALLING); block.vy = -this.planet.fallSpeed; return block; }; GameCore.prototype.integrateFalling = function (dt) { var falling = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].state === STATE_FALLING) { falling.push(this.blocks[i]); } } // Lowest first, so a stack of falling blocks rests on itself. falling.sort(function (a, b) { return a.y - b.y; }); for (var i = 0; i < falling.length; i++) { var block = falling[i]; if (block.state !== STATE_FALLING) { continue; } this.accelerateFall(block, dt); var nextY = block.y + block.vy * dt; var manual = this.manualInColumnHit(block, block.y, nextY); if (manual) { this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block])); continue; } var flyer = this.highestFlyingBelow(block); if (flyer && nextY <= flyer.y + 1 + 1e-9) { if (this.attachToFlyingCluster(block, flyer)) { continue; } } var top = this.stackTop(block.col, null, block.y); var below = this.highestFallingBelow(block); if (below && below.y + 1 > top) { top = below.y + 1; } if (nextY <= top) { block.y = top; this.landFallingBlock(block); } else { block.y = nextY; } } }; GameCore.prototype.clusterMembers = function (clusterId) { var out = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].clusterId === clusterId) { out.push(this.blocks[i]); } } return out; }; /** * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a * jump of height H peaks at exactly H after riseTime. Returns dy. * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the * upward deceleration. After the apex, vy eases from 0 to the * terminal descent speed at the matching accel, then stays there. * Flying clusters (forCluster) use the halved cluster float-down * (t1122 / t1124); manual jumps use the full single-block fallSpeed. */ GameCore.prototype.descentParams = function (forCluster) { var p = this.planet; if (forCluster) { return { fallSpeed: p.clusterFallSpeed, fallAccel: p.clusterFallAccel }; } return { fallSpeed: p.fallSpeed, fallAccel: p.fallAccel }; }; GameCore.prototype.advanceJump = function (body, dt, forCluster) { var dy = 0; var left = dt; if (body.phase === 'up') { var decel = body.decel; var vy = body.vy; var tApex = decel > 1e-12 ? vy / decel : Infinity; if (tApex <= left + 1e-15) { dy += vy * tApex - 0.5 * decel * tApex * tApex; body.vy = 0; body.phase = 'down'; left -= tApex; } else { var vyNew = vy - decel * left; dy += (vy + vyNew) * 0.5 * left; body.vy = vyNew; left = 0; } } if (body.phase === 'up' && body.vy <= 1e-10) { body.vy = 0; body.phase = 'down'; } if (body.phase === 'down' && left > 0) { var desc = this.descentParams(forCluster); var target = -desc.fallSpeed; var accel = desc.fallAccel; if (accel < 1e-12) { body.vy = target; dy += body.vy * left; } else if (body.vy > target + 1e-12) { var tReach = (body.vy - target) / accel; if (tReach <= left + 1e-15) { dy += (body.vy + target) * 0.5 * tReach; body.vy = target; left -= tReach; dy += body.vy * left; } else { var vyNew = body.vy - accel * left; dy += (body.vy + vyNew) * 0.5 * left; body.vy = vyNew; } } else { body.vy = target; dy += body.vy * left; } } return dy; }; GameCore.prototype.integrateClusters = function (dt) { var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster) { continue; } var members = this.clusterMembers(cluster.id); if (!members.length) { delete this.clusters[cluster.id]; continue; } if (cluster.phase === 'landed' || cluster.phase === 'hold') { continue; } this.prepareClusterBody(cluster); var dy = this.advanceJump(cluster, dt, true); cluster.anchorY += dy; this.syncClusterMembers(cluster); this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id)); this.checkChainRelaunch(cluster); if (cluster.phase === 'down' && this.clusters[cluster.id]) { this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); } } }; /** * If two or more flying clusters overlap in the same column, merge them * into one cluster. Velocity (and deceleration and jumpHeight) is the * mass-weighted average by block count. Phase is 'up' when the merged * vy is positive, otherwise 'down'. Overlapping members in a column * are packed so the higher one sits flush on the lower. */ GameCore.prototype.mergeFlyingClusters = function () { var flying = []; var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster) { continue; } if (cluster.phase === 'landed' || cluster.phase === 'hold') { continue; } flying.push(cluster); } if (flying.length < 2) { return; } var uf = new UnionFind(); for (var i = 0; i < flying.length; i++) { uf.add(flying[i].id); } for (var i = 0; i < flying.length; i++) { for (var j = i + 1; j < flying.length; j++) { if (this.flyingClustersOverlap(flying[i], flying[j])) { uf.union(flying[i].id, flying[j].id); } } } var groups = Object.create(null); for (var i = 0; i < flying.length; i++) { var root = uf.find(flying[i].id); if (!groups[root]) { groups[root] = []; } groups[root].push(flying[i]); } for (var root in groups) { if (groups[root].length >= 2) { this.mergeClusterGroup(groups[root]); } } }; GameCore.prototype.flyingClustersOverlap = function (a, b) { var ma = this.clusterMembers(a.id); var mb = this.clusterMembers(b.id); for (var i = 0; i < ma.length; i++) { for (var j = 0; j < mb.length; j++) { if (ma[i].col !== mb[j].col) { continue; } if (this.sweptIntervalsOverlap(ma[i], mb[j])) { return true; } } } return false; }; /** * Swept [y, y+1) of two blocks this substep, using _prevY when present. * Catches pairs that crossed without sharing a cell at either endpoint. */ GameCore.prototype.sweptIntervalsOverlap = function (a, b) { var a0 = (a._prevY != null) ? a._prevY : a.y; var a1 = a.y; var b0 = (b._prevY != null) ? b._prevY : b.y; var b1 = b.y; var aLo = Math.min(a0, a1); var aHi = Math.max(a0, a1) + 1; var bLo = Math.min(b0, b1); var bHi = Math.max(b0, b1) + 1; return aLo < bHi - 1e-9 && bLo < aHi - 1e-9; }; GameCore.prototype.mergeClusterGroup = function (clusters) { clusters.sort(function (a, b) { return a.id - b.id; }); var keep = clusters[0]; var n = 0; var vySum = 0; var decelSum = 0; var hSum = 0; for (var c = 0; c < clusters.length; c++) { var mem = this.clusterMembers(clusters[c].id); var m = mem.length; n += m; vySum += clusters[c].vy * m; decelSum += (clusters[c].decel || 0) * m; hSum += (clusters[c].jumpHeight || 0) * m; } if (n === 0) { return; } keep.vy = vySum / n; keep.decel = decelSum / n; keep.jumpHeight = hSum / n; keep.phase = keep.vy > 1e-10 ? 'up' : 'down'; var maxChain = 0; for (var c = 0; c < clusters.length; c++) { var ch = clusters[c].landingChain || 0; if (ch > maxChain) { maxChain = ch; } } keep.landingChain = maxChain; for (var c = 0; c < clusters.length; c++) { var mem = this.clusterMembers(clusters[c].id); for (var i = 0; i < mem.length; i++) { mem[i].clusterId = keep.id; mem[i].vy = keep.vy; mem[i].state = STATE_FLYING; } if (clusters[c] !== keep) { delete this.clusters[clusters[c].id]; } } this.prepareClusterBody(keep); this.checkChainRelaunch(keep); if (keep.phase === 'down' && this.clusters[keep.id]) { this.tryLandCluster(keep, this.clusterMembers(keep.id)); } }; GameCore.prototype.packClusterOverlaps = function (cluster) { var members = this.clusterMembers(cluster.id); var byCol = Object.create(null); for (var i = 0; i < members.length; i++) { var col = members[i].col; if (!byCol[col]) { byCol[col] = []; } byCol[col].push(members[i]); } var cols = Object.keys(byCol); for (var c = 0; c < cols.length; c++) { var list = byCol[cols[c]]; list.sort(function (a, b) { return a.y - b.y; }); for (var i = 1; i < list.length; i++) { var minY = list[i - 1].y + 1; if (list[i].y < minY - 1e-12) { list[i].y = minY; } } } }; /** * Derive integer cell offsets from current member positions and a * single anchorY, packing overlaps in each column while preserving * order (lower y stays lower; ties break on id). Then sync. * Flying clusters are one rigid body: one y, one vy, integer offsets. */ GameCore.prototype.prepareClusterBody = function (cluster) { if (!cluster) { return; } var members = this.clusterMembers(cluster.id); if (!members.length) { return; } this.rebuildClusterOffsets(cluster, members); }; GameCore.prototype.rebuildClusterOffsets = function (cluster, members) { members = members || this.clusterMembers(cluster.id); if (!members.length) { return; } var byCol = Object.create(null); for (var i = 0; i < members.length; i++) { var col = members[i].col; if (!byCol[col]) { byCol[col] = []; } byCol[col].push(members[i]); } var minY = Infinity; for (var i = 0; i < members.length; i++) { if (members[i].y < minY) { minY = members[i].y; } } if (cluster.anchorY == null || !isFinite(cluster.anchorY)) { cluster.anchorY = minY; } var cols = Object.keys(byCol); for (var c = 0; c < cols.length; c++) { var list = byCol[cols[c]]; list.sort(function (a, b) { if (a.y !== b.y) { return a.y - b.y; } return a.id - b.id; }); var prevOff = -Infinity; for (var i = 0; i < list.length; i++) { var off = Math.round(list[i].y - cluster.anchorY); if (off <= prevOff) { off = prevOff + 1; } list[i].clusterOffset = off; prevOff = off; } } // Re-base so the lowest offset is 0, keeping relative integers. var minOff = Infinity; for (var i = 0; i < members.length; i++) { if (members[i].clusterOffset < minOff) { minOff = members[i].clusterOffset; } } if (minOff !== 0 && isFinite(minOff)) { cluster.anchorY += minOff; for (var i = 0; i < members.length; i++) { members[i].clusterOffset -= minOff; } } this.syncClusterMembers(cluster); }; GameCore.prototype.syncClusterMembers = function (cluster) { if (!cluster) { return; } var members = this.clusterMembers(cluster.id); if (cluster.anchorY == null) { var minY = Infinity; for (var i = 0; i < members.length; i++) { if (members[i].y < minY) { minY = members[i].y; } } cluster.anchorY = isFinite(minY) ? minY : 0; } for (var i = 0; i < members.length; i++) { var block = members[i]; if (block.clusterOffset == null) { block.clusterOffset = Math.round(block.y - cluster.anchorY); } block.y = cluster.anchorY + block.clusterOffset; if (cluster.phase !== 'landed') { block.vy = cluster.vy; } } }; GameCore.prototype.snapshotPrevY = function () { for (var i = 0; i < this.blocks.length; i++) { this.blocks[i]._prevY = this.blocks[i].y; } }; /** * Safety net after the specific integrates: any remaining mid-air * overlap or swept crossing is resolved with the same rules, then * every flying cluster is rebuilt as a rigid body. Repeats a few * times because one attach can create a new contact. */ GameCore.prototype.resolveAirborneCollisions = function () { var guard = 0; while (guard++ < this.height + 4) { var changed = false; // Manual vs falling / cluster / manual. var manuals = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].state === STATE_MANUAL) { manuals.push(this.blocks[i]); } } manuals.sort(function (a, b) { return b.y - a.y; }); for (var m = 0; m < manuals.length; m++) { var manual = manuals[m]; if (manual.state !== STATE_MANUAL) { continue; } var oldY = (manual._prevY != null) ? manual._prevY : manual.y; if (this.resolveManualCollisions(manual, oldY, manual.y)) { changed = true; } } // Falling vs flying (sit on the roof). for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.state !== STATE_FALLING) { continue; } var flyer = this.highestFlyingBelow(block); if (!flyer) { // Also a flyer whose swept path crosses this falling block. flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y); } if (flyer && this.sweptIntervalsOverlap(block, flyer)) { if (this.attachToFlyingCluster(block, flyer)) { changed = true; } } } // Cluster vs cluster (swept, including after a column push). var before = Object.keys(this.clusters).length; this.mergeFlyingClusters(); if (Object.keys(this.clusters).length !== before) { changed = true; } // Rebuild every flying body so offsets stay integer and unique. var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold') { continue; } this.prepareClusterBody(cluster); } if (!changed) { break; } } }; /** * Invariant checker (t1112). No two blocks occupy the same cell or * overlap their [y, y+1) intervals. Flying-cluster members are * grid-aligned to a single anchor. Returns a list of violation * strings (empty if clean). */ GameCore.prototype.checkInvariants = function () { var issues = []; var byCol = Object.create(null); var ids = Object.create(null); for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (ids[block.id]) { issues.push('duplicate id ' + block.id); } ids[block.id] = true; if (!byCol[block.col]) { byCol[block.col] = []; } byCol[block.col].push(block); if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet && block.color >= this.planet.colors.length)) { issues.push('block ' + block.id + ' has invalid color ' + block.color); } } var cols = Object.keys(byCol); for (var c = 0; c < cols.length; c++) { var list = byCol[cols[c]]; list.sort(function (a, b) { if (a.y !== b.y) { return a.y - b.y; } return a.id - b.id; }); for (var i = 0; i < list.length; i++) { var a = list[i]; if (i > 0) { var prev = list[i - 1]; if (a.y < prev.y + 1 - 1e-6) { issues.push('overlap col=' + a.col + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a) + ' gap=' + (a.y - prev.y)); } var cellA = Math.floor(a.y + 1e-9); var cellP = Math.floor(prev.y + 1e-9); if (cellA === cellP) { issues.push('duplicate cell col=' + a.col + ' row=' + cellA + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)); } } } } var cids = Object.keys(this.clusters); for (var n = 0; n < cids.length; n++) { var cluster = this.clusters[cids[n]]; if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold') { continue; } var mem = this.clusterMembers(cluster.id); var seenOff = Object.create(null); for (var i = 0; i < mem.length; i++) { var b = mem[i]; if (cluster.anchorY != null && b.clusterOffset != null) { var expected = cluster.anchorY + b.clusterOffset; if (Math.abs(b.y - expected) > 1e-6) { issues.push('cluster ' + cluster.id + ' member ' + b.id + ' y=' + b.y + ' != anchor+off ' + expected); } if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9) { issues.push('cluster ' + cluster.id + ' member ' + b.id + ' non-integer offset ' + b.clusterOffset); } var key = b.col + ':' + b.clusterOffset; if (seenOff[key]) { issues.push('cluster ' + cluster.id + ' duplicate offset ' + key); } seenOff[key] = true; } } } return issues; }; GameCore.prototype._invBlock = function (b) { return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y=' + (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')'; }; GameCore.prototype.assertInvariants = function (label) { if (!this.strictInvariants && !this.debugInvariants) { return; } var issues = this.checkInvariants(); this.lastInvariantViolations = issues; if (!issues.length) { return; } var msg = 'physics invariants failed' + (label ? ' at ' + label : '') + ':\n ' + issues.join('\n ') + '\n' + (this.snapshot ? this.snapshot().picture : ''); if (this.strictInvariants) { throw new Error(msg); } }; GameCore.prototype.tryLandCluster = function (cluster, members) { if (!members.length) { return; } var shift = 0; var hit = false; for (var i = 0; i < members.length; i++) { var block = members[i]; var top = this.stackTop(block.col, function (other) { return other.clusterId === cluster.id; }, block.y); if (block.y <= top + 1e-9) { hit = true; var need = top - block.y; if (need > shift) { shift = need; } } } if (!hit) { return; } // Lift the whole rigid body so the deepest contact sits flush. this.prepareClusterBody(cluster); cluster.anchorY += shift; this.syncClusterMembers(cluster); this.landCluster(cluster, this.clusterMembers(cluster.id)); }; /** * Land as a rigid group: relative positions are kept, so part of the * cluster may hang above a gap. Grey members start the 3s settle timer; * coloured cargo stays put with them until every grey has recolored. * Members that actually rest on the floor or on another block bounce. */ GameCore.prototype.landCluster = function (cluster, members) { for (var i = 0; i < members.length; i++) { var block = members[i]; block.vy = 0; block.flame = false; block.clusterId = cluster.id; if (block.color === COLOR_GRAY) { block.state = STATE_SETTLING; block.settleTime = 0; } else { // Cargo stays in the rigid group (not matchable) until release. block.state = STATE_SETTLING; block.settleTime = 0; } if (this.hasSupport(block)) { this.startBounce(block); } } cluster.phase = 'landed'; cluster.vy = 0; cluster.landedPending = true; if (cluster.landingChain == null) { cluster.landingChain = 0; } }; /** * After every grey in a landed cluster has recolored, let the group go. * Unsupported blocks fall individually from rest; supported ones stay. */ GameCore.prototype.releaseLandedCluster = function (cluster) { var members = this.clusterMembers(cluster.id); var releasing = Object.create(null); for (var i = 0; i < members.length; i++) { releasing[members[i].id] = true; } for (var i = 0; i < members.length; i++) { var block = members[i]; if (block.color === COLOR_GRAY) { block.color = this.randomColor(); block.settleTime = 0; } // Persist the chain across release so a post-recolor match in // this same tick still gets the landing bonus (t1120). block.justLanded = !!cluster.landedPending; block.landingChain = cluster.landingChain || 0; this.leaveCluster(block); // Always drop leftover launch / manual velocity. A stale upward // vy here is what sends blocks off the top "very fast" after // a grey group recolors. this.clearFlightState(block); // Support from outside the group (floor or a foreign block). Fellow // members that will also fall do not count, so a hanging stack // drops together without the top one staying put. var supported = this.hasSupportOutside(block, releasing); block.state = supported ? STATE_STILL : STATE_FALLING; } delete this.clusters[cluster.id]; }; GameCore.prototype.hasSupportOutside = function (block, ignoreIds) { if (block.y <= 1e-9) { return true; } for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === block || other.col !== block.col) { continue; } if (ignoreIds && ignoreIds[other.id]) { continue; } if (!this.isGrounded(other)) { continue; } if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS) { return true; } } return false; }; GameCore.prototype.integrateManual = function (dt) { for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.state !== STATE_MANUAL) { continue; } if (block.manualPhase === 'up') { var oldY = block.y; var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel }; var dy = this.advanceJump(proxy, dt); var nextY = oldY + dy; block.vy = proxy.vy; block.manualPhase = proxy.phase; if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget))) { continue; } block.y = Math.min(nextY, block.manualTarget); if (block.y >= block.manualTarget - 1e-12) { block.y = block.manualTarget; block.vy = 0; block.manualPhase = 'down'; } if (block.y > this.height - 1) { block.y = this.height - 1; block.vy = 0; block.manualPhase = 'down'; } } if (block.manualPhase === 'down') { var proxy = { phase: 'down', vy: block.vy, decel: 0 }; var dy = this.advanceJump(proxy, dt); block.vy = proxy.vy; var nextY = block.y + dy; var top = this.stackTop(block.col, null, block.y); if (nextY <= top) { block.y = top; block.state = STATE_STILL; block.vy = 0; block.manualPhase = null; block.flame = false; this.startBounce(block); } else { var downNext = Math.min(nextY, this.height - 1); if (this.resolveManualCollisions(block, block.y, downNext)) { continue; } block.y = downNext; } } } }; /** * If the manual throw (or its path this step) hits falling blocks, merge * them into a flying cluster with mass-weighted velocity, the same rule * as two flying clusters colliding (t1108). Returns true if merged. */ GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY) { if (!manual || manual.state !== STATE_MANUAL) { return false; } var hits = this.fallingHitsOnManualPath(manual, oldY, newY); if (!hits.length) { return false; } this.mergeManualWithFalling(manual, hits); return true; }; GameCore.prototype.manualInColumnHit = function (falling, oldY, newY) { var lo = Math.min(oldY, newY); var hi = Math.max(oldY, newY) + 1; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === falling || other.col !== falling.col) { continue; } if (other.state !== STATE_MANUAL) { continue; } if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9) { return other; } } return null; }; GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY) { var lo = Math.min(oldY, newY); var hi = Math.max(oldY, newY) + 1; var hits = []; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === manual || other.col !== manual.col) { continue; } if (other.state !== STATE_FALLING) { continue; } if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9) { hits.push(other); } } if (!hits.length) { return hits; } return this.contiguousFallingInColumn(manual.col, manual, hits); }; /** * Every falling block in `col` that overlaps `anchor` or a hit already * in `seed`, plus a contiguous falling stack sitting on them. */ GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed) { var falling = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING) { falling.push(this.blocks[i]); } } falling.sort(function (a, b) { return a.y - b.y; }); var include = Object.create(null); var queue = []; function enqueue (b) { if (!b || include[b.id]) { return; } include[b.id] = true; queue.push(b); } if (seed) { for (var s = 0; s < seed.length; s++) { enqueue(seed[s]); } } // Also include falling that already overlap the anchor. if (anchor) { for (var i = 0; i < falling.length; i++) { if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9) { enqueue(falling[i]); } } } for (var q = 0; q < queue.length; q++) { var a = queue[q]; for (var i = 0; i < falling.length; i++) { var b = falling[i]; if (include[b.id]) { continue; } if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9) { enqueue(b); } } } var out = []; for (var i = 0; i < falling.length; i++) { if (include[falling[i].id]) { out.push(falling[i]); } } return out; }; /** * Merge a thrown (manual) block with falling blocks into one flying * cluster. Velocity, deceleration and jumpHeight are the mass-weighted * averages by block count, identical to mergeClusterGroup. The thrown * block stops being manual and the group follows normal cluster physics. * fromManual marks the cluster so later falling cargo also averages in. */ GameCore.prototype.mergeManualWithFalling = function (manual, fallingList) { if (!manual || manual.state !== STATE_MANUAL) { return null; } var blocks = [manual]; for (var i = 0; i < fallingList.length; i++) { if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0) { blocks.push(fallingList[i]); } } if (blocks.length < 2) { return null; } var n = blocks.length; var vySum = 0; var decelSum = 0; var hSum = 0; for (var i = 0; i < n; i++) { var b = blocks[i]; vySum += b.vy; if (b === manual) { decelSum += manual.manualDecel || 0; hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y); } } var cluster = { id: this.nextClusterId++, jumpHeight: hSum / n, vy: vySum / n, decel: decelSum / n, phase: (vySum / n) > 1e-10 ? 'up' : 'down', fromManual: true }; this.clusters[cluster.id] = cluster; for (var i = 0; i < n; i++) { var b = blocks[i]; b.clusterId = cluster.id; b.state = STATE_FLYING; b.vy = cluster.vy; b.flame = b.color === COLOR_GRAY; b.manualPhase = null; b.manualTarget = null; b.manualDecel = 0; b.manualJumpHeight = 0; b.pushedClusters = null; b.settleTime = 0; } if (this.drag && this.drag.blockId === manual.id) { this.drag = null; } this.prepareClusterBody(cluster); this.checkChainRelaunch(cluster); return cluster; }; /** Safety net: any remaining manual/falling overlaps after the substep. */ GameCore.prototype.mergeAnyManualFallingOverlaps = function () { var manuals = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].state === STATE_MANUAL) { manuals.push(this.blocks[i]); } } for (var m = 0; m < manuals.length; m++) { var manual = manuals[m]; if (manual.state !== STATE_MANUAL) { continue; } var hits = this.contiguousFallingInColumn(manual.col, manual); if (hits.length) { this.mergeManualWithFalling(manual, hits); } } }; /** * Resolve collisions of a thrown (manual) block along [oldY, nextY]. * Falling blocks merge (t1108). A flying cluster is pushed one cell up * in the hit column and the shot attaches at the bottom (t1111). * Another thrown block is promoted to a 1-block cluster and then the * same attach-at-bottom rule applies. Returns true if `manual` is no * longer in the MANUAL state. */ GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY) { if (!manual || manual.state !== STATE_MANUAL) { return true; } var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY); if (fallingHits.length) { this.mergeManualWithFalling(manual, fallingHits); return manual.state !== STATE_MANUAL; } var flyer = this.flyingHitOnManualPath(manual, oldY, nextY); if (flyer) { var cluster = this.clusters[flyer.clusterId]; if (cluster && cluster.phase !== 'landed') { if (nextY + 1e-12 < oldY) { this.attachToFlyingCluster(manual, flyer); } else { this.attachShotUnderCluster(manual, cluster, manual.col); } return manual.state !== STATE_MANUAL; } } var other = this.manualHitOnManualPath(manual, oldY, nextY); if (other) { var host = this.promoteManualToCluster(other); if (host) { if (nextY + 1e-12 < oldY) { this.attachToFlyingCluster(manual, other); } else { this.attachShotUnderCluster(manual, host, manual.col); } return manual.state !== STATE_MANUAL; } } return false; }; /** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */ GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY) { var lo = Math.min(oldY, nextY); var hi = Math.max(oldY, nextY) + 1; var best = null; var bestY = Infinity; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === manual || other.col !== manual.col) { continue; } if (other.state !== STATE_FLYING || other.clusterId == null) { continue; } var cluster = this.clusters[other.clusterId]; if (!cluster || cluster.phase === 'landed') { continue; } var o0 = (other._prevY != null) ? other._prevY : other.y; var o1 = other.y; var oLo = Math.min(o0, o1); var oHi = Math.max(o0, o1) + 1; if (lo < oHi - 1e-9 && oLo < hi - 1e-9) { if (other.y < bestY) { bestY = other.y; best = other; } } } return best; }; /** Another thrown block in the same column on the path (prefer the lower). */ GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY) { var lo = Math.min(oldY, nextY); var hi = Math.max(oldY, nextY) + 1; var best = null; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === manual || other.col !== manual.col) { continue; } if (other.state !== STATE_MANUAL) { continue; } var o0 = (other._prevY != null) ? other._prevY : other.y; var o1 = other.y; var oLo = Math.min(o0, o1); var oHi = Math.max(o0, o1) + 1; if (lo < oHi - 1e-9 && oLo < hi - 1e-9) { if (!best || other.y < best.y) { best = other; } } } return best; }; /** * t1111: push every member of `cluster` in `col` up by one cell, then * attach `manual` at the bottom of that column, grid-aligned, as part * of the cluster. The cluster keeps its velocity; the shot takes it. * Other columns are untouched. Same rule for every successive shot. */ GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col) { if (!manual || !cluster || !this.clusters[cluster.id]) { return false; } if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id) { // Already belonging elsewhere: leave first. if (manual.clusterId != null) { this.leaveCluster(manual); } } this.prepareClusterBody(cluster); var members = this.clusterMembers(cluster.id); var minOff = null; for (var i = 0; i < members.length; i++) { if (members[i].col !== col) { continue; } if (minOff == null || members[i].clusterOffset < minOff) { minOff = members[i].clusterOffset; } } if (minOff == null) { minOff = 0; } else { for (var i = 0; i < members.length; i++) { if (members[i].col === col) { members[i].clusterOffset += 1; } } } if (this.drag && this.drag.blockId === manual.id) { this.drag = null; } manual.clusterId = cluster.id; manual.clusterOffset = minOff; manual.state = STATE_FLYING; manual.flame = manual.color === COLOR_GRAY; manual.settleTime = 0; manual.manualPhase = null; manual.manualTarget = null; manual.manualDecel = 0; manual.manualJumpHeight = 0; manual.pushedClusters = null; this.syncClusterMembers(cluster); this.cullOffTop(); if (this.clusters[cluster.id]) { this.checkChainRelaunch(cluster); } return true; }; /** * Turn a lone thrown block into a 1-block flying cluster so a later * shot can use the t1111 attach-at-bottom rule. A single throw stays * MANUAL (and is capped at the top of the field) until it collides. */ GameCore.prototype.promoteManualToCluster = function (manual) { if (!manual) { return null; } if (manual.state === STATE_FLYING && manual.clusterId != null) { var existing = this.clusters[manual.clusterId]; if (existing && existing.phase !== 'landed') { return existing; } } if (manual.state !== STATE_MANUAL) { return null; } var height = manual.manualJumpHeight != null ? manual.manualJumpHeight : Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y); var cluster = { id: this.nextClusterId++, jumpHeight: height, vy: manual.vy, decel: manual.manualDecel || 0, phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up', fromManual: true, anchorY: manual.y }; this.clusters[cluster.id] = cluster; manual.state = STATE_FLYING; manual.clusterId = cluster.id; manual.clusterOffset = 0; manual.flame = manual.color === COLOR_GRAY; manual.settleTime = 0; manual.manualPhase = null; manual.manualTarget = null; manual.manualDecel = 0; manual.manualJumpHeight = 0; manual.pushedClusters = null; this.syncClusterMembers(cluster); return cluster; }; /** Kept for older tests / call sites: push a cluster column by one cell. */ GameCore.prototype.checkManualPush = function (manual, oldY, nextY) { return this.resolveManualCollisions(manual, oldY, nextY); }; /** * Push every flying block of the cluster that sits in `col` one tile up. * Other columns stay put (they remain linked). Then look for a new * same-color line of 3+ in the flying cluster; if there is one, those * blocks turn gray, join the link, and the whole cluster re-launches * with the same jump height from its current position. */ GameCore.prototype.pushClusterColumn = function (clusterId, col) { var cluster = this.clusters[clusterId]; if (!cluster) { return false; } var members = this.clusterMembers(clusterId); for (var i = 0; i < members.length; i++) { if (members[i].col === col) { members[i].y += 1; } } this.cullOffTop(); if (!this.clusters[clusterId]) { return true; } this.checkChainRelaunch(cluster); return true; }; /** * After a cargo attach or a cluster merge (or any other mid-air state * change), turn spontaneous lines of 3+ into rockets and give the whole * already-flying cluster an extra launch from its current position — * the same re-launch as a player push that completes a row. */ GameCore.prototype.resolveFlyingMatches = function () { var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster || cluster.phase === 'landed') { continue; } this.checkChainRelaunch(cluster); } }; GameCore.prototype.checkChainRelaunch = function (cluster) { if (!this.clusters[cluster.id]) { return; } var lines = this.findFlyingMatchLines(cluster.id); if (!lines.length) { return; } var newly = []; var seen = Object.create(null); for (var i = 0; i < lines.length; i++) { for (var j = 0; j < lines[i].blocks.length; j++) { var block = lines[i].blocks[j]; if (seen[block.id]) { continue; } seen[block.id] = true; newly.push(block); } } for (var i = 0; i < newly.length; i++) { var block = newly[i]; block.color = COLOR_GRAY; block.flame = true; block.clusterId = cluster.id; block.state = STATE_FLYING; } this.relaunchCluster(cluster, cluster.jumpHeight); }; GameCore.prototype.relaunchCluster = function (cluster, height) { cluster.jumpHeight = height; cluster.vy = PlanetMod.launchVelocity(this.planet, height); cluster.decel = PlanetMod.launchDeceleration(this.planet, height); cluster.phase = 'up'; var members = this.clusterMembers(cluster.id); for (var i = 0; i < members.length; i++) { members[i].vy = cluster.vy; members[i].state = STATE_FLYING; if (members[i].color === COLOR_GRAY) { members[i].flame = true; } } }; GameCore.prototype.startManualLaunch = function (block) { var target = this.height - 1; var height = Math.max(0.05, target - block.y); this.leaveCluster(block); block.state = STATE_MANUAL; block.pushedClusters = Object.create(null); block.manualTarget = target; block.manualPhase = 'up'; block.manualJumpHeight = height; block.vy = PlanetMod.launchVelocity(this.planet, height); block.manualDecel = PlanetMod.launchDeceleration(this.planet, height); block.flame = false; if (this.drag && this.drag.blockId === block.id) { this.drag = null; } }; GameCore.prototype.cullOffTop = function () { var gone = []; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.state === STATE_MANUAL) { if (block.y > this.height - 1) { block.y = this.height - 1; } continue; } if (block.y >= this.height - 1e-9) { gone.push(block); } } for (var i = 0; i < gone.length; i++) { var block = gone[i]; this.outgoingShots.push({ id: block.id, color: block.color, col: block.col, y: block.y }); this.score += 1; this.removeBlock(block); } }; GameCore.prototype.consumeOutgoingShots = function () { var shots = this.outgoingShots; this.outgoingShots = []; return shots; }; /** * A compact field picture for the multiplayer snapshot (miniatures). * Includes every block's col, y, color, state and flame. */ GameCore.prototype.fieldSnapshot = function () { var blocks = []; for (var i = 0; i < this.blocks.length; i++) { var b = this.blocks[i]; blocks.push({ id: b.id, col: b.col, y: Math.round(b.y * 1000) / 1000, color: b.color, state: b.state, flame: !!b.flame }); } return { score: this.score, state: this.state, width: this.width, height: this.height, locked: this.lockedColumnCount(), blocks: blocks }; }; /** * Incoming garbage from another player: a dark-grey block that falls * normally from the top of an open column. After landing it uses the * usual 3s settle and then a random colour (landFallingBlock). * `col` is optional; a random eligible column is used otherwise. * Returns the new block, or null if every column is locked or full. */ /** * Open columns a garbage block can fall into (not locked, not full). */ GameCore.prototype.eligibleGarbageColumns = function () { var eligible = []; for (var c = 0; c < this.width; c++) { if (this.isColumnLocked(c)) { continue; } if (this.groundedCount(c) >= this.height) { continue; } eligible.push(c); } return eligible; }; /** * Choose a garbage column. If `preferred` is still open, it wins; * otherwise a random eligible column (t1126). Returns null if none. */ GameCore.prototype.pickGarbageColumn = function (preferred) { var eligible = this.eligibleGarbageColumns(); if (!eligible.length) { return null; } if (preferred != null && isFinite(preferred)) { var want = preferred | 0; for (var i = 0; i < eligible.length; i++) { if (eligible[i] === want) { return want; } } } return eligible[Math.floor(this.rng() * eligible.length) % eligible.length]; }; GameCore.prototype.ingestGarbage = function (col) { if (this.state !== 'playing') { return null; } var chosen = this.pickGarbageColumn(col); if (chosen == null) { return null; } var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING); block.vy = -this.planet.fallSpeed; block.flame = false; return block; }; GameCore.prototype.advanceSettle = function (dt) { for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.state !== STATE_SETTLING) { continue; } var inLanded = block.clusterId != null && this.clusters[block.clusterId] && this.clusters[block.clusterId].phase === 'landed'; if (block.color === COLOR_GRAY) { block.settleTime += dt; if (block.settleTime >= this.settleTime) { block.color = this.randomColor(); block.settleTime = 0; block.flame = false; if (inLanded) { // Stay in the rigid group; releaseLandedCluster runs below. block.state = STATE_SETTLING; } else { this.leaveCluster(block); this.clearFlightState(block); block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING; } } } else if (!inLanded) { // Coloured settling that is not in a landed cluster (shouldn't // normally happen): just become still or fall, from rest. this.leaveCluster(block); this.clearFlightState(block); block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING; } } var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster || cluster.phase !== 'landed') { continue; } var members = this.clusterMembers(cluster.id); var greySettling = false; for (var i = 0; i < members.length; i++) { if (members[i].color === COLOR_GRAY && members[i].state === STATE_SETTLING) { greySettling = true; } } if (!greySettling) { this.releaseLandedCluster(cluster); } } }; GameCore.prototype.findMatchLines = function () { var candidates = []; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; // Coloured cargo in a just-landed cluster (SETTLING) can match // with already-resting blocks immediately (t1110). Greys have no // colour and wait until they recolor; after release they are STILL. if ((block.state === STATE_STILL || block.state === STATE_SETTLING) && block.color >= 0) { candidates.push(block); } } return this.collectLines(candidates, true); }; GameCore.prototype.findFlyingMatchLines = function (clusterId) { var candidates = []; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.clusterId === clusterId && block.color >= 0 && (block.state === STATE_FLYING)) { candidates.push(block); } } return this.collectLines(candidates, false); }; GameCore.prototype.collectLines = function (candidates, snapInteger) { var lines = []; if (!candidates.length) { return lines; } var byRow = Object.create(null); for (var i = 0; i < candidates.length; i++) { var block = candidates[i]; var row = Math.round(block.y); if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5)) { continue; } if (!byRow[row]) { byRow[row] = []; } byRow[row].push(block); } var rows = Object.keys(byRow); for (var r = 0; r < rows.length; r++) { var list = byRow[rows[r]]; list.sort(function (a, b) { return a.col - b.col; }); this.pushRuns(lines, list, false, function (a, b) { return a.color === b.color && a.col === b.col - 1 && a.color >= 0; }); } var byCol = Object.create(null); for (var i = 0; i < candidates.length; i++) { var block = candidates[i]; if (!byCol[block.col]) { byCol[block.col] = []; } byCol[block.col].push(block); } var cols = Object.keys(byCol); for (var c = 0; c < cols.length; c++) { var list = byCol[cols[c]]; list.sort(function (a, b) { return a.y - b.y; }); this.pushRuns(lines, list, true, function (a, b) { return a.color === b.color && a.color >= 0 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS; }); } return lines; }; GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent) { var start = 0; for (var i = 1; i <= list.length; i++) { var same = i < list.length && adjacent(list[i - 1], list[i]); if (!same) { var length = i - start; if (length >= 3) { lines.push({ blocks: list.slice(start, i), length: length, vertical: vertical }); } start = i; } } }; GameCore.prototype.resolveMatches = function () { if (this.state !== 'playing' || this.drag) { return []; } var lines = this.findMatchLines(); if (!lines.length) { this.finishLandingChains([]); return []; } var uf = new UnionFind(); var blockById = Object.create(null); for (var i = 0; i < lines.length; i++) { var line = lines[i]; for (var j = 0; j < line.blocks.length; j++) { uf.add(line.blocks[j].id); blockById[line.blocks[j].id] = line.blocks[j]; if (j > 0) { uf.union(line.blocks[0].id, line.blocks[j].id); } } } var matched = []; var seen = Object.create(null); for (var id in blockById) { if (!seen[id]) { seen[id] = true; matched.push(blockById[id]); } } for (var i = 0; i < matched.length; i++) { for (var j = i + 1; j < matched.length; j++) { if (matched[i].col === matched[j].col) { uf.union(matched[i].id, matched[j].id); } } } var groups = Object.create(null); for (var i = 0; i < matched.length; i++) { var root = uf.find(matched[i].id); if (!groups[root]) { groups[root] = []; } groups[root].push(matched[i]); } var launched = []; for (var root in groups) { var group = groups[root]; var height = 0; for (var i = 0; i < lines.length; i++) { var line = lines[i]; var overlaps = false; for (var j = 0; j < line.blocks.length; j++) { for (var k = 0; k < group.length; k++) { if (line.blocks[j].id === group[k].id) { overlaps = true; } } } if (overlaps) { var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical); if (h > height) { height = h; } } } var chain = this.landingChainFor(group); var bonusMul = 1 + LANDING_CHAIN_BONUS * chain; height *= bonusMul; this.launchCluster(group, height, { landingChain: chain }); launched.push({ blocks: group, jumpHeight: height, landingChain: chain, chainBonus: bonusMul }); } this.finishLandingChains(launched); this.updateChainIndicator(launched); return launched; }; /** * Gray the matched blocks, take everything sitting on top of them in * those columns, link them, and launch with jump height `height`. */ GameCore.prototype.launchCluster = function (matchedBlocks, height, opts) { opts = opts || {}; var lowestInCol = Object.create(null); var matchedIds = Object.create(null); for (var i = 0; i < matchedBlocks.length; i++) { var block = matchedBlocks[i]; matchedIds[block.id] = true; if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col]) { lowestInCol[block.col] = block.y; } } var clusterId = this.nextClusterId++; var cluster = { id: clusterId, jumpHeight: height, vy: PlanetMod.launchVelocity(this.planet, height), decel: PlanetMod.launchDeceleration(this.planet, height), phase: 'up', landingChain: opts.landingChain || 0, landedPending: false }; this.clusters[clusterId] = cluster; var riders = []; var cols = Object.keys(lowestInCol); for (var c = 0; c < cols.length; c++) { var col = +cols[c]; var lowest = lowestInCol[col]; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { var block = list[i]; if (!this.isGrounded(block) && block.state !== STATE_STILL) { if (block.state !== STATE_SETTLING) { continue; } } if (block.y + ALIGN_EPS >= lowest) { riders.push(block); } } } for (var i = 0; i < riders.length; i++) { var block = riders[i]; var isMatch = !!matchedIds[block.id]; if (isMatch || block.color === COLOR_GRAY) { block.color = COLOR_GRAY; block.flame = true; } else { block.flame = false; } block.state = STATE_FLYING; block.clusterId = clusterId; block.vy = cluster.vy; block.settleTime = 0; } this.prepareClusterBody(cluster); return cluster; }; GameCore.prototype.checkLocks = function () { for (var col = 0; col < this.width; col++) { if (this.isColumnLocked(col)) { continue; } if (this.groundedCount(col) < this.height) { continue; } // Must fill the column from floor to top: 13 grounded blocks at y 0..12. var filled = true; for (var row = 0; row < this.height; row++) { var block = this.blockAt(col, row); if (!block || !this.isGrounded(block)) { filled = false; break; } } if (!filled) { continue; } var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { var block = list[i]; if (!this.isGrounded(block)) { continue; } block.state = STATE_LOCKED; block.color = COLOR_GRAY; block.flame = false; block.vy = 0; block.settleTime = 0; if (block.clusterId != null) { this.leaveCluster(block); } } } }; GameCore.prototype.checkGameOver = function () { if (this.state !== 'playing') { return; } for (var col = 0; col < this.width; col++) { if (!this.isColumnLocked(col)) { return; } } this.state = 'gameover'; this.gameOverTime = 0; this.drag = null; }; /* ---------- dragging -------------------------------------------------- */ GameCore.prototype.beginDrag = function (col, y) { if (this.state !== 'playing') { return false; } var block = this.snapDragBlock(col, y); if (!block) { return false; } var top = this.columnStackTopRow(block.col); var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS; this.drag = { blockId: block.id, pointerY: y, startY: y, accum: 0, launchIntent: false, startedAsTop: startedAsTop }; return true; }; /** * Instant grab, cell-based (t1109). The press is mapped to the grid cell * floor(col), floor(y); any press inside that cell — corners, padding, * gaps between sprites, a visually tweened or bouncing sprite — grabs * the block that occupies it. This uses simulation cells, not the drawn * sprite bounds. If no block sits in that cell (mid-animation, a block * whose y is off the integer), fall back to the nearest grabbable block * in the same column within SNAP_Y (about half a tile). A small * horizontal slop still consults a neighbouring column when the press * is near the edge and the primary cell is empty. */ GameCore.prototype.snapDragBlock = function (col, y) { var raw = col; var c0 = Math.floor(raw + 1e-9); var row = Math.floor(y + 1e-9); var frac = raw - c0; if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0)) { var exact = this.draggableInCell(c0, row); if (exact) { return exact; } var near = this.nearestDraggableInColumn(c0, y, SNAP_Y); if (near) { return near; } } // Primary cell empty: allow a small horizontal slop into a neighbour. var neighbours = []; if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0) { neighbours.push(c0 - 1); } if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width) { neighbours.push(c0 + 1); } var best = null; var bestDist = Infinity; for (var n = 0; n < neighbours.length; n++) { var cc = neighbours[n]; if (!this.columnAllowsDrag(cc)) { continue; } var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y); if (!hit) { continue; } var dist = this.pointerDistToBlock(hit, raw, y); if (dist < bestDist) { bestDist = dist; best = hit; } } return best; }; /** The draggable block that occupies grid cell (col, row), if any. */ GameCore.prototype.draggableInCell = function (col, row) { var best = null; var bestOverlap = 0; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { var block = list[i]; if (!this.isDraggableBlock(block)) { continue; } var lo = Math.max(block.y, row); var hi = Math.min(block.y + 1, row + 1); var overlap = hi - lo; if (overlap > bestOverlap + 1e-12) { bestOverlap = overlap; best = block; } } if (best && bestOverlap > 1e-9) { return best; } return null; }; /** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */ GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist) { var best = null; var bestDist = Infinity; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { var block = list[i]; if (!this.isDraggableBlock(block)) { continue; } var dist = this.pointerDistToBlock(block, col + 0.5, y); if (dist < bestDist) { bestDist = dist; best = block; } } if (!best || bestDist > maxDist) { return null; } return best; }; GameCore.prototype.pointerDistToBlock = function (block, col, y) { var dx; if (col >= block.col && col < block.col + 1) { dx = 0; } else if (col < block.col) { dx = block.col - col; } else { dx = col - (block.col + 1); } var dy; if (y >= block.y && y < block.y + 1) { dy = 0; } else if (y < block.y) { dy = block.y - y; } else { dy = y - (block.y + 1); } return Math.sqrt(dx * dx + dy * dy); }; GameCore.prototype.moveDrag = function (y) { if (!this.drag) { return; } var block = this.blockById(this.drag.blockId); if (!block || !this.isDraggableBlock(block)) { this.drag = null; return; } if (!this.columnAllowsDrag(block.col)) { this.drag = null; return; } this.drag.pointerY = y; // 1:1 tracking: the target row is the one under the pointer, clamped // to the still stack. Swap step by step with each neighbour, and stop // exactly there. When the pointer stops, nothing else moves. // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold // used to jump a full cell on a short pull, and one large event // could walk the entire column (the "jumps all the way" bug). var top = this.columnStackTopRow(block.col); var bottom = this.columnStackBottomRow(block.col); var target = Math.floor(y + 1e-12); if (bottom < 0) { bottom = 0; } if (target < bottom) { target = bottom; } if (target > top) { target = top; } this.swapToward(block, target); top = this.columnStackTopRow(block.col); var isTop = Math.abs(block.y - top) < ALIGN_EPS; if (this.drag.startedAsTop) { // Already the topmost block: pulling upward past its own position // (LAUNCH_PULL tiles above the press point) starts a manual jump. this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL); } else { // Started mid-stack: swap first, and only launch once the pointer // is pulled into the empty space above the (new) top. this.drag.launchIntent = isTop && (y > top + 1 + 0.25); } }; /** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */ GameCore.prototype.swapOne = function (block, dir) { var neighbor = this.blockAt(block.col, block.y + dir); if (neighbor && this.isGrounded(neighbor) && neighbor !== block) { this.swapBlocks(block, neighbor); return true; } return false; }; GameCore.prototype.endDrag = function () { if (!this.drag) { return; } var block = this.blockById(this.drag.blockId); var launch = this.drag.launchIntent; this.drag = null; if (launch && block && block.state === STATE_STILL) { this.startManualLaunch(block); } else { this.resolveMatches(); } }; GameCore.prototype.blockById = function (id) { for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].id === id) { return this.blocks[i]; } } return null; }; GameCore.prototype.columnStackTopRow = function (col) { var top = -1; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { if (this.isGrounded(list[i]) && list[i].y > top) { top = list[i].y; } } return top; }; GameCore.prototype.columnStackBottomRow = function (col) { var bottom = Infinity; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { if (this.isGrounded(list[i]) && list[i].y < bottom) { bottom = list[i].y; } } return bottom === Infinity ? 0 : bottom; }; GameCore.prototype.swapToward = function (block, targetY) { var guard = 0; while (guard++ < this.height + 2) { var current = block.y; if (targetY > current + 0.5) { var above = this.blockAt(block.col, current + 1); if (above && this.isGrounded(above) && above !== block) { this.swapBlocks(block, above); } else { break; } } else if (targetY < current - 0.5) { var below = this.blockAt(block.col, current - 1); if (below && this.isGrounded(below) && below !== block) { this.swapBlocks(block, below); } else { break; } } else { break; } } }; GameCore.prototype.swapBlocks = function (a, b) { var ay = a.y; var by = b.y; a.y = by; b.y = ay; this.transferLandedMembership(a, b); if (!this.swapEvents) { this.swapEvents = []; } this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col }); this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col }); }; GameCore.prototype.consumeSwapEvents = function () { var ev = this.swapEvents || []; this.swapEvents = []; return ev; }; /** * Highest landing-chain counter among just-landed members of this * match group, plus one. Returns 0 when the match did not come from * a cluster landing (player/bot swap, mid-air, etc.). */ GameCore.prototype.landingChainFor = function (group) { var maxChain = 0; var fromLanding = false; for (var i = 0; i < group.length; i++) { var block = group[i]; if (block.justLanded) { fromLanding = true; if ((block.landingChain || 0) > maxChain) { maxChain = block.landingChain || 0; } } if (block.clusterId != null) { var cluster = this.clusters[block.clusterId]; if (cluster && cluster.landedPending) { fromLanding = true; if ((cluster.landingChain || 0) > maxChain) { maxChain = cluster.landingChain || 0; } } } } if (!fromLanding) { return 0; } return maxChain + 1; }; /** * After resolveMatches: clear the landing-pending flag and reset the * chain on landings that did not make a match. A cluster that is still * settling (greys not yet recolored) keeps landedPending so a later * post-recolor match in this same landing still gets the bonus. */ GameCore.prototype.finishLandingChains = function (launched) { var launchedIds = Object.create(null); launched = launched || []; for (var i = 0; i < launched.length; i++) { var blocks = launched[i].blocks || []; for (var j = 0; j < blocks.length; j++) { launchedIds[blocks[j].id] = true; } } for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (!block.justLanded) { continue; } if (!launchedIds[block.id]) { block.landingChain = 0; } block.justLanded = false; } var ids = Object.keys(this.clusters); for (var c = 0; c < ids.length; c++) { var cluster = this.clusters[ids[c]]; if (!cluster || !cluster.landedPending) { continue; } var members = this.clusterMembers(cluster.id); var anyLaunched = false; var stillSettling = false; for (var i = 0; i < members.length; i++) { if (launchedIds[members[i].id]) { anyLaunched = true; } if (members[i].state === STATE_SETTLING) { stillSettling = true; } } if (anyLaunched) { cluster.landingChain = 0; cluster.landedPending = false; } else if (!stillSettling) { // Released leftovers or a fully-still landed group that // already had its match opportunity and missed it. cluster.landingChain = 0; cluster.landedPending = false; } // else: still settling, no match yet — keep landedPending. } }; GameCore.prototype.updateChainIndicator = function (launched) { var maxChain = 0; for (var i = 0; i < launched.length; i++) { var ch = launched[i].landingChain || 0; if (ch > maxChain) { maxChain = ch; } } if (maxChain >= 1) { this.lastChainIndicator = { chain: maxChain, bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100) }; return; } if (!this.hasActiveLandingChain()) { this.lastChainIndicator = null; } }; GameCore.prototype.hasActiveLandingChain = function () { var ids = Object.keys(this.clusters); for (var i = 0; i < ids.length; i++) { var cluster = this.clusters[ids[i]]; if (cluster && (cluster.landingChain || 0) >= 1 && cluster.phase !== 'landed') { return true; } } return false; }; /** * A landed cluster (grey rockets or linked cargo resting on the ground) * is a swappable part of the contiguous grounded stack. Flying, falling * and manual blocks are not. A locked column is not. */ GameCore.prototype.isDraggableBlock = function (block) { if (!block) { return false; } if (block.state === STATE_LOCKED || block.state === STATE_FLYING || block.state === STATE_FALLING || block.state === STATE_MANUAL) { return false; } if (block.clusterId != null) { var cluster = this.clusters[block.clusterId]; // Flying (rising / descending) clusters stay non-draggable. if (cluster && cluster.phase !== 'landed') { return false; } } return block.state === STATE_STILL || block.state === STATE_SETTLING; }; /** * The grounded contiguous stack in this column can be dragged, even if a * flying cluster or a falling spawn occupies the air above it. Only a * locked column is blocked as a whole. */ GameCore.prototype.columnAllowsDrag = function (col) { return !this.isColumnLocked(col); }; GameCore.prototype.landedClusterId = function (block) { if (!block || block.clusterId == null) { return null; } var cluster = this.clusters[block.clusterId]; if (!cluster || cluster.phase !== 'landed') { return null; } return block.clusterId; }; /** * After a swap: leaving a landed cluster clears membership; joining one * makes the block part of that rigid group. Same-cluster swaps only * exchange positions. See docs/ASSUMPTIONS.md (t1107). */ GameCore.prototype.transferLandedMembership = function (a, b) { var ca = this.landedClusterId(a); var cb = this.landedClusterId(b); if (ca === cb) { return; } // Join first so leaveCluster does not delete a cluster that still // has the incoming member. this.applyLandedMembership(b, ca); this.applyLandedMembership(a, cb); }; GameCore.prototype.applyLandedMembership = function (block, clusterId) { if (clusterId == null) { var wasGrey = block.color === COLOR_GRAY; var wasSettling = block.state === STATE_SETTLING; this.leaveCluster(block); if (wasGrey && wasSettling) { // Keep settling and recolor on its own, same remaining timer. block.state = STATE_SETTLING; } else if (wasSettling) { block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING; } return; } if (!this.clusters[clusterId]) { return; } block.clusterId = clusterId; block.flame = false; if (block.state === STATE_STILL || block.state === STATE_SETTLING) { block.state = STATE_SETTLING; } }; /** * Test helper: stepwise-swap the block at (col, fromRow) to toRow. * Returns the moved block, or null if the column does not allow a drag. */ GameCore.prototype.swapTo = function (col, fromRow, toRow) { if (!this.columnAllowsDrag(col)) { return null; } var block = this.blockAt(col, fromRow); if (!block) { return null; } this.swapToward(block, toRow); return block; }; /** * Test helper: a compact picture of grounded/falling/flying blocks. * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling, * L locked, f falling, m manual, . empty. Flying colored blocks use * their color with a marker in `flying`. */ GameCore.prototype.snapshot = function () { var grid = []; for (var r = 0; r < this.height; r++) { var row = []; for (var c = 0; c < this.width; c++) { row.push('.'); } grid.push(row); } var airborne = []; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; var ch; if (block.state === STATE_LOCKED) { ch = 'L'; } else if (block.color === COLOR_GRAY) { ch = 'g'; } else { ch = String(block.color); } if (this.isGrounded(block) || block.state === STATE_FALLING) { var row = Math.round(block.y); if (row >= 0 && row < this.height) { grid[row][block.col] = ch; } } else { airborne.push({ id: block.id, col: block.col, y: block.y, color: block.color, state: block.state, clusterId: block.clusterId, flame: block.flame, vy: block.vy }); } } var lines = []; for (var r = this.height - 1; r >= 0; r--) { lines.push(grid[r].join('')); } return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state }; }; var GameCoreAPI = { GameCore: GameCore, COLOR_GRAY: COLOR_GRAY, STATE_STILL: STATE_STILL, STATE_FALLING: STATE_FALLING, STATE_FLYING: STATE_FLYING, STATE_SETTLING: STATE_SETTLING, STATE_LOCKED: STATE_LOCKED, STATE_MANUAL: STATE_MANUAL }; if (typeof module !== 'undefined' && module.exports) { module.exports = GameCoreAPI; } else if (typeof globalThis !== 'undefined') { globalThis.GameCore = GameCore; globalThis.GameCoreAPI = GameCoreAPI; }