'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; // Grab a still block if the pointer is at most this far (tiles) from it. var SNAP_Y = 0.65; // Horizontal slop (tiles) for snapping to a neighbouring column on press. var HORIZONTAL_SLOP = 0.35; 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); } 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])); } 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.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; }; GameCore.prototype.stackTop = function (col, ignore) { 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 (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.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 () { 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; } }; 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; } var roof = flyer.y + 1; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === block || other.col !== block.col) { continue; } if (other.clusterId !== cluster.id) { continue; } if (other.y + 1 > roof) { roof = other.y + 1; } } block.y = roof; block.state = STATE_FLYING; block.clusterId = cluster.id; block.vy = cluster.vy; block.flame = false; block.settleTime = 0; 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.integrateFalling(step); this.integrateClusters(step); this.mergeFlyingClusters(); this.integrateManual(step); 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(); }; /** 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 flyer = this.highestFlyingBelow(block); if (flyer && nextY <= flyer.y + 1 + 1e-9) { if (this.attachToFlyingCluster(block, flyer)) { continue; } } var top = this.stackTop(block.col); 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 -fallSpeed * at planet.fallAccel, then stays at terminal fallSpeed. */ GameCore.prototype.advanceJump = function (body, dt) { 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 target = -this.planet.fallSpeed; var accel = this.planet.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; } var dy = this.advanceJump(cluster, dt); for (var i = 0; i < members.length; i++) { members[i].y += dy; members[i].vy = cluster.vy; } this.catchFallingOntoCluster(cluster, members); if (cluster.phase === 'down') { 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 (ma[i].y < mb[j].y + 1 - 1e-9 && mb[j].y < ma[i].y + 1 - 1e-9) { return true; } } } return false; }; 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'; 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.packClusterOverlaps(keep); if (keep.phase === 'down') { 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; } } } }; 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; }); 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. for (var i = 0; i < members.length; i++) { members[i].y += shift; } this.landCluster(cluster, members); }; /** * 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; }; /** * 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; } 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; this.checkManualPush(block, oldY, Math.min(nextY, block.manualTarget)); block.vy = proxy.vy; block.manualPhase = proxy.phase; 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); if (nextY <= top) { block.y = top; block.state = STATE_STILL; block.vy = 0; block.manualPhase = null; block.flame = false; this.startBounce(block); } else { block.y = Math.min(nextY, this.height - 1); } } } }; GameCore.prototype.checkManualPush = function (manual, oldY, nextY) { if (!manual.pushedClusters) { manual.pushedClusters = Object.create(null); } var manualTopOld = oldY + 1; var manualTopNew = nextY + 1; var low = Math.min(oldY, nextY); var high = Math.max(oldY, nextY) + 1; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === manual) { continue; } if (other.col !== manual.col) { continue; } if (other.state !== STATE_FLYING || other.clusterId == null) { continue; } if (manual.pushedClusters[other.clusterId]) { continue; } var otherBot = other.y; var otherTop = other.y + 1; var overlapping = otherBot < high + 1e-9 && otherTop > low - 1e-9; var crossing = manualTopOld <= otherBot + 1e-9 && manualTopNew >= otherBot - 1e-9; if (overlapping || crossing) { if (this.pushClusterColumn(other.clusterId, manual.col)) { manual.pushedClusters[other.clusterId] = true; return; } } } }; /** * 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; }; 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); block.state = STATE_MANUAL; block.pushedClusters = Object.create(null); block.manualTarget = target; block.manualPhase = 'up'; 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. */ GameCore.prototype.ingestGarbage = function (col) { if (this.state !== 'playing') { return null; } var chosen = null; if (col != null && col >= 0 && col < this.width && !this.isColumnLocked(col) && this.groundedCount(col) < this.height) { chosen = col | 0; } else { 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); } if (!eligible.length) { return null; } chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length]; } 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]; if (block.state === STATE_STILL && 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) { 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; } } } this.launchCluster(group, height); launched.push({ blocks: group, jumpHeight: height }); } 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) { 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' }; 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; } 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: the nearest still, coloured block to (col, y), allowing * a small vertical miss and a horizontal slop into a neighbouring * column. `col` may be fractional (pointer x in tiles). No hold delay. */ GameCore.prototype.snapDragBlock = function (col, y) { var raw = col; var c0 = Math.floor(raw + 1e-9); var frac = raw - c0; var candidates = []; if (c0 >= 0 && c0 < this.width) { candidates.push(c0); } // Only consult a neighbour when the pointer is actually near the edge // (a whole-number col, as in unit tests, stays in that column). if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0) { candidates.push(c0 - 1); } if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width) { candidates.push(c0 + 1); } var best = null; var bestDist = Infinity; for (var c = 0; c < candidates.length; c++) { var cc = candidates[c]; if (!this.isColumnStill(cc)) { continue; } var list = this.blocksInColumn(cc); for (var i = 0; i < list.length; i++) { var block = list[i]; if (block.state !== STATE_STILL || block.color < 0) { continue; } var dist = this.pointerDistToBlock(block, raw, y); // Prefer the column the pointer is actually in on a tie. if (dist < bestDist - 1e-12 || (Math.abs(dist - bestDist) < 1e-12 && cc === c0)) { bestDist = dist; best = block; } } } if (!best || bestDist > SNAP_Y) { 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 || block.state !== STATE_STILL) { this.drag = null; return; } if (!this.isColumnStill(block.col)) { this.drag = null; return; } var dy = y - this.drag.pointerY; this.drag.pointerY = y; if (this.drag.accum == null) { this.drag.accum = 0; } this.drag.accum += dy; // One swap per tile of travel, triggered after a minimal SWAP_DISTANCE. // A single large move (fast swipe) walks every tile; none are skipped. var guard = 0; while (guard++ < this.height + 2 && (this.drag.accum >= SWAP_DISTANCE || this.drag.accum <= -SWAP_DISTANCE)) { var dir = this.drag.accum > 0 ? 1 : -1; if (!this.swapOne(block, dir)) { if (dir > 0) { this.drag.accum = Math.min(this.drag.accum, SWAP_DISTANCE - 1e-9); } else { this.drag.accum = Math.max(this.drag.accum, -(SWAP_DISTANCE - 1e-9)); } break; } this.drag.accum -= dir; // A short move (SWAP_DISTANCE < 1) leaves a negative leftover; // do not let that immediately swap back the other way. if ((dir > 0 && this.drag.accum < 0) || (dir < 0 && this.drag.accum > 0)) { this.drag.accum = 0; } if (!this.isColumnStill(block.col)) { this.drag = null; return; } } var 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.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 y = a.y; a.y = b.y; b.y = y; }; /** * Test helper: stepwise-swap the block at (col, fromRow) to toRow. * Returns the moved block, or null if the column is not still. */ GameCore.prototype.swapTo = function (col, fromRow, toRow) { if (!this.isColumnStill(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; }