/* * AUTO-GENERATED FILE — DO NOT EDIT BY HAND. * Built by src/build.sh from the sources in src/. */ /* * Start File: * /workspace/meteors/src/rng.js */ 'use strict'; /** * Seedable mulberry32 RNG, so the game core stays deterministic in tests * and (later) for multiplayer replays. */ function createRng (seed) { var a = (seed >>> 0) || 1; return function rng () { a |= 0; a = a + 0x6D2B79F5 | 0; var t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; }; } function pickIndex (rng, count) { var n = count | 0; if (n <= 0) { return 0; } return Math.floor(rng() * n) % n; } function pickFrom (rng, list) { if (!list || !list.length) { return undefined; } return list[pickIndex(rng, list.length)]; } var Rng = { create: createRng, pickIndex: pickIndex, pickFrom: pickFrom }; if (typeof module !== 'undefined' && module.exports) { module.exports = Rng; } else if (typeof globalThis !== 'undefined') { globalThis.Rng = Rng; } /* * End File: * /workspace/meteors/src/rng.js */ /* * Start File: * /workspace/meteors/src/planet.js */ 'use strict'; /** * Planet physics and visuals for Meteors. * * Stage 1 uses a single default planet. Stage 3 lets the player pick a * planet; the numbers and jump-height rules are already applied here so * that later planets only need new data, not new physics code. * * Gravity (jumpsToClear): 1 (easy, high jump) .. 4 (hard, short jump). * A horizontal match of 3 jumps FIELD_HEIGHT / jumpsToClear tiles — * at 1, one jump from the floor clears the field; at 4, you need four. * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall). * After a jump peaks, blocks float down at FIELD_HEIGHT / fallTime tiles/s. * Mass (riseTime): 0.5 s (hard, fast jump) .. 3 s (easy, slow jump). * Time to reach the apex, independent of jump height. * * Jump-height multipliers (never explained in the game): * A vertical match of 3 is 120 % of a horizontal row of 3. * Each extra block beyond 3 adds 5 %. * * Power is the average of the three difficulty axes (0 easy .. 1 hard) * and is shown as a percentage. Miss chance (stage 2) goes from 60 % at * power 0 to 5 % at power 1. */ var FIELD_WIDTH = 10; var FIELD_HEIGHT = 13; function clamp (value, lo, hi) { return Math.max(lo, Math.min(hi, value)); } function defaultColors () { return [ { id: 0, name: 'ember', hex: '#e85d3a', shape: 'triangle', image: 'images/block-ember.png' }, { id: 1, name: 'aqua', hex: '#3db8e8', shape: 'circle', image: 'images/block-aqua.png' }, { id: 2, name: 'leaf', hex: '#4cbf4c', shape: 'square', image: 'images/block-leaf.png' }, { id: 3, name: 'sun', hex: '#f0c53a', shape: 'diamond', image: 'images/block-sun.png' }, { id: 4, name: 'orchid', hex: '#c45ad4', shape: 'star', image: 'images/block-orchid.png' } ]; } function createPlanet (opts) { opts = opts || {}; var jumpsToClear = clamp(opts.jumpsToClear == null ? 2 : opts.jumpsToClear, 1, 4); var fallTime = clamp(opts.fallTime == null ? 3 : opts.fallTime, 1, 5); var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3); var colors = opts.colors || defaultColors(); var planet = { name: opts.name || 'Terra', people: opts.people || 'Terrans', jumpsToClear: jumpsToClear, fallTime: fallTime, riseTime: riseTime, colors: colors, baseJumpHeight: FIELD_HEIGHT / jumpsToClear, fallSpeed: FIELD_HEIGHT / fallTime, // Time to ease from vy=0 at the apex to terminal fallSpeed. // Shorter when air resistance is low (small fallTime). apexEaseTime: 0.15 * fallTime, fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime), // Visual landing bounce: faster at low air resistance. Stage-3 params. bounceDuration: 0.12 * fallTime, bounceSquash: 0.16 }; return planet; } function defaultPlanet () { return createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 }); } /** * Jump height in tiles for a match line. * @param {object} planet * @param {number} matchLength number of blocks in the line (>= 3) * @param {boolean} vertical true for a vertical line */ function jumpHeight (planet, matchLength, vertical) { var extra = Math.max(0, (matchLength | 0) - 3); var multiplier = (vertical ? 1.2 : 1.0) + 0.05 * extra; return planet.baseJumpHeight * multiplier; } /** Initial upward speed (tiles/s) so a jump of `height` peaks in riseTime. */ function launchVelocity (planet, height) { if (height <= 0) { return 0; } return (2 * height) / planet.riseTime; } /** Constant deceleration (tiles/s^2) paired with launchVelocity. */ function launchDeceleration (planet, height) { if (height <= 0) { return 0; } return (2 * height) / (planet.riseTime * planet.riseTime); } /** * Difficulty power in 0..1. Higher is harder (and, in stage 2, a lower * chance that a shot-off block misses the opponent). */ function power (planet) { var gravity = (planet.jumpsToClear - 1) / 3; var air = (5 - planet.fallTime) / 4; var mass = (3 - planet.riseTime) / 2.5; return (gravity + air + mass) / 3; } /** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */ function missChance (planet) { return 0.60 - 0.55 * power(planet); } /** * Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³), * launch force (N), and power as a percentage. The numbers do not have to * explain themselves. */ function displayValues (planet) { var gravity = 9.81 * planet.jumpsToClear / 2; var density = 0.25 + ((5 - planet.fallTime) / 4) * 1.60; var newtons = 40 + ((planet.riseTime - 0.5) / 2.5) * 160; return { gravity: gravity, density: density, newtons: newtons, power: Math.round(power(planet) * 100), missChance: missChance(planet) }; } var Planet = { FIELD_WIDTH: FIELD_WIDTH, FIELD_HEIGHT: FIELD_HEIGHT, COLOR_COUNT: 5, SETTLE_TIME: 3, SPAWN_INTERVAL: 1, JUMP_VERTICAL_BONUS: 1.2, JUMP_EXTRA_BLOCK: 0.05, createPlanet: createPlanet, defaultPlanet: defaultPlanet, defaultColors: defaultColors, jumpHeight: jumpHeight, launchVelocity: launchVelocity, launchDeceleration: launchDeceleration, power: power, missChance: missChance, displayValues: displayValues }; if (typeof module !== 'undefined' && module.exports) { module.exports = Planet; } else if (typeof globalThis !== 'undefined') { globalThis.Planet = Planet; } /* * End File: * /workspace/meteors/src/planet.js */ /* * Start File: * /workspace/meteors/src/easing.js */ 'use strict'; /** * Easing curves matching Qt QEasingCurve defaults (the same values Tim's * KWin Click Tween effect uses). Formulas and default parameters come from * Qt 6's QEasingCurve and https://easings.net/. * * Source of the click/release defaults: * /workspace/click-tween/settings.h (clickTime, releaseTime, easing names) * /workspace/click-tween/clicktween.cpp (press scale 0.8, release scale 1.0) * /workspace/click-tween/README.md */ /** Qt QEasingCurve default overshoot for InBack / OutBack / InOutBack. */ var BACK_OVERSHOOT = 1.70158; /** Qt QEasingCurve default period and amplitude for Elastic curves. */ var ELASTIC_PERIOD = 0.3; var ELASTIC_AMPLITUDE = 1.0; function clamp01 (t) { if (t <= 0) { return 0; } if (t >= 1) { return 1; } return t; } /** easeOutBack: overshoots the end value, then settles. Qt / easings.net. */ function easeOutBack (t) { t = clamp01(t); var c1 = BACK_OVERSHOOT; var c3 = c1 + 1; var u = t - 1; return 1 + c3 * u * u * u + c1 * u * u; } /** * easeOutElastic: decaying sine overshoot past the end value. * Qt default amplitude 1, period 0.3 (equivalent to easings.net). */ function easeOutElastic (t) { t = clamp01(t); if (t === 0 || t === 1) { return t; } var p = ELASTIC_PERIOD; var s = p / 4; return Math.pow(2, -10 * t) * Math.sin((t - s) * (2 * Math.PI) / p) + 1; } function tween (from, to, t, ease) { return from + (to - from) * ease(clamp01(t)); } /** * DEFAULT settings of Tim's KWin Click Tween * (git.timfalken.com/timfa/click-tween). * * Press: shrink to 80% in 150 ms with easeOutBack, stay at 80% while held. * Release: grow back to 100% in 720 ms with easeOutElastic. * Mid-animation release starts from the current scale, like QVariantAnimation. */ var CLICK_TWEEN = { pressScale: 0.8, releaseScale: 1.0, pressDuration: 0.150, releaseDuration: 0.720, pressEase: easeOutBack, releaseEase: easeOutElastic, backOvershoot: BACK_OVERSHOOT, elasticPeriod: ELASTIC_PERIOD, elasticAmplitude: ELASTIC_AMPLITUDE, source: 'click-tween settings.h + clicktween.cpp (Qt QEasingCurve defaults)' }; /** * Visual landing bounce, u in 0..1. Subtle squash with a slight stretch * on the other axis and a tiny upward rebound (in tiles, visual only). */ function bouncePose (u, squash) { if (u <= 0 || u >= 1) { return { sx: 1, sy: 1, dy: 0 }; } var wave = Math.sin(Math.PI * u); return { sx: 1 + squash * 0.6 * wave, sy: 1 - squash * wave, dy: 0.07 * wave * (1 - u) }; } var Easing = { BACK_OVERSHOOT: BACK_OVERSHOOT, ELASTIC_PERIOD: ELASTIC_PERIOD, ELASTIC_AMPLITUDE: ELASTIC_AMPLITUDE, easeOutBack: easeOutBack, easeOutElastic: easeOutElastic, tween: tween, CLICK_TWEEN: CLICK_TWEEN, clamp01: clamp01, bouncePose: bouncePose }; if (typeof module !== 'undefined' && module.exports) { module.exports = Easing; } else if (typeof globalThis !== 'undefined') { globalThis.Easing = Easing; } /* * End File: * /workspace/meteors/src/easing.js */ /* * Start File: * /workspace/meteors/src/gameCore.js */ '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; } 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.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++) { this.score += 1; this.removeBlock(gone[i]); } }; 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; } /* * End File: * /workspace/meteors/src/gameCore.js */ /* * Start File: * /workspace/meteors/src/main.js */ 'use strict'; /** * View and input for Meteors. The simulation lives in GameCore; this file * only draws it, scales it to the viewport, and translates pointer events * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view * that reuses the same core. */ var IMAGES = [ { name: 'ember', url: 'images/block-ember.png' }, { name: 'aqua', url: 'images/block-aqua.png' }, { name: 'leaf', url: 'images/block-leaf.png' }, { name: 'sun', url: 'images/block-sun.png' }, { name: 'orchid', url: 'images/block-orchid.png' }, { name: 'gray', url: 'images/block-gray.png' }, { name: 'locked', url: 'images/block-locked.png' }, { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 }, { name: 'cell', url: 'images/cell.png' }, { name: 'pixel', url: 'images/pixel.png' } ]; var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid']; var GAME_OVER_DELAY = 2; var game = new Game(); var app = { mode: 'menu', core: null, scene: null, manager: null, planet: null, lastScore: 0, tile: 48, fieldX: 0, fieldY: 0, fieldW: 0, fieldH: 0, hudH: 56, sprites: Object.create(null), flames: Object.create(null), cells: [], pointerId: null, gameOverShown: false, selectTween: null }; window.onload = function () { var play = document.getElementById('btn-play'); play.addEventListener('click', onPlay); play.addEventListener('pointerup', function (e) { // A touch-friendly path: some mobile browsers swallow the click // after a slightly sloppy tap. Ignore the following click. if (e.pointerType === 'touch' || e.pointerType === 'pen') { e.preventDefault(); onPlay(); } }); game.preloadImagesThenStart(IMAGES, function () { if (game.images.flame && game.images.flame.addAnimationCycle) { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); } }); }; function onPlay () { if (app.mode === 'playing') { return; } startPlay(); } function startPlay () { hideEl('menu'); hideEl('game-over'); showEl('hud'); app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet()); app.core = new GameCore(app.planet, Math.random); app.mode = 'playing'; app.gameOverShown = false; app.sprites = Object.create(null); app.flames = Object.create(null); app.cells = []; app.pointerId = null; app.selectTween = null; layout(); app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH); app.scene.backgroundColor = { r: 12, g: 16, b: 32 }; app.scene.renderBackground = true; game.loadScene(app.scene); buildCells(); app.manager = app.scene.addObject(makeManager()); bindPointer(app.scene.canvas); refreshHud(); } function returnToMenu () { unbindPointer(); if (app.scene) { app.scene.destroy(); app.scene = null; } app.manager = null; app.core = null; app.mode = 'menu'; app.sprites = Object.create(null); app.flames = Object.create(null); app.cells = []; app.selectTween = null; hideEl('hud'); hideEl('game-over'); showEl('menu'); var last = document.getElementById('last-score'); if (app.lastScore > 0) { last.hidden = false; last.querySelector('strong').textContent = String(app.lastScore); } } function buildCells () { if (!app.scene) { return; } var img = game.images.cell; for (var row = 0; row < 13; row++) { for (var col = 0; col < 10; col++) { var obj = new GameObject(0, 0, img, 0); placeTile(obj, col, row); obj.renderer.alpha = 0.9; app.scene.addObject(obj); app.cells.push(obj); } } } function placeTile (obj, col, y) { var t = app.tile; obj.transform.position.x = col * t + t / 2; obj.transform.position.y = app.fieldH - (y + 0.5) * t; obj.transform.size = { x: t, y: t }; } function layout () { var vw = window.innerWidth || 320; var vh = window.innerHeight || 480; var safeTop = 0; try { // env(safe-area) is a CSS thing; keep a conservative HUD height. safeTop = 0; } catch (e) { /* ignore */ } app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop); var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015)); var availW = Math.max(80, vw - margin * 2); var availH = Math.max(80, vh - app.hudH - margin); app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13))); app.fieldW = app.tile * 10; app.fieldH = app.tile * 13; app.fieldX = Math.floor((vw - app.fieldW) / 2); app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2); if (app.fieldY < app.hudH) { app.fieldY = app.hudH; } if (app.scene) { app.scene.position.x = app.fieldX; app.scene.position.y = app.fieldY; app.scene.size.x = app.fieldW; app.scene.size.y = app.fieldH; } } function spriteFor (block) { if (block.state === 'locked') { return game.images.locked; } if (block.color < 0) { return game.images.gray; } return game.images[COLOR_SPRITES[block.color]] || game.images.gray; } function syncSprites () { if (!app.core || !app.scene) { return; } var seen = Object.create(null); var blocks = app.core.blocks; for (var i = 0; i < blocks.length; i++) { var block = blocks[i]; seen[block.id] = true; var obj = app.sprites[block.id]; if (!obj) { obj = new GameObject(0, 0, spriteFor(block), 2); app.scene.addObject(obj); app.sprites[block.id] = obj; } obj.renderer.sprite = spriteFor(block); placeTile(obj, block.col, block.y); applyBlockVisual(obj, block); obj.renderer.visible = true; obj.renderer.alpha = 1; if (block.flame) { var flame = app.flames[block.id]; if (!flame) { flame = new GameObject(0, 0, game.images.flame, 1); flame.renderer.setAnimation('burn', 0, 0.08); app.scene.addObject(flame); app.flames[block.id] = flame; } flame.renderer.visible = true; var t = app.tile; flame.transform.position.x = block.col * t + t / 2; flame.transform.position.y = app.fieldH - block.y * t + t * 0.15; flame.transform.size = { x: t * 0.85, y: t * 0.85 }; } else if (app.flames[block.id]) { app.flames[block.id].renderer.visible = false; } } var ids = Object.keys(app.sprites); for (var i = 0; i < ids.length; i++) { if (!seen[ids[i]]) { app.sprites[ids[i]].destroy(); delete app.sprites[ids[i]]; if (app.flames[ids[i]]) { app.flames[ids[i]].destroy(); delete app.flames[ids[i]]; } } } } function applyBlockVisual (obj, block) { var t = app.tile; var sx = 1; var sy = 1; var dy = 0; if (block.bouncing && app.planet && app.planet.bounceDuration > 0 && typeof Easing !== 'undefined' && Easing.bouncePose) { var u = block.bounceAge / app.planet.bounceDuration; var pose = Easing.bouncePose(u, app.planet.bounceSquash); sx = pose.sx; sy = pose.sy; dy = pose.dy; } var sel = 1; var tw = app.selectTween; if (tw && tw.blockId === block.id && tw.phase !== 'idle') { sel = tw.scale; } obj.transform.size = { x: t * sx * sel, y: t * sy * sel }; if (dy) { obj.transform.position.y -= dy * t; } } function clickTween () { return (typeof Easing !== 'undefined' && Easing.CLICK_TWEEN) ? Easing.CLICK_TWEEN : null; } function startPressTween (blockId) { var c = clickTween(); if (!c) { return; } var from = (app.selectTween && app.selectTween.phase !== 'idle') ? app.selectTween.scale : 1; app.selectTween = { blockId: blockId, from: from, to: c.pressScale, t: 0, duration: c.pressDuration, ease: c.pressEase, scale: from, phase: 'press' }; } function startReleaseTween () { var c = clickTween(); var tw = app.selectTween; if (!c || !tw || tw.phase === 'idle') { return; } app.selectTween = { blockId: tw.blockId, from: tw.scale, to: c.releaseScale, t: 0, duration: c.releaseDuration, ease: c.releaseEase, scale: tw.scale, phase: 'release' }; } function updateSelectTween (dt) { var tw = app.selectTween; if (!tw || tw.phase === 'idle' || tw.phase === 'hold') { return; } tw.t += dt; var u = tw.duration > 0 ? tw.t / tw.duration : 1; if (u >= 1) { tw.scale = tw.to; tw.t = tw.duration; if (tw.phase === 'press') { tw.phase = 'hold'; } else { tw.phase = 'idle'; tw.scale = 1; tw.blockId = null; } return; } var ease = tw.ease || (typeof Easing !== 'undefined' && Easing.easeOutBack); tw.scale = ease ? Easing.tween(tw.from, tw.to, u, ease) : tw.from + (tw.to - tw.from) * u; } function refreshHud () { if (!app.core) { return; } document.getElementById('score').textContent = String(app.core.score); var planet = app.planet; document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people; var d = Planet.displayValues(planet); document.getElementById('planet-stats').textContent = 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) + ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%'; } function makeManager () { var obj = new GameObject(0, 0, game.images.pixel, 0); obj.renderer.visible = false; var base = obj.update.bind(obj); obj.update = function (dt) { base(dt); tickView(dt); }; return obj; } function tickView (dt) { if (app.mode !== 'playing' || !app.core) { return; } layout(); for (var i = 0; i < app.cells.length; i++) { var col = i % 10; var row = Math.floor(i / 10); placeTile(app.cells[i], col, row); } app.core.tick(dt); updateSelectTween(dt); syncSprites(); refreshHud(); if (app.core.state === 'gameover' && !app.gameOverShown) { app.gameOverShown = true; app.lastScore = app.core.score; document.getElementById('go-score').textContent = String(app.lastScore); showEl('game-over'); } if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY) { returnToMenu(); } } /* ---------- pointer input (mouse + touch) --------------------------- */ /* * Both mouse and touch use Pointer Events. After pointerdown we listen * on window, so a drag that leaves the canvas (needed to launch a * block at the top of a full column) still reaches moveDrag. We do * not treat lostpointercapture as the end of a drag: on some touch * browsers that fires mid-gesture and would cancel a launch. */ var boundCanvas = null; var windowListening = false; function addWindowPointer () { if (windowListening) { return; } window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false }); window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false }); window.addEventListener('pointercancel', onPointerUp, { capture: true, passive: false }); windowListening = true; } function removeWindowPointer () { if (!windowListening) { return; } window.removeEventListener('pointermove', onPointerMove, { capture: true }); window.removeEventListener('pointerup', onPointerUp, { capture: true }); window.removeEventListener('pointercancel', onPointerUp, { capture: true }); windowListening = false; } function bindPointer (canvas) { unbindPointer(); boundCanvas = canvas; canvas.addEventListener('pointerdown', onPointerDown, { passive: false }); canvas.style.touchAction = 'none'; canvas.style.cursor = 'pointer'; canvas.style.webkitUserSelect = 'none'; canvas.style.userSelect = 'none'; } function unbindPointer () { removeWindowPointer(); if (boundCanvas) { boundCanvas.removeEventListener('pointerdown', onPointerDown); } boundCanvas = null; app.pointerId = null; } function fieldFromEvent (e) { var canvas = app.scene && app.scene.canvas; if (!canvas) { return null; } var rect = canvas.getBoundingClientRect(); if (rect.width <= 0 || rect.height <= 0) { return null; } var x = (e.clientX - rect.left) * (canvas.width / rect.width); var y = (e.clientY - rect.top) * (canvas.height / rect.height); // Fractional column so beginDrag can snap across a nearby edge. var col = x / app.tile; var fieldY = (canvas.height - y) / app.tile; return { col: col, y: fieldY }; } function onPointerDown (e) { if (!app.core || app.core.state !== 'playing') { return; } if (app.pointerId != null) { return; } e.preventDefault(); app.pointerId = e.pointerId; try { boundCanvas.setPointerCapture(e.pointerId); } catch (err) { /* ignore */ } addWindowPointer(); var pos = fieldFromEvent(e); // Instant grab, no long-press or hold delay: the block is taken on // pointerdown and the click tween starts in the same moment. if (pos && app.core.beginDrag(pos.col, pos.y) && app.core.drag) { startPressTween(app.core.drag.blockId); } } function onPointerMove (e) { if (app.pointerId == null || e.pointerId !== app.pointerId) { return; } if (!app.core || !app.core.drag) { return; } e.preventDefault(); var pos = fieldFromEvent(e); if (pos) { app.core.moveDrag(pos.y); } } function onPointerUp (e) { if (app.pointerId == null) { return; } if (e && e.pointerId != null && e.pointerId !== app.pointerId) { return; } if (e) { e.preventDefault(); } app.pointerId = null; removeWindowPointer(); if (boundCanvas) { try { boundCanvas.releasePointerCapture(e && e.pointerId); } catch (err) { /* ignore */ } } startReleaseTween(); if (app.core) { app.core.endDrag(); } } function hideEl (id) { document.getElementById(id).hidden = true; } function showEl (id) { document.getElementById(id).hidden = false; } window.addEventListener('resize', function () { if (app.mode === 'playing') { layout(); } }); window.addEventListener('orientationchange', function () { setTimeout(function () { if (app.mode === 'playing') { layout(); } }, 120); }); /* * End File: * /workspace/meteors/src/main.js */