/* * AUTO-GENERATED FILE — DO NOT EDIT BY HAND. * Built by src/build.sh from the sources in src/. */ var PLANET_CATALOG = { "planets": [ { "id": "terra", "name": "Terra", "people": "Terrans", "jumpsToClear": 2, "fallTime": 3, "riseTime": 1.5, "colors": [ {"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"}, {"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"}, {"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"}, {"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"}, {"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"} ] }, { "id": "aurel", "name": "Aurel", "people": "Aurelians", "jumpsToClear": 1, "fallTime": 5, "riseTime": 3, "colors": [ {"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"}, {"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"}, {"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"}, {"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"}, {"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"} ] }, { "id": "cinder", "name": "Cinder", "people": "Cindari", "jumpsToClear": 4, "fallTime": 1, "riseTime": 0.5, "colors": [ {"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"}, {"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"}, {"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"}, {"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"}, {"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"} ] }, { "id": "lunara", "name": "Lunara", "people": "Lunarites", "jumpsToClear": 1, "fallTime": 2, "riseTime": 1.2, "colors": [ {"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"}, {"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"}, {"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"}, {"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"}, {"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"} ] }, { "id": "mire", "name": "Mire", "people": "Mirians", "jumpsToClear": 2, "fallTime": 5, "riseTime": 2.5, "colors": [ {"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"}, {"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"}, {"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"}, {"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"}, {"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"} ] }, { "id": "galeon", "name": "Galeon", "people": "Galeoni", "jumpsToClear": 3, "fallTime": 1, "riseTime": 1.8, "colors": [ {"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"}, {"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"}, {"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"}, {"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"}, {"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"} ] }, { "id": "obsid", "name": "Obsid", "people": "Obsidians", "jumpsToClear": 4, "fallTime": 3.5, "riseTime": 2.2, "colors": [ {"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"}, {"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"}, {"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"}, {"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"}, {"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"} ] }, { "id": "wisp", "name": "Wisp", "people": "Wisplings", "jumpsToClear": 2, "fallTime": 3.5, "riseTime": 0.5, "colors": [ {"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"}, {"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"}, {"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"}, {"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"}, {"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"} ] }, { "id": "thorn", "name": "Thorn", "people": "Thornfolk", "jumpsToClear": 3, "fallTime": 2, "riseTime": 1.0, "colors": [ {"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"}, {"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"}, {"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"}, {"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"}, {"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"} ] }, { "id": "zephyr", "name": "Zephyr", "people": "Zephyrites", "jumpsToClear": 1, "fallTime": 1.2, "riseTime": 2.8, "colors": [ {"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"}, {"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"}, {"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"}, {"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"}, {"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"} ] }, { "id": "frore", "name": "Frore", "people": "Frorians", "jumpsToClear": 3, "fallTime": 4.5, "riseTime": 0.8, "colors": [ {"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"}, {"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"}, {"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"}, {"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"}, {"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"} ] }, { "id": "forge", "name": "Forge", "people": "Forgelings", "jumpsToClear": 4, "fallTime": 2, "riseTime": 1.5, "colors": [ {"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"}, {"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"}, {"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"}, {"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"}, {"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"} ] } ] } ; /* * 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 JUMP_HEIGHT_SCALE * FIELD_HEIGHT * / jumpsToClear tiles (JUMP_HEIGHT_SCALE is 1.5 since t1119: the * minimum jump is 50% higher). At gravity 1 that is 19.5 tiles, so * one jump from the floor clears the 13-tile field with room to spare; * at 4 you still need more than one jump, but each is 50% taller. * Air (fallTime): 1 s (hard, fast fall) .. 5 s (easy, slow fall). * Spawn, unsupported and cargo blocks fall at FIELD_HEIGHT / fallTime * tiles/s. After a jump peaks, a flying cluster floats down at * DESCENT_SPEED_SCALE * that speed (0.5 since t1122 / t1124: only the * cluster float-down is halved). Relative differences between planets * (1 / fallTime) are unchanged. Upward launch is not affected. * 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; /** t1119: every match jump (the gravity-applied minimum and the * vertical / extra-block bonuses derived from it) is 50% higher. */ var JUMP_HEIGHT_SCALE = 1.5; /** t1122 / t1124: only a flying cluster's post-apex float-down * (terminal speed and the apex ease into it) is halved. Spawn fall, * unsupported / released singles and dropped cargo use the full * fallSpeed. Upward launch is unchanged. */ var DESCENT_SPEED_SCALE = 0.5; 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 = { id: opts.id || null, name: opts.name || 'Terra', people: opts.people || 'Terrans', jumpsToClear: jumpsToClear, fallTime: fallTime, riseTime: riseTime, colors: colors, baseJumpHeight: JUMP_HEIGHT_SCALE * FIELD_HEIGHT / jumpsToClear, // Single-block fall (spawn, unsupported, dropped cargo). fallSpeed: FIELD_HEIGHT / fallTime, // Time to ease from vy=0 at the apex to terminal speed. // Shorter when air resistance is low (small fallTime). apexEaseTime: 0.15 * fallTime, fallAccel: (FIELD_HEIGHT / fallTime) / (0.15 * fallTime), // t1122 / t1124: flying-cluster float-down only. Same ease // duration; accel scales with the halved terminal speed. clusterFallSpeed: DESCENT_SPEED_SCALE * FIELD_HEIGHT / fallTime, clusterFallAccel: (DESCENT_SPEED_SCALE * 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 loadCatalog () { if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets) { return PLANET_CATALOG; } if (typeof require !== 'undefined') { try { return require('../server/lib/planets.json'); } catch (e) {} } return { planets: [] }; } function planetFromData (data) { var planet = createPlanet({ name: data.name, people: data.people, jumpsToClear: data.jumpsToClear, fallTime: data.fallTime, riseTime: data.riseTime, colors: data.colors }); planet.id = data.id; return planet; } function allPlanets () { var raw = loadCatalog().planets || []; var out = []; for (var i = 0; i < raw.length; i++) { out.push(planetFromData(raw[i])); } if (out.length === 0) { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; } return out; } function planetById (id) { var all = allPlanets(); for (var i = 0; i < all.length; i++) { if (all[i].id === id) { return all[i]; } } return defaultPlanet(); } function defaultPlanet () { var all = allPlanets(); for (var i = 0; i < all.length; i++) { if (all[i].id === 'terra') { return all[i]; } } return all[0]; } function formatStats (planet) { var d = displayValues(planet); return 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) + ' F ' + Math.round(d.newtons) + ' N' + ' Power ' + d.power + '%'; } function spriteKey (planet, colorIndex) { var colors = planet && planet.colors; var c = colors && colors[colorIndex]; if (!c) { return 'gray'; } return (planet.id || 'planet') + '-' + (c.name || String(colorIndex)); } /** * 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; } /** Maximum miss chance, used by the gameplay formula and the displayed Power. */ var MAX_MISS_CHANCE = 0.60; var MIN_MISS_CHANCE = 0.05; /** Stage-2 miss chance, 0.60 at power 0 down to 0.05 at power 1. */ function missChance (planet) { return MAX_MISS_CHANCE - (MAX_MISS_CHANCE - MIN_MISS_CHANCE) * power(planet); } /** * Displayed Power, as a 0–100 percentage. This is the complement of the * miss chance against the maximum (60%): 0% miss → 100% Power, 60% miss * → 0% Power. The gameplay power() and missChance() formulas are unchanged. */ function displayPower (planet) { return Math.round((1 - missChance(planet) / MAX_MISS_CHANCE) * 100); } /** * Numeric HUD values: a gravity-like constant (m/s²), air density (kg/m³), * launch force (N), and displayed 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: displayPower(planet), missChance: missChance(planet) }; } var Planet = { FIELD_WIDTH: FIELD_WIDTH, FIELD_HEIGHT: FIELD_HEIGHT, JUMP_HEIGHT_SCALE: JUMP_HEIGHT_SCALE, DESCENT_SPEED_SCALE: DESCENT_SPEED_SCALE, 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, allPlanets: allPlanets, planetById: planetById, planetFromData: planetFromData, formatStats: formatStats, spriteKey: spriteKey, jumpHeight: jumpHeight, launchVelocity: launchVelocity, launchDeceleration: launchDeceleration, MAX_MISS_CHANCE: MAX_MISS_CHANCE, MIN_MISS_CHANCE: MIN_MISS_CHANCE, power: power, missChance: missChance, displayPower: displayPower, 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; } /** easeOutCubic: 1 − (1−t)³. Smooth, no overshoot (easings.net). */ function easeOutCubic (t) { t = clamp01(t); var u = 1 - t; return 1 - u * u * u; } function tween (from, to, t, ease) { return from + (to - from) * ease(clamp01(t)); } /** * Visual-only block swap tween (t1121). Game logic and the grid update * immediately; this only moves the displaced sprite. 100 ms sits in the * requested 80–120 ms range. */ var SWAP_TWEEN = { duration: 0.100, ease: easeOutCubic }; /** * 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, easeOutCubic: easeOutCubic, tween: tween, CLICK_TWEEN: CLICK_TWEEN, SWAP_TWEEN: SWAP_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; // Fallback snap (tiles) when the press cell is empty: nearest block in the column. var SNAP_Y = 0.5; // Horizontal slop (tiles) for snapping to a neighbouring column on press. var HORIZONTAL_SLOP = 0.35; /** t1120: additive jump bonus per landing-chain step. A landing that * immediately makes a match launches at (1 + 0.25 * chain) times the * usual height, with chain 1, 2, 3, … → ×1.25, ×1.50, ×1.75. */ var LANDING_CHAIN_BONUS = 0.25; /** t1123: a column pulses red at or above this many grounded rows * (10 of 13 is just over 70%). */ var COLUMN_WARN_ROWS = 10; function UnionFind () { this.parent = Object.create(null); } UnionFind.prototype.add = function (id) { if (this.parent[id] == null) { this.parent[id] = id; } }; UnionFind.prototype.find = function (id) { if (this.parent[id] !== id) { this.parent[id] = this.find(this.parent[id]); } return this.parent[id]; }; UnionFind.prototype.union = function (a, b) { this.add(a); this.add(b); var ra = this.find(a); var rb = this.find(b); if (ra !== rb) { this.parent[rb] = ra; } }; function GameCore (planet, rng) { this.planet = planet || PlanetMod.defaultPlanet(); this.rng = rng || Math.random; this.width = PlanetMod.FIELD_WIDTH; this.height = PlanetMod.FIELD_HEIGHT; this.blocks = []; this.clusters = Object.create(null); this.nextBlockId = 1; this.nextClusterId = 1; this.spawnTimer = 0; this.spawnInterval = PlanetMod.SPAWN_INTERVAL; this.settleTime = PlanetMod.SETTLE_TIME; this.score = 0; this.state = 'playing'; this.drag = null; this.gameOverTime = 0; this.outgoingShots = []; // Stage-2 default; stage 3 replaces this with Planet.missChance (Power). this.missChance = optsMissChance(arguments); // t1112: invariant checker. strictInvariants throws (tests); // debugInvariants records violations for the ?debug overlay. this.strictInvariants = false; this.debugInvariants = false; this.lastInvariantViolations = []; // t1121: visual-only swap events, consumed by the view each frame. this.swapEvents = []; // t1120: last landing-chain indicator { chain, bonusPct }, or null. this.lastChainIndicator = null; } function optsMissChance (args) { // GameCore(planet, rng, missChance) — third arg is optional. if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2])) { return Math.max(0, Math.min(1, args[2])); } var planet = args[0]; if (planet && typeof PlanetMod.missChance === 'function') { return PlanetMod.missChance(planet); } return GameCore.DEFAULT_MISS_CHANCE; } GameCore.COLOR_GRAY = COLOR_GRAY; GameCore.LAUNCH_PULL = LAUNCH_PULL; GameCore.SWAP_DISTANCE = SWAP_DISTANCE; GameCore.SNAP_Y = SNAP_Y; GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP; GameCore.LANDING_CHAIN_BONUS = LANDING_CHAIN_BONUS; GameCore.COLUMN_WARN_ROWS = COLUMN_WARN_ROWS; GameCore.DEFAULT_MISS_CHANCE = 0.30; GameCore.STATE_STILL = STATE_STILL; GameCore.STATE_FALLING = STATE_FALLING; GameCore.STATE_FLYING = STATE_FLYING; GameCore.STATE_SETTLING = STATE_SETTLING; GameCore.STATE_LOCKED = STATE_LOCKED; GameCore.STATE_MANUAL = STATE_MANUAL; GameCore.prototype.randomColor = function () { return Math.floor(this.rng() * this.planet.colors.length) % this.planet.colors.length; }; GameCore.prototype.createBlock = function (col, y, color, state) { var block = { id: this.nextBlockId++, col: col, y: y, color: color, state: state || STATE_STILL, vy: 0, clusterId: null, settleTime: 0, flame: false, pushedClusters: null, manualTarget: 0, manualDecel: 0, manualPhase: null, bouncing: false, bounceAge: 0 }; this.blocks.push(block); return block; }; GameCore.prototype.removeBlock = function (block) { if (block.clusterId != null) { this.leaveCluster(block); } var index = this.blocks.indexOf(block); if (index >= 0) { this.blocks.splice(index, 1); } }; GameCore.prototype.leaveCluster = function (block) { var id = block.clusterId; block.clusterId = null; block.flame = false; if (id == null || !this.clusters[id]) { return; } var still = 0; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].clusterId === id) { still++; } } if (still === 0) { delete this.clusters[id]; } }; GameCore.prototype.blocksInColumn = function (col) { var out = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].col === col) { out.push(this.blocks[i]); } } out.sort(function (a, b) { return a.y - b.y; }); return out; }; GameCore.prototype.isGrounded = function (block) { return block.state === STATE_STILL || block.state === STATE_SETTLING || block.state === STATE_LOCKED; }; /** * Highest grounded landing surface in `col`. If `belowY` is given, only * blocks strictly below that y count — a hanging still block above a * gap must never pull a falling or thrown block upward through the gap. */ GameCore.prototype.stackTop = function (col, ignore, belowY) { var top = 0; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.col !== col) { continue; } if (ignore && ignore(block)) { continue; } if (belowY != null && block.y + 1e-9 >= belowY) { continue; } if (this.isGrounded(block)) { var surface = block.y + 1; if (surface > top) { top = surface; } } } return top; }; GameCore.prototype.isColumnLocked = function (col) { for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.col === col && block.state === STATE_LOCKED) { return true; } } return false; }; GameCore.prototype.isColumnStill = function (col) { if (this.isColumnLocked(col)) { return false; } for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.col !== col) { continue; } if (block.state === STATE_FLYING || block.state === STATE_FALLING || block.state === STATE_MANUAL || block.state === STATE_SETTLING) { return false; } } return true; }; GameCore.prototype.groundedCount = function (col) { var n = 0; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].col === col && this.isGrounded(this.blocks[i])) { n++; } } return n; }; GameCore.prototype.columnNeedsWarn = function (col) { return this.groundedCount(col) >= COLUMN_WARN_ROWS; }; /** * Which columns of a field snapshot should pulse (t1123). Flying, * falling and manual (airborne) blocks do not count: they are * temporary and would flicker the warning. Still, settling and * locked (grounded) blocks do. */ GameCore.warnColumnsFromSnapshot = function (snapshot, threshold) { threshold = threshold == null ? COLUMN_WARN_ROWS : threshold; var width = (snapshot && snapshot.width) || 10; var flags = []; var counts = []; for (var c = 0; c < width; c++) { counts[c] = 0; flags[c] = false; } var blocks = (snapshot && snapshot.blocks) || []; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; if (b.col < 0 || b.col >= width) { continue; } if (b.state === 'still' || b.state === 'settling' || b.state === 'locked') { counts[b.col]++; } } for (var c = 0; c < width; c++) { flags[c] = counts[c] >= threshold; } return flags; }; GameCore.columnWarnPulse = function (timeSec) { // Smooth sine, ~0.5 Hz, alpha 0.16–0.44. Shared by the player // field and opponent / bot minis so they pulse in sync. var t = timeSec; if (t == null) { t = (typeof performance !== 'undefined' && performance.now) ? performance.now() / 1000 : Date.now() / 1000; } return 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(t * Math.PI * 2 * 0.55)); }; GameCore.prototype.blockAt = function (col, row) { for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.col === col && Math.abs(block.y - row) < ALIGN_EPS) { return block; } } return null; }; GameCore.prototype.place = function (col, row, color, state) { return this.createBlock(col, row, color, state || STATE_STILL); }; GameCore.prototype.lockedColumnCount = function () { var n = 0; for (var c = 0; c < this.width; c++) { if (this.isColumnLocked(c)) { n++; } } return n; }; GameCore.prototype.startBounce = function (block) { if (!block) { return; } block.bouncing = true; block.bounceAge = 0; }; GameCore.prototype.advanceBounces = function (dt) { var duration = this.planet.bounceDuration; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (!block.bouncing) { continue; } block.bounceAge += dt; if (duration <= 0 || block.bounceAge >= duration) { block.bouncing = false; block.bounceAge = duration; } } }; /** * True if `block` rests on the floor or on a solid (still / settling / * locked) block immediately below it in the same column. */ GameCore.prototype.hasSupport = function (block) { if (block.y <= 1e-9) { return true; } for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === block || other.col !== block.col) { continue; } if (!this.isGrounded(other)) { continue; } if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS) { return true; } } return false; }; /** Highest flying block in this column whose top is at or below `block.y + 1`. */ GameCore.prototype.highestFlyingBelow = function (block) { var best = null; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === block || other.col !== block.col) { continue; } if (other.state !== STATE_FLYING || other.clusterId == null) { continue; } var cluster = this.clusters[other.clusterId]; if (!cluster || cluster.phase === 'landed') { continue; } // The falling block is at or above this flyer (or already overlapping). if (block.y + 1e-9 < other.y) { continue; } if (!best || other.y > best.y) { best = other; } } return best; }; GameCore.prototype.highestFallingBelow = function (block) { var best = null; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === block || other.col !== block.col) { continue; } if (other.state !== STATE_FALLING) { continue; } if (other.y > block.y - 1e-9) { continue; } if (!best || other.y > best.y) { best = other; } } return best; }; /** * Make an unsupported still block start falling from rest, so it eases * into fallSpeed under normal gravity. Skips the block being dragged. */ /** * Strip leftover launch / manual kinematics so a block that has just * become still or falling starts from rest. Used after a landed grey * cluster recolors, and whenever an unsupported still block drops. */ GameCore.prototype.clearFlightState = function (block) { block.vy = 0; block.flame = false; block.manualPhase = null; block.manualTarget = null; block.manualDecel = 0; block.pushedClusters = null; }; GameCore.prototype.releaseUnsupported = function () { // Repeat until stable: a still sitting on a still that itself just // became falling must also drop. Two fixed passes are not enough // for a chain of hanging blocks (t1112). var guard = 0; var changed = true; while (changed && guard++ < this.height + 2) { changed = false; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.state !== STATE_STILL) { continue; } if (this.drag && this.drag.blockId === block.id) { continue; } if (this.hasSupport(block)) { continue; } this.leaveCluster(block); this.clearFlightState(block); block.state = STATE_FALLING; changed = true; } } }; GameCore.prototype.accelerateFall = function (block, dt) { var target = -this.planet.fallSpeed; if (block.vy > target) { block.vy = Math.max(target, block.vy - this.planet.fallAccel * dt); } else { block.vy = target; } }; GameCore.prototype.landFallingBlock = function (block) { block.vy = 0; block.flame = false; this.startBounce(block); if (block.color === COLOR_GRAY) { block.state = STATE_SETTLING; block.settleTime = 0; } else { block.state = STATE_STILL; } }; /** * Sit `block` on top of the flying cluster that `flyer` belongs to, and * carry it along as cargo (no flame). Returns true if attached. */ GameCore.prototype.attachToFlyingCluster = function (block, flyer) { var cluster = this.clusters[flyer.clusterId]; if (!cluster || cluster.phase === 'landed') { return false; } this.prepareClusterBody(cluster); var maxOff = null; var members = this.clusterMembers(cluster.id); for (var i = 0; i < members.length; i++) { if (members[i].col !== block.col) { continue; } if (maxOff == null || members[i].clusterOffset > maxOff) { maxOff = members[i].clusterOffset; } } var oldN = members.length; var fallingVy = block.vy; if (block.clusterId != null && block.clusterId !== cluster.id) { this.leaveCluster(block); } block.state = STATE_FLYING; block.clusterId = cluster.id; block.clusterOffset = (maxOff == null) ? 0 : maxOff + 1; block.flame = false; block.settleTime = 0; block.manualPhase = null; block.manualTarget = null; block.manualDecel = 0; block.pushedClusters = null; // A cluster born from a thrown block averages in falling cargo // the same way two flying clusters merge (t1108). Other rockets // keep their velocity and just pick the cargo up. if (cluster.fromManual) { var newN = oldN + 1; cluster.vy = (cluster.vy * oldN + fallingVy) / newN; cluster.decel = ((cluster.decel || 0) * oldN) / newN; cluster.jumpHeight = ((cluster.jumpHeight || 0) * oldN) / newN; cluster.phase = cluster.vy > 1e-10 ? 'up' : 'down'; } this.syncClusterMembers(cluster); return true; }; GameCore.prototype.catchFallingOntoCluster = function (cluster, members) { if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold') { return; } // Snapshot falling blocks; attaching mutates state. var falling = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].state === STATE_FALLING) { falling.push(this.blocks[i]); } } for (var i = 0; i < falling.length; i++) { var block = falling[i]; var flyer = null; for (var m = 0; m < members.length; m++) { var other = members[m]; if (other.col !== block.col) { continue; } // Overlap or rest on this member's top. if (block.y < other.y + 1 + 1e-9 && block.y + 1 > other.y - 1e-9) { if (!flyer || other.y > flyer.y) { flyer = other; } } } if (flyer) { this.attachToFlyingCluster(block, flyer); } } }; GameCore.prototype.tick = function (dt) { if (this.state === 'gameover') { this.gameOverTime += Math.max(0, dt); return; } if (dt <= 0) { return; } dt = Math.min(dt, 0.1); this.spawnTimer += dt; while (this.spawnTimer >= this.spawnInterval) { this.spawnTimer -= this.spawnInterval; this.trySpawn(); } var left = dt; while (left > 1e-12) { var step = Math.min(SUBSTEP, left); this.snapshotPrevY(); this.integrateFalling(step); this.resolveFlyingMatches(); this.integrateClusters(step); this.mergeFlyingClusters(); this.integrateManual(step); this.mergeAnyManualFallingOverlaps(); this.resolveAirborneCollisions(); this.cullOffTop(); left -= step; } this.releaseUnsupported(); this.advanceSettle(dt); // After a landed grey group is released, blocks that were sitting on // hanging members are still STILL (the earlier pass ran while those // members counted as support). Drop them from rest before matching, // so they cannot form a mid-air match and shoot off the top. this.releaseUnsupported(); this.advanceBounces(dt); if (!this.drag) { this.resolveMatches(); } this.checkLocks(); this.checkGameOver(); this.assertInvariants('tick'); }; /** Step a stretch of time in fixed substeps. Useful for tests. */ GameCore.prototype.step = function (seconds, dt) { dt = dt || SUBSTEP; var t = 0; while (t < seconds - 1e-15) { var s = Math.min(dt, seconds - t); this.tick(s); t += s; } }; GameCore.prototype.trySpawn = function () { if (this.state !== 'playing') { return null; } var eligible = []; for (var col = 0; col < this.width; col++) { if (this.isColumnLocked(col)) { continue; } if (this.groundedCount(col) >= this.height) { continue; } var alreadyFalling = false; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { if (list[i].state === STATE_FALLING) { alreadyFalling = true; break; } } if (!alreadyFalling) { eligible.push(col); } } if (!eligible.length) { return null; } var col = eligible[Math.floor(this.rng() * eligible.length) % eligible.length]; var color = this.randomColor(); var block = this.createBlock(col, this.height, color, STATE_FALLING); block.vy = -this.planet.fallSpeed; return block; }; GameCore.prototype.integrateFalling = function (dt) { var falling = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].state === STATE_FALLING) { falling.push(this.blocks[i]); } } // Lowest first, so a stack of falling blocks rests on itself. falling.sort(function (a, b) { return a.y - b.y; }); for (var i = 0; i < falling.length; i++) { var block = falling[i]; if (block.state !== STATE_FALLING) { continue; } this.accelerateFall(block, dt); var nextY = block.y + block.vy * dt; var manual = this.manualInColumnHit(block, block.y, nextY); if (manual) { this.mergeManualWithFalling(manual, this.contiguousFallingInColumn(manual.col, manual, [block])); continue; } var flyer = this.highestFlyingBelow(block); if (flyer && nextY <= flyer.y + 1 + 1e-9) { if (this.attachToFlyingCluster(block, flyer)) { continue; } } var top = this.stackTop(block.col, null, block.y); var below = this.highestFallingBelow(block); if (below && below.y + 1 > top) { top = below.y + 1; } if (nextY <= top) { block.y = top; this.landFallingBlock(block); } else { block.y = nextY; } } }; GameCore.prototype.clusterMembers = function (clusterId) { var out = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].clusterId === clusterId) { out.push(this.blocks[i]); } } return out; }; /** * Advance a jump (cluster or manual) by dt. Uses exact kinematics so a * jump of height H peaks at exactly H after riseTime. Returns dy. * Mutates body.vy and body.phase ('up' / 'down'). body.decel is the * upward deceleration. After the apex, vy eases from 0 to the * terminal descent speed at the matching accel, then stays there. * Flying clusters (forCluster) use the halved cluster float-down * (t1122 / t1124); manual jumps use the full single-block fallSpeed. */ GameCore.prototype.descentParams = function (forCluster) { var p = this.planet; if (forCluster) { return { fallSpeed: p.clusterFallSpeed, fallAccel: p.clusterFallAccel }; } return { fallSpeed: p.fallSpeed, fallAccel: p.fallAccel }; }; GameCore.prototype.advanceJump = function (body, dt, forCluster) { var dy = 0; var left = dt; if (body.phase === 'up') { var decel = body.decel; var vy = body.vy; var tApex = decel > 1e-12 ? vy / decel : Infinity; if (tApex <= left + 1e-15) { dy += vy * tApex - 0.5 * decel * tApex * tApex; body.vy = 0; body.phase = 'down'; left -= tApex; } else { var vyNew = vy - decel * left; dy += (vy + vyNew) * 0.5 * left; body.vy = vyNew; left = 0; } } if (body.phase === 'up' && body.vy <= 1e-10) { body.vy = 0; body.phase = 'down'; } if (body.phase === 'down' && left > 0) { var desc = this.descentParams(forCluster); var target = -desc.fallSpeed; var accel = desc.fallAccel; if (accel < 1e-12) { body.vy = target; dy += body.vy * left; } else if (body.vy > target + 1e-12) { var tReach = (body.vy - target) / accel; if (tReach <= left + 1e-15) { dy += (body.vy + target) * 0.5 * tReach; body.vy = target; left -= tReach; dy += body.vy * left; } else { var vyNew = body.vy - accel * left; dy += (body.vy + vyNew) * 0.5 * left; body.vy = vyNew; } } else { body.vy = target; dy += body.vy * left; } } return dy; }; GameCore.prototype.integrateClusters = function (dt) { var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster) { continue; } var members = this.clusterMembers(cluster.id); if (!members.length) { delete this.clusters[cluster.id]; continue; } if (cluster.phase === 'landed' || cluster.phase === 'hold') { continue; } this.prepareClusterBody(cluster); var dy = this.advanceJump(cluster, dt, true); cluster.anchorY += dy; this.syncClusterMembers(cluster); this.catchFallingOntoCluster(cluster, this.clusterMembers(cluster.id)); this.checkChainRelaunch(cluster); if (cluster.phase === 'down' && this.clusters[cluster.id]) { this.tryLandCluster(cluster, this.clusterMembers(cluster.id)); } } }; /** * If two or more flying clusters overlap in the same column, merge them * into one cluster. Velocity (and deceleration and jumpHeight) is the * mass-weighted average by block count. Phase is 'up' when the merged * vy is positive, otherwise 'down'. Overlapping members in a column * are packed so the higher one sits flush on the lower. */ GameCore.prototype.mergeFlyingClusters = function () { var flying = []; var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster) { continue; } if (cluster.phase === 'landed' || cluster.phase === 'hold') { continue; } flying.push(cluster); } if (flying.length < 2) { return; } var uf = new UnionFind(); for (var i = 0; i < flying.length; i++) { uf.add(flying[i].id); } for (var i = 0; i < flying.length; i++) { for (var j = i + 1; j < flying.length; j++) { if (this.flyingClustersOverlap(flying[i], flying[j])) { uf.union(flying[i].id, flying[j].id); } } } var groups = Object.create(null); for (var i = 0; i < flying.length; i++) { var root = uf.find(flying[i].id); if (!groups[root]) { groups[root] = []; } groups[root].push(flying[i]); } for (var root in groups) { if (groups[root].length >= 2) { this.mergeClusterGroup(groups[root]); } } }; GameCore.prototype.flyingClustersOverlap = function (a, b) { var ma = this.clusterMembers(a.id); var mb = this.clusterMembers(b.id); for (var i = 0; i < ma.length; i++) { for (var j = 0; j < mb.length; j++) { if (ma[i].col !== mb[j].col) { continue; } if (this.sweptIntervalsOverlap(ma[i], mb[j])) { return true; } } } return false; }; /** * Swept [y, y+1) of two blocks this substep, using _prevY when present. * Catches pairs that crossed without sharing a cell at either endpoint. */ GameCore.prototype.sweptIntervalsOverlap = function (a, b) { var a0 = (a._prevY != null) ? a._prevY : a.y; var a1 = a.y; var b0 = (b._prevY != null) ? b._prevY : b.y; var b1 = b.y; var aLo = Math.min(a0, a1); var aHi = Math.max(a0, a1) + 1; var bLo = Math.min(b0, b1); var bHi = Math.max(b0, b1) + 1; return aLo < bHi - 1e-9 && bLo < aHi - 1e-9; }; GameCore.prototype.mergeClusterGroup = function (clusters) { clusters.sort(function (a, b) { return a.id - b.id; }); var keep = clusters[0]; var n = 0; var vySum = 0; var decelSum = 0; var hSum = 0; for (var c = 0; c < clusters.length; c++) { var mem = this.clusterMembers(clusters[c].id); var m = mem.length; n += m; vySum += clusters[c].vy * m; decelSum += (clusters[c].decel || 0) * m; hSum += (clusters[c].jumpHeight || 0) * m; } if (n === 0) { return; } keep.vy = vySum / n; keep.decel = decelSum / n; keep.jumpHeight = hSum / n; keep.phase = keep.vy > 1e-10 ? 'up' : 'down'; var maxChain = 0; for (var c = 0; c < clusters.length; c++) { var ch = clusters[c].landingChain || 0; if (ch > maxChain) { maxChain = ch; } } keep.landingChain = maxChain; for (var c = 0; c < clusters.length; c++) { var mem = this.clusterMembers(clusters[c].id); for (var i = 0; i < mem.length; i++) { mem[i].clusterId = keep.id; mem[i].vy = keep.vy; mem[i].state = STATE_FLYING; } if (clusters[c] !== keep) { delete this.clusters[clusters[c].id]; } } this.prepareClusterBody(keep); this.checkChainRelaunch(keep); if (keep.phase === 'down' && this.clusters[keep.id]) { this.tryLandCluster(keep, this.clusterMembers(keep.id)); } }; GameCore.prototype.packClusterOverlaps = function (cluster) { var members = this.clusterMembers(cluster.id); var byCol = Object.create(null); for (var i = 0; i < members.length; i++) { var col = members[i].col; if (!byCol[col]) { byCol[col] = []; } byCol[col].push(members[i]); } var cols = Object.keys(byCol); for (var c = 0; c < cols.length; c++) { var list = byCol[cols[c]]; list.sort(function (a, b) { return a.y - b.y; }); for (var i = 1; i < list.length; i++) { var minY = list[i - 1].y + 1; if (list[i].y < minY - 1e-12) { list[i].y = minY; } } } }; /** * Derive integer cell offsets from current member positions and a * single anchorY, packing overlaps in each column while preserving * order (lower y stays lower; ties break on id). Then sync. * Flying clusters are one rigid body: one y, one vy, integer offsets. */ GameCore.prototype.prepareClusterBody = function (cluster) { if (!cluster) { return; } var members = this.clusterMembers(cluster.id); if (!members.length) { return; } this.rebuildClusterOffsets(cluster, members); }; GameCore.prototype.rebuildClusterOffsets = function (cluster, members) { members = members || this.clusterMembers(cluster.id); if (!members.length) { return; } var byCol = Object.create(null); for (var i = 0; i < members.length; i++) { var col = members[i].col; if (!byCol[col]) { byCol[col] = []; } byCol[col].push(members[i]); } var minY = Infinity; for (var i = 0; i < members.length; i++) { if (members[i].y < minY) { minY = members[i].y; } } if (cluster.anchorY == null || !isFinite(cluster.anchorY)) { cluster.anchorY = minY; } var cols = Object.keys(byCol); for (var c = 0; c < cols.length; c++) { var list = byCol[cols[c]]; list.sort(function (a, b) { if (a.y !== b.y) { return a.y - b.y; } return a.id - b.id; }); var prevOff = -Infinity; for (var i = 0; i < list.length; i++) { var off = Math.round(list[i].y - cluster.anchorY); if (off <= prevOff) { off = prevOff + 1; } list[i].clusterOffset = off; prevOff = off; } } // Re-base so the lowest offset is 0, keeping relative integers. var minOff = Infinity; for (var i = 0; i < members.length; i++) { if (members[i].clusterOffset < minOff) { minOff = members[i].clusterOffset; } } if (minOff !== 0 && isFinite(minOff)) { cluster.anchorY += minOff; for (var i = 0; i < members.length; i++) { members[i].clusterOffset -= minOff; } } this.syncClusterMembers(cluster); }; GameCore.prototype.syncClusterMembers = function (cluster) { if (!cluster) { return; } var members = this.clusterMembers(cluster.id); if (cluster.anchorY == null) { var minY = Infinity; for (var i = 0; i < members.length; i++) { if (members[i].y < minY) { minY = members[i].y; } } cluster.anchorY = isFinite(minY) ? minY : 0; } for (var i = 0; i < members.length; i++) { var block = members[i]; if (block.clusterOffset == null) { block.clusterOffset = Math.round(block.y - cluster.anchorY); } block.y = cluster.anchorY + block.clusterOffset; if (cluster.phase !== 'landed') { block.vy = cluster.vy; } } }; GameCore.prototype.snapshotPrevY = function () { for (var i = 0; i < this.blocks.length; i++) { this.blocks[i]._prevY = this.blocks[i].y; } }; /** * Safety net after the specific integrates: any remaining mid-air * overlap or swept crossing is resolved with the same rules, then * every flying cluster is rebuilt as a rigid body. Repeats a few * times because one attach can create a new contact. */ GameCore.prototype.resolveAirborneCollisions = function () { var guard = 0; while (guard++ < this.height + 4) { var changed = false; // Manual vs falling / cluster / manual. var manuals = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].state === STATE_MANUAL) { manuals.push(this.blocks[i]); } } manuals.sort(function (a, b) { return b.y - a.y; }); for (var m = 0; m < manuals.length; m++) { var manual = manuals[m]; if (manual.state !== STATE_MANUAL) { continue; } var oldY = (manual._prevY != null) ? manual._prevY : manual.y; if (this.resolveManualCollisions(manual, oldY, manual.y)) { changed = true; } } // Falling vs flying (sit on the roof). for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.state !== STATE_FALLING) { continue; } var flyer = this.highestFlyingBelow(block); if (!flyer) { // Also a flyer whose swept path crosses this falling block. flyer = this.flyingHitOnManualPath(block, (block._prevY != null) ? block._prevY : block.y, block.y); } if (flyer && this.sweptIntervalsOverlap(block, flyer)) { if (this.attachToFlyingCluster(block, flyer)) { changed = true; } } } // Cluster vs cluster (swept, including after a column push). var before = Object.keys(this.clusters).length; this.mergeFlyingClusters(); if (Object.keys(this.clusters).length !== before) { changed = true; } // Rebuild every flying body so offsets stay integer and unique. var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold') { continue; } this.prepareClusterBody(cluster); } if (!changed) { break; } } }; /** * Invariant checker (t1112). No two blocks occupy the same cell or * overlap their [y, y+1) intervals. Flying-cluster members are * grid-aligned to a single anchor. Returns a list of violation * strings (empty if clean). */ GameCore.prototype.checkInvariants = function () { var issues = []; var byCol = Object.create(null); var ids = Object.create(null); for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (ids[block.id]) { issues.push('duplicate id ' + block.id); } ids[block.id] = true; if (!byCol[block.col]) { byCol[block.col] = []; } byCol[block.col].push(block); if (block.color < COLOR_GRAY || (block.color >= 0 && this.planet && block.color >= this.planet.colors.length)) { issues.push('block ' + block.id + ' has invalid color ' + block.color); } } var cols = Object.keys(byCol); for (var c = 0; c < cols.length; c++) { var list = byCol[cols[c]]; list.sort(function (a, b) { if (a.y !== b.y) { return a.y - b.y; } return a.id - b.id; }); for (var i = 0; i < list.length; i++) { var a = list[i]; if (i > 0) { var prev = list[i - 1]; if (a.y < prev.y + 1 - 1e-6) { issues.push('overlap col=' + a.col + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a) + ' gap=' + (a.y - prev.y)); } var cellA = Math.floor(a.y + 1e-9); var cellP = Math.floor(prev.y + 1e-9); if (cellA === cellP) { issues.push('duplicate cell col=' + a.col + ' row=' + cellA + ' ' + this._invBlock(prev) + ' and ' + this._invBlock(a)); } } } } var cids = Object.keys(this.clusters); for (var n = 0; n < cids.length; n++) { var cluster = this.clusters[cids[n]]; if (!cluster || cluster.phase === 'landed' || cluster.phase === 'hold') { continue; } var mem = this.clusterMembers(cluster.id); var seenOff = Object.create(null); for (var i = 0; i < mem.length; i++) { var b = mem[i]; if (cluster.anchorY != null && b.clusterOffset != null) { var expected = cluster.anchorY + b.clusterOffset; if (Math.abs(b.y - expected) > 1e-6) { issues.push('cluster ' + cluster.id + ' member ' + b.id + ' y=' + b.y + ' != anchor+off ' + expected); } if (Math.abs(b.clusterOffset - Math.round(b.clusterOffset)) > 1e-9) { issues.push('cluster ' + cluster.id + ' member ' + b.id + ' non-integer offset ' + b.clusterOffset); } var key = b.col + ':' + b.clusterOffset; if (seenOff[key]) { issues.push('cluster ' + cluster.id + ' duplicate offset ' + key); } seenOff[key] = true; } } } return issues; }; GameCore.prototype._invBlock = function (b) { return '#' + b.id + '(' + b.state + ',c=' + b.color + ',y=' + (Math.round(b.y * 1000) / 1000) + ',cid=' + b.clusterId + ')'; }; GameCore.prototype.assertInvariants = function (label) { if (!this.strictInvariants && !this.debugInvariants) { return; } var issues = this.checkInvariants(); this.lastInvariantViolations = issues; if (!issues.length) { return; } var msg = 'physics invariants failed' + (label ? ' at ' + label : '') + ':\n ' + issues.join('\n ') + '\n' + (this.snapshot ? this.snapshot().picture : ''); if (this.strictInvariants) { throw new Error(msg); } }; GameCore.prototype.tryLandCluster = function (cluster, members) { if (!members.length) { return; } var shift = 0; var hit = false; for (var i = 0; i < members.length; i++) { var block = members[i]; var top = this.stackTop(block.col, function (other) { return other.clusterId === cluster.id; }, block.y); if (block.y <= top + 1e-9) { hit = true; var need = top - block.y; if (need > shift) { shift = need; } } } if (!hit) { return; } // Lift the whole rigid body so the deepest contact sits flush. this.prepareClusterBody(cluster); cluster.anchorY += shift; this.syncClusterMembers(cluster); this.landCluster(cluster, this.clusterMembers(cluster.id)); }; /** * Land as a rigid group: relative positions are kept, so part of the * cluster may hang above a gap. Grey members start the 3s settle timer; * coloured cargo stays put with them until every grey has recolored. * Members that actually rest on the floor or on another block bounce. */ GameCore.prototype.landCluster = function (cluster, members) { for (var i = 0; i < members.length; i++) { var block = members[i]; block.vy = 0; block.flame = false; block.clusterId = cluster.id; if (block.color === COLOR_GRAY) { block.state = STATE_SETTLING; block.settleTime = 0; } else { // Cargo stays in the rigid group (not matchable) until release. block.state = STATE_SETTLING; block.settleTime = 0; } if (this.hasSupport(block)) { this.startBounce(block); } } cluster.phase = 'landed'; cluster.vy = 0; cluster.landedPending = true; if (cluster.landingChain == null) { cluster.landingChain = 0; } }; /** * After every grey in a landed cluster has recolored, let the group go. * Unsupported blocks fall individually from rest; supported ones stay. */ GameCore.prototype.releaseLandedCluster = function (cluster) { var members = this.clusterMembers(cluster.id); var releasing = Object.create(null); for (var i = 0; i < members.length; i++) { releasing[members[i].id] = true; } for (var i = 0; i < members.length; i++) { var block = members[i]; if (block.color === COLOR_GRAY) { block.color = this.randomColor(); block.settleTime = 0; } // Persist the chain across release so a post-recolor match in // this same tick still gets the landing bonus (t1120). block.justLanded = !!cluster.landedPending; block.landingChain = cluster.landingChain || 0; this.leaveCluster(block); // Always drop leftover launch / manual velocity. A stale upward // vy here is what sends blocks off the top "very fast" after // a grey group recolors. this.clearFlightState(block); // Support from outside the group (floor or a foreign block). Fellow // members that will also fall do not count, so a hanging stack // drops together without the top one staying put. var supported = this.hasSupportOutside(block, releasing); block.state = supported ? STATE_STILL : STATE_FALLING; } delete this.clusters[cluster.id]; }; GameCore.prototype.hasSupportOutside = function (block, ignoreIds) { if (block.y <= 1e-9) { return true; } for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === block || other.col !== block.col) { continue; } if (ignoreIds && ignoreIds[other.id]) { continue; } if (!this.isGrounded(other)) { continue; } if (Math.abs((other.y + 1) - block.y) < ALIGN_EPS) { return true; } } return false; }; GameCore.prototype.integrateManual = function (dt) { for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.state !== STATE_MANUAL) { continue; } if (block.manualPhase === 'up') { var oldY = block.y; var proxy = { phase: 'up', vy: block.vy, decel: block.manualDecel }; var dy = this.advanceJump(proxy, dt); var nextY = oldY + dy; block.vy = proxy.vy; block.manualPhase = proxy.phase; if (this.resolveManualCollisions(block, oldY, Math.min(nextY, block.manualTarget))) { continue; } block.y = Math.min(nextY, block.manualTarget); if (block.y >= block.manualTarget - 1e-12) { block.y = block.manualTarget; block.vy = 0; block.manualPhase = 'down'; } if (block.y > this.height - 1) { block.y = this.height - 1; block.vy = 0; block.manualPhase = 'down'; } } if (block.manualPhase === 'down') { var proxy = { phase: 'down', vy: block.vy, decel: 0 }; var dy = this.advanceJump(proxy, dt); block.vy = proxy.vy; var nextY = block.y + dy; var top = this.stackTop(block.col, null, block.y); if (nextY <= top) { block.y = top; block.state = STATE_STILL; block.vy = 0; block.manualPhase = null; block.flame = false; this.startBounce(block); } else { var downNext = Math.min(nextY, this.height - 1); if (this.resolveManualCollisions(block, block.y, downNext)) { continue; } block.y = downNext; } } } }; /** * If the manual throw (or its path this step) hits falling blocks, merge * them into a flying cluster with mass-weighted velocity, the same rule * as two flying clusters colliding (t1108). Returns true if merged. */ GameCore.prototype.tryMergeManualWithFalling = function (manual, oldY, newY) { if (!manual || manual.state !== STATE_MANUAL) { return false; } var hits = this.fallingHitsOnManualPath(manual, oldY, newY); if (!hits.length) { return false; } this.mergeManualWithFalling(manual, hits); return true; }; GameCore.prototype.manualInColumnHit = function (falling, oldY, newY) { var lo = Math.min(oldY, newY); var hi = Math.max(oldY, newY) + 1; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === falling || other.col !== falling.col) { continue; } if (other.state !== STATE_MANUAL) { continue; } if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9) { return other; } } return null; }; GameCore.prototype.fallingHitsOnManualPath = function (manual, oldY, newY) { var lo = Math.min(oldY, newY); var hi = Math.max(oldY, newY) + 1; var hits = []; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === manual || other.col !== manual.col) { continue; } if (other.state !== STATE_FALLING) { continue; } if (other.y < hi - 1e-9 && other.y + 1 > lo + 1e-9) { hits.push(other); } } if (!hits.length) { return hits; } return this.contiguousFallingInColumn(manual.col, manual, hits); }; /** * Every falling block in `col` that overlaps `anchor` or a hit already * in `seed`, plus a contiguous falling stack sitting on them. */ GameCore.prototype.contiguousFallingInColumn = function (col, anchor, seed) { var falling = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING) { falling.push(this.blocks[i]); } } falling.sort(function (a, b) { return a.y - b.y; }); var include = Object.create(null); var queue = []; function enqueue (b) { if (!b || include[b.id]) { return; } include[b.id] = true; queue.push(b); } if (seed) { for (var s = 0; s < seed.length; s++) { enqueue(seed[s]); } } // Also include falling that already overlap the anchor. if (anchor) { for (var i = 0; i < falling.length; i++) { if (falling[i].y < anchor.y + 1 - 1e-9 && anchor.y < falling[i].y + 1 - 1e-9) { enqueue(falling[i]); } } } for (var q = 0; q < queue.length; q++) { var a = queue[q]; for (var i = 0; i < falling.length; i++) { var b = falling[i]; if (include[b.id]) { continue; } if (a.y < b.y + 1 + 1e-9 && b.y < a.y + 1 + 1e-9) { enqueue(b); } } } var out = []; for (var i = 0; i < falling.length; i++) { if (include[falling[i].id]) { out.push(falling[i]); } } return out; }; /** * Merge a thrown (manual) block with falling blocks into one flying * cluster. Velocity, deceleration and jumpHeight are the mass-weighted * averages by block count, identical to mergeClusterGroup. The thrown * block stops being manual and the group follows normal cluster physics. * fromManual marks the cluster so later falling cargo also averages in. */ GameCore.prototype.mergeManualWithFalling = function (manual, fallingList) { if (!manual || manual.state !== STATE_MANUAL) { return null; } var blocks = [manual]; for (var i = 0; i < fallingList.length; i++) { if (fallingList[i] && fallingList[i].state === STATE_FALLING && blocks.indexOf(fallingList[i]) < 0) { blocks.push(fallingList[i]); } } if (blocks.length < 2) { return null; } var n = blocks.length; var vySum = 0; var decelSum = 0; var hSum = 0; for (var i = 0; i < n; i++) { var b = blocks[i]; vySum += b.vy; if (b === manual) { decelSum += manual.manualDecel || 0; hSum += manual.manualJumpHeight != null ? manual.manualJumpHeight : Math.max(0, (manual.manualTarget || this.height - 1) - manual.y); } } var cluster = { id: this.nextClusterId++, jumpHeight: hSum / n, vy: vySum / n, decel: decelSum / n, phase: (vySum / n) > 1e-10 ? 'up' : 'down', fromManual: true }; this.clusters[cluster.id] = cluster; for (var i = 0; i < n; i++) { var b = blocks[i]; b.clusterId = cluster.id; b.state = STATE_FLYING; b.vy = cluster.vy; b.flame = b.color === COLOR_GRAY; b.manualPhase = null; b.manualTarget = null; b.manualDecel = 0; b.manualJumpHeight = 0; b.pushedClusters = null; b.settleTime = 0; } if (this.drag && this.drag.blockId === manual.id) { this.drag = null; } this.prepareClusterBody(cluster); this.checkChainRelaunch(cluster); return cluster; }; /** Safety net: any remaining manual/falling overlaps after the substep. */ GameCore.prototype.mergeAnyManualFallingOverlaps = function () { var manuals = []; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].state === STATE_MANUAL) { manuals.push(this.blocks[i]); } } for (var m = 0; m < manuals.length; m++) { var manual = manuals[m]; if (manual.state !== STATE_MANUAL) { continue; } var hits = this.contiguousFallingInColumn(manual.col, manual); if (hits.length) { this.mergeManualWithFalling(manual, hits); } } }; /** * Resolve collisions of a thrown (manual) block along [oldY, nextY]. * Falling blocks merge (t1108). A flying cluster is pushed one cell up * in the hit column and the shot attaches at the bottom (t1111). * Another thrown block is promoted to a 1-block cluster and then the * same attach-at-bottom rule applies. Returns true if `manual` is no * longer in the MANUAL state. */ GameCore.prototype.resolveManualCollisions = function (manual, oldY, nextY) { if (!manual || manual.state !== STATE_MANUAL) { return true; } var fallingHits = this.fallingHitsOnManualPath(manual, oldY, nextY); if (fallingHits.length) { this.mergeManualWithFalling(manual, fallingHits); return manual.state !== STATE_MANUAL; } var flyer = this.flyingHitOnManualPath(manual, oldY, nextY); if (flyer) { var cluster = this.clusters[flyer.clusterId]; if (cluster && cluster.phase !== 'landed') { if (nextY + 1e-12 < oldY) { this.attachToFlyingCluster(manual, flyer); } else { this.attachShotUnderCluster(manual, cluster, manual.col); } return manual.state !== STATE_MANUAL; } } var other = this.manualHitOnManualPath(manual, oldY, nextY); if (other) { var host = this.promoteManualToCluster(other); if (host) { if (nextY + 1e-12 < oldY) { this.attachToFlyingCluster(manual, other); } else { this.attachShotUnderCluster(manual, host, manual.col); } return manual.state !== STATE_MANUAL; } } return false; }; /** Closest flying cluster member in `manual`'s column on [oldY, nextY]. */ GameCore.prototype.flyingHitOnManualPath = function (manual, oldY, nextY) { var lo = Math.min(oldY, nextY); var hi = Math.max(oldY, nextY) + 1; var best = null; var bestY = Infinity; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === manual || other.col !== manual.col) { continue; } if (other.state !== STATE_FLYING || other.clusterId == null) { continue; } var cluster = this.clusters[other.clusterId]; if (!cluster || cluster.phase === 'landed') { continue; } var o0 = (other._prevY != null) ? other._prevY : other.y; var o1 = other.y; var oLo = Math.min(o0, o1); var oHi = Math.max(o0, o1) + 1; if (lo < oHi - 1e-9 && oLo < hi - 1e-9) { if (other.y < bestY) { bestY = other.y; best = other; } } } return best; }; /** Another thrown block in the same column on the path (prefer the lower). */ GameCore.prototype.manualHitOnManualPath = function (manual, oldY, nextY) { var lo = Math.min(oldY, nextY); var hi = Math.max(oldY, nextY) + 1; var best = null; for (var i = 0; i < this.blocks.length; i++) { var other = this.blocks[i]; if (other === manual || other.col !== manual.col) { continue; } if (other.state !== STATE_MANUAL) { continue; } var o0 = (other._prevY != null) ? other._prevY : other.y; var o1 = other.y; var oLo = Math.min(o0, o1); var oHi = Math.max(o0, o1) + 1; if (lo < oHi - 1e-9 && oLo < hi - 1e-9) { if (!best || other.y < best.y) { best = other; } } } return best; }; /** * t1111: push every member of `cluster` in `col` up by one cell, then * attach `manual` at the bottom of that column, grid-aligned, as part * of the cluster. The cluster keeps its velocity; the shot takes it. * Other columns are untouched. Same rule for every successive shot. */ GameCore.prototype.attachShotUnderCluster = function (manual, cluster, col) { if (!manual || !cluster || !this.clusters[cluster.id]) { return false; } if (manual.state !== STATE_MANUAL && manual.clusterId !== cluster.id) { // Already belonging elsewhere: leave first. if (manual.clusterId != null) { this.leaveCluster(manual); } } this.prepareClusterBody(cluster); var members = this.clusterMembers(cluster.id); var minOff = null; for (var i = 0; i < members.length; i++) { if (members[i].col !== col) { continue; } if (minOff == null || members[i].clusterOffset < minOff) { minOff = members[i].clusterOffset; } } if (minOff == null) { minOff = 0; } else { for (var i = 0; i < members.length; i++) { if (members[i].col === col) { members[i].clusterOffset += 1; } } } if (this.drag && this.drag.blockId === manual.id) { this.drag = null; } manual.clusterId = cluster.id; manual.clusterOffset = minOff; manual.state = STATE_FLYING; manual.flame = manual.color === COLOR_GRAY; manual.settleTime = 0; manual.manualPhase = null; manual.manualTarget = null; manual.manualDecel = 0; manual.manualJumpHeight = 0; manual.pushedClusters = null; this.syncClusterMembers(cluster); this.cullOffTop(); if (this.clusters[cluster.id]) { this.checkChainRelaunch(cluster); } return true; }; /** * Turn a lone thrown block into a 1-block flying cluster so a later * shot can use the t1111 attach-at-bottom rule. A single throw stays * MANUAL (and is capped at the top of the field) until it collides. */ GameCore.prototype.promoteManualToCluster = function (manual) { if (!manual) { return null; } if (manual.state === STATE_FLYING && manual.clusterId != null) { var existing = this.clusters[manual.clusterId]; if (existing && existing.phase !== 'landed') { return existing; } } if (manual.state !== STATE_MANUAL) { return null; } var height = manual.manualJumpHeight != null ? manual.manualJumpHeight : Math.max(0.05, (manual.manualTarget || this.height - 1) - manual.y); var cluster = { id: this.nextClusterId++, jumpHeight: height, vy: manual.vy, decel: manual.manualDecel || 0, phase: (manual.manualPhase === 'down' || manual.vy <= 1e-10) ? 'down' : 'up', fromManual: true, anchorY: manual.y }; this.clusters[cluster.id] = cluster; manual.state = STATE_FLYING; manual.clusterId = cluster.id; manual.clusterOffset = 0; manual.flame = manual.color === COLOR_GRAY; manual.settleTime = 0; manual.manualPhase = null; manual.manualTarget = null; manual.manualDecel = 0; manual.manualJumpHeight = 0; manual.pushedClusters = null; this.syncClusterMembers(cluster); return cluster; }; /** Kept for older tests / call sites: push a cluster column by one cell. */ GameCore.prototype.checkManualPush = function (manual, oldY, nextY) { return this.resolveManualCollisions(manual, oldY, nextY); }; /** * Push every flying block of the cluster that sits in `col` one tile up. * Other columns stay put (they remain linked). Then look for a new * same-color line of 3+ in the flying cluster; if there is one, those * blocks turn gray, join the link, and the whole cluster re-launches * with the same jump height from its current position. */ GameCore.prototype.pushClusterColumn = function (clusterId, col) { var cluster = this.clusters[clusterId]; if (!cluster) { return false; } var members = this.clusterMembers(clusterId); for (var i = 0; i < members.length; i++) { if (members[i].col === col) { members[i].y += 1; } } this.cullOffTop(); if (!this.clusters[clusterId]) { return true; } this.checkChainRelaunch(cluster); return true; }; /** * After a cargo attach or a cluster merge (or any other mid-air state * change), turn spontaneous lines of 3+ into rockets and give the whole * already-flying cluster an extra launch from its current position — * the same re-launch as a player push that completes a row. */ GameCore.prototype.resolveFlyingMatches = function () { var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster || cluster.phase === 'landed') { continue; } this.checkChainRelaunch(cluster); } }; GameCore.prototype.checkChainRelaunch = function (cluster) { if (!this.clusters[cluster.id]) { return; } var lines = this.findFlyingMatchLines(cluster.id); if (!lines.length) { return; } var newly = []; var seen = Object.create(null); for (var i = 0; i < lines.length; i++) { for (var j = 0; j < lines[i].blocks.length; j++) { var block = lines[i].blocks[j]; if (seen[block.id]) { continue; } seen[block.id] = true; newly.push(block); } } for (var i = 0; i < newly.length; i++) { var block = newly[i]; block.color = COLOR_GRAY; block.flame = true; block.clusterId = cluster.id; block.state = STATE_FLYING; } this.relaunchCluster(cluster, cluster.jumpHeight); }; GameCore.prototype.relaunchCluster = function (cluster, height) { cluster.jumpHeight = height; cluster.vy = PlanetMod.launchVelocity(this.planet, height); cluster.decel = PlanetMod.launchDeceleration(this.planet, height); cluster.phase = 'up'; var members = this.clusterMembers(cluster.id); for (var i = 0; i < members.length; i++) { members[i].vy = cluster.vy; members[i].state = STATE_FLYING; if (members[i].color === COLOR_GRAY) { members[i].flame = true; } } }; GameCore.prototype.startManualLaunch = function (block) { var target = this.height - 1; var height = Math.max(0.05, target - block.y); this.leaveCluster(block); block.state = STATE_MANUAL; block.pushedClusters = Object.create(null); block.manualTarget = target; block.manualPhase = 'up'; block.manualJumpHeight = height; block.vy = PlanetMod.launchVelocity(this.planet, height); block.manualDecel = PlanetMod.launchDeceleration(this.planet, height); block.flame = false; if (this.drag && this.drag.blockId === block.id) { this.drag = null; } }; GameCore.prototype.cullOffTop = function () { var gone = []; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.state === STATE_MANUAL) { if (block.y > this.height - 1) { block.y = this.height - 1; } continue; } if (block.y >= this.height - 1e-9) { gone.push(block); } } for (var i = 0; i < gone.length; i++) { var block = gone[i]; this.outgoingShots.push({ id: block.id, color: block.color, col: block.col, y: block.y }); this.score += 1; this.removeBlock(block); } }; GameCore.prototype.consumeOutgoingShots = function () { var shots = this.outgoingShots; this.outgoingShots = []; return shots; }; /** * A compact field picture for the multiplayer snapshot (miniatures). * Includes every block's col, y, color, state and flame. */ GameCore.prototype.fieldSnapshot = function () { var blocks = []; for (var i = 0; i < this.blocks.length; i++) { var b = this.blocks[i]; blocks.push({ id: b.id, col: b.col, y: Math.round(b.y * 1000) / 1000, color: b.color, state: b.state, flame: !!b.flame }); } return { score: this.score, state: this.state, width: this.width, height: this.height, locked: this.lockedColumnCount(), blocks: blocks }; }; /** * Incoming garbage from another player: a dark-grey block that falls * normally from the top of an open column. After landing it uses the * usual 3s settle and then a random colour (landFallingBlock). * `col` is optional; a random eligible column is used otherwise. * Returns the new block, or null if every column is locked or full. */ 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]; // Coloured cargo in a just-landed cluster (SETTLING) can match // with already-resting blocks immediately (t1110). Greys have no // colour and wait until they recolor; after release they are STILL. if ((block.state === STATE_STILL || block.state === STATE_SETTLING) && block.color >= 0) { candidates.push(block); } } return this.collectLines(candidates, true); }; GameCore.prototype.findFlyingMatchLines = function (clusterId) { var candidates = []; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (block.clusterId === clusterId && block.color >= 0 && (block.state === STATE_FLYING)) { candidates.push(block); } } return this.collectLines(candidates, false); }; GameCore.prototype.collectLines = function (candidates, snapInteger) { var lines = []; if (!candidates.length) { return lines; } var byRow = Object.create(null); for (var i = 0; i < candidates.length; i++) { var block = candidates[i]; var row = Math.round(block.y); if (Math.abs(block.y - row) > (snapInteger ? ALIGN_EPS : 0.5)) { continue; } if (!byRow[row]) { byRow[row] = []; } byRow[row].push(block); } var rows = Object.keys(byRow); for (var r = 0; r < rows.length; r++) { var list = byRow[rows[r]]; list.sort(function (a, b) { return a.col - b.col; }); this.pushRuns(lines, list, false, function (a, b) { return a.color === b.color && a.col === b.col - 1 && a.color >= 0; }); } var byCol = Object.create(null); for (var i = 0; i < candidates.length; i++) { var block = candidates[i]; if (!byCol[block.col]) { byCol[block.col] = []; } byCol[block.col].push(block); } var cols = Object.keys(byCol); for (var c = 0; c < cols.length; c++) { var list = byCol[cols[c]]; list.sort(function (a, b) { return a.y - b.y; }); this.pushRuns(lines, list, true, function (a, b) { return a.color === b.color && a.color >= 0 && Math.abs((b.y - a.y) - 1) < ALIGN_EPS; }); } return lines; }; GameCore.prototype.pushRuns = function (lines, list, vertical, adjacent) { var start = 0; for (var i = 1; i <= list.length; i++) { var same = i < list.length && adjacent(list[i - 1], list[i]); if (!same) { var length = i - start; if (length >= 3) { lines.push({ blocks: list.slice(start, i), length: length, vertical: vertical }); } start = i; } } }; GameCore.prototype.resolveMatches = function () { if (this.state !== 'playing' || this.drag) { return []; } var lines = this.findMatchLines(); if (!lines.length) { this.finishLandingChains([]); return []; } var uf = new UnionFind(); var blockById = Object.create(null); for (var i = 0; i < lines.length; i++) { var line = lines[i]; for (var j = 0; j < line.blocks.length; j++) { uf.add(line.blocks[j].id); blockById[line.blocks[j].id] = line.blocks[j]; if (j > 0) { uf.union(line.blocks[0].id, line.blocks[j].id); } } } var matched = []; var seen = Object.create(null); for (var id in blockById) { if (!seen[id]) { seen[id] = true; matched.push(blockById[id]); } } for (var i = 0; i < matched.length; i++) { for (var j = i + 1; j < matched.length; j++) { if (matched[i].col === matched[j].col) { uf.union(matched[i].id, matched[j].id); } } } var groups = Object.create(null); for (var i = 0; i < matched.length; i++) { var root = uf.find(matched[i].id); if (!groups[root]) { groups[root] = []; } groups[root].push(matched[i]); } var launched = []; for (var root in groups) { var group = groups[root]; var height = 0; for (var i = 0; i < lines.length; i++) { var line = lines[i]; var overlaps = false; for (var j = 0; j < line.blocks.length; j++) { for (var k = 0; k < group.length; k++) { if (line.blocks[j].id === group[k].id) { overlaps = true; } } } if (overlaps) { var h = PlanetMod.jumpHeight(this.planet, line.length, line.vertical); if (h > height) { height = h; } } } var chain = this.landingChainFor(group); var bonusMul = 1 + LANDING_CHAIN_BONUS * chain; height *= bonusMul; this.launchCluster(group, height, { landingChain: chain }); launched.push({ blocks: group, jumpHeight: height, landingChain: chain, chainBonus: bonusMul }); } this.finishLandingChains(launched); this.updateChainIndicator(launched); return launched; }; /** * Gray the matched blocks, take everything sitting on top of them in * those columns, link them, and launch with jump height `height`. */ GameCore.prototype.launchCluster = function (matchedBlocks, height, opts) { opts = opts || {}; var lowestInCol = Object.create(null); var matchedIds = Object.create(null); for (var i = 0; i < matchedBlocks.length; i++) { var block = matchedBlocks[i]; matchedIds[block.id] = true; if (lowestInCol[block.col] == null || block.y < lowestInCol[block.col]) { lowestInCol[block.col] = block.y; } } var clusterId = this.nextClusterId++; var cluster = { id: clusterId, jumpHeight: height, vy: PlanetMod.launchVelocity(this.planet, height), decel: PlanetMod.launchDeceleration(this.planet, height), phase: 'up', landingChain: opts.landingChain || 0, landedPending: false }; this.clusters[clusterId] = cluster; var riders = []; var cols = Object.keys(lowestInCol); for (var c = 0; c < cols.length; c++) { var col = +cols[c]; var lowest = lowestInCol[col]; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { var block = list[i]; if (!this.isGrounded(block) && block.state !== STATE_STILL) { if (block.state !== STATE_SETTLING) { continue; } } if (block.y + ALIGN_EPS >= lowest) { riders.push(block); } } } for (var i = 0; i < riders.length; i++) { var block = riders[i]; var isMatch = !!matchedIds[block.id]; if (isMatch || block.color === COLOR_GRAY) { block.color = COLOR_GRAY; block.flame = true; } else { block.flame = false; } block.state = STATE_FLYING; block.clusterId = clusterId; block.vy = cluster.vy; block.settleTime = 0; } this.prepareClusterBody(cluster); return cluster; }; GameCore.prototype.checkLocks = function () { for (var col = 0; col < this.width; col++) { if (this.isColumnLocked(col)) { continue; } if (this.groundedCount(col) < this.height) { continue; } // Must fill the column from floor to top: 13 grounded blocks at y 0..12. var filled = true; for (var row = 0; row < this.height; row++) { var block = this.blockAt(col, row); if (!block || !this.isGrounded(block)) { filled = false; break; } } if (!filled) { continue; } var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { var block = list[i]; if (!this.isGrounded(block)) { continue; } block.state = STATE_LOCKED; block.color = COLOR_GRAY; block.flame = false; block.vy = 0; block.settleTime = 0; if (block.clusterId != null) { this.leaveCluster(block); } } } }; GameCore.prototype.checkGameOver = function () { if (this.state !== 'playing') { return; } for (var col = 0; col < this.width; col++) { if (!this.isColumnLocked(col)) { return; } } this.state = 'gameover'; this.gameOverTime = 0; this.drag = null; }; /* ---------- dragging -------------------------------------------------- */ GameCore.prototype.beginDrag = function (col, y) { if (this.state !== 'playing') { return false; } var block = this.snapDragBlock(col, y); if (!block) { return false; } var top = this.columnStackTopRow(block.col); var startedAsTop = Math.abs(block.y - top) < ALIGN_EPS; this.drag = { blockId: block.id, pointerY: y, startY: y, accum: 0, launchIntent: false, startedAsTop: startedAsTop }; return true; }; /** * Instant grab, cell-based (t1109). The press is mapped to the grid cell * floor(col), floor(y); any press inside that cell — corners, padding, * gaps between sprites, a visually tweened or bouncing sprite — grabs * the block that occupies it. This uses simulation cells, not the drawn * sprite bounds. If no block sits in that cell (mid-animation, a block * whose y is off the integer), fall back to the nearest grabbable block * in the same column within SNAP_Y (about half a tile). A small * horizontal slop still consults a neighbouring column when the press * is near the edge and the primary cell is empty. */ GameCore.prototype.snapDragBlock = function (col, y) { var raw = col; var c0 = Math.floor(raw + 1e-9); var row = Math.floor(y + 1e-9); var frac = raw - c0; if (c0 >= 0 && c0 < this.width && this.columnAllowsDrag(c0)) { var exact = this.draggableInCell(c0, row); if (exact) { return exact; } var near = this.nearestDraggableInColumn(c0, y, SNAP_Y); if (near) { return near; } } // Primary cell empty: allow a small horizontal slop into a neighbour. var neighbours = []; if (frac > 1e-9 && frac < HORIZONTAL_SLOP && c0 - 1 >= 0) { neighbours.push(c0 - 1); } if (frac > 1 - HORIZONTAL_SLOP && frac < 1 - 1e-9 && c0 + 1 < this.width) { neighbours.push(c0 + 1); } var best = null; var bestDist = Infinity; for (var n = 0; n < neighbours.length; n++) { var cc = neighbours[n]; if (!this.columnAllowsDrag(cc)) { continue; } var hit = this.draggableInCell(cc, row) || this.nearestDraggableInColumn(cc, y, SNAP_Y); if (!hit) { continue; } var dist = this.pointerDistToBlock(hit, raw, y); if (dist < bestDist) { bestDist = dist; best = hit; } } return best; }; /** The draggable block that occupies grid cell (col, row), if any. */ GameCore.prototype.draggableInCell = function (col, row) { var best = null; var bestOverlap = 0; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { var block = list[i]; if (!this.isDraggableBlock(block)) { continue; } var lo = Math.max(block.y, row); var hi = Math.min(block.y + 1, row + 1); var overlap = hi - lo; if (overlap > bestOverlap + 1e-12) { bestOverlap = overlap; best = block; } } if (best && bestOverlap > 1e-9) { return best; } return null; }; /** Nearest draggable block in `col` whose footprint is within `maxDist` of `y`. */ GameCore.prototype.nearestDraggableInColumn = function (col, y, maxDist) { var best = null; var bestDist = Infinity; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { var block = list[i]; if (!this.isDraggableBlock(block)) { continue; } var dist = this.pointerDistToBlock(block, col + 0.5, y); if (dist < bestDist) { bestDist = dist; best = block; } } if (!best || bestDist > maxDist) { return null; } return best; }; GameCore.prototype.pointerDistToBlock = function (block, col, y) { var dx; if (col >= block.col && col < block.col + 1) { dx = 0; } else if (col < block.col) { dx = block.col - col; } else { dx = col - (block.col + 1); } var dy; if (y >= block.y && y < block.y + 1) { dy = 0; } else if (y < block.y) { dy = block.y - y; } else { dy = y - (block.y + 1); } return Math.sqrt(dx * dx + dy * dy); }; GameCore.prototype.moveDrag = function (y) { if (!this.drag) { return; } var block = this.blockById(this.drag.blockId); if (!block || !this.isDraggableBlock(block)) { this.drag = null; return; } if (!this.columnAllowsDrag(block.col)) { this.drag = null; return; } this.drag.pointerY = y; // 1:1 tracking: the target row is the one under the pointer, clamped // to the still stack. Swap step by step with each neighbour, and stop // exactly there. When the pointer stops, nothing else moves. // Accumulated deltas are not used: a SWAP_DISTANCE (0.25) threshold // used to jump a full cell on a short pull, and one large event // could walk the entire column (the "jumps all the way" bug). var top = this.columnStackTopRow(block.col); var bottom = this.columnStackBottomRow(block.col); var target = Math.floor(y + 1e-12); if (bottom < 0) { bottom = 0; } if (target < bottom) { target = bottom; } if (target > top) { target = top; } this.swapToward(block, target); top = this.columnStackTopRow(block.col); var isTop = Math.abs(block.y - top) < ALIGN_EPS; if (this.drag.startedAsTop) { // Already the topmost block: pulling upward past its own position // (LAUNCH_PULL tiles above the press point) starts a manual jump. this.drag.launchIntent = isTop && (y > this.drag.startY + LAUNCH_PULL); } else { // Started mid-stack: swap first, and only launch once the pointer // is pulled into the empty space above the (new) top. this.drag.launchIntent = isTop && (y > top + 1 + 0.25); } }; /** Swap `block` one tile up (dir=+1) or down (dir=-1). Returns true if swapped. */ GameCore.prototype.swapOne = function (block, dir) { var neighbor = this.blockAt(block.col, block.y + dir); if (neighbor && this.isGrounded(neighbor) && neighbor !== block) { this.swapBlocks(block, neighbor); return true; } return false; }; GameCore.prototype.endDrag = function () { if (!this.drag) { return; } var block = this.blockById(this.drag.blockId); var launch = this.drag.launchIntent; this.drag = null; if (launch && block && block.state === STATE_STILL) { this.startManualLaunch(block); } else { this.resolveMatches(); } }; GameCore.prototype.blockById = function (id) { for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].id === id) { return this.blocks[i]; } } return null; }; GameCore.prototype.columnStackTopRow = function (col) { var top = -1; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { if (this.isGrounded(list[i]) && list[i].y > top) { top = list[i].y; } } return top; }; GameCore.prototype.columnStackBottomRow = function (col) { var bottom = Infinity; var list = this.blocksInColumn(col); for (var i = 0; i < list.length; i++) { if (this.isGrounded(list[i]) && list[i].y < bottom) { bottom = list[i].y; } } return bottom === Infinity ? 0 : bottom; }; GameCore.prototype.swapToward = function (block, targetY) { var guard = 0; while (guard++ < this.height + 2) { var current = block.y; if (targetY > current + 0.5) { var above = this.blockAt(block.col, current + 1); if (above && this.isGrounded(above) && above !== block) { this.swapBlocks(block, above); } else { break; } } else if (targetY < current - 0.5) { var below = this.blockAt(block.col, current - 1); if (below && this.isGrounded(below) && below !== block) { this.swapBlocks(block, below); } else { break; } } else { break; } } }; GameCore.prototype.swapBlocks = function (a, b) { var ay = a.y; var by = b.y; a.y = by; b.y = ay; this.transferLandedMembership(a, b); if (!this.swapEvents) { this.swapEvents = []; } this.swapEvents.push({ id: a.id, fromY: ay, toY: by, col: a.col }); this.swapEvents.push({ id: b.id, fromY: by, toY: ay, col: b.col }); }; GameCore.prototype.consumeSwapEvents = function () { var ev = this.swapEvents || []; this.swapEvents = []; return ev; }; /** * Highest landing-chain counter among just-landed members of this * match group, plus one. Returns 0 when the match did not come from * a cluster landing (player/bot swap, mid-air, etc.). */ GameCore.prototype.landingChainFor = function (group) { var maxChain = 0; var fromLanding = false; for (var i = 0; i < group.length; i++) { var block = group[i]; if (block.justLanded) { fromLanding = true; if ((block.landingChain || 0) > maxChain) { maxChain = block.landingChain || 0; } } if (block.clusterId != null) { var cluster = this.clusters[block.clusterId]; if (cluster && cluster.landedPending) { fromLanding = true; if ((cluster.landingChain || 0) > maxChain) { maxChain = cluster.landingChain || 0; } } } } if (!fromLanding) { return 0; } return maxChain + 1; }; /** * After resolveMatches: clear the landing-pending flag and reset the * chain on landings that did not make a match. A cluster that is still * settling (greys not yet recolored) keeps landedPending so a later * post-recolor match in this same landing still gets the bonus. */ GameCore.prototype.finishLandingChains = function (launched) { var launchedIds = Object.create(null); launched = launched || []; for (var i = 0; i < launched.length; i++) { var blocks = launched[i].blocks || []; for (var j = 0; j < blocks.length; j++) { launchedIds[blocks[j].id] = true; } } for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; if (!block.justLanded) { continue; } if (!launchedIds[block.id]) { block.landingChain = 0; } block.justLanded = false; } var ids = Object.keys(this.clusters); for (var c = 0; c < ids.length; c++) { var cluster = this.clusters[ids[c]]; if (!cluster || !cluster.landedPending) { continue; } var members = this.clusterMembers(cluster.id); var anyLaunched = false; var stillSettling = false; for (var i = 0; i < members.length; i++) { if (launchedIds[members[i].id]) { anyLaunched = true; } if (members[i].state === STATE_SETTLING) { stillSettling = true; } } if (anyLaunched) { cluster.landingChain = 0; cluster.landedPending = false; } else if (!stillSettling) { // Released leftovers or a fully-still landed group that // already had its match opportunity and missed it. cluster.landingChain = 0; cluster.landedPending = false; } // else: still settling, no match yet — keep landedPending. } }; GameCore.prototype.updateChainIndicator = function (launched) { var maxChain = 0; for (var i = 0; i < launched.length; i++) { var ch = launched[i].landingChain || 0; if (ch > maxChain) { maxChain = ch; } } if (maxChain >= 1) { this.lastChainIndicator = { chain: maxChain, bonusPct: Math.round(maxChain * LANDING_CHAIN_BONUS * 100) }; return; } if (!this.hasActiveLandingChain()) { this.lastChainIndicator = null; } }; GameCore.prototype.hasActiveLandingChain = function () { var ids = Object.keys(this.clusters); for (var i = 0; i < ids.length; i++) { var cluster = this.clusters[ids[i]]; if (cluster && (cluster.landingChain || 0) >= 1 && cluster.phase !== 'landed') { return true; } } return false; }; /** * A landed cluster (grey rockets or linked cargo resting on the ground) * is a swappable part of the contiguous grounded stack. Flying, falling * and manual blocks are not. A locked column is not. */ GameCore.prototype.isDraggableBlock = function (block) { if (!block) { return false; } if (block.state === STATE_LOCKED || block.state === STATE_FLYING || block.state === STATE_FALLING || block.state === STATE_MANUAL) { return false; } if (block.clusterId != null) { var cluster = this.clusters[block.clusterId]; // Flying (rising / descending) clusters stay non-draggable. if (cluster && cluster.phase !== 'landed') { return false; } } return block.state === STATE_STILL || block.state === STATE_SETTLING; }; /** * The grounded contiguous stack in this column can be dragged, even if a * flying cluster or a falling spawn occupies the air above it. Only a * locked column is blocked as a whole. */ GameCore.prototype.columnAllowsDrag = function (col) { return !this.isColumnLocked(col); }; GameCore.prototype.landedClusterId = function (block) { if (!block || block.clusterId == null) { return null; } var cluster = this.clusters[block.clusterId]; if (!cluster || cluster.phase !== 'landed') { return null; } return block.clusterId; }; /** * After a swap: leaving a landed cluster clears membership; joining one * makes the block part of that rigid group. Same-cluster swaps only * exchange positions. See docs/ASSUMPTIONS.md (t1107). */ GameCore.prototype.transferLandedMembership = function (a, b) { var ca = this.landedClusterId(a); var cb = this.landedClusterId(b); if (ca === cb) { return; } // Join first so leaveCluster does not delete a cluster that still // has the incoming member. this.applyLandedMembership(b, ca); this.applyLandedMembership(a, cb); }; GameCore.prototype.applyLandedMembership = function (block, clusterId) { if (clusterId == null) { var wasGrey = block.color === COLOR_GRAY; var wasSettling = block.state === STATE_SETTLING; this.leaveCluster(block); if (wasGrey && wasSettling) { // Keep settling and recolor on its own, same remaining timer. block.state = STATE_SETTLING; } else if (wasSettling) { block.state = this.hasSupport(block) ? STATE_STILL : STATE_FALLING; } return; } if (!this.clusters[clusterId]) { return; } block.clusterId = clusterId; block.flame = false; if (block.state === STATE_STILL || block.state === STATE_SETTLING) { block.state = STATE_SETTLING; } }; /** * Test helper: stepwise-swap the block at (col, fromRow) to toRow. * Returns the moved block, or null if the column does not allow a drag. */ GameCore.prototype.swapTo = function (col, fromRow, toRow) { if (!this.columnAllowsDrag(col)) { return null; } var block = this.blockAt(col, fromRow); if (!block) { return null; } this.swapToward(block, toRow); return block; }; /** * Test helper: a compact picture of grounded/falling/flying blocks. * Bottom row is index 0. Characters: 0-4 color, g gray flying/settling, * L locked, f falling, m manual, . empty. Flying colored blocks use * their color with a marker in `flying`. */ GameCore.prototype.snapshot = function () { var grid = []; for (var r = 0; r < this.height; r++) { var row = []; for (var c = 0; c < this.width; c++) { row.push('.'); } grid.push(row); } var airborne = []; for (var i = 0; i < this.blocks.length; i++) { var block = this.blocks[i]; var ch; if (block.state === STATE_LOCKED) { ch = 'L'; } else if (block.color === COLOR_GRAY) { ch = 'g'; } else { ch = String(block.color); } if (this.isGrounded(block) || block.state === STATE_FALLING) { var row = Math.round(block.y); if (row >= 0 && row < this.height) { grid[row][block.col] = ch; } } else { airborne.push({ id: block.id, col: block.col, y: block.y, color: block.color, state: block.state, clusterId: block.clusterId, flame: block.flame, vy: block.vy }); } } var lines = []; for (var r = this.height - 1; r >= 0; r--) { lines.push(grid[r].join('')); } return { grid: grid, picture: lines.join('\n'), airborne: airborne, score: this.score, state: this.state }; }; var GameCoreAPI = { GameCore: GameCore, COLOR_GRAY: COLOR_GRAY, STATE_STILL: STATE_STILL, STATE_FALLING: STATE_FALLING, STATE_FLYING: STATE_FLYING, STATE_SETTLING: STATE_SETTLING, STATE_LOCKED: STATE_LOCKED, STATE_MANUAL: STATE_MANUAL }; if (typeof module !== 'undefined' && module.exports) { module.exports = GameCoreAPI; } else if (typeof globalThis !== 'undefined') { globalThis.GameCore = GameCore; globalThis.GameCoreAPI = GameCoreAPI; } /* * End File: * /workspace/meteors/src/gameCore.js */ /* * Start File: * /workspace/meteors/src/miniLayout.js */ 'use strict'; /** * Opponent miniature layout for online and Offline Strijd (t1125). * Wide screens: alternating left/right of the player's field, extra * rows stacked upward. Narrow screens: a row (wrapping) above the field. */ var MiniLayout = (function () { var GAP = 12; var VGAP = 8; var EDGE = 16; var MIN_TILE_FOR_SIDES = 18; var MIN_VIEWPORT_FOR_SIDES = 960; var LABEL_H = 32; function canvasSize (n, mode, availH) { n = n || 0; if (mode === 'sides' && availH && n > 0) { var rows = Math.ceil(n / 2); var maxOuter = Math.floor((availH - (rows - 1) * VGAP) / Math.max(1, rows)); var ch = Math.max(40, Math.min(104, maxOuter - LABEL_H)); var cw = Math.max(32, Math.round(ch * 10 / 13)); return { w: cw, h: ch, outerW: Math.max(cw + 8, 64), outerH: ch + LABEL_H }; } if (n >= 10) { return { w: 40, h: 52, outerW: 56, outerH: 52 + LABEL_H }; } if (n >= 6) { return { w: 56, h: 73, outerW: 68, outerH: 73 + LABEL_H }; } return { w: 80, h: 104, outerW: 90, outerH: 104 + LABEL_H }; } function sidePositions (n, fieldX, fieldY, fieldW, fieldH, mini, hudH) { var positions = []; if (n <= 0) { return positions; } var rows = Math.ceil(n / 2); var stackH = rows * mini.outerH + Math.max(0, rows - 1) * VGAP; var bottom = fieldY + fieldH; var top = bottom - stackH; if (top < hudH + 4) { top = hudH + 4; bottom = top + stackH; } for (var i = 0; i < n; i++) { var col = i % 2; var row = Math.floor(i / 2); var x = col === 0 ? fieldX - GAP - mini.outerW : fieldX + fieldW + GAP; var y = bottom - (row + 1) * mini.outerH - row * VGAP; positions.push({ index: i, side: col === 0 ? 'left' : 'right', row: row, x: x, y: y, w: mini.outerW, h: mini.outerH, canvasW: mini.w, canvasH: mini.h }); } return positions; } /** * Compute the field and mini plan for a viewport. * `n` is the number of opponents (0 = solo, no minis). */ function plan (vw, vh, n, hudH, margin) { vw = vw || 320; vh = vh || 480; n = n || 0; hudH = hudH == null ? 56 : hudH; margin = margin == null ? Math.max(6, Math.round(Math.min(vw, vh) * 0.015)) : margin; function finish (mode, tile, fieldX, fieldY, miniH, mini, positions) { return { mode: mode, tile: tile, fieldW: tile * 10, fieldH: tile * 13, fieldX: fieldX, fieldY: fieldY, miniH: miniH, mini: mini, positions: positions || [], n: n }; } if (n > 0) { var availHSide = Math.max(80, vh - hudH - margin); var probe = canvasSize(n, 'sides', availHSide); var availWSide = Math.max(80, vw - margin * 2 - 2 * (probe.outerW + GAP)); var tileSide = Math.max(14, Math.floor(Math.min(availWSide / 10, availHSide / 13))); var fieldWSide = tileSide * 10; var fieldHSide = tileSide * 13; var leftover = (vw - fieldWSide) / 2; var need = probe.outerW + GAP + EDGE; if (vw >= MIN_VIEWPORT_FOR_SIDES && leftover >= need && tileSide >= MIN_TILE_FOR_SIDES) { var fieldX = Math.floor((vw - fieldWSide) / 2); var fieldY = hudH + Math.floor((availHSide - fieldHSide) / 2); if (fieldY < hudH) { fieldY = hudH; } return finish('sides', tileSide, fieldX, fieldY, 0, probe, sidePositions(n, fieldX, fieldY, fieldWSide, fieldHSide, probe, hudH)); } } var miniTop = canvasSize(n, 'top', 0); var miniH = 0; if (n > 0) { var share = n > 6 ? 0.26 : 0.20; miniH = Math.min(n > 6 ? 180 : 150, Math.max(86, Math.round(vh * share))); } var availW = Math.max(80, vw - margin * 2); var availH = Math.max(80, vh - hudH - miniH - margin); var tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13))); var fieldW = tile * 10; var fieldH = tile * 13; var fieldX = Math.floor((vw - fieldW) / 2); var topBand = hudH + miniH; var fieldY = topBand + Math.floor((vh - topBand - fieldH - margin / 2) / 2); if (fieldY < topBand) { fieldY = topBand; } return finish('top', tile, fieldX, fieldY, miniH, miniTop, []); } var api = { GAP: GAP, VGAP: VGAP, EDGE: EDGE, MIN_TILE_FOR_SIDES: MIN_TILE_FOR_SIDES, MIN_VIEWPORT_FOR_SIDES: MIN_VIEWPORT_FOR_SIDES, LABEL_H: LABEL_H, canvasSize: canvasSize, sidePositions: sidePositions, plan: plan }; if (typeof module !== 'undefined' && module.exports) { module.exports = api; } else if (typeof globalThis !== 'undefined') { globalThis.MiniLayout = api; } return api; })(); if (typeof module !== 'undefined' && module.exports && typeof MiniLayout !== 'undefined') { module.exports = MiniLayout; } /* * End File: * /workspace/meteors/src/miniLayout.js */ /* * Start File: * /workspace/meteors/src/online.js */ 'use strict'; /** * Online play: talks to api.php (cookie session), polls lobby and game * state, and draws opponent miniatures plus flying-block tweens. * Real-time sync is not required; a 0.75 s poll is enough. */ var Online = { POLL_MS: 750, DEFAULT_MISS_CHANCE: 0.30, FLIGHT_DURATION: 1.2, configured: false, local: false, csrf: '', me: null, lobby: null, incoming: [], shotResults: [], error: '', _timer: null, _pendingShots: [], _flights: [], _lastStatus: null, onChange: null, onGameStart: null, onIncoming: null, onFinished: null, onLobbyReturn: null }; Online._headers = function (json) { var h = { 'Accept': 'application/json' }; if (json) { h['Content-Type'] = 'application/json'; } if (this.csrf) { h['X-CSRF-Token'] = this.csrf; } return h; }; Online._apply = function (data) { if (!data) { return; } if (typeof data.configured === 'boolean') { this.configured = data.configured; } if (typeof data.local === 'boolean') { this.local = data.local; } if (data.csrf) { this.csrf = data.csrf; } if (data.me !== undefined) { this.me = data.me; } if (data.lobby !== undefined) { this.lobby = data.lobby; } if (data.incoming) { this.incoming = data.incoming; } if (data.shot_results) { this.shotResults = data.shot_results; } if (data.miss_chance_default != null) { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; } if (data.flight_duration != null) { this.FLIGHT_DURATION = data.flight_duration; } if (data.error) { this.error = data.error; } else if (data.ok) { this.error = ''; } }; Online.request = function (action, body) { var self = this; var isGet = action === 'me' || action === ''; var url = 'api.php?action=' + encodeURIComponent(action || 'me'); var opts = { method: isGet && !body ? 'GET' : 'POST', credentials: 'same-origin', headers: this._headers(!!body || !isGet) }; if (opts.method === 'POST') { var payload = body ? Object.assign({ action: action }, body) : { action: action }; opts.body = JSON.stringify(payload); } return fetch(url, opts).then(function (res) { return res.json().then(function (data) { data = data || {}; if (!res.ok && !data.error) { data.error = 'De server gaf ' + res.status; data.ok = false; } self._apply(data); return data; }, function () { var fail = { ok: false, error: 'Geen geldig antwoord van de server.' }; self.error = fail.error; return fail; }); }).catch(function (err) { var fail = { ok: false, error: 'Geen verbinding met de server.' }; self.error = fail.error; return fail; }); }; Online.refresh = function () { return this.request('me'); }; Online.testLogin = function (who) { return this.request('test_login', { user: who }); }; Online.createLobby = function (planetId) { return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') }); }; Online.joinLobby = function (code, planetId) { return this.request('lobby_join', { code: code, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') }); }; Online.setPlanet = function (planetId) { return this.request('lobby_set_planet', { planet_id: planetId }); }; Online.leaveLobby = function () { return this.request('lobby_leave'); }; Online.setReady = function (ready) { return this.request('lobby_ready', { ready: !!ready }); }; Online.startGame = function () { var self = this; var prev = this.lobby && this.lobby.status; return this.request('lobby_start').then(function (data) { self._handleTransitions(prev, data); return data; }); }; Online.queueShots = function (shots) { for (var i = 0; i < shots.length; i++) { this._pendingShots.push({ client_id: String(shots[i].id), color: shots[i].color, col: shots[i].col, y: shots[i].y }); } }; Online.poll = function (opts) { opts = opts || {}; var body = {}; if (opts.snapshot) { body.snapshot = opts.snapshot; } if (opts.score != null) { body.score = opts.score; } if (opts.eliminated) { body.eliminated = true; } if (this._pendingShots.length) { body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length); } var self = this; var prevStatus = this.lobby && this.lobby.status; return this.request('poll', body).then(function (data) { self._handleTransitions(prevStatus, data); if (self.onChange) { self.onChange(self); } return data; }); }; Online._handleTransitions = function (prevStatus, data) { var lobby = this.lobby; var status = lobby && lobby.status; if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart) { this.onGameStart(lobby); } if (data && data.incoming && data.incoming.length && this.onIncoming) { this.onIncoming(data.incoming); } // Own outgoing results (immediate) and lobby-wide recent flights // (so every client can draw opponent and enemy-to-enemy arcs, t1125). var flights = []; if (data && data.shot_results && data.shot_results.length) { flights = flights.concat(data.shot_results); } if (data && data.shot_flights && data.shot_flights.length) { flights = flights.concat(data.shot_flights); } if (flights.length) { this.spawnFlights(flights, this._flightLocals); } if (status === 'finished' && prevStatus !== 'finished' && this.onFinished) { this.onFinished(lobby); } if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn) { this.onLobbyReturn(lobby); } }; Online.startPolling = function (getPayload) { this.stopPolling(); var self = this; var tick = function () { var payload = getPayload ? getPayload() : {}; self.poll(payload); }; tick(); this._timer = setInterval(tick, this.POLL_MS); }; Online.stopPolling = function () { if (this._timer) { clearInterval(this._timer); this._timer = null; } }; Online.loginUrl = function () { return 'auth.php'; }; Online.logoutUrl = function () { return 'logout.php'; }; Online.opponents = function () { if (!this.lobby || !this.lobby.players) { return []; } return this.lobby.players.filter(function (p) { return !p.is_me; }); }; Online.aliveOpponents = function () { return this.opponents().filter(function (p) { return !p.eliminated; }); }; Online.mePlayer = function () { if (!this.lobby || !this.lobby.players) { return null; } for (var i = 0; i < this.lobby.players.length; i++) { if (this.lobby.players[i].is_me) { return this.lobby.players[i]; } } return null; }; /* ---------- miniatures --------------------------------------------- */ Online.renderMinis = function (container) { if (!container) { return; } var opponents = this.opponents(); var existing = {}; var kids = container.querySelectorAll('[data-player]'); for (var i = 0; i < kids.length; i++) { existing[kids[i].getAttribute('data-player')] = kids[i]; } var seen = Object.create(null); for (var i = 0; i < opponents.length; i++) { var p = opponents[i]; seen[p.id] = true; var el = existing[p.id]; if (!el) { el = document.createElement('div'); el.className = 'mini'; el.setAttribute('data-player', p.id); el.innerHTML = '
' + '' + '
'; container.appendChild(el); } var mz = (typeof app !== 'undefined' && app.miniLayout && app.miniLayout.mini) ? app.miniLayout.mini : { w: 80, h: 104 }; var canvas = el.querySelector('canvas'); if (canvas && (canvas.width !== mz.w || canvas.height !== mz.h)) { canvas.width = mz.w; canvas.height = mz.h; } if (canvas) { canvas.style.width = mz.w + 'px'; canvas.style.height = mz.h + 'px'; } el.classList.toggle('eliminated', !!p.eliminated); el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : ''); el.querySelector('.mini-meta').textContent = p.eliminated ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : '')) : ('Punten ' + (p.score || 0)); this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet); } for (var id in existing) { if (!seen[id]) { existing[id].remove(); } } if (typeof applyMinisLayout === 'function') { applyMinisLayout(); } }; var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4']; function miniColor (planet, color) { if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex) { return planet.colors[color].hex; } return MINI_COLORS[color] || '#888'; } Online._drawMini = function (canvas, snapshot, planet) { if (!canvas) { return; } var ctx = canvas.getContext('2d'); var w = 10; var h = 13; var tw = canvas.width / w; var th = canvas.height / h; ctx.fillStyle = '#0c1020'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.strokeStyle = 'rgba(255,255,255,0.06)'; ctx.lineWidth = 1; for (var c = 0; c <= w; c++) { ctx.beginPath(); ctx.moveTo(c * tw + 0.5, 0); ctx.lineTo(c * tw + 0.5, canvas.height); ctx.stroke(); } for (var r = 0; r <= h; r++) { ctx.beginPath(); ctx.moveTo(0, r * th + 0.5); ctx.lineTo(canvas.width, r * th + 0.5); ctx.stroke(); } if (!snapshot || !snapshot.blocks) { return; } // t1123: cheap sine pulse behind blocks of nearly-full columns. if (typeof GameCore !== 'undefined' && GameCore.warnColumnsFromSnapshot) { var warns = GameCore.warnColumnsFromSnapshot(snapshot); var pulse = GameCore.columnWarnPulse(); for (var wc = 0; wc < warns.length; wc++) { if (!warns[wc]) { continue; } ctx.fillStyle = 'rgba(220, 36, 36,' + pulse + ')'; ctx.fillRect(wc * tw, 0, tw, canvas.height); } } var blocks = snapshot.blocks; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; var x = b.col * tw; var y = canvas.height - (b.y + 1) * th; if (b.state === 'locked') { ctx.fillStyle = '#3a3d4a'; } else if (b.color < 0) { ctx.fillStyle = '#5a5d66'; } else { ctx.fillStyle = miniColor(planet, b.color); } ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1); } }; Online.miniElement = function (playerId) { return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]'); }; /* ---------- flight tweens ------------------------------------------ */ function colorSpriteUrl (color, planetId) { if (color < 0) { return 'images/block-gray.png'; } var planet = null; if (typeof Planet !== 'undefined') { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); } if (planet && planet.colors && planet.colors[color] && planet.colors[color].image) { return planet.colors[color].image; } return 'images/block-gray.png'; } /** * Animate shot results. `locals` is a map of client_id → {col, y, color, * startX, startY} in viewport pixels, filled by the view just after * consumeOutgoingShots. */ Online.playerId = function () { if (typeof app !== 'undefined' && app.offline) { return 'player'; } if (this.lobby && this.lobby.players) { for (var i = 0; i < this.lobby.players.length; i++) { if (this.lobby.players[i].is_me) { return this.lobby.players[i].id; } } } return 'player'; }; /** * Classify a shot for visual treatment (t1125). * player-to-enemy, enemy-to-player, enemy-to-enemy, * player-miss, enemy-miss. */ Online.flightKind = function (fromId, targetId, miss) { var me = this.playerId(); var fromMe = !fromId || fromId === me || fromId === 'player'; if (miss) { return fromMe ? 'player-miss' : 'enemy-miss'; } if (fromMe) { return 'player-to-enemy'; } if (targetId === me || targetId === 'player') { return 'enemy-to-player'; } return 'enemy-to-enemy'; }; /** * Parabolic arc: linear in x, a rise of `height` pixels above the * chord at mid-flight (screen y grows downward, so we subtract). */ Online.arcPoint = function (start, end, u, height) { var t = u < 0 ? 0 : (u > 1 ? 1 : u); var x = start.x + (end.x - start.x) * t; var y = start.y + (end.y - start.y) * t - 4 * height * t * (1 - t); return { x: x, y: y }; }; Online.arcHeight = function (start, end) { var dx = end.x - start.x; var dy = end.y - start.y; var dist = Math.sqrt(dx * dx + dy * dy); return Math.max(48, Math.min(220, dist * 0.28)); }; Online.easeInOutCubic = function (t) { if (t < 0.5) { return 4 * t * t * t; } var u = -2 * t + 2; return 1 - (u * u * u) / 2; }; Online._miniCellSize = function (playerId) { var el = this.miniElement(playerId); var canvas = el && el.querySelector('canvas'); if (canvas) { var r = canvas.getBoundingClientRect(); return Math.max(6, r.width / 10); } return 10; }; Online._fullTileSize = function () { if (typeof app !== 'undefined' && app.tile) { return app.tile; } return 40; }; Online._miniAnchor = function (playerId, dir) { var el = this.miniElement(playerId); var canvas = el && (el.querySelector ? el.querySelector('canvas') : null); var box = canvas || el; if (!box) { return { x: window.innerWidth / 2, y: 48 }; } var r = box.getBoundingClientRect(); if (dir === 'out') { return { x: r.left + r.width / 2, y: r.top + 4 }; } return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; }; Online._fieldTop = function (col) { return this._flightStart(col); }; /** * Animate shot results. `locals` is a map of client_id → {col, y, color, * startX, startY, from_id} in viewport pixels. * * Visual-only (t1125): a parabolic arc whose scale goes from mini-cell * to full tile (or the reverse). Enemy-to-enemy arcs stay small and * are drawn behind the player's field. Delivery timing is unchanged; * a late-seen flight starts mid-arc via `age`. */ Online.spawnFlights = function (results, locals) { locals = locals || this._flightLocals || {}; var front = document.getElementById('flights'); var back = document.getElementById('flights-back') || front; if (!front) { return; } if (!this._flightSeen) { this._flightSeen = Object.create(null); } var now = performance.now(); var full = this._fullTileSize(); for (var i = 0; i < results.length; i++) { var r = results[i]; var sid = String(r.id != null ? r.id : (r.client_id || ('tmp-' + i))); if (this._flightSeen[sid]) { continue; } this._flightSeen[sid] = now; var meta = locals[r.client_id] || locals[sid] || {}; var fromId = r.from_id || r.from_user || meta.from_id || null; var targetId = r.target_id != null ? r.target_id : r.to_user; var miss = !!r.miss; var kind = this.flightKind(fromId, targetId, miss); var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000; if (r.age != null && isFinite(r.age) && r.age * 1000 >= duration) { continue; } var start; if (meta.startX != null && isFinite(meta.startX)) { start = { x: meta.startX, y: meta.startY }; } else if (kind === 'player-to-enemy' || kind === 'player-miss') { start = this._flightStart(meta.col != null ? meta.col : r.col); } else { start = this._miniAnchor(fromId, 'out'); } var end; if (miss) { end = this._missEnd(start, kind === 'enemy-miss'); } else if (kind === 'enemy-to-player') { end = this._fieldTop(null); } else { end = this._targetEnd(targetId, start); } var startScale; var endScale; var mini = this._miniCellSize(fromId || targetId) / full; if (mini < 0.12) { mini = 0.2; } if (kind === 'player-to-enemy') { startScale = 1; endScale = mini; } else if (kind === 'enemy-to-player') { startScale = mini; endScale = 1; } else if (kind === 'enemy-to-enemy') { startScale = mini; endScale = mini; } else if (kind === 'enemy-miss') { startScale = mini; endScale = 0; } else { startScale = 1; endScale = 0; } var layer = (kind === 'enemy-to-enemy' && back) ? back : front; var el = document.createElement('img'); el.src = colorSpriteUrl(r.color != null ? r.color : meta.color); el.alt = ''; el.className = 'flight' + (kind === 'enemy-to-enemy' ? ' flight-behind' : ''); el.style.width = full + 'px'; el.style.height = full + 'px'; layer.appendChild(el); var t0 = now; if (r.age != null && isFinite(r.age) && r.age > 0) { var u0 = Math.min(0.95, (r.age * 1000) / duration); t0 = now - u0 * duration; } var height = miss ? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35)) : this.arcHeight(start, end); this._flights.push({ el: el, start: start, end: end, ctrl: miss ? this._missCtrl(start, end) : null, height: height, t0: t0, duration: duration, spin: (Math.random() * 2 - 1) * 720, miss: miss, kind: kind, startScale: startScale, endScale: endScale, angle: Math.random() * 360, id: sid }); } this._flightLocals = {}; }; Online.rememberFlightLocal = function (shot, startX, startY) { if (!this._flightLocals) { this._flightLocals = {}; } this._flightLocals[String(shot.id)] = { col: shot.col, y: shot.y, color: shot.color, startX: startX, startY: startY, from_id: shot.from_id }; }; Online._flightStart = function (col) { var appRef = typeof app !== 'undefined' ? app : null; if (appRef && appRef.scene && appRef.scene.canvas) { var canvas = appRef.scene.canvas; var rect = canvas.getBoundingClientRect(); var c = col == null ? 4.5 : col; return { x: rect.left + (c + 0.5) * (rect.width / 10), y: rect.top + 4 }; } var field = document.querySelector('canvas'); if (field) { var rect = field.getBoundingClientRect(); return { x: rect.left + rect.width / 2, y: rect.top }; } return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 }; }; Online._targetEnd = function (targetId, start) { var el = targetId && this.miniElement(targetId); if (el) { var canvas = el.querySelector('canvas') || el; var r = canvas.getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; } return { x: start.x + (Math.random() - 0.5) * 80, y: 40 }; }; Online._missEnd = function (start, fromMini) { var w = window.innerWidth || 800; var outward; if (start.x < w * 0.4) { outward = -(80 + Math.random() * w * 0.25); } else if (start.x > w * 0.6) { outward = (80 + Math.random() * w * 0.25); } else { outward = (Math.random() * 2 - 1) * w * 0.35; } var lift = fromMini ? (80 + Math.random() * 160) : (120 + Math.random() * 220); return { x: start.x + outward, y: start.y - lift }; }; Online._missCtrl = function (start, end) { return { x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160, y: Math.min(start.y, end.y) - 40 - Math.random() * 80 }; }; Online._hitCtrl = function (start, end) { return { x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40, y: (start.y + end.y) / 2 - 30 }; }; Online.tickFlights = function (now) { now = now || performance.now(); var leftover = []; for (var i = 0; i < this._flights.length; i++) { var f = this._flights[i]; var raw = (now - f.t0) / f.duration; if (raw >= 1) { if (f.el && f.el.parentNode) { f.el.parentNode.removeChild(f.el); } continue; } if (raw < 0) { raw = 0; } var u = this.easeInOutCubic(raw); var x, y; if (f.miss && f.ctrl) { var e = raw * raw; var mt = 1 - e; x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x; y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y; } else { var pt = this.arcPoint(f.start, f.end, u, f.height || 80); x = pt.x; y = pt.y; } var scale = f.startScale + (f.endScale - f.startScale) * u; if (f.miss) { var fadeU = raw * raw; scale = f.startScale * (1 - fadeU); } var angle = f.angle + f.spin * raw; f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate(' + angle + 'deg) scale(' + scale + ')'; f.el.style.opacity = f.miss ? String(Math.max(0, 1 - raw * raw)) : '1'; leftover.push(f); } this._flights = leftover; if (this._flightSeen) { var cutoff = now - 8000; var ids = Object.keys(this._flightSeen); for (var k = 0; k < ids.length; k++) { if (this._flightSeen[ids[k]] < cutoff) { delete this._flightSeen[ids[k]]; } } } }; Online.clearFlights = function () { for (var i = 0; i < this._flights.length; i++) { var el = this._flights[i].el; if (el && el.parentNode) { el.parentNode.removeChild(el); } } this._flights = []; this._flightLocals = {}; this._flightSeen = Object.create(null); }; if (typeof globalThis !== 'undefined') { globalThis.Online = Online; } if (typeof module !== 'undefined' && module.exports) { module.exports = Online; } /* * End File: * /workspace/meteors/src/online.js */ /* * Start File: * /workspace/meteors/src/offline.js */ 'use strict'; /** * Offline Strijd: a client-side single-player mode that plays like * multiplayer (shots, miss chance, opponent minis) against local bots * (t1119). Pure simulation — no server. */ var Offline = (function () { var BOT_INTERVAL = 0.5; var SKILL_START = 0.05; var SKILL_STEP = 0.01; var SKILL_CAP = 1; var FLIGHT_DURATION = 1.2; var ROUND_WON_DELAY = 1.5; /** * N opponents for N−1 rounds when N >= 2; 1 opponent for 1 round. * Documented in docs/ASSUMPTIONS.md (t1119). */ function roundsAtOpponentCount (n) { if (n <= 1) { return 1; } return n - 1; } function skillForRound (round) { var r = Math.max(1, Math.floor(Number(round) || 1)); var pct = 5 + (r - 1); if (pct > 100) { pct = 100; } return pct / 100; } function scheduleForRound (round) { var r = Math.max(1, Math.floor(Number(round) || 1)); var cursor = 1; var n = 1; for (;;) { var count = roundsAtOpponentCount(n); if (r < cursor + count) { return { round: r, opponents: n, skill: skillForRound(r), roundsAtLevel: count, indexInLevel: r - cursor + 1 }; } cursor += count; n++; if (n > 10000) { return { round: r, opponents: n, skill: SKILL_CAP, roundsAtLevel: roundsAtOpponentCount(n), indexInLevel: 1 }; } } } function GameCoreCtor () { if (typeof GameCore !== 'undefined') { return GameCore; } if (typeof module !== 'undefined') { return require('./gameCore.js').GameCore; } return null; } function PlanetMod () { if (typeof Planet !== 'undefined') { return Planet; } if (typeof module !== 'undefined') { return require('./planet.js'); } return null; } /** * Integer-row colour grid of grounded (still / settling / locked) * blocks, including greys (color < 0) so a swap can shift them. */ function snapshotGrid (core) { var width = core.width; var height = core.height; var grid = []; for (var c = 0; c < width; c++) { grid[c] = []; for (var r = 0; r < height; r++) { grid[c][r] = null; } } for (var i = 0; i < core.blocks.length; i++) { var b = core.blocks[i]; if (!core.isGrounded(b)) { continue; } var row = Math.round(b.y); if (row < 0 || row >= height || b.col < 0 || b.col >= width) { continue; } if (Math.abs(b.y - row) > 0.2) { continue; } grid[b.col][row] = b.color; } return grid; } function cloneGrid (grid) { var out = []; for (var c = 0; c < grid.length; c++) { out[c] = grid[c].slice(); } return out; } /** * Apply swapToward's net result: the block at fromRow moves to toRow, * and the blocks it passed through each shift one cell toward fromRow. */ function applyColumnMove (grid, col, fromRow, toRow) { if (fromRow === toRow) { return; } var moving = grid[col][fromRow]; if (toRow > fromRow) { for (var y = fromRow; y < toRow; y++) { grid[col][y] = grid[col][y + 1]; } grid[col][toRow] = moving; } else { for (var y = fromRow; y > toRow; y--) { grid[col][y] = grid[col][y - 1]; } grid[col][toRow] = moving; } } function hasMatch (grid, width, height) { var c, r, run, prev; for (r = 0; r < height; r++) { run = 0; prev = null; for (c = 0; c < width; c++) { var color = grid[c][r]; if (color != null && color >= 0 && color === prev) { run++; if (run >= 3) { return true; } } else { run = (color != null && color >= 0) ? 1 : 0; prev = (color != null && color >= 0) ? color : null; } } } for (c = 0; c < width; c++) { run = 0; prev = null; for (r = 0; r < height; r++) { var color = grid[c][r]; if (color != null && color >= 0 && color === prev) { run++; if (run >= 3) { return true; } } else { run = (color != null && color >= 0) ? 1 : 0; prev = (color != null && color >= 0) ? color : null; } } } return false; } /** * Contiguous segments of draggable, nearly-integer-y blocks in a * column. Gaps break a segment the same way swapToward stops at gaps. */ function contiguousSegments (core, col) { if (!core.columnAllowsDrag(col)) { return []; } var list = core.blocksInColumn(col).filter(function (b) { return core.isDraggableBlock(b); }); list.sort(function (a, b) { return a.y - b.y; }); var segs = []; var cur = []; for (var i = 0; i < list.length; i++) { var y = list[i].y; if (Math.abs(y - Math.round(y)) > 0.15) { if (cur.length) { segs.push(cur); cur = []; } continue; } if (cur.length && Math.abs(y - (cur[cur.length - 1].y + 1)) > 0.15) { segs.push(cur); cur = [list[i]]; } else { cur.push(list[i]); } } if (cur.length) { segs.push(cur); } return segs; } /** * The shortest vertical move that would create a 3+ match, or null. * Ties break on lowest column, then lowest fromY, then lowest toY. */ function findBotMove (core) { var grid = snapshotGrid(core); if (hasMatch(grid, core.width, core.height)) { return null; } var best = null; for (var col = 0; col < core.width; col++) { var segs = contiguousSegments(core, col); for (var s = 0; s < segs.length; s++) { var seg = segs[s]; if (seg.length < 2) { continue; } for (var i = 0; i < seg.length; i++) { var fromY = Math.round(seg[i].y); for (var j = 0; j < seg.length; j++) { if (i === j) { continue; } var toY = Math.round(seg[j].y); var dist = Math.abs(toY - fromY); if (best && dist > best.dist) { continue; } var trial = cloneGrid(grid); applyColumnMove(trial, col, fromY, toY); if (!hasMatch(trial, core.width, core.height)) { continue; } var cand = { col: col, fromY: fromY, toY: toY, dist: dist, blockId: seg[i].id }; if (!best || dist < best.dist || (dist === best.dist && col < best.col) || (dist === best.dist && col === best.col && fromY < best.fromY) || (dist === best.dist && col === best.col && fromY === best.fromY && toY < best.toY)) { best = cand; } } } } } return best; } function executeBotMove (core, move) { if (!core || !move) { return false; } var list = core.blocksInColumn(move.col); var block = null; for (var i = 0; i < list.length; i++) { if (move.blockId != null && list[i].id === move.blockId) { block = list[i]; break; } if (Math.abs(list[i].y - move.fromY) < 0.2) { block = list[i]; } } if (!block || !core.isDraggableBlock(block)) { return false; } core.swapToward(block, move.toY); return true; } /** * One AI tick. `rng` is a () => [0,1) function. Success if roll < skill. * At skill 0 the bot never moves; at skill 1 it always looks for a move. */ function tryBotRoll (core, skill, rng) { rng = rng || Math.random; var roll = rng(); if (!(roll < skill)) { return { rolled: true, success: false, moved: false, roll: roll, move: null }; } var move = findBotMove(core); if (!move) { return { rolled: true, success: true, moved: false, roll: roll, move: null }; } var ok = executeBotMove(core, move); return { rolled: true, success: true, moved: !!ok, roll: roll, move: move }; } function pickPlanet (rng, P) { var all = P.allPlanets(); if (!all.length) { return P.defaultPlanet(); } var i = Math.floor(rng() * all.length) % all.length; return all[i]; } function OfflineBattle (opts) { opts = opts || {}; var P = PlanetMod(); this.playerPlanet = opts.playerPlanet || (P && P.defaultPlanet()); this.rng = opts.rng || Math.random; this.round = opts.round || 1; this.schedule = scheduleForRound(this.round); this.clock = 0; this.state = 'playing'; this.pending = []; this.flightResults = []; this.shotLocals = []; this.bots = []; this.playerId = 'player'; this._initBots(); } OfflineBattle.prototype._initBots = function () { var P = PlanetMod(); var Ctor = GameCoreCtor(); var n = this.schedule.opponents; this.bots = []; for (var i = 0; i < n; i++) { var planet = pickPlanet(this.rng, P); var miss = P.missChance(planet); var core = new Ctor(planet, this.rng, miss); this.bots.push({ id: 'bot-' + (i + 1), name: 'Bot ' + (i + 1), planet: planet, core: core, eliminated: false, score: 0, aiAcc: 0 }); } }; OfflineBattle.prototype.aliveBots = function () { var out = []; for (var i = 0; i < this.bots.length; i++) { if (!this.bots[i].eliminated && this.bots[i].core && this.bots[i].core.state !== 'gameover') { out.push(this.bots[i]); } } return out; }; OfflineBattle.prototype.coreFor = function (id, playerCore) { if (id === this.playerId) { return playerCore; } for (var i = 0; i < this.bots.length; i++) { if (this.bots[i].id === id) { return this.bots[i].core; } } return null; }; OfflineBattle.prototype._targetsFor = function (fromId, playerCore) { var targets = []; if (fromId !== this.playerId && playerCore && playerCore.state === 'playing') { targets.push({ id: this.playerId, core: playerCore }); } for (var i = 0; i < this.bots.length; i++) { var bot = this.bots[i]; if (bot.id === fromId || bot.eliminated) { continue; } if (bot.core && bot.core.state === 'playing') { targets.push({ id: bot.id, core: bot.core }); } } return targets; }; OfflineBattle.prototype._dispatchShots = function (fromId, core, planet, playerCore) { if (!core || !core.consumeOutgoingShots) { return; } var shots = core.consumeOutgoingShots(); if (!shots.length) { return; } var P = PlanetMod(); var missChance = (P && planet) ? P.missChance(planet) : 0.30; var targets = this._targetsFor(fromId, playerCore); for (var i = 0; i < shots.length; i++) { var shot = shots[i]; var miss = targets.length === 0 || this.rng() < missChance; var target = null; if (!miss) { var idx = Math.floor(this.rng() * targets.length) % targets.length; target = targets[idx]; } var clientId = fromId + '-' + shot.id + '-' + this.clock; var result = { client_id: clientId, miss: miss, target_id: target ? target.id : null, color: shot.color, flight_duration: FLIGHT_DURATION, from_id: fromId, col: shot.col, y: shot.y }; this.flightResults.push(result); this.shotLocals.push({ client_id: clientId, col: shot.col, y: shot.y, color: shot.color, from_id: fromId }); if (!miss && target) { this.pending.push({ at: this.clock + FLIGHT_DURATION, targetId: target.id, color: shot.color, fromId: fromId }); } } }; OfflineBattle.prototype._deliver = function (playerCore) { var keep = []; for (var i = 0; i < this.pending.length; i++) { var ev = this.pending[i]; if (this.clock + 1e-9 < ev.at) { keep.push(ev); continue; } var core = this.coreFor(ev.targetId, playerCore); if (core && core.state === 'playing' && core.ingestGarbage) { core.ingestGarbage(); } } this.pending = keep; }; OfflineBattle.prototype.tick = function (dt, playerCore) { this.flightResults = []; this.shotLocals = []; if (this.state !== 'playing') { return { flights: [], locals: [] }; } if (dt < 0) { dt = 0; } this.clock += dt; var skill = this.schedule.skill; for (var i = 0; i < this.bots.length; i++) { var bot = this.bots[i]; if (bot.eliminated) { continue; } if (bot.core.state === 'gameover') { bot.eliminated = true; bot.score = bot.core.score; continue; } bot.core.tick(dt); bot.score = bot.core.score; bot.aiAcc += dt; while (bot.aiAcc >= BOT_INTERVAL) { bot.aiAcc -= BOT_INTERVAL; if (bot.core.state === 'playing' && !bot.core.drag) { tryBotRoll(bot.core, skill, this.rng); } } } this._dispatchShots(this.playerId, playerCore, this.playerPlanet, playerCore); for (var i = 0; i < this.bots.length; i++) { var bot = this.bots[i]; if (bot.eliminated) { continue; } this._dispatchShots(bot.id, bot.core, bot.planet, playerCore); } this._deliver(playerCore); for (var i = 0; i < this.bots.length; i++) { if (this.bots[i].core && this.bots[i].core.state === 'gameover') { this.bots[i].eliminated = true; this.bots[i].score = this.bots[i].core.score; } } if (playerCore && playerCore.state === 'gameover') { this.state = 'lost'; } else if (this.aliveBots().length === 0 && this.bots.length > 0) { this.state = 'round_won'; } return { flights: this.flightResults, locals: this.shotLocals }; }; /** * Start the next round (fresh bots, new skill and opponent count). * The caller must also give the player a fresh GameCore. */ OfflineBattle.prototype.advanceRound = function () { this.round += 1; this.schedule = scheduleForRound(this.round); this.state = 'playing'; this.pending = []; this.flightResults = []; this.shotLocals = []; this.clock = 0; this._initBots(); return this.schedule; }; function createBattle (opts) { return new OfflineBattle(opts); } var api = { BOT_INTERVAL: BOT_INTERVAL, SKILL_START: SKILL_START, SKILL_STEP: SKILL_STEP, SKILL_CAP: SKILL_CAP, FLIGHT_DURATION: FLIGHT_DURATION, ROUND_WON_DELAY: ROUND_WON_DELAY, roundsAtOpponentCount: roundsAtOpponentCount, skillForRound: skillForRound, scheduleForRound: scheduleForRound, findBotMove: findBotMove, tryBotRoll: tryBotRoll, executeBotMove: executeBotMove, snapshotGrid: snapshotGrid, applyColumnMove: applyColumnMove, hasMatch: hasMatch, createBattle: createBattle, OfflineBattle: OfflineBattle }; if (typeof module !== 'undefined' && module.exports) { module.exports = api; } else if (typeof globalThis !== 'undefined') { globalThis.Offline = api; } return api; })(); if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undefined') { module.exports = Offline; } /* * End File: * /workspace/meteors/src/offline.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. Online play (stage 2) is wired * through Online (src/online.js) and the same GameCore. Offline Strijd * (t1119) uses Offline (src/offline.js) against local bots. */ function planetImages () { var list = [ { 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' }, { name: 'columnWarn', url: 'images/column-warn.png' }, // Keep the original Terra placeholders as aliases (Tim may still have them). { 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' } ]; var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []); for (var i = 0; i < planets.length; i++) { var pl = planets[i]; for (var c = 0; c < pl.colors.length; c++) { list.push({ name: Planet.spriteKey(pl, c), url: pl.colors[c].image }); } } return list; } var IMAGES = planetImages(); 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, pointerType: null, activeTouchId: null, debugDrag: false, debugPhysics: false, gameOverShown: false, selectTween: null, online: false, eliminatedReported: false, spectating: false, miniH: 0, selectedPlanetId: 'terra', planetSelectContext: 'solo', offline: false, battle: null, swapTweens: null, columnWarn: null, warnClock: 0, miniAcc: 0, offlineResultShown: false, roundWonDelay: 0, roundWonHandled: false }; window.onload = function () { app.debugDrag = isDragDebugEnabled(); app.debugPhysics = isPhysicsDebugEnabled(); 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); } }); bindOnlineUi(); bindOfflineUi(); bindPlanetSelect(); restoreSelectedPlanet(); }; function onPlay () { if (app.mode === 'playing') { return; } openPlanetSelect('solo'); } function startPlay (opts) { opts = opts || {}; hideEl('menu'); hideEl('game-over'); hideEl('online-panel'); hideEl('spectator'); hideEl('podium'); hideEl('planet-select'); hideEl('offline-result'); showEl('hud'); var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod; app.planet = opts.planet || planetMod.planetById(selectedPlanetId()); var miss = opts.missChance; if (typeof miss !== 'number' || !isFinite(miss)) { miss = planetMod.missChance(app.planet); } app.core = new GameCore(app.planet, Math.random, miss); if (app.debugPhysics) { app.core.debugInvariants = true; } app.mode = 'playing'; app.online = !!opts.online; app.offline = !!opts.offline; app.gameOverShown = false; app.eliminatedReported = false; app.spectating = false; app.sprites = Object.create(null); app.flames = Object.create(null); app.cells = []; app.pointerId = null; app.selectTween = null; app.swapTweens = Object.create(null); app.columnWarn = []; app.warnClock = 0; app.miniAcc = 1; // draw minis on the first frame app.offlineResultShown = false; if (!opts.keepBattle) { app.roundWonDelay = 0; app.roundWonHandled = false; } if (app.offline && !opts.keepBattle && typeof Offline !== 'undefined') { app.battle = Offline.createBattle({ playerPlanet: app.planet, rng: Math.random, round: opts.round || 1 }); } layout(); if (app.scene) { app.scene.destroy(); app.scene = null; } 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()); if (!app.spectating) { bindPointer(app.scene.canvas); } refreshHud(); if (app.online || app.offline) { showEl('minis'); } else { hideEl('minis'); } buildColumnWarn(); refreshOfflineHud(); refreshChainIndicator(); } function teardownPlay () { unbindPointer(); if (app.scene) { app.scene.destroy(); app.scene = null; } app.manager = null; app.core = null; app.sprites = Object.create(null); app.flames = Object.create(null); app.cells = []; app.selectTween = null; app.swapTweens = Object.create(null); app.columnWarn = []; app.pointerId = null; app.gameOverShown = false; hideEl('hud'); hideEl('game-over'); hideEl('spectator'); hideEl('minis'); hideEl('offline-result'); hideOfflineHud(); hideChainIndicator(); if (typeof Online !== 'undefined') { Online.clearFlights(); } if (!app._keepBattleOnTeardown) { app.battle = null; app.offline = false; } app._keepBattleOnTeardown = false; } function returnToMenu () { if (app.online && typeof Online !== 'undefined') { // Online matches do not dump you back to the solo menu: // elimination becomes spectating; a finished match shows the podium. return; } teardownPlay(); app.mode = 'menu'; app.online = false; app.offline = false; app.battle = null; hideEl('planet-select'); 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 opponentCount () { if (app.offline && app.battle && app.battle.bots) { return app.battle.bots.length; } if (app.online && typeof Online !== 'undefined' && Online.opponents) { return Online.opponents().length; } return 0; } function currentMiniSize () { if (app.miniLayout && app.miniLayout.mini) { return { w: app.miniLayout.mini.w, h: app.miniLayout.mini.h }; } var n = opponentCount(); var mode = (app.miniLayout && app.miniLayout.mode) || 'top'; if (typeof MiniLayout !== 'undefined' && MiniLayout.canvasSize) { return MiniLayout.canvasSize(n, mode, 0); } if (n >= 10) { return { w: 40, h: 52 }; } if (n >= 6) { return { w: 56, h: 73 }; } return { w: 80, h: 104 }; } function applyMinisContainer (plan) { var minis = document.getElementById('minis'); if (!minis) { return; } var n = plan ? plan.n : 0; minis.classList.toggle('crowded', n > 5); if (!plan || n === 0 || plan.mode !== 'sides') { minis.classList.remove('sides'); minis.style.top = (app.hudH || 56) + 'px'; minis.style.maxHeight = (plan && plan.miniH ? plan.miniH : 0) + 'px'; minis.style.bottom = ''; minis.style.left = ''; minis.style.right = ''; var kids = minis.querySelectorAll('.mini'); for (var i = 0; i < kids.length; i++) { kids[i].style.left = ''; kids[i].style.top = ''; kids[i].style.width = ''; kids[i].style.position = ''; } return; } minis.classList.add('sides'); minis.style.top = '0'; minis.style.bottom = '0'; minis.style.left = '0'; minis.style.right = '0'; minis.style.maxHeight = 'none'; } function applyMinisLayout () { var plan = app.miniLayout; var minis = document.getElementById('minis'); if (!minis) { return; } applyMinisContainer(plan); if (!plan || plan.mode !== 'sides') { return; } var positions = plan.positions || []; var kids = minis.querySelectorAll('.mini'); for (var i = 0; i < positions.length && i < kids.length; i++) { var p = positions[i]; var el = kids[i]; el.style.position = 'absolute'; el.style.left = p.x + 'px'; el.style.top = p.y + 'px'; el.style.width = p.w + 'px'; var canvas = el.querySelector('canvas'); if (canvas) { canvas.style.width = p.canvasW + 'px'; canvas.style.height = p.canvasH + 'px'; } } } function applyFlightsBackClip () { var back = document.getElementById('flights-back'); if (!back) { return; } var x = app.fieldX || 0; var y = app.fieldY || 0; var w = app.fieldW || 0; var h = app.fieldH || 0; if (!w || !h) { back.style.clipPath = ''; return; } // Even-odd polygon: full viewport with a hole over the player's field, // so enemy-to-enemy arcs travel behind the field (t1125). back.style.clipPath = 'polygon(evenodd, 0 0, 100% 0, 100% 100%, 0 100%, 0 0, ' + x + 'px ' + y + 'px, ' + (x + w) + 'px ' + y + 'px, ' + (x + w) + 'px ' + (y + h) + 'px, ' + x + 'px ' + (y + h) + 'px, ' + x + 'px ' + y + 'px)'; } function layoutIfNeeded () { if (app.core && app.core.drag) { return; } var vw = window.innerWidth || 320; var vh = window.innerHeight || 480; var n = (app.online || app.offline) ? opponentCount() : 0; if (app._layoutVw === vw && app._layoutVh === vh && app._layoutN === n && app.scene && app.tile) { return; } layout(); } function layout () { if (app.core && app.core.drag) { return; } var vw = window.innerWidth || 320; var vh = window.innerHeight || 480; var n = (app.online || app.offline) ? opponentCount() : 0; app._layoutVw = vw; app._layoutVh = vh; app._layoutN = n; 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 plan; if (typeof MiniLayout !== 'undefined' && MiniLayout.plan) { plan = MiniLayout.plan(vw, vh, n, app.hudH, margin); } else { plan = { mode: 'top', tile: 14, fieldW: 140, fieldH: 182, fieldX: Math.floor((vw - 140) / 2), fieldY: app.hudH, miniH: n > 0 ? 100 : 0, mini: { w: 80, h: 104 }, positions: [], n: n }; } app.miniLayout = plan; app.miniH = plan.miniH; app.tile = plan.tile; app.fieldW = plan.fieldW; app.fieldH = plan.fieldH; app.fieldX = plan.fieldX; app.fieldY = plan.fieldY; applyMinisLayout(); applyFlightsBackClip(); 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; } var key = Planet.spriteKey(app.planet, block.color); return game.images[key] || game.images.gray; } function syncSprites (dt) { if (!app.core || !app.scene) { return; } dt = dt || 0; consumeAndStartSwapTweens(); advanceSwapTweens(dt); 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, blockVisualY(block)); 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; // 3x as large (length and width, t1110). Keep the top of the // flame at the same overlap into the block so the extra length // extends downward under the rocket. var flameW = t * 0.85 * 3; var flameH = t * 0.85 * 3; var origCenter = app.fieldH - block.y * t + t * 0.15; var origTop = origCenter - (t * 0.85) / 2; flame.transform.position.x = block.col * t + t / 2; flame.transform.position.y = origTop + flameH / 2; flame.transform.size = { x: flameW, y: flameH }; } 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; } /* ---------- visual-only swap tween (t1121) -------------------------- */ function swapTweenSpec () { if (typeof Easing !== 'undefined' && Easing.SWAP_TWEEN) { return Easing.SWAP_TWEEN; } return { duration: 0.100, ease: null }; } function swapEase (u) { if (typeof Easing !== 'undefined' && Easing.easeOutCubic) { return Easing.easeOutCubic(u); } var v = 1 - Math.max(0, Math.min(1, u)); return 1 - v * v * v; } function tweenVisualY (tw) { var u = tw.duration > 0 ? Math.min(1, tw.age / tw.duration) : 1; return tw.fromY + (tw.toY - tw.fromY) * swapEase(u); } /** * Consume GameCore swap events. The currently dragged block is skipped * (it follows the pointer). A block that is mid-tween and is swapped * again restarts from its current visual y, so rapid swaps chain * smoothly without snapping. */ function consumeAndStartSwapTweens () { if (!app.core || !app.core.consumeSwapEvents) { return; } if (!app.swapTweens) { app.swapTweens = Object.create(null); } var ev = app.core.consumeSwapEvents(); if (!ev.length) { return; } var dragId = app.core.drag && app.core.drag.blockId; var duration = swapTweenSpec().duration; for (var i = 0; i < ev.length; i++) { var e = ev[i]; if (e.id === dragId) { delete app.swapTweens[e.id]; continue; } var fromY = e.fromY; var existing = app.swapTweens[e.id]; if (existing) { fromY = tweenVisualY(existing); } app.swapTweens[e.id] = { fromY: fromY, toY: e.toY, age: 0, duration: duration }; } } function advanceSwapTweens (dt) { if (!app.swapTweens) { return; } var ids = Object.keys(app.swapTweens); for (var i = 0; i < ids.length; i++) { var tw = app.swapTweens[ids[i]]; tw.age += dt; if (tw.age >= tw.duration) { delete app.swapTweens[ids[i]]; } } } function blockVisualY (block) { if (!app.swapTweens) { return block.y; } var dragId = app.core && app.core.drag && app.core.drag.blockId; if (block.id === dragId) { return block.y; } var tw = app.swapTweens[block.id]; if (!tw) { return block.y; } return tweenVisualY(tw); } 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; document.getElementById('planet-stats').textContent = Planet.formatStats(planet); } 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; } // Never resize the canvas mid-drag: a URL-bar hide would move the // field under the finger and jump the target row. Also skip work // when the viewport has not actually changed. if (!(app.core && app.core.drag)) { layoutIfNeeded(); } 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); if (app.offline && app.battle) { tickOffline(dt); } updateSelectTween(dt); syncSprites(dt); updateColumnWarn(dt); refreshHud(); refreshOfflineHud(); refreshChainIndicator(); tickOnline(dt); if (app.debugPhysics) { logPhysicsDebug(); } if (app.core.state === 'gameover' && !app.gameOverShown) { app.gameOverShown = true; app.lastScore = app.core.score; document.getElementById('go-score').textContent = String(app.lastScore); if (app.online) { onOnlineEliminated(); } else if (app.offline) { /* Offline result is shown from tickOffline. */ } else { showEl('game-over'); } } if (!app.online && !app.offline && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY) { returnToMenu(); } } /* ---------- pointer input (mouse + touch) --------------------------- */ /* * Mouse uses Pointer Events. Touch uses Touch Events as the authority: * on a real phone, pointer clientX/Y can disagree with the visual * finger (zoomed visual viewport, gesture takeover, capture cancel) * while changedTouches stays correct. When a touch is active, pointer * move/up/cancel are ignored so a poisoned pointer coordinate cannot * walk the block to the top or bottom of the stack (t1106). * * After a down we also listen on the document, 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 call setPointerCapture: on mobile * that is often cancelled when the browser takes the gesture, which * would fire pointercancel mid-drag. * * A non-passive document touchstart/touchmove preventDefault during * play stops scrolling, rubber-banding and the pointercancel that * follows. pointercancel / touchcancel end the drag without launch. * * ?debug=drag (or localStorage meteors-debug-drag=1) shows an overlay. */ var boundCanvas = null; var windowListening = false; var touchListening = false; var lastDragDebug = null; function isDragDebugEnabled () { try { var q = window.location && window.location.search; if (q && /(?:\?|&)debug=drag(?:&|$)/.test(q)) { return true; } if (window.localStorage && window.localStorage.getItem('meteors-debug-drag') === '1') { return true; } } catch (err) { /* ignore */ } return false; } /** ?debug, ?debug=physics, ?debug=drag, or localStorage meteors-debug=1. */ function isPhysicsDebugEnabled () { try { var q = window.location && window.location.search; if (q && /(?:\?|&)debug(?:=|&|$)/.test(q)) { return true; } if (window.localStorage && (window.localStorage.getItem('meteors-debug') === '1' || window.localStorage.getItem('meteors-debug-drag') === '1')) { return true; } } catch (err) { /* ignore */ } return false; } function eventClient (e) { var t = null; if (e.changedTouches && e.changedTouches.length) { t = e.changedTouches[0]; } else if (e.touches && e.touches.length) { t = e.touches[0]; } if (t) { return { x: t.clientX, y: t.clientY, id: t.identifier, src: 'touch' }; } if (e.clientX != null && e.clientY != null) { return { x: e.clientX, y: e.clientY, id: e.pointerId, src: 'pointer' }; } return null; } function addWindowPointer () { if (windowListening) { return; } window.addEventListener('pointermove', onPointerMove, { capture: true, passive: false }); window.addEventListener('pointerup', onPointerUp, { capture: true, passive: false }); window.addEventListener('pointercancel', onPointerCancel, { 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', onPointerCancel, { capture: true }); windowListening = false; } function addTouchListeners () { if (touchListening) { return; } var opts = { capture: true, passive: false }; document.addEventListener('touchstart', onTouchStart, opts); document.addEventListener('touchmove', onTouchMove, opts); document.addEventListener('touchend', onTouchEnd, opts); document.addEventListener('touchcancel', onTouchCancel, opts); touchListening = true; } function removeTouchListeners () { if (!touchListening) { return; } var opts = { capture: true }; document.removeEventListener('touchstart', onTouchStart, opts); document.removeEventListener('touchmove', onTouchMove, opts); document.removeEventListener('touchend', onTouchEnd, opts); document.removeEventListener('touchcancel', onTouchCancel, opts); touchListening = false; } function bindPointer (canvas) { unbindPointer(); boundCanvas = canvas; canvas.addEventListener('pointerdown', onPointerDown, { passive: false }); canvas.style.touchAction = 'none'; canvas.style.position = 'fixed'; canvas.style.cursor = 'pointer'; canvas.style.webkitUserSelect = 'none'; canvas.style.userSelect = 'none'; addTouchListeners(); if (app.debugDrag) { ensureDragDebugOverlay(); } } function unbindPointer () { removeWindowPointer(); removeTouchListeners(); if (boundCanvas) { boundCanvas.removeEventListener('pointerdown', onPointerDown); } boundCanvas = null; app.pointerId = null; app.pointerType = null; app.activeTouchId = 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 pt = eventClient(e); if (!pt) { return null; } // Map through the CSS box only. Using canvas.width / app.tile would // scale the pointer by the backing-store ratio whenever that differs // from the layout size (high-DPR devices), so a short finger move // would look like a long swipe. var width = Planet.FIELD_WIDTH; var height = Planet.FIELD_HEIGHT; var col = ((pt.x - rect.left) / rect.width) * width; var fieldY = (1 - (pt.y - rect.top) / rect.height) * height; return { col: col, y: fieldY, src: pt.src, clientX: pt.x, clientY: pt.y, rect: rect }; } function playingForDrag () { return app.core && app.core.state === 'playing'; } function startDragFromEvent (e) { var pos = fieldFromEvent(e); if (!pos) { return; } if (app.core.drag) { app.core.moveDrag(pos.y); logDragDebug(e, pos, 'move-already'); return; } if (app.core.beginDrag(pos.col, pos.y) && app.core.drag) { startPressTween(app.core.drag.blockId); } logDragDebug(e, pos, 'down'); } function moveDragFromEvent (e) { if (!app.core || !app.core.drag) { return; } var pos = fieldFromEvent(e); if (pos) { app.core.moveDrag(pos.y); } logDragDebug(e, pos, 'move'); } function finishDrag (opts) { opts = opts || {}; app.pointerId = null; app.pointerType = null; app.activeTouchId = null; removeWindowPointer(); if (boundCanvas) { try { if (opts.pointerId != null && boundCanvas.releasePointerCapture) { boundCanvas.releasePointerCapture(opts.pointerId); } } catch (err) { /* ignore */ } } startReleaseTween(); if (app.core && app.core.drag) { if (opts.noLaunch) { app.core.drag.launchIntent = false; } app.core.endDrag(); } else if (app.core) { app.core.endDrag(); } logDragDebug(null, null, opts.noLaunch ? 'cancel' : 'up'); } function onPointerDown (e) { if (!playingForDrag()) { return; } if (app.pointerId != null && e.pointerId !== app.pointerId) { return; } if (e.preventDefault) { e.preventDefault(); } app.pointerId = e.pointerId; app.pointerType = e.pointerType || 'mouse'; addWindowPointer(); // If a touch is already in charge, do not reset the grab from pointerdown. if (app.activeTouchId != null) { return; } startDragFromEvent(e); } function onPointerMove (e) { if (app.pointerId == null || e.pointerId !== app.pointerId) { return; } if (!app.core || !app.core.drag) { return; } // Touch coordinates are the authority; ignore pointer moves for a // live touch so a wrong clientY cannot walk the whole column. // Only skip when touchstart has actually arrived — some environments // deliver touch-pointer events without a TouchEvent stream. if (app.activeTouchId != null) { if (e.preventDefault) { e.preventDefault(); } logDragDebug(e, fieldFromEvent(e), 'pointer-ignored'); return; } if (e.preventDefault) { e.preventDefault(); } moveDragFromEvent(e); } function onPointerUp (e) { if (app.pointerId == null) { return; } if (e && e.pointerId != null && e.pointerId !== app.pointerId) { return; } if (app.activeTouchId != null) { // touchend will finish the drag. if (e && e.preventDefault) { e.preventDefault(); } logDragDebug(e, fieldFromEvent(e), 'pointer-up-ignored'); return; } if (e && e.preventDefault) { e.preventDefault(); } finishDrag({ pointerId: e && e.pointerId }); } function onPointerCancel (e) { if (app.pointerId == null) { return; } if (e && e.pointerId != null && e.pointerId !== app.pointerId) { return; } if (app.activeTouchId != null) { if (e && e.preventDefault) { e.preventDefault(); } logDragDebug(e, fieldFromEvent(e), 'pointer-cancel-ignored'); return; } if (e && e.preventDefault) { e.preventDefault(); } // A cancelled gesture is not a launch pull. finishDrag({ pointerId: e && e.pointerId, noLaunch: true }); } function touchById (list, id) { if (!list) { return null; } for (var i = 0; i < list.length; i++) { if (list[i].identifier === id) { return list[i]; } } return null; } function onTouchStart (e) { if (!playingForDrag()) { return; } if (app.activeTouchId != null) { if (e.preventDefault) { e.preventDefault(); } return; } var t = e.changedTouches && e.changedTouches[0]; if (!t) { return; } if (e.preventDefault) { e.preventDefault(); } app.activeTouchId = t.identifier; addWindowPointer(); startDragFromEvent(e); } function onTouchMove (e) { if (app.activeTouchId == null) { return; } if (!touchById(e.changedTouches, app.activeTouchId) && !touchById(e.touches, app.activeTouchId)) { return; } if (e.preventDefault) { e.preventDefault(); } moveDragFromEvent(e); } function onTouchEnd (e) { if (app.activeTouchId == null) { return; } if (!touchById(e.changedTouches, app.activeTouchId)) { return; } if (e.preventDefault) { e.preventDefault(); } finishDrag({}); } function onTouchCancel (e) { if (app.activeTouchId == null) { return; } if (!touchById(e.changedTouches, app.activeTouchId)) { return; } if (e.preventDefault) { e.preventDefault(); } finishDrag({ noLaunch: true }); } function logPhysicsDebug () { if (!app.debugPhysics || !app.core) { return; } ensureDragDebugOverlay(); var el = document.getElementById('drag-debug'); if (!el) { return; } var issues = app.core.lastInvariantViolations || []; var flying = 0; var manuals = 0; var clusters = app.core.clusters ? Object.keys(app.core.clusters).length : 0; for (var i = 0; i < app.core.blocks.length; i++) { if (app.core.blocks[i].state === 'flying') { flying++; } if (app.core.blocks[i].state === 'manual') { manuals++; } } var status = issues.length ? ('PHYSICS FAIL x' + issues.length + '\n' + issues.slice(0, 6).join('\n')) : ('physics ok blocks=' + app.core.blocks.length + ' fly=' + flying + ' man=' + manuals + ' cl=' + clusters); // Keep any live drag line above the physics status. var dragLine = ''; if (app.debugDrag && lastDragDebug) { dragLine = el.textContent && el.textContent.indexOf('drag ') === 0 ? el.textContent.split('\n')[0] + '\n' : ''; } el.textContent = dragLine + status; el.hidden = false; el.style.color = issues.length ? '#ffb4b4' : '#c6f6c8'; } function ensureDragDebugOverlay () { if (document.getElementById('drag-debug')) { return; } var el = document.createElement('div'); el.id = 'drag-debug'; el.setAttribute('aria-live', 'polite'); document.body.appendChild(el); } function logDragDebug (e, pos, phase) { if (!app.debugDrag) { return; } ensureDragDebugOverlay(); var el = document.getElementById('drag-debug'); if (!el) { return; } var block = null; if (app.core && app.core.drag) { block = app.core.blockById(app.core.drag.blockId); } var pt = e ? eventClient(e) : null; var evType = e ? e.type : phase; var info = { phase: phase, ev: evType, src: pos && pos.src, fieldY: pos && Math.round(pos.y * 100) / 100, col: pos && Math.round(pos.col * 100) / 100, cy: pt && Math.round(pt.y * 10) / 10, blockY: block && Math.round(block.y * 100) / 100, target: block && Math.floor((pos && pos.y) + 1e-12), launch: app.core && app.core.drag && app.core.drag.launchIntent, touchId: app.activeTouchId, pid: app.pointerId, ptype: app.pointerType }; lastDragDebug = info; el.textContent = 'drag ' + phase + ' ev=' + evType + ' src=' + (info.src || '-') + ' y=' + (info.fieldY != null ? info.fieldY : '-') + ' → ' + (info.target != null ? info.target : '-') + ' block=' + (info.blockY != null ? info.blockY : '-') + (info.launch ? ' LAUNCH' : '') + ' tId=' + info.touchId + ' pId=' + info.pid; el.hidden = false; } 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); }); /* ---------- online play (stage 2) ---------------------------------- */ function tickOnline (dt) { if (!app.online || typeof Online === 'undefined') { return; } if (app.core) { var shots = app.core.consumeOutgoingShots(); for (var i = 0; i < shots.length; i++) { var s = shots[i]; var start = fieldToViewport(s.col, s.y + 1); Online.rememberFlightLocal(s, start.x, start.y); } Online.queueShots(shots); } Online.tickFlights(); Online.renderMinis(document.getElementById('minis')); applyMinisLayout(); } /* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */ function bindOfflineUi () { var btn = document.getElementById('btn-offline'); if (btn) { btn.addEventListener('click', onOffline); btn.addEventListener('pointerup', function (e) { if (e.pointerType === 'touch' || e.pointerType === 'pen') { e.preventDefault(); onOffline(); } }); } var back = document.getElementById('btn-offline-menu'); if (back) { back.addEventListener('click', function () { teardownPlay(); app.mode = 'menu'; app.offline = false; app.battle = null; hideEl('offline-result'); showEl('menu'); }); } } function onOffline () { openPlanetSelect('offline'); } function tickOffline (dt) { if (!app.battle || !app.core || typeof Offline === 'undefined') { return; } if (app.battle.state === 'round_won') { if (!app.roundWonHandled) { app.roundWonHandled = true; app.roundWonDelay = Offline.ROUND_WON_DELAY || 1.5; } app.roundWonDelay -= dt; if (app.roundWonDelay <= 0) { startNextOfflineRound(); } updateOfflineMinis(dt, true); return; } var result = app.battle.tick(dt, app.core); if (result && result.flights && result.flights.length && typeof Online !== 'undefined' && Online.spawnFlights) { var locals = Object.create(null); var list = result.locals || []; for (var i = 0; i < list.length; i++) { var s = list[i]; var start; if (s.from_id === 'player') { start = fieldToViewport(s.col, s.y + 1); } else { start = miniViewportCenter(s.from_id); } locals[s.client_id] = { col: s.col, y: s.y, color: s.color, startX: start.x, startY: start.y, from_id: s.from_id }; } Online.spawnFlights(result.flights, locals); } if (typeof Online !== 'undefined' && Online.tickFlights) { Online.tickFlights(); } updateOfflineMinis(dt, false); if (app.battle.state === 'lost' && !app.offlineResultShown) { showOfflineResult(); } } function startNextOfflineRound () { if (!app.battle) { return; } app.battle.advanceRound(); app.roundWonHandled = false; app.roundWonDelay = 0; app._keepBattleOnTeardown = true; // Tear down the current scene then start a fresh player field, // keeping the same battle (already advanced). var planet = app.battle.playerPlanet; app._keepBattleOnTeardown = true; teardownPlay(); app.offline = true; app.battle = app.battle; // kept startPlay({ planet: planet, offline: true, keepBattle: true }); } function showOfflineResult () { app.offlineResultShown = true; var battle = app.battle; var reached = document.getElementById('offline-reached'); if (reached) { reached.textContent = String(battle.round); } var detail = document.getElementById('offline-result-detail'); if (detail) { var sch = battle.schedule; var n = sch.opponents; var noun = n === 1 ? 'tegenstander' : 'tegenstanders'; detail.textContent = 'Je speelde tegen ' + n + ' ' + noun + ' met skill ' + Math.round(sch.skill * 100) + '%.'; } hideEl('game-over'); showEl('offline-result'); } function refreshOfflineHud () { var el = document.getElementById('offline-hud'); if (!el) { return; } if (!(app.offline && app.battle && app.mode === 'playing')) { el.hidden = true; return; } el.hidden = false; var sch = app.battle.schedule; var n = sch.opponents; var noun = n === 1 ? 'tegenstander' : 'tegenstanders'; var r = document.getElementById('offline-round'); var o = document.getElementById('offline-opponents'); var s = document.getElementById('offline-skill'); if (r) { r.textContent = 'Ronde ' + sch.round; } if (o) { o.textContent = n + ' ' + noun; } if (s) { s.textContent = 'Skill ' + Math.round(sch.skill * 100) + '%'; } } function hideOfflineHud () { var el = document.getElementById('offline-hud'); if (el) { el.hidden = true; } } function refreshChainIndicator () { var el = document.getElementById('chain-indicator'); if (!el) { return; } var info = app.core && app.core.lastChainIndicator; var active = app.core && app.core.hasActiveLandingChain && app.core.hasActiveLandingChain(); // Show only while a chained cluster is still in the air. if (!info || info.chain < 1 || app.mode !== 'playing' || !active) { el.hidden = true; return; } el.hidden = false; el.textContent = 'x' + info.chain + ' +' + info.bonusPct + '%'; } function hideChainIndicator () { var el = document.getElementById('chain-indicator'); if (el) { el.hidden = true; } } function miniViewportCenter (botId) { var el = document.querySelector('#minis .mini[data-player="' + botId + '"] canvas'); if (!el) { return { x: window.innerWidth / 2, y: 40 }; } var rect = el.getBoundingClientRect(); var plan = app.miniLayout; if (plan && plan.mode === 'sides') { var mid = plan.fieldX + plan.fieldW / 2; if (rect.left + rect.width / 2 < mid) { return { x: rect.right, y: rect.top + rect.height / 2 }; } return { x: rect.left, y: rect.top + rect.height / 2 }; } return { x: rect.left + rect.width / 2, y: rect.bottom }; } function offlineMiniSize (n) { return currentMiniSize(); } function updateOfflineMinis (dt, force) { app.miniAcc = (app.miniAcc || 0) + dt; if (!force && app.miniAcc < 0.1) { return; } app.miniAcc = 0; renderOfflineMinis(); } function renderOfflineMinis () { var container = document.getElementById('minis'); if (!container || !app.battle) { return; } var bots = app.battle.bots; var size = offlineMiniSize(bots.length); container.classList.toggle('crowded', bots.length > 5); var existing = {}; var kids = container.querySelectorAll('[data-player]'); for (var i = 0; i < kids.length; i++) { existing[kids[i].getAttribute('data-player')] = kids[i]; } var seen = Object.create(null); for (var i = 0; i < bots.length; i++) { var bot = bots[i]; seen[bot.id] = true; var el = existing[bot.id]; if (!el) { el = document.createElement('div'); el.className = 'mini'; el.setAttribute('data-player', bot.id); el.innerHTML = '
' + '' + '
'; container.appendChild(el); } var canvas = el.querySelector('canvas'); if (canvas && (canvas.width !== size.w || canvas.height !== size.h)) { canvas.width = size.w; canvas.height = size.h; } el.classList.toggle('eliminated', !!bot.eliminated); var planetName = bot.planet && bot.planet.name ? bot.planet.name : ''; el.querySelector('.mini-name').textContent = bot.name + (planetName ? ' · ' + planetName : ''); el.querySelector('.mini-meta').textContent = bot.eliminated ? 'Uit' : ('Punten ' + (bot.score || 0)); var snap = bot.core ? bot.core.fieldSnapshot() : { blocks: [] }; if (typeof Online !== 'undefined' && Online._drawMini) { Online._drawMini(canvas, snap, bot.planet); } } for (var id in existing) { if (!seen[id]) { existing[id].remove(); } } applyMinisLayout(); } function buildColumnWarn () { app.columnWarn = []; if (!app.scene) { return; } var img = (game.images && (game.images.columnWarn || game.images.pixel)) || null; if (!img) { return; } for (var c = 0; c < 10; c++) { var obj = new GameObject(0, 0, img, 0); obj.renderer.alpha = 0; obj.renderer.visible = false; app.scene.addObject(obj); app.columnWarn.push(obj); } updateColumnWarn(0); } function updateColumnWarn (dt) { if (!app.columnWarn || !app.core) { return; } app.warnClock = (app.warnClock || 0) + (dt || 0); var pulse = (typeof GameCore !== 'undefined' && GameCore.columnWarnPulse) ? GameCore.columnWarnPulse(app.warnClock) : 0.16 + 0.28 * (0.5 + 0.5 * Math.sin(app.warnClock * 3.45575)); var t = app.tile; for (var c = 0; c < app.columnWarn.length; c++) { var obj = app.columnWarn[c]; var on = app.core.columnNeedsWarn && app.core.columnNeedsWarn(c); obj.renderer.visible = !!on; obj.renderer.alpha = on ? pulse : 0; if (t) { obj.transform.position.x = c * t + t / 2; obj.transform.position.y = app.fieldH / 2; obj.transform.size = { x: t, y: app.fieldH }; } } } function fieldToViewport (col, fieldY) { var canvas = app.scene && app.scene.canvas; if (!canvas) { return { x: window.innerWidth / 2, y: 40 }; } var rect = canvas.getBoundingClientRect(); var x = rect.left + ((col + 0.5) / 10) * rect.width; var y = rect.top + (1 - (fieldY / 13)) * rect.height; return { x: x, y: y }; } function onlinePayload () { if (!app.online || !app.core) { return {}; } return { snapshot: app.core.fieldSnapshot(), score: app.core.score, eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported }; } function onOnlineEliminated () { app.eliminatedReported = true; app.spectating = true; unbindPointer(); hideEl('game-over'); var lobby = typeof Online !== 'undefined' && Online.lobby; if (lobby && lobby.status === 'finished') { showPodium(lobby); return; } showEl('spectator'); } function showPodium (lobby) { hideEl('spectator'); hideEl('game-over'); hideEl('online-panel'); showEl('podium'); var list = document.getElementById('podium-list'); list.innerHTML = ''; var ranks = (lobby && lobby.rankings) || []; for (var i = 0; i < ranks.length; i++) { var r = ranks[i]; var li = document.createElement('li'); var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e')); li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten'; list.appendChild(li); } var hint = document.getElementById('podium-hint'); var secs = (lobby && lobby.podium_seconds) || 5; hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…'; } function startOnlineMatch () { if (app.mode === 'playing' && app.online) { return; } var planet = Planet.planetById(selectedPlanetId()); var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null; if (me && me.planet && me.planet.id) { planet = Planet.planetById(me.planet.id); } startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) }); if (typeof Online !== 'undefined') { Online.startPolling(onlinePayload); } } function leaveOnlineMatch (goMenu) { if (typeof Online !== 'undefined') { Online.stopPolling(); Online.leaveLobby(); Online.clearFlights(); } teardownPlay(); app.online = false; if (goMenu) { app.mode = 'menu'; showEl('menu'); } else { app.mode = 'online'; openOnlinePanel(); } } function bindOnlineUi () { var onlineBtn = document.getElementById('btn-online'); if (!onlineBtn) { return; } onlineBtn.addEventListener('click', function () { openOnlinePanel(); }); var backs = document.querySelectorAll('[data-back-menu]'); for (var i = 0; i < backs.length; i++) { backs[i].addEventListener('click', function () { if (typeof Online !== 'undefined') { Online.stopPolling(); } hideEl('online-panel'); app.mode = 'menu'; app.online = false; showEl('menu'); }); } document.getElementById('btn-create').addEventListener('click', function () { Online.createLobby().then(function (data) { if (data && data.ok) { renderOnline(); Online.startPolling(onlinePayload); } else { renderOnline(); } }); }); document.getElementById('join-form').addEventListener('submit', function (e) { e.preventDefault(); var code = (document.getElementById('join-code').value || '').trim(); if (!code) { return; } Online.joinLobby(code).then(function () { renderOnline(); if (Online.lobby) { Online.startPolling(onlinePayload); } }); }); document.getElementById('btn-ready').addEventListener('click', function () { var me = Online.mePlayer(); Online.setReady(!(me && me.ready)).then(renderOnline); }); document.getElementById('btn-start').addEventListener('click', function () { Online.startGame().then(function (data) { if (data && data.ok) { startOnlineMatch(); } else { renderOnline(); } }); }); document.getElementById('btn-leave-lobby').addEventListener('click', function () { Online.leaveLobby().then(function () { Online.stopPolling(); renderOnline(); }); }); document.getElementById('btn-copy-code').addEventListener('click', function () { var code = document.getElementById('lobby-code').textContent; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(code); } }); document.getElementById('btn-spectate').addEventListener('click', function () { hideEl('spectator'); app.spectating = true; }); document.getElementById('btn-leave-game').addEventListener('click', function () { leaveOnlineMatch(false); }); if (typeof Online !== 'undefined') { Online.onChange = function () { renderOnline(); }; Online.onGameStart = function () { startOnlineMatch(); }; Online.onIncoming = function (incoming) { if (!app.core || app.core.state !== 'playing') { return; } for (var i = 0; i < incoming.length; i++) { app.core.ingestGarbage(); } }; Online.onFinished = function (lobby) { showPodium(lobby); }; Online.onLobbyReturn = function (lobby) { teardownPlay(); app.online = false; app.mode = 'online'; hideEl('podium'); showEl('online-panel'); renderOnline(); Online.startPolling(onlinePayload); }; } var params = new URLSearchParams(window.location.search); if (params.get('online') === '1' || params.get('auth') === 'unconfigured') { openOnlinePanel(); } } function openOnlinePanel () { hideEl('menu'); hideEl('game-over'); hideEl('podium'); hideEl('spectator'); hideEl('planet-select'); showEl('online-panel'); app.mode = 'online'; setOnlineStatus('Even kijken of online spelen beschikbaar is…'); if (typeof Online === 'undefined') { showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.'); showOnly('online-unconfigured'); return; } Online.refresh().then(function (data) { if (!data || data.ok === false) { var msg = (data && data.error) || 'Geen verbinding met de server.'; showOnlineError(msg + ' Je kunt wel alleen spelen.'); if (data && data.configured === false) { showOnly('online-unconfigured'); } else { showOnly('online-login'); } document.getElementById('btn-login').style.display = 'none'; return; } renderOnline(); if (Online.lobby) { Online.startPolling(onlinePayload); } }); } function setOnlineStatus (text) { var el = document.getElementById('online-status'); if (el) { el.textContent = text; } } function showOnlineError (text) { var el = document.getElementById('online-error'); if (!el) { return; } if (!text) { el.hidden = true; el.textContent = ''; return; } el.hidden = false; el.textContent = text; } function showOnly (id) { var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby']; for (var i = 0; i < ids.length; i++) { document.getElementById(ids[i]).hidden = (ids[i] !== id); } } function renderOnline () { if (typeof Online === 'undefined') { return; } if (app.mode === 'playing' && app.online) { Online.renderMinis(document.getElementById('minis')); if (Online.lobby && Online.lobby.status === 'finished') { showPodium(Online.lobby); } return; } showOnlineError(Online.error); if (!Online.configured && !Online.me && !Online.local) { setOnlineStatus('Online spelen is nog niet ingesteld.'); showOnly('online-unconfigured'); return; } if (!Online.me) { setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.'); showOnly('online-login'); document.getElementById('btn-login').style.display = ''; document.getElementById('btn-login').href = Online.loginUrl(); document.getElementById('local-login').hidden = !Online.local; return; } if (Online.lobby) { setOnlineStatus('Lobby'); showOnly('online-lobby'); document.getElementById('lobby-me-name').textContent = Online.me.name; document.getElementById('lobby-code').textContent = Online.lobby.code; var list = document.getElementById('lobby-players'); list.innerHTML = ''; var players = Online.lobby.players || []; for (var i = 0; i < players.length; i++) { var p = players[i]; var li = document.createElement('li'); if (p.is_me) { li.classList.add('you'); } var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : ''); var state = p.ready ? 'Gereed' : 'Wacht…'; var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : ''; li.innerHTML = '' + escapeText(label) + (world ? '' + escapeText(world) + '' : '') + '' + state + ''; list.appendChild(li); } renderPlanetGrid('lobby-planet-grid', true); var me = Online.mePlayer(); document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed'; var start = document.getElementById('btn-start'); start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id); start.disabled = !Online.lobby.can_start; var hint = document.getElementById('lobby-hint'); if (Online.lobby.status === 'playing') { hint.textContent = 'Het spel start…'; } else if (players.length < 2) { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; } else if (!Online.lobby.all_ready) { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; } else if (Online.lobby.can_start) { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; } else { hint.textContent = 'Wachten tot de host start.'; } return; } setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.'); showOnly('online-home'); document.getElementById('me-name').textContent = Online.me.name; document.getElementById('local-login').hidden = !Online.local; } function escapeText (s) { return String(s) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function selectedPlanetId () { if (app.selectedPlanetId) { return app.selectedPlanetId; } return 'terra'; } function restoreSelectedPlanet () { var id = 'terra'; try { id = localStorage.getItem('meteors-planet') || 'terra'; } catch (e) {} setSelectedPlanet(id, true); } function setSelectedPlanet (id, silent) { var all = Planet.allPlanets(); var found = null; for (var i = 0; i < all.length; i++) { if (all[i].id === id) { found = all[i]; break; } } if (!found) { found = Planet.defaultPlanet(); } app.selectedPlanetId = found.id; try { localStorage.setItem('meteors-planet', found.id); } catch (e) {} if (!silent) { var grid = document.getElementById('planet-grid'); if (grid && !grid.hidden && grid.children.length) { renderPlanetGrid('planet-grid', false); } var lobby = document.getElementById('lobby-planet-grid'); if (lobby && lobby.children.length) { renderPlanetGrid('lobby-planet-grid', true); } } return found; } function openPlanetSelect (context) { if (app.mode === 'playing') { return; } app.planetSelectContext = context || 'solo'; app.mode = 'planet-select'; hideEl('menu'); hideEl('online-panel'); hideEl('game-over'); showEl('planet-select'); renderPlanetGrid('planet-grid', false); var go = document.getElementById('btn-planet-go'); if (go) { go.textContent = 'Spelen'; } } function renderPlanetGrid (containerId, compact) { var grid = document.getElementById(containerId); if (!grid) { return; } var current = selectedPlanetId(); var all = Planet.allPlanets(); grid.innerHTML = ''; if (compact) { grid.classList.add('compact'); } for (var i = 0; i < all.length; i++) { var pl = all[i]; var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'planet-card' + (pl.id === current ? ' selected' : ''); btn.setAttribute('role', 'listitem'); btn.dataset.planet = pl.id; var swatches = ''; for (var c = 0; c < pl.colors.length; c++) { swatches += ''
				+ escapeText(pl.colors[c].name) + ''; } btn.innerHTML = '
' + escapeText(pl.name) + '
' + '
' + escapeText(pl.people) + '
' + '
' + escapeText(Planet.formatStats(pl)) + '
' + '
' + swatches + '
'; btn.addEventListener('click', (function (id, isCompact) { return function () { onPlanetPicked(id, isCompact); }; })(pl.id, !!compact)); grid.appendChild(btn); } } function onPlanetPicked (id, fromLobby) { setSelectedPlanet(id); if (fromLobby && typeof Online !== 'undefined' && Online.lobby) { Online.setPlanet(id).then(function () { renderOnline(); }); } else { renderPlanetGrid('planet-grid', false); } } function confirmPlanetSelect () { var planet = setSelectedPlanet(selectedPlanetId()); hideEl('planet-select'); if (app.planetSelectContext === 'online') { openOnlinePanel(); return; } if (app.planetSelectContext === 'offline') { startPlay({ planet: planet, offline: true }); return; } startPlay({ planet: planet }); } function cancelPlanetSelect () { hideEl('planet-select'); app.mode = 'menu'; showEl('menu'); } function bindPlanetSelect () { var go = document.getElementById('btn-planet-go'); var back = document.getElementById('btn-planet-back'); if (go) { go.addEventListener('click', confirmPlanetSelect); } if (back) { back.addEventListener('click', cancelPlanetSelect); } } /* * End File: * /workspace/meteors/src/main.js */