/* * 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": 2, "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": 2, "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": 2, "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"} ] } ] } ; var BLOCK_REGISTRY = { "_comment": "Append-only block registry. Never reorder, rename ids, or insert in the middle. New blocks go at the end. The first five (Terra) are unlocked by default; index 5 requires 500 lifetime points, each next index requires 14.5% more (rounded).", "terraCount": 5, "firstThreshold": 500, "thresholdGrowth": 1.145, "blocks": [ { "id": "terra-ember", "name": "Ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png", "terra": true }, { "id": "terra-aqua", "name": "Aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png", "terra": true }, { "id": "terra-leaf", "name": "Leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png", "terra": true }, { "id": "terra-sun", "name": "Sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png", "terra": true }, { "id": "terra-orchid", "name": "Orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png", "terra": true }, { "id": "rune-fehu", "name": "Fehu", "hex": "#e8a44a", "shape": "rune_fehu", "image": "images/block-rune-fehu.png", "terra": false }, { "id": "rune-ansuz", "name": "Ansuz", "hex": "#6ab0e8", "shape": "rune_ansuz", "image": "images/block-rune-ansuz.png", "terra": false }, { "id": "rune-thurisaz", "name": "Thurisaz", "hex": "#c05040", "shape": "rune_thurisaz", "image": "images/block-rune-thurisaz.png", "terra": false }, { "id": "rune-raido", "name": "Raido", "hex": "#d0c070", "shape": "rune_raido", "image": "images/block-rune-raido.png", "terra": false }, { "id": "rune-sowilo", "name": "Sowilo", "hex": "#f0d040", "shape": "rune_sowilo", "image": "images/block-rune-sowilo.png", "terra": false }, { "id": "rune-algiz", "name": "Algiz", "hex": "#80d0a0", "shape": "rune_algiz", "image": "images/block-rune-algiz.png", "terra": false }, { "id": "arrow-up", "name": "Arrow", "hex": "#f07040", "shape": "arrow", "image": "images/block-arrow-up.png", "terra": false }, { "id": "arrow-chevron", "name": "Chevron", "hex": "#50c0e0", "shape": "chevron", "image": "images/block-arrow-chevron.png", "terra": false }, { "id": "arrow-double", "name": "Double Arrow", "hex": "#e05080", "shape": "double_arrow", "image": "images/block-arrow-double.png", "terra": false }, { "id": "arrow-return", "name": "Return", "hex": "#a080e0", "shape": "return_arrow", "image": "images/block-arrow-return.png", "terra": false }, { "id": "fig-person", "name": "Figure", "hex": "#f0c0a0", "shape": "person", "image": "images/block-fig-person.png", "terra": false }, { "id": "fig-walker", "name": "Walker", "hex": "#c09070", "shape": "walker", "image": "images/block-fig-walker.png", "terra": false }, { "id": "fig-hero", "name": "Hero", "hex": "#e8b070", "shape": "hero", "image": "images/block-fig-hero.png", "terra": false }, { "id": "face-smile", "name": "Smile", "hex": "#f0d060", "shape": "smile", "image": "images/block-face-smile.png", "terra": false }, { "id": "face-wink", "name": "Wink", "hex": "#f0a050", "shape": "wink", "image": "images/block-face-wink.png", "terra": false }, { "id": "face-cool", "name": "Cool", "hex": "#6090d0", "shape": "cool", "image": "images/block-face-cool.png", "terra": false }, { "id": "face-grin", "name": "Grin", "hex": "#f0c848", "shape": "grin", "image": "images/block-face-grin.png", "terra": false }, { "id": "icon-heart", "name": "Heart", "hex": "#e04060", "shape": "heart", "image": "images/block-icon-heart.png", "terra": false }, { "id": "icon-moon", "name": "Moon", "hex": "#d0d8f0", "shape": "crescent", "image": "images/block-icon-moon.png", "terra": false }, { "id": "icon-bolt", "name": "Bolt", "hex": "#f0e050", "shape": "lightning", "image": "images/block-icon-bolt.png", "terra": false }, { "id": "icon-shield", "name": "Shield", "hex": "#5080c0", "shape": "shield", "image": "images/block-icon-shield.png", "terra": false }, { "id": "icon-crown", "name": "Crown", "hex": "#f0c030", "shape": "crown", "image": "images/block-icon-crown.png", "terra": false }, { "id": "icon-eye", "name": "Eye", "hex": "#70d0c0", "shape": "eye", "image": "images/block-icon-eye.png", "terra": false }, { "id": "icon-star6", "name": "Hexastar", "hex": "#f0e8a0", "shape": "star6", "image": "images/block-icon-star6.png", "terra": false }, { "id": "icon-spiral", "name": "Spiral", "hex": "#c070d0", "shape": "spiral", "image": "images/block-icon-spiral.png", "terra": false }, { "id": "icon-wave", "name": "Wave", "hex": "#3090d0", "shape": "wave", "image": "images/block-icon-wave.png", "terra": false }, { "id": "icon-mountain", "name": "Mountain", "hex": "#809070", "shape": "mountain", "image": "images/block-icon-mountain.png", "terra": false }, { "id": "icon-fish", "name": "Fish", "hex": "#40a8c8", "shape": "fish", "image": "images/block-icon-fish.png", "terra": false }, { "id": "icon-bird", "name": "Bird", "hex": "#e07050", "shape": "bird", "image": "images/block-icon-bird.png", "terra": false }, { "id": "icon-key", "name": "Key", "hex": "#d0b050", "shape": "key", "image": "images/block-icon-key.png", "terra": false }, { "id": "icon-comet", "name": "Comet", "hex": "#90d0f0", "shape": "comet", "image": "images/block-icon-comet.png", "terra": false }, { "id": "icon-clover", "name": "Clover", "hex": "#40b060", "shape": "clover", "image": "images/block-icon-clover.png", "terra": false }, { "id": "icon-paw", "name": "Paw", "hex": "#c08050", "shape": "paw", "image": "images/block-icon-paw.png", "terra": false }, { "id": "icon-sword", "name": "Sword", "hex": "#b0b8c0", "shape": "sword", "image": "images/block-icon-sword.png", "terra": false }, { "id": "icon-bell", "name": "Bell", "hex": "#f0c848", "shape": "bell", "image": "images/block-icon-bell.png", "terra": false }, { "id": "icon-mushroom", "name": "Mushroom", "hex": "#e06050", "shape": "mushroom", "image": "images/block-icon-mushroom.png", "terra": false }, { "id": "icon-cactus", "name": "Cactus", "hex": "#50b068", "shape": "cactus", "image": "images/block-icon-cactus.png", "terra": false }, { "id": "icon-ring", "name": "Ring", "hex": "#e8d080", "shape": "ring", "image": "images/block-icon-ring.png", "terra": false }, { "id": "icon-flag", "name": "Flag", "hex": "#d04050", "shape": "flag", "image": "images/block-icon-flag.png", "terra": false }, { "id": "icon-snow", "name": "Snowflake", "hex": "#c8e0f8", "shape": "snowflake", "image": "images/block-icon-snow.png", "terra": false }, { "id": "icon-flame", "name": "Flame", "hex": "#ff7030", "shape": "flame_icon", "image": "images/block-icon-flame.png", "terra": false }, { "id": "icon-ankh", "name": "Ankh", "hex": "#d0a060", "shape": "ankh", "image": "images/block-icon-ankh.png", "terra": false }, { "id": "icon-yin", "name": "Yin Yang", "hex": "#606080", "shape": "yinyang", "image": "images/block-icon-yin.png", "terra": false }, { "id": "aurel-gold", "name": "Aurel gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png", "terra": false }, { "id": "aurel-cream", "name": "Aurel cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png", "terra": false }, { "id": "aurel-amber", "name": "Aurel amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png", "terra": false }, { "id": "aurel-sage", "name": "Aurel sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png", "terra": false }, { "id": "aurel-rose", "name": "Aurel rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png", "terra": false }, { "id": "cinder-magma", "name": "Cinder magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png", "terra": false }, { "id": "cinder-coal", "name": "Cinder coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png", "terra": false }, { "id": "cinder-spark", "name": "Cinder spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png", "terra": false }, { "id": "cinder-ash", "name": "Cinder ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png", "terra": false }, { "id": "cinder-core", "name": "Cinder core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png", "terra": false }, { "id": "lunara-silver", "name": "Lunara silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png", "terra": false }, { "id": "lunara-dust", "name": "Lunara dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png", "terra": false }, { "id": "lunara-pale", "name": "Lunara pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png", "terra": false }, { "id": "lunara-void", "name": "Lunara void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png", "terra": false }, { "id": "lunara-lilac", "name": "Lunara lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png", "terra": false }, { "id": "mire-moss", "name": "Mire moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png", "terra": false }, { "id": "mire-bog", "name": "Mire bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png", "terra": false }, { "id": "mire-rust", "name": "Mire rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png", "terra": false }, { "id": "mire-spore", "name": "Mire spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png", "terra": false }, { "id": "mire-murk", "name": "Mire murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png", "terra": false }, { "id": "galeon-sky", "name": "Galeon sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png", "terra": false }, { "id": "galeon-cloud", "name": "Galeon cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png", "terra": false }, { "id": "galeon-storm", "name": "Galeon storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png", "terra": false }, { "id": "galeon-sand", "name": "Galeon sand", "hex": "#d4b483", "shape": "diamond", "image": "images/block-galeon-sand.png", "terra": false }, { "id": "galeon-kite", "name": "Galeon kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png", "terra": false }, { "id": "obsid-glass", "name": "Obsid glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png", "terra": false }, { "id": "obsid-violet", "name": "Obsid violet", "hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png", "terra": false }, { "id": "obsid-shard", "name": "Obsid shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png", "terra": false }, { "id": "obsid-vein", "name": "Obsid vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png", "terra": false }, { "id": "obsid-basalt", "name": "Obsid basalt", "hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png", "terra": false }, { "id": "wisp-glow", "name": "Wisp glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png", "terra": false }, { "id": "wisp-mist", "name": "Wisp mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png", "terra": false }, { "id": "wisp-sparkle", "name": "Wisp sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png", "terra": false }, { "id": "wisp-veil", "name": "Wisp veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png", "terra": false }, { "id": "wisp-gleam", "name": "Wisp gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png", "terra": false }, { "id": "thorn-briar", "name": "Thorn briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png", "terra": false }, { "id": "thorn-berry", "name": "Thorn berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png", "terra": false }, { "id": "thorn-bark", "name": "Thorn bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png", "terra": false }, { "id": "thorn-petal", "name": "Thorn petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png", "terra": false }, { "id": "thorn-gold", "name": "Thorn gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png", "terra": false }, { "id": "zephyr-azure", "name": "Zephyr azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png", "terra": false }, { "id": "zephyr-breeze", "name": "Zephyr breeze", "hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png", "terra": false }, { "id": "zephyr-cirrus", "name": "Zephyr cirrus", "hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png", "terra": false }, { "id": "zephyr-dusk", "name": "Zephyr dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png", "terra": false }, { "id": "zephyr-haze", "name": "Zephyr haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png", "terra": false }, { "id": "frore-ice", "name": "Frore ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png", "terra": false }, { "id": "frore-frost", "name": "Frore frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png", "terra": false }, { "id": "frore-deep", "name": "Frore deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png", "terra": false }, { "id": "frore-aurora", "name": "Frore aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png", "terra": false }, { "id": "frore-rime", "name": "Frore rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png", "terra": false }, { "id": "forge-iron", "name": "Forge iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png", "terra": false }, { "id": "forge-slag", "name": "Forge slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png", "terra": false }, { "id": "forge-spark", "name": "Forge spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png", "terra": false }, { "id": "forge-brass", "name": "Forge brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png", "terra": false }, { "id": "forge-soot", "name": "Forge soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png", "terra": false } ] } ; var I18N_CATALOG = { "locales": { "en": { "menu.play": "Play", "menu.online": "Play online", "menu.designer": "Planet Designer", "menu.lastScore": "Last score:", "menu.hint": "Drag blocks vertically to swap them. Pull a block above its column to launch it upward. Blocks that leave the field score points.", "menu.login": "Log in", "loginPrompt.title": "Log in?", "loginPrompt.body": "Log in to save your points and play online.", "loginPrompt.guest": "Play as Guest", "menu.localTest": "local test:", "menu.loggedInAs": "Logged in as", "menu.total": "Total:", "menu.pointsWord": "points", "menu.logout": "Log out", "menu.player": "player", "planet.title": "Choose a field", "planet.back": "Back", "planet.customBadge": "Yours", "stats.powerLabel": "Power", "online.title": "Online", "online.checking": "Checking whether online play is available…", "online.notLoaded": "Online play is not included in this build. You can still play offline.", "online.canPlaySolo": "You can still play offline.", "online.unconfiguredHtml": "Online play is not set up yet. The administrator must add the callback path /meteors/callback.php at auth.timfalken.com/admin (the same client as the other sites on this domain; do not generate the secret again) and put that secret in data/config.php on the server. See the README.", "online.loginPrompt": "To play online, log in with your account on auth.timfalken.com.", "online.localTest": "Local test:", "online.createLobby": "Create lobby", "online.lobbyCode": "Lobby code", "online.join": "Join", "online.copy": "Copy", "online.copied": "Copied", "online.code": "Code:", "online.yourField": "Your field", "online.ready": "Ready", "online.notReady": "Not ready", "online.start": "Start", "online.leave": "Leave", "online.statusUnconfigured": "Online play is not set up yet.", "online.statusLogin": "Log in to create a lobby or join one.", "online.statusLobby": "Lobby", "online.statusHome": "Hi {name}. Create a lobby or join with a code.", "online.hintStarting": "The game is starting…", "online.hintNeedPlayers": "Wait for at least one other player. Share the code.", "online.hintNeedReady": "Everyone must press Ready. The host starts afterwards.", "online.hintHostStart": "Everyone is ready. Press Start.", "online.hintWaitHost": "Waiting for the host to start.", "online.host": "host", "online.you": "you", "designer.title": "Planet Designer", "designer.taglineBefore": "Total:", "designer.taglineAfter": "points.", "designer.empty": "You don’t have any planets of your own yet. Create one.", "designer.new": "New planet", "designer.editTitle": "Edit planet", "designer.createTitle": "New planet", "designer.name": "Planet name", "designer.people": "People’s name", "designer.gravity": "Gravity", "designer.air": "Air resistance", "designer.mass": "Mass", "designer.power": "Power {n}%", "designer.slotsHint": "Choose five blocks. Click a slot to change it.", "designer.save": "Save", "designer.delete": "Delete", "designer.cancel": "Back", "designer.edit": "Edit", "designer.pickBlock": "Choose a block", "designer.close": "Close", "designer.choose": "Choose", "designer.slotAria": "Block {n}", "designer.needPoints": "{n} points required", "designer.alreadyUsed": "already in another slot", "designer.confirmDelete": "Delete the planet “{name}”?", "designer.deleteFailed": "Could not delete the planet.", "designer.saveFailed": "Could not save the planet.", "designer.needNames": "Enter a name for the planet and for its people.", "designer.needFive": "Choose five blocks.", "designer.defaultName": "New planet", "designer.defaultPeople": "People", "hud.points": "Points", "hud.round": "Round {n}", "hud.out": "Out", "hud.miniPoints": "Points {n}", "hud.opponent.one": "opponent", "hud.opponent.few": "opponents", "hud.opponent.many": "opponents", "hud.opponent.other": "opponents", "offline.resultTitle": "Results", "offline.reachedBefore": "You reached round", "offline.reachedAfter": ".", "offline.reached": "You reached round {n}.", "offline.backMenu": "Back to the menu", "gameover.title": "You lost", "gameover.detail": "Every column is locked.", "gameover.score": "Score:", "spectator.title": "You’re out", "spectator.detail": "All your columns are full. You can watch or leave the match.", "spectator.watch": "Spectate", "podium.title": "Victory!", "podium.subtitle": "The last player is still standing.", "podium.hint": "Returning to the lobby in {n} seconds…", "podium.line": "{place} {name} · {score} points", "podium.place.1": "1st", "podium.place.2": "2nd", "podium.place.3": "3rd", "podium.place.n": "{n}th", "lang.current": "Language: {name}. Click to change.", "lang.choose": "Choose a language", "error.loginRequired": "Log in to continue.", "error.unknownPlanet": "Unknown planet.", "error.unknownLanguage": "Unknown language.", "error.unknownMode": "Unknown play mode.", "error.invalidSession": "Invalid play session.", "error.sessionExpired": "The play session has expired.", "error.needFiveBlocks": "A planet needs exactly five blocks.", "error.unknownBlock": "Unknown block.", "error.blockLocked": "This block is not unlocked yet.", "error.duplicateBlock": "Each block may only fill one slot.", "error.maxPlanets": "You have reached the limit of {n} planets.", "error.saveFailed": "Could not save.", "error.unknownAction": "Unknown action.", "error.internal": "Internal error.", "error.notAvailable": "Not available.", "error.csrf": "Invalid or missing security token.", "error.alreadyInLobby": "You are already in a lobby. Leave it first.", "error.alreadyInOtherLobby": "You are already in another lobby. Leave it first.", "error.unknownLobby": "Unknown lobby code.", "error.lobbyStarted": "This lobby has already started.", "error.lobbyFull": "This lobby is full (maximum {n} players).", "error.notInLobby": "You are not in a lobby.", "error.notInAnyLobby": "You are not in a lobby.", "error.hostOnly": "Only the host can start the game.", "error.gameAlreadyStarted": "The game has already started.", "error.needTwoPlayers": "At least two players are required.", "error.notAllReady": "Not everyone is ready.", "error.planetLocked": "You can only choose a planet before the game starts.", "error.fillField": "Enter a {field}.", "error.fieldPlanet": "planet name", "error.fieldPeople": "people’s name", "error.connection": "No connection to the server.", "error.badResponse": "The server did not send a valid reply.", "error.serverStatus": "The server returned {status}.", "auth.unavailable": "Signing in is not possible right now.", "auth.backToGame": "Back to the game", "auth.failed": "Sign-in failed.", "auth.retry": "Try again", "auth.back": "Back", "planet.terra.name": "Terra", "planet.terra.people": "Terrans", "planet.aurel.name": "Aurel", "planet.aurel.people": "Aurelians", "planet.cinder.name": "Cinder", "planet.cinder.people": "Cindari", "planet.lunara.name": "Lunara", "planet.lunara.people": "Lunarites", "planet.mire.name": "Mire", "planet.mire.people": "Mirians", "planet.galeon.name": "Galeon", "planet.galeon.people": "Galeoni", "planet.obsid.name": "Obsid", "planet.obsid.people": "Obsidians", "planet.wisp.name": "Wisp", "planet.wisp.people": "Wisplings", "planet.thorn.name": "Thorn", "planet.thorn.people": "Thornfolk", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "Zephyrites", "planet.frore.name": "Frore", "planet.frore.people": "Frorians", "planet.forge.name": "Forge", "planet.forge.people": "Forgelings", "block.terra-ember": "Ember", "block.terra-aqua": "Aqua", "block.terra-leaf": "Leaf", "block.terra-sun": "Sun", "block.terra-orchid": "Orchid", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "Arrow", "block.arrow-chevron": "Chevron", "block.arrow-double": "Double Arrow", "block.arrow-return": "Return", "block.fig-person": "Figure", "block.fig-walker": "Walker", "block.fig-hero": "Hero", "block.face-smile": "Smile", "block.face-wink": "Wink", "block.face-cool": "Cool", "block.face-grin": "Grin", "block.icon-heart": "Heart", "block.icon-moon": "Moon", "block.icon-bolt": "Bolt", "block.icon-shield": "Shield", "block.icon-crown": "Crown", "block.icon-eye": "Eye", "block.icon-star6": "Hexastar", "block.icon-spiral": "Spiral", "block.icon-wave": "Wave", "block.icon-mountain": "Mountain", "block.icon-fish": "Fish", "block.icon-bird": "Bird", "block.icon-key": "Key", "block.icon-comet": "Comet", "block.icon-clover": "Clover", "block.icon-paw": "Paw", "block.icon-sword": "Sword", "block.icon-bell": "Bell", "block.icon-mushroom": "Mushroom", "block.icon-cactus": "Cactus", "block.icon-ring": "Ring", "block.icon-flag": "Flag", "block.icon-snow": "Snowflake", "block.icon-flame": "Flame", "block.icon-ankh": "Ankh", "block.icon-yin": "Yin Yang", "block.aurel-gold": "Aurel gold", "block.aurel-cream": "Aurel cream", "block.aurel-amber": "Aurel amber", "block.aurel-sage": "Aurel sage", "block.aurel-rose": "Aurel rose", "block.cinder-magma": "Cinder magma", "block.cinder-coal": "Cinder coal", "block.cinder-spark": "Cinder spark", "block.cinder-ash": "Cinder ash", "block.cinder-core": "Cinder core", "block.lunara-silver": "Lunara silver", "block.lunara-dust": "Lunara dust", "block.lunara-pale": "Lunara pale", "block.lunara-void": "Lunara void", "block.lunara-lilac": "Lunara lilac", "block.mire-moss": "Mire moss", "block.mire-bog": "Mire bog", "block.mire-rust": "Mire rust", "block.mire-spore": "Mire spore", "block.mire-murk": "Mire murk", "block.galeon-sky": "Galeon sky", "block.galeon-cloud": "Galeon cloud", "block.galeon-storm": "Galeon storm", "block.galeon-sand": "Galeon sand", "block.galeon-kite": "Galeon kite", "block.obsid-glass": "Obsid glass", "block.obsid-violet": "Obsid violet", "block.obsid-shard": "Obsid shard", "block.obsid-vein": "Obsid vein", "block.obsid-basalt": "Obsid basalt", "block.wisp-glow": "Wisp glow", "block.wisp-mist": "Wisp mist", "block.wisp-sparkle": "Wisp sparkle", "block.wisp-veil": "Wisp veil", "block.wisp-gleam": "Wisp gleam", "block.thorn-briar": "Thorn briar", "block.thorn-berry": "Thorn berry", "block.thorn-bark": "Thorn bark", "block.thorn-petal": "Thorn petal", "block.thorn-gold": "Thorn gold", "block.zephyr-azure": "Zephyr azure", "block.zephyr-breeze": "Zephyr breeze", "block.zephyr-cirrus": "Zephyr cirrus", "block.zephyr-dusk": "Zephyr dusk", "block.zephyr-haze": "Zephyr haze", "block.frore-ice": "Frore ice", "block.frore-frost": "Frore frost", "block.frore-deep": "Frore deep", "block.frore-aurora": "Frore aurora", "block.frore-rime": "Frore rime", "block.forge-iron": "Forge iron", "block.forge-slag": "Forge slag", "block.forge-spark": "Forge spark", "block.forge-brass": "Forge brass", "block.forge-soot": "Forge soot", "error.webgl": "This game needs WebGL. Please try another browser, or turn on hardware acceleration.", "error.startFailed": "Could not start the game.", "reward.won": "You won!", "reward.lost": "You lost...", "reward.total": "Total points", "reward.continue": "Tap to continue", "game.menu": "Menu", "game.paused": "Paused", "game.resume": "Resume", "game.backToMenu": "Back to main menu", "reward.ended": "Game ended", "offline.defeated.one": "{n} opponent defeated", "offline.defeated.few": "{n} opponents defeated", "offline.defeated.many": "{n} opponents defeated", "offline.defeated.other": "{n} opponents defeated", "stats.gravity": "{pct}% ({g}g)", "menu.survival": "Survival", "menu.leaderboard": "Leaderboard", "leaderboard.title": "Leaderboard", "leaderboard.global": "Top 10", "leaderboard.friends": "Friends", "leaderboard.empty": "No scores yet.", "leaderboard.loginPrompt": "Log in to see how your friends rank.", "leaderboard.loadError": "The leaderboard could not be loaded.", "leaderboard.points": "{n} points" }, "nl": { "menu.play": "Spelen", "menu.online": "Online spelen", "menu.designer": "Planeetontwerper", "menu.lastScore": "Laatste score:", "menu.hint": "Sleep blokjes verticaal om ze te wisselen. Trek een blokje boven zijn kolom om het omhoog te duwen. Blokjes die het veld verlaten, leveren punten op.", "menu.login": "Inloggen", "loginPrompt.title": "Inloggen?", "loginPrompt.body": "Log in om je punten te bewaren en online te spelen.", "loginPrompt.guest": "Speel als gast", "menu.localTest": "lokale test:", "menu.loggedInAs": "Ingelogd als", "menu.total": "Totaal:", "menu.pointsWord": "punten", "menu.logout": "Uitloggen", "menu.player": "speler", "planet.title": "Kies een veld", "planet.back": "Terug", "planet.customBadge": "Eigen", "stats.powerLabel": "Power", "online.title": "Online", "online.checking": "Even kijken of online spelen beschikbaar is…", "online.notLoaded": "Online spelen is in deze build niet geladen. Je kunt wel offline spelen.", "online.canPlaySolo": "Je kunt wel offline spelen.", "online.unconfiguredHtml": "Online spelen is nog niet ingesteld. De beheerder moet bij auth.timfalken.com/admin het callback-pad /meteors/callback.php toevoegen (zelfde client als de andere sites op dit domein; het geheim niet opnieuw genereren) en dat geheim in data/config.php op de server zetten. Zie de README.", "online.loginPrompt": "Om online te spelen log je in met je account op auth.timfalken.com.", "online.localTest": "Lokale test:", "online.createLobby": "Lobby maken", "online.lobbyCode": "Lobbycode", "online.join": "Deelnemen", "online.copy": "Kopieer", "online.copied": "Gekopieerd", "online.code": "Code:", "online.yourField": "Jouw veld", "online.ready": "Gereed", "online.notReady": "Niet gereed", "online.start": "Starten", "online.leave": "Verlaten", "online.statusUnconfigured": "Online spelen is nog niet ingesteld.", "online.statusLogin": "Log in om een lobby te maken of eraan deel te nemen.", "online.statusLobby": "Lobby", "online.statusHome": "Hoi {name}. Maak een lobby of val in met een code.", "online.hintStarting": "Het spel start…", "online.hintNeedPlayers": "Wacht op minstens één andere speler. Deel de code.", "online.hintNeedReady": "Iedereen moet op Gereed drukken. De host start daarna.", "online.hintHostStart": "Iedereen is gereed. Druk op Starten.", "online.hintWaitHost": "Wachten tot de host start.", "online.host": "host", "online.you": "jij", "designer.title": "Planeetontwerper", "designer.taglineBefore": "Totaal:", "designer.taglineAfter": "punten.", "designer.empty": "Je hebt nog geen eigen planeten. Maak er een aan.", "designer.new": "Nieuwe planeet", "designer.editTitle": "Planeet bewerken", "designer.createTitle": "Nieuwe planeet", "designer.name": "Naam van de planeet", "designer.people": "Naam van de bevolking", "designer.gravity": "Zwaartekracht", "designer.air": "Luchtweerstand", "designer.mass": "Massa", "designer.power": "Power {n}%", "designer.slotsHint": "Kies vijf blokjes. Klik op een vak om te wisselen.", "designer.save": "Opslaan", "designer.delete": "Verwijderen", "designer.cancel": "Terug", "designer.edit": "Bewerken", "designer.pickBlock": "Kies een blokje", "designer.close": "Sluiten", "designer.choose": "Kies", "designer.slotAria": "Blokje {n}", "designer.needPoints": "{n} punten nodig", "designer.alreadyUsed": "al in een ander vak", "designer.confirmDelete": "Wil je de planeet “{name}” verwijderen?", "designer.deleteFailed": "Verwijderen is mislukt.", "designer.saveFailed": "Opslaan is mislukt.", "designer.needNames": "Vul een naam voor de planeet en voor de bevolking in.", "designer.needFive": "Kies vijf blokjes.", "designer.defaultName": "Nieuwe planeet", "designer.defaultPeople": "Volk", "hud.points": "Punten", "hud.round": "Ronde {n}", "hud.out": "Uit", "hud.miniPoints": "Punten {n}", "hud.opponent.one": "tegenstander", "hud.opponent.few": "tegenstanders", "hud.opponent.many": "tegenstanders", "hud.opponent.other": "tegenstanders", "offline.resultTitle": "Uitslag", "offline.reachedBefore": "Je hebt ronde", "offline.reachedAfter": " bereikt.", "offline.reached": "Je hebt ronde {n} bereikt.", "offline.backMenu": "Terug naar het menu", "gameover.title": "Je hebt verloren", "gameover.detail": "Alle kolommen zitten vast.", "gameover.score": "Score:", "spectator.title": "Je ligt eruit", "spectator.detail": "Al je kolommen zitten vol. Je kunt toekijken of de wedstrijd verlaten.", "spectator.watch": "Toekijken", "podium.title": "Gewonnen!", "podium.subtitle": "De laatste speler staat overeind.", "podium.hint": "Over {n} seconden teruggaan naar de lobby…", "podium.line": "{place} {name} · {score} punten", "podium.place.1": "1e", "podium.place.2": "2e", "podium.place.3": "3e", "podium.place.n": "{n}e", "lang.current": "Taal: {name}. Klik om te wijzigen.", "lang.choose": "Kies een taal", "error.loginRequired": "Log in om verder te gaan.", "error.unknownPlanet": "Onbekende planeet.", "error.unknownLanguage": "Onbekende taal.", "error.unknownMode": "Onbekende speelmodus.", "error.invalidSession": "Ongeldige speelsessie.", "error.sessionExpired": "Speelsessie is verlopen.", "error.needFiveBlocks": "Een planeet heeft precies vijf blokjes nodig.", "error.unknownBlock": "Onbekend blokje.", "error.blockLocked": "Dit blokje is nog niet ontgrendeld.", "error.duplicateBlock": "Elk blokje mag maar in één vak.", "error.maxPlanets": "Je hebt het maximum van {n} planeten bereikt.", "error.saveFailed": "Opslaan is mislukt.", "error.unknownAction": "Onbekende actie.", "error.internal": "Interne fout.", "error.notAvailable": "Niet beschikbaar.", "error.csrf": "Ongeldige of ontbrekende CSRF-token.", "error.alreadyInLobby": "Je zit al in een lobby. Verlaat die eerst.", "error.alreadyInOtherLobby": "Je zit al in een andere lobby. Verlaat die eerst.", "error.unknownLobby": "Onbekende lobbycode.", "error.lobbyStarted": "Deze lobby is al begonnen.", "error.lobbyFull": "Deze lobby is vol (maximaal {n} spelers).", "error.notInLobby": "Je zit niet in een lobby.", "error.notInAnyLobby": "Je zit in geen lobby.", "error.hostOnly": "Alleen de host kan het spel starten.", "error.gameAlreadyStarted": "Het spel is al begonnen.", "error.needTwoPlayers": "Er zijn minstens twee spelers nodig.", "error.notAllReady": "Niet iedereen is gereed.", "error.planetLocked": "De planeet kun je alleen kiezen voordat het spel start.", "error.fillField": "Vul een {field} in.", "error.fieldPlanet": "planeetnaam", "error.fieldPeople": "bevolkingsnaam", "error.connection": "Geen verbinding met de server.", "error.badResponse": "Geen geldig antwoord van de server.", "error.serverStatus": "De server gaf {status}.", "auth.unavailable": "Inloggen is nu niet mogelijk.", "auth.backToGame": "Terug naar het spel", "auth.failed": "Inloggen is mislukt.", "auth.retry": "Opnieuw proberen", "auth.back": "Terug", "planet.terra.name": "Terra", "planet.terra.people": "Terranen", "planet.aurel.name": "Aurel", "planet.aurel.people": "Aurelianen", "planet.cinder.name": "Cinder", "planet.cinder.people": "Cindari", "planet.lunara.name": "Lunara", "planet.lunara.people": "Lunarieten", "planet.mire.name": "Mire", "planet.mire.people": "Mirianen", "planet.galeon.name": "Galeon", "planet.galeon.people": "Galeoni", "planet.obsid.name": "Obsid", "planet.obsid.people": "Obsidianen", "planet.wisp.name": "Wisp", "planet.wisp.people": "Wisplingen", "planet.thorn.name": "Thorn", "planet.thorn.people": "Doornvolk", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "Zephyrieten", "planet.frore.name": "Frore", "planet.frore.people": "Frorianen", "planet.forge.name": "Forge", "planet.forge.people": "Smeedlingen", "block.terra-ember": "Sintel", "block.terra-aqua": "Aqua", "block.terra-leaf": "Blad", "block.terra-sun": "Zon", "block.terra-orchid": "Orchidee", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "Pijl", "block.arrow-chevron": "Chevron", "block.arrow-double": "Dubbele pijl", "block.arrow-return": "Terug", "block.fig-person": "Figuur", "block.fig-walker": "Loper", "block.fig-hero": "Held", "block.face-smile": "Glimlach", "block.face-wink": "Knipoog", "block.face-cool": "Cool", "block.face-grin": "Grijns", "block.icon-heart": "Hart", "block.icon-moon": "Maan", "block.icon-bolt": "Bliksem", "block.icon-shield": "Schild", "block.icon-crown": "Kroon", "block.icon-eye": "Oog", "block.icon-star6": "Zesster", "block.icon-spiral": "Spiraal", "block.icon-wave": "Golf", "block.icon-mountain": "Berg", "block.icon-fish": "Vis", "block.icon-bird": "Vogel", "block.icon-key": "Sleutel", "block.icon-comet": "Komeet", "block.icon-clover": "Klaver", "block.icon-paw": "Poot", "block.icon-sword": "Zwaard", "block.icon-bell": "Bel", "block.icon-mushroom": "Paddenstoel", "block.icon-cactus": "Cactus", "block.icon-ring": "Ring", "block.icon-flag": "Vlag", "block.icon-snow": "Sneeuwvlok", "block.icon-flame": "Vlam", "block.icon-ankh": "Ankh", "block.icon-yin": "Yin en yang", "block.aurel-gold": "Aurel-goud", "block.aurel-cream": "Aurel-crème", "block.aurel-amber": "Aurel-amber", "block.aurel-sage": "Aurel-salie", "block.aurel-rose": "Aurel-roze", "block.cinder-magma": "Cinder-magma", "block.cinder-coal": "Cinder-kool", "block.cinder-spark": "Cinder-vonk", "block.cinder-ash": "Cinder-as", "block.cinder-core": "Cinder-kern", "block.lunara-silver": "Lunara-zilver", "block.lunara-dust": "Lunara-stof", "block.lunara-pale": "Lunara-bleek", "block.lunara-void": "Lunara-leegte", "block.lunara-lilac": "Lunara-lila", "block.mire-moss": "Mire-mos", "block.mire-bog": "Mire-veen", "block.mire-rust": "Mire-roest", "block.mire-spore": "Mire-spore", "block.mire-murk": "Mire-duister", "block.galeon-sky": "Galeon-lucht", "block.galeon-cloud": "Galeon-wolk", "block.galeon-storm": "Galeon-storm", "block.galeon-sand": "Galeon-zand", "block.galeon-kite": "Galeon-vlieger", "block.obsid-glass": "Obsid-glas", "block.obsid-violet": "Obsid-violet", "block.obsid-shard": "Obsid-scherf", "block.obsid-vein": "Obsid-ader", "block.obsid-basalt": "Obsid-basalt", "block.wisp-glow": "Wisp-gloed", "block.wisp-mist": "Wisp-nevel", "block.wisp-sparkle": "Wisp-glitter", "block.wisp-veil": "Wisp-sluier", "block.wisp-gleam": "Wisp-schijn", "block.thorn-briar": "Thorn-braam", "block.thorn-berry": "Thorn-bes", "block.thorn-bark": "Thorn-schors", "block.thorn-petal": "Thorn-bloemblad", "block.thorn-gold": "Thorn-goud", "block.zephyr-azure": "Zephyr-azuur", "block.zephyr-breeze": "Zephyr-bries", "block.zephyr-cirrus": "Zephyr-cirrus", "block.zephyr-dusk": "Zephyr-schemer", "block.zephyr-haze": "Zephyr-waas", "block.frore-ice": "Frore-ijs", "block.frore-frost": "Frore-vorst", "block.frore-deep": "Frore-diep", "block.frore-aurora": "Frore-aurora", "block.frore-rime": "Frore-rijp", "block.forge-iron": "Forge-ijzer", "block.forge-slag": "Forge-slak", "block.forge-spark": "Forge-vonk", "block.forge-brass": "Forge-messing", "block.forge-soot": "Forge-roet", "error.webgl": "Dit spel heeft WebGL nodig. Probeer een andere browser, of zet hardwareversnelling aan.", "error.startFailed": "Het spel kon niet worden gestart.", "reward.won": "Gewonnen!", "reward.lost": "Verloren...", "reward.total": "Totaal punten", "reward.continue": "Tik om verder te gaan", "game.menu": "Menu", "game.paused": "Gepauzeerd", "game.resume": "Verder spelen", "game.backToMenu": "Terug naar hoofdmenu", "reward.ended": "Spel gestopt", "offline.defeated.one": "{n} tegenstander verslagen", "offline.defeated.few": "{n} tegenstanders verslagen", "offline.defeated.many": "{n} tegenstanders verslagen", "offline.defeated.other": "{n} tegenstanders verslagen", "stats.gravity": "{pct}% ({g}g)", "menu.survival": "Overleven", "menu.leaderboard": "Ranglijst", "leaderboard.title": "Ranglijst", "leaderboard.global": "Top 10", "leaderboard.friends": "Vrienden", "leaderboard.empty": "Nog geen scores.", "leaderboard.loginPrompt": "Log in om te zien hoe je vrienden ervoor staan.", "leaderboard.loadError": "De ranglijst kon niet worden geladen.", "leaderboard.points": "{n} punten" }, "de": { "menu.play": "Spielen", "menu.online": "Online spielen", "menu.designer": "Planeten-Designer", "menu.lastScore": "Letzter Punktestand:", "menu.hint": "Ziehe Blöcke senkrecht, um sie zu tauschen. Ziehe einen Block über seine Spalte, um ihn nach oben zu schießen. Blöcke, die das Feld verlassen, bringen Punkte.", "menu.login": "Anmelden", "loginPrompt.title": "Anmelden?", "loginPrompt.body": "Melde dich an, um deine Punkte zu speichern und online zu spielen.", "loginPrompt.guest": "Als Gast spielen", "menu.localTest": "lokaler Test:", "menu.loggedInAs": "Angemeldet als", "menu.total": "Gesamt:", "menu.pointsWord": "Punkte", "menu.logout": "Abmelden", "menu.player": "Spieler", "planet.title": "Wähle ein Feld", "planet.back": "Zurück", "planet.customBadge": "Eigene", "stats.powerLabel": "Power", "online.title": "Online", "online.checking": "Prüfe, ob Online-Spiel verfügbar ist…", "online.notLoaded": "Online-Spiel ist in diesem Build nicht geladen. Du kannst trotzdem offline spielen.", "online.canPlaySolo": "Du kannst trotzdem offline spielen.", "online.unconfiguredHtml": "Online-Spiel ist noch nicht eingerichtet. Der Administrator muss unter auth.timfalken.com/admin den Callback-Pfad /meteors/callback.php hinzufügen (derselbe Client wie bei den anderen Seiten auf dieser Domain; das Geheimnis nicht neu erzeugen) und es in data/config.php auf dem Server eintragen. Siehe die README.", "online.loginPrompt": "Um online zu spielen, melde dich mit deinem Konto auf auth.timfalken.com an.", "online.localTest": "Lokaler Test:", "online.createLobby": "Lobby erstellen", "online.lobbyCode": "Lobby-Code", "online.join": "Beitreten", "online.copy": "Kopieren", "online.copied": "Kopiert", "online.code": "Code:", "online.yourField": "Dein Feld", "online.ready": "Bereit", "online.notReady": "Nicht bereit", "online.start": "Starten", "online.leave": "Verlassen", "online.statusUnconfigured": "Online-Spiel ist noch nicht eingerichtet.", "online.statusLogin": "Melde dich an, um eine Lobby zu erstellen oder einer beizutreten.", "online.statusLobby": "Lobby", "online.statusHome": "Hallo {name}. Erstelle eine Lobby oder tritt mit einem Code bei.", "online.hintStarting": "Das Spiel startet…", "online.hintNeedPlayers": "Warte auf mindestens einen weiteren Spieler. Teile den Code.", "online.hintNeedReady": "Alle müssen auf Bereit drücken. Danach startet der Host.", "online.hintHostStart": "Alle sind bereit. Drücke auf Starten.", "online.hintWaitHost": "Warten, bis der Host startet.", "online.host": "Host", "online.you": "du", "designer.title": "Planeten-Designer", "designer.taglineBefore": "Gesamt:", "designer.taglineAfter": "Punkte.", "designer.empty": "Du hast noch keine eigenen Planeten. Erstelle einen.", "designer.new": "Neuer Planet", "designer.editTitle": "Planet bearbeiten", "designer.createTitle": "Neuer Planet", "designer.name": "Name des Planeten", "designer.people": "Name des Volkes", "designer.gravity": "Schwerkraft", "designer.air": "Luftwiderstand", "designer.mass": "Masse", "designer.power": "Power {n}%", "designer.slotsHint": "Wähle fünf Blöcke. Klicke auf ein Fach, um es zu ändern.", "designer.save": "Speichern", "designer.delete": "Löschen", "designer.cancel": "Zurück", "designer.edit": "Bearbeiten", "designer.pickBlock": "Wähle einen Block", "designer.close": "Schließen", "designer.choose": "Wählen", "designer.slotAria": "Block {n}", "designer.needPoints": "{n} Punkte nötig", "designer.alreadyUsed": "bereits in einem anderen Fach", "designer.confirmDelete": "Planet „{name}“ wirklich löschen?", "designer.deleteFailed": "Löschen ist fehlgeschlagen.", "designer.saveFailed": "Speichern ist fehlgeschlagen.", "designer.needNames": "Gib einen Namen für den Planeten und sein Volk ein.", "designer.needFive": "Wähle fünf Blöcke.", "designer.defaultName": "Neuer Planet", "designer.defaultPeople": "Volk", "hud.points": "Punkte", "hud.round": "Runde {n}", "hud.out": "Raus", "hud.miniPoints": "Punkte {n}", "hud.opponent.one": "Gegner", "hud.opponent.few": "Gegner", "hud.opponent.many": "Gegner", "hud.opponent.other": "Gegner", "offline.resultTitle": "Ergebnis", "offline.reachedBefore": "Du hast Runde", "offline.reachedAfter": " erreicht.", "offline.reached": "Du hast Runde {n} erreicht.", "offline.backMenu": "Zurück zum Menü", "gameover.title": "Du hast verloren", "gameover.detail": "Alle Spalten sind festgesetzt.", "gameover.score": "Punktestand:", "spectator.title": "Du bist raus", "spectator.detail": "Alle deine Spalten sind voll. Du kannst zuschauen oder das Spiel verlassen.", "spectator.watch": "Zuschauen", "podium.title": "Gewonnen!", "podium.subtitle": "Der letzte Spieler steht noch.", "podium.hint": "Zurück zur Lobby in {n} Sekunden…", "podium.line": "{place} {name} · {score} Punkte", "podium.place.1": "1.", "podium.place.2": "2.", "podium.place.3": "3.", "podium.place.n": "{n}.", "lang.current": "Sprache: {name}. Klicken zum Ändern.", "lang.choose": "Wähle eine Sprache", "error.loginRequired": "Melde dich an, um fortzufahren.", "error.unknownPlanet": "Unbekannter Planet.", "error.unknownLanguage": "Unbekannte Sprache.", "error.unknownMode": "Unbekannter Spielmodus.", "error.invalidSession": "Ungültige Spielsitzung.", "error.sessionExpired": "Die Spielsitzung ist abgelaufen.", "error.needFiveBlocks": "Ein Planet braucht genau fünf Blöcke.", "error.unknownBlock": "Unbekannter Block.", "error.blockLocked": "Dieser Block ist noch nicht freigeschaltet.", "error.duplicateBlock": "Jeder Block darf nur in einem Fach liegen.", "error.maxPlanets": "Du hast die Obergrenze von {n} Planeten erreicht.", "error.saveFailed": "Speichern ist fehlgeschlagen.", "error.unknownAction": "Unbekannte Aktion.", "error.internal": "Interner Fehler.", "error.notAvailable": "Nicht verfügbar.", "error.csrf": "Ungültiges oder fehlendes Sicherheits-Token.", "error.alreadyInLobby": "Du bist bereits in einer Lobby. Verlasse sie zuerst.", "error.alreadyInOtherLobby": "Du bist bereits in einer anderen Lobby. Verlasse sie zuerst.", "error.unknownLobby": "Unbekannter Lobby-Code.", "error.lobbyStarted": "Diese Lobby hat bereits begonnen.", "error.lobbyFull": "Diese Lobby ist voll (höchstens {n} Spieler).", "error.notInLobby": "Du bist in keiner Lobby.", "error.notInAnyLobby": "Du bist in keiner Lobby.", "error.hostOnly": "Nur der Host kann das Spiel starten.", "error.gameAlreadyStarted": "Das Spiel hat bereits begonnen.", "error.needTwoPlayers": "Es werden mindestens zwei Spieler gebraucht.", "error.notAllReady": "Nicht alle sind bereit.", "error.planetLocked": "Den Planeten kannst du nur vor Spielbeginn wählen.", "error.fillField": "Gib {field} ein.", "error.fieldPlanet": "einen Planetennamen", "error.fieldPeople": "einen Volksnamen", "error.connection": "Keine Verbindung zum Server.", "error.badResponse": "Der Server hat keine gültige Antwort gesendet.", "error.serverStatus": "Der Server antwortete mit {status}.", "auth.unavailable": "Die Anmeldung ist gerade nicht möglich.", "auth.backToGame": "Zurück zum Spiel", "auth.failed": "Die Anmeldung ist fehlgeschlagen.", "auth.retry": "Erneut versuchen", "auth.back": "Zurück", "planet.terra.name": "Terra", "planet.terra.people": "Terraner", "planet.aurel.name": "Aurel", "planet.aurel.people": "Aurelianer", "planet.cinder.name": "Cinder", "planet.cinder.people": "Cindari", "planet.lunara.name": "Lunara", "planet.lunara.people": "Lunariten", "planet.mire.name": "Mire", "planet.mire.people": "Mirianer", "planet.galeon.name": "Galeon", "planet.galeon.people": "Galeoni", "planet.obsid.name": "Obsid", "planet.obsid.people": "Obsidianer", "planet.wisp.name": "Wisp", "planet.wisp.people": "Wisplinge", "planet.thorn.name": "Thorn", "planet.thorn.people": "Dornvolk", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "Zephyriten", "planet.frore.name": "Frore", "planet.frore.people": "Frorianer", "planet.forge.name": "Forge", "planet.forge.people": "Schmiedlinge", "block.terra-ember": "Glut", "block.terra-aqua": "Aqua", "block.terra-leaf": "Blatt", "block.terra-sun": "Sonne", "block.terra-orchid": "Orchidee", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "Pfeil", "block.arrow-chevron": "Chevron", "block.arrow-double": "Doppelpfeil", "block.arrow-return": "Zurück", "block.fig-person": "Figur", "block.fig-walker": "Läufer", "block.fig-hero": "Held", "block.face-smile": "Lächeln", "block.face-wink": "Zwinkern", "block.face-cool": "Cool", "block.face-grin": "Grinsen", "block.icon-heart": "Herz", "block.icon-moon": "Mond", "block.icon-bolt": "Blitz", "block.icon-shield": "Schild", "block.icon-crown": "Krone", "block.icon-eye": "Auge", "block.icon-star6": "Sechsstern", "block.icon-spiral": "Spirale", "block.icon-wave": "Welle", "block.icon-mountain": "Berg", "block.icon-fish": "Fisch", "block.icon-bird": "Vogel", "block.icon-key": "Schlüssel", "block.icon-comet": "Komet", "block.icon-clover": "Klee", "block.icon-paw": "Pfote", "block.icon-sword": "Schwert", "block.icon-bell": "Glocke", "block.icon-mushroom": "Pilz", "block.icon-cactus": "Kaktus", "block.icon-ring": "Ring", "block.icon-flag": "Flagge", "block.icon-snow": "Schneeflocke", "block.icon-flame": "Flamme", "block.icon-ankh": "Ankh", "block.icon-yin": "Yin und Yang", "block.aurel-gold": "Aurel-Gold", "block.aurel-cream": "Aurel-Creme", "block.aurel-amber": "Aurel-Bernstein", "block.aurel-sage": "Aurel-Salbei", "block.aurel-rose": "Aurel-Rosa", "block.cinder-magma": "Cinder-Magma", "block.cinder-coal": "Cinder-Kohle", "block.cinder-spark": "Cinder-Funke", "block.cinder-ash": "Cinder-Asche", "block.cinder-core": "Cinder-Kern", "block.lunara-silver": "Lunara-Silber", "block.lunara-dust": "Lunara-Staub", "block.lunara-pale": "Lunara-blass", "block.lunara-void": "Lunara-Leere", "block.lunara-lilac": "Lunara-Flieder", "block.mire-moss": "Mire-Moos", "block.mire-bog": "Mire-Moor", "block.mire-rust": "Mire-Rost", "block.mire-spore": "Mire-Spore", "block.mire-murk": "Mire-Dunst", "block.galeon-sky": "Galeon-Himmel", "block.galeon-cloud": "Galeon-Wolke", "block.galeon-storm": "Galeon-Sturm", "block.galeon-sand": "Galeon-Sand", "block.galeon-kite": "Galeon-Drachen", "block.obsid-glass": "Obsid-Glas", "block.obsid-violet": "Obsid-Violett", "block.obsid-shard": "Obsid-Scherbe", "block.obsid-vein": "Obsid-Ader", "block.obsid-basalt": "Obsid-Basalt", "block.wisp-glow": "Wisp-Glühen", "block.wisp-mist": "Wisp-Nebel", "block.wisp-sparkle": "Wisp-Funkeln", "block.wisp-veil": "Wisp-Schleier", "block.wisp-gleam": "Wisp-Schimmer", "block.thorn-briar": "Thorn-Dornbusch", "block.thorn-berry": "Thorn-Beere", "block.thorn-bark": "Thorn-Rinde", "block.thorn-petal": "Thorn-Blütenblatt", "block.thorn-gold": "Thorn-Gold", "block.zephyr-azure": "Zephyr-Azur", "block.zephyr-breeze": "Zephyr-Brise", "block.zephyr-cirrus": "Zephyr-Cirrus", "block.zephyr-dusk": "Zephyr-Dämmerung", "block.zephyr-haze": "Zephyr-Dunst", "block.frore-ice": "Frore-Eis", "block.frore-frost": "Frore-Frost", "block.frore-deep": "Frore-tief", "block.frore-aurora": "Frore-Aurora", "block.frore-rime": "Frore-Raureif", "block.forge-iron": "Forge-Eisen", "block.forge-slag": "Forge-Schlacke", "block.forge-spark": "Forge-Funke", "block.forge-brass": "Forge-Messing", "block.forge-soot": "Forge-Ruß", "error.webgl": "Dieses Spiel benötigt WebGL. Bitte verwende einen anderen Browser oder aktiviere die Hardwarebeschleunigung.", "error.startFailed": "Das Spiel konnte nicht gestartet werden.", "reward.won": "Gewonnen!", "reward.lost": "Verloren...", "reward.total": "Punkte gesamt", "reward.continue": "Tippen zum Fortfahren", "game.menu": "Menü", "game.paused": "Pausiert", "game.resume": "Weiterspielen", "game.backToMenu": "Zurück zum Hauptmenü", "reward.ended": "Spiel beendet", "offline.defeated.one": "{n} Gegner besiegt", "offline.defeated.few": "{n} Gegner besiegt", "offline.defeated.many": "{n} Gegner besiegt", "offline.defeated.other": "{n} Gegner besiegt", "stats.gravity": "{pct} % ({g} g)", "menu.survival": "Überleben", "menu.leaderboard": "Rangliste", "leaderboard.title": "Rangliste", "leaderboard.global": "Top 10", "leaderboard.friends": "Freunde", "leaderboard.empty": "Noch keine Punkte.", "leaderboard.loginPrompt": "Melde dich an, um zu sehen, wie deine Freunde dastehen.", "leaderboard.loadError": "Die Rangliste konnte nicht geladen werden.", "leaderboard.points": "{n} Punkte" }, "fr": { "menu.play": "Jouer", "menu.online": "Jouer en ligne", "menu.designer": "Concepteur de planètes", "menu.lastScore": "Dernier score :", "menu.hint": "Fais glisser les blocs verticalement pour les échanger. Tire un bloc au-dessus de sa colonne pour le lancer. Les blocs qui quittent le terrain rapportent des points.", "menu.login": "Connexion", "loginPrompt.title": "Se connecter ?", "loginPrompt.body": "Connecte-toi pour enregistrer tes points et jouer en ligne.", "loginPrompt.guest": "Jouer en invité", "menu.localTest": "test local :", "menu.loggedInAs": "Connecté en tant que", "menu.total": "Total :", "menu.pointsWord": "points", "menu.logout": "Déconnexion", "menu.player": "joueur", "planet.title": "Choisis un terrain", "planet.back": "Retour", "planet.customBadge": "Perso", "stats.powerLabel": "Puissance", "online.title": "En ligne", "online.checking": "Vérification de la disponibilité du jeu en ligne…", "online.notLoaded": "Le jeu en ligne n’est pas chargé dans cette version. Tu peux quand même jouer hors ligne.", "online.canPlaySolo": "Tu peux quand même jouer hors ligne.", "online.unconfiguredHtml": "Le jeu en ligne n’est pas encore configuré. L’administrateur doit ajouter le chemin de rappel /meteors/callback.php sur auth.timfalken.com/admin (le même client que les autres sites de ce domaine ; il ne faut pas régénérer le secret) et placer ce secret dans data/config.php sur le serveur. Voir le README.", "online.loginPrompt": "Pour jouer en ligne, connecte-toi avec ton compte sur auth.timfalken.com.", "online.localTest": "Test local :", "online.createLobby": "Créer un salon", "online.lobbyCode": "Code du salon", "online.join": "Rejoindre", "online.copy": "Copier", "online.copied": "Copié", "online.code": "Code :", "online.yourField": "Ton terrain", "online.ready": "Prêt", "online.notReady": "Pas prêt", "online.start": "Démarrer", "online.leave": "Quitter", "online.statusUnconfigured": "Le jeu en ligne n’est pas encore configuré.", "online.statusLogin": "Connecte-toi pour créer un salon ou en rejoindre un.", "online.statusLobby": "Salon", "online.statusHome": "Salut {name}. Crée un salon ou rejoins-en un avec un code.", "online.hintStarting": "La partie commence…", "online.hintNeedPlayers": "Attends au moins un autre joueur. Partage le code.", "online.hintNeedReady": "Tout le monde doit appuyer sur Prêt. L’hôte lance ensuite la partie.", "online.hintHostStart": "Tout le monde est prêt. Appuie sur Démarrer.", "online.hintWaitHost": "En attente du lancement par l’hôte.", "online.host": "hôte", "online.you": "toi", "designer.title": "Concepteur de planètes", "designer.taglineBefore": "Total :", "designer.taglineAfter": "points.", "designer.empty": "Tu n’as pas encore de planète à toi. Crées-en une.", "designer.new": "Nouvelle planète", "designer.editTitle": "Modifier la planète", "designer.createTitle": "Nouvelle planète", "designer.name": "Nom de la planète", "designer.people": "Nom du peuple", "designer.gravity": "Gravité", "designer.air": "Résistance de l’air", "designer.mass": "Masse", "designer.power": "Puissance {n} %", "designer.slotsHint": "Choisis cinq blocs. Clique sur un emplacement pour le changer.", "designer.save": "Enregistrer", "designer.delete": "Supprimer", "designer.cancel": "Retour", "designer.edit": "Modifier", "designer.pickBlock": "Choisis un bloc", "designer.close": "Fermer", "designer.choose": "Choisir", "designer.slotAria": "Bloc {n}", "designer.needPoints": "{n} points requis", "designer.alreadyUsed": "déjà dans un autre emplacement", "designer.confirmDelete": "Supprimer la planète « {name} » ?", "designer.deleteFailed": "La suppression a échoué.", "designer.saveFailed": "L’enregistrement a échoué.", "designer.needNames": "Saisis un nom pour la planète et pour son peuple.", "designer.needFive": "Choisis cinq blocs.", "designer.defaultName": "Nouvelle planète", "designer.defaultPeople": "Peuple", "hud.points": "Points", "hud.round": "Manche {n}", "hud.out": "Éliminé", "hud.miniPoints": "Points {n}", "hud.opponent.one": "adversaire", "hud.opponent.few": "adversaires", "hud.opponent.many": "adversaires", "hud.opponent.other": "adversaires", "offline.resultTitle": "Résultat", "offline.reachedBefore": "Tu as atteint la manche", "offline.reachedAfter": ".", "offline.reached": "Tu as atteint la manche {n}.", "offline.backMenu": "Retour au menu", "gameover.title": "Tu as perdu", "gameover.detail": "Toutes les colonnes sont bloquées.", "gameover.score": "Score :", "spectator.title": "Tu es éliminé", "spectator.detail": "Toutes tes colonnes sont pleines. Tu peux regarder ou quitter la partie.", "spectator.watch": "Regarder", "podium.title": "Victoire !", "podium.subtitle": "Le dernier joueur est encore debout.", "podium.hint": "Retour au salon dans {n} secondes…", "podium.line": "{place} {name} · {score} points", "podium.place.1": "1er", "podium.place.2": "2e", "podium.place.3": "3e", "podium.place.n": "{n}e", "lang.current": "Langue : {name}. Clique pour changer.", "lang.choose": "Choisis une langue", "error.loginRequired": "Connecte-toi pour continuer.", "error.unknownPlanet": "Planète inconnue.", "error.unknownLanguage": "Langue inconnue.", "error.unknownMode": "Mode de jeu inconnu.", "error.invalidSession": "Session de jeu invalide.", "error.sessionExpired": "La session de jeu a expiré.", "error.needFiveBlocks": "Une planète a besoin d’exactement cinq blocs.", "error.unknownBlock": "Bloc inconnu.", "error.blockLocked": "Ce bloc n’est pas encore débloqué.", "error.duplicateBlock": "Chaque bloc ne peut occuper qu’un seul emplacement.", "error.maxPlanets": "Tu as atteint la limite de {n} planètes.", "error.saveFailed": "L’enregistrement a échoué.", "error.unknownAction": "Action inconnue.", "error.internal": "Erreur interne.", "error.notAvailable": "Indisponible.", "error.csrf": "Jeton de sécurité invalide ou manquant.", "error.alreadyInLobby": "Tu es déjà dans un salon. Quitte-le d’abord.", "error.alreadyInOtherLobby": "Tu es déjà dans un autre salon. Quitte-le d’abord.", "error.unknownLobby": "Code de salon inconnu.", "error.lobbyStarted": "Ce salon a déjà commencé.", "error.lobbyFull": "Ce salon est complet (maximum {n} joueurs).", "error.notInLobby": "Tu n’es pas dans un salon.", "error.notInAnyLobby": "Tu n’es pas dans un salon.", "error.hostOnly": "Seul l’hôte peut lancer la partie.", "error.gameAlreadyStarted": "La partie a déjà commencé.", "error.needTwoPlayers": "Il faut au moins deux joueurs.", "error.notAllReady": "Tout le monde n’est pas prêt.", "error.planetLocked": "Tu ne peux choisir une planète qu’avant le début de la partie.", "error.fillField": "Saisis {field}.", "error.fieldPlanet": "un nom de planète", "error.fieldPeople": "un nom de peuple", "error.connection": "Pas de connexion au serveur.", "error.badResponse": "Le serveur n’a pas envoyé de réponse valide.", "error.serverStatus": "Le serveur a renvoyé {status}.", "auth.unavailable": "La connexion n’est pas possible pour le moment.", "auth.backToGame": "Retour au jeu", "auth.failed": "La connexion a échoué.", "auth.retry": "Réessayer", "auth.back": "Retour", "planet.terra.name": "Terra", "planet.terra.people": "Terraniens", "planet.aurel.name": "Aurel", "planet.aurel.people": "Auréliens", "planet.cinder.name": "Cinder", "planet.cinder.people": "Cindari", "planet.lunara.name": "Lunara", "planet.lunara.people": "Lunarites", "planet.mire.name": "Mire", "planet.mire.people": "Miriens", "planet.galeon.name": "Galeon", "planet.galeon.people": "Galéoni", "planet.obsid.name": "Obsid", "planet.obsid.people": "Obsidianiens", "planet.wisp.name": "Wisp", "planet.wisp.people": "Wisplings", "planet.thorn.name": "Thorn", "planet.thorn.people": "Peuple d’Épine", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "Zéphyrites", "planet.frore.name": "Frore", "planet.frore.people": "Froriens", "planet.forge.name": "Forge", "planet.forge.people": "Forglins", "block.terra-ember": "Braise", "block.terra-aqua": "Aqua", "block.terra-leaf": "Feuille", "block.terra-sun": "Soleil", "block.terra-orchid": "Orchidée", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "Flèche", "block.arrow-chevron": "Chevron", "block.arrow-double": "Double flèche", "block.arrow-return": "Retour", "block.fig-person": "Figurine", "block.fig-walker": "Marcheur", "block.fig-hero": "Héros", "block.face-smile": "Sourire", "block.face-wink": "Clin d’œil", "block.face-cool": "Cool", "block.face-grin": "Sourire large", "block.icon-heart": "Cœur", "block.icon-moon": "Lune", "block.icon-bolt": "Éclair", "block.icon-shield": "Bouclier", "block.icon-crown": "Couronne", "block.icon-eye": "Œil", "block.icon-star6": "Hexétoile", "block.icon-spiral": "Spirale", "block.icon-wave": "Vague", "block.icon-mountain": "Montagne", "block.icon-fish": "Poisson", "block.icon-bird": "Oiseau", "block.icon-key": "Clé", "block.icon-comet": "Comète", "block.icon-clover": "Trèfle", "block.icon-paw": "Patte", "block.icon-sword": "Épée", "block.icon-bell": "Cloche", "block.icon-mushroom": "Champignon", "block.icon-cactus": "Cactus", "block.icon-ring": "Anneau", "block.icon-flag": "Drapeau", "block.icon-snow": "Flocon", "block.icon-flame": "Flamme", "block.icon-ankh": "Ankh", "block.icon-yin": "Yin Yang", "block.aurel-gold": "Aurel or", "block.aurel-cream": "Aurel crème", "block.aurel-amber": "Aurel ambre", "block.aurel-sage": "Aurel sauge", "block.aurel-rose": "Aurel rose", "block.cinder-magma": "Cinder magma", "block.cinder-coal": "Cinder charbon", "block.cinder-spark": "Cinder étincelle", "block.cinder-ash": "Cinder cendre", "block.cinder-core": "Cinder noyau", "block.lunara-silver": "Lunara argent", "block.lunara-dust": "Lunara poussière", "block.lunara-pale": "Lunara pâle", "block.lunara-void": "Lunara vide", "block.lunara-lilac": "Lunara lilas", "block.mire-moss": "Mire mousse", "block.mire-bog": "Mire tourbière", "block.mire-rust": "Mire rouille", "block.mire-spore": "Mire spore", "block.mire-murk": "Mire obscur", "block.galeon-sky": "Galeon ciel", "block.galeon-cloud": "Galeon nuage", "block.galeon-storm": "Galeon orage", "block.galeon-sand": "Galeon sable", "block.galeon-kite": "Galeon cerf-volant", "block.obsid-glass": "Obsid verre", "block.obsid-violet": "Obsid violet", "block.obsid-shard": "Obsid éclat", "block.obsid-vein": "Obsid veine", "block.obsid-basalt": "Obsid basalte", "block.wisp-glow": "Wisp lueur", "block.wisp-mist": "Wisp brume", "block.wisp-sparkle": "Wisp étincellement", "block.wisp-veil": "Wisp voile", "block.wisp-gleam": "Wisp éclat", "block.thorn-briar": "Thorn ronce", "block.thorn-berry": "Thorn baie", "block.thorn-bark": "Thorn écorce", "block.thorn-petal": "Thorn pétale", "block.thorn-gold": "Thorn or", "block.zephyr-azure": "Zephyr azur", "block.zephyr-breeze": "Zephyr brise", "block.zephyr-cirrus": "Zephyr cirrus", "block.zephyr-dusk": "Zephyr crépuscule", "block.zephyr-haze": "Zephyr brume", "block.frore-ice": "Frore glace", "block.frore-frost": "Frore givre", "block.frore-deep": "Frore profond", "block.frore-aurora": "Frore aurore", "block.frore-rime": "Frore givre", "block.forge-iron": "Forge fer", "block.forge-slag": "Forge scorie", "block.forge-spark": "Forge étincelle", "block.forge-brass": "Forge laiton", "block.forge-soot": "Forge suie", "error.webgl": "Ce jeu a besoin de WebGL. Essayez un autre navigateur, ou activez l’accélération matérielle.", "error.startFailed": "Impossible de lancer le jeu.", "reward.won": "Victoire !", "reward.lost": "Perdu...", "reward.total": "Total des points", "reward.continue": "Touchez pour continuer", "game.menu": "Menu", "game.paused": "En pause", "game.resume": "Reprendre", "game.backToMenu": "Retour au menu principal", "reward.ended": "Partie terminée", "offline.defeated.one": "{n} adversaire vaincu", "offline.defeated.few": "{n} adversaires vaincus", "offline.defeated.many": "{n} adversaires vaincus", "offline.defeated.other": "{n} adversaires vaincus", "stats.gravity": "{pct} % ({g} g)", "menu.survival": "Survie", "menu.leaderboard": "Classement", "leaderboard.title": "Classement", "leaderboard.global": "Top 10", "leaderboard.friends": "Amis", "leaderboard.empty": "Pas encore de scores.", "leaderboard.loginPrompt": "Connecte-toi pour voir le classement de tes amis.", "leaderboard.loadError": "Le classement n'a pas pu être chargé.", "leaderboard.points": "{n} points" }, "ja": { "menu.play": "プレイ", "menu.online": "オンラインで遊ぶ", "menu.designer": "惑星デザイナー", "menu.lastScore": "前回のスコア:", "menu.hint": "ブロックを縦にドラッグして入れ替えます。列の上まで引っ張ると打ち上げられます。フィールドを出たブロックが得点になります。", "menu.login": "ログイン", "loginPrompt.title": "ログインしますか?", "loginPrompt.body": "ログインするとポイントが保存され、オンラインで遊べます。", "loginPrompt.guest": "ゲストとして遊ぶ", "menu.localTest": "ローカルテスト:", "menu.loggedInAs": "ログイン中:", "menu.total": "合計:", "menu.pointsWord": "ポイント", "menu.logout": "ログアウト", "menu.player": "プレイヤー", "planet.title": "フィールドを選ぶ", "planet.back": "戻る", "planet.customBadge": "自作", "stats.powerLabel": "パワー", "online.title": "オンライン", "online.checking": "オンラインプレイが使えるか確認しています…", "online.notLoaded": "このビルドにはオンラインプレイが含まれていません。オフラインでは遊べます。", "online.canPlaySolo": "オフラインでは遊べます。", "online.unconfiguredHtml": "オンラインプレイはまだ設定されていません。管理者は auth.timfalken.com/admin でコールバックパス /meteors/callback.php を追加し(このドメインの他サイトと同じクライアントを使い、秘密は再生成しないでください)、その秘密をサーバーの data/config.php に書いてください。README を参照。", "online.loginPrompt": "オンラインで遊ぶには、auth.timfalken.com のアカウントでログインしてください。", "online.localTest": "ローカルテスト:", "online.createLobby": "ロビーを作る", "online.lobbyCode": "ロビーコード", "online.join": "参加", "online.copy": "コピー", "online.copied": "コピーしました", "online.code": "コード:", "online.yourField": "あなたのフィールド", "online.ready": "準備完了", "online.notReady": "準備を取り消す", "online.start": "開始", "online.leave": "退出", "online.statusUnconfigured": "オンラインプレイはまだ設定されていません。", "online.statusLogin": "ログインしてロビーを作るか参加してください。", "online.statusLobby": "ロビー", "online.statusHome": "{name}さん、こんにちは。ロビーを作るか、コードで参加してください。", "online.hintStarting": "ゲームを開始します…", "online.hintNeedPlayers": "他のプレイヤーを待って、コードを共有してください。", "online.hintNeedReady": "全員が「準備完了」を押してください。その後ホストが開始します。", "online.hintHostStart": "全員の準備ができました。「開始」を押してください。", "online.hintWaitHost": "ホストの開始を待っています。", "online.host": "ホスト", "online.you": "あなた", "designer.title": "惑星デザイナー", "designer.taglineBefore": "合計:", "designer.taglineAfter": "ポイント。", "designer.empty": "まだ自分の惑星がありません。新しく作ってみましょう。", "designer.new": "新しい惑星", "designer.editTitle": "惑星を編集", "designer.createTitle": "新しい惑星", "designer.name": "惑星の名前", "designer.people": "民の名前", "designer.gravity": "重力", "designer.air": "空気抵抗", "designer.mass": "質量", "designer.power": "パワー {n}%", "designer.slotsHint": "ブロックを五つ選んでください。枠をタップすると変更できます。", "designer.save": "保存", "designer.delete": "削除", "designer.cancel": "戻る", "designer.edit": "編集", "designer.pickBlock": "ブロックを選ぶ", "designer.close": "閉じる", "designer.choose": "選ぶ", "designer.slotAria": "ブロック {n}", "designer.needPoints": "{n} ポイント必要", "designer.alreadyUsed": "すでに別の枠で使用中", "designer.confirmDelete": "惑星「{name}」を削除しますか?", "designer.deleteFailed": "削除に失敗しました。", "designer.saveFailed": "保存に失敗しました。", "designer.needNames": "惑星と民の名前を入力してください。", "designer.needFive": "ブロックを五つ選んでください。", "designer.defaultName": "新しい惑星", "designer.defaultPeople": "民", "hud.points": "ポイント", "hud.round": "ラウンド {n}", "hud.out": "脱落", "hud.miniPoints": "ポイント {n}", "hud.opponent.one": "相手", "hud.opponent.few": "相手", "hud.opponent.many": "相手", "hud.opponent.other": "相手", "offline.resultTitle": "結果", "offline.reachedBefore": "到達ラウンド:", "offline.reachedAfter": "。", "offline.reached": "ラウンド {n} まで到達しました。", "offline.backMenu": "メニューに戻る", "gameover.title": "負けました", "gameover.detail": "すべての列がロックされました。", "gameover.score": "スコア:", "spectator.title": "脱落しました", "spectator.detail": "すべての列がいっぱいです。観戦するか、試合を退出できます。", "spectator.watch": "観戦する", "podium.title": "勝利!", "podium.subtitle": "最後のプレイヤーが残りました。", "podium.hint": "{n} 秒後にロビーへ戻ります…", "podium.line": "{place} {name} · {score} ポイント", "podium.place.1": "1位", "podium.place.2": "2位", "podium.place.3": "3位", "podium.place.n": "{n}位", "lang.current": "言語: {name}。クリックして変更します。", "lang.choose": "言語を選ぶ", "error.loginRequired": "続行するにはログインしてください。", "error.unknownPlanet": "不明な惑星です。", "error.unknownLanguage": "不明な言語です。", "error.unknownMode": "不明なプレイモードです。", "error.invalidSession": "無効なプレイセッションです。", "error.sessionExpired": "プレイセッションの期限が切れました。", "error.needFiveBlocks": "惑星にはちょうど五つのブロックが必要です。", "error.unknownBlock": "不明なブロックです。", "error.blockLocked": "このブロックはまだ解放されていません。", "error.duplicateBlock": "同じブロックは一つの枠にしか使えません。", "error.maxPlanets": "惑星は最大 {n} 個までです。", "error.saveFailed": "保存に失敗しました。", "error.unknownAction": "不明な操作です。", "error.internal": "内部エラーです。", "error.notAvailable": "利用できません。", "error.csrf": "セキュリティトークンが無効か、ありません。", "error.alreadyInLobby": "すでにロビーに入っています。先に退出してください。", "error.alreadyInOtherLobby": "すでに別のロビーに入っています。先に退出してください。", "error.unknownLobby": "不明なロビーコードです。", "error.lobbyStarted": "このロビーはすでに始まっています。", "error.lobbyFull": "このロビーは満員です(最大 {n} 人)。", "error.notInLobby": "ロビーに入っていません。", "error.notInAnyLobby": "ロビーに入っていません。", "error.hostOnly": "ホストだけがゲームを開始できます。", "error.gameAlreadyStarted": "ゲームはすでに始まっています。", "error.needTwoPlayers": "プレイヤーは少なくとも二人必要です。", "error.notAllReady": "全員の準備ができていません。", "error.planetLocked": "惑星はゲーム開始前にしか選べません。", "error.fillField": "{field}を入力してください。", "error.fieldPlanet": "惑星名", "error.fieldPeople": "民の名前", "error.connection": "サーバーに接続できません。", "error.badResponse": "サーバーから有効な応答がありません。", "error.serverStatus": "サーバーは {status} を返しました。", "auth.unavailable": "現在ログインできません。", "auth.backToGame": "ゲームに戻る", "auth.failed": "ログインに失敗しました。", "auth.retry": "再試行", "auth.back": "戻る", "planet.terra.name": "Terra", "planet.terra.people": "テラン", "planet.aurel.name": "Aurel", "planet.aurel.people": "オーレル人", "planet.cinder.name": "Cinder", "planet.cinder.people": "シンダリ", "planet.lunara.name": "Lunara", "planet.lunara.people": "ルナライト", "planet.mire.name": "Mire", "planet.mire.people": "ミリアン", "planet.galeon.name": "Galeon", "planet.galeon.people": "ガレオニ", "planet.obsid.name": "Obsid", "planet.obsid.people": "オブシディアン", "planet.wisp.name": "Wisp", "planet.wisp.people": "ウィスプリング", "planet.thorn.name": "Thorn", "planet.thorn.people": "ソーンフォーク", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "ゼファライト", "planet.frore.name": "Frore", "planet.frore.people": "フロリアン", "planet.forge.name": "Forge", "planet.forge.people": "フォージリング", "block.terra-ember": "残り火", "block.terra-aqua": "アクア", "block.terra-leaf": "葉", "block.terra-sun": "太陽", "block.terra-orchid": "蘭", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "矢", "block.arrow-chevron": "シェブロン", "block.arrow-double": "二重の矢", "block.arrow-return": "戻り", "block.fig-person": "人", "block.fig-walker": "歩き", "block.fig-hero": "英雄", "block.face-smile": "微笑", "block.face-wink": "ウインク", "block.face-cool": "クール", "block.face-grin": "にやり", "block.icon-heart": "ハート", "block.icon-moon": "月", "block.icon-bolt": "雷", "block.icon-shield": "盾", "block.icon-crown": "王冠", "block.icon-eye": "目", "block.icon-star6": "六芒星", "block.icon-spiral": "渦巻き", "block.icon-wave": "波", "block.icon-mountain": "山", "block.icon-fish": "魚", "block.icon-bird": "鳥", "block.icon-key": "鍵", "block.icon-comet": "彗星", "block.icon-clover": "クローバー", "block.icon-paw": "足跡", "block.icon-sword": "剣", "block.icon-bell": "鈴", "block.icon-mushroom": "きのこ", "block.icon-cactus": "サボテン", "block.icon-ring": "指輪", "block.icon-flag": "旗", "block.icon-snow": "雪の結晶", "block.icon-flame": "炎", "block.icon-ankh": "アンク", "block.icon-yin": "陰陽", "block.aurel-gold": "オーレルの金", "block.aurel-cream": "オーレルのクリーム", "block.aurel-amber": "オーレルの琥珀", "block.aurel-sage": "オーレルのセージ", "block.aurel-rose": "オーレルの薔薇", "block.cinder-magma": "シンダーのマグマ", "block.cinder-coal": "シンダーの石炭", "block.cinder-spark": "シンダーの火花", "block.cinder-ash": "シンダーの灰", "block.cinder-core": "シンダーの核", "block.lunara-silver": "ルナラの銀", "block.lunara-dust": "ルナラの塵", "block.lunara-pale": "ルナラの淡い", "block.lunara-void": "ルナラの虚空", "block.lunara-lilac": "ルナラのライラック", "block.mire-moss": "マイアの苔", "block.mire-bog": "マイアの湿地", "block.mire-rust": "マイアの錆", "block.mire-spore": "マイアの胞子", "block.mire-murk": "マイアの闇", "block.galeon-sky": "ガレオンの空", "block.galeon-cloud": "ガレオンの雲", "block.galeon-storm": "ガレオンの嵐", "block.galeon-sand": "ガレオンの砂", "block.galeon-kite": "ガレオンの凧", "block.obsid-glass": "オブシドのガラス", "block.obsid-violet": "オブシドの紫", "block.obsid-shard": "オブシドの破片", "block.obsid-vein": "オブシドの脈", "block.obsid-basalt": "オブシドの玄武岩", "block.wisp-glow": "ウィスプの輝き", "block.wisp-mist": "ウィスプの霧", "block.wisp-sparkle": "ウィスプのきらめき", "block.wisp-veil": "ウィスプのヴェール", "block.wisp-gleam": "ウィスプの輝き", "block.thorn-briar": "ソーンの茨", "block.thorn-berry": "ソーンの実", "block.thorn-bark": "ソーンの樹皮", "block.thorn-petal": "ソーンの花びら", "block.thorn-gold": "ソーンの金", "block.zephyr-azure": "ゼファーの紺碧", "block.zephyr-breeze": "ゼファーのそよ風", "block.zephyr-cirrus": "ゼファーの巻雲", "block.zephyr-dusk": "ゼファーの黄昏", "block.zephyr-haze": "ゼファーの霞", "block.frore-ice": "フロアの氷", "block.frore-frost": "フロアの霜", "block.frore-deep": "フロアの深海", "block.frore-aurora": "フロアのオーロラ", "block.frore-rime": "フロアの樹霜", "block.forge-iron": "フォージの鉄", "block.forge-slag": "フォージのスラグ", "block.forge-spark": "フォージの火花", "block.forge-brass": "フォージの真鍮", "block.forge-soot": "フォージの煤", "error.webgl": "このゲームにはWebGLが必要です。別のブラウザを使うか、ハードウェアアクセラレーションを有効にしてください。", "error.startFailed": "ゲームを開始できませんでした。", "reward.won": "勝利!", "reward.lost": "敗北...", "reward.total": "合計ポイント", "reward.continue": "タップして続ける", "game.menu": "メニュー", "game.paused": "一時停止中", "game.resume": "再開", "game.backToMenu": "メインメニューに戻る", "reward.ended": "ゲーム終了", "offline.defeated.one": "{n}人の相手を倒した", "offline.defeated.few": "{n}人の相手を倒した", "offline.defeated.many": "{n}人の相手を倒した", "offline.defeated.other": "{n}人の相手を倒した", "stats.gravity": "{pct}% ({g}g)", "menu.survival": "サバイバル", "menu.leaderboard": "ランキング", "leaderboard.title": "ランキング", "leaderboard.global": "トップ10", "leaderboard.friends": "フレンド", "leaderboard.empty": "まだスコアがありません。", "leaderboard.loginPrompt": "ログインするとフレンドの順位が見られます。", "leaderboard.loadError": "ランキングを読み込めませんでした。", "leaderboard.points": "{n} ポイント" }, "zh": { "menu.play": "开始游戏", "menu.online": "在线游戏", "menu.designer": "星球设计器", "menu.lastScore": "上次得分:", "menu.hint": "上下拖动方块来交换位置。把方块拉到其所在列的上方即可发射。离开场地的方块会得分。", "menu.login": "登录", "loginPrompt.title": "要登录吗?", "loginPrompt.body": "登录后可保存分数并在线游玩。", "loginPrompt.guest": "以游客身份游玩", "menu.localTest": "本地测试:", "menu.loggedInAs": "已登录:", "menu.total": "总分:", "menu.pointsWord": "分", "menu.logout": "退出", "menu.player": "玩家", "planet.title": "选择场地", "planet.back": "返回", "planet.customBadge": "自制", "stats.powerLabel": "力量", "online.title": "在线", "online.checking": "正在检查在线游戏是否可用…", "online.notLoaded": "此版本未加载在线游戏。你仍然可以离线游戏。", "online.canPlaySolo": "你仍然可以离线游戏。", "online.unconfiguredHtml": "在线游戏尚未配置。管理员需要在 auth.timfalken.com/admin 添加回调路径 /meteors/callback.php(使用本域其他站点的同一客户端;不要重新生成密钥),并把该密钥写入服务器上的 data/config.php。详见 README。", "online.loginPrompt": "要在线游玩,请使用你在 auth.timfalken.com 上的账号登录。", "online.localTest": "本地测试:", "online.createLobby": "创建大厅", "online.lobbyCode": "大厅代码", "online.join": "加入", "online.copy": "复制", "online.copied": "已复制", "online.code": "代码:", "online.yourField": "你的场地", "online.ready": "准备就绪", "online.notReady": "取消准备", "online.start": "开始", "online.leave": "离开", "online.statusUnconfigured": "在线游戏尚未配置。", "online.statusLogin": "登录以创建或加入大厅。", "online.statusLobby": "大厅", "online.statusHome": "你好,{name}。创建一个大厅,或用代码加入。", "online.hintStarting": "游戏即将开始…", "online.hintNeedPlayers": "至少再等一位玩家,并把代码分享出去。", "online.hintNeedReady": "所有人都必须按下“准备就绪”,然后由房主开始。", "online.hintHostStart": "所有人都已准备好。请按“开始”。", "online.hintWaitHost": "正在等待房主开始。", "online.host": "房主", "online.you": "你", "designer.title": "星球设计器", "designer.taglineBefore": "总分:", "designer.taglineAfter": "分。", "designer.empty": "你还没有自己的星球。来创建一个吧。", "designer.new": "新星球", "designer.editTitle": "编辑星球", "designer.createTitle": "新星球", "designer.name": "星球名称", "designer.people": "居民名称", "designer.gravity": "重力", "designer.air": "空气阻力", "designer.mass": "质量", "designer.power": "力量 {n}%", "designer.slotsHint": "选择五个方块。点击空位即可更换。", "designer.save": "保存", "designer.delete": "删除", "designer.cancel": "返回", "designer.edit": "编辑", "designer.pickBlock": "选择方块", "designer.close": "关闭", "designer.choose": "选择", "designer.slotAria": "方块 {n}", "designer.needPoints": "需要 {n} 分", "designer.alreadyUsed": "已在其他空位中", "designer.confirmDelete": "要删除星球“{name}”吗?", "designer.deleteFailed": "删除失败。", "designer.saveFailed": "保存失败。", "designer.needNames": "请填写星球名称和居民名称。", "designer.needFive": "请选择五个方块。", "designer.defaultName": "新星球", "designer.defaultPeople": "居民", "hud.points": "分数", "hud.round": "第 {n} 轮", "hud.out": "出局", "hud.miniPoints": "分数 {n}", "hud.opponent.one": "对手", "hud.opponent.few": "对手", "hud.opponent.many": "对手", "hud.opponent.other": "对手", "offline.resultTitle": "结果", "offline.reachedBefore": "你到达了第", "offline.reachedAfter": " 轮。", "offline.reached": "你到达了第 {n} 轮。", "offline.backMenu": "返回菜单", "gameover.title": "你输了", "gameover.detail": "所有列都已锁定。", "gameover.score": "得分:", "spectator.title": "你出局了", "spectator.detail": "你的所有列都已满。你可以旁观或离开比赛。", "spectator.watch": "旁观", "podium.title": "胜利!", "podium.subtitle": "最后一名玩家仍然站着。", "podium.hint": "{n} 秒后返回大厅…", "podium.line": "{place} {name} · {score} 分", "podium.place.1": "第1", "podium.place.2": "第2", "podium.place.3": "第3", "podium.place.n": "第{n}", "lang.current": "语言:{name}。点击可更改。", "lang.choose": "选择语言", "error.loginRequired": "请登录后再继续。", "error.unknownPlanet": "未知星球。", "error.unknownLanguage": "未知语言。", "error.unknownMode": "未知游戏模式。", "error.invalidSession": "无效的游戏会话。", "error.sessionExpired": "游戏会话已过期。", "error.needFiveBlocks": "一颗星球必须正好有五个方块。", "error.unknownBlock": "未知方块。", "error.blockLocked": "此方块尚未解锁。", "error.duplicateBlock": "每个方块只能放在一个空位里。", "error.maxPlanets": "你已达到 {n} 颗星球的上限。", "error.saveFailed": "保存失败。", "error.unknownAction": "未知操作。", "error.internal": "内部错误。", "error.notAvailable": "不可用。", "error.csrf": "安全令牌无效或缺失。", "error.alreadyInLobby": "你已在一个大厅中。请先离开。", "error.alreadyInOtherLobby": "你已在另一个大厅中。请先离开。", "error.unknownLobby": "未知的大厅代码。", "error.lobbyStarted": "该大厅已经开始。", "error.lobbyFull": "该大厅已满(最多 {n} 名玩家)。", "error.notInLobby": "你不在大厅中。", "error.notInAnyLobby": "你不在大厅中。", "error.hostOnly": "只有房主可以开始游戏。", "error.gameAlreadyStarted": "游戏已经开始。", "error.needTwoPlayers": "至少需要两名玩家。", "error.notAllReady": "还有人尚未准备就绪。", "error.planetLocked": "只能在游戏开始前选择星球。", "error.fillField": "请填写{field}。", "error.fieldPlanet": "星球名称", "error.fieldPeople": "居民名称", "error.connection": "无法连接服务器。", "error.badResponse": "服务器未返回有效回复。", "error.serverStatus": "服务器返回了 {status}。", "auth.unavailable": "暂时无法登录。", "auth.backToGame": "返回游戏", "auth.failed": "登录失败。", "auth.retry": "再试一次", "auth.back": "返回", "planet.terra.name": "Terra", "planet.terra.people": "泰拉人", "planet.aurel.name": "Aurel", "planet.aurel.people": "奥瑞尔人", "planet.cinder.name": "Cinder", "planet.cinder.people": "辛达里", "planet.lunara.name": "Lunara", "planet.lunara.people": "月民", "planet.mire.name": "Mire", "planet.mire.people": "米尔人", "planet.galeon.name": "Galeon", "planet.galeon.people": "加莱昂人", "planet.obsid.name": "Obsid", "planet.obsid.people": "黑曜民", "planet.wisp.name": "Wisp", "planet.wisp.people": "灵光民", "planet.thorn.name": "Thorn", "planet.thorn.people": "荆棘民", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "西风民", "planet.frore.name": "Frore", "planet.frore.people": "弗罗里安", "planet.forge.name": "Forge", "planet.forge.people": "锻民", "block.terra-ember": "余烬", "block.terra-aqua": "水色", "block.terra-leaf": "叶子", "block.terra-sun": "太阳", "block.terra-orchid": "兰花", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "箭", "block.arrow-chevron": "折线", "block.arrow-double": "双箭头", "block.arrow-return": "返回", "block.fig-person": "小人", "block.fig-walker": "行走者", "block.fig-hero": "英雄", "block.face-smile": "微笑", "block.face-wink": "眨眼", "block.face-cool": "酷", "block.face-grin": "咧笑", "block.icon-heart": "心", "block.icon-moon": "月亮", "block.icon-bolt": "闪电", "block.icon-shield": "盾", "block.icon-crown": "王冠", "block.icon-eye": "眼睛", "block.icon-star6": "六角星", "block.icon-spiral": "螺旋", "block.icon-wave": "波浪", "block.icon-mountain": "山", "block.icon-fish": "鱼", "block.icon-bird": "鸟", "block.icon-key": "钥匙", "block.icon-comet": "彗星", "block.icon-clover": "四叶草", "block.icon-paw": "爪印", "block.icon-sword": "剑", "block.icon-bell": "铃", "block.icon-mushroom": "蘑菇", "block.icon-cactus": "仙人掌", "block.icon-ring": "戒指", "block.icon-flag": "旗", "block.icon-snow": "雪花", "block.icon-flame": "火焰", "block.icon-ankh": "安卡", "block.icon-yin": "阴阳", "block.aurel-gold": "Aurel金", "block.aurel-cream": "Aurel奶油", "block.aurel-amber": "Aurel琥珀", "block.aurel-sage": "Aurel鼠尾草", "block.aurel-rose": "Aurel玫瑰", "block.cinder-magma": "Cinder岩浆", "block.cinder-coal": "Cinder煤", "block.cinder-spark": "Cinder火花", "block.cinder-ash": "Cinder灰", "block.cinder-core": "Cinder核心", "block.lunara-silver": "Lunara银", "block.lunara-dust": "Lunara尘", "block.lunara-pale": "Lunara苍白", "block.lunara-void": "Lunara虚空", "block.lunara-lilac": "Lunara丁香", "block.mire-moss": "Mire苔藓", "block.mire-bog": "Mire沼泽", "block.mire-rust": "Mire锈", "block.mire-spore": "Mire孢子", "block.mire-murk": "Mire昏暗", "block.galeon-sky": "Galeon天空", "block.galeon-cloud": "Galeon云", "block.galeon-storm": "Galeon风暴", "block.galeon-sand": "Galeon沙", "block.galeon-kite": "Galeon风筝", "block.obsid-glass": "Obsid玻璃", "block.obsid-violet": "Obsid紫", "block.obsid-shard": "Obsid碎片", "block.obsid-vein": "Obsid矿脉", "block.obsid-basalt": "Obsid玄武岩", "block.wisp-glow": "Wisp辉光", "block.wisp-mist": "Wisp雾", "block.wisp-sparkle": "Wisp闪光", "block.wisp-veil": "Wisp面纱", "block.wisp-gleam": "Wisp微光", "block.thorn-briar": "Thorn荆棘", "block.thorn-berry": "Thorn浆果", "block.thorn-bark": "Thorn树皮", "block.thorn-petal": "Thorn花瓣", "block.thorn-gold": "Thorn金", "block.zephyr-azure": "Zephyr蔚蓝", "block.zephyr-breeze": "Zephyr微风", "block.zephyr-cirrus": "Zephyr卷云", "block.zephyr-dusk": "Zephyr黄昏", "block.zephyr-haze": "Zephyr薄雾", "block.frore-ice": "Frore冰", "block.frore-frost": "Frore霜", "block.frore-deep": "Frore深", "block.frore-aurora": "Frore极光", "block.frore-rime": "Frore雾凇", "block.forge-iron": "Forge铁", "block.forge-slag": "Forge炉渣", "block.forge-spark": "Forge火花", "block.forge-brass": "Forge黄铜", "block.forge-soot": "Forge煤烟", "error.webgl": "本游戏需要 WebGL。请尝试其他浏览器,或开启硬件加速。", "error.startFailed": "无法开始游戏。", "reward.won": "你赢了!", "reward.lost": "你输了...", "reward.total": "总积分", "reward.continue": "点击继续", "game.menu": "菜单", "game.paused": "已暂停", "game.resume": "继续游戏", "game.backToMenu": "返回主菜单", "reward.ended": "游戏结束", "offline.defeated.one": "击败了 {n} 名对手", "offline.defeated.few": "击败了 {n} 名对手", "offline.defeated.many": "击败了 {n} 名对手", "offline.defeated.other": "击败了 {n} 名对手", "stats.gravity": "{pct}% ({g}g)", "menu.survival": "生存", "menu.leaderboard": "排行榜", "leaderboard.title": "排行榜", "leaderboard.global": "前 10 名", "leaderboard.friends": "好友", "leaderboard.empty": "还没有分数。", "leaderboard.loginPrompt": "登录后即可查看好友排名。", "leaderboard.loadError": "无法加载排行榜。", "leaderboard.points": "{n} 分" }, "ko": { "menu.play": "플레이", "menu.online": "온라인 플레이", "menu.designer": "행성 디자이너", "menu.lastScore": "이전 점수:", "menu.hint": "블록을 세로로 끌어 자리를 바꿉니다. 열 위로 끌어올리면 발사됩니다. 필드를 벗어난 블록이 점수가 됩니다.", "menu.login": "로그인", "loginPrompt.title": "로그인할까요?", "loginPrompt.body": "로그인하면 점수가 저장되고 온라인으로 플레이할 수 있습니다.", "loginPrompt.guest": "게스트로 플레이", "menu.localTest": "로컬 테스트:", "menu.loggedInAs": "로그인:", "menu.total": "합계:", "menu.pointsWord": "점", "menu.logout": "로그아웃", "menu.player": "플레이어", "planet.title": "필드 선택", "planet.back": "뒤로", "planet.customBadge": "내 것", "stats.powerLabel": "파워", "online.title": "온라인", "online.checking": "온라인 플레이가 가능한지 확인하는 중…", "online.notLoaded": "이 빌드에는 온라인 플레이가 없습니다. 오프라인으로는 플레이할 수 있습니다.", "online.canPlaySolo": "오프라인으로는 플레이할 수 있습니다.", "online.unconfiguredHtml": "온라인 플레이가 아직 설정되지 않았습니다. 관리자는 auth.timfalken.com/admin에서 콜백 경로 /meteors/callback.php를 추가하고(이 도메인의 다른 사이트와 같은 클라이언트를 사용하며, 비밀키를 다시 생성하지 마세요), 그 비밀키를 서버의 data/config.php에 넣어야 합니다. README를 참고하세요.", "online.loginPrompt": "온라인으로 플레이하려면 auth.timfalken.com 계정으로 로그인하세요.", "online.localTest": "로컬 테스트:", "online.createLobby": "로비 만들기", "online.lobbyCode": "로비 코드", "online.join": "참가", "online.copy": "복사", "online.copied": "복사됨", "online.code": "코드:", "online.yourField": "내 필드", "online.ready": "준비", "online.notReady": "준비 취소", "online.start": "시작", "online.leave": "나가기", "online.statusUnconfigured": "온라인 플레이가 아직 설정되지 않았습니다.", "online.statusLogin": "로그인하여 로비를 만들거나 참가하세요.", "online.statusLobby": "로비", "online.statusHome": "{name} 님, 안녕하세요. 로비를 만들거나 코드로 참가하세요.", "online.hintStarting": "게임이 시작됩니다…", "online.hintNeedPlayers": "다른 플레이어를 적어도 한 명 기다리고, 코드를 공유하세요.", "online.hintNeedReady": "모두 「준비」를 눌러야 합니다. 그다음 호스트가 시작합니다.", "online.hintHostStart": "모두 준비되었습니다. 「시작」을 누르세요.", "online.hintWaitHost": "호스트가 시작하기를 기다리는 중.", "online.host": "호스트", "online.you": "나", "designer.title": "행성 디자이너", "designer.taglineBefore": "합계:", "designer.taglineAfter": "점.", "designer.empty": "아직 내 행성이 없습니다. 하나 만들어 보세요.", "designer.new": "새 행성", "designer.editTitle": "행성 편집", "designer.createTitle": "새 행성", "designer.name": "행성 이름", "designer.people": "주민 이름", "designer.gravity": "중력", "designer.air": "공기 저항", "designer.mass": "질량", "designer.power": "파워 {n}%", "designer.slotsHint": "블록 다섯 개를 고르세요. 칸을 눌러 바꿀 수 있습니다.", "designer.save": "저장", "designer.delete": "삭제", "designer.cancel": "뒤로", "designer.edit": "편집", "designer.pickBlock": "블록 선택", "designer.close": "닫기", "designer.choose": "선택", "designer.slotAria": "블록 {n}", "designer.needPoints": "{n}점 필요", "designer.alreadyUsed": "이미 다른 칸에 사용 중", "designer.confirmDelete": "행성 “{name}”을(를) 삭제할까요?", "designer.deleteFailed": "삭제에 실패했습니다.", "designer.saveFailed": "저장에 실패했습니다.", "designer.needNames": "행성 이름과 주민 이름을 입력하세요.", "designer.needFive": "블록 다섯 개를 고르세요.", "designer.defaultName": "새 행성", "designer.defaultPeople": "주민", "hud.points": "점수", "hud.round": "{n}라운드", "hud.out": "탈락", "hud.miniPoints": "점수 {n}", "hud.opponent.one": "상대", "hud.opponent.few": "상대", "hud.opponent.many": "상대", "hud.opponent.other": "상대", "offline.resultTitle": "결과", "offline.reachedBefore": "도달한 라운드:", "offline.reachedAfter": ".", "offline.reached": "{n}라운드까지 도달했습니다.", "offline.backMenu": "메뉴로 돌아가기", "gameover.title": "패배했습니다", "gameover.detail": "모든 열이 잠겼습니다.", "gameover.score": "점수:", "spectator.title": "탈락했습니다", "spectator.detail": "모든 열이 가득 찼습니다. 관전하거나 경기에서 나갈 수 있습니다.", "spectator.watch": "관전", "podium.title": "승리!", "podium.subtitle": "마지막 플레이어가 남았습니다.", "podium.hint": "{n}초 후 로비로 돌아갑니다…", "podium.line": "{place} {name} · {score}점", "podium.place.1": "1위", "podium.place.2": "2위", "podium.place.3": "3위", "podium.place.n": "{n}위", "lang.current": "언어: {name}. 클릭하여 변경하세요.", "lang.choose": "언어 선택", "error.loginRequired": "계속하려면 로그인하세요.", "error.unknownPlanet": "알 수 없는 행성입니다.", "error.unknownLanguage": "알 수 없는 언어입니다.", "error.unknownMode": "알 수 없는 플레이 모드입니다.", "error.invalidSession": "유효하지 않은 플레이 세션입니다.", "error.sessionExpired": "플레이 세션이 만료되었습니다.", "error.needFiveBlocks": "행성에는 블록이 정확히 다섯 개 필요합니다.", "error.unknownBlock": "알 수 없는 블록입니다.", "error.blockLocked": "이 블록은 아직 해금되지 않았습니다.", "error.duplicateBlock": "같은 블록은 한 칸에만 쓸 수 있습니다.", "error.maxPlanets": "행성은 최대 {n}개까지입니다.", "error.saveFailed": "저장에 실패했습니다.", "error.unknownAction": "알 수 없는 작업입니다.", "error.internal": "내부 오류입니다.", "error.notAvailable": "사용할 수 없습니다.", "error.csrf": "보안 토큰이 없거나 유효하지 않습니다.", "error.alreadyInLobby": "이미 로비에 있습니다. 먼저 나가세요.", "error.alreadyInOtherLobby": "이미 다른 로비에 있습니다. 먼저 나가세요.", "error.unknownLobby": "알 수 없는 로비 코드입니다.", "error.lobbyStarted": "이 로비는 이미 시작되었습니다.", "error.lobbyFull": "이 로비는 가득 찼습니다(최대 {n}명).", "error.notInLobby": "로비에 있지 않습니다.", "error.notInAnyLobby": "로비에 있지 않습니다.", "error.hostOnly": "호스트만 게임을 시작할 수 있습니다.", "error.gameAlreadyStarted": "게임이 이미 시작되었습니다.", "error.needTwoPlayers": "플레이어가 적어도 두 명 필요합니다.", "error.notAllReady": "아직 모두 준비되지 않았습니다.", "error.planetLocked": "행성은 게임이 시작되기 전에만 고를 수 있습니다.", "error.fillField": "{field}을(를) 입력하세요.", "error.fieldPlanet": "행성 이름", "error.fieldPeople": "주민 이름", "error.connection": "서버에 연결할 수 없습니다.", "error.badResponse": "서버가 유효한 응답을 보내지 않았습니다.", "error.serverStatus": "서버가 {status}을(를) 반환했습니다.", "auth.unavailable": "지금은 로그인할 수 없습니다.", "auth.backToGame": "게임으로 돌아가기", "auth.failed": "로그인에 실패했습니다.", "auth.retry": "다시 시도", "auth.back": "뒤로", "planet.terra.name": "Terra", "planet.terra.people": "테란", "planet.aurel.name": "Aurel", "planet.aurel.people": "아우렐인", "planet.cinder.name": "Cinder", "planet.cinder.people": "신다리", "planet.lunara.name": "Lunara", "planet.lunara.people": "루나라이트", "planet.mire.name": "Mire", "planet.mire.people": "미리안", "planet.galeon.name": "Galeon", "planet.galeon.people": "갈레오니", "planet.obsid.name": "Obsid", "planet.obsid.people": "옵시디안", "planet.wisp.name": "Wisp", "planet.wisp.people": "위스플링", "planet.thorn.name": "Thorn", "planet.thorn.people": "손포크", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "제피라이트", "planet.frore.name": "Frore", "planet.frore.people": "프로리안", "planet.forge.name": "Forge", "planet.forge.people": "포지링", "block.terra-ember": "불씨", "block.terra-aqua": "아쿠아", "block.terra-leaf": "잎", "block.terra-sun": "태양", "block.terra-orchid": "난초", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "화살", "block.arrow-chevron": "셰브론", "block.arrow-double": "쌍화살", "block.arrow-return": "돌아가기", "block.fig-person": "사람", "block.fig-walker": "걷는이", "block.fig-hero": "영웅", "block.face-smile": "웃음", "block.face-wink": "윙크", "block.face-cool": "쿨", "block.face-grin": "싱긋", "block.icon-heart": "하트", "block.icon-moon": "달", "block.icon-bolt": "번개", "block.icon-shield": "방패", "block.icon-crown": "왕관", "block.icon-eye": "눈", "block.icon-star6": "육각별", "block.icon-spiral": "나선형", "block.icon-wave": "파도", "block.icon-mountain": "산", "block.icon-fish": "물고기", "block.icon-bird": "새", "block.icon-key": "열쇠", "block.icon-comet": "혜성", "block.icon-clover": "클로버", "block.icon-paw": "발자국", "block.icon-sword": "검", "block.icon-bell": "종", "block.icon-mushroom": "버섯", "block.icon-cactus": "선인장", "block.icon-ring": "반지", "block.icon-flag": "깃발", "block.icon-snow": "눈송이", "block.icon-flame": "불꽃", "block.icon-ankh": "앙크", "block.icon-yin": "음양", "block.aurel-gold": "Aurel 금", "block.aurel-cream": "Aurel 크림", "block.aurel-amber": "Aurel 호박", "block.aurel-sage": "Aurel 세이지", "block.aurel-rose": "Aurel 장미", "block.cinder-magma": "Cinder 마그마", "block.cinder-coal": "Cinder 석탄", "block.cinder-spark": "Cinder 불꽃", "block.cinder-ash": "Cinder 재", "block.cinder-core": "Cinder 핵", "block.lunara-silver": "Lunara 은", "block.lunara-dust": "Lunara 먼지", "block.lunara-pale": "Lunara 옅은", "block.lunara-void": "Lunara 공허", "block.lunara-lilac": "Lunara 라일락", "block.mire-moss": "Mire 이끼", "block.mire-bog": "Mire 늪", "block.mire-rust": "Mire 녹", "block.mire-spore": "Mire 포자", "block.mire-murk": "Mire 어둠", "block.galeon-sky": "Galeon 하늘", "block.galeon-cloud": "Galeon 구름", "block.galeon-storm": "Galeon 폭풍", "block.galeon-sand": "Galeon 모래", "block.galeon-kite": "Galeon 연", "block.obsid-glass": "Obsid 유리", "block.obsid-violet": "Obsid 보라", "block.obsid-shard": "Obsid 파편", "block.obsid-vein": "Obsid 광맥", "block.obsid-basalt": "Obsid 현무암", "block.wisp-glow": "Wisp 빛", "block.wisp-mist": "Wisp 안개", "block.wisp-sparkle": "Wisp 반짝임", "block.wisp-veil": "Wisp 베일", "block.wisp-gleam": "Wisp 광채", "block.thorn-briar": "Thorn 가시덤불", "block.thorn-berry": "Thorn 열매", "block.thorn-bark": "Thorn 나무껍질", "block.thorn-petal": "Thorn 꽃잎", "block.thorn-gold": "Thorn 금", "block.zephyr-azure": "Zephyr 하늘색", "block.zephyr-breeze": "Zephyr 미풍", "block.zephyr-cirrus": "Zephyr 권운", "block.zephyr-dusk": "Zephyr 황혼", "block.zephyr-haze": "Zephyr 아지랑이", "block.frore-ice": "Frore 얼음", "block.frore-frost": "Frore 서리", "block.frore-deep": "Frore 깊은", "block.frore-aurora": "Frore 오로라", "block.frore-rime": "Frore 흰서리", "block.forge-iron": "Forge 철", "block.forge-slag": "Forge 슬래그", "block.forge-spark": "Forge 불꽃", "block.forge-brass": "Forge 황동", "block.forge-soot": "Forge 그을음", "error.webgl": "이 게임은 WebGL이 필요합니다. 다른 브라우저를 사용하거나 하드웨어 가속을 켜 주세요.", "error.startFailed": "게임을 시작할 수 없습니다.", "reward.won": "승리!", "reward.lost": "패배...", "reward.total": "총 포인트", "reward.continue": "탭하여 계속", "game.menu": "메뉴", "game.paused": "일시정지", "game.resume": "계속하기", "game.backToMenu": "메인 메뉴로 돌아가기", "reward.ended": "게임 종료", "offline.defeated.one": "상대 {n}명 격파", "offline.defeated.few": "상대 {n}명 격파", "offline.defeated.many": "상대 {n}명 격파", "offline.defeated.other": "상대 {n}명 격파", "stats.gravity": "{pct}% ({g}g)", "menu.survival": "서바이벌", "menu.leaderboard": "순위표", "leaderboard.title": "순위표", "leaderboard.global": "상위 10", "leaderboard.friends": "친구", "leaderboard.empty": "아직 점수가 없습니다.", "leaderboard.loginPrompt": "로그인하면 친구 순위를 볼 수 있습니다.", "leaderboard.loadError": "순위표를 불러올 수 없습니다.", "leaderboard.points": "{n}점" }, "pl": { "menu.play": "Graj", "menu.online": "Graj online", "menu.designer": "Kreator planet", "menu.lastScore": "Ostatni wynik:", "menu.hint": "Przeciągaj klocki pionowo, aby je zamieniać. Pociągnij klocek ponad jego kolumnę, aby go wystrzelić. Klocki, które opuszczą pole, dają punkty.", "menu.login": "Zaloguj się", "loginPrompt.title": "Zalogować się?", "loginPrompt.body": "Zaloguj się, aby zapisać punkty i grać online.", "loginPrompt.guest": "Graj jako gość", "menu.localTest": "test lokalny:", "menu.loggedInAs": "Zalogowano jako", "menu.total": "Suma:", "menu.pointsWord": "pkt", "menu.logout": "Wyloguj się", "menu.player": "gracz", "planet.title": "Wybierz pole", "planet.back": "Wstecz", "planet.customBadge": "Twoja", "stats.powerLabel": "Moc", "online.title": "Online", "online.checking": "Sprawdzam, czy gra online jest dostępna…", "online.notLoaded": "Gra online nie jest w tej wersji wczytana. Nadal możesz grać offline.", "online.canPlaySolo": "Nadal możesz grać offline.", "online.unconfiguredHtml": "Gra online nie jest jeszcze skonfigurowana. Administrator musi dodać ścieżkę zwrotną /meteors/callback.php na auth.timfalken.com/admin (ten sam klient co inne witryny w tej domenie; sekretu nie generować ponownie) i umieścić ten sekret w data/config.php na serwerze. Zobacz README.", "online.loginPrompt": "Aby grać online, zaloguj się kontem z auth.timfalken.com.", "online.localTest": "Test lokalny:", "online.createLobby": "Utwórz lobby", "online.lobbyCode": "Kod lobby", "online.join": "Dołącz", "online.copy": "Kopiuj", "online.copied": "Skopiowano", "online.code": "Kod:", "online.yourField": "Twoje pole", "online.ready": "Gotowy", "online.notReady": "Niegotowy", "online.start": "Start", "online.leave": "Opuść", "online.statusUnconfigured": "Gra online nie jest jeszcze skonfigurowana.", "online.statusLogin": "Zaloguj się, aby utworzyć lobby lub do niego dołączyć.", "online.statusLobby": "Lobby", "online.statusHome": "Cześć {name}. Utwórz lobby albo dołącz z kodem.", "online.hintStarting": "Gra się zaczyna…", "online.hintNeedPlayers": "Poczekaj na co najmniej jednego gracza. Udostępnij kod.", "online.hintNeedReady": "Wszyscy muszą nacisnąć Gotowy. Potem host rozpoczyna grę.", "online.hintHostStart": "Wszyscy są gotowi. Naciśnij Start.", "online.hintWaitHost": "Czekam, aż host zacznie.", "online.host": "host", "online.you": "ty", "designer.title": "Kreator planet", "designer.taglineBefore": "Suma:", "designer.taglineAfter": "pkt.", "designer.empty": "Nie masz jeszcze własnych planet. Utwórz jedną.", "designer.new": "Nowa planeta", "designer.editTitle": "Edytuj planetę", "designer.createTitle": "Nowa planeta", "designer.name": "Nazwa planety", "designer.people": "Nazwa ludu", "designer.gravity": "Grawitacja", "designer.air": "Opór powietrza", "designer.mass": "Masa", "designer.power": "Moc {n}%", "designer.slotsHint": "Wybierz pięć klocków. Kliknij pole, aby je zmienić.", "designer.save": "Zapisz", "designer.delete": "Usuń", "designer.cancel": "Wstecz", "designer.edit": "Edytuj", "designer.pickBlock": "Wybierz klocek", "designer.close": "Zamknij", "designer.choose": "Wybierz", "designer.slotAria": "Klocek {n}", "designer.needPoints": "wymagane {n} pkt", "designer.alreadyUsed": "już w innym polu", "designer.confirmDelete": "Usunąć planetę „{name}”?", "designer.deleteFailed": "Nie udało się usunąć.", "designer.saveFailed": "Nie udało się zapisać.", "designer.needNames": "Podaj nazwę planety i jej ludu.", "designer.needFive": "Wybierz pięć klocków.", "designer.defaultName": "Nowa planeta", "designer.defaultPeople": "Lud", "hud.points": "Punkty", "hud.round": "Runda {n}", "hud.out": "Poza", "hud.miniPoints": "Punkty {n}", "hud.opponent.one": "przeciwnik", "hud.opponent.few": "przeciwników", "hud.opponent.many": "przeciwników", "hud.opponent.other": "przeciwników", "offline.resultTitle": "Wynik", "offline.reachedBefore": "Dotarłeś do rundy", "offline.reachedAfter": ".", "offline.reached": "Dotarłeś do rundy {n}.", "offline.backMenu": "Powrót do menu", "gameover.title": "Przegrałeś", "gameover.detail": "Wszystkie kolumny są zablokowane.", "gameover.score": "Wynik:", "spectator.title": "Odpadasz", "spectator.detail": "Wszystkie twoje kolumny są pełne. Możesz oglądać albo opuścić mecz.", "spectator.watch": "Obserwuj", "podium.title": "Zwycięstwo!", "podium.subtitle": "Ostatni gracz nadal stoi.", "podium.hint": "Powrót do lobby za {n} s…", "podium.line": "{place} {name} · {score} pkt", "podium.place.1": "1.", "podium.place.2": "2.", "podium.place.3": "3.", "podium.place.n": "{n}.", "lang.current": "Język: {name}. Kliknij, aby zmienić.", "lang.choose": "Wybierz język", "error.loginRequired": "Zaloguj się, aby kontynuować.", "error.unknownPlanet": "Nieznana planeta.", "error.unknownLanguage": "Nieznany język.", "error.unknownMode": "Nieznany tryb gry.", "error.invalidSession": "Nieprawidłowa sesja gry.", "error.sessionExpired": "Sesja gry wygasła.", "error.needFiveBlocks": "Planeta wymaga dokładnie pięciu klocków.", "error.unknownBlock": "Nieznany klocek.", "error.blockLocked": "Ten klocek nie jest jeszcze odblokowany.", "error.duplicateBlock": "Każdy klocek może być tylko w jednym polu.", "error.maxPlanets": "Osiągnięto limit {n} planet.", "error.saveFailed": "Nie udało się zapisać.", "error.unknownAction": "Nieznane działanie.", "error.internal": "Błąd wewnętrzny.", "error.notAvailable": "Niedostępne.", "error.csrf": "Nieprawidłowy lub brakujący token zabezpieczający.", "error.alreadyInLobby": "Jesteś już w lobby. Najpierw je opuść.", "error.alreadyInOtherLobby": "Jesteś już w innym lobby. Najpierw je opuść.", "error.unknownLobby": "Nieznany kod lobby.", "error.lobbyStarted": "To lobby już się rozpoczęło.", "error.lobbyFull": "To lobby jest pełne (maks. {n} graczy).", "error.notInLobby": "Nie jesteś w lobby.", "error.notInAnyLobby": "Nie jesteś w lobby.", "error.hostOnly": "Tylko host może rozpocząć grę.", "error.gameAlreadyStarted": "Gra już się rozpoczęła.", "error.needTwoPlayers": "Potrzeba co najmniej dwóch graczy.", "error.notAllReady": "Nie wszyscy są gotowi.", "error.planetLocked": "Planetę można wybrać tylko przed startem gry.", "error.fillField": "Podaj {field}.", "error.fieldPlanet": "nazwę planety", "error.fieldPeople": "nazwę ludu", "error.connection": "Brak połączenia z serwerem.", "error.badResponse": "Serwer nie przysłał poprawnej odpowiedzi.", "error.serverStatus": "Serwer zwrócił {status}.", "auth.unavailable": "Logowanie jest teraz niemożliwe.", "auth.backToGame": "Powrót do gry", "auth.failed": "Logowanie nie powiodło się.", "auth.retry": "Spróbuj ponownie", "auth.back": "Wstecz", "planet.terra.name": "Terra", "planet.terra.people": "Teranie", "planet.aurel.name": "Aurel", "planet.aurel.people": "Aurelianie", "planet.cinder.name": "Cinder", "planet.cinder.people": "Cindari", "planet.lunara.name": "Lunara", "planet.lunara.people": "Lunaryci", "planet.mire.name": "Mire", "planet.mire.people": "Mirianie", "planet.galeon.name": "Galeon", "planet.galeon.people": "Galeoni", "planet.obsid.name": "Obsid", "planet.obsid.people": "Obsydianie", "planet.wisp.name": "Wisp", "planet.wisp.people": "Wispilingi", "planet.thorn.name": "Thorn", "planet.thorn.people": "Cierniacy", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "Zefiryci", "planet.frore.name": "Frore", "planet.frore.people": "Frorianie", "planet.forge.name": "Forge", "planet.forge.people": "Kowale", "block.terra-ember": "Żar", "block.terra-aqua": "Aqua", "block.terra-leaf": "Liść", "block.terra-sun": "Słońce", "block.terra-orchid": "Orchidea", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "Strzała", "block.arrow-chevron": "Szewron", "block.arrow-double": "Podwójna strzała", "block.arrow-return": "Powrót", "block.fig-person": "Postać", "block.fig-walker": "Wędrowiec", "block.fig-hero": "Bohater", "block.face-smile": "Uśmiech", "block.face-wink": "Mrugnięcie", "block.face-cool": "Cool", "block.face-grin": "Uśmieszek", "block.icon-heart": "Serce", "block.icon-moon": "Księżyc", "block.icon-bolt": "Piorun", "block.icon-shield": "Tarcza", "block.icon-crown": "Korona", "block.icon-eye": "Oko", "block.icon-star6": "Sześcioramienna", "block.icon-spiral": "Spirala", "block.icon-wave": "Fala", "block.icon-mountain": "Góra", "block.icon-fish": "Ryba", "block.icon-bird": "Ptak", "block.icon-key": "Klucz", "block.icon-comet": "Kometa", "block.icon-clover": "Koniczyna", "block.icon-paw": "Łapa", "block.icon-sword": "Miecz", "block.icon-bell": "Dzwonek", "block.icon-mushroom": "Grzyb", "block.icon-cactus": "Kaktus", "block.icon-ring": "Pierścień", "block.icon-flag": "Flaga", "block.icon-snow": "Płatek śniegu", "block.icon-flame": "Płomień", "block.icon-ankh": "Ankh", "block.icon-yin": "Yin i yang", "block.aurel-gold": "Aurel złoto", "block.aurel-cream": "Aurel krem", "block.aurel-amber": "Aurel bursztyn", "block.aurel-sage": "Aurel szałwia", "block.aurel-rose": "Aurel róż", "block.cinder-magma": "Cinder magma", "block.cinder-coal": "Cinder węgiel", "block.cinder-spark": "Cinder iskra", "block.cinder-ash": "Cinder popiół", "block.cinder-core": "Cinder rdzeń", "block.lunara-silver": "Lunara srebro", "block.lunara-dust": "Lunara pył", "block.lunara-pale": "Lunara blady", "block.lunara-void": "Lunara pustka", "block.lunara-lilac": "Lunara lilak", "block.mire-moss": "Mire mech", "block.mire-bog": "Mire bagno", "block.mire-rust": "Mire rdza", "block.mire-spore": "Mire zarodnik", "block.mire-murk": "Mire mrok", "block.galeon-sky": "Galeon niebo", "block.galeon-cloud": "Galeon chmura", "block.galeon-storm": "Galeon burza", "block.galeon-sand": "Galeon piasek", "block.galeon-kite": "Galeon latawiec", "block.obsid-glass": "Obsid szkło", "block.obsid-violet": "Obsid fiolet", "block.obsid-shard": "Obsid odłamek", "block.obsid-vein": "Obsid żyła", "block.obsid-basalt": "Obsid bazalt", "block.wisp-glow": "Wisp poświata", "block.wisp-mist": "Wisp mgła", "block.wisp-sparkle": "Wisp iskrzenie", "block.wisp-veil": "Wisp woal", "block.wisp-gleam": "Wisp blask", "block.thorn-briar": "Thorn głóg", "block.thorn-berry": "Thorn jagoda", "block.thorn-bark": "Thorn kora", "block.thorn-petal": "Thorn płatek", "block.thorn-gold": "Thorn złoto", "block.zephyr-azure": "Zephyr lazurowy", "block.zephyr-breeze": "Zephyr bryza", "block.zephyr-cirrus": "Zephyr cirrus", "block.zephyr-dusk": "Zephyr zmierzch", "block.zephyr-haze": "Zephyr mgiełka", "block.frore-ice": "Frore lód", "block.frore-frost": "Frore szron", "block.frore-deep": "Frore głębia", "block.frore-aurora": "Frore zorza", "block.frore-rime": "Frore szadź", "block.forge-iron": "Forge żelazo", "block.forge-slag": "Forge żużel", "block.forge-spark": "Forge iskra", "block.forge-brass": "Forge mosiądz", "block.forge-soot": "Forge sadza", "error.webgl": "Ta gra wymaga WebGL. Spróbuj innej przeglądarki albo włącz akcelerację sprzętową.", "error.startFailed": "Nie udało się uruchomić gry.", "reward.won": "Wygrana!", "reward.lost": "Przegrana...", "reward.total": "Suma punktów", "reward.continue": "Dotknij, aby kontynuować", "game.menu": "Menu", "game.paused": "Pauza", "game.resume": "Wznów", "game.backToMenu": "Powrót do menu głównego", "reward.ended": "Gra zakończona", "offline.defeated.one": "{n} pokonany przeciwnik", "offline.defeated.few": "{n} pokonanych przeciwników", "offline.defeated.many": "{n} pokonanych przeciwników", "offline.defeated.other": "{n} pokonanych przeciwników", "stats.gravity": "{pct} % ({g} g)", "menu.survival": "Przetrwanie", "menu.leaderboard": "Ranking", "leaderboard.title": "Ranking", "leaderboard.global": "Top 10", "leaderboard.friends": "Znajomi", "leaderboard.empty": "Brak wyników.", "leaderboard.loginPrompt": "Zaloguj się, aby zobaczyć pozycję znajomych.", "leaderboard.loadError": "Nie udało się wczytać rankingu.", "leaderboard.points": "{n} pkt" }, "ru": { "menu.play": "Играть", "menu.online": "Играть онлайн", "menu.designer": "Конструктор планет", "menu.lastScore": "Последний счёт:", "menu.hint": "Перетаскивай блоки вертикально, чтобы менять их местами. Потяни блок выше его столбца, чтобы запустить его вверх. Блоки, покинувшие поле, дают очки.", "menu.login": "Войти", "loginPrompt.title": "Войти?", "loginPrompt.body": "Войди, чтобы сохранять очки и играть онлайн.", "loginPrompt.guest": "Играть как гость", "menu.localTest": "локальный тест:", "menu.loggedInAs": "Вы вошли как", "menu.total": "Всего:", "menu.pointsWord": "очков", "menu.logout": "Выйти", "menu.player": "игрок", "planet.title": "Выбери поле", "planet.back": "Назад", "planet.customBadge": "Своя", "stats.powerLabel": "Мощность", "online.title": "Онлайн", "online.checking": "Проверяю, доступна ли онлайн-игра…", "online.notLoaded": "Онлайн-игра в этой сборке не загружена. Ты всё ещё можешь играть офлайн.", "online.canPlaySolo": "Ты всё ещё можешь играть офлайн.", "online.unconfiguredHtml": "Онлайн-игра ещё не настроена. Администратор должен добавить путь обратного вызова /meteors/callback.php на auth.timfalken.com/admin (тот же клиент, что и у других сайтов этого домена; секрет не генерировать заново) и записать его в data/config.php на сервере. См. README.", "online.loginPrompt": "Чтобы играть онлайн, войди через свой аккаунт на auth.timfalken.com.", "online.localTest": "Локальный тест:", "online.createLobby": "Создать лобби", "online.lobbyCode": "Код лобби", "online.join": "Войти", "online.copy": "Копировать", "online.copied": "Скопировано", "online.code": "Код:", "online.yourField": "Твоё поле", "online.ready": "Готов", "online.notReady": "Не готов", "online.start": "Старт", "online.leave": "Выйти", "online.statusUnconfigured": "Онлайн-игра ещё не настроена.", "online.statusLogin": "Войди, чтобы создать лобби или присоединиться.", "online.statusLobby": "Лобби", "online.statusHome": "Привет, {name}. Создай лобби или войди по коду.", "online.hintStarting": "Игра начинается…", "online.hintNeedPlayers": "Подожди хотя бы ещё одного игрока. Поделись кодом.", "online.hintNeedReady": "Все должны нажать «Готов». Затем хост начнёт игру.", "online.hintHostStart": "Все готовы. Нажми «Старт».", "online.hintWaitHost": "Ждём, пока хост начнёт.", "online.host": "хост", "online.you": "ты", "designer.title": "Конструктор планет", "designer.taglineBefore": "Всего:", "designer.taglineAfter": "очков.", "designer.empty": "У тебя ещё нет своих планет. Создай одну.", "designer.new": "Новая планета", "designer.editTitle": "Изменить планету", "designer.createTitle": "Новая планета", "designer.name": "Название планеты", "designer.people": "Название народа", "designer.gravity": "Гравитация", "designer.air": "Сопротивление воздуха", "designer.mass": "Масса", "designer.power": "Мощность {n} %", "designer.slotsHint": "Выбери пять блоков. Нажми на слот, чтобы сменить его.", "designer.save": "Сохранить", "designer.delete": "Удалить", "designer.cancel": "Назад", "designer.edit": "Изменить", "designer.pickBlock": "Выбери блок", "designer.close": "Закрыть", "designer.choose": "Выбрать", "designer.slotAria": "Блок {n}", "designer.needPoints": "нужно {n} очков", "designer.alreadyUsed": "уже в другом слоте", "designer.confirmDelete": "Удалить планету «{name}»?", "designer.deleteFailed": "Не удалось удалить.", "designer.saveFailed": "Не удалось сохранить.", "designer.needNames": "Введи название планеты и её народа.", "designer.needFive": "Выбери пять блоков.", "designer.defaultName": "Новая планета", "designer.defaultPeople": "Народ", "hud.points": "Очки", "hud.round": "Раунд {n}", "hud.out": "Вне", "hud.miniPoints": "Очки {n}", "hud.opponent.one": "противник", "hud.opponent.few": "противника", "hud.opponent.many": "противников", "hud.opponent.other": "противников", "offline.resultTitle": "Итоги", "offline.reachedBefore": "Ты дошёл до раунда", "offline.reachedAfter": ".", "offline.reached": "Ты дошёл до раунда {n}.", "offline.backMenu": "Вернуться в меню", "gameover.title": "Ты проиграл", "gameover.detail": "Все столбцы заблокированы.", "gameover.score": "Счёт:", "spectator.title": "Ты выбыл", "spectator.detail": "Все твои столбцы заполнены. Можно смотреть или покинуть матч.", "spectator.watch": "Смотреть", "podium.title": "Победа!", "podium.subtitle": "Последний игрок ещё стоит.", "podium.hint": "Возврат в лобби через {n} с…", "podium.line": "{place} {name} · {score} очков", "podium.place.1": "1-е", "podium.place.2": "2-е", "podium.place.3": "3-е", "podium.place.n": "{n}-е", "lang.current": "Язык: {name}. Нажми, чтобы сменить.", "lang.choose": "Выбери язык", "error.loginRequired": "Войди, чтобы продолжить.", "error.unknownPlanet": "Неизвестная планета.", "error.unknownLanguage": "Неизвестный язык.", "error.unknownMode": "Неизвестный режим.", "error.invalidSession": "Недействительная игровая сессия.", "error.sessionExpired": "Игровая сессия истекла.", "error.needFiveBlocks": "Планете нужно ровно пять блоков.", "error.unknownBlock": "Неизвестный блок.", "error.blockLocked": "Этот блок ещё не открыт.", "error.duplicateBlock": "Каждый блок можно поставить только в один слот.", "error.maxPlanets": "Достигнут предел в {n} планет.", "error.saveFailed": "Не удалось сохранить.", "error.unknownAction": "Неизвестное действие.", "error.internal": "Внутренняя ошибка.", "error.notAvailable": "Недоступно.", "error.csrf": "Недействительный или отсутствующий токен безопасности.", "error.alreadyInLobby": "Ты уже в лобби. Сначала выйди из него.", "error.alreadyInOtherLobby": "Ты уже в другом лобби. Сначала выйди из него.", "error.unknownLobby": "Неизвестный код лобби.", "error.lobbyStarted": "Это лобби уже началось.", "error.lobbyFull": "Это лобби заполнено (максимум {n} игроков).", "error.notInLobby": "Ты не в лобби.", "error.notInAnyLobby": "Ты не в лобби.", "error.hostOnly": "Только хост может начать игру.", "error.gameAlreadyStarted": "Игра уже началась.", "error.needTwoPlayers": "Нужно как минимум два игрока.", "error.notAllReady": "Не все готовы.", "error.planetLocked": "Планету можно выбрать только до начала игры.", "error.fillField": "Введи {field}.", "error.fieldPlanet": "название планеты", "error.fieldPeople": "название народа", "error.connection": "Нет соединения с сервером.", "error.badResponse": "Сервер не прислал корректный ответ.", "error.serverStatus": "Сервер вернул {status}.", "auth.unavailable": "Сейчас войти нельзя.", "auth.backToGame": "Вернуться к игре", "auth.failed": "Вход не удался.", "auth.retry": "Попробовать снова", "auth.back": "Назад", "planet.terra.name": "Terra", "planet.terra.people": "Терранцы", "planet.aurel.name": "Aurel", "planet.aurel.people": "Аурелианцы", "planet.cinder.name": "Cinder", "planet.cinder.people": "Циндари", "planet.lunara.name": "Lunara", "planet.lunara.people": "Лунариты", "planet.mire.name": "Mire", "planet.mire.people": "Мирианцы", "planet.galeon.name": "Galeon", "planet.galeon.people": "Галеони", "planet.obsid.name": "Obsid", "planet.obsid.people": "Обсидианцы", "planet.wisp.name": "Wisp", "planet.wisp.people": "Висплинги", "planet.thorn.name": "Thorn", "planet.thorn.people": "Шипородцы", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "Зефириты", "planet.frore.name": "Frore", "planet.frore.people": "Фрорианцы", "planet.forge.name": "Forge", "planet.forge.people": "Кузнецы", "block.terra-ember": "Тлеющий", "block.terra-aqua": "Аква", "block.terra-leaf": "Лист", "block.terra-sun": "Солнце", "block.terra-orchid": "Орхидея", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "Стрела", "block.arrow-chevron": "Шеврон", "block.arrow-double": "Двойная стрела", "block.arrow-return": "Возврат", "block.fig-person": "Фигурка", "block.fig-walker": "Ходок", "block.fig-hero": "Герой", "block.face-smile": "Улыбка", "block.face-wink": "Подмигивание", "block.face-cool": "Крутой", "block.face-grin": "Оскал", "block.icon-heart": "Сердце", "block.icon-moon": "Луна", "block.icon-bolt": "Молния", "block.icon-shield": "Щит", "block.icon-crown": "Корона", "block.icon-eye": "Глаз", "block.icon-star6": "Шестиконечная", "block.icon-spiral": "Спираль", "block.icon-wave": "Волна", "block.icon-mountain": "Гора", "block.icon-fish": "Рыба", "block.icon-bird": "Птица", "block.icon-key": "Ключ", "block.icon-comet": "Комета", "block.icon-clover": "Клевер", "block.icon-paw": "Лапа", "block.icon-sword": "Меч", "block.icon-bell": "Колокол", "block.icon-mushroom": "Гриб", "block.icon-cactus": "Кактус", "block.icon-ring": "Кольцо", "block.icon-flag": "Флаг", "block.icon-snow": "Снежинка", "block.icon-flame": "Пламя", "block.icon-ankh": "Анх", "block.icon-yin": "Инь и ян", "block.aurel-gold": "Aurel (золото)", "block.aurel-cream": "Aurel (кремовый)", "block.aurel-amber": "Aurel (янтарь)", "block.aurel-sage": "Aurel (шалфей)", "block.aurel-rose": "Aurel (роза)", "block.cinder-magma": "Cinder (магма)", "block.cinder-coal": "Cinder (уголь)", "block.cinder-spark": "Cinder (искра)", "block.cinder-ash": "Cinder (пепел)", "block.cinder-core": "Cinder (ядро)", "block.lunara-silver": "Lunara (серебро)", "block.lunara-dust": "Lunara (пыль)", "block.lunara-pale": "Lunara (бледный)", "block.lunara-void": "Lunara (пустота)", "block.lunara-lilac": "Lunara (сирень)", "block.mire-moss": "Mire (мох)", "block.mire-bog": "Mire (болото)", "block.mire-rust": "Mire (ржавчина)", "block.mire-spore": "Mire (спора)", "block.mire-murk": "Mire (мгла)", "block.galeon-sky": "Galeon (небо)", "block.galeon-cloud": "Galeon (облако)", "block.galeon-storm": "Galeon (буря)", "block.galeon-sand": "Galeon (песок)", "block.galeon-kite": "Galeon (воздушный змей)", "block.obsid-glass": "Obsid (стекло)", "block.obsid-violet": "Obsid (фиолетовый)", "block.obsid-shard": "Obsid (осколок)", "block.obsid-vein": "Obsid (жила)", "block.obsid-basalt": "Obsid (базальт)", "block.wisp-glow": "Wisp (сияние)", "block.wisp-mist": "Wisp (туман)", "block.wisp-sparkle": "Wisp (блеск)", "block.wisp-veil": "Wisp (вуаль)", "block.wisp-gleam": "Wisp (отсвет)", "block.thorn-briar": "Thorn (терновник)", "block.thorn-berry": "Thorn (ягода)", "block.thorn-bark": "Thorn (кора)", "block.thorn-petal": "Thorn (лепесток)", "block.thorn-gold": "Thorn (золото)", "block.zephyr-azure": "Zephyr (лазурь)", "block.zephyr-breeze": "Zephyr (бриз)", "block.zephyr-cirrus": "Zephyr (перистое)", "block.zephyr-dusk": "Zephyr (сумерки)", "block.zephyr-haze": "Zephyr (дымка)", "block.frore-ice": "Frore (лёд)", "block.frore-frost": "Frore (иней)", "block.frore-deep": "Frore (глубина)", "block.frore-aurora": "Frore (заря)", "block.frore-rime": "Frore (изморозь)", "block.forge-iron": "Forge (железо)", "block.forge-slag": "Forge (шлак)", "block.forge-spark": "Forge (искра)", "block.forge-brass": "Forge (латунь)", "block.forge-soot": "Forge (сажа)", "error.webgl": "Этой игре нужен WebGL. Попробуйте другой браузер или включите аппаратное ускорение.", "error.startFailed": "Не удалось начать игру.", "reward.won": "Победа!", "reward.lost": "Поражение...", "reward.total": "Всего очков", "reward.continue": "Нажмите, чтобы продолжить", "game.menu": "Меню", "game.paused": "Пауза", "game.resume": "Продолжить", "game.backToMenu": "В главное меню", "reward.ended": "Игра окончена", "offline.defeated.one": "{n} противник побеждён", "offline.defeated.few": "{n} противника побеждено", "offline.defeated.many": "{n} противников побеждено", "offline.defeated.other": "{n} противников побеждено", "stats.gravity": "{pct} % ({g} g)", "menu.survival": "Выживание", "menu.leaderboard": "Таблица лидеров", "leaderboard.title": "Таблица лидеров", "leaderboard.global": "Топ-10", "leaderboard.friends": "Друзья", "leaderboard.empty": "Пока нет очков.", "leaderboard.loginPrompt": "Войди, чтобы увидеть места друзей.", "leaderboard.loadError": "Не удалось загрузить таблицу лидеров.", "leaderboard.points": "{n} очков" }, "es": { "menu.play": "Jugar", "menu.online": "Jugar en línea", "menu.designer": "Diseñador de planetas", "menu.lastScore": "Última puntuación:", "menu.hint": "Arrastra los bloques en vertical para intercambiarlos. Tira de un bloque por encima de su columna para lanzarlo. Los bloques que salen del campo dan puntos.", "menu.login": "Iniciar sesión", "loginPrompt.title": "¿Iniciar sesión?", "loginPrompt.body": "Inicia sesión para guardar tus puntos y jugar en línea.", "loginPrompt.guest": "Jugar como invitado", "menu.localTest": "prueba local:", "menu.loggedInAs": "Sesión iniciada como", "menu.total": "Total:", "menu.pointsWord": "puntos", "menu.logout": "Cerrar sesión", "menu.player": "jugador", "planet.title": "Elige un campo", "planet.back": "Volver", "planet.customBadge": "Tuya", "stats.powerLabel": "Potencia", "online.title": "En línea", "online.checking": "Comprobando si el juego en línea está disponible…", "online.notLoaded": "El juego en línea no está cargado en esta versión. Aún puedes jugar sin conexión.", "online.canPlaySolo": "Aún puedes jugar sin conexión.", "online.unconfiguredHtml": "El juego en línea aún no está configurado. El administrador debe añadir la ruta de retorno /meteors/callback.php en auth.timfalken.com/admin (el mismo cliente que los demás sitios de este dominio; no vuelvas a generar el secreto) y colocar ese secreto en data/config.php en el servidor. Consulta el README.", "online.loginPrompt": "Para jugar en línea, inicia sesión con tu cuenta en auth.timfalken.com.", "online.localTest": "Prueba local:", "online.createLobby": "Crear sala", "online.lobbyCode": "Código de sala", "online.join": "Unirse", "online.copy": "Copiar", "online.copied": "Copiado", "online.code": "Código:", "online.yourField": "Tu campo", "online.ready": "Listo", "online.notReady": "No listo", "online.start": "Empezar", "online.leave": "Salir", "online.statusUnconfigured": "El juego en línea aún no está configurado.", "online.statusLogin": "Inicia sesión para crear una sala o unirte a una.", "online.statusLobby": "Sala", "online.statusHome": "Hola, {name}. Crea una sala o únete con un código.", "online.hintStarting": "La partida está empezando…", "online.hintNeedPlayers": "Espera al menos a otro jugador. Comparte el código.", "online.hintNeedReady": "Todos deben pulsar Listo. Después, el anfitrión inicia la partida.", "online.hintHostStart": "Todos están listos. Pulsa Empezar.", "online.hintWaitHost": "Esperando a que el anfitrión empiece.", "online.host": "anfitrión", "online.you": "tú", "designer.title": "Diseñador de planetas", "designer.taglineBefore": "Total:", "designer.taglineAfter": "puntos.", "designer.empty": "Aún no tienes planetas propios. Crea uno.", "designer.new": "Nuevo planeta", "designer.editTitle": "Editar planeta", "designer.createTitle": "Nuevo planeta", "designer.name": "Nombre del planeta", "designer.people": "Nombre del pueblo", "designer.gravity": "Gravedad", "designer.air": "Resistencia del aire", "designer.mass": "Masa", "designer.power": "Potencia {n} %", "designer.slotsHint": "Elige cinco bloques. Pulsa un hueco para cambiarlo.", "designer.save": "Guardar", "designer.delete": "Eliminar", "designer.cancel": "Volver", "designer.edit": "Editar", "designer.pickBlock": "Elige un bloque", "designer.close": "Cerrar", "designer.choose": "Elegir", "designer.slotAria": "Bloque {n}", "designer.needPoints": "{n} puntos necesarios", "designer.alreadyUsed": "ya está en otro hueco", "designer.confirmDelete": "¿Eliminar el planeta «{name}»?", "designer.deleteFailed": "No se pudo eliminar.", "designer.saveFailed": "No se pudo guardar.", "designer.needNames": "Introduce un nombre para el planeta y para su pueblo.", "designer.needFive": "Elige cinco bloques.", "designer.defaultName": "Nuevo planeta", "designer.defaultPeople": "Pueblo", "hud.points": "Puntos", "hud.round": "Ronda {n}", "hud.out": "Fuera", "hud.miniPoints": "Puntos {n}", "hud.opponent.one": "rival", "hud.opponent.few": "rivales", "hud.opponent.many": "rivales", "hud.opponent.other": "rivales", "offline.resultTitle": "Resultado", "offline.reachedBefore": "Has llegado a la ronda", "offline.reachedAfter": ".", "offline.reached": "Has llegado a la ronda {n}.", "offline.backMenu": "Volver al menú", "gameover.title": "Has perdido", "gameover.detail": "Todas las columnas están bloqueadas.", "gameover.score": "Puntuación:", "spectator.title": "Has quedado fuera", "spectator.detail": "Todas tus columnas están llenas. Puedes mirar o abandonar la partida.", "spectator.watch": "Mirar", "podium.title": "¡Victoria!", "podium.subtitle": "El último jugador sigue en pie.", "podium.hint": "Volviendo a la sala en {n} segundos…", "podium.line": "{place} {name} · {score} puntos", "podium.place.1": "1.º", "podium.place.2": "2.º", "podium.place.3": "3.º", "podium.place.n": "{n}.º", "lang.current": "Idioma: {name}. Pulsa para cambiar.", "lang.choose": "Elige un idioma", "error.loginRequired": "Inicia sesión para continuar.", "error.unknownPlanet": "Planeta desconocido.", "error.unknownLanguage": "Idioma desconocido.", "error.unknownMode": "Modo de juego desconocido.", "error.invalidSession": "Sesión de juego no válida.", "error.sessionExpired": "La sesión de juego ha caducado.", "error.needFiveBlocks": "Un planeta necesita exactamente cinco bloques.", "error.unknownBlock": "Bloque desconocido.", "error.blockLocked": "Este bloque aún no está desbloqueado.", "error.duplicateBlock": "Cada bloque solo puede ocupar un hueco.", "error.maxPlanets": "Has alcanzado el límite de {n} planetas.", "error.saveFailed": "No se pudo guardar.", "error.unknownAction": "Acción desconocida.", "error.internal": "Error interno.", "error.notAvailable": "No disponible.", "error.csrf": "Token de seguridad no válido o ausente.", "error.alreadyInLobby": "Ya estás en una sala. Sal primero de ella.", "error.alreadyInOtherLobby": "Ya estás en otra sala. Sal primero de ella.", "error.unknownLobby": "Código de sala desconocido.", "error.lobbyStarted": "Esta sala ya ha comenzado.", "error.lobbyFull": "Esta sala está llena (máximo {n} jugadores).", "error.notInLobby": "No estás en una sala.", "error.notInAnyLobby": "No estás en una sala.", "error.hostOnly": "Solo el anfitrión puede empezar la partida.", "error.gameAlreadyStarted": "La partida ya ha comenzado.", "error.needTwoPlayers": "Se necesitan al menos dos jugadores.", "error.notAllReady": "No todo el mundo está listo.", "error.planetLocked": "Solo puedes elegir un planeta antes de que empiece la partida.", "error.fillField": "Introduce {field}.", "error.fieldPlanet": "un nombre de planeta", "error.fieldPeople": "un nombre de pueblo", "error.connection": "Sin conexión con el servidor.", "error.badResponse": "El servidor no envió una respuesta válida.", "error.serverStatus": "El servidor devolvió {status}.", "auth.unavailable": "Ahora mismo no es posible iniciar sesión.", "auth.backToGame": "Volver al juego", "auth.failed": "Error al iniciar sesión.", "auth.retry": "Intentar de nuevo", "auth.back": "Volver", "planet.terra.name": "Terra", "planet.terra.people": "Terranos", "planet.aurel.name": "Aurel", "planet.aurel.people": "Aurelianos", "planet.cinder.name": "Cinder", "planet.cinder.people": "Cindari", "planet.lunara.name": "Lunara", "planet.lunara.people": "Lunaritas", "planet.mire.name": "Mire", "planet.mire.people": "Mirianos", "planet.galeon.name": "Galeon", "planet.galeon.people": "Galeoni", "planet.obsid.name": "Obsid", "planet.obsid.people": "Obsidianos", "planet.wisp.name": "Wisp", "planet.wisp.people": "Wisplingos", "planet.thorn.name": "Thorn", "planet.thorn.people": "Espinosos", "planet.zephyr.name": "Zephyr", "planet.zephyr.people": "Cefiritas", "planet.frore.name": "Frore", "planet.frore.people": "Frorianos", "planet.forge.name": "Forge", "planet.forge.people": "Forjadores", "block.terra-ember": "Brasa", "block.terra-aqua": "Agua", "block.terra-leaf": "Hoja", "block.terra-sun": "Sol", "block.terra-orchid": "Orquídea", "block.rune-fehu": "Fehu", "block.rune-ansuz": "Ansuz", "block.rune-thurisaz": "Thurisaz", "block.rune-raido": "Raido", "block.rune-sowilo": "Sowilo", "block.rune-algiz": "Algiz", "block.arrow-up": "Flecha", "block.arrow-chevron": "Chevron", "block.arrow-double": "Flecha doble", "block.arrow-return": "Retorno", "block.fig-person": "Figura", "block.fig-walker": "Caminante", "block.fig-hero": "Héroe", "block.face-smile": "Sonrisa", "block.face-wink": "Guiño", "block.face-cool": "Guay", "block.face-grin": "Sonrisón", "block.icon-heart": "Corazón", "block.icon-moon": "Luna", "block.icon-bolt": "Rayo", "block.icon-shield": "Escudo", "block.icon-crown": "Corona", "block.icon-eye": "Ojo", "block.icon-star6": "Hexaestrella", "block.icon-spiral": "Espiral", "block.icon-wave": "Ola", "block.icon-mountain": "Montaña", "block.icon-fish": "Pez", "block.icon-bird": "Pájaro", "block.icon-key": "Llave", "block.icon-comet": "Cometa", "block.icon-clover": "Trébol", "block.icon-paw": "Huella", "block.icon-sword": "Espada", "block.icon-bell": "Campana", "block.icon-mushroom": "Seta", "block.icon-cactus": "Cacto", "block.icon-ring": "Anillo", "block.icon-flag": "Bandera", "block.icon-snow": "Copo de nieve", "block.icon-flame": "Llama", "block.icon-ankh": "Anj", "block.icon-yin": "Yin y yang", "block.aurel-gold": "Aurel oro", "block.aurel-cream": "Aurel crema", "block.aurel-amber": "Aurel ámbar", "block.aurel-sage": "Aurel salvia", "block.aurel-rose": "Aurel rosa", "block.cinder-magma": "Cinder magma", "block.cinder-coal": "Cinder carbón", "block.cinder-spark": "Cinder chispa", "block.cinder-ash": "Cinder ceniza", "block.cinder-core": "Cinder núcleo", "block.lunara-silver": "Lunara plata", "block.lunara-dust": "Lunara polvo", "block.lunara-pale": "Lunara pálido", "block.lunara-void": "Lunara vacío", "block.lunara-lilac": "Lunara lila", "block.mire-moss": "Mire musgo", "block.mire-bog": "Mire ciénaga", "block.mire-rust": "Mire óxido", "block.mire-spore": "Mire espora", "block.mire-murk": "Mire oscuridad", "block.galeon-sky": "Galeon cielo", "block.galeon-cloud": "Galeon nube", "block.galeon-storm": "Galeon tormenta", "block.galeon-sand": "Galeon arena", "block.galeon-kite": "Galeon cometa", "block.obsid-glass": "Obsid cristal", "block.obsid-violet": "Obsid violeta", "block.obsid-shard": "Obsid fragmento", "block.obsid-vein": "Obsid vena", "block.obsid-basalt": "Obsid basalto", "block.wisp-glow": "Wisp resplandor", "block.wisp-mist": "Wisp niebla", "block.wisp-sparkle": "Wisp destello", "block.wisp-veil": "Wisp velo", "block.wisp-gleam": "Wisp brillo", "block.thorn-briar": "Thorn zarza", "block.thorn-berry": "Thorn baya", "block.thorn-bark": "Thorn corteza", "block.thorn-petal": "Thorn pétalo", "block.thorn-gold": "Thorn oro", "block.zephyr-azure": "Zephyr azur", "block.zephyr-breeze": "Zephyr brisa", "block.zephyr-cirrus": "Zephyr cirro", "block.zephyr-dusk": "Zephyr crepúsculo", "block.zephyr-haze": "Zephyr calima", "block.frore-ice": "Frore hielo", "block.frore-frost": "Frore escarcha", "block.frore-deep": "Frore profundo", "block.frore-aurora": "Frore aurora", "block.frore-rime": "Frore escarcha blanca", "block.forge-iron": "Forge hierro", "block.forge-slag": "Forge escoria", "block.forge-spark": "Forge chispa", "block.forge-brass": "Forge latón", "block.forge-soot": "Forge hollín", "error.webgl": "Este juego necesita WebGL. Prueba con otro navegador o activa la aceleración por hardware.", "error.startFailed": "No se pudo iniciar el juego.", "reward.won": "¡Has ganado!", "reward.lost": "Has perdido...", "reward.total": "Puntos totales", "reward.continue": "Toca para continuar", "game.menu": "Menú", "game.paused": "En pausa", "game.resume": "Continuar", "game.backToMenu": "Volver al menú principal", "reward.ended": "Partida terminada", "offline.defeated.one": "{n} rival derrotado", "offline.defeated.few": "{n} rivales derrotados", "offline.defeated.many": "{n} rivales derrotados", "offline.defeated.other": "{n} rivales derrotados", "stats.gravity": "{pct} % ({g} g)", "menu.survival": "Supervivencia", "menu.leaderboard": "Clasificación", "leaderboard.title": "Clasificación", "leaderboard.global": "Top 10", "leaderboard.friends": "Amigos", "leaderboard.empty": "Aún no hay puntuaciones.", "leaderboard.loginPrompt": "Inicia sesión para ver la clasificación de tus amigos.", "leaderboard.loadError": "No se pudo cargar la clasificación.", "leaderboard.points": "{n} puntos" } }, "errors": { "Log in om verder te gaan.": "error.loginRequired", "Onbekende planeet.": "error.unknownPlanet", "Onbekende taal.": "error.unknownLanguage", "Onbekende speelmodus.": "error.unknownMode", "Ongeldige speelsessie.": "error.invalidSession", "Speelsessie is verlopen.": "error.sessionExpired", "Een planeet heeft precies vijf blokjes nodig.": "error.needFiveBlocks", "Onbekend blokje.": "error.unknownBlock", "Dit blokje is nog niet ontgrendeld.": "error.blockLocked", "Elk blokje mag maar in één vak.": "error.duplicateBlock", "Opslaan is mislukt.": "error.saveFailed", "Onbekende actie.": "error.unknownAction", "Interne fout.": "error.internal", "Niet beschikbaar.": "error.notAvailable", "Ongeldige of ontbrekende CSRF-token.": "error.csrf", "Je zit al in een lobby. Verlaat die eerst.": "error.alreadyInLobby", "Je zit al in een andere lobby. Verlaat die eerst.": "error.alreadyInOtherLobby", "Onbekende lobbycode.": "error.unknownLobby", "Deze lobby is al begonnen.": "error.lobbyStarted", "Je zit niet in een lobby.": "error.notInLobby", "Je zit in geen lobby.": "error.notInAnyLobby", "Alleen de host kan het spel starten.": "error.hostOnly", "Het spel is al begonnen.": "error.gameAlreadyStarted", "Er zijn minstens twee spelers nodig.": "error.needTwoPlayers", "Niet iedereen is gereed.": "error.notAllReady", "De planeet kun je alleen kiezen voordat het spel start.": "error.planetLocked", "Geen verbinding met de server.": "error.connection", "Geen geldig antwoord van de server.": "error.badResponse", "Onbekende testgebruiker.": "error.notAvailable" }, "localeIds": [ "en", "nl", "de", "fr", "ja", "zh", "ko", "pl", "ru", "es" ] } ; /* * 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/i18n.js */ 'use strict'; /** * Player-facing translations for Meteors (t1141). * Default locale is English. The player's choice is stored in * localStorage and, when they are logged in, on their server profile. */ var I18n = { LOCALES: [ { id: 'en', flag: 'gb', endonym: 'English', htmlLang: 'en' }, { id: 'nl', flag: 'nl', endonym: 'Nederlands', htmlLang: 'nl' }, { id: 'de', flag: 'de', endonym: 'Deutsch', htmlLang: 'de' }, { id: 'fr', flag: 'fr', endonym: 'Français', htmlLang: 'fr' }, { id: 'ja', flag: 'jp', endonym: '日本語', htmlLang: 'ja' }, { id: 'zh', flag: 'cn', endonym: '简体中文', htmlLang: 'zh-Hans' }, { id: 'ko', flag: 'kr', endonym: '한국어', htmlLang: 'ko' }, { id: 'pl', flag: 'pl', endonym: 'Polski', htmlLang: 'pl' }, { id: 'ru', flag: 'ru', endonym: 'Русский', htmlLang: 'ru' }, { id: 'es', flag: 'es', endonym: 'Español', htmlLang: 'es' } ], DEFAULT: 'en', STORAGE_KEY: 'meteors-locale', EXPLICIT_KEY: 'meteors-locale-chosen', COOKIE: 'meteors-locale', locale: 'en', _catalog: null, _listeners: [], _pickerOpen: false }; I18n._load = function () { if (this._catalog) { return this._catalog; } var data = null; if (typeof I18N_CATALOG !== 'undefined' && I18N_CATALOG) { data = I18N_CATALOG; } else if (typeof require !== 'undefined') { try { data = require('../server/lib/i18n.json'); } catch (e) { data = null; } } this._catalog = data && data.locales ? data : { locales: { en: {} }, errors: {} }; return this._catalog; }; I18n.known = function (id) { if (!id) { return false; } for (var i = 0; i < this.LOCALES.length; i++) { if (this.LOCALES[i].id === id) { return true; } } return false; }; /** * Map a BCP 47 auth claim (zh-Hans) or a stored id to a Meteors locale. * Unknown values return null. */ I18n.normalize = function (id) { if (id == null || id === '') { return null; } var s = String(id).trim().toLowerCase().replace(/_/g, '-'); if (s === 'zh-hans' || s === 'zh-cn' || s === 'zh-sg' || s === 'zh-my') { return 'zh'; } if (this.known(s)) { return s; } var primary = s.split('-')[0]; return this.known(primary) ? primary : null; }; I18n.hasExplicitChoice = function () { try { if (typeof localStorage !== 'undefined') { return localStorage.getItem(this.EXPLICIT_KEY) === '1'; } } catch (e) { /* private mode */ } return false; }; I18n.markExplicit = function (on) { try { if (typeof localStorage === 'undefined') { return; } if (on === false) { localStorage.removeItem(this.EXPLICIT_KEY); } else { localStorage.setItem(this.EXPLICIT_KEY, '1'); } } catch (e) { /* ignore */ } }; I18n.info = function (id) { id = id || this.locale; for (var i = 0; i < this.LOCALES.length; i++) { if (this.LOCALES[i].id === id) { return this.LOCALES[i]; } } return this.LOCALES[0]; }; I18n.t = function (key, params, fallback) { this._load(); var loc = this._catalog.locales[this.locale] || {}; var en = this._catalog.locales.en || {}; var s = loc[key]; if (s == null || s === '') { s = en[key]; } if (s == null || s === '') { s = fallback != null ? fallback : key; } s = String(s); if (params) { s = s.replace(/\{(\w+)\}/g, function (_, k) { return params[k] != null ? String(params[k]) : ''; }); } return s; }; /** Slavic-style plural: one / few / many (falls back to other). */ I18n.pluralForm = function (n, locale) { n = Math.abs(parseInt(n, 10) || 0); locale = locale || this.locale; if (locale === 'ru') { var mod10 = n % 10, mod100 = n % 100; if (mod10 === 1 && mod100 !== 11) { return 'one'; } if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) { return 'few'; } return 'many'; } if (locale === 'pl') { if (n === 1) { return 'one'; } var mod10 = n % 10, mod100 = n % 100; if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) { return 'few'; } return 'many'; } if (locale === 'fr' || locale === 'es') { return (n === 0 || n === 1) ? 'one' : 'other'; } if (locale === 'ja' || locale === 'zh' || locale === 'ko') { return 'other'; } return n === 1 ? 'one' : 'other'; }; I18n.plural = function (base, n, params) { params = params || {}; params.n = n; var form = this.pluralForm(n); var key = base + '.' + form; this._load(); var loc = this._catalog.locales[this.locale] || {}; var en = this._catalog.locales.en || {}; if (loc[key] == null && en[key] == null) { if (form === 'few' || form === 'many') { key = base + '.other'; } } if ((loc[key] == null && en[key] == null) && form !== 'one') { key = base + '.other'; } return this.t(key, params); }; I18n.place = function (n) { return this.t('podium.place.' + (n === 1 ? '1' : n === 2 ? '2' : n === 3 ? '3' : 'n'), { n: n }, String(n)); }; I18n.planetName = function (planet) { if (!planet) { return ''; } if (planet.custom) { return planet.name || ''; } return this.t('planet.' + planet.id + '.name', null, planet.name || planet.id); }; I18n.peopleName = function (planet) { if (!planet) { return ''; } if (planet.custom) { return planet.people || ''; } return this.t('planet.' + planet.id + '.people', null, planet.people || ''); }; I18n.blockName = function (id, fallback) { if (!id) { return fallback || ''; } return this.t('block.' + id, null, fallback || id); }; I18n.error = function (msg) { if (!msg) { return ''; } this._load(); var map = this._catalog.errors || {}; if (map[msg]) { return this.t(map[msg]); } var m = /^Deze lobby is vol \(maximaal (\d+) spelers\)\.$/.exec(msg); if (m) { return this.t('error.lobbyFull', { n: m[1] }); } m = /^Je hebt het maximum van (\d+) planeten bereikt\.$/.exec(msg); if (m) { return this.t('error.maxPlanets', { n: m[1] }); } m = /^Vul een (.+) in\.$/.exec(msg); if (m) { var field = m[1]; if (field === 'planeetnaam') { field = this.t('error.fieldPlanet'); } else if (field === 'bevolkingsnaam') { field = this.t('error.fieldPeople'); } return this.t('error.fillField', { field: field }); } m = /^De server gaf (\d+)$/.exec(msg); if (m) { return this.t('error.serverStatus', { status: m[1] }); } return msg; }; I18n.readStored = function () { try { if (typeof localStorage !== 'undefined') { var v = localStorage.getItem(this.STORAGE_KEY); if (this.known(v)) { return v; } } } catch (e) { /* private mode */ } return this.DEFAULT; }; I18n._writeStored = function (id) { try { if (typeof localStorage !== 'undefined') { localStorage.setItem(this.STORAGE_KEY, id); } } catch (e) { /* ignore */ } try { if (typeof document !== 'undefined') { document.cookie = this.COOKIE + '=' + encodeURIComponent(id) + ';path=/;max-age=31536000;SameSite=Lax'; } } catch (e) { /* ignore */ } }; I18n.setLocale = function (id, opts) { opts = opts || {}; id = this.normalize(id); if (!id) { id = this.DEFAULT; } var changed = id !== this.locale; this.locale = id; if (opts.persist !== false) { this._writeStored(id); } if (opts.explicit !== false && opts.persist !== false) { this.markExplicit(); } if (typeof document !== 'undefined' && document.documentElement) { document.documentElement.lang = this.info(id).htmlLang; document.documentElement.setAttribute('data-locale', id); } this.apply(); this.renderPicker(); if (changed || opts.force) { for (var i = 0; i < this._listeners.length; i++) { try { this._listeners[i](id); } catch (e) { /* listener errors must not break i18n */ } } } if (opts.sync !== false && typeof Online !== 'undefined' && Online.me && Online.setLocale) { Online.setLocale(id); } return id; }; I18n.onChange = function (fn) { if (typeof fn === 'function') { this._listeners.push(fn); } }; I18n.apply = function (root) { if (typeof document === 'undefined') { return; } root = root || document; var nodes = root.querySelectorAll('[data-i18n]'); for (var i = 0; i < nodes.length; i++) { var el = nodes[i]; var key = el.getAttribute('data-i18n'); if (!key) { continue; } // Fall back to English (inside t) then the existing label so a // missing/stale key never replaces visible text with the raw key. el.textContent = this.t(key, null, el.textContent); } nodes = root.querySelectorAll('[data-i18n-html]'); for (var i = 0; i < nodes.length; i++) { var el = nodes[i]; var key = el.getAttribute('data-i18n-html'); if (!key) { continue; } el.innerHTML = this.t(key, null, el.innerHTML); } nodes = root.querySelectorAll('[data-i18n-placeholder]'); for (var i = 0; i < nodes.length; i++) { var el = nodes[i]; el.setAttribute('placeholder', this.t(el.getAttribute('data-i18n-placeholder'), null, el.getAttribute('placeholder'))); } nodes = root.querySelectorAll('[data-i18n-aria]'); for (var i = 0; i < nodes.length; i++) { var el = nodes[i]; el.setAttribute('aria-label', this.t(el.getAttribute('data-i18n-aria'), null, el.getAttribute('aria-label'))); } nodes = root.querySelectorAll('[data-i18n-title]'); for (var i = 0; i < nodes.length; i++) { var el = nodes[i]; el.setAttribute('title', this.t(el.getAttribute('data-i18n-title'), null, el.getAttribute('title'))); } }; I18n.flagUrl = function (id) { var info = this.info(id); return 'images/flags/' + info.flag + '.svg'; }; I18n.togglePicker = function (force) { if (typeof force === 'boolean') { this._pickerOpen = force; } else { this._pickerOpen = !this._pickerOpen; } this.renderPicker(); }; I18n.renderPicker = function () { if (typeof document === 'undefined') { return; } var wrap = document.getElementById('lang-picker'); var btn = document.getElementById('lang-current'); var list = document.getElementById('lang-list'); if (!wrap || !btn || !list) { return; } var info = this.info(); var img = btn.querySelector('img'); if (img) { img.src = this.flagUrl(this.locale); img.alt = info.endonym; } btn.setAttribute('aria-label', this.t('lang.current', { name: info.endonym })); btn.setAttribute('aria-expanded', this._pickerOpen ? 'true' : 'false'); btn.title = info.endonym; list.innerHTML = ''; if (!this._pickerOpen) { list.hidden = true; wrap.classList.remove('open'); return; } wrap.classList.add('open'); list.hidden = false; for (var i = 0; i < this.LOCALES.length; i++) { var loc = this.LOCALES[i]; var opt = document.createElement('button'); opt.type = 'button'; opt.className = 'lang-option' + (loc.id === this.locale ? ' current' : ''); opt.setAttribute('data-locale', loc.id); opt.setAttribute('aria-label', loc.endonym); opt.title = loc.endonym; opt.innerHTML = '' + '' + loc.endonym + ''; (function (id) { opt.addEventListener('click', function (e) { e.stopPropagation(); I18n.setLocale(id); I18n.togglePicker(false); }); })(loc.id); list.appendChild(opt); } }; I18n.bindPicker = function () { if (typeof document === 'undefined') { return; } var btn = document.getElementById('lang-current'); var list = document.getElementById('lang-list'); if (btn) { btn.addEventListener('click', function (e) { e.stopPropagation(); I18n.togglePicker(); }); } document.addEventListener('click', function (e) { var wrap = document.getElementById('lang-picker'); if (!wrap || !I18n._pickerOpen) { return; } if (!wrap.contains(e.target)) { I18n.togglePicker(false); } }); document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && I18n._pickerOpen) { I18n.togglePicker(false); } }); this.renderPicker(); }; I18n.init = function () { this._load(); this.locale = this.readStored(); if (typeof document !== 'undefined' && document.documentElement) { document.documentElement.lang = this.info().htmlLang; document.documentElement.setAttribute('data-locale', this.locale); } this.apply(); }; I18n.applyFromProfile = function (locale) { this.applyPreferred({ locale: locale, explicit: true }); }; /** * t1250: an explicit in-game choice always wins. Otherwise a logged-in * player follows the auth OIDC locale (mapped, e.g. zh-Hans → zh). * Guests are left to init()/localStorage. */ I18n.applyPreferred = function (opts) { opts = opts || {}; var chosen = this.normalize(opts.locale); var auth = this.normalize(opts.authLocale); var explicit = !!(opts.explicit && chosen) || this.hasExplicitChoice(); if (explicit) { var id = chosen || this.readStored(); if (this.known(id)) { this.setLocale(id, { sync: false, persist: true, explicit: true }); if (opts.syncExplicit && typeof Online !== 'undefined' && Online.me && Online.setLocale && Online.locale !== id) { Online.setLocale(id); } } return id; } if (auth) { return this.setLocale(auth, { persist: false, sync: false, explicit: false }); } return this.locale; }; if (typeof module !== 'undefined' && module.exports) { module.exports = I18n; } else if (typeof globalThis !== 'undefined') { globalThis.I18n = I18n; } /* * End File: * /workspace/meteors/src/i18n.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): 2 (easy, high jump) .. 4 (hard, short jump). * Minimum raised from 1 to 2 in t1199 (GRAVITY_MIN). Shown as a * percentage, linear in the value: pct = (v − 1)·100, so 2 → 100 % * (9.81 g), 3 → 200 % (19.62 g), 4 → 300 % (29.43 g). * 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' } ]; } /** t1199: gravity (jumpsToClear) range; values below the minimum clamp up. */ var GRAVITY_MIN = 2; var GRAVITY_MAX = 4; /** t1199: g at 100 % (jumpsToClear 2). */ var EARTH_G = 9.81; /** t1199: displayed gravity percentage, linear: (v − 1)·100. */ function gravityPercent (jumpsToClear) { return Math.round((clamp(jumpsToClear, GRAVITY_MIN, GRAVITY_MAX) - 1) * 100); } /** t1199: displayed g, consistent with the percentage: 9.81·(v − 1). */ function gravityG (jumpsToClear) { return EARTH_G * (clamp(jumpsToClear, GRAVITY_MIN, GRAVITY_MAX) - 1); } /** t1199: "100% (9.81g)" style text (i18n template stats.gravity). */ function formatGravity (jumpsToClear) { var params = { pct: gravityPercent(jumpsToClear), g: gravityG(jumpsToClear).toFixed(2) }; if (typeof I18n !== 'undefined' && I18n.t) { var s = I18n.t('stats.gravity', params); if (s && s !== 'stats.gravity') { return s; } } return params.pct + '% (' + params.g + 'g)'; } function createPlanet (opts) { opts = opts || {}; var jumpsToClear = clamp(opts.jumpsToClear == null ? 2 : opts.jumpsToClear, GRAVITY_MIN, GRAVITY_MAX); 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: [] }; } /** Player-owned custom planets (from the profile) and any remembered * snapshots (opponents in a lobby), not part of the official catalog. */ var _customPlanets = []; var _remembered = Object.create(null); function setCustomPlanets (list) { _customPlanets = []; if (!list || !list.length) { return; } for (var i = 0; i < list.length; i++) { _customPlanets.push(planetFromData(list[i])); } } function rememberPlanet (data) { if (!data || !data.id) { return null; } var pl = planetFromData(data); _remembered[pl.id] = pl; return pl; } function forgetRemembered () { _remembered = Object.create(null); } 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; if (data.custom) { planet.custom = true; } if (data.owner_id) { planet.owner_id = data.owner_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'; } for (var c = 0; c < _customPlanets.length; c++) { out.push(_customPlanets[c]); } return out; } function planetById (id) { var all = allPlanets(); for (var i = 0; i < all.length; i++) { if (all[i].id === id) { return all[i]; } } if (id && _remembered[id]) { return _remembered[id]; } return defaultPlanet(); } function officialPlanets () { var raw = loadCatalog().planets || []; var out = []; for (var i = 0; i < raw.length; i++) { out.push(planetFromData(raw[i])); } return out; } function customPlanets () { return _customPlanets.slice(); } function pickerPlanets () { return officialPlanets().concat(_customPlanets); } 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); var power = (typeof I18n !== 'undefined') ? I18n.t('stats.powerLabel') : 'Power'; return 'g ' + formatGravity(planet.jumpsToClear) + ' 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'; } // Custom planets (and any color that names a registry block) share // the preloaded Blocks.images() sprite, so late-loaded customs and // opponent snapshots do not need a second preload. if (c.block) { return 'block:' + c.block; } 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) { // t1199: scale kept on the old 1..4 axis on purpose, so unchanged // planets keep their Power/miss chance; the 2.0 minimum means the // gravity term is now at least 1/3 (lowest possible Power ≈ 0.11). 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 = gravityG(planet.jumpsToClear); var density = 0.25 + ((5 - planet.fallTime) / 4) * 1.60; var newtons = 40 + ((planet.riseTime - 0.5) / 2.5) * 160; return { gravity: gravity, gravityPct: gravityPercent(planet.jumpsToClear), 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, GRAVITY_MIN: GRAVITY_MIN, GRAVITY_MAX: GRAVITY_MAX, EARTH_G: EARTH_G, gravityPercent: gravityPercent, gravityG: gravityG, formatGravity: formatGravity, createPlanet: createPlanet, defaultPlanet: defaultPlanet, defaultColors: defaultColors, allPlanets: allPlanets, officialPlanets: officialPlanets, customPlanets: customPlanets, pickerPlanets: pickerPlanets, setCustomPlanets: setCustomPlanets, rememberPlanet: rememberPlanet, forgetRemembered: forgetRemembered, 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/blocks.js */ 'use strict'; /** * Append-only block registry. Thresholds and order stay in lockstep with * server/lib/Blocks.php: Terra's first five are free; the next costs 500 * lifetime points; each one after that costs 14.5% more (rounded, always * strictly increasing). Points are a requirement, not a spend. */ var Blocks = (function () { var TERRA_COUNT = 5; var FIRST_THRESHOLD = 500; var GROWTH = 1.145; var _all = null; function loadRegistry () { if (_all) { return _all; } var data = null; if (typeof BLOCK_REGISTRY !== 'undefined' && BLOCK_REGISTRY && BLOCK_REGISTRY.blocks) { data = BLOCK_REGISTRY; } else if (typeof require !== 'undefined') { try { data = require('../server/lib/blocks.json'); } catch (e) { data = null; } } _all = (data && data.blocks) ? data.blocks.slice() : []; return _all; } function all () { return loadRegistry(); } function byId (id) { var list = all(); for (var i = 0; i < list.length; i++) { if (list[i].id === id) { return list[i]; } } return null; } function indexOf (id) { var list = all(); for (var i = 0; i < list.length; i++) { if (list[i].id === id) { return i; } } return -1; } function threshold (index) { if (index < TERRA_COUNT) { return 0; } var t = FIRST_THRESHOLD; for (var i = TERRA_COUNT; i < index; i++) { var next = Math.round(t * GROWTH); t = Math.max(t + 1, next); } return t; } function unlocked (index, points) { points = points || 0; return points >= threshold(index); } function unlockedId (id, points) { var i = indexOf(id); return i >= 0 && unlocked(i, points); } function present (points) { points = points || 0; var list = all(); var out = []; for (var i = 0; i < list.length; i++) { var b = list[i]; var need = threshold(i); out.push({ id: b.id, name: b.name || b.id, hex: b.hex, shape: b.shape, image: b.image, terra: !!b.terra || i < TERRA_COUNT, index: i, threshold: need, unlocked: points >= need }); } return out; } function asColor (id, slot) { var b = byId(id); if (!b) { return null; } return { id: slot, block: b.id, name: b.name || b.id, hex: b.hex, shape: b.shape, image: b.image }; } function images () { var list = all(); var out = []; var seen = Object.create(null); for (var i = 0; i < list.length; i++) { var url = list[i].image; if (!url || seen[url]) { continue; } seen[url] = true; out.push({ name: 'block:' + list[i].id, url: url }); } return out; } return { TERRA_COUNT: TERRA_COUNT, FIRST_THRESHOLD: FIRST_THRESHOLD, GROWTH: GROWTH, all: all, byId: byId, indexOf: indexOf, threshold: threshold, unlocked: unlocked, unlockedId: unlockedId, present: present, asColor: asColor, images: images }; })(); if (typeof module !== 'undefined' && module.exports) { module.exports = Blocks; } else if (typeof globalThis !== 'undefined') { globalThis.Blocks = Blocks; } /* * End File: * /workspace/meteors/src/blocks.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; /** Seconds of actual play in this match / round (t1189). */ this.playTime = 0; /** t1197: matches in the current combo and seconds since the last one. */ this.combo = 0; this.comboAge = 0; this.settleTime = PlanetMod.SETTLE_TIME; this.score = 0; this.state = 'playing'; this.drag = null; this.gameOverTime = 0; this.outgoingShots = []; /** Received garbage waiting for room (t1192). */ this.garbageQueue = []; // 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; /** t1197/t1198: each earlier match in a combo adds this much jump height (additive). */ GameCore.COMBO_STEP = 0.01; /** t1198: combo steps that count at most (bonus capped at +30 %). */ GameCore.COMBO_MAX_STEPS = 30; /** t1197: the combo resets when no match is made for this long (s). */ GameCore.COMBO_RESET_S = 5; 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); // t1189: spawn timeline by elapsed play time (intro burst, ramp, then // the per-spawn speed-up). Interval is re-read after every spawn. // t1192: waiting received blocks drop first, as soon as there is room. if (this.garbageQueue.length) { this.drainGarbageQueue(); } // t1197: combo expires after COMBO_RESET_S without a match. this.comboAge += dt; if (this.combo > 0 && this.comboAge >= GameCore.COMBO_RESET_S) { this.combo = 0; if (!this.hasActiveLandingChain()) { this.lastChainIndicator = null; } } this.spawnTimer += dt; var iv = this.currentSpawnInterval(); while (this.spawnTimer >= iv) { this.spawnTimer -= iv; this.trySpawn(); iv = this.currentSpawnInterval(); } this.playTime += dt; 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; } }; /** Share of the field height a rising stack must pass (t1184). */ GameCore.DEPART_SHARE = 0.75; /** * Columns with a rising rocket stack that will certainly leave the * screen (t1184). A flying cluster counts when it is still going up, * its highest block is past DEPART_SHARE of the field height, its apex * (y + vy^2 / (2 * decel)) is at or above the top, and nothing grounded * hangs above it in its columns. Every column that stack occupies is * departing: newly spawned blocks and received garbage pick another * column (t1185/t1186). Returns { col: true }. */ GameCore.prototype.departingColumns = function () { var out = Object.create(null); var H = this.height; var ids = Object.keys(this.clusters); for (var n = 0; n < ids.length; n++) { var cluster = this.clusters[ids[n]]; if (!cluster || cluster.phase !== 'up' || !(cluster.vy > 1e-9)) { continue; } var members = this.clusterMembers(cluster.id); if (!members.length) { continue; } var top = -Infinity; var lowest = Object.create(null); for (var i = 0; i < members.length; i++) { var m = members[i]; if (m.state !== STATE_FLYING) { continue; } if (m.y > top) { top = m.y; } if (lowest[m.col] == null || m.y < lowest[m.col]) { lowest[m.col] = m.y; } } if (top < this.DEPART_LINE()) { continue; } var decel = cluster.decel || 0; var rise = decel > 1e-12 ? (cluster.vy * cluster.vy) / (2 * decel) : Infinity; if (top + rise < H - 1e-9) { continue; } var blocked = false; for (var col in lowest) { var c = col | 0; for (var j = 0; j < this.blocks.length; j++) { var b = this.blocks[j]; if (b.col === c && b.clusterId !== cluster.id && this.isGrounded(b) && b.y > lowest[col]) { blocked = true; break; } } if (blocked) { break; } } if (blocked) { continue; } // t1185/t1186: every column the departing stack occupies is off // limits; new and received blocks pick another column. for (var col2 in lowest) { out[col2 | 0] = true; } } return out; }; /** Height (tiles from the ground) a rising stack must pass: 75% of the field. */ GameCore.prototype.DEPART_LINE = function () { return this.height * GameCore.DEPART_SHARE; }; GameCore.prototype.trySpawn = function () { if (this.state !== 'playing') { return null; } var eligible = []; var departing = this.departingColumns(); for (var col = 0; col < this.width; col++) { if (this.isColumnLocked(col)) { continue; } if (this.groundedCount(col) >= this.height) { continue; } // t1184: never drop a new block onto a stack that is leaving. if (departing[col]) { continue; } var alreadyFalling = false; var list = this.blocksInColumn(col); // t1189/t1191: during the opening burst and ramp a column may take // another block as soon as the previous falling one has cleared a // full cell below the spawn row (no overlap); later the classic // one-falling-block-per-column rule applies. var opening = this.playTime < GameCore.SPAWN_RAMP_END; for (var i = 0; i < list.length; i++) { if (list[i].state !== STATE_FALLING) { continue; } if (opening && list[i].y <= this.height - 1 + 1e-9) { continue; } alreadyFalling = true; break; } if (!alreadyFalling) { eligible.push(col); } } if (!eligible.length) { return null; } var col = this.playTime < GameCore.SPAWN_INTRO_END ? this.pickWeightedSpawnColumn(eligible) : 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; // t1187/t1188 speed-up only counts blocks spawned after the intro (t1189). if (this.playTime >= GameCore.SPAWN_RAMP_END) { this.speedUpSpawning(); } return block; }; /** * Burst-phase column choice (t1191): weight each eligible column by its * free cells (height − grounded − already falling blocks, min 1), so the fast opening burst fills * the field evenly instead of piling onto one column. One rng() draw, like * the uniform pick. */ GameCore.prototype.fallingCount = function (col) { var n = 0; for (var i = 0; i < this.blocks.length; i++) { if (this.blocks[i].col === col && this.blocks[i].state === STATE_FALLING) { n++; } } return n; }; GameCore.prototype.pickWeightedSpawnColumn = function (eligible) { var weights = []; var total = 0; for (var i = 0; i < eligible.length; i++) { var w = Math.max(1, this.height - this.groundedCount(eligible[i]) - this.fallingCount(eligible[i])); weights.push(w); total += w; } var r = this.rng() * total; for (var j = 0; j < eligible.length; j++) { r -= weights[j]; if (r < 0) { return eligible[j]; } } return eligible[eligible.length - 1]; }; /** t1189/t1191: first seconds of a match spawn fast ... */ GameCore.SPAWN_INTRO_END = 3; /** ... at this interval (seconds) ... */ GameCore.SPAWN_INTRO_INTERVAL = 0.1; /** ... then lerp back to PlanetMod.SPAWN_INTERVAL (1 s) until this time. */ GameCore.SPAWN_RAMP_END = 6; /** * Spawn interval right now (t1189): * playTime < 3 s → 0.1 s (burst, weighted column choice) * 3 s – 6 s → linear 0.1 s → 1.0 s * ≥ 6 s → spawnInterval (starts at 1 s, ×0.997 per spawn * after 6 s, floor 0.1 s) * An interval set above the 1 s start (tests / tools use 1e9 to switch * spawning off) is always respected. */ GameCore.prototype.currentSpawnInterval = function () { var base = PlanetMod.SPAWN_INTERVAL; if (this.spawnInterval > base + 1e-9) { return this.spawnInterval; } var t = this.playTime || 0; if (t < GameCore.SPAWN_INTRO_END) { return GameCore.SPAWN_INTRO_INTERVAL; } if (t < GameCore.SPAWN_RAMP_END) { var k = (t - GameCore.SPAWN_INTRO_END) / (GameCore.SPAWN_RAMP_END - GameCore.SPAWN_INTRO_END); return GameCore.SPAWN_INTRO_INTERVAL + (base - GameCore.SPAWN_INTRO_INTERVAL) * k; } return this.spawnInterval; }; /** Each spawned block shrinks the spawn interval by 0.3% (t1187 / t1188). */ GameCore.SPAWN_SPEEDUP = 0.997; /** The spawn interval never goes below this (seconds, t1187). */ GameCore.SPAWN_INTERVAL_MIN = 0.1; /** * After every real spawn: spawnInterval *= SPAWN_SPEEDUP, floored at * SPAWN_INTERVAL_MIN. Starts at PlanetMod.SPAWN_INTERVAL (1 s) for every * new core, i.e. every game and every round, for players and bots alike. * Reaches the floor after ~767 spawns (~5 min of continuous play). */ GameCore.prototype.speedUpSpawning = function () { var next = this.spawnInterval * GameCore.SPAWN_SPEEDUP; this.spawnInterval = Math.max(GameCore.SPAWN_INTERVAL_MIN, next); return this.spawnInterval; }; 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, vy: block.vy }); this.score += 1; this.removeBlock(block); } }; GameCore.prototype.consumeOutgoingShots = function () { var shots = this.outgoingShots; this.outgoingShots = []; return shots; }; /** * A compact field picture for the multiplayer snapshot (miniatures). * Includes every block's col, y, color, state and flame. */ GameCore.prototype.fieldSnapshot = function () { var blocks = []; for (var i = 0; i < this.blocks.length; i++) { var b = this.blocks[i]; blocks.push({ id: b.id, col: b.col, y: Math.round(b.y * 1000) / 1000, color: b.color, state: b.state, flame: !!b.flame }); } return { score: this.score, state: this.state, width: this.width, height: this.height, locked: this.lockedColumnCount(), blocks: blocks }; }; /** * Incoming garbage from another player: a dark-grey block that falls * normally from the top of an open column. After landing it uses the * usual 3s settle and then a random colour (landFallingBlock). * `col` is optional; a random eligible column is used otherwise. * Returns the new block, or null if every column is locked or full. */ /** * Open columns a garbage block can fall into (not locked, not full). */ GameCore.prototype.eligibleGarbageColumns = function () { var eligible = []; for (var c = 0; c < this.width; c++) { if (this.isColumnLocked(c)) { continue; } if (this.groundedCount(c) >= this.height) { continue; } eligible.push(c); } return eligible; }; /** * Choose a garbage column. If `preferred` is still open, it wins; * otherwise a random eligible column (t1126). Returns null if none. */ GameCore.prototype.pickGarbageColumn = function (preferred) { var eligible = this.eligibleGarbageColumns(); if (!eligible.length) { return null; } // t1184: skip columns whose rocket stack is certainly leaving; only // if every open column is departing, fall back so no garbage is lost. var departing = this.departingColumns(); var staying = []; for (var k = 0; k < eligible.length; k++) { if (!departing[eligible[k]]) { staying.push(eligible[k]); } } if (staying.length) { eligible = staying; } if (preferred != null && isFinite(preferred)) { var want = preferred | 0; for (var i = 0; i < eligible.length; i++) { if (eligible[i] === want) { return want; } } } return eligible[Math.floor(this.rng() * eligible.length) % eligible.length]; }; /** * Receive one garbage block (t1192). It is queued and dropped as soon as * there is room; received blocks are never lost. Returns the block when * it could drop right away, otherwise null (it waits in garbageQueue). * * Before t1192 every received block was created at once at the spawn * row of its column. Several blocks aimed at the same column overlapped * there: the second one "landed" on the first at y ≥ 13, was culled off * the top and even counted as the receiver's own shot. */ GameCore.prototype.ingestGarbage = function (col) { if (this.state !== 'playing') { return null; } var want = (col != null && isFinite(col)) ? (col | 0) : null; var item = { col: want, block: null }; this.garbageQueue.push(item); this.drainGarbageQueue(); return item.block; }; /** * Can a block enter `col` at the spawn row now? Same rule as the opening * burst: every block already in the column must be at least a full cell * below the spawn row (no overlap). */ GameCore.prototype.spawnCellClear = function (col) { for (var i = 0; i < this.blocks.length; i++) { var b = this.blocks[i]; if (b.col === col && b.y > this.height - 1 + 1e-9) { return false; } } return true; }; /** Columns a queued garbage block can drop into right now (t1192). */ GameCore.prototype.garbageDropColumns = function () { var open = this.eligibleGarbageColumns(); var departing = this.departingColumns(); var out = []; for (var i = 0; i < open.length; i++) { var c = open[i]; if (departing[c]) { continue; } // Room left for one more block once everything in flight lands. if (this.groundedCount(c) + this.fallingCount(c) >= this.height) { continue; } if (!this.spawnCellClear(c)) { continue; } out.push(c); } return out; }; /** * Drop queued garbage in arrival order while there is room. The wanted * column (server land_col / bot pick) wins when it can take a block, * otherwise a random open one. When nothing is open the rest waits. * Returns how many blocks dropped. */ GameCore.prototype.drainGarbageQueue = function () { var dropped = 0; while (this.garbageQueue.length && this.state === 'playing') { var cols = this.garbageDropColumns(); if (!cols.length) { break; } var item = this.garbageQueue[0]; var chosen = null; if (item.col != null && cols.indexOf(item.col) >= 0) { chosen = item.col; } else { chosen = cols[Math.floor(this.rng() * cols.length) % cols.length]; } this.garbageQueue.shift(); var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING); block.vy = -this.planet.fallSpeed; block.flame = false; item.block = block; dropped++; } return dropped; }; /** Received blocks still waiting for room (t1192). */ GameCore.prototype.pendingGarbage = function () { return this.garbageQueue.length; }; 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); // t1197/t1198: combo bonus = COMBO_STEP per earlier match in this combo // (at most COMBO_MAX_STEPS steps), // added to the landing-chain bonus (one shown "+x%"). var comboBonus = GameCore.COMBO_STEP * Math.min(this.combo, GameCore.COMBO_MAX_STEPS); var bonusMul = 1 + LANDING_CHAIN_BONUS * chain + comboBonus; height *= bonusMul; this.launchCluster(group, height, { landingChain: chain }); launched.push({ blocks: group, jumpHeight: height, landingChain: chain, comboBonus: comboBonus, chainBonus: bonusMul }); this.combo += 1; this.comboAge = 0; } 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; var maxPct = 0; for (var i = 0; i < launched.length; i++) { var ch = launched[i].landingChain || 0; if (ch > maxChain) { maxChain = ch; } var pct = Math.round(((launched[i].chainBonus || 1) - 1) * 100); if (pct > maxPct) { maxPct = pct; } } if (maxPct > 0) { this.lastChainIndicator = { chain: maxChain, combo: this.combo, bonusPct: maxPct }; return; } if (!this.hasActiveLandingChain() && !(launched.length && this.combo > 0)) { this.lastChainIndicator = null; } }; /** * Combo bonus in percent, 0.01·min(combo, 30)·100: what the next match gets * from the combo alone. This is the only number the HUD "+x%" shows (t1200). */ GameCore.prototype.comboBonusPct = function () { return Math.round(GameCore.COMBO_STEP * Math.min(this.combo, GameCore.COMBO_MAX_STEPS) * 100); }; 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/flameFx.js */ /** * t1183 — rocket flame jitter. * * Every animation tick (FPS ticks per second) the flame picks a random * sprite frame (different from the current one), flips horizontally with * 50% chance and gets a small random scale / width / height / rotation. * All of it pivots on the top-centre of the flame, where it attaches to * the block, so that point never moves. * * Purely visual. Pure functions so it can be unit-tested. */ var FlameFx = {}; /** Ticks per second (was 12.5 fps = 0.08 s per frame; doubled). */ FlameFx.FPS = 25; /** Reduced motion: old frame rate, no flip/scale/rotation jitter. */ FlameFx.REDUCED_FPS = 12.5; /** Overall scale variation (±). */ FlameFx.SCALE_VAR = 0.06; /** Extra independent width variation (±). */ FlameFx.WIDTH_VAR = 0.07; /** Extra independent height variation (±). */ FlameFx.HEIGHT_VAR = 0.07; /** Rotation variation in degrees (±). */ FlameFx.ROT_VAR_DEG = 2.5; FlameFx.reducedMotion = function () { try { var w = typeof window !== 'undefined' ? window : null; return !!(w && w.matchMedia && w.matchMedia('(prefers-reduced-motion: reduce)').matches); } catch (e) { return false; } }; /** New per-flame state; the phase is random so flames don't tick in sync. */ FlameFx.create = function (frames, rand, reduced) { rand = rand || Math.random; var st = { frame: 0, timer: 0, flip: false, scale: 1, w: 1, h: 1, rot: 0, frames: frames || 1 }; st.timer = rand() / FlameFx.FPS; FlameFx.roll(st, rand, !!reduced); return st; }; /** Random frame index in [0, frames), different from `current` when possible. */ FlameFx.pickFrame = function (current, frames, rand) { rand = rand || Math.random; if (frames <= 1) { return 0; } // Choose among the other frames-1 indices uniformly. var k = Math.floor(rand() * (frames - 1)); if (k >= frames - 1) { k = frames - 2; } return k >= current ? k + 1 : k; }; function flameVar (rand, amount) { return 1 + (rand() * 2 - 1) * amount; } /** One animation tick: new frame, flip, scales and rotation. */ FlameFx.roll = function (st, rand, reduced) { rand = rand || Math.random; st.frame = FlameFx.pickFrame(st.frame, st.frames, rand); if (reduced) { st.flip = false; st.scale = 1; st.w = 1; st.h = 1; st.rot = 0; return st; } st.flip = rand() < 0.5; st.scale = flameVar(rand, FlameFx.SCALE_VAR); st.w = flameVar(rand, FlameFx.WIDTH_VAR); st.h = flameVar(rand, FlameFx.HEIGHT_VAR); st.rot = (rand() * 2 - 1) * FlameFx.ROT_VAR_DEG; return st; }; /** Advance time (seconds). Returns the number of ticks that happened. */ FlameFx.advance = function (st, dt, rand, reduced) { var period = 1 / (reduced ? FlameFx.REDUCED_FPS : FlameFx.FPS); st.timer += Math.max(0, dt || 0); var ticks = 0; while (st.timer >= period - 1e-9) { st.timer = Math.max(0, st.timer - period); ticks++; } // Long stall: one roll is enough, don't loop the RNG for nothing. if (ticks > 0) { FlameFx.roll(st, rand, reduced); } return ticks; }; /** * Draw pose for a flame whose top-centre anchor is (ax, ay) and whose * nominal size is baseW × baseH. The framework draws sprites centred on * (x, y), rotated by `rotation` degrees (clockwise, canvas y-down) around * that centre, and mirrorX flips around the vertical centre line. The * centre is placed so the rotated, scaled top-centre lands exactly on * the anchor. */ FlameFx.pose = function (st, ax, ay, baseW, baseH) { var w = baseW * st.scale * st.w; var h = baseH * st.scale * st.h; var rad = st.rot * Math.PI / 180; return { x: ax - Math.sin(rad) * h / 2, y: ay + Math.cos(rad) * h / 2, w: w, h: h, rotation: st.rot, mirrorX: !!st.flip, frame: st.frame }; }; /** * Where the top-centre of the drawn quad ends up for a pose — same * transform as the framework's sprite matrix (model point (0, -0.5)). * Used by tests to prove the anchor never moves. */ FlameFx.topCentreOf = function (pose) { var rad = pose.rotation * Math.PI / 180; var c = Math.cos(rad); var s = Math.sin(rad); var sy = pose.h; // x' = c*sx*u - s*sy*v + x ; y' = s*sx*u + c*sy*v + y with u = 0, v = -0.5 return { x: pose.x + s * sy * 0.5, y: pose.y - c * sy * 0.5 }; }; if (typeof globalThis !== 'undefined') { globalThis.FlameFx = FlameFx; } if (typeof module !== 'undefined' && module.exports) { module.exports = FlameFx; } /* * End File: * /workspace/meteors/src/flameFx.js */ /* * Start File: * /workspace/meteors/src/miniLayout.js */ 'use strict'; /** * Opponent miniature layout for online and Offline Strijd * (t1125, t1127, t1129, t1131, t1133). * Wide screens: minis sit beside the field, anchored to the outer * screen edges, filling inward (1 = left outer, 2 = right outer, * 3 = left next inward, …). Extra minis wrap to a new row upward * only when a side's row is full. Narrow / portrait: a row above * the field. */ var MiniLayout = (function () { var GAP = 12; var VGAP = 8; var EDGE = 16; var MIN_TILE_FOR_SIDES = 18; var LABEL_H = 32; /* Extra space above the field in the wide (sides) layout so enemy↔player arcs can route around the top edge (t1129). */ var ARC_TOP_PAD = 100; /* Below this width, or in a narrow portrait, keep the top row (t1131). */ var PORTRAIT_NARROW = 700; var PORTRAIT_MAX = 850; function preferredMini () { return { w: 80, h: 104, outerW: 90, outerH: 104 + LABEL_H }; } function canvasSize (n, mode, availH, rows) { n = n || 0; if (mode === 'sides') { rows = Math.max(1, rows || 1); if (availH && rows > 1) { var maxOuter = Math.floor((availH - (rows - 1) * VGAP) / 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, 56), outerH: ch + LABEL_H }; } return preferredMini(); } 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 }; } /** * How many minis fit in one row on a side, between the screen edge * and the field: EDGE + n*outerW + n*GAP <= sideWidth. */ function colsThatFit (sideWidth, mini) { if (!mini || !mini.outerW) { return 0; } var stride = mini.outerW + GAP; if (stride <= 0) { return 0; } return Math.max(0, Math.floor((sideWidth - EDGE) / stride)); } /** * Place n opponents. Anchored to the OUTER screen edges, filling * inward toward the field (t1133). Row 0 is bottom-aligned with the * field; further rows stack upward only after a side's row is full * (t1127). * * Index 0 → left outer, 1 → right outer, 2 → left next inward, … */ function sidePositions (n, fieldX, fieldY, fieldW, fieldH, mini, hudH, vw, colsPerSide) { var positions = []; if (n <= 0) { return positions; } vw = vw || (fieldX * 2 + fieldW); var leftSpace = fieldX; var rightSpace = vw - (fieldX + fieldW); var colsL = colsPerSide != null ? colsPerSide : Math.max(1, colsThatFit(leftSpace, mini)); var colsR = colsPerSide != null ? colsPerSide : Math.max(1, colsThatFit(rightSpace, mini)); if (colsL < 1) { colsL = 1; } if (colsR < 1) { colsR = 1; } var leftCount = Math.ceil(n / 2); var rightCount = Math.floor(n / 2); var rows = Math.max( Math.ceil(leftCount / colsL), rightCount ? Math.ceil(rightCount / colsR) : 1 ); 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 isLeft = (i % 2) === 0; var slot = Math.floor(i / 2); var cols = isLeft ? colsL : colsR; var row = Math.floor(slot / cols); var fromOuter = slot % cols; var x = isLeft ? EDGE + fromOuter * (mini.outerW + GAP) : vw - EDGE - mini.outerW - fromOuter * (mini.outerW + GAP); var y = bottom - (row + 1) * mini.outerH - row * VGAP; positions.push({ index: i, side: isLeft ? 'left' : 'right', row: row, fromOuter: fromOuter, colsPerSide: cols, x: x, y: y, w: mini.outerW, h: mini.outerH, canvasW: mini.w, canvasH: mini.h }); } return positions; } /* ---- t1203: top-row minis scale down so they all fit above the field ---- */ /** Horizontal / vertical gap between top-row minis (px). */ var TOP_GAP = 8; var TOP_VGAP = 4; /** Padding above the first top row (matches #minis padding-top). */ var TOP_PAD = 6; /** Largest and smallest mini canvas width in the top row (px). 32 px is * 3.2 px per column: the smallest size that still reads as a field. */ var TOP_MAX_W = 80; var TOP_MIN_W = 32; /** Label font: 11 px at full size, never below 9 px. */ var TOP_FONT_MAX = 11; var TOP_FONT_MIN = 9; /** Size of one top-row mini for a canvas width `w` (px). */ function topMiniForWidth (w) { w = Math.max(TOP_MIN_W, Math.min(TOP_MAX_W, Math.round(w))); var h = Math.round(w * 13 / 10); var font = Math.max(TOP_FONT_MIN, Math.min(TOP_FONT_MAX, Math.round(TOP_FONT_MAX * w / TOP_MAX_W))); var labelH = Math.round(font * 2.9); var outerW = w + Math.max(4, Math.round(10 * w / TOP_MAX_W)); return { w: w, h: h, outerW: outerW, outerH: h + labelH + 2, font: font, labelH: labelH, scale: w / TOP_MAX_W }; } function topGrid (n, availW, mini) { var cols = Math.max(1, Math.floor((availW + TOP_GAP) / (mini.outerW + TOP_GAP))); cols = Math.min(cols, Math.max(1, n)); var rows = Math.max(1, Math.ceil(n / cols)); // Balance the rows (6 → 3 + 3 rather than 5 + 1). cols = Math.max(1, Math.ceil(n / rows)); return { cols: cols, rows: rows, height: rows * mini.outerH + (rows - 1) * TOP_VGAP }; } /** * The largest top-row mini so that all `n` fit in `availW` × `bandH` * (t1203). If even TOP_MIN_W does not fit, return the minimum size with * fits = false and `capacity` = how many still fit above the field. */ function topMiniFit (n, availW, bandH) { n = Math.max(0, n || 0); for (var w = TOP_MAX_W; w >= TOP_MIN_W; w--) { var m = topMiniForWidth(w); var g = topGrid(n, availW, m); if (g.height <= bandH) { m.cols = g.cols; m.rows = g.rows; m.fits = true; m.capacity = Math.max(n, g.cols * g.rows); return m; } } var min = topMiniForWidth(TOP_MIN_W); var maxCols = Math.max(1, Math.floor((availW + TOP_GAP) / (min.outerW + TOP_GAP))); var rowsFit = Math.max(1, Math.floor((bandH + TOP_VGAP) / (min.outerH + TOP_VGAP))); min.cols = maxCols; min.rows = Math.ceil(n / maxCols); min.fits = false; min.capacity = maxCols * rowsFit; return min; } /** * Slot per opponent (t1203). When everything fits, slot = index (order * unchanged). Only when they do not fit: alive opponents first, then the * eliminated ones, each group in its original order (stable), so the * ones that end up behind the field are the defeated ones. * @param {boolean[]} eliminated per original index * @return {number[]} slot for each original index */ function topSlots (eliminated, fits) { var n = eliminated.length; var slots = new Array(n); if (fits) { for (var i = 0; i < n; i++) { slots[i] = i; } return slots; } var next = 0; for (var a = 0; a < n; a++) { if (!eliminated[a]) { slots[a] = next++; } } for (var e = 0; e < n; e++) { if (eliminated[e]) { slots[e] = next++; } } return slots; } /** Viewport position of top-row slot `slot` (rows centred). */ function topSlotPosition (slot, n, plan) { var mini = plan.mini; var cols = mini.cols || 1; var row = Math.floor(slot / cols); var inRow = Math.min(cols, n - row * cols); var rowW = inRow * mini.outerW + (inRow - 1) * TOP_GAP; var x0 = Math.round((plan.vw - rowW) / 2); return { slot: slot, row: row, x: x0 + (slot % cols) * (mini.outerW + TOP_GAP), y: plan.hudH + TOP_PAD + row * (mini.outerH + TOP_VGAP), w: mini.outerW, h: mini.outerH, canvasW: mini.w, canvasH: mini.h, font: mini.font, aboveField: (plan.hudH + TOP_PAD + row * (mini.outerH + TOP_VGAP) + mini.outerH) <= plan.fieldY + 0.5 }; } /** Positions per original index for the top row (t1203). */ function topPositions (eliminated, plan) { var n = eliminated.length; var slots = topSlots(eliminated, plan.mini && plan.mini.fits); var out = []; for (var i = 0; i < n; i++) { var pos = topSlotPosition(slots[i], n, plan); pos.index = i; pos.eliminated = !!eliminated[i]; out.push(pos); } return out; } function isPortraitNarrow (vw, vh) { if (vw < PORTRAIT_NARROW) { return true; } if (vw < vh && vw < PORTRAIT_MAX) { return true; } return false; } /** * 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, cols) { return { mode: mode, tile: tile, fieldW: tile * 10, fieldH: tile * 13, fieldX: fieldX, fieldY: fieldY, miniH: miniH, mini: mini, positions: positions || [], colsPerSide: cols || 0, n: n }; } if (n > 0 && !isPortraitNarrow(vw, vh)) { var availHSide = Math.max(80, vh - hudH - margin); var probe = preferredMini(); var availWSide = Math.max(80, vw - margin * 2 - 2 * (probe.outerW + GAP)); var availHForField = Math.max(80, availHSide - ARC_TOP_PAD); var tileSide = Math.max(14, Math.floor(Math.min(availWSide / 10, availHForField / 13))); var fieldWSide = tileSide * 10; var leftover = (vw - fieldWSide) / 2; var cols = colsThatFit(leftover, probe); // If a large mini does not fit, shrink it so a small one still can (t1131). if (cols < 1) { var shrinkStride = leftover - EDGE; if (shrinkStride >= 56 + GAP) { var ow = Math.max(56, shrinkStride - GAP); var oh = Math.round(ow * (104 + LABEL_H) / 90); var ch = Math.max(40, oh - LABEL_H); var cw = Math.max(32, Math.round(ch * 10 / 13)); probe = { w: cw, h: ch, outerW: ow, outerH: ch + LABEL_H }; cols = colsThatFit(leftover, probe); } } var need = probe.outerW + GAP + EDGE; if (leftover >= need && tileSide >= MIN_TILE_FOR_SIDES && cols >= 1) { var fieldX = Math.floor((vw - fieldWSide) / 2); var fieldHSide = tileSide * 13; var fieldY = hudH + ARC_TOP_PAD + Math.floor((availHForField - fieldHSide) / 2); if (fieldY < hudH + ARC_TOP_PAD) { fieldY = hudH + ARC_TOP_PAD; } var leftCount = Math.ceil(n / 2); var rows = Math.max(1, Math.ceil(leftCount / cols)); var stackAvail = fieldY + fieldHSide - (hudH + 4); if (rows > 1) { probe = canvasSize(n, 'sides', stackAvail, rows); cols = Math.max(1, colsThatFit(leftover, probe)); rows = Math.max(1, Math.ceil(leftCount / cols)); } return finish('sides', tileSide, fieldX, fieldY, 0, probe, sidePositions(n, fieldX, fieldY, fieldWSide, fieldHSide, probe, hudH, vw, cols), cols); } } 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; } if (n > 0) { // t1203: scale the minis so all of them fit in the band above the // field (band = from below the HUD to the top of the field). var bandH = Math.max(0, fieldY - hudH - TOP_PAD - 2); miniTop = topMiniFit(n, Math.max(40, vw - 2 * TOP_GAP), bandH); } var res = finish('top', tile, fieldX, fieldY, miniH, miniTop, [], 0); res.vw = vw; res.hudH = hudH; if (n > 0) { var none = []; for (var k = 0; k < n; k++) { none.push(false); } res.positions = topPositions(none, res); } return res; } var api = { GAP: GAP, VGAP: VGAP, EDGE: EDGE, MIN_TILE_FOR_SIDES: MIN_TILE_FOR_SIDES, ARC_TOP_PAD: ARC_TOP_PAD, PORTRAIT_NARROW: PORTRAIT_NARROW, LABEL_H: LABEL_H, canvasSize: canvasSize, TOP_GAP: TOP_GAP, TOP_VGAP: TOP_VGAP, TOP_PAD: TOP_PAD, TOP_MAX_W: TOP_MAX_W, TOP_MIN_W: TOP_MIN_W, TOP_FONT_MIN: TOP_FONT_MIN, topMiniForWidth: topMiniForWidth, topMiniFit: topMiniFit, topSlots: topSlots, topSlotPosition: topSlotPosition, topPositions: topPositions, colsThatFit: colsThatFit, 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/miniPredict.js */ 'use strict'; /** * t1182: client-side prediction for falling blocks on opponents' mini * fields. Purely visual. Between snapshots (one per poll, ~0.75 s) a * block whose authoritative state is 'falling' keeps descending at that * player's fallSpeed (13 / fallTime cells/s), with sub-cell motion. It * never goes below the first obstacle in its column, so a landing, lock * or match is never predicted — those only appear when the next * snapshot says so. When a snapshot arrives the shown position is * reconciled smoothly: a block that lags catches up a little faster, a * block that ran ahead falls more slowly until the truth catches up * (it never moves up), and a large difference snaps. */ var MiniPredict = { FIELD_HEIGHT: 13, /** Seconds over which a lagging block closes its gap (on top of fallSpeed). */ RECONCILE_S: 0.16, /** Cells: further off than this → snap to the authoritative pose. */ SNAP_CELLS: 1.5, /** Never extrapolate further than this past the last snapshot (s). */ MAX_EXTRAP_S: 1.5, /** Share of fallSpeed used while a block that ran ahead waits for the truth. */ AHEAD_SPEED_SHARE: 0.5, /** Largest frame step used for the smoothing integrator (s). */ MAX_FRAME_S: 0.1 }; /** Arrival samples kept for the sender-clock offset estimate. */ MiniPredict.OFFSET_SAMPLES = 16; MiniPredict.create = function () { return { snap: null, at: 0, lastFrame: 0, shown: Object.create(null), offsets: [], sig: null }; }; /** Cheap content signature for snapshots without a sender time. */ MiniPredict.signature = function (snapshot) { if (!snapshot || !snapshot.blocks) { return ''; } var s = String(snapshot.blocks.length); for (var i = 0; i < snapshot.blocks.length; i++) { var b = snapshot.blocks[i]; s += '|' + b.id + ':' + b.y + ':' + b.state; } return s; }; MiniPredict.fallSpeedFor = function (planet) { var ft = planet && (planet.fallTime != null ? planet.fallTime : planet.fall_time); ft = Number(ft); if (!(ft > 0)) { ft = 3; } return this.FIELD_HEIGHT / ft; }; /** * Record an authoritative snapshot. A poll can repeat the same * snapshot (the opponent has not polled since); that must not restart * the extrapolation. With a sender time `t` (ms, sender clock) the * snapshot's moment is mapped to our clock via the smallest observed * arrival offset, so a late-arriving snapshot is placed at the time it * was really taken. Returns true when the snapshot is new. */ MiniPredict.update = function (st, snapshot, now) { if (snapshot === st.snap) { return false; } if (!snapshot) { st.snap = null; st.sig = null; return false; } var hasT = snapshot.t != null && isFinite(snapshot.t); if (st.snap && hasT && st.snap.t === snapshot.t) { st.snap = snapshot; return false; } if (!hasT) { var sig = this.signature(snapshot); if (st.snap && sig === st.sig) { st.snap = snapshot; return false; } st.sig = sig; st.snap = snapshot; st.at = now; return true; } st.offsets.push(now - snapshot.t); if (st.offsets.length > this.OFFSET_SAMPLES) { st.offsets.shift(); } var off = Math.min.apply(null, st.offsets); st.snap = snapshot; st.sig = null; // Never in the future, never older than the extrapolation cap. st.at = Math.max(now - this.MAX_EXTRAP_S * 1000, Math.min(now, snapshot.t + off)); return true; }; /** * Predicted y for every falling block at time `now`, clamped above the * first non-falling block (or the floor) below it in its column, chaining * falling blocks in the same column bottom-up. Returns id → y. */ MiniPredict.predict = function (snapshot, sinceS, fallSpeed) { var out = Object.create(null); if (!snapshot || !snapshot.blocks) { return out; } var dt = Math.max(0, Math.min(this.MAX_EXTRAP_S, sinceS || 0)); var cols = Object.create(null); var blocks = snapshot.blocks; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; (cols[b.col] = cols[b.col] || []).push(b); } for (var c in cols) { var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; }); var floor = 0; // lowest y the next block may occupy for (var k = 0; k < list.length; k++) { var blk = list[k]; if (blk.state === 'falling') { var y = Math.max(floor, blk.y - fallSpeed * dt); if (y > blk.y) { y = blk.y; } // only ever predict downwards out[blk.id] = y; floor = y + 1; } else { floor = Math.max(floor, blk.y + 1); } } } return out; }; /** * Advance the shown positions to `now` and return id → display y for * falling blocks. Non-falling blocks are not in the map (draw them at * their authoritative y). */ MiniPredict.step = function (st, now, fallSpeed) { var frame = st.lastFrame ? Math.min(this.MAX_FRAME_S, Math.max(0, (now - st.lastFrame) / 1000)) : 0; st.lastFrame = now; var target = this.predict(st.snap, (now - st.at) / 1000, fallSpeed); var shown = Object.create(null); var floors = this._floors(st.snap, target); for (var id in target) { var t = target[id]; var s = st.shown[id]; if (s == null || !isFinite(s) || Math.abs(s - t) > this.SNAP_CELLS) { s = t; } else if (s > t) { // Lagging: fall at fallSpeed plus a share of the gap. s -= (fallSpeed + (s - t) / this.RECONCILE_S) * frame; if (s < t) { s = t; } } else if (s < t) { // Ran ahead: keep falling, slower, never upwards. s -= fallSpeed * this.AHEAD_SPEED_SHARE * frame; } var fl = floors[id] != null ? floors[id] : 0; if (s < fl) { s = fl; } shown[id] = s; } st.shown = shown; return shown; }; /** Floor (lowest allowed y) for each falling block given the targets. */ MiniPredict._floors = function (snapshot, target) { var out = Object.create(null); if (!snapshot || !snapshot.blocks) { return out; } var cols = Object.create(null); for (var i = 0; i < snapshot.blocks.length; i++) { var b = snapshot.blocks[i]; (cols[b.col] = cols[b.col] || []).push(b); } for (var c in cols) { var list = cols[c].slice().sort(function (a, b) { return a.y - b.y; }); var floor = 0; for (var k = 0; k < list.length; k++) { var blk = list[k]; if (blk.state === 'falling') { out[blk.id] = floor; floor = (target[blk.id] != null ? target[blk.id] : blk.y) + 1; } else { floor = Math.max(floor, blk.y + 1); } } } return out; }; if (typeof globalThis !== 'undefined') { globalThis.MiniPredict = MiniPredict; } if (typeof module !== 'undefined' && module.exports) { module.exports = MiniPredict; } /* * End File: * /workspace/meteors/src/miniPredict.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, lifetimePoints: 0, onlineAwarded: null, locale: null, localeExplicit: false, authLocale: null, blocks: [], planets: [], lobby: null, incoming: [], shotResults: [], error: '', _timer: null, _pendingShots: [], _pollInFlight: false, _flushPending: false, _lastPollAt: 0, _getPayload: null, _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 = ''; } if (data.lifetime_points != null) { this.lifetimePoints = data.lifetime_points; } if (data.online_awarded !== undefined) { this.onlineAwarded = data.online_awarded; } if (data.locale !== undefined) { this.locale = data.locale; } if (data.locale_explicit !== undefined) { this.localeExplicit = !!data.locale_explicit; } if (data.auth_locale !== undefined) { this.authLocale = data.auth_locale; } if (data.last_planet !== undefined) { this.lastPlanet = data.last_planet; } if (data.blocks) { this.blocks = data.blocks; } if (data.planets) { this.planets = data.planets; if (typeof Planet !== 'undefined' && Planet.setCustomPlanets) { Planet.setCustomPlanets(data.planets); } } if (data.lobby && data.lobby.players && typeof Planet !== 'undefined' && Planet.rememberPlanet) { for (var i = 0; i < data.lobby.players.length; i++) { if (data.lobby.players[i].planet) { Planet.rememberPlanet(data.lobby.players[i].planet); } } } }; 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 = (typeof I18n !== 'undefined' ? I18n.t('error.serverStatus', { status: res.status }) : ('De server gaf ' + res.status)); data.ok = false; } self._apply(data); return data; }, function () { var fail = { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.badResponse') : 'Geen geldig antwoord van de server.') }; self.error = fail.error; return fail; }); }).catch(function (err) { var fail = { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.connection') : '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.playBegin = function (mode) { return this.request('play_begin', { mode: mode || 'solo' }); }; Online.playFinish = function (token, score) { return this.request('play_finish', { token: token, score: score || 0 }); }; Online.savePlanet = function (planet) { return this.request('planet_save', { planet: planet }); }; Online.deletePlanet = function (id) { return this.request('planet_delete', { id: id }); }; /** Remember the last chosen planet on the profile (t1196). */ Online.setLastPlanet = function (planetId) { this.lastPlanet = planetId; return this.request('set_last_planet', { planet_id: planetId }); }; Online.setLocale = function (locale) { return this.request('set_locale', { locale: locale }); }; 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; this._pollInFlight = true; this._lastPollAt = Date.now(); return this.request('poll', body).then(function (data) { self._pollInFlight = false; if (self._flushPending) { self._flushPending = false; self.flushShotsSoon(); } 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; this._getPayload = getPayload || null; var tick = function () { var payload = getPayload ? getPayload() : {}; self.poll(payload); }; tick(); this._timer = setInterval(tick, this.POLL_MS); }; /** Minimum gap between an extra shot flush and the previous poll (ms). */ Online.FLUSH_MIN_GAP_MS = 120; /** * Pure decision for flushShotsSoon (t1181): 'now', 'later' (wait for the * in-flight poll or the min gap) or 'none' (nothing to send / not polling). */ Online.flushDecision = function (state) { if (!state || !state.polling || !(state.pending > 0)) { return 'none'; } if (state.inFlight) { return 'later'; } if (state.sinceLast < (state.minGap != null ? state.minGap : this.FLUSH_MIN_GAP_MS)) { return 'later'; } return 'now'; }; /** * Send freshly cleared shots on the next possible poll instead of up to * POLL_MS later, so the server's hit/miss result (and the retarget of the * local flight) arrives in about one round trip. Network cadence only; * the server still decides hits, targets and delivery (t1181). */ Online.flushShotsSoon = function () { var self = this; var d = this.flushDecision({ polling: !!this._timer, pending: this._pendingShots.length, inFlight: this._pollInFlight, sinceLast: Date.now() - (this._lastPollAt || 0) }); if (d === 'none') { return d; } if (d === 'later') { if (this._pollInFlight) { this._flushPending = true; } else if (!this._flushTimer) { var wait = Math.max(0, this.FLUSH_MIN_GAP_MS - (Date.now() - (this._lastPollAt || 0))); this._flushTimer = setTimeout(function () { self._flushTimer = null; self.flushShotsSoon(); }, wait); } return d; } this.poll(this._getPayload ? this._getPayload() : {}); return d; }; Online.stopPolling = function () { if (this._flushTimer) { clearTimeout(this._flushTimer); this._flushTimer = null; } this._flushPending = false; if (this._timer) { clearInterval(this._timer); this._timer = null; } }; /** Login from the Online screen: come back to online play (t1193). */ Online.loginUrl = function () { return 'auth.php?return=online'; }; /** t1247: global or friends leaderboard (GET, no CSRF). */ Online.leaderboard = function (scope) { var self = this; var url = 'api.php?action=leaderboard&scope=' + encodeURIComponent(scope === 'friends' ? 'friends' : 'global'); return fetch(url, { method: 'GET', credentials: 'same-origin', headers: this._headers(false) }).then(function (res) { return res.json().then(function (data) { data = data || {}; if (!res.ok && !data.error) { data.error = (typeof I18n !== 'undefined' ? I18n.t('error.serverStatus', { status: res.status }) : ('De server gaf ' + res.status)); data.ok = false; } return data; }, function () { return { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.badResponse') : 'Geen geldig antwoord van de server.') }; }); }).catch(function () { return { ok: false, error: (typeof I18n !== 'undefined' ? I18n.t('error.connection') : 'Geen verbinding met de server.') }; }); }; 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); var hostTag = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host'; el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (' + hostTag + ')' : ''); if (p.eliminated) { var out = (typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out'; if (p.place && typeof I18n !== 'undefined') { out += ' · ' + I18n.place(p.place); } else if (p.place) { out += ' · ' + p.place; } el.querySelector('.mini-meta').textContent = out; } else { el.querySelector('.mini-meta').textContent = (typeof I18n !== 'undefined') ? I18n.t('hud.miniPoints', { n: p.score || 0 }) : ('Points ' + (p.score || 0)); } this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet, this._predictMini(p)); } 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'; } /** * t1182: smoothed display y for an opponent's falling blocks (see * src/miniPredict.js). Returns id → y, or null without the module. */ Online._predictMini = function (p, now) { var MP = typeof MiniPredict !== 'undefined' ? MiniPredict : null; if (!MP || !p) { return null; } if (!this._miniPredict) { this._miniPredict = Object.create(null); } var st = this._miniPredict[p.id]; if (!st) { st = this._miniPredict[p.id] = MP.create(); } now = now != null ? now : (typeof performance !== 'undefined' ? performance.now() : Date.now()); MP.update(st, p.snapshot, now); if (p.eliminated) { return null; } return MP.step(st, now, MP.fallSpeedFor(p.planet)); }; Online._drawMini = function (canvas, snapshot, planet, shownY) { 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 by = (shownY && shownY[b.id] != null) ? shownY[b.id] : b.y; var y = canvas.height - (by + 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; }; /** Bounding box of the player's field in viewport pixels. */ Online.playerFieldRect = function () { var appRef = typeof app !== 'undefined' ? app : null; var canvas = appRef && appRef.scene && appRef.scene.canvas; if (canvas && canvas.getBoundingClientRect) { return canvas.getBoundingClientRect(); } if (appRef && appRef.fieldW) { return { left: appRef.fieldX, top: appRef.fieldY, right: appRef.fieldX + appRef.fieldW, bottom: appRef.fieldY + appRef.fieldH, width: appRef.fieldW, height: appRef.fieldH }; } return null; }; /** * True if (x, y) is inside the field's interior. The top edge (a few * pixels) is not interior: launch and landing may use that band. */ Online.pointInFieldInterior = function (x, y, field, slop) { if (!field) { return false; } slop = slop == null ? 6 : slop; return x > field.left + 0.5 && x < field.right - 0.5 && y > field.top + slop && y < field.bottom - 0.5; }; /** Cubic Bezier C(t), t ∈ [0, 1]. C¹ (in fact C^∞) on (0, 1) — no corners (t1134). */ Online.cubicBezier = function (p0, p1, p2, p3, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var u = 1 - t; var a = u * u * u; var b = 3 * u * u * t; var c = 3 * u * t * t; var d = t * t * t; return { x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y }; }; /** C'(t) = 3(1−t)²(P1−P0) + 6(1−t)t(P2−P1) + 3t²(P3−P2). */ Online.cubicBezierDeriv = function (p0, p1, p2, p3, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var u = 1 - t; return { x: 3 * u * u * (p1.x - p0.x) + 6 * u * t * (p2.x - p1.x) + 3 * t * t * (p3.x - p2.x), y: 3 * u * u * (p1.y - p0.y) + 6 * u * t * (p2.y - p1.y) + 3 * t * t * (p3.y - p2.y) }; }; Online.cubicBezierDeriv2 = function (p0, p1, p2, p3, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var u = 1 - t; // C''(t) = 6(1−t)(P2−2P1+P0) + 6t(P3−2P2+P1) return { x: 6 * u * (p2.x - 2 * p1.x + p0.x) + 6 * t * (p3.x - 2 * p2.x + p1.x), y: 6 * u * (p2.y - 2 * p1.y + p0.y) + 6 * t * (p3.y - 2 * p2.y + p1.y) }; }; /** Degree-5 Bézier. One polynomial ⇒ C^∞ on (0, 1) (t1138). */ Online.quinticBezier = function (pts, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var u = 1 - t; var u2 = u * u, u3 = u2 * u, u4 = u3 * u, u5 = u4 * u; var t2 = t * t, t3 = t2 * t, t4 = t3 * t, t5 = t4 * t; var b0 = u5, b1 = 5 * u4 * t, b2 = 10 * u3 * t2; var b3 = 10 * u2 * t3, b4 = 5 * u * t4, b5 = t5; return { x: b0 * pts[0].x + b1 * pts[1].x + b2 * pts[2].x + b3 * pts[3].x + b4 * pts[4].x + b5 * pts[5].x, y: b0 * pts[0].y + b1 * pts[1].y + b2 * pts[2].y + b3 * pts[3].y + b4 * pts[4].y + b5 * pts[5].y }; }; Online.quinticBezierDeriv = function (pts, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var d = []; for (var i = 0; i < 5; i++) { d.push({ x: pts[i + 1].x - pts[i].x, y: pts[i + 1].y - pts[i].y }); } var u = 1 - t; var u2 = u * u, u3 = u2 * u, u4 = u3 * u; var t2 = t * t, t3 = t2 * t, t4 = t3 * t; var b0 = u4, b1 = 4 * u3 * t, b2 = 6 * u2 * t2, b3 = 4 * u * t3, b4 = t4; return { x: 5 * (b0 * d[0].x + b1 * d[1].x + b2 * d[2].x + b3 * d[3].x + b4 * d[4].x), y: 5 * (b0 * d[0].y + b1 * d[1].y + b2 * d[2].y + b3 * d[3].y + b4 * d[4].y) }; }; Online.quinticBezierDeriv2 = function (pts, t) { if (t < 0) { t = 0; } if (t > 1) { t = 1; } var d2 = []; for (var i = 0; i < 4; i++) { d2.push({ x: pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x, y: pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y }); } var u = 1 - t; var u2 = u * u, u3 = u2 * u; var t2 = t * t, t3 = t2 * t; var b0 = u3, b1 = 3 * u2 * t, b2 = 3 * u * t2, b3 = t3; return { x: 20 * (b0 * d2[0].x + b1 * d2[1].x + b2 * d2[2].x + b3 * d2[3].x), y: 20 * (b0 * d2[0].y + b1 * d2[1].y + b2 * d2[2].y + b3 * d2[3].y) }; }; /** Signed curvature κ = (x'y'' − y'x'') / |r'|³ (independent of parametrisation). */ Online.curvature = function (d1, d2) { var sp = d1.x * d1.x + d1.y * d1.y; var den = Math.pow(sp, 1.5); if (den < 1e-12) { return 0; } return (d1.x * d2.y - d1.y * d2.x) / den; }; /** * de Casteljau evaluation of a Bézier of any degree, plus first * and second derivatives (t1138). A single polynomial is C^∞ on (0, 1). */ Online.bezierPoint = function (pts, t) { if (!pts || !pts.length) { return { x: 0, y: 0 }; } if (t < 0) { t = 0; } if (t > 1) { t = 1; } var tmp = []; var i, k, u = 1 - t; for (i = 0; i < pts.length; i++) { tmp.push({ x: pts[i].x, y: pts[i].y }); } for (k = 1; k < pts.length; k++) { for (i = 0; i < pts.length - k; i++) { tmp[i] = { x: u * tmp[i].x + t * tmp[i + 1].x, y: u * tmp[i].y + t * tmp[i + 1].y }; } } return tmp[0]; }; Online.bezierDeriv = function (pts, t) { var n = pts ? pts.length - 1 : 0; if (n < 1) { return { x: 0, y: 0 }; } var d = []; for (var i = 0; i < n; i++) { d.push({ x: n * (pts[i + 1].x - pts[i].x), y: n * (pts[i + 1].y - pts[i].y) }); } return this.bezierPoint(d, t); }; Online.bezierDeriv2 = function (pts, t) { var n = pts ? pts.length - 1 : 0; if (n < 2) { return { x: 0, y: 0 }; } var s = n * (n - 1); var d2 = []; for (var i = 0; i < n - 1; i++) { d2.push({ x: s * (pts[i + 2].x - 2 * pts[i + 1].x + pts[i].x), y: s * (pts[i + 2].y - 2 * pts[i + 1].y + pts[i].y) }); } return this.bezierPoint(d2, t); }; /** * Hermite parameter with p(0)=0, p(1)=1, p'(0)=v0, p'(1)=v1. * v0=v1=1 is linear (constant speed in t, no endpoint halt). */ Online.smoothParam = function (t, v0, v1) { if (t < 0) { return 0; } if (t > 1) { return 1; } if (v0 == null) { v0 = 1; } if (v1 == null) { v1 = 1; } var b = 3 - 2 * v0 - v1; var a = v0 + v1 - 2; return ((a * t + b) * t + v0) * t; }; /** * One continuous degree-7 Bézier: a single big, round, ballistic * arch (t1138). Vertical at the exit (heading up) and at the * landing (heading down). Horizontal travel sits on the apex, * above the field — a cluster of high control points on each * side keeps the hull out of the interior, with no straight * cruise and no quarter-turn kinks. C^∞ on (0, 1). * * Incoming (low mini → high field): the first mid controls stay * on the outside so the rise clears the top before crossing. * Outgoing (high exit → low mini): mid controls sit above the * target so the dive happens outside. Enemy→enemy (no field) * is a symmetric parabola behind the field. */ Online.makeAroundCurve = function (start, end, field, opts) { opts = opts || {}; if (!start) { start = { x: 0, y: 0 }; } if (!end) { end = { x: 0, y: 0 }; } var clearance = opts.clearance || 150; if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD) { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD); } if (clearance < 150) { clearance = 150; } var apexY; var left, right, top; if (field) { top = field.top; left = field.left; right = field.right; apexY = top - clearance; if (apexY < 8) { apexY = Math.max(8, top - Math.max(28, clearance * 0.5)); } } else { apexY = Math.min(start.y, end.y) - Math.max(56, clearance * 0.6); if (apexY < 8) { apexY = Math.min(start.y, end.y) - 40; } left = right = top = null; } function outsideX (x) { if (!field) { return x; } var pad = 40; if (x < left + 8) { return Math.min(x, left - pad); } if (x > right - 8) { return Math.max(x, right + pad); } return x; } var startLow = field && start.y > top + 8; var endLow = field && end.y > top + 8; var startInside = field && start.x > left + 8 && start.x < right - 8; var endInside = field && end.x > left + 8 && end.x < right - 8; // Incoming: rise on the outside first. Outgoing: cross at // the apex, then dive outside. Otherwise a symmetric arch. var kind; if (startLow && !endLow) { kind = 'in'; } else if (!startLow && endLow) { kind = 'out'; } else if (startLow && endLow) { kind = startInside ? 'out' : (endInside ? 'in' : 'sym'); } else { kind = 'sym'; } var sx = outsideX(start.x); var ex = outsideX(end.x); var rise = Math.max(80, Math.abs(start.y - apexY) * 0.35); var P0 = { x: start.x, y: start.y }; var P1 = { x: start.x, y: start.y - rise }; var P2, P3, P4, P5; var P6 = { x: end.x, y: apexY }; var P7 = { x: end.x, y: end.y }; if (kind === 'in') { P2 = { x: sx, y: apexY }; P3 = { x: sx, y: apexY }; P4 = { x: sx + (ex - sx) * 0.5, y: apexY }; P5 = { x: sx + (ex - sx) * 0.85, y: apexY }; } else if (kind === 'out') { P2 = { x: start.x, y: apexY }; P3 = { x: sx + (ex - sx) * 0.55, y: apexY }; P4 = { x: ex, y: apexY }; P5 = { x: end.x, y: apexY }; } else { P2 = { x: sx, y: apexY }; P3 = { x: sx + (ex - sx) * 0.35, y: apexY }; P4 = { x: sx + (ex - sx) * 0.65, y: apexY }; P5 = { x: ex, y: apexY }; } var pts = [P0, P1, P2, P3, P4, P5, P6, P7]; var curve = { degree: 7, pts: pts, p0: P0, p3: P7, apexY: apexY, kind: kind, arcLength: true }; this._buildArcLut(curve); return curve; }; Online._evalPoly = function (curve, t) { if (curve && curve.pts && curve.pts.length >= 2) { return this.bezierPoint(curve.pts, t); } if (curve && curve.p1) { return this.cubicBezier(curve.p0, curve.p1, curve.p2, curve.p3, t); } if (curve && curve.segments) { var n = curve.segments.length; var at = (t < 0 ? 0 : (t > 1 ? 1 : t)) * n; var i = Math.floor(at); if (i >= n) { i = n - 1; } var s = curve.segments[i]; return this.cubicBezier(s.p0, s.p1, s.p2, s.p3, at - i); } return { x: 0, y: 0 }; }; Online._evalPolyDeriv = function (curve, t) { if (curve && curve.pts && curve.pts.length >= 2) { return this.bezierDeriv(curve.pts, t); } if (curve && curve.p1) { return this.cubicBezierDeriv(curve.p0, curve.p1, curve.p2, curve.p3, t); } return { x: 0, y: 0 }; }; Online._evalPolyDeriv2 = function (curve, t) { if (curve && curve.pts && curve.pts.length >= 3) { return this.bezierDeriv2(curve.pts, t); } if (curve && curve.p1) { return this.cubicBezierDeriv2(curve.p0, curve.p1, curve.p2, curve.p3, t); } return { x: 0, y: 0 }; }; /** Cumulative-length LUT so u is a fraction of arc length (t1138). */ Online._buildArcLut = function (curve, steps) { steps = steps || 48; var acc = [0]; var prev = this._evalPoly(curve, 0); for (var i = 1; i <= steps; i++) { var p = this._evalPoly(curve, i / steps); acc.push(acc[i - 1] + Math.sqrt((p.x - prev.x) * (p.x - prev.x) + (p.y - prev.y) * (p.y - prev.y))); prev = p; } curve.lutS = acc; curve.lutN = steps; curve.totalLen = Math.max(acc[steps], 1); return curve; }; /** Polynomial t whose arc length fraction is u. */ Online._arcT = function (curve, u) { if (u <= 0) { return 0; } if (u >= 1) { return 1; } if (!curve.lutS) { this._buildArcLut(curve); } var s = u * curve.totalLen; var acc = curve.lutS; var n = curve.lutN; var lo = 0; var hi = n; while (lo < hi) { var mid = (lo + hi) >> 1; if (acc[mid] < s) { lo = mid + 1; } else { hi = mid; } } var i = lo; if (i <= 0) { return 0; } var s0 = acc[i - 1]; var s1 = acc[i]; var f = (s1 > s0) ? (s - s0) / (s1 - s0) : 0; return ((i - 1) + f) / n; }; Online._measureCurve = function (curve) { if (!curve) { return curve; } if (!curve.lutS) { this._buildArcLut(curve); } return curve; }; Online._segLen = function (seg, steps) { steps = steps || 10; if (seg && seg.degree === 5) { if (!seg.lutS) { this._buildArcLut(seg, steps * 4); } return seg.totalLen; } var len = 0; var prev = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, 0); for (var i = 1; i <= steps; i++) { var p = this.cubicBezier(seg.p0, seg.p1, seg.p2, seg.p3, i / steps); len += Math.sqrt((p.x - prev.x) * (p.x - prev.x) + (p.y - prev.y) * (p.y - prev.y)); prev = p; } return Math.max(len, 1); }; /** Point at arc-length fraction u ∈ [0, 1]. */ Online.curvePoint = function (curve, u) { if (!curve) { return { x: 0, y: 0 }; } var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u)); return this._evalPoly(curve, t); }; /** * dP/du under arc-length parametrisation: unit tangent × total length * (constant speed in u, direction from the polynomial). */ Online.curveDeriv = function (curve, u) { if (!curve) { return { x: 0, y: 0 }; } var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u)); var d = this._evalPolyDeriv(curve, t); if (curve.arcLength !== false) { if (!curve.lutS) { this._buildArcLut(curve); } var mag = Math.sqrt(d.x * d.x + d.y * d.y); if (mag < 1e-9) { return { x: 0, y: 0 }; } var s = curve.totalLen / mag; return { x: d.x * s, y: d.y * s }; } return d; }; Online.curveDeriv2 = function (curve, u) { if (!curve) { return { x: 0, y: 0 }; } var t = curve.arcLength !== false ? this._arcT(curve, u) : (u < 0 ? 0 : (u > 1 ? 1 : u)); return this._evalPolyDeriv2(curve, t); }; /** Curvature at arc-length fraction u (uses polynomial t, κ is invariant). */ Online.curveCurvature = function (curve, u) { var t = curve && curve.arcLength !== false ? this._arcT(curve, u) : u; return this.curvature(this._evalPolyDeriv(curve, t), this._evalPolyDeriv2(curve, t)); }; /** * Endpoint ease rates so arrival speed ≈ fallSpeed under arc-length * parametrisation: v = (L / duration) * p'(raw). */ Online.flightEaseRates = function (curve, duration, fallPx) { if (!curve || !curve.lutS) { this._measureCurve(curve); } var L = (curve && curve.totalLen) || 400; duration = duration || this.FLIGHT_DURATION; var v1 = fallPx && L ? (fallPx * duration) / L : 0.75; if (v1 < 0.28) { v1 = 0.28; } if (v1 > 1.15) { v1 = 1.15; } var v0 = v1 + 0.2; if (v0 > 1) { v0 = 1; } if (v0 < 0.45) { v0 = 0.45; } return { v0: v0, v1: v1 }; }; Online.aroundFieldPoint = function (start, end, u, field, clearance) { var opts = (clearance && typeof clearance === 'object') ? clearance : { clearance: clearance }; var curve = opts.curve || this.makeAroundCurve(start, end, field, opts); return this.curvePoint(curve, u); }; Online.waypointsAroundField = function (start, end, field, clearance) { var c = this.makeAroundCurve(start, end, field, { clearance: clearance || 100 }); if (c.pts && c.pts.length) { return c.pts.slice(); } return [c.p0, c.p1, c.p2, c.p3]; }; Online.pointOnPath = function (points, u) { // Legacy polyline; new flights use cubicBezier. u = u < 0 ? 0 : (u > 1 ? 1 : u); if (!points || !points.length) { return { x: 0, y: 0 }; } if (points.length === 4 && points[0] && points[3]) { return this.cubicBezier(points[0], points[1], points[2], points[3], u); } if (points.length === 1) { return { x: points[0].x, y: points[0].y }; } var n = points.length - 1; var at = u * n; var i = Math.floor(at); if (i >= n) { i = n - 1; } var t = at - i; var a = points[i]; var b = points[i + 1]; return { x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t }; }; /** Viewport centre of a field cell (y=0 is the bottom row). */ Online.cellViewport = function (col, y, rect) { if (!rect) { var field = this.playerFieldRect(); if (!field) { return { x: 0, y: 0 }; } rect = field; } var w = rect.width != null ? rect.width : (rect.right - rect.left); var h = rect.height != null ? rect.height : (rect.bottom - rect.top); return { x: rect.left + ((col + 0.5) / 10) * w, y: rect.top + (1 - (y + 0.5) / 13) * h }; }; /** Handoff point of an incoming garbage block: y = 13, just into the column (t1135). */ Online.fieldEntry = function (col) { return this.cellViewport(col == null ? 4.5 : col, 13); }; Online.miniCellViewport = function (playerId, col, y) { var el = this.miniElement(playerId); var canvas = el && (el.querySelector ? el.querySelector('canvas') : null); var box = canvas || el; if (!box || !box.getBoundingClientRect) { return { x: window.innerWidth / 2, y: 48 }; } return this.cellViewport(col == null ? 4.5 : col, y == null ? 13 : y, box.getBoundingClientRect()); }; Online._fallSpeedPx = function (field, duration) { var px = 40; if (field && field.height) { px = field.height / 13; } else if (typeof app !== 'undefined' && app.tile) { px = app.tile; } var cells = 13 / 3; if (typeof app !== 'undefined' && app.planet && app.planet.fallSpeed) { cells = app.planet.fallSpeed; } duration = duration || this.FLIGHT_DURATION; // Distance of P2 from P3 so C'(1)/duration ≈ fall speed (t1135). return (cells * px * duration) / 3; }; Online.rememberLandCol = function (id, col) { if (id == null || col == null || !isFinite(col)) { return; } if (!this._pendingLandCol) { this._pendingLandCol = Object.create(null); } this._pendingLandCol[String(id)] = col | 0; }; /** Resolve the landing column for an incoming shot (t1126). */ Online.takeLandCol = function (incoming) { if (!incoming) { return null; } if (incoming.land_col != null && isFinite(incoming.land_col)) { return incoming.land_col | 0; } if (!this._pendingLandCol) { return null; } var keys = []; if (incoming.id != null) { keys.push(String(incoming.id)); } if (incoming.client_id) { keys.push(String(incoming.client_id)); } for (var i = 0; i < keys.length; i++) { if (this._pendingLandCol[keys[i]] != null) { return this._pendingLandCol[keys[i]]; } } return null; }; 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.fieldEntry(col); }; /** * Animate shot results. `locals` is a map of client_id → {col, y, color, * startX, startY, from_id} in viewport pixels. * * Visual-only: a smooth cubic that leaves the real cell, arcs around * the field, and dives into the landing column at the spawn pose * (t1134 / t1135). Enemy-to-enemy arcs stay small and are drawn * behind the player's field. 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); } if (!this._previewIds) { this._previewIds = 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))); // Own shot already flying locally since the clear (t1181): // pick it up at its current pose and fly on to the real target. var cid = r.client_id != null ? String(r.client_id) : null; if (cid && this._previewIds[cid] && this._isOwnShot(r)) { var own = this._findFlight(cid); this._flightSeen[sid] = now; if (own) { this.retargetFlight(own, r, locals[cid] || {}, now); } continue; } if (this._flightSeen[sid]) { if (this._previewIds[sid]) { var existing = this._findFlight(sid); if (existing) { var meta0 = locals[r.client_id] || locals[sid] || {}; this.retargetFlight(existing, r, meta0, now); } } 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 landCol = null; if (r.land_col != null && isFinite(r.land_col)) { landCol = r.land_col | 0; } else if (meta.land_col != null && isFinite(meta.land_col)) { landCol = meta.land_col | 0; } else if (kind === 'enemy-to-player' && typeof app !== 'undefined' && app.core && app.core.pickGarbageColumn) { landCol = app.core.pickGarbageColumn(); } if (landCol != null) { this.rememberLandCol(sid, landCol); if (r.client_id) { this.rememberLandCol(r.client_id, landCol); } } var startCol = meta.col != null ? meta.col : r.col; var startY = meta.y != null ? meta.y : r.y; 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(startCol, startY); } else if (startCol != null || startY != null) { start = this.miniCellViewport(fromId, startCol, startY != null ? startY : 13); } 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.fieldEntry(landCol != null ? landCol : 4.5); } else { end = this._targetEnd(targetId, start, landCol); } // Hits are ingested as grey garbage; draw them grey (t1130). // Misses keep the sender's colour — nothing is received. var flightColor = miss ? (r.color != null ? r.color : meta.color) : -1; 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(flightColor); el.alt = ''; el.className = 'flight' + (kind === 'enemy-to-enemy' ? ' flight-behind' : ''); el.style.width = full + 'px'; el.style.height = full + 'px'; layer.appendChild(el); // A flight seen late (poll delay) still starts at the sender's // field and plays the whole arc, just a bit faster, so it lands // about when the server delivers it — never a mid-arc pop-in (t1181). var t0 = now; duration = this.lateFlightDuration(r.age, duration); var height = miss ? Math.max(40, Math.min(160, Math.abs(end.y - start.y) * 0.35)) : this.arcHeight(start, end); var field = this.playerFieldRect(); var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy'); var clearance = Math.max(150, height * 0.55); var endSpeed = this._fallSpeedPx(field, duration / 1000); var curve = miss ? null : this.makeAroundCurve(start, end, around ? field : null, { clearance: clearance }); var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null; this._flights.push({ el: el, start: start, end: end, ctrl: miss ? this._missCtrl(start, end) : null, height: height, t0: t0, duration: duration, easeRates: easeRates, spin: miss ? ((Math.random() * 2 - 1) * 720) : ((Math.random() * 2 - 1) * 120), miss: miss, kind: kind, startScale: startScale, endScale: endScale, angle: 0, id: sid, landCol: landCol, field: field, curve: curve, color: flightColor }); } this._flightLocals = {}; }; /** Shortest share of the normal flight a late-seen flight may get. */ Online.LATE_MIN_SHARE = 0.5; /** Duration (ms) for a flight first seen `age` seconds after it was fired. */ Online.lateFlightDuration = function (age, duration) { if (age == null || !isFinite(age) || age <= 0) { return duration; } return Math.max(duration * this.LATE_MIN_SHARE, duration - age * 1000); }; /** Remaining duration (ms) after a local preview has flown `elapsedMs`. */ Online.retargetDuration = function (elapsedMs, duration) { if (!(elapsedMs > 0)) { return duration; } return Math.max(duration * this.LATE_MIN_SHARE, duration - elapsedMs); }; Online._isOwnShot = function (r) { var mine = this.me && this.me.id; var from = r.from_id || r.from_user || null; return !from || (mine != null && String(from) === String(mine)); }; /** * Sender side (t1181): start the flight the moment the block leaves the * field, before any server round trip. It rises out of the exit cell; * the poll answer retargets it (hit → opponent mini, miss → off-screen). */ Online.startLocalShot = function (shot, start) { if (!shot || !start) { return null; } return this.previewExit({ id: shot.id, col: shot.col, y: shot.y, vy: shot.vy, color: shot.color, start: start, from_id: null }); }; 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, land_col: shot.land_col, vy: shot.vy }; }; Online._flightStart = function (col, y) { if (y == null || !isFinite(y)) { y = 13; } return this.cellViewport(col == null ? 4.5 : col, y); }; Online._targetEnd = function (targetId, start, col) { var el = targetId && this.miniElement(targetId); if (el) { // Slightly inside the mini, in the landing column (t1135). return this.miniCellViewport(targetId, col, 12); } 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._findFlight = function (sid) { sid = String(sid); if (!this._flights) { return null; } for (var i = 0; i < this._flights.length; i++) { if (String(this._flights[i].id) === sid) { return this._flights[i]; } } return null; }; /** * True once a block has really left the field, matching cullOffTop * (y ≥ height, default 13). Used so an arc never starts for a * rocket that only peaked near the top and fell back (t1137). */ Online.EXIT_Y = 13; Online.hasLeftTheField = function (y, height) { height = height == null ? this.EXIT_Y : height; return y != null && isFinite(y) && y >= height - 1e-9; }; /** * Start a flight only at the true exit (y ≥ 13). Callers that pass * a rocket still on the field are ignored, so a fallback never * shows a phantom arc (t1137). The start pose is the exit cell, * continuing upward; retargetFlight aims it at the real target * if a preview was used in the same frame as cull. */ Online.previewExit = function (info) { if (!info || info.id == null) { return null; } if (!this.hasLeftTheField(info.y)) { return null; } var sid = String(info.id); if (!this._flights) { this._flights = []; } if (!this._flightSeen) { this._flightSeen = Object.create(null); } if (!this._previewIds) { this._previewIds = Object.create(null); } if (this._previewIds[sid] || this._flightSeen[sid]) { return; } var front = document.getElementById('flights'); if (!front || !info.start) { return; } var start = info.start; var field = this.playerFieldRect(); var clearance = 80; if (typeof MiniLayout !== 'undefined' && MiniLayout.ARC_TOP_PAD) { clearance = Math.max(clearance, MiniLayout.ARC_TOP_PAD * 0.7); } var apexY = (field ? field.top : start.y) - clearance; if (apexY < 8) { apexY = Math.max(8, start.y - 80); } var end = { x: start.x, y: apexY }; var duration = this.FLIGHT_DURATION * 1000; var full = this._fullTileSize(); var el = document.createElement('img'); el.src = colorSpriteUrl(info.color); el.alt = ''; el.className = 'flight'; el.style.width = full + 'px'; el.style.height = full + 'px'; front.appendChild(el); var endSpeed = this._fallSpeedPx(field, this.FLIGHT_DURATION); var curve = this.makeAroundCurve(start, end, info.from_id ? null : field, { clearance: clearance }); var easeRates = this.flightEaseRates(curve, this.FLIGHT_DURATION, endSpeed); var now = performance.now(); var mini = info.from_id ? (this._miniCellSize(info.from_id) / full) : 1; if (mini < 0.12) { mini = 0.2; } this._flights.push({ el: el, start: start, end: end, ctrl: null, height: clearance, t0: now, duration: duration, spin: (Math.random() * 2 - 1) * 90, miss: false, kind: info.from_id ? 'enemy-to-enemy' : 'player-to-enemy', startScale: mini, endScale: mini, angle: 0, id: sid, landCol: null, field: field, curve: curve, easeRates: easeRates, preview: true, color: info.color, from_id: info.from_id || null }); this._previewIds[sid] = true; this._flightSeen[sid] = now; return true; }; /** True while a field sprite should stay hidden — the flight is its visual. */ Online.hasExitVisual = function (id) { if (id == null) { return false; } var sid = String(id); if (this._previewIds && this._previewIds[sid]) { return true; } var f = this._findFlight(sid); if (!f || f.miss) { return false; } var raw = (performance.now() - f.t0) / f.duration; return raw < 0.4; }; /** * Once the shot is scored, pick up the preview at its current pose * and fly the rest of the way to the real end (no jump). */ Online.retargetFlight = function (f, r, meta, now) { now = now || performance.now(); meta = meta || {}; var raw = (now - f.t0) / f.duration; if (raw < 0) { raw = 0; } if (raw > 0.95) { raw = 0.95; } var u = this.smoothParam(raw, 0.9, 0.9); var pt = f.curve ? this.curvePoint(f.curve, u) : { x: f.start.x, y: f.start.y }; var curScale = f.startScale + (f.endScale - f.startScale) * u; var fromId = r.from_id || r.from_user || meta.from_id || f.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 (f.preview) { duration = this.retargetDuration(now - f.t0, duration); } var landCol = null; if (r.land_col != null && isFinite(r.land_col)) { landCol = r.land_col | 0; } else if (meta.land_col != null && isFinite(meta.land_col)) { landCol = meta.land_col | 0; } else if (f.landCol != null) { landCol = f.landCol; } if (landCol != null) { this.rememberLandCol(String(f.id), landCol); } var end; if (miss) { end = this._missEnd(pt, kind === 'enemy-miss'); } else if (kind === 'enemy-to-player') { end = this.fieldEntry(landCol != null ? landCol : 4.5); } else { end = this._targetEnd(targetId, pt, landCol); } var flightColor = miss ? (r.color != null ? r.color : meta.color) : -1; if (f.el && flightColor !== f.color) { f.el.src = colorSpriteUrl(flightColor); } var full = this._fullTileSize(); var mini = this._miniCellSize(fromId || targetId) / full; if (mini < 0.12) { mini = 0.2; } var endScale; if (kind === 'player-to-enemy') { endScale = mini; } else if (kind === 'enemy-to-player') { endScale = 1; } else if (kind === 'enemy-to-enemy') { endScale = mini; } else { endScale = 0; } var field = this.playerFieldRect(); var around = !miss && (kind === 'enemy-to-player' || kind === 'player-to-enemy'); var height = miss ? Math.max(40, Math.min(160, Math.abs(end.y - pt.y) * 0.35)) : this.arcHeight(pt, end); var clearance = Math.max(150, height * 0.55); var endSpeed = this._fallSpeedPx(field, duration / 1000); var curve = miss ? null : this.makeAroundCurve(pt, end, around ? field : null, { clearance: clearance }); var easeRates = curve ? this.flightEaseRates(curve, duration / 1000, endSpeed) : null; f.start = pt; f.end = end; f.t0 = now; f.duration = duration; f.curve = curve; f.easeRates = easeRates; f.ctrl = miss ? this._missCtrl(pt, end) : null; f.height = height; f.miss = miss; f.kind = kind; f.startScale = curScale; f.endScale = endScale; f.landCol = landCol; f.field = field; f.preview = false; f.color = flightColor; f.from_id = fromId; if (this._previewIds) { delete this._previewIds[String(f.id)]; } if (kind === 'enemy-to-enemy' && f.el) { var back = document.getElementById('flights-back'); if (back && f.el.parentNode !== back) { f.el.className = 'flight flight-behind'; back.appendChild(f.el); } } }; /** Point and (optional) derivative of a flight at parameter u. */ Online.flightPointAt = function (f, u) { if (!f) { return { x: 0, y: 0 }; } if (f.curve) { return this.curvePoint(f.curve, u); } if (f.miss && f.ctrl) { var e = u; var mt = 1 - e; return { 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 }; } return this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45); }; Online.pointAllowedOnArc = function (p, field, start, end, slop) { if (!this.pointInFieldInterior(p.x, p.y, field, slop)) { return true; } if (!field) { return true; } var w = (field.right - field.left) / 10; var corridor = w * 0.7; if (start && Math.abs(p.x - start.x) <= corridor) { return true; } if (end && Math.abs(p.x - end.x) <= corridor) { return true; } return false; }; /** How long a local preview may wait at its apex for the server (ms). */ Online.PREVIEW_HOLD_MS = 2500; 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 (f.preview && raw >= 0.999 && now - f.t0 < f.duration + this.PREVIEW_HOLD_MS) { raw = 0.999; } if (raw >= 1) { if (f.el && f.el.parentNode) { f.el.parentNode.removeChild(f.el); } if (this._previewIds) { delete this._previewIds[String(f.id)]; } continue; } if (raw < 0) { raw = 0; } // Non-zero endpoint speed so the handoff matches fallSpeed (t1135/t1138). var v0 = (f.easeRates && f.easeRates.v0 != null) ? f.easeRates.v0 : 0.85; var v1 = (f.easeRates && f.easeRates.v1 != null) ? f.easeRates.v1 : 0.85; var u = f.miss ? this.easeInOutCubic(raw) : this.smoothParam(raw, v0, v1); 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 if (f.curve) { var pt = this.curvePoint(f.curve, u); x = pt.x; y = pt.y; } else { var pt = this.aroundFieldPoint(f.start, f.end, u, f.field, (f.height || 80) * 0.45); 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); this._pendingLandCol = Object.create(null); this._previewIds = Object.create(null); this._miniPredict = Object.create(null); }; /** * Totals for the end-of-match reward (t1173 / t1278). Prefers the * server's online_awarded (same shape as play_finish: after − awarded) * so a rematch or a stringy payload still starts the tally. Falls back * to the snapshot taken at match start. */ Online.rewardResult = function (opts) { opts = opts || {}; var after = Number(opts.lifetimePoints); if (!isFinite(after)) { return null; } after = Math.max(0, Math.floor(after)); if (opts.awarded != null && opts.awarded !== '') { var awarded = Number(opts.awarded); if (isFinite(awarded)) { awarded = Math.max(0, Math.floor(awarded)); return { before: Math.max(0, after - awarded), after: after }; } } var before = Number(opts.before); if (!isFinite(before)) { before = after; } before = Math.max(0, Math.floor(before)); if (before > after) { before = after; } return { before: before, after: after }; }; 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; } /** * Max board evaluations (apply + hasMatch + undo) for a depth-2 search * in one AI tick. A 10×13 field with typical stacks stays well under this. */ var PLAN_BUDGET = 4000; /** Skill at or below this: never start a 2-step setup (early rounds). */ var LOOKAHEAD_START = 0.10; /** Skill at or above this: always look for a 2-step setup when no immediate match. */ var LOOKAHEAD_FULL = 0.40; /** * Probability of searching a 2-step setup after a successful roll * that found no immediate match. 0 through 10% skill (rondes 1–6), * then linear up to 1 at 40% skill (ronde 36). */ function lookaheadChance (skill) { skill = Number(skill) || 0; if (skill <= LOOKAHEAD_START) { return 0; } if (skill >= LOOKAHEAD_FULL) { return 1; } return (skill - LOOKAHEAD_START) / (LOOKAHEAD_FULL - LOOKAHEAD_START); } function copyMove (m) { return { col: m.col, fromY: m.fromY, toY: m.toY, dist: m.dist, blockId: m.blockId }; } function movesEqual (a, b) { return a && b && a.col === b.col && a.fromY === b.fromY && a.toY === b.toY; } function betterImmediate (cand, best) { if (!best) { return true; } if (cand.dist !== best.dist) { return cand.dist < best.dist; } if (cand.col !== best.col) { return cand.col < best.col; } if (cand.fromY !== best.fromY) { return cand.fromY < best.fromY; } return cand.toY < best.toY; } function betterPlan (cand, best) { if (!best) { return true; } if (cand.total !== best.total) { return cand.total < best.total; } var a0 = cand.steps[0]; var b0 = best.steps[0]; if (a0.dist !== b0.dist) { return a0.dist < b0.dist; } if (a0.col !== b0.col || a0.fromY !== b0.fromY || a0.toY !== b0.toY) { return betterImmediate(a0, b0); } return betterImmediate(cand.steps[1], best.steps[1]); } /** * Legal vertical swaps from a colour grid: contiguous non-null cells * in a column (gaps break a segment, same as swapToward). */ function listMovesFromGrid (grid, width, height) { var moves = []; for (var col = 0; col < width; col++) { var start = -1; for (var r = 0; r <= height; r++) { var filled = r < height && grid[col][r] != null; if (filled) { if (start < 0) { start = r; } } else if (start >= 0) { var end = r; if (end - start >= 2) { for (var i = start; i < end; i++) { for (var j = start; j < end; j++) { if (i === j) { continue; } moves.push({ col: col, fromY: i, toY: j, dist: Math.abs(j - i), blockId: null }); } } } start = -1; } } } return moves; } function listMovesFromCore (core) { var moves = []; 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); moves.push({ col: col, fromY: fromY, toY: toY, dist: Math.abs(toY - fromY), blockId: seg[i].id }); } } } } return moves; } /** * A 2-step setup: first swap creates no match, second swap does. * Prefers smaller total distance, then shorter first step, then the * same column / fromY / toY ties as findBotMove. First moves come * from the live core (legal segments only). Budget-capped. */ function findSetupPlan (core, budget) { if (!core) { return null; } var width = core.width; var height = core.height; var grid = snapshotGrid(core); if (hasMatch(grid, width, height)) { return null; } budget = budget == null ? PLAN_BUDGET : budget; var firstMoves = listMovesFromCore(core); firstMoves.sort(function (a, b) { if (a.dist !== b.dist) { return a.dist - b.dist; } if (a.col !== b.col) { return a.col - b.col; } if (a.fromY !== b.fromY) { return a.fromY - b.fromY; } return a.toY - b.toY; }); var best = null; var evals = 0; for (var i = 0; i < firstMoves.length; i++) { var first = firstMoves[i]; if (best && first.dist + 1 > best.total) { break; } applyColumnMove(grid, first.col, first.fromY, first.toY); if (hasMatch(grid, width, height)) { applyColumnMove(grid, first.col, first.toY, first.fromY); continue; } var seconds = listMovesFromGrid(grid, width, height); for (var j = 0; j < seconds.length; j++) { var second = seconds[j]; var total = first.dist + second.dist; if (best && total > best.total) { continue; } if (evals++ >= budget) { break; } applyColumnMove(grid, second.col, second.fromY, second.toY); var ok = hasMatch(grid, width, height); applyColumnMove(grid, second.col, second.toY, second.fromY); if (!ok) { continue; } var cand = { steps: [copyMove(first), copyMove(second)], total: total }; if (betterPlan(cand, best)) { best = cand; } } applyColumnMove(grid, first.col, first.toY, first.fromY); if (evals >= budget) { break; } // 1+1 is the shortest possible setup; firstMoves is sorted so // the first such plan is already the tie-break winner. if (best && best.total === 2) { break; } } return best; } /** * True when `step` is still a legal vertical swap on this core, and * (when mustMatch) would create a 3+ match. */ function stepIsValid (core, step, mustMatch) { if (!core || !step) { return false; } var moves = listMovesFromCore(core); var found = null; for (var i = 0; i < moves.length; i++) { if (movesEqual(moves[i], step)) { found = moves[i]; break; } } if (!found) { return false; } step.blockId = found.blockId; if (!mustMatch) { return true; } var grid = snapshotGrid(core); applyColumnMove(grid, step.col, step.fromY, step.toY); return hasMatch(grid, core.width, core.height); } /** * 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. * `memory` is an optional object that stores a 2-step plan across ticks * (`memory.plan`). On a later successful roll the bot follows the * remaining step if it is still legal and still makes a match; otherwise * it re-plans. */ function tryBotRoll (core, skill, rng, memory) { rng = rng || Math.random; var roll = rng(); if (!(roll < skill)) { return { rolled: true, success: false, moved: false, roll: roll, move: null }; } var grid = snapshotGrid(core); if (hasMatch(grid, core.width, core.height)) { if (memory) { memory.plan = null; } return { rolled: true, success: true, moved: false, roll: roll, move: null }; } if (memory && memory.plan && memory.plan.steps && memory.plan.index < memory.plan.steps.length) { var step = memory.plan.steps[memory.plan.index]; var last = memory.plan.index === memory.plan.steps.length - 1; if (stepIsValid(core, step, last)) { var followed = executeBotMove(core, step); if (followed) { memory.plan.index++; if (memory.plan.index >= memory.plan.steps.length) { memory.plan = null; } return { rolled: true, success: true, moved: true, roll: roll, move: step, followed: true }; } } memory.plan = null; } var move = findBotMove(core); if (move) { if (memory) { memory.plan = null; } var ok = executeBotMove(core, move); return { rolled: true, success: true, moved: !!ok, roll: roll, move: move }; } var chance = lookaheadChance(skill); if (chance <= 0 || !(rng() < chance)) { return { rolled: true, success: true, moved: false, roll: roll, move: null }; } var plan = findSetupPlan(core); if (!plan || !plan.steps || !plan.steps[0]) { return { rolled: true, success: true, moved: false, roll: roll, move: null }; } var first = plan.steps[0]; var started = executeBotMove(core, first); if (started && memory) { memory.plan = { steps: plan.steps, index: 1, total: plan.total }; } else if (memory) { memory.plan = null; } return { rolled: true, success: true, moved: !!started, roll: roll, move: first, planned: true, plan: plan }; } 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'; /** Opponents knocked out over all rounds of this battle (t1198). */ this.defeated = 0; this._initBots(); } /** Mark a bot as out once; counts towards `defeated` (t1198). */ OfflineBattle.prototype._eliminate = function (bot) { if (bot.eliminated) { return; } bot.eliminated = true; bot.score = bot.core ? bot.core.score : bot.score; this.defeated += 1; }; 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, plan: null }); } }; 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 landCol = null; if (!miss && target && target.core && target.core.pickGarbageColumn) { landCol = target.core.pickGarbageColumn(); } 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, land_col: landCol }; this.flightResults.push(result); this.shotLocals.push({ client_id: clientId, col: shot.col, y: shot.y, color: shot.color, from_id: fromId, land_col: landCol }); if (!miss && target) { this.pending.push({ at: this.clock + FLIGHT_DURATION, targetId: target.id, color: shot.color, fromId: fromId, landCol: landCol }); } } }; 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(ev.landCol); } } 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') { this._eliminate(bot); 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, bot); } } } 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._eliminate(this.bots[i]); } } 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, findSetupPlan: findSetupPlan, tryBotRoll: tryBotRoll, executeBotMove: executeBotMove, stepIsValid: stepIsValid, lookaheadChance: lookaheadChance, listMovesFromCore: listMovesFromCore, listMovesFromGrid: listMovesFromGrid, PLAN_BUDGET: PLAN_BUDGET, LOOKAHEAD_START: LOOKAHEAD_START, LOOKAHEAD_FULL: LOOKAHEAD_FULL, 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/reward.js */ /* * End-of-round reward screen (t1173 / t1174). * * Logged-in only. Sequence: a centred "You won!" / "You lost..." for * INTRO seconds, then it tweens to the top (RISE seconds). Once the * server has confirmed the new profile total, blocks of the player's * planet arc from the top of the screen into a counter at the bottom * centre, one block per newly earned point. Each arrival adds 1. * * Spawn rate (t1194): starts at RATE0 = 3 blocks/s and accelerates * linearly, rate(t) = RATE0 + a·t, with `a` chosen per reward so the last * block always leaves at SPAWN_END = 4 s, whatever the point count. * Blocks spawned after t seconds: N(t) = RATE0·t + a·t²/2; block i * (0-based) leaves at T(i) = the t where N(t) = i. The last block is * i = n − 1, so N(4) = n − 1 → a = 2·((n − 1) − RATE0·T) / T². * If n − 1 ≤ RATE0·T (n ≤ 13) a would be ≤ 0: then a constant rate * (n − 1) / T is used (a = 0), so it still ends at 4 s (1 point: one * block at t = 0). * * The pure timing / sequencing part (Reward.spawnTime, Reward.createSequence) * has no DOM and is unit-tested. Reward.play wires it to an overlay. */ (function (root) { 'use strict'; /** Blocks per second at t = 0 (t1177: 10, t1178: 15, t1194: 3). */ var RATE0 = 3; /** Seconds after the first block when the last block leaves (t1194). */ var SPAWN_END = 4; var INTRO = 1.0; // centred title before it rises var RISE = 0.6; // title tween to the top var FLIGHT = 0.7; // one block's arc duration var HOLD = 1.5; // final total shown before continuing var HOLD_ZERO = 1.5; // earned 0: show the number briefly var WAIT_MAX = 8; // give up waiting for the server after this /** * Spawn parameters for a reward of n blocks (t1194): { r0, a } with * rate(t) = r0 + a·t and the last block (i = n − 1) leaving at SPAWN_END. */ function spawnParams (n) { var T = SPAWN_END; var last = Math.max(0, (n | 0) - 1); if (last <= RATE0 * T) { return { r0: last / T, a: 0 }; } return { r0: RATE0, a: 2 * (last - RATE0 * T) / (T * T) }; } /** Seconds after the start of counting when block i (0-based) of n leaves. */ function spawnTime (i, n) { if (!(i > 0)) { return 0; } var p = spawnParams(n == null ? i + 1 : n); if (p.a === 0) { return p.r0 > 0 ? i / p.r0 : 0; } return (-p.r0 + Math.sqrt(p.r0 * p.r0 + 2 * p.a * i)) / p.a; } /** Blocks spawned (left the top) by time t, capped at n. */ function spawnedBy (t, n) { if (!(t >= 0) || !(n > 0)) { return 0; } var p = spawnParams(n); // Block i has left when T(i) <= t, i.e. i <= N(t). var k = Math.floor(p.r0 * t + p.a * t * t / 2 + 1e-9) + 1; return Math.min(n, Math.max(0, k)); } /** Blocks that have arrived in the counter by time t. */ function arrivedBy (t, n, flight) { flight = flight == null ? FLIGHT : flight; return spawnedBy(t - flight, n); } /** Total seconds from the first spawn until the last block arrives. */ function countDuration (n, flight) { flight = flight == null ? FLIGHT : flight; if (!(n > 0)) { return 0; } return spawnTime(n - 1, n) + flight; } /** * A pure, dt-driven sequence. Phases: intro → rise → wait → count → * hold → done. `setResult({ before, after })` supplies the confirmed * totals (earned = after − before, never negative); `setResult(null)` * means the server did not confirm, so nothing is counted and the * title is held briefly. tick(dt) returns * { phase, counter, spawn: [indices], arrived, done }. */ function createSequence (opts) { opts = opts || {}; var s = { phase: 'intro', t: 0, // time inside the current phase countT: 0, won: !!opts.won, flight: opts.flight == null ? FLIGHT : opts.flight, intro: opts.intro == null ? INTRO : opts.intro, rise: opts.rise == null ? RISE : opts.rise, hold: opts.hold == null ? HOLD : opts.hold, holdZero: opts.holdZero == null ? HOLD_ZERO : opts.holdZero, waitMax: opts.waitMax == null ? WAIT_MAX : opts.waitMax, hasResult: false, failed: false, before: 0, after: 0, earned: 0, spawned: 0, arrived: 0, counter: 0 }; function toCount (v) { var n = Number(v); if (!isFinite(n)) { return null; } return Math.max(0, Math.floor(n)); } s.setResult = function (res) { if (s.hasResult) { return; } s.hasResult = true; if (!res) { s.failed = true; return; } var after = toCount(res.after); if (after == null) { s.failed = true; return; } var before = (res.before != null && res.before !== '') ? toCount(res.before) : after; if (before == null) { before = after; } if (before > after) { before = after; } s.before = before; s.after = after; s.earned = after - before; s.counter = before; }; s.finish = function () { if (s.phase !== 'hold') { return false; } s.phase = 'done'; return true; }; function enter (phase) { s.phase = phase; s.t = 0; } s.tick = function (dt) { var out = { phase: s.phase, counter: s.counter, spawn: [], arrived: 0, done: false }; if (s.phase === 'done') { out.done = true; return out; } dt = Math.max(0, Number(dt) || 0); var left = dt; // Allow several phase changes inside one large dt. for (var guard = 0; guard < 8 && left >= 0; guard++) { if (s.phase === 'intro') { if (s.t + left < s.intro) { s.t += left; left = -1; break; } left -= (s.intro - s.t); enter('rise'); } else if (s.phase === 'rise') { if (s.t + left < s.rise) { s.t += left; left = -1; break; } left -= (s.rise - s.t); enter('wait'); } else if (s.phase === 'wait') { if (!s.hasResult) { s.t += left; if (s.t >= s.waitMax) { s.hasResult = true; s.failed = true; enter('hold'); continue; } left = -1; break; } if (s.failed || s.earned <= 0) { enter('hold'); continue; } enter('count'); s.countT = 0; } else if (s.phase === 'count') { s.countT += left; left = -1; var sp = spawnedBy(s.countT, s.earned); for (var i = s.spawned; i < sp; i++) { out.spawn.push(i); } s.spawned = sp; var ar = arrivedBy(s.countT, s.earned, s.flight); out.arrived = ar - s.arrived; s.arrived = ar; s.counter = s.before + ar; if (ar >= s.earned) { s.counter = s.after; enter('hold'); } break; } else if (s.phase === 'hold') { var need = (s.failed || s.earned <= 0) ? s.holdZero : s.hold; if (s.t + left < need) { s.t += left; left = -1; break; } enter('done'); break; } else { break; } } out.phase = s.phase; out.counter = s.counter; out.done = s.phase === 'done'; return out; }; return s; } /* ---------------- DOM / canvas player (browser only) ---------------- */ var active = null; function reducedMotion () { try { return !!(root.matchMedia && root.matchMedia('(prefers-reduced-motion: reduce)').matches); } catch (e) { return false; } } function tr (key, fallback) { if (typeof I18n !== 'undefined' && I18n.t) { var v = I18n.t(key); if (v && v !== key) { return v; } } return fallback; } function planetImages (planet) { var list = []; var colors = (planet && planet.colors) || []; for (var i = 0; i < colors.length; i++) { if (!colors[i] || !colors[i].image) { continue; } var img = new Image(); img.decoding = 'async'; img.src = colors[i].image; list.push({ img: img, hex: colors[i].hex || '#ffffff' }); } if (!list.length) { list.push({ img: null, hex: '#ffffff' }); } return list; } /** * Show the reward overlay. opts: { won, planet, result: Promise<{before, * after}|null>, onDone }. Returns a handle with .active and .cancel(). */ function play (opts) { opts = opts || {}; if (active) { active.cancel(); } var doc = root.document; var overlay = doc.getElementById('reward'); var title = doc.getElementById('reward-title'); var counter = doc.getElementById('reward-total'); var label = doc.getElementById('reward-label'); var canvas = doc.getElementById('reward-canvas'); var hint = doc.getElementById('reward-hint'); if (!overlay || !title || !counter || !canvas) { if (opts.onDone) { opts.onDone(); } return null; } var still = reducedMotion(); var seq = createSequence({ won: opts.won, rise: still ? 0 : RISE }); var imgs = planetImages(opts.planet); var flying = []; var last = 0; var raf = 0; var pop = 0; var ctx = canvas.getContext('2d'); var dpr = Math.min(2, root.devicePixelRatio || 1); var W = 0; var H = 0; // t1193: quitting via the in-game menu shows a neutral title. title.textContent = opts.title ? String(opts.title) : (opts.won ? tr('reward.won', 'You won!') : tr('reward.lost', 'You lost...')); title.className = 'reward-title' + (opts.title ? ' ended' : (opts.won ? ' won' : ' lost')); if (label) { label.textContent = tr('reward.total', 'Total points'); } counter.textContent = ''; counter.parentNode.hidden = true; if (hint) { hint.hidden = true; hint.textContent = tr('reward.continue', 'Tap to continue'); } overlay.classList.toggle('reduced', still); overlay.hidden = false; function resize () { W = root.innerWidth || 360; H = root.innerHeight || 640; canvas.width = Math.round(W * dpr); canvas.height = Math.round(H * dpr); canvas.style.width = W + 'px'; canvas.style.height = H + 'px'; if (ctx) { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); } } resize(); root.addEventListener('resize', resize); function target () { var r = counter.getBoundingClientRect(); if (r.width > 0) { return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; } return { x: W / 2, y: H - 80 }; } function spawn () { var size = Math.max(28, Math.min(56, Math.round(Math.min(W, H) * 0.075))); var sx = size + Math.random() * Math.max(1, W - 2 * size); var sy = -size; var tg = target(); // Random arc: control point pushed sideways and up. var mx = (sx + tg.x) / 2 + (Math.random() - 0.5) * W * 0.9; var my = Math.min(sy, tg.y) + (Math.random() * 0.5) * H; flying.push({ t: 0, sx: sx, sy: sy, cx: mx, cy: my, pick: imgs[Math.floor(Math.random() * imgs.length)], size: size, rot: (Math.random() - 0.5) * 6 }); } function draw (dt) { if (!ctx) { return; } ctx.clearRect(0, 0, W, H); var tg = target(); for (var i = flying.length - 1; i >= 0; i--) { var f = flying[i]; f.t += dt / FLIGHT; if (f.t >= 1) { flying.splice(i, 1); continue; } var u = f.t; // Ease in a little so blocks accelerate into the counter. var e = u * u * (3 - 2 * u) * 0.35 + u * 0.65; var a = 1 - e; var x = a * a * f.sx + 2 * a * e * f.cx + e * e * tg.x; var y = a * a * f.sy + 2 * a * e * f.cy + e * e * tg.y; var s = f.size * (1 - 0.45 * e); ctx.save(); ctx.translate(x, y); ctx.rotate(f.rot * e); if (f.pick.img && f.pick.img.complete && f.pick.img.naturalWidth) { ctx.drawImage(f.pick.img, -s / 2, -s / 2, s, s); } else { ctx.fillStyle = f.pick.hex; ctx.fillRect(-s / 2, -s / 2, s, s); } ctx.restore(); } } function setCounter (v) { counter.textContent = String(v); } var handle = { active: true, seq: seq, flyingCount: function () { return flying.length; }, cancel: function () { cleanup(false); } }; function onTap (e) { if (seq.phase !== 'hold') { return; } if (e && e.type === 'keydown' && e.key !== ' ' && e.key !== 'Enter' && e.key !== 'Spacebar') { return; } if (e && e.preventDefault) { e.preventDefault(); } seq.finish(); } overlay.addEventListener('pointerup', onTap); doc.addEventListener('keydown', onTap); function cleanup (callDone) { if (!handle.active) { return; } handle.active = false; if (raf && root.cancelAnimationFrame) { root.cancelAnimationFrame(raf); } root.removeEventListener('resize', resize); overlay.removeEventListener('pointerup', onTap); doc.removeEventListener('keydown', onTap); overlay.hidden = true; overlay.classList.remove('risen'); if (ctx) { ctx.clearRect(0, 0, W, H); } if (active === handle) { active = null; } if (callDone && opts.onDone) { opts.onDone(); } } Promise.resolve(opts.result).then(function (res) { seq.setResult(res); }, function () { seq.setResult(null); }); function frame (now) { if (!handle.active) { return; } var dt = last ? Math.min(0.1, (now - last) / 1000) : 0; last = now; var prev = seq.phase; var out = seq.tick(dt); if (prev === 'intro' && out.phase !== 'intro') { overlay.classList.add('risen'); } if ((out.phase === 'count' || out.phase === 'hold' || out.phase === 'done') && counter.parentNode.hidden && seq.hasResult && !seq.failed) { counter.parentNode.hidden = false; setCounter(seq.before); } if (!still) { for (var i = 0; i < out.spawn.length; i++) { spawn(); } } if (out.arrived > 0) { pop = 1; setCounter(out.counter); } if (out.phase === 'hold' && !seq.failed) { setCounter(seq.after); } if (out.phase === 'hold' && hint && hint.hidden) { hint.hidden = false; } if (pop > 0) { pop = Math.max(0, pop - dt * 6); counter.style.transform = 'scale(' + (1 + 0.18 * pop).toFixed(3) + ')'; } draw(dt); if (out.done) { cleanup(true); return; } raf = root.requestAnimationFrame(frame); } raf = root.requestAnimationFrame(frame); active = handle; return handle; } var Reward = { RATE0: RATE0, SPAWN_END: SPAWN_END, spawnParams: spawnParams, INTRO: INTRO, RISE: RISE, FLIGHT: FLIGHT, HOLD: HOLD, HOLD_ZERO: HOLD_ZERO, WAIT_MAX: WAIT_MAX, spawnTime: spawnTime, spawnedBy: spawnedBy, arrivedBy: arrivedBy, countDuration: countDuration, createSequence: createSequence, play: play, isActive: function () { return !!(active && active.active); }, /** Read-only snapshot for tests and debugging. */ debugState: function () { if (!active) { return null; } var q = active.seq; return { phase: q.phase, counter: q.counter, before: q.before, after: q.after, earned: q.earned, spawned: q.spawned, arrived: q.arrived, failed: q.failed, won: q.won, flying: active.flyingCount() }; } }; if (typeof module !== 'undefined' && module.exports) { module.exports = Reward; } root.Reward = Reward; })(typeof globalThis !== 'undefined' ? globalThis : this); /* * End File: * /workspace/meteors/src/reward.js */ /* * Start File: * /workspace/meteors/src/designer.js */ 'use strict'; /** * Planeetontwerper (t1139). Only available on the main menu when the * player is logged in. Talks to api.php through Online. */ var Designer = { openSlot: 0, editingId: null, slots: [null, null, null, null, null], dirty: false }; Designer._blocks = function () { if (typeof Blocks !== 'undefined') { return Blocks; } if (typeof require !== 'undefined') { try { return require('./blocks.js'); } catch (e) { return null; } } return null; }; Designer.defaultSlots = function () { var B = Designer._blocks(); var all = B ? B.all() : []; var ids = []; for (var i = 0; i < 5 && i < all.length; i++) { ids.push(all[i].id); } return ids; }; Designer.points = function () { return (typeof Online !== 'undefined' && Online.lifetimePoints) || 0; }; Designer.blocks = function () { if (typeof Online !== 'undefined' && Online.blocks && Online.blocks.length) { return Online.blocks; } var B = Designer._blocks(); if (B) { return B.present(Designer.points()); } return []; }; Designer.planets = function () { if (typeof Planet !== 'undefined' && Planet.customPlanets) { return Planet.customPlanets(); } return (typeof Online !== 'undefined' && Online.planets) || []; }; Designer.openList = function () { if (typeof Online === 'undefined' || !Online.me) { return; } if (typeof app !== 'undefined') { app.mode = 'designer'; } hideIf('menu'); hideIf('planet-select'); hideIf('online-panel'); hideIf('designer-edit'); showIf('designer'); Designer.renderList(); }; Designer.close = function () { hideIf('designer'); hideIf('designer-edit'); Designer.closeModal(); if (typeof app !== 'undefined') { app.mode = 'menu'; } showIf('menu'); if (typeof refreshMenuAccount === 'function') { refreshMenuAccount(); } if (typeof renderPlanetGrid === 'function') { renderPlanetGrid('planet-grid', false); renderPlanetGrid('lobby-planet-grid', true); } }; Designer.renderList = function () { var box = document.getElementById('designer-list'); var pts = document.getElementById('designer-points'); if (pts) { pts.textContent = String(Designer.points()); } if (!box) { return; } box.innerHTML = ''; var planets = Designer.planets(); if (!planets.length) { var empty = document.createElement('p'); empty.className = 'hint'; empty.textContent = (typeof I18n !== 'undefined') ? I18n.t('designer.empty') : 'You don’t have any planets of your own yet. Create one.'; box.appendChild(empty); return; } for (var i = 0; i < planets.length; i++) { var pl = planets[i]; if (typeof Planet !== 'undefined' && Planet.planetFromData && !pl.baseJumpHeight) { pl = Planet.planetFromData(pl); } var card = document.createElement('div'); card.className = 'planet-card designer-card'; var swatches = ''; var colors = pl.colors || []; for (var c = 0; c < colors.length; c++) { swatches += ''
				+ Designer.esc(colors[c].name) + ''; } var stats = (typeof Planet !== 'undefined' && Planet.formatStats) ? Planet.formatStats(pl) : ''; card.innerHTML = '
' + Designer.esc(pl.name) + '
' + '
' + Designer.esc(pl.people) + '
' + '
' + Designer.esc(stats) + '
' + '
' + swatches + '
' + '
' + '' + '' + '
'; (function (id) { card.querySelector('[data-edit]').addEventListener('click', function () { Designer.openEdit(id); }); card.querySelector('[data-del]').addEventListener('click', function () { Designer.confirmDelete(id); }); })(pl.id); box.appendChild(card); } }; Designer.confirmDelete = function (id) { var pl = Designer.planetById(id); var name = pl ? pl.name : id; var q = (typeof I18n !== 'undefined') ? I18n.t('designer.confirmDelete', { name: name }) : ('Delete the planet “' + name + '”?'); if (!window.confirm(q)) { return; } Online.deletePlanet(id).then(function (data) { if (!data || !data.ok) { window.alert((data && data.error && (typeof I18n !== 'undefined' ? I18n.error(data.error) : data.error)) || ((typeof I18n !== 'undefined') ? I18n.t('designer.deleteFailed') : 'Could not delete the planet.')); return; } Designer.renderList(); if (typeof renderPlanetGrid === 'function') { renderPlanetGrid('planet-grid', false); renderPlanetGrid('lobby-planet-grid', true); } }); }; Designer.planetById = function (id) { var list = Designer.planets(); for (var i = 0; i < list.length; i++) { if (list[i].id === id) { return list[i]; } } return null; }; Designer.openEdit = function (id) { var pl = id ? Designer.planetById(id) : null; Designer.editingId = pl ? pl.id : null; if (pl) { Designer.slots = []; for (var i = 0; i < 5; i++) { var c = pl.colors && pl.colors[i]; Designer.slots[i] = c ? (c.block || c.id) : Designer.defaultSlots()[i]; // c.id is the slot index 0-4 on snapshots; prefer c.block if (c && c.block) { Designer.slots[i] = c.block; } else if (c && typeof c.id === 'string') { Designer.slots[i] = c.id; } } document.getElementById('des-name').value = pl.name || ''; document.getElementById('des-people').value = pl.people || ''; document.getElementById('des-gravity').value = String(Math.max(2, pl.jumpsToClear != null ? pl.jumpsToClear : 2)); document.getElementById('des-air').value = String(pl.fallTime != null ? pl.fallTime : 3); document.getElementById('des-mass').value = String(pl.riseTime != null ? pl.riseTime : 1.5); document.getElementById('designer-edit-title').textContent = (typeof I18n !== 'undefined') ? I18n.t('designer.editTitle') : 'Edit planet'; document.getElementById('btn-designer-delete').hidden = false; } else { Designer.slots = Designer.defaultSlots().slice(); document.getElementById('des-name').value = ''; document.getElementById('des-people').value = ''; document.getElementById('des-gravity').value = '2'; document.getElementById('des-air').value = '3'; document.getElementById('des-mass').value = '1.5'; document.getElementById('designer-edit-title').textContent = (typeof I18n !== 'undefined') ? I18n.t('designer.createTitle') : 'New planet'; document.getElementById('btn-designer-delete').hidden = true; } hideIf('designer'); showIf('designer-edit'); Designer.syncPreview(); Designer.renderSlots(); var name = document.getElementById('des-name'); if (name) { name.focus(); } }; Designer.draftPlanet = function () { var jumps = clampNum(document.getElementById('des-gravity').value, 2, 4, 2); var fall = clampNum(document.getElementById('des-air').value, 1, 5, 3); var rise = clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5); var colors = []; for (var i = 0; i < 5; i++) { var B = Designer._blocks(); var col = B ? B.asColor(Designer.slots[i], i) : null; if (col) { colors.push(col); } } var opts = { id: Designer.editingId || 'draft', name: (document.getElementById('des-name').value || (typeof I18n !== 'undefined' ? I18n.t('designer.defaultName') : 'New planet')).trim() || (typeof I18n !== 'undefined' ? I18n.t('designer.defaultName') : 'New planet'), people: (document.getElementById('des-people').value || (typeof I18n !== 'undefined' ? I18n.t('designer.defaultPeople') : 'People')).trim() || (typeof I18n !== 'undefined' ? I18n.t('designer.defaultPeople') : 'People'), jumpsToClear: jumps, fallTime: fall, riseTime: rise, colors: colors }; if (typeof Planet === 'undefined') { return opts; } return Planet.createPlanet ? (function () { var p = Planet.createPlanet(opts); p.id = opts.id; p.custom = true; return p; })() : opts; }; Designer.syncPreview = function () { var p = Designer.draftPlanet(); var d = (typeof Planet !== 'undefined' && Planet.displayValues) ? Planet.displayValues(p) : null; // t1199: gravity as a percentage (2.0 = 100 % = 9.81 g). var gv = clampNum(document.getElementById('des-gravity').value, 2, 4, 2); setText('des-gravity-val', (typeof Planet !== 'undefined' && Planet.formatGravity) ? Planet.formatGravity(gv) : Math.round((gv - 1) * 100) + '%'); setText('des-air-val', Number(document.getElementById('des-air').value).toFixed(1) + (d ? ' · d ' + d.density.toFixed(2) : '')); setText('des-mass-val', Number(document.getElementById('des-mass').value).toFixed(1) + (d ? ' · F ' + Math.round(d.newtons) + ' N' : '')); var power = d ? d.power : 0; setText('des-power', (typeof I18n !== 'undefined') ? I18n.t('designer.power', { n: power }) : ('Power ' + power + '%')); }; Designer.renderSlots = function () { var row = document.getElementById('des-slots'); if (!row) { return; } row.innerHTML = ''; for (var i = 0; i < 5; i++) { var id = Designer.slots[i]; var B = Designer._blocks(); var b = B ? B.byId(id) : null; var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'des-slot'; btn.setAttribute('aria-label', (typeof I18n !== 'undefined') ? I18n.t('designer.slotAria', { n: i + 1 }) : ('Block ' + (i + 1))); if (b) { var bname = (typeof I18n !== 'undefined') ? I18n.blockName(b.id, b.name) : b.name; btn.innerHTML = '' + Designer.esc(bname) + '' + '' + Designer.esc(bname) + ''; } else { btn.innerHTML = '' + ((typeof I18n !== 'undefined') ? I18n.t('designer.choose') : 'Choose') + ''; } (function (slot) { btn.addEventListener('click', function () { Designer.openModal(slot); }); })(i); row.appendChild(btn); } }; Designer.openModal = function (slot) { Designer.openSlot = slot; var modal = document.getElementById('des-modal'); var grid = document.getElementById('des-modal-grid'); if (!modal || !grid) { return; } grid.innerHTML = ''; var blocks = Designer.blocks(); var used = Object.create(null); for (var i = 0; i < 5; i++) { if (i !== slot && Designer.slots[i]) { used[Designer.slots[i]] = true; } } for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; var cell = document.createElement('button'); cell.type = 'button'; cell.className = 'des-block'; cell.dataset.id = b.id; var locked = !b.unlocked; var taken = !!used[b.id]; if (locked) { cell.classList.add('locked'); } if (taken) { cell.classList.add('used'); } if (Designer.slots[slot] === b.id) { cell.classList.add('current'); } var bname = (typeof I18n !== 'undefined') ? I18n.blockName(b.id, b.name) : b.name; var title = bname; if (locked) { title += ' — ' + ((typeof I18n !== 'undefined') ? I18n.t('designer.needPoints', { n: b.threshold }) : (b.threshold + ' points required')); } else if (taken) { title += ' — ' + ((typeof I18n !== 'undefined') ? I18n.t('designer.alreadyUsed') : 'already in another slot'); } cell.title = title; cell.setAttribute('aria-label', title); cell.innerHTML = '' + (locked ? '' : '') + '' + Designer.esc(bname) + '' + (locked ? '' + b.threshold + '' : ''); if (locked || taken) { cell.disabled = true; } else { cell.addEventListener('click', (function (id) { return function () { Designer.slots[Designer.openSlot] = id; Designer.closeModal(); Designer.renderSlots(); }; })(b.id)); } grid.appendChild(cell); } modal.hidden = false; modal.setAttribute('aria-hidden', 'false'); var close = document.getElementById('des-modal-close'); if (close) { close.focus(); } }; Designer.closeModal = function () { var modal = document.getElementById('des-modal'); if (!modal) { return; } modal.hidden = true; modal.setAttribute('aria-hidden', 'true'); }; Designer.save = function () { var name = (document.getElementById('des-name').value || '').trim(); var people = (document.getElementById('des-people').value || '').trim(); if (!name || !people) { window.alert((typeof I18n !== 'undefined') ? I18n.t('designer.needNames') : 'Enter a name for the planet and for its people.'); return; } for (var i = 0; i < 5; i++) { if (!Designer.slots[i]) { window.alert((typeof I18n !== 'undefined') ? I18n.t('designer.needFive') : 'Choose five blocks.'); return; } } var payload = { id: Designer.editingId || undefined, name: name, people: people, jumpsToClear: clampNum(document.getElementById('des-gravity').value, 2, 4, 2), fallTime: clampNum(document.getElementById('des-air').value, 1, 5, 3), riseTime: clampNum(document.getElementById('des-mass').value, 0.5, 3, 1.5), colors: Designer.slots.slice() }; Online.savePlanet(payload).then(function (data) { if (!data || !data.ok) { window.alert((data && data.error && (typeof I18n !== 'undefined' ? I18n.error(data.error) : data.error)) || ((typeof I18n !== 'undefined') ? I18n.t('designer.saveFailed') : 'Could not save the planet.')); return; } hideIf('designer-edit'); showIf('designer'); Designer.editingId = data.planet ? data.planet.id : null; Designer.renderList(); if (typeof renderPlanetGrid === 'function') { renderPlanetGrid('planet-grid', false); renderPlanetGrid('lobby-planet-grid', true); } }); }; Designer.bind = function () { var btn = document.getElementById('btn-designer'); if (btn) { btn.addEventListener('click', function () { Designer.openList(); }); } var back = document.getElementById('btn-designer-back'); if (back) { back.addEventListener('click', Designer.close); } var neu = document.getElementById('btn-designer-new'); if (neu) { neu.addEventListener('click', function () { Designer.openEdit(null); }); } var cancel = document.getElementById('btn-designer-cancel'); if (cancel) { cancel.addEventListener('click', function () { hideIf('designer-edit'); showIf('designer'); Designer.renderList(); }); } var save = document.getElementById('btn-designer-save'); if (save) { save.addEventListener('click', function (e) { e.preventDefault(); Designer.save(); }); } var form = document.getElementById('designer-form'); if (form) { form.addEventListener('submit', function (e) { e.preventDefault(); Designer.save(); }); } var del = document.getElementById('btn-designer-delete'); if (del) { del.addEventListener('click', function () { if (!Designer.editingId) { return; } Designer.confirmDelete(Designer.editingId); hideIf('designer-edit'); showIf('designer'); }); } ['des-gravity', 'des-air', 'des-mass'].forEach(function (id) { var el = document.getElementById(id); if (!el) { return; } el.addEventListener('input', Designer.syncPreview); }); var modal = document.getElementById('des-modal'); if (modal) { modal.addEventListener('click', function (e) { if (e.target === modal) { Designer.closeModal(); } }); } var close = document.getElementById('des-modal-close'); if (close) { close.addEventListener('click', Designer.closeModal); } document.addEventListener('keydown', function (e) { if (e.key === 'Escape') { Designer.closeModal(); } }); }; Designer.esc = function (s) { return String(s == null ? '' : s) .replace(/&/g, '&').replace(//g, '>') .replace(/"/g, '"'); }; function hideIf (id) { var el = document.getElementById(id); if (el) { el.hidden = true; } } function showIf (id) { var el = document.getElementById(id); if (el) { el.hidden = false; } } function setText (id, text) { var el = document.getElementById(id); if (el) { el.textContent = text; } } function clampNum (v, lo, hi, fallback) { var n = Number(v); if (!isFinite(n)) { n = fallback; } return Math.max(lo, Math.min(hi, n)); } if (typeof module !== 'undefined' && module.exports) { module.exports = Designer; } else if (typeof globalThis !== 'undefined') { globalThis.Designer = Designer; } /* * End File: * /workspace/meteors/src/designer.js */ /* * Start File: * /workspace/meteors/src/loginPrompt.js */ 'use strict'; /** * Startup login prompt (t1246). A logged-out player is asked to log in * or play as guest. The guest / "already asked" choice lives in * sessionStorage so it survives a return to the menu in the same tab, * but a fresh start (new tab or closed tab) asks again. */ var LoginPrompt = { STORAGE_KEY: 'meteors-login-prompt' }; LoginPrompt._storage = function (storage) { if (storage !== undefined) { return storage; } try { if (typeof sessionStorage !== 'undefined') { return sessionStorage; } } catch (e) { /* private mode / disabled storage */ } return null; }; LoginPrompt.remembered = function (storage) { var store = this._storage(storage); if (!store) { return false; } try { return store.getItem(this.STORAGE_KEY) === '1'; } catch (e) { return false; } }; LoginPrompt.remember = function (storage) { var store = this._storage(storage); if (!store) { return false; } try { store.setItem(this.STORAGE_KEY, '1'); return true; } catch (e) { return false; } }; /** * True when this page load is a return from the auth flow, so the * prompt must not reappear (successful login is already covered by * `me`; this also covers a cancelled or failed attempt). * * `search` is location.search; `referrer` is document.referrer. */ LoginPrompt.isAuthReturn = function (search, referrer) { search = search == null ? '' : String(search); referrer = referrer == null ? '' : String(referrer); try { var q = search.charAt(0) === '?' ? search.slice(1) : search; var params = new URLSearchParams(q); if (params.get('online') === '1') { return true; } if (params.get('auth')) { return true; } } catch (e) { /* URLSearchParams missing or bad input */ } var r = referrer.toLowerCase(); if (r.indexOf('callback.php') !== -1) { return true; } if (r.indexOf('auth.timfalken.com') !== -1) { return true; } return false; }; /** * Whether the startup prompt should be shown. * `opts.me` — current user (truthy when logged in). * `opts.remembered` — session already chose guest or started login. * `opts.fromAuthReturn` — this load comes from the auth callback / return URL. */ LoginPrompt.shouldShow = function (opts) { opts = opts || {}; if (opts.me) { return false; } if (opts.remembered) { return false; } if (opts.fromAuthReturn) { return false; } return true; }; if (typeof module !== 'undefined' && module.exports) { module.exports = LoginPrompt; } else if (typeof globalThis !== 'undefined') { globalThis.LoginPrompt = LoginPrompt; } /* * End File: * /workspace/meteors/src/loginPrompt.js */ /* * Start File: * /workspace/meteors/src/avatar.js */ 'use strict'; /** * Player avatars, same idea as Allianties: a coloured initials circle, * with the auth profile picture on top when it loads. A failed picture * is dropped; the initials stay. */ var Avatar = { failed: {}, loaded: {}, initials: function (name) { if (!name) { return '?'; } var parts = String(name).trim().split(/[\s._-]+/).filter(function (s) { return s.length > 0; }); if (!parts.length) { return '?'; } var first = Array.from(parts[0]); var s = first[0]; if (parts.length > 1) { s += Array.from(parts[parts.length - 1])[0]; } else if (first.length > 1 && /[a-z]/i.test(first[1])) { s += first[1]; } return s.toUpperCase(); }, usableUrl: function (url) { if (typeof url !== 'string') { return null; } url = url.trim(); if (!url) { return null; } if (!/^(https?:\/\/|data:image\/|\/|\.{0,2}\/?[\w-])/i.test(url)) { return null; } if (/^(javascript|vbscript):/i.test(url)) { return null; } if (Avatar.failed[url]) { return null; } return url; }, colorFor: function (id) { var palette = ['#e85d5d', '#4fa3e8', '#5dd39e', '#e8c547', '#b07ce8', '#e8873a', '#3ad1d1', '#e86fb8']; var h = 0; String(id || '').split('').forEach(function (c) { h = (h * 31 + c.charCodeAt(0)) >>> 0; }); return palette[h % palette.length]; }, textColor: function (hex) { var m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(hex || '')); if (!m) { return '#fff'; } var v = m[1]; if (v.length === 3) { v = v[0] + v[0] + v[1] + v[1] + v[2] + v[2]; } var r = parseInt(v.slice(0, 2), 16), g = parseInt(v.slice(2, 4), 16), b = parseInt(v.slice(4, 6), 16); var lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255; return lum > 0.6 ? '#111' : '#fff'; }, piece: function (player, opts) { opts = opts || {}; var doc = opts.doc || document; var color = player.color || Avatar.colorFor(player.id || player.name); var el = doc.createElement('span'); el.className = 'player-avatar' + (player.alive === false ? ' dead' : ''); el.setAttribute('role', 'img'); el.setAttribute('aria-label', player.name || '?'); el.title = player.name || ''; el.style.borderColor = color; el.style.backgroundColor = color; el.style.color = Avatar.textColor(color); if (opts.size) { var size = opts.size; el.style.width = size + 'px'; el.style.height = size + 'px'; el.style.fontSize = Math.max(10, Math.round(size * 0.4)) + 'px'; } var txt = doc.createElement('span'); txt.className = 'player-avatar-initials'; txt.textContent = Avatar.initials(player.name); el.appendChild(txt); var url = Avatar.usableUrl(player.avatar); if (url) { var img = doc.createElement('img'); img.alt = ''; img.className = 'player-avatar-img'; img.decoding = 'async'; img.referrerPolicy = 'no-referrer'; img.addEventListener('error', function () { Avatar.failed[url] = true; el.classList.remove('has-img'); if (img.parentNode) { img.parentNode.removeChild(img); } }); img.addEventListener('load', function () { if (!img.naturalWidth) { Avatar.failed[url] = true; if (img.parentNode) { img.parentNode.removeChild(img); } return; } Avatar.loaded[url] = true; el.classList.add('has-img'); }); if (Avatar.loaded[url]) { el.classList.add('has-img'); } img.src = url; el.appendChild(img); } return el; } }; if (typeof module !== 'undefined' && module.exports) { module.exports = Avatar; } else if (typeof globalThis !== 'undefined') { globalThis.Avatar = Avatar; } /* * End File: * /workspace/meteors/src/avatar.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 }); } } if (typeof Blocks !== 'undefined' && Blocks.images) { var extra = Blocks.images(); for (var b = 0; b < extra.length; b++) { list.push(extra[b]); } } 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, rewardActive: false, onlineBefore: 0, pendingLobbyReturn: null }; window.onload = function () { app.debugDrag = isDragDebugEnabled(); app.debugPhysics = isPhysicsDebugEnabled(); var play = document.getElementById('btn-play'); play.addEventListener('click', onPlay); bindGameMenu(); 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); } }); if (typeof I18n !== 'undefined') { I18n.init(); I18n.bindPicker(); I18n.onChange(function () { refreshAllUi(); }); } bindOnlineUi(); bindLeaderboard(); bindOfflineUi(); bindPlanetSelect(); restoreSelectedPlanet(); if (typeof Designer !== 'undefined' && Designer.bind) { Designer.bind(); } bindLoginPrompt(); if (typeof Online !== 'undefined' && Online.refresh) { Online.refresh().then(function () { applyProfileLocale(); refreshMenuAccount(); restoreSelectedPlanet(); renderPlanetGrid('planet-grid', false); renderPlanetGrid('lobby-planet-grid', true); maybeShowLoginPrompt(); }); } else { refreshMenuAccount(); maybeShowLoginPrompt(); } }; /** * t1201: the big "Play" button starts the rounds against bots (internal * mode 'offline', formerly "Offline Battle"); "Survival" starts the endless * solo game (internal mode 'solo', formerly "Play"). Internal ids and * play_finish modes are unchanged. */ function onPlay () { if (app.mode === 'playing') { return; } clearStartError(); openPlanetSelect('offline'); } function onSurvival () { if (app.mode === 'playing') { return; } clearStartError(); openPlanetSelect('solo'); } /** t1201: player-facing name of a mode / planet-select context. */ function modeLabel (context) { var key = context === 'offline' ? 'menu.play' : (context === 'online' ? 'menu.online' : 'menu.survival'); var fallback = context === 'offline' ? 'Play' : (context === 'online' ? 'Play online' : 'Survival'); if (typeof I18n === 'undefined') { return fallback; } var s = I18n.t(key); return (s && s !== key) ? s : fallback; } function startPlay (opts) { opts = opts || {}; var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod; var planet = opts.planet || planetMod.planetById(selectedPlanetId()); var miss = opts.missChance; if (typeof miss !== 'number' || !isFinite(miss)) { miss = planetMod.missChance(planet); } hideEl('menu'); hideEl('game-over'); hideEl('online-panel'); hideEl('spectator'); hideEl('podium'); hideEl('planet-select'); hideEl('offline-result'); hideEl('designer'); hideEl('designer-edit'); if (typeof Designer !== 'undefined' && Designer.closeModal) { Designer.closeModal(); } // Do not show the HUD until the scene is on screen. Showing it first // left the default "Terra" / "0" labels on a blank starfield when // `new Scene` threw (WebGL unavailable) after inserting a transparent // canvas — the t1143 live blank-screen report. app.planet = planet; app.core = new GameCore(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; } try { 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(); showEl('hud'); setGameMenuButton(!app.online && !app.spectating); } catch (err) { abortStartPlay(err); return; } if (app.online || app.offline) { showEl('minis'); } else { hideEl('minis'); } buildColumnWarn(); refreshOfflineHud(); refreshChainIndicator(); if (!opts.online) { beginPlaySession(opts.offline ? 'offline' : 'solo'); } } function removeOrphanPlayCanvases () { // Scene's constructor inserts a body canvas, then GLContext may throw, // leaving a transparent leftover that hides nothing and shows stars. var nodes = document.querySelectorAll('body > canvas'); for (var i = 0; i < nodes.length; i++) { if (nodes[i].parentNode) { nodes[i].parentNode.removeChild(nodes[i]); } } } function abortStartPlay (err) { if (typeof console !== 'undefined' && console.error) { console.error('startPlay failed', err); } try { unbindPointer(); if (app.scene && app.scene.destroy) { app.scene.destroy(); } } catch (e) { /* ignore cleanup errors */ } app.scene = null; app.core = null; app.manager = null; app.mode = 'menu'; app.online = false; app.offline = false; app.battle = null; app.cells = []; removeOrphanPlayCanvases(); hideEl('hud'); hideEl('minis'); hideEl('planet-select'); showEl('menu'); refreshMenuAccount(); var box = document.getElementById('start-error'); if (box) { var msg = (err && err.message) ? String(err.message) : ''; var webgl = /webgl/i.test(msg); if (typeof I18n !== 'undefined') { box.textContent = I18n.t(webgl ? 'error.webgl' : 'error.startFailed'); } else { box.textContent = webgl ? 'This game needs WebGL. Please try another browser, or turn on hardware acceleration.' : 'Could not start the game.'; } box.hidden = false; } } function clearStartError () { var box = document.getElementById('start-error'); if (box) { box.hidden = true; box.textContent = ''; } } 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; app.paused = false; app.quitting = false; hideEl('game-menu'); setGameMenuButton(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 () { clearStartError(); 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 === 'top' && plan.mini && plan.mini.cols) { // t1203: top row is placed absolutely too, scaled to fit above the field. minis.classList.remove('sides'); minis.classList.add('placed'); minis.style.top = '0'; minis.style.bottom = '0'; minis.style.left = '0'; minis.style.right = '0'; minis.style.maxHeight = 'none'; return; } minis.classList.remove('placed'); 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 = ''; kids[i].style.fontSize = ''; } 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.n || (plan.mode !== 'sides' && plan.mode !== 'top')) { return; } var positions = plan.positions || []; var kids = minis.querySelectorAll('.mini'); if (plan.mode === 'top' && kids.length && typeof MiniLayout !== 'undefined' && MiniLayout.topPositions) { // t1203: if they do not all fit even at the minimum size, defeated // opponents move to the back (stable), so the living stay visible. var elim = []; for (var k = 0; k < kids.length; k++) { elim.push(kids[k].classList.contains('eliminated')); } positions = MiniLayout.topPositions(elim, plan); plan.positions = positions; } 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'; el.style.fontSize = p.font ? p.font + 'px' : ''; el.setAttribute('data-slot', p.slot != null ? String(p.slot) : String(i)); 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; } /** Frames in the flame sprite (from the loaded image, default 4). */ function flameFrameCount () { var img = typeof game !== 'undefined' && game.images ? game.images.flame : null; return img && img.subImages ? img.subImages : 4; } 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 (typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(block.id)) { obj.renderer.visible = false; obj.renderer.alpha = 0; } if (block.flame) { var flame = app.flames[block.id]; if (!flame) { flame = new GameObject(0, 0, game.images.flame, 1); // t1183: frames are chosen by FlameFx, not the framework cycle. flame.fx = FlameFx.create(flameFrameCount(), Math.random, FlameFx.reducedMotion()); flame.renderer.setSubImage(flame.fx.frame); app.scene.addObject(flame); app.flames[block.id] = flame; } flame.renderer.visible = true; FlameFx.advance(flame.fx, dt, Math.random, FlameFx.reducedMotion()); 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. t1183: random frame, flip, // scale and rotation all pivot on that top-centre anchor. 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; var pose = FlameFx.pose(flame.fx, block.col * t + t / 2, origTop, flameW, flameH); flame.renderer.subImage = pose.frame; flame.renderer.mirrorX = pose.mirrorX; flame.transform.rotation = pose.rotation; flame.transform.position.x = pose.x; flame.transform.position.y = pose.y; flame.transform.size = { x: pose.w, y: pose.h }; } else if (app.flames[block.id]) { app.flames[block.id].renderer.visible = false; } if (block.flame && app.flames[block.id] && typeof Online !== 'undefined' && Online.hasExitVisual && Online.hasExitVisual(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; var pname = (typeof I18n !== 'undefined') ? I18n.planetName(planet) : planet.name; var people = (typeof I18n !== 'undefined') ? I18n.peopleName(planet) : planet.people; document.getElementById('planet-name').textContent = pname + ' · ' + 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); } // t1193: in-game menu open (Spelen / Offline Strijd) or quitting: // the field, bots and timers stand still; only the view is kept. if (app.paused) { syncSprites(0); return; } 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 if (rewardEnabled()) { showReward(false, finishPlaySession(app.lastScore), returnToMenu); } else { showEl('game-over'); finishPlaySession(app.lastScore); } } if (!app.online && !app.offline && !app.rewardActive && 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' && !app.paused; } /** Touches on HUD buttons / menus are UI taps, not field drags (t1193). */ function isUiTouchTarget (e) { var el = e && e.target; if (!el || !el.closest) { return false; } return !!el.closest('button, a, input, select, #game-menu, #reward'); } 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 && isUiTouchTarget(e)) { 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); Online.rememberFlightLocal(s, start.x, start.y); // Draw the flight locally right away (t1181); the server // answer only retargets it. if (Online.startLocalShot) { Online.startLocalShot(s, start); } } Online.queueShots(shots); if (shots.length && Online.flushShotsSoon) { Online.flushShotsSoon(); } } Online.tickFlights(); Online.renderMinis(document.getElementById('minis')); applyMinisLayout(); } /* ---------- Offline Strijd (t1119) + column warn (t1123) ----------- */ function bindOfflineUi () { // t1201: the second menu button is now "Survival" (endless solo). var btn = document.getElementById('btn-survival'); if (btn) { btn.addEventListener('click', onSurvival); btn.addEventListener('pointerup', function (e) { if (e.pointerType === 'touch' || e.pointerType === 'pen') { e.preventDefault(); onSurvival(); } }); } 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 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; if (rewardEnabled()) { showReward(true, finishPlaySession(app.core.score), startNextOfflineRound); } } if (app.rewardActive) { updateOfflineMinis(dt, true); return; } 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); } else if (typeof Online !== 'undefined' && Online.miniCellViewport) { start = Online.miniCellViewport(s.from_id, s.col, s.y != null ? s.y : 12); } 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, land_col: s.land_col }; } Online.spawnFlights(result.flights, locals); } if (typeof Online !== 'undefined' && Online.tickFlights) { Online.tickFlights(); } updateOfflineMinis(dt, false); if (app.battle.state === 'lost' && !app.offlineResultShown) { if (rewardEnabled()) { // Guard against starting the reward twice; showOfflineResult // sets the flag again when it runs afterwards. app.offlineResultShown = true; showReward(false, finishPlaySession(app.core ? app.core.score : 0), showOfflineResult); } else { 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; var roundScore = app.core ? app.core.score : 0; finishPlaySession(roundScore); 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'); var line = document.getElementById('offline-reached-line'); if (line && typeof I18n !== 'undefined') { line.textContent = I18n.t('offline.reached', { n: battle.round }); } else if (reached) { reached.textContent = String(battle.round); } // t1198: "X opponents defeated" over all rounds (replaces the // opponents / skill line). var detail = document.getElementById('offline-result-detail'); if (detail) { var beaten = battle.defeated || 0; detail.textContent = (typeof I18n !== 'undefined') ? I18n.plural('offline.defeated', beaten, { n: beaten }) : beaten + (beaten === 1 ? ' opponent defeated' : ' opponents defeated'); } hideEl('game-over'); showEl('offline-result'); finishPlaySession(app.core ? app.core.score : 0); } 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; // t1195: the Offline Strijd HUD shows only "Round N". var sch = app.battle.schedule; var r = document.getElementById('offline-round'); if (r) { r.textContent = (typeof I18n !== 'undefined') ? I18n.t('hud.round', { n: sch.round }) : 'Round ' + sch.round; } } function hideOfflineHud () { var el = document.getElementById('offline-hud'); if (el) { el.hidden = true; } } function refreshChainIndicator () { var el = document.getElementById('chain-indicator'); if (!el) { return; } // t1200: the yellow "+x%" shows ONLY the combo bonus // (0.01·min(combo, 30)); the landing-chain bonus still boosts the jump // but is not part of this number. Visible while that bonus is > 0. var pct = (app.core && app.core.comboBonusPct) ? app.core.comboBonusPct() : 0; if (!(pct > 0) || app.mode !== 'playing') { el.hidden = true; return; } el.hidden = false; el.textContent = '+' + pct + '%'; } 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') { // Leave from the top of the mini, then the arc goes up and over (t1131). return { x: rect.left + rect.width / 2, y: rect.top + 4 }; } 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 : ''; var shownPlanet = planetName; if (bot.planet && typeof I18n !== 'undefined') { shownPlanet = I18n.planetName(bot.planet); } el.querySelector('.mini-name').textContent = bot.name + (shownPlanet ? ' · ' + shownPlanet : ''); el.querySelector('.mini-meta').textContent = bot.eliminated ? ((typeof I18n !== 'undefined') ? I18n.t('hud.out') : 'Out') : ((typeof I18n !== 'undefined') ? I18n.t('hud.miniPoints', { n: bot.score || 0 }) : ('Points ' + (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 }; } } } /** * A flight starts only when a block has actually left the field * (y ≥ height, the same threshold as cullOffTop). Rockets that * peak below the top and fall back must never get an arc (t1137). * Shared by the player's field, enemy minis, offline and online. */ function previewOutgoingFlights () { // Intentionally not called before core.tick: a block still on // the field (y < 13) is not a shot yet. Flights are spawned // from consumeOutgoingShots after cull, at the exit pose. if (typeof Online === 'undefined' || !Online.previewExit) { return; } if (app.core) { previewCoreExits(app.core, null); } if (app.offline && app.battle && app.battle.bots) { var bots = app.battle.bots; for (var i = 0; i < bots.length; i++) { var bot = bots[i]; if (bot && bot.core && !bot.eliminated) { previewCoreExits(bot.core, bot.id); } } } } function previewCoreExits (core, fromId) { if (!core || !core.blocks) { return; } var height = core.height != null ? core.height : 13; var blocks = core.blocks; for (var i = 0; i < blocks.length; i++) { var b = blocks[i]; if (b.state === 'manual') { continue; } if (typeof Online.hasLeftTheField === 'function' ? !Online.hasLeftTheField(b.y, height) : !(b.y >= height - 1e-9)) { continue; } if (!(b.vy > 0)) { continue; } var start = fromId ? (Online.miniCellViewport ? Online.miniCellViewport(fromId, b.col, b.y) : miniViewportCenter(fromId)) : fieldToViewport(b.col, b.y); Online.previewExit({ id: b.id, col: b.col, y: b.y, vy: b.vy, color: b.color, start: start, from_id: fromId || null }); } } 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; // Cell centre matches placeTile: y = fieldH - (fieldY + 0.5) * tile (t1134). var y = rect.top + (1 - ((fieldY + 0.5) / 13)) * rect.height; return { x: x, y: y }; } function onlinePayload () { if (!app.online || !app.core) { return {}; } var snap = app.core.fieldSnapshot(); // t1182: sender time (ms) so opponents can place the snapshot in // time and predict falling blocks smoothly. Visual only. snap.t = Math.round(typeof performance !== 'undefined' ? performance.now() : Date.now()); return { snapshot: snap, 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'); if (app.rewardActive) { return; } 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 = (typeof I18n !== 'undefined') ? I18n.place(r.place) : (r.place === 1 ? '1st' : (r.place === 2 ? '2nd' : (r.place === 3 ? '3rd' : r.place + 'th'))); li.textContent = (typeof I18n !== 'undefined') ? I18n.t('podium.line', { place: medal, name: r.name, score: r.score }) : (medal + ' ' + r.name + ' · ' + r.score + ' points'); list.appendChild(li); } var hint = document.getElementById('podium-hint'); var secs = (lobby && lobby.podium_seconds) || 5; if (hint) { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('podium.hint', { n: secs }) : ('Returning to the lobby in ' + secs + ' seconds…'); } } function startOnlineMatch () { if (app.mode === 'playing' && app.online) { return; } var planet = Planet.planetById(selectedPlanetId()); var miss = Planet.missChance(planet); var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null; if (me && me.planet) { if (typeof Planet.rememberPlanet === 'function') { planet = Planet.rememberPlanet(me.planet) || planet; } else if (me.planet.id) { planet = Planet.planetById(me.planet.id); } if (typeof me.planet.miss_chance === 'number') { miss = me.planet.miss_chance; } } app.onlineBefore = Number((typeof Online !== 'undefined' && Online.lifetimePoints) || 0) || 0; if (typeof Online !== 'undefined') { Online.onlineAwarded = null; } app.pendingLobbyReturn = null; startPlay({ online: true, planet: planet, missChance: miss }); 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; var btn = document.getElementById('btn-copy-code'); var done = function () { if (!btn) { return; } btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copied') : 'Copied'; setTimeout(function () { btn.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.copy') : 'Copy'; }, 1500); }; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(code).then(done, done); } else { done(); } }); 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++) { var col = Online.takeLandCol ? Online.takeLandCol(incoming[i]) : incoming[i].land_col; app.core.ingestGarbage(col); } }; Online.onFinished = function (lobby) { if (app.mode === 'playing' && app.online && rewardEnabled() && !app.rewardActive) { // Prefer the poll's online_awarded (t1278): same formula as // play_finish. Rematches in a reused lobby used to leave // lifetimePoints unchanged, so before === after and the // tally never started even though "You won!" still rose. var result = (typeof Online.rewardResult === 'function') ? Online.rewardResult({ lifetimePoints: Online.lifetimePoints, awarded: Online.onlineAwarded, before: app.onlineBefore }) : { before: app.onlineBefore || 0, after: Online.lifetimePoints || 0 }; showReward(myOnlinePlace(lobby) === 1, Promise.resolve(result), function () { var pending = app.pendingLobbyReturn; app.pendingLobbyReturn = null; if (pending || !(Online.lobby && Online.lobby.status === 'finished')) { Online.onLobbyReturn(pending || Online.lobby); } else { showPodium(Online.lobby); } }); return; } showPodium(lobby); }; Online.onLobbyReturn = function (lobby) { if (app.rewardActive) { app.pendingLobbyReturn = lobby; return; } 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(); // t1193: one-shot; a reload must not jump to online play again. try { params.delete('online'); var rest = params.toString(); window.history.replaceState(null, '', window.location.pathname + (rest ? '?' + rest : '') + window.location.hash); } catch (e) { /* ignore */ } } } function openOnlinePanel () { hideEl('menu'); hideEl('game-over'); hideEl('podium'); hideEl('spectator'); hideEl('planet-select'); showEl('online-panel'); app.mode = 'online'; setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.checking') : 'Checking whether online play is available…'); if (typeof Online === 'undefined') { showOnlineError((typeof I18n !== 'undefined') ? I18n.t('online.notLoaded') : 'Online play is not included in this build. You can still play offline.'); showOnly('online-unconfigured'); return; } Online.refresh().then(function (data) { if (!data || data.ok === false) { var msg = (data && data.error) ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error) : ((typeof I18n !== 'undefined') ? I18n.t('error.connection') : 'No connection to the server.'); showOnlineError(msg + ' ' + ((typeof I18n !== 'undefined') ? I18n.t('online.canPlaySolo') : 'You can still play offline.')); 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' && !app.rewardActive) { showPodium(Online.lobby); } return; } showOnlineError((typeof I18n !== 'undefined' && Online.error) ? I18n.error(Online.error) : Online.error); if (!Online.configured && !Online.me && !Online.local) { setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusUnconfigured') : 'Online play is not set up yet.'); showOnly('online-unconfigured'); return; } if (!Online.me) { setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusLogin') : 'Log in to create a lobby or join one.'); 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((typeof I18n !== 'undefined') ? I18n.t('online.statusLobby') : '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 host = (typeof I18n !== 'undefined') ? I18n.t('online.host') : 'host'; var you = (typeof I18n !== 'undefined') ? I18n.t('online.you') : 'you'; var label = p.name + (p.is_host ? ' (' + host + ')' : '') + (p.is_me ? ' (' + you + ')' : ''); 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) ? ((typeof I18n !== 'undefined') ? I18n.t('online.notReady') : 'Not ready') : ((typeof I18n !== 'undefined') ? I18n.t('online.ready') : 'Ready'); 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 = (typeof I18n !== 'undefined') ? I18n.t('online.hintStarting') : 'The game is starting…'; } else if (players.length < 2) { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedPlayers') : 'Wait for at least one other player. Share the code.'; } else if (!Online.lobby.all_ready) { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintNeedReady') : 'Everyone must press Ready. The host starts afterwards.'; } else if (Online.lobby.can_start) { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintHostStart') : 'Everyone is ready. Press Start.'; } else { hint.textContent = (typeof I18n !== 'undefined') ? I18n.t('online.hintWaitHost') : 'Waiting for the host to start.'; } return; } setOnlineStatus((typeof I18n !== 'undefined') ? I18n.t('online.statusHome', { name: Online.me.name }) : ('Hi ' + Online.me.name + '. Create a lobby or join with a 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'; } /** * Pre-select the last chosen planet (t1196): logged in the profile value * (server), otherwise / as fallback localStorage, otherwise Terra. A * deleted custom planet falls back to the default (setSelectedPlanet). */ function restoreSelectedPlanet () { var id = null; if (typeof Online !== 'undefined' && Online.me && Online.lastPlanet) { id = Online.lastPlanet; } if (!id) { try { id = localStorage.getItem('meteors-planet'); } catch (e) {} } setSelectedPlanet(id || 'terra', true); } function rememberPlanetChoice (id) { if (typeof Online === 'undefined' || !Online.me || !Online.setLastPlanet) { return; } if (Online.lastPlanet === id) { return; } Promise.resolve(Online.setLastPlanet(id)).then(null, function () {}); } 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) { rememberPlanetChoice(found.id); 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 = (typeof I18n !== 'undefined') ? I18n.t('menu.play') : 'Play'; } // t1201: show which mode this planet choice is for. var modeEl = document.getElementById('planet-mode'); if (modeEl) { modeEl.textContent = modeLabel(app.planetSelectContext); } } 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' : '') + (pl.custom ? ' custom' : ''); btn.setAttribute('role', 'listitem'); btn.dataset.planet = pl.id; var swatches = ''; var colors = pl.colors || []; for (var c = 0; c < colors.length; c++) { var cname = colors[c].name; if (typeof I18n !== 'undefined' && (colors[c].block || (!pl.custom && colors[c].name))) { cname = I18n.blockName(colors[c].block || (pl.id + '-' + colors[c].name), colors[c].name); } swatches += ''
				+ escapeText(cname) + ''; } var title = (typeof I18n !== 'undefined') ? I18n.planetName(pl) : pl.name; var people = (typeof I18n !== 'undefined') ? I18n.peopleName(pl) : pl.people; var badge = (typeof I18n !== 'undefined') ? I18n.t('planet.customBadge') : 'Yours'; btn.innerHTML = '
' + escapeText(title) + '
' + '
' + escapeText(people) + '
' + '
' + escapeText(Planet.formatStats(pl)) + '
' + '
' + swatches + '
' + (pl.custom ? '' + escapeText(badge) + '' : ''); 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); } } /** t1246: ask a logged-out player to log in, or continue as guest. */ function bindLoginPrompt () { if (typeof LoginPrompt !== 'undefined' && LoginPrompt.isAuthReturn) { var search = (window.location && window.location.search) || ''; var referrer = (typeof document !== 'undefined' && document.referrer) || ''; if (LoginPrompt.isAuthReturn(search, referrer)) { LoginPrompt.remember(); } } var guest = document.getElementById('btn-play-guest'); if (guest) { guest.addEventListener('click', playAsGuest); } var login = document.getElementById('btn-login-prompt'); if (login) { login.addEventListener('click', function () { if (typeof LoginPrompt !== 'undefined') { LoginPrompt.remember(); } }); } var local = document.getElementById('login-prompt-local'); if (local) { local.addEventListener('click', function (e) { var a = e.target && e.target.closest ? e.target.closest('a') : null; if (a && typeof LoginPrompt !== 'undefined') { LoginPrompt.remember(); } }); } } function maybeShowLoginPrompt () { var me = (typeof Online !== 'undefined') ? Online.me : null; var remembered = (typeof LoginPrompt !== 'undefined') && LoginPrompt.remembered(); var fromAuth = (typeof LoginPrompt !== 'undefined') && LoginPrompt.isAuthReturn( (window.location && window.location.search) || '', (typeof document !== 'undefined' && document.referrer) || '' ); var show = (typeof LoginPrompt === 'undefined') ? (!me && !remembered && !fromAuth) : LoginPrompt.shouldShow({ me: me, remembered: remembered, fromAuthReturn: fromAuth }); if (show) { showLoginPrompt(); } else { hideLoginPrompt(); } app.loginPromptReady = true; } function showLoginPrompt () { var el = document.getElementById('login-prompt'); if (!el) { return; } el.hidden = false; var login = document.getElementById('btn-login-prompt'); if (login && login.focus) { login.focus(); } } function hideLoginPrompt () { var el = document.getElementById('login-prompt'); if (el) { el.hidden = true; } } function playAsGuest () { if (typeof LoginPrompt !== 'undefined') { LoginPrompt.remember(); } hideLoginPrompt(); } function refreshMenuAccount () { var guest = document.getElementById('menu-guest'); var user = document.getElementById('menu-user'); var designerBtn = document.getElementById('btn-designer'); var localLogin = document.getElementById('menu-local-login'); var me = (typeof Online !== 'undefined') ? Online.me : null; if (me) { if (guest) { guest.hidden = true; } if (user) { user.hidden = false; } var name = document.getElementById('menu-name'); if (name) { name.textContent = me.name || me.id || ((typeof I18n !== 'undefined') ? I18n.t('menu.player') : 'player'); } var pts = document.getElementById('menu-points'); if (pts) { pts.textContent = String((typeof Online !== 'undefined' && Online.lifetimePoints) || 0); } if (designerBtn) { designerBtn.hidden = false; } } else { if (guest) { guest.hidden = false; } if (user) { user.hidden = true; } if (designerBtn) { designerBtn.hidden = true; } } if (localLogin) { localLogin.hidden = !(typeof Online !== 'undefined' && Online.local); } var promptLocal = document.getElementById('login-prompt-local'); if (promptLocal) { promptLocal.hidden = !(typeof Online !== 'undefined' && Online.local); } } /* ---------- t1193 in-game menu (Spelen / Offline Strijd) ----------- */ function setGameMenuButton (show) { var btn = document.getElementById('btn-game-menu'); if (btn) { btn.hidden = !show; } } /** The menu can open during a running solo / offline field only. */ function canOpenGameMenu () { return app.mode === 'playing' && !!app.core && !app.online && !app.spectating && app.core.state === 'playing' && !app.rewardActive && !app.quitting && !(app.offline && app.battle && app.battle.state !== 'playing'); } function openGameMenu () { if (!canOpenGameMenu()) { return false; } if (app.core.drag) { finishDrag({ noLaunch: true }); } app.paused = true; // t1201: name the running mode ("Play" = rounds vs bots, "Survival" = endless). var modeEl = document.getElementById('game-menu-mode'); if (modeEl) { modeEl.textContent = modeLabel(app.offline ? 'offline' : 'solo'); } showEl('game-menu'); var resume = document.getElementById('btn-game-resume'); if (resume && resume.focus) { resume.focus(); } return true; } function resumeFromGameMenu () { hideEl('game-menu'); if (!app.quitting) { app.paused = false; } } /** * "Back to main menu": ends the match now. Logged in, the points so far * go through the normal play_finish + reward screen first (the server * still applies its caps); logged out, straight to the menu. Offline * Strijd ends the whole battle (no next round). */ function quitToMainMenu () { if (!app.core || app.quitting) { return; } hideEl('game-menu'); app.paused = true; app.quitting = true; app.gameOverShown = true; app.lastScore = app.core.score || 0; setGameMenuButton(false); var score = app.lastScore; var done = function () { app.quitting = false; app.paused = false; returnToMenu(); }; if (rewardEnabled()) { var title = (typeof I18n !== 'undefined') ? I18n.t('reward.ended') : 'Game ended'; showReward(false, finishPlaySession(score), done, title); } else { finishPlaySession(score); done(); } } function bindGameMenu () { var btn = document.getElementById('btn-game-menu'); if (btn) { btn.addEventListener('click', function () { openGameMenu(); }); } var resume = document.getElementById('btn-game-resume'); if (resume) { resume.addEventListener('click', resumeFromGameMenu); } var quit = document.getElementById('btn-game-quit'); if (quit) { quit.addEventListener('click', quitToMainMenu); } document.addEventListener('keydown', function (e) { if (e.key !== 'Escape') { return; } var menu = document.getElementById('game-menu'); if (menu && !menu.hidden) { resumeFromGameMenu(); } else { openGameMenu(); } }); } function beginPlaySession (mode) { if (app.playToken) { finishPlaySession(app.core ? app.core.score : (app.lastScore || 0)); } app.playToken = null; if (typeof Online === 'undefined' || !Online.me || !Online.playBegin) { return; } Online.playBegin(mode || 'solo').then(function (data) { if (data && data.ok && data.token) { app.playToken = data.token; } }); } /** * Ends the solo/offline play session. Resolves to the server-confirmed * { before, after } profile totals (t1173), or null when there is no * logged-in user or the server did not confirm. Without a token (e.g. * play_begin failed) a logged-in player gets { before = after = current }. */ function finishPlaySession (score) { var token = app.playToken; app.playToken = null; var hasOnline = typeof Online !== 'undefined'; var current = hasOnline ? (Online.lifetimePoints || 0) : 0; if (!token || !hasOnline || !Online.playFinish) { return Promise.resolve(hasOnline && Online.me ? { before: current, after: current } : null); } return Promise.resolve(Online.playFinish(token, score || 0)).then(function (data) { refreshMenuAccount(); if (data && data.ok !== false && typeof data.lifetime_points === 'number') { var awarded = Math.max(0, Number(data.awarded) || 0); return { before: data.lifetime_points - awarded, after: data.lifetime_points }; } return null; }, function () { return null; }); } /* ---------- t1173 reward screen (logged in only) ------------------- */ function rewardEnabled () { return typeof Reward !== 'undefined' && typeof Online !== 'undefined' && !!Online.me; } /** * Shows "You won!" / "You lost..." and the points fly-in, then calls * next() — the same destination the mode used before (menu, next * offline round, offline result, or the online lobby/podium). */ function showReward (won, resultPromise, next, title) { app.rewardActive = true; hideEl('game-over'); hideEl('spectator'); hideEl('podium'); var handle = Reward.play({ won: won, title: title || null, planet: app.planet, result: resultPromise, onDone: function () { app.rewardActive = false; if (next) { next(); } } }); if (!handle) { app.rewardActive = false; // No reward overlay (e.g. missing DOM): still continue (t1193). if (title && next) { next(); } } } function myOnlinePlace (lobby) { var me = typeof Online !== 'undefined' ? Online.me : null; var ranks = (lobby && lobby.rankings) || []; for (var i = 0; i < ranks.length; i++) { if (me && ranks[i].id === me.id) { return ranks[i].place; } } return null; } function applyProfileLocale () { if (typeof I18n === 'undefined' || typeof Online === 'undefined') { return; } if (!Online.me) { return; } I18n.applyPreferred({ explicit: !!(Online.localeExplicit && Online.locale), locale: Online.locale, authLocale: Online.authLocale, syncExplicit: true }); } /* ---------- t1247 leaderboard -------------------------------------- */ function bindLeaderboard () { var btn = document.getElementById('btn-leaderboard'); if (btn) { var open = function () { openLeaderboard(); }; btn.addEventListener('click', open); // Same mobile path as Play / Survival: some browsers swallow click // after a slightly sloppy tap. btn.addEventListener('pointerup', function (e) { if (e.pointerType === 'touch' || e.pointerType === 'pen') { e.preventDefault(); open(); } }); } var back = document.getElementById('btn-lb-back'); if (back) { back.addEventListener('click', closeLeaderboard); } var globalTab = document.getElementById('lb-tab-global'); var friendsTab = document.getElementById('lb-tab-friends'); if (globalTab) { globalTab.addEventListener('click', function () { setLeaderboardTab('global'); }); } if (friendsTab) { friendsTab.addEventListener('click', function () { setLeaderboardTab('friends'); }); } } function openLeaderboard (tab) { if (app.mode === 'leaderboard') { return; } hideEl('menu'); hideEl('online-panel'); hideEl('planet-select'); hideEl('login-prompt'); app.mode = 'leaderboard'; app.leaderboardTab = tab || app.leaderboardTab || 'global'; showEl('leaderboard'); setLeaderboardTab(app.leaderboardTab); } function closeLeaderboard () { hideEl('leaderboard'); app.mode = 'menu'; showEl('menu'); } function setLeaderboardTab (tab) { tab = tab === 'friends' ? 'friends' : 'global'; app.leaderboardTab = tab; var globalTab = document.getElementById('lb-tab-global'); var friendsTab = document.getElementById('lb-tab-friends'); if (globalTab) { globalTab.setAttribute('aria-selected', tab === 'global' ? 'true' : 'false'); } if (friendsTab) { friendsTab.setAttribute('aria-selected', tab === 'friends' ? 'true' : 'false'); } loadLeaderboard(tab); } function loadLeaderboard (tab) { tab = tab || app.leaderboardTab || 'global'; var login = document.getElementById('lb-login'); var list = document.getElementById('lb-list'); var empty = document.getElementById('lb-empty'); var err = document.getElementById('lb-error'); if (err) { err.hidden = true; err.textContent = ''; } if (empty) { empty.hidden = true; } if (list) { list.innerHTML = ''; } var loggedIn = typeof Online !== 'undefined' && !!Online.me; if (tab === 'friends' && !loggedIn) { if (login) { login.hidden = false; } return; } if (login) { login.hidden = true; } if (typeof Online === 'undefined' || !Online.leaderboard) { showLeaderboardError((typeof I18n !== 'undefined') ? I18n.t('leaderboard.loadError') : 'The leaderboard could not be loaded.'); return; } Online.leaderboard(tab).then(function (data) { if (app.mode !== 'leaderboard' || app.leaderboardTab !== tab) { return; } if (!data || data.ok === false) { var msg = (data && data.error) ? ((typeof I18n !== 'undefined') ? I18n.error(data.error) : data.error) : ((typeof I18n !== 'undefined') ? I18n.t('leaderboard.loadError') : 'The leaderboard could not be loaded.'); showLeaderboardError(msg); return; } if (tab === 'friends' && data.login_required) { if (login) { login.hidden = false; } return; } renderLeaderboard(data.players || [], tab); }); } function showLeaderboardError (text) { var err = document.getElementById('lb-error'); if (!err) { return; } err.hidden = !text; err.textContent = text || ''; } function renderLeaderboard (players, tab) { var list = document.getElementById('lb-list'); var empty = document.getElementById('lb-empty'); var login = document.getElementById('lb-login'); if (login) { login.hidden = true; } if (!list) { return; } list.innerHTML = ''; if (!players || !players.length) { if (empty) { empty.hidden = false; } return; } if (empty) { empty.hidden = true; } var meId = (typeof Online !== 'undefined' && Online.me) ? Online.me.id : null; for (var i = 0; i < players.length; i++) { var p = players[i]; var li = document.createElement('li'); var you = !!(p.you || (meId && p.id === meId)); li.className = 'lb-row' + (you ? ' you' : ''); var rank = document.createElement('span'); rank.className = 'lb-rank'; rank.textContent = String(p.rank || (i + 1)); li.appendChild(rank); if (typeof Avatar !== 'undefined' && Avatar.piece) { li.appendChild(Avatar.piece({ id: p.id, name: p.name, avatar: p.avatar }, { size: 40 })); } var name = document.createElement('span'); name.className = 'lb-name'; name.textContent = p.name || ''; li.appendChild(name); var pts = document.createElement('span'); pts.className = 'lb-points'; var n = p.points || 0; pts.textContent = (typeof I18n !== 'undefined') ? I18n.t('leaderboard.points', { n: n }, n + ' points') : (n + ' points'); li.appendChild(pts); list.appendChild(li); } } function refreshAllUi () { if (typeof I18n !== 'undefined') { I18n.apply(); } refreshMenuAccount(); if (typeof renderPlanetGrid === 'function') { renderPlanetGrid('planet-grid', false); renderPlanetGrid('lobby-planet-grid', true); } if (app && app.mode === 'online' && typeof renderOnline === 'function') { renderOnline(); } if (typeof Designer !== 'undefined') { var des = document.getElementById('designer'); var edit = document.getElementById('designer-edit'); if (des && !des.hidden) { Designer.renderList(); } if (edit && !edit.hidden) { Designer.syncPreview(); Designer.renderSlots(); var modal = document.getElementById('des-modal'); if (modal && !modal.hidden) { Designer.openModal(Designer.openSlot); } } } if (app && app.mode === 'playing') { if (typeof refreshHud === 'function') { refreshHud(); } if (typeof refreshOfflineHud === 'function') { refreshOfflineHud(); } } if (app && app.mode === 'leaderboard' && typeof loadLeaderboard === 'function') { loadLeaderboard(app.leaderboardTab); } } /* * End File: * /workspace/meteors/src/main.js */