Merge branch 'feature/t1139-planet-designer'
Planet Designer for logged-in players (lifetime points, unlockable blocks, custom planets) and custom planets in every mode's picker (t1139, t1140).
@@ -56,6 +56,10 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
| Pad | Rol |
| --- | --- |
| `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power, apex-ease, bounce |
| `src/blocks.js` | Append-only blokjesregister, drempels, ontgrendeling |
| `src/designer.js` | Planeetontwerper (lijst, bewerken, blokjes-modal) |
| `server/lib/blocks.json` | Blokjesregister (JS en PHP delen dit bestand) |
| `server/lib/Blocks.php` | Server-kant van het register en de drempels |
| `src/rng.js` | Seedable RNG (tests en later replays) |
| `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |
| `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |
@@ -111,6 +115,30 @@ staan in `server/lib/planets.json`. De blokplaatjes zijn unieke
placeholders (`build/images/block-{planeet}-{kleur}.png`); Tim kan ze
zelf vervangen.
## Planeetontwerper
Ingelogde spelers zien op het hoofdmenu hun puntentotaal en de knop
**Planeetontwerper**. Punten verzamel je door ingelogd te spelen
(solo aan het einde, elke ronde van Offline Strijd, en Online bij
uitschakeling). Ze worden niet uitgegeven: bij vaste drempels (Terra
gratis, daarna 500 punten en elke volgende 14,5 % hoger) ontgrendel
je extra blokjes.
In de ontwerper maak, bewerk of verwijder je eigen planeten (naam,
bevolking, de drie sliders voor zwaartekracht / lucht / massa, en
een live Power-preview met dezelfde formule als in het spel). Vijf
blokjesvakjes openen een raster van het hele register: blokjes die
al in een ander vak zitten zijn grijs, vergrendelde blokjes zijn
grijs mét een slotje.
Eigen planeten kun je in **elke** modus kiezen (Spelen, Offline
Strijd, Online). Online valideert de server de configuratie en
deelt een snapshot met de andere spelers.
Lokaal inloggen: `auth.php?test=1`. Op de live site blijft de
ontwerper verborgen tot OAuth (`callback.php` + CI-geheim
`auth_client_secret`) is ingesteld.
## Deploy
BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.
@@ -56,6 +56,10 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2| Pad | Rol || Pad | Rol || --- | --- || --- | --- || `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power, apex-ease, bounce || `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power, apex-ease, bounce || `src/blocks.js` | Append-only blokjesregister, drempels, ontgrendeling || `src/designer.js` | Planeetontwerper (lijst, bewerken, blokjes-modal) || `server/lib/blocks.json` | Blokjesregister (JS en PHP delen dit bestand) || `server/lib/Blocks.php` | Server-kant van het register en de drempels || `src/rng.js` | Seedable RNG (tests en later replays) || `src/rng.js` | Seedable RNG (tests en later replays) || `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie || `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie || `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` || `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |@@ -111,6 +115,30 @@ staan in `server/lib/planets.json`. De blokplaatjes zijn uniekeplaceholders (`build/images/block-{planeet}-{kleur}.png`); Tim kan zeplaceholders (`build/images/block-{planeet}-{kleur}.png`); Tim kan zezelf vervangen.zelf vervangen.## PlaneetontwerperIngelogde spelers zien op het hoofdmenu hun puntentotaal en de knop**Planeetontwerper**. Punten verzamel je door ingelogd te spelen(solo aan het einde, elke ronde van Offline Strijd, en Online bijuitschakeling). Ze worden niet uitgegeven: bij vaste drempels (Terragratis, daarna 500 punten en elke volgende 14,5 % hoger) ontgrendelje extra blokjes.In de ontwerper maak, bewerk of verwijder je eigen planeten (naam,bevolking, de drie sliders voor zwaartekracht / lucht / massa, eneen live Power-preview met dezelfde formule als in het spel). Vijfblokjesvakjes openen een raster van het hele register: blokjes dieal in een ander vak zitten zijn grijs, vergrendelde blokjes zijngrijs mét een slotje.Eigen planeten kun je in **elke** modus kiezen (Spelen, OfflineStrijd, Online). Online valideert de server de configuratie endeelt een snapshot met de andere spelers.Lokaal inloggen: `auth.php?test=1`. Op de live site blijft deontwerper verborgen tot OAuth (`callback.php` + CI-geheim`auth_client_secret`) is ingesteld.## Deploy## DeployBlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.BlueGit CI (`blue-ci-cd.yml`) draait tests en een build op feature-branches en op `master`. Op `master` volgt daarna `ftp_upload`: `build/` gaat via FTP naar `projectftp` (secret: `$timftproot/meteors`; de job expandeert `$timftproot` zelf en normaliseert dubbele slashes). **Geen `--delete`**. De eerste deploy weigert te schrijven als de doelmap al vreemde bestanden bevat.@@ -187,6 +187,839 @@ var PLANET_CATALOG = {
]
}
;
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
}
]
}
;
/*
* Start File:
@@ -353,6 +1186,34 @@ function loadCatalog ()
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({
@@ -364,6 +1225,10 @@ function planetFromData (data)
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;
}
@@ -375,6 +1240,8 @@ function allPlanets ()
{ 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;
}
@@ -386,9 +1253,30 @@ function planetById (id)
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();
@@ -415,6 +1303,11 @@ function spriteKey (planet, colorIndex)
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));
}
@@ -512,6 +1405,12 @@ var Planet = {
defaultPlanet: defaultPlanet,
defaultColors: defaultColors,
allPlanets: allPlanets,
officialPlanets: officialPlanets,
customPlanets: customPlanets,
pickerPlanets: pickerPlanets,
setCustomPlanets: setCustomPlanets,
rememberPlanet: rememberPlanet,
forgetRemembered: forgetRemembered,
planetById: planetById,
planetFromData: planetFromData,
formatStats: formatStats,
@@ -528,13 +1427,183 @@ var Planet = {
};
if (typeof module !== 'undefined' && module.exports)
{ module.exports = Planet; }
{ 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.Planet = Planet; }
{ globalThis.Blocks = Blocks; }
/*
* End File:
* /workspace/meteors/src/planet.js
* /workspace/meteors/src/blocks.js
*/
/*
@@ -4074,6 +5143,10 @@ var Online = {
local: false,
csrf: '',
me: null,
lifetimePoints: 0,
locale: null,
blocks: [],
planets: [],
lobby: null,
incoming: [],
shotResults: [],
@@ -4125,6 +5198,26 @@ Online._apply = function (data)
{ this.error = data.error; }
else if (data.ok)
{ this.error = ''; }
if (data.lifetime_points != null)
{ this.lifetimePoints = data.lifetime_points; }
if (data.locale !== undefined)
{ this.locale = data.locale; }
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)
@@ -4196,6 +5289,31 @@ 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 });
};
Online.setLocale = function (locale)
{
return this.request('set_locale', { locale: locale });
};
Online.leaveLobby = function ()
{
return this.request('lobby_leave');
@@ -6444,6 +7562,545 @@ if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undef
* /workspace/meteors/src/offline.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 = 'Je hebt nog geen eigen planeten. Maak er een aan.';
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 += '<img src="' + Designer.esc(colors[c].image) + '" alt="'
+ Designer.esc(colors[c].name) + '">';
}
var stats = (typeof Planet !== 'undefined' && Planet.formatStats)
? Planet.formatStats(pl) : '';
card.innerHTML = '<div class="planet-title">' + Designer.esc(pl.name) + '</div>'
+ '<div class="planet-people">' + Designer.esc(pl.people) + '</div>'
+ '<div class="planet-nums">' + Designer.esc(stats) + '</div>'
+ '<div class="planet-swatches">' + swatches + '</div>'
+ '<div class="designer-card-actions">'
+ '<button type="button" class="btn-tiny" data-edit>Bewerken</button>'
+ '<button type="button" class="btn-tiny btn-danger-lite" data-del>Verwijderen</button>'
+ '</div>';
(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;
if (!window.confirm('Wil je de planeet “' + name + '” verwijderen?'))
{ return; }
Online.deletePlanet(id).then(function (data)
{
if (!data || !data.ok)
{
window.alert((data && data.error) || 'Verwijderen is mislukt.');
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(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 = 'Planeet bewerken';
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 = 'Nieuwe planeet';
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, 1, 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 || 'Nieuwe planeet').trim() || 'Nieuwe planeet',
people: (document.getElementById('des-people').value || 'Volk').trim() || 'Volk',
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;
setText('des-gravity-val', Number(document.getElementById('des-gravity').value).toFixed(1)
+ (d ? ' · g ' + d.gravity.toFixed(2) : ''));
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', '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', 'Blokje ' + (i + 1));
if (b)
{
btn.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="' + Designer.esc(b.name) + '">'
+ '<span>' + Designer.esc(b.name) + '</span>';
}
else
{
btn.innerHTML = '<span class="des-slot-empty">Kies</span>';
}
(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 title = b.name;
if (locked)
{ title += ' — ' + b.threshold + ' punten nodig'; }
else if (taken)
{ title += ' — al in een ander vak'; }
cell.title = title;
cell.setAttribute('aria-label', title);
cell.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="">'
+ (locked ? '<span class="des-lock" aria-hidden="true">'
+ '<svg viewBox="0 0 18 18" width="16" height="16">'
+ '<rect x="4" y="8" width="10" height="8" rx="1.5" fill="#ffe27a"/>'
+ '<path d="M6 8 V6 a3 3 0 0 1 6 0 v2" fill="none" stroke="#ffe27a" stroke-width="1.8" stroke-linecap="round"/>'
+ '<circle cx="9" cy="12" r="1.2" fill="#1a1628"/>'
+ '</svg></span>' : '')
+ '<span class="des-block-name">' + Designer.esc(b.name) + '</span>'
+ (locked ? '<span class="des-block-need">' + b.threshold + '</span>' : '');
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('Vul een naam voor de planeet en voor de bevolking in.');
return;
}
for (var i = 0; i < 5; i++)
{
if (!Designer.slots[i])
{
window.alert('Kies vijf blokjes.');
return;
}
}
var payload = {
id: Designer.editingId || undefined,
name: name,
people: people,
jumpsToClear: clampNum(document.getElementById('des-gravity').value, 1, 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) || 'Opslaan is mislukt.');
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, '>')
.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/main.js
@@ -6486,6 +8143,12 @@ function planetImages ()
});
}
}
if (typeof Blocks !== 'undefined' && Blocks.images)
{
var extra = Blocks.images();
for (var b = 0; b < extra.length; b++)
{ list.push(extra[b]); }
}
return list;
}
@@ -6560,6 +8223,20 @@ window.onload = function ()
bindOfflineUi();
bindPlanetSelect();
restoreSelectedPlanet();
if (typeof Designer !== 'undefined' && Designer.bind)
{ Designer.bind(); }
if (typeof Online !== 'undefined' && Online.refresh)
{
Online.refresh().then(function ()
{
refreshMenuAccount();
restoreSelectedPlanet();
renderPlanetGrid('planet-grid', false);
renderPlanetGrid('lobby-planet-grid', true);
});
}
else
{ refreshMenuAccount(); }
};
function onPlay ()
@@ -6579,6 +8256,10 @@ function startPlay (opts)
hideEl('podium');
hideEl('planet-select');
hideEl('offline-result');
hideEl('designer');
hideEl('designer-edit');
if (typeof Designer !== 'undefined' && Designer.closeModal)
{ Designer.closeModal(); }
showEl('hud');
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
@@ -6642,6 +8323,8 @@ function startPlay (opts)
buildColumnWarn();
refreshOfflineHud();
refreshChainIndicator();
if (!opts.online)
{ beginPlaySession(opts.offline ? 'offline' : 'solo'); }
}
function teardownPlay ()
@@ -7234,7 +8917,10 @@ function tickView (dt)
else if (app.offline)
{ /* Offline result is shown from tickOffline. */ }
else
{ showEl('game-over'); }
{
showEl('game-over');
finishPlaySession(app.lastScore);
}
}
if (!app.online && !app.offline && app.core.state === 'gameover'
&& app.core.gameOverTime >= GAME_OVER_DELAY)
@@ -7845,6 +9531,8 @@ function startNextOfflineRound ()
// 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;
@@ -7870,6 +9558,7 @@ function showOfflineResult ()
}
hideEl('game-over');
showEl('offline-result');
finishPlaySession(app.core ? app.core.score : 0);
}
function refreshOfflineHud ()
@@ -8181,10 +9870,18 @@ 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 && me.planet.id)
{ planet = Planet.planetById(me.planet.id); }
startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
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; }
}
startPlay({ online: true, planet: planet, missChance: miss });
if (typeof Online !== 'undefined')
{ Online.startPolling(onlinePayload); }
}
@@ -8562,19 +10259,22 @@ function renderPlanetGrid (containerId, compact)
var pl = all[i];
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
+ (pl.custom ? ' custom' : '');
btn.setAttribute('role', 'listitem');
btn.dataset.planet = pl.id;
var swatches = '';
for (var c = 0; c < pl.colors.length; c++)
var colors = pl.colors || [];
for (var c = 0; c < colors.length; c++)
{
swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
+ escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
+ escapeText(colors[c].name) + '" title="' + escapeText(colors[c].name) + '">';
}
btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
+ '<div class="planet-people">' + escapeText(pl.people) + '</div>'
+ '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
+ '<div class="planet-swatches">' + swatches + '</div>';
+ '<div class="planet-swatches">' + swatches + '</div>'
+ (pl.custom ? '<span class="custom-badge">Eigen</span>' : '');
btn.addEventListener('click', (function (id, isCompact)
{
return function ()
@@ -8636,6 +10336,67 @@ function bindPlanetSelect ()
}
}
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 || 'speler'; }
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); }
}
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; }
});
}
function finishPlaySession (score)
{
var token = app.playToken;
app.playToken = null;
if (!token || typeof Online === 'undefined' || !Online.playFinish)
{ return; }
Online.playFinish(token, score || 0).then(function ()
{ refreshMenuAccount(); });
}
/*
* End File:
* /workspace/meteors/src/main.js
@@ -187,6 +187,839 @@ var PLANET_CATALOG = { ] ]}};;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 } ]};/*/* * Start File: * Start File:@@ -353,6 +1186,34 @@ function loadCatalog () return { planets: [] }; 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)function planetFromData (data){{ var planet = createPlanet({ var planet = createPlanet({@@ -364,6 +1225,10 @@ function planetFromData (data) colors: data.colors colors: data.colors }); }); planet.id = data.id; planet.id = data.id; if (data.custom) { planet.custom = true; } if (data.owner_id) { planet.owner_id = data.owner_id; } return planet; return planet;}}@@ -375,6 +1240,8 @@ function allPlanets () { out.push(planetFromData(raw[i])); } { out.push(planetFromData(raw[i])); } if (out.length === 0) if (out.length === 0) { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; } { 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; return out;}}@@ -386,9 +1253,30 @@ function planetById (id) if (all[i].id === id) if (all[i].id === id) { return all[i]; } { return all[i]; } } } if (id && _remembered[id]) { return _remembered[id]; } return defaultPlanet(); 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 ()function defaultPlanet (){{ var all = allPlanets(); var all = allPlanets();@@ -415,6 +1303,11 @@ function spriteKey (planet, colorIndex) var c = colors && colors[colorIndex]; var c = colors && colors[colorIndex]; if (!c) if (!c) { return 'gray'; } { 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)); return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));}}@@ -512,6 +1405,12 @@ var Planet = { defaultPlanet: defaultPlanet, defaultPlanet: defaultPlanet, defaultColors: defaultColors, defaultColors: defaultColors, allPlanets: allPlanets, allPlanets: allPlanets, officialPlanets: officialPlanets, customPlanets: customPlanets, pickerPlanets: pickerPlanets, setCustomPlanets: setCustomPlanets, rememberPlanet: rememberPlanet, forgetRemembered: forgetRemembered, planetById: planetById, planetById: planetById, planetFromData: planetFromData, planetFromData: planetFromData, formatStats: formatStats, formatStats: formatStats,@@ -528,13 +1427,183 @@ var Planet = {};};if (typeof module !== 'undefined' && module.exports)if (typeof module !== 'undefined' && module.exports){ module.exports = Planet; }{ 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')else if (typeof globalThis !== 'undefined'){ globalThis.Planet = Planet; }{ globalThis.Blocks = Blocks; }/*/* * End File: * End File: * /workspace/meteors/src/planet.js * /workspace/meteors/src/blocks.js */ */ /*/*@@ -4074,6 +5143,10 @@ var Online = { local: false, local: false, csrf: '', csrf: '', me: null, me: null, lifetimePoints: 0, locale: null, blocks: [], planets: [], lobby: null, lobby: null, incoming: [], incoming: [], shotResults: [], shotResults: [],@@ -4125,6 +5198,26 @@ Online._apply = function (data) { this.error = data.error; } { this.error = data.error; } else if (data.ok) else if (data.ok) { this.error = ''; } { this.error = ''; } if (data.lifetime_points != null) { this.lifetimePoints = data.lifetime_points; } if (data.locale !== undefined) { this.locale = data.locale; } 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)Online.request = function (action, body)@@ -4196,6 +5289,31 @@ Online.setPlanet = function (planetId) return this.request('lobby_set_planet', { planet_id: 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 });};Online.setLocale = function (locale){ return this.request('set_locale', { locale: locale });};Online.leaveLobby = function ()Online.leaveLobby = function (){{ return this.request('lobby_leave'); return this.request('lobby_leave');@@ -6444,6 +7562,545 @@ if (typeof module !== 'undefined' && module.exports && typeof Offline !== 'undef * /workspace/meteors/src/offline.js * /workspace/meteors/src/offline.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 = 'Je hebt nog geen eigen planeten. Maak er een aan.'; 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 += '<img src="' + Designer.esc(colors[c].image) + '" alt="' + Designer.esc(colors[c].name) + '">'; } var stats = (typeof Planet !== 'undefined' && Planet.formatStats) ? Planet.formatStats(pl) : ''; card.innerHTML = '<div class="planet-title">' + Designer.esc(pl.name) + '</div>' + '<div class="planet-people">' + Designer.esc(pl.people) + '</div>' + '<div class="planet-nums">' + Designer.esc(stats) + '</div>' + '<div class="planet-swatches">' + swatches + '</div>' + '<div class="designer-card-actions">' + '<button type="button" class="btn-tiny" data-edit>Bewerken</button>' + '<button type="button" class="btn-tiny btn-danger-lite" data-del>Verwijderen</button>' + '</div>'; (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; if (!window.confirm('Wil je de planeet “' + name + '” verwijderen?')) { return; } Online.deletePlanet(id).then(function (data) { if (!data || !data.ok) { window.alert((data && data.error) || 'Verwijderen is mislukt.'); 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(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 = 'Planeet bewerken'; 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 = 'Nieuwe planeet'; 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, 1, 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 || 'Nieuwe planeet').trim() || 'Nieuwe planeet', people: (document.getElementById('des-people').value || 'Volk').trim() || 'Volk', 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; setText('des-gravity-val', Number(document.getElementById('des-gravity').value).toFixed(1) + (d ? ' · g ' + d.gravity.toFixed(2) : '')); 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', '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', 'Blokje ' + (i + 1)); if (b) { btn.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="' + Designer.esc(b.name) + '">' + '<span>' + Designer.esc(b.name) + '</span>'; } else { btn.innerHTML = '<span class="des-slot-empty">Kies</span>'; } (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 title = b.name; if (locked) { title += ' — ' + b.threshold + ' punten nodig'; } else if (taken) { title += ' — al in een ander vak'; } cell.title = title; cell.setAttribute('aria-label', title); cell.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="">' + (locked ? '<span class="des-lock" aria-hidden="true">' + '<svg viewBox="0 0 18 18" width="16" height="16">' + '<rect x="4" y="8" width="10" height="8" rx="1.5" fill="#ffe27a"/>' + '<path d="M6 8 V6 a3 3 0 0 1 6 0 v2" fill="none" stroke="#ffe27a" stroke-width="1.8" stroke-linecap="round"/>' + '<circle cx="9" cy="12" r="1.2" fill="#1a1628"/>' + '</svg></span>' : '') + '<span class="des-block-name">' + Designer.esc(b.name) + '</span>' + (locked ? '<span class="des-block-need">' + b.threshold + '</span>' : ''); 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('Vul een naam voor de planeet en voor de bevolking in.'); return; } for (var i = 0; i < 5; i++) { if (!Designer.slots[i]) { window.alert('Kies vijf blokjes.'); return; } } var payload = { id: Designer.editingId || undefined, name: name, people: people, jumpsToClear: clampNum(document.getElementById('des-gravity').value, 1, 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) || 'Opslaan is mislukt.'); 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, '>') .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: * Start File: * /workspace/meteors/src/main.js * /workspace/meteors/src/main.js@@ -6486,6 +8143,12 @@ function planetImages () }); }); } } } } if (typeof Blocks !== 'undefined' && Blocks.images) { var extra = Blocks.images(); for (var b = 0; b < extra.length; b++) { list.push(extra[b]); } } return list; return list;}}@@ -6560,6 +8223,20 @@ window.onload = function () bindOfflineUi(); bindOfflineUi(); bindPlanetSelect(); bindPlanetSelect(); restoreSelectedPlanet(); restoreSelectedPlanet(); if (typeof Designer !== 'undefined' && Designer.bind) { Designer.bind(); } if (typeof Online !== 'undefined' && Online.refresh) { Online.refresh().then(function () { refreshMenuAccount(); restoreSelectedPlanet(); renderPlanetGrid('planet-grid', false); renderPlanetGrid('lobby-planet-grid', true); }); } else { refreshMenuAccount(); }};};function onPlay ()function onPlay ()@@ -6579,6 +8256,10 @@ function startPlay (opts) hideEl('podium'); hideEl('podium'); hideEl('planet-select'); hideEl('planet-select'); hideEl('offline-result'); hideEl('offline-result'); hideEl('designer'); hideEl('designer-edit'); if (typeof Designer !== 'undefined' && Designer.closeModal) { Designer.closeModal(); } showEl('hud'); showEl('hud'); var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod; var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;@@ -6642,6 +8323,8 @@ function startPlay (opts) buildColumnWarn(); buildColumnWarn(); refreshOfflineHud(); refreshOfflineHud(); refreshChainIndicator(); refreshChainIndicator(); if (!opts.online) { beginPlaySession(opts.offline ? 'offline' : 'solo'); }}}function teardownPlay ()function teardownPlay ()@@ -7234,7 +8917,10 @@ function tickView (dt) else if (app.offline) else if (app.offline) { /* Offline result is shown from tickOffline. */ } { /* Offline result is shown from tickOffline. */ } else else { showEl('game-over'); } { showEl('game-over'); finishPlaySession(app.lastScore); } } } if (!app.online && !app.offline && app.core.state === 'gameover' if (!app.online && !app.offline && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY) && app.core.gameOverTime >= GAME_OVER_DELAY)@@ -7845,6 +9531,8 @@ function startNextOfflineRound () // Tear down the current scene then start a fresh player field, // Tear down the current scene then start a fresh player field, // keeping the same battle (already advanced). // keeping the same battle (already advanced). var planet = app.battle.playerPlanet; var planet = app.battle.playerPlanet; var roundScore = app.core ? app.core.score : 0; finishPlaySession(roundScore); app._keepBattleOnTeardown = true; app._keepBattleOnTeardown = true; teardownPlay(); teardownPlay(); app.offline = true; app.offline = true;@@ -7870,6 +9558,7 @@ function showOfflineResult () } } hideEl('game-over'); hideEl('game-over'); showEl('offline-result'); showEl('offline-result'); finishPlaySession(app.core ? app.core.score : 0);}}function refreshOfflineHud ()function refreshOfflineHud ()@@ -8181,10 +9870,18 @@ function startOnlineMatch () if (app.mode === 'playing' && app.online) if (app.mode === 'playing' && app.online) { return; } { return; } var planet = Planet.planetById(selectedPlanetId()); var planet = Planet.planetById(selectedPlanetId()); var miss = Planet.missChance(planet); var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null; var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null; if (me && me.planet && me.planet.id) if (me && me.planet) { planet = Planet.planetById(me.planet.id); } { startPlay({ online: true, planet: planet, missChance: Planet.missChance(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; } } startPlay({ online: true, planet: planet, missChance: miss }); if (typeof Online !== 'undefined') if (typeof Online !== 'undefined') { Online.startPolling(onlinePayload); } { Online.startPolling(onlinePayload); }}}@@ -8562,19 +10259,22 @@ function renderPlanetGrid (containerId, compact) var pl = all[i]; var pl = all[i]; var btn = document.createElement('button'); var btn = document.createElement('button'); btn.type = 'button'; btn.type = 'button'; btn.className = 'planet-card' + (pl.id === current ? ' selected' : ''); btn.className = 'planet-card' + (pl.id === current ? ' selected' : '') + (pl.custom ? ' custom' : ''); btn.setAttribute('role', 'listitem'); btn.setAttribute('role', 'listitem'); btn.dataset.planet = pl.id; btn.dataset.planet = pl.id; var swatches = ''; var swatches = ''; for (var c = 0; c < pl.colors.length; c++) var colors = pl.colors || []; for (var c = 0; c < colors.length; c++) { { swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="' swatches += '<img src="' + escapeText(colors[c].image) + '" alt="' + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">'; + escapeText(colors[c].name) + '" title="' + escapeText(colors[c].name) + '">'; } } btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>' btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>' + '<div class="planet-people">' + escapeText(pl.people) + '</div>' + '<div class="planet-people">' + escapeText(pl.people) + '</div>' + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>' + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>' + '<div class="planet-swatches">' + swatches + '</div>'; + '<div class="planet-swatches">' + swatches + '</div>' + (pl.custom ? '<span class="custom-badge">Eigen</span>' : ''); btn.addEventListener('click', (function (id, isCompact) btn.addEventListener('click', (function (id, isCompact) { { return function () return function ()@@ -8636,6 +10336,67 @@ function bindPlanetSelect () } }}}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 || 'speler'; } 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); }}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; } });}function finishPlaySession (score){ var token = app.playToken; app.playToken = null; if (!token || typeof Online === 'undefined' || !Online.playFinish) { return; } Online.playFinish(token, score || 0).then(function () { refreshMenuAccount(); });}/*/* * End File: * End File: * /workspace/meteors/src/main.js * /workspace/meteors/src/main.jsThe contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -21,8 +21,24 @@
<button type="button" id="btn-play">Spelen</button>
<button type="button" id="btn-offline" class="btn-secondary">Offline Strijd</button>
<button type="button" id="btn-online" class="btn-secondary">Online spelen</button>
<button type="button" id="btn-designer" class="btn-secondary" hidden>Planeetontwerper</button>
<p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
<p class="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.</p>
<div id="menu-account" class="menu-account">
<p id="menu-guest">
<a id="menu-login" href="auth.php">Inloggen</a>
<span id="menu-local-login" hidden>
· lokale test:
<a href="auth.php?test=1">test_user_1</a> ·
<a href="auth.php?test=2">test_user_2</a>
</span>
</p>
<p id="menu-user" hidden>
Ingelogd als <strong id="menu-name"></strong>
· Totaal: <strong id="menu-points">0</strong> punten
· <a id="menu-logout" href="logout.php">Uitloggen</a>
</p>
</div>
</div>
<div id="planet-select" class="screen" hidden>
@@ -85,6 +101,63 @@
</div>
</div>
<div id="designer" class="screen" hidden>
<h1>Planeetontwerper</h1>
<p class="tagline">Totaal: <strong id="designer-points">0</strong> punten. Blokjes ontgrendel je door punten te verdienen — je geeft ze niet uit.</p>
<div id="designer-list" class="planet-grid" role="list"></div>
<div class="planet-actions">
<button type="button" id="btn-designer-new">Nieuwe planeet</button>
<button type="button" id="btn-designer-back" class="btn-secondary">Terug</button>
</div>
</div>
<div id="designer-edit" class="screen" hidden>
<h1 id="designer-edit-title">Nieuwe planeet</h1>
<form id="designer-form" class="designer-form" action="javascript:void(0)">
<label class="des-field">
<span>Naam van de planeet</span>
<input id="des-name" type="text" maxlength="32" autocomplete="off" required>
</label>
<label class="des-field">
<span>Naam van de bevolking</span>
<input id="des-people" type="text" maxlength="32" autocomplete="off" required>
</label>
<label class="des-field des-slider">
<span>Zwaartekracht</span>
<input id="des-gravity" type="range" min="1" max="4" step="0.1" value="2">
<span id="des-gravity-val" class="des-val"></span>
</label>
<label class="des-field des-slider">
<span>Luchtweerstand</span>
<input id="des-air" type="range" min="1" max="5" step="0.1" value="3">
<span id="des-air-val" class="des-val"></span>
</label>
<label class="des-field des-slider">
<span>Massa</span>
<input id="des-mass" type="range" min="0.5" max="3" step="0.1" value="1.5">
<span id="des-mass-val" class="des-val"></span>
</label>
<div id="des-power" class="des-power">Power 0%</div>
<p class="hint">Kies vijf blokjes. Klik op een vak om te wisselen.</p>
<div id="des-slots" class="des-slots"></div>
<div class="planet-actions">
<button type="submit" id="btn-designer-save">Opslaan</button>
<button type="button" id="btn-designer-delete" class="btn-secondary" hidden>Verwijderen</button>
<button type="button" id="btn-designer-cancel" class="btn-secondary">Terug</button>
</div>
</form>
</div>
<div id="des-modal" class="des-modal" hidden aria-hidden="true" role="dialog" aria-labelledby="des-modal-title">
<div class="des-modal-card">
<div class="des-modal-head">
<h2 id="des-modal-title">Kies een blokje</h2>
<button type="button" id="des-modal-close" class="btn-tiny">Sluiten</button>
</div>
<div id="des-modal-grid" class="des-block-grid"></div>
</div>
</div>
<div id="minis" hidden></div>
<div id="hud" hidden>
@@ -21,8 +21,24 @@ <button type="button" id="btn-play">Spelen</button> <button type="button" id="btn-play">Spelen</button> <button type="button" id="btn-offline" class="btn-secondary">Offline Strijd</button> <button type="button" id="btn-offline" class="btn-secondary">Offline Strijd</button> <button type="button" id="btn-online" class="btn-secondary">Online spelen</button> <button type="button" id="btn-online" class="btn-secondary">Online spelen</button> <button type="button" id="btn-designer" class="btn-secondary" hidden>Planeetontwerper</button> <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p> <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p> <p class="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.</p> <p class="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.</p> <div id="menu-account" class="menu-account"> <p id="menu-guest"> <a id="menu-login" href="auth.php">Inloggen</a> <span id="menu-local-login" hidden> · lokale test: <a href="auth.php?test=1">test_user_1</a> · <a href="auth.php?test=2">test_user_2</a> </span> </p> <p id="menu-user" hidden> Ingelogd als <strong id="menu-name"></strong> · Totaal: <strong id="menu-points">0</strong> punten · <a id="menu-logout" href="logout.php">Uitloggen</a> </p> </div> </div> </div> <div id="planet-select" class="screen" hidden> <div id="planet-select" class="screen" hidden>@@ -85,6 +101,63 @@ </div> </div> </div> </div> <div id="designer" class="screen" hidden> <h1>Planeetontwerper</h1> <p class="tagline">Totaal: <strong id="designer-points">0</strong> punten. Blokjes ontgrendel je door punten te verdienen — je geeft ze niet uit.</p> <div id="designer-list" class="planet-grid" role="list"></div> <div class="planet-actions"> <button type="button" id="btn-designer-new">Nieuwe planeet</button> <button type="button" id="btn-designer-back" class="btn-secondary">Terug</button> </div> </div> <div id="designer-edit" class="screen" hidden> <h1 id="designer-edit-title">Nieuwe planeet</h1> <form id="designer-form" class="designer-form" action="javascript:void(0)"> <label class="des-field"> <span>Naam van de planeet</span> <input id="des-name" type="text" maxlength="32" autocomplete="off" required> </label> <label class="des-field"> <span>Naam van de bevolking</span> <input id="des-people" type="text" maxlength="32" autocomplete="off" required> </label> <label class="des-field des-slider"> <span>Zwaartekracht</span> <input id="des-gravity" type="range" min="1" max="4" step="0.1" value="2"> <span id="des-gravity-val" class="des-val"></span> </label> <label class="des-field des-slider"> <span>Luchtweerstand</span> <input id="des-air" type="range" min="1" max="5" step="0.1" value="3"> <span id="des-air-val" class="des-val"></span> </label> <label class="des-field des-slider"> <span>Massa</span> <input id="des-mass" type="range" min="0.5" max="3" step="0.1" value="1.5"> <span id="des-mass-val" class="des-val"></span> </label> <div id="des-power" class="des-power">Power 0%</div> <p class="hint">Kies vijf blokjes. Klik op een vak om te wisselen.</p> <div id="des-slots" class="des-slots"></div> <div class="planet-actions"> <button type="submit" id="btn-designer-save">Opslaan</button> <button type="button" id="btn-designer-delete" class="btn-secondary" hidden>Verwijderen</button> <button type="button" id="btn-designer-cancel" class="btn-secondary">Terug</button> </div> </form> </div> <div id="des-modal" class="des-modal" hidden aria-hidden="true" role="dialog" aria-labelledby="des-modal-title"> <div class="des-modal-card"> <div class="des-modal-head"> <h2 id="des-modal-title">Kies een blokje</h2> <button type="button" id="des-modal-close" class="btn-tiny">Sluiten</button> </div> <div id="des-modal-grid" class="des-block-grid"></div> </div> </div> <div id="minis" hidden></div> <div id="minis" hidden></div> <div id="hud" hidden> <div id="hud" hidden>@@ -46,7 +46,7 @@ html, body {
text-align: center;
}
.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden] { display: none !important; }
.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden], #designer[hidden], #designer-edit[hidden] { display: none !important; }
h1 {
font-size: clamp(48px, 14vw, 96px);
@@ -208,11 +208,12 @@ a.button:is(:hover, :focus-visible) {
color: #fff6c8;
}
#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
#btn-play, #btn-planet-go {
#btn-play, #btn-planet-go, #btn-designer-new, #btn-designer-save {
/* play already styled */
}
#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate {
#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
#btn-designer-new, #btn-designer-save {
padding: 10px 28px;
font-size: clamp(16px, 4vw, 20px);
border: 0;
@@ -627,3 +628,237 @@ a.button:is(:hover, :focus-visible) {
@media (max-width: 520px) {
.hud-offline { font-size: 11px; bottom: 4px; }
}
/* —— t1139 Planet Designer + account chrome —— */
.menu-account {
margin-top: 1.2rem;
font-size: 0.9rem;
color: #c8c4d4;
}
.menu-account a { color: #ffe27a; }
.menu-account a:hover { color: #fff; }
#btn-designer {
display: block;
margin: 0.7rem auto 0;
}
#btn-designer[hidden] { display: none; }
#menu-user[hidden], #menu-guest[hidden], #menu-local-login[hidden],
#btn-designer-delete[hidden] { display: none; }
.designer-card { cursor: default; text-align: left; }
.designer-card-actions {
display: flex;
gap: 6px;
margin-top: 8px;
justify-content: center;
}
.btn-tiny {
font: inherit;
font-size: 0.85rem;
padding: 6px 10px;
border-radius: 8px;
border: 1px solid #5a5470;
background: #2a2540;
color: #eee;
cursor: pointer;
min-height: 36px;
}
.btn-tiny:hover, .btn-tiny:focus-visible { background: #3a3555; border-color: #ffe27a; }
.btn-danger-lite { color: #ffb4b4; }
.designer-form {
max-width: 28rem;
margin: 0 auto;
display: flex;
flex-direction: column;
gap: 0.7rem;
text-align: left;
}
.des-field { display: flex; flex-direction: column; gap: 4px; }
.des-field > span:first-child { font-weight: 600; color: #ddd; }
.des-field input[type="text"] {
font: inherit;
padding: 8px 10px;
border-radius: 8px;
border: 1px solid #5a5470;
background: #1a1628;
color: #fff;
min-height: 40px;
}
.des-slider input[type="range"] { width: 100%; min-height: 32px; }
.des-val, .des-power {
font-variant-numeric: tabular-nums;
color: #ffe27a;
font-weight: 700;
}
.des-power {
font-size: 1.25rem;
text-align: center;
margin: 0.2rem 0;
}
.des-slots {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 8px;
}
.des-slot {
font: inherit;
background: #1a1628;
border: 1px solid #5a5470;
border-radius: 10px;
padding: 8px 4px;
cursor: pointer;
color: #eee;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
min-height: 88px;
}
.des-slot img { width: 48px; height: 48px; image-rendering: pixelated; }
.des-slot span { font-size: 0.7rem; text-align: center; line-height: 1.15; }
.des-slot:hover, .des-slot:focus-visible { border-color: #ffe27a; background: #2a2540; }
.des-modal {
position: fixed;
inset: 0;
background: rgba(8, 6, 16, 0.78);
z-index: 40;
display: flex;
align-items: flex-start;
justify-content: center;
padding: 12px;
overflow: auto;
}
.des-modal[hidden] { display: none !important; }
.des-modal-card {
background: #161226;
border: 1px solid #5a5470;
border-radius: 14px;
padding: 14px 14px 18px;
max-width: 56rem;
width: 100%;
margin: 1.5rem auto 3rem;
box-shadow: 0 12px 40px rgba(0,0,0,0.5);
}
.des-modal-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.des-modal-head h2 { margin: 0; font-size: 1.2rem; }
.des-block-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(76px, 1fr));
gap: 8px;
}
.des-block {
position: relative;
font: inherit;
background: #1a1628;
border: 1px solid #5a5470;
border-radius: 10px;
padding: 6px 4px 8px;
cursor: pointer;
color: #eee;
display: flex;
flex-direction: column;
align-items: center;
gap: 3px;
min-height: 92px;
}
.des-block img { width: 48px; height: 48px; image-rendering: pixelated; }
.des-block-name {
font-size: 0.65rem;
text-align: center;
line-height: 1.15;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
.des-block:hover:not(:disabled), .des-block:focus-visible:not(:disabled) {
border-color: #ffe27a;
background: #2a2540;
}
.des-block.current { outline: 2px solid #ffe27a; }
.des-block.used img, .des-block.locked img,
.des-block.used .des-block-name, .des-block.locked .des-block-name {
opacity: 0.42;
filter: grayscale(1);
}
.des-block.used, .des-block.locked {
cursor: not-allowed;
}
.des-block-need {
font-size: 0.6rem;
color: #ffe27a;
opacity: 0.9;
}
.des-lock {
position: absolute;
top: 2px;
right: 2px;
width: 22px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
background: rgba(16, 12, 28, 0.92);
border-radius: 5px;
pointer-events: none;
z-index: 2;
box-shadow: 0 0 0 1px rgba(255, 226, 122, 0.35);
}
.des-lock svg { display: block; }
.planet-card.custom { position: relative; }
.planet-card .custom-badge {
position: absolute;
top: 6px;
right: 6px;
font-size: 0.65rem;
background: #3a2a10;
color: #ffe27a;
border: 1px solid #ffe27a;
border-radius: 999px;
padding: 1px 6px;
letter-spacing: 0.02em;
}
@media (max-width: 520px) {
.des-slots { grid-template-columns: repeat(5, 1fr); gap: 4px; }
.des-slot { min-height: 76px; padding: 4px 2px; }
.des-slot img, .des-block img { width: 36px; height: 36px; }
.des-block { min-height: 80px; }
.des-block-grid { grid-template-columns: repeat(auto-fill, minmax(64px, 1fr)); gap: 6px; }
.des-field input[type="text"], .btn-tiny { min-height: 44px; }
}
#designer, #designer-edit {
justify-content: flex-start;
overflow-y: auto;
touch-action: pan-y;
-webkit-overflow-scrolling: touch;
padding-top: 16px;
padding-bottom: 40px;
}
#designer h1, #designer-edit h1 {
font-size: clamp(28px, 8vw, 56px);
margin-bottom: 6px;
}
#designer .tagline, #designer-edit .tagline { margin-bottom: 12px; }
#designer-list {
width: min(1000px, 100%);
margin-bottom: 16px;
}
@media (max-width: 520px) {
#designer-edit .designer-form { gap: 0.45rem; }
.des-slots { margin-bottom: 8px; }
#designer-edit .planet-actions, #designer .planet-actions {
position: sticky;
bottom: 0;
padding-bottom: 8px;
background: linear-gradient(180deg, transparent, #0b1020 30%);
}
}
#designer-edit .hint, #designer .hint { margin: 8px auto 4px; }
#designer-edit .designer-form { max-width: 26rem; }
#designer-edit .planet-actions { margin-top: 12px; padding-bottom: 16px; }
@@ -46,7 +46,7 @@ html, body { text-align: center; text-align: center;}}.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden] { display: none !important; }.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #flights-back[hidden], #planet-select[hidden], #offline-result[hidden], #offline-hud[hidden], #chain-indicator[hidden], #designer[hidden], #designer-edit[hidden] { display: none !important; }h1 {h1 { font-size: clamp(48px, 14vw, 96px); font-size: clamp(48px, 14vw, 96px);@@ -208,11 +208,12 @@ a.button:is(:hover, :focus-visible) { color: #fff6c8; color: #fff6c8;}}#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,#btn-play, #btn-planet-go {#btn-play, #btn-planet-go, #btn-designer-new, #btn-designer-save { /* play already styled */ /* play already styled */}}#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate {#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,#btn-designer-new, #btn-designer-save { padding: 10px 28px; padding: 10px 28px; font-size: clamp(16px, 4vw, 20px); font-size: clamp(16px, 4vw, 20px); border: 0; border: 0;@@ -627,3 +628,237 @@ a.button:is(:hover, :focus-visible) {@media (max-width: 520px) {@media (max-width: 520px) { .hud-offline { font-size: 11px; bottom: 4px; } .hud-offline { font-size: 11px; bottom: 4px; }}}/* —— t1139 Planet Designer + account chrome —— */.menu-account { margin-top: 1.2rem; font-size: 0.9rem; color: #c8c4d4;}.menu-account a { color: #ffe27a; }.menu-account a:hover { color: #fff; }#btn-designer { display: block; margin: 0.7rem auto 0;}#btn-designer[hidden] { display: none; }#menu-user[hidden], #menu-guest[hidden], #menu-local-login[hidden],#btn-designer-delete[hidden] { display: none; }.designer-card { cursor: default; text-align: left; }.designer-card-actions { display: flex; gap: 6px; margin-top: 8px; justify-content: center;}.btn-tiny { font: inherit; font-size: 0.85rem; padding: 6px 10px; border-radius: 8px; border: 1px solid #5a5470; background: #2a2540; color: #eee; cursor: pointer; min-height: 36px;}.btn-tiny:hover, .btn-tiny:focus-visible { background: #3a3555; border-color: #ffe27a; }.btn-danger-lite { color: #ffb4b4; }.designer-form { max-width: 28rem; margin: 0 auto; display: flex; flex-direction: column; gap: 0.7rem; text-align: left;}.des-field { display: flex; flex-direction: column; gap: 4px; }.des-field > span:first-child { font-weight: 600; color: #ddd; }.des-field input[type="text"] { font: inherit; padding: 8px 10px; border-radius: 8px; border: 1px solid #5a5470; background: #1a1628; color: #fff; min-height: 40px;}.des-slider input[type="range"] { width: 100%; min-height: 32px; }.des-val, .des-power { font-variant-numeric: tabular-nums; color: #ffe27a; font-weight: 700;}.des-power { font-size: 1.25rem; text-align: center; margin: 0.2rem 0;}.des-slots { display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px;}.des-slot { font: inherit; background: #1a1628; border: 1px solid #5a5470; border-radius: 10px; padding: 8px 4px; cursor: pointer; color: #eee; display: flex; flex-direction: column; align-items: center; gap: 4px; min-height: 88px;}.des-slot img { width: 48px; height: 48px; image-rendering: pixelated; }.des-slot span { font-size: 0.7rem; text-align: center; line-height: 1.15; }.des-slot:hover, .des-slot:focus-visible { border-color: #ffe27a; background: #2a2540; }.des-modal { position: fixed; inset: 0; background: rgba(8, 6, 16, 0.78); z-index: 40; display: flex; align-items: flex-start; justify-content: center; padding: 12px; overflow: auto;}.des-modal[hidden] { display: none !important; }.des-modal-card { background: #161226; border: 1px solid #5a5470; border-radius: 14px; padding: 14px 14px 18px; max-width: 56rem; width: 100%; margin: 1.5rem auto 3rem; box-shadow: 0 12px 40px rgba(0,0,0,0.5);}.des-modal-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px;}.des-modal-head h2 { margin: 0; font-size: 1.2rem; }.des-block-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(76px, 1fr)); gap: 8px;}.des-block { position: relative; font: inherit; background: #1a1628; border: 1px solid #5a5470; border-radius: 10px; padding: 6px 4px 8px; cursor: pointer; color: #eee; display: flex; flex-direction: column; align-items: center; gap: 3px; min-height: 92px;}.des-block img { width: 48px; height: 48px; image-rendering: pixelated; }.des-block-name { font-size: 0.65rem; text-align: center; line-height: 1.15; overflow: hidden; text-overflow: ellipsis; max-width: 100%;}.des-block:hover:not(:disabled), .des-block:focus-visible:not(:disabled) { border-color: #ffe27a; background: #2a2540;}.des-block.current { outline: 2px solid #ffe27a; }.des-block.used img, .des-block.locked img,.des-block.used .des-block-name, .des-block.locked .des-block-name { opacity: 0.42; filter: grayscale(1);}.des-block.used, .des-block.locked { cursor: not-allowed;}.des-block-need { font-size: 0.6rem; color: #ffe27a; opacity: 0.9;}.des-lock { position: absolute; top: 2px; right: 2px; width: 22px; height: 22px; display: flex; align-items: center; justify-content: center; background: rgba(16, 12, 28, 0.92); border-radius: 5px; pointer-events: none; z-index: 2; box-shadow: 0 0 0 1px rgba(255, 226, 122, 0.35);}.des-lock svg { display: block; }.planet-card.custom { position: relative; }.planet-card .custom-badge { position: absolute; top: 6px; right: 6px; font-size: 0.65rem; background: #3a2a10; color: #ffe27a; border: 1px solid #ffe27a; border-radius: 999px; padding: 1px 6px; letter-spacing: 0.02em;}@media (max-width: 520px) { .des-slots { grid-template-columns: repeat(5, 1fr); gap: 4px; } .des-slot { min-height: 76px; padding: 4px 2px; } .des-slot img, .des-block img { width: 36px; height: 36px; } .des-block { min-height: 80px; } .des-block-grid { grid-template-columns: repeat(auto-fill, minmax(64px, 1fr)); gap: 6px; } .des-field input[type="text"], .btn-tiny { min-height: 44px; }}#designer, #designer-edit { justify-content: flex-start; overflow-y: auto; touch-action: pan-y; -webkit-overflow-scrolling: touch; padding-top: 16px; padding-bottom: 40px;}#designer h1, #designer-edit h1 { font-size: clamp(28px, 8vw, 56px); margin-bottom: 6px;}#designer .tagline, #designer-edit .tagline { margin-bottom: 12px; }#designer-list { width: min(1000px, 100%); margin-bottom: 16px;}@media (max-width: 520px) { #designer-edit .designer-form { gap: 0.45rem; } .des-slots { margin-bottom: 8px; } #designer-edit .planet-actions, #designer .planet-actions { position: sticky; bottom: 0; padding-bottom: 8px; background: linear-gradient(180deg, transparent, #0b1020 30%); }}#designer-edit .hint, #designer .hint { margin: 8px auto 4px; }#designer-edit .designer-form { max-width: 26rem; }#designer-edit .planet-actions { margin-top: 12px; padding-bottom: 16px; }@@ -763,3 +763,55 @@ Aanname:
uiteinden, corridors, en de fallSpeed-overdracht. Playwright
legt early/mid/late vast op 1024×532 en 1920×1080, plus een
webm van beide formaten.
## t1139 — Planeetontwerper
- De ontwerper is alleen beschikbaar op het hoofdmenu, en alleen als
je bent ingelogd. Tot de live OAuth-callback en het CI-geheim
`auth_client_secret` zijn ingericht, is dat op productie onzichtbaar.
Lokaal kun je inloggen met `auth.php?test=1` (of `test=2`).
- Levenslange punten staan in het server-profiel (`profiles`). Alleen
ingelogde spellen tellen mee. Bots leveren geen punten op.
- **Spelen** (solo): de score aan het einde van het spel.
- **Offline Strijd**: de score van **elke ronde**, gewonnen of
verloren, omdat de score per ronde opnieuw begint.
- **Online**: de server kent de score via de poll; punten worden
toegekend bij uitschakeling of als de lobby klaar is, één keer per
`online:{lobbyId}:{userId}`. De client kan hier geen punten
insturen.
- Anti-cheat voor solo/offline: `play_begin` geeft een eenmalig token
(geldig 6 uur). `play_finish` klempt de score op 0–10000, weigert
een positieve score als het spel korter dan 3 seconden duurde, en
laat maximaal 4 punten per seconde door. Herhaalde finishes van
hetzelfde token zijn een no-op. Overduidelijk valsspelen wordt
geklemd, niet keihard verboden, zodat een trage verbinding geen
eerlijke score weggooit.
- Het blokjesregister (`server/lib/blocks.json`) is append-only: de
volgorde ligt nu vast. Eerst Terra's vijf (gratis), daarna 43 nieuwe
icoontjes (eerste, Fehu, op 500 punten; daarna telkens 14,5 % meer,
afgerond en strikt stijgend — de laatste icoon zit rond de 147 000
punten), daarna de 55 kleuren van de officiële niet-Terra-planeten
als lange staart (de laatste zit in de honderden miljoenen). Punten
zijn een **eis**, geen uitgave. Officiële planeten blijven hun eigen
blokjes gebruiken zonder ontgrendeling; ontgrendelen is alleen voor
de ontwerper.
- Een speler mag tot 30 eigen planeten hebben. Id's zijn `c_` plus
16 hex-tekens. Namen (planeet en volk) zijn 1–32 tekens, zonder
tags. De vijf blokjes moeten verschillend en ontgrendeld zijn.
- Nieuwe blokjes-plaatjes staan in `build/images/block-*.png`, 64×64,
in dezelfde stijl als Terra (gekleurde silhouet, donkere omtrek,
highlight, slagschaduw). Gegenereerd door
`scripts/gen_unlock_blocks.py`.
## t1140 — Eigen planeten in elke modus
- In Spelen, Offline Strijd en Online Spelen toont de planeetkiezer
naast de officiële catalogus ook **je eigen** ontworpen planeten
(badge "Eigen"). Planeten van anderen staan daar niet in.
- Voor Online stuurt de client alleen het planeet-id. De server
controleert eigendom, legt een **snapshot** (`planet_json`) vast bij
kiezen/aanmaken/joinen, en stuurt de volledige configuratie
(variabelen, kleuren, `miss_chance`) mee in de lobby. Tegenstanders
onthouden die snapshot om fysica, miss-kans en sprites te simuleren;
een latere wijziging of verwijdering verandert een lopend spel niet.
@@ -763,3 +763,55 @@ Aanname: uiteinden, corridors, en de fallSpeed-overdracht. Playwright uiteinden, corridors, en de fallSpeed-overdracht. Playwright legt early/mid/late vast op 1024×532 en 1920×1080, plus een legt early/mid/late vast op 1024×532 en 1920×1080, plus een webm van beide formaten. webm van beide formaten.## t1139 — Planeetontwerper- De ontwerper is alleen beschikbaar op het hoofdmenu, en alleen als je bent ingelogd. Tot de live OAuth-callback en het CI-geheim `auth_client_secret` zijn ingericht, is dat op productie onzichtbaar. Lokaal kun je inloggen met `auth.php?test=1` (of `test=2`).- Levenslange punten staan in het server-profiel (`profiles`). Alleen ingelogde spellen tellen mee. Bots leveren geen punten op. - **Spelen** (solo): de score aan het einde van het spel. - **Offline Strijd**: de score van **elke ronde**, gewonnen of verloren, omdat de score per ronde opnieuw begint. - **Online**: de server kent de score via de poll; punten worden toegekend bij uitschakeling of als de lobby klaar is, één keer per `online:{lobbyId}:{userId}`. De client kan hier geen punten insturen.- Anti-cheat voor solo/offline: `play_begin` geeft een eenmalig token (geldig 6 uur). `play_finish` klempt de score op 0–10000, weigert een positieve score als het spel korter dan 3 seconden duurde, en laat maximaal 4 punten per seconde door. Herhaalde finishes van hetzelfde token zijn een no-op. Overduidelijk valsspelen wordt geklemd, niet keihard verboden, zodat een trage verbinding geen eerlijke score weggooit.- Het blokjesregister (`server/lib/blocks.json`) is append-only: de volgorde ligt nu vast. Eerst Terra's vijf (gratis), daarna 43 nieuwe icoontjes (eerste, Fehu, op 500 punten; daarna telkens 14,5 % meer, afgerond en strikt stijgend — de laatste icoon zit rond de 147 000 punten), daarna de 55 kleuren van de officiële niet-Terra-planeten als lange staart (de laatste zit in de honderden miljoenen). Punten zijn een **eis**, geen uitgave. Officiële planeten blijven hun eigen blokjes gebruiken zonder ontgrendeling; ontgrendelen is alleen voor de ontwerper.- Een speler mag tot 30 eigen planeten hebben. Id's zijn `c_` plus 16 hex-tekens. Namen (planeet en volk) zijn 1–32 tekens, zonder tags. De vijf blokjes moeten verschillend en ontgrendeld zijn.- Nieuwe blokjes-plaatjes staan in `build/images/block-*.png`, 64×64, in dezelfde stijl als Terra (gekleurde silhouet, donkere omtrek, highlight, slagschaduw). Gegenereerd door `scripts/gen_unlock_blocks.py`.## t1140 — Eigen planeten in elke modus- In Spelen, Offline Strijd en Online Spelen toont de planeetkiezer naast de officiële catalogus ook **je eigen** ontworpen planeten (badge "Eigen"). Planeten van anderen staan daar niet in.- Voor Online stuurt de client alleen het planeet-id. De server controleert eigendom, legt een **snapshot** (`planet_json`) vast bij kiezen/aanmaken/joinen, en stuurt de volledige configuratie (variabelen, kleuren, `miss_chance`) mee in de lobby. Tegenstanders onthouden die snapshot om fysica, miss-kans en sprites te simuleren; een latere wijziging of verwijdering verandert een lopend spel niet.@@ -0,0 +1,665 @@
#!/usr/bin/env python3
"""Build server/lib/blocks.json (append-only registry) and new unlockable
block PNGs in the existing 64×64 style: coloured silhouette, dark outline,
soft highlight, drop shadow.
Official catalog colours are listed first (Terra's five, then the other
planets in catalog order) and their existing PNGs are left untouched.
New icons are appended and rendered here.
Run from the repo root: python3 scripts/gen_unlock_blocks.py
"""
from __future__ import annotations
import json
import math
from pathlib import Path
from PIL import Image, ImageDraw, ImageFilter
ROOT = Path(__file__).resolve().parents[1]
CATALOG = ROOT / 'server' / 'lib' / 'planets.json'
OUT_JSON = ROOT / 'server' / 'lib' / 'blocks.json'
OUT_IMG = ROOT / 'build' / 'images'
SIZE = 64
SCALE = 4
SS = SIZE * SCALE
def hex_rgb(h):
h = h.lstrip('#')
return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
def lighten(rgb, f=0.35):
return tuple(min(255, int(c + (255 - c) * f)) for c in rgb)
def darken(rgb, f=0.28):
return tuple(max(0, int(c * (1 - f))) for c in rgb)
def regular_poly(cx, cy, r, n, rot=-math.pi / 2):
pts = []
for i in range(n):
a = rot + i * 2 * math.pi / n
pts.append((cx + r * math.cos(a), cy + r * math.sin(a)))
return pts
def star_pts(cx, cy, r, n=5, inner=0.42, rot=-math.pi / 2):
pts = []
for i in range(n * 2):
a = rot + i * math.pi / n
rr = r if i % 2 == 0 else r * inner
pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
return pts
# ---------- shape primitives (filled polygons / lines) ----------
def poly_stroke(draw, pts, fill, outline, width):
draw.polygon(pts, fill=fill, outline=outline, width=width)
def thick_lines(draw, segs, color, width, closed=False):
"""segs: list of point lists."""
for pts in segs:
if len(pts) < 2:
continue
draw.line(pts, fill=color, width=width, joint='curve')
# round caps
r = width / 2
for p in (pts[0], pts[-1]):
draw.ellipse([p[0] - r, p[1] - r, p[0] + r, p[1] + r], fill=color)
if closed and pts[0] != pts[-1]:
draw.line([pts[-1], pts[0]], fill=color, width=width)
def icon_path(cx, cy, r, kind):
"""Return ('poly', pts) or ('polys', [pts, ...]) or ('lines', [pts,...], wfrac)
or ('combo', list of commands). Coordinates in actual pixels."""
def P(x, y):
return (cx + x * r, cy + y * r)
k = kind.lower()
if k == 'circle':
return ('ellipse', [-1, -1, 1, 1])
if k == 'square':
s = 0.86
return ('roundrect', [-s, -s, s, s], 0.12)
if k == 'triangle':
return ('poly', regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2))
if k == 'diamond':
return ('poly', regular_poly(cx, cy, r * 1.05, 4, 0))
if k == 'star':
return ('poly', star_pts(cx, cy, r * 1.12))
if k == 'hexagon':
return ('poly', regular_poly(cx, cy, r * 1.05, 6, 0))
if k == 'pentagon':
return ('poly', regular_poly(cx, cy, r * 1.08, 5))
if k == 'arrow':
return ('poly', [
P(0, -1.1), P(0.85, 0.05), P(0.28, 0.05), P(0.28, 1),
P(-0.28, 1), P(-0.28, 0.05), P(-0.85, 0.05),
])
if k == 'chevron':
return ('poly', [
P(0, -1.05), P(0.95, 0.15), P(0.95, 0.55), P(0, -0.15),
P(-0.95, 0.55), P(-0.95, 0.15),
])
if k == 'double_arrow':
return ('poly', [
P(0, -1.15), P(0.72, -0.25), P(0.28, -0.25), P(0.28, 0.05),
P(0.72, 0.05), P(0, 1.15), P(-0.72, 0.05), P(-0.28, 0.05),
P(-0.28, -0.25), P(-0.72, -0.25),
])
if k == 'return_arrow':
return ('poly', [
P(-0.15, -1.1), P(0.7, -0.4), P(0.25, -0.4), P(0.25, 0.15),
P(0.85, 0.15), P(0.85, 0.55), P(-0.25, 0.55), P(-0.25, -0.4),
P(-0.7, -0.4),
])
# Runes — stylized, thick, readable
if k == 'rune_fehu':
return ('lines', [
[P(-0.15, 1.0), P(-0.15, -1.0)],
[P(-0.15, -0.55), P(0.85, -0.95)],
[P(-0.15, -0.05), P(0.85, -0.45)],
], 0.28)
if k == 'rune_ansuz':
return ('lines', [
[P(-0.2, 1.0), P(-0.2, -1.0)],
[P(-0.2, -0.85), P(0.85, -0.25)],
[P(-0.2, -0.15), P(0.7, 0.45)],
], 0.28)
if k == 'rune_thurisaz':
return ('lines', [
[P(-0.35, 1.0), P(-0.35, -1.0)],
[P(-0.35, -0.55), P(0.7, 0), P(-0.35, 0.55)],
], 0.28)
if k == 'rune_raido':
return ('lines', [
[P(-0.3, 1.0), P(-0.3, -1.0)],
[P(-0.3, -1.0), P(0.65, -0.55), P(-0.3, -0.1)],
[P(-0.05, -0.1), P(0.7, 1.0)],
], 0.26)
if k == 'rune_sowilo':
return ('lines', [
[P(0.55, -1.05), P(-0.45, -0.25), P(0.45, 0.25), P(-0.55, 1.05)],
], 0.30)
if k == 'rune_algiz':
return ('lines', [
[P(0, 1.05), P(0, -1.05)],
[P(0, -0.15), P(-0.75, -0.95)],
[P(0, -0.15), P(0.75, -0.95)],
], 0.28)
# Figures
if k == 'person':
# head + body + arms + legs as one silhouette
head = []
for i in range(16):
a = i * 2 * math.pi / 16
head.append(P(0.0 + 0.28 * math.cos(a), -0.72 + 0.28 * math.sin(a)))
body = [
P(-0.22, -0.42), P(-0.72, -0.15), P(-0.72, 0.12), P(-0.22, -0.08),
P(-0.28, 0.35), P(-0.55, 1.05), P(-0.22, 1.05), P(0, 0.5),
P(0.22, 1.05), P(0.55, 1.05), P(0.28, 0.35), P(0.22, -0.08),
P(0.72, 0.12), P(0.72, -0.15), P(0.22, -0.42),
]
return ('polys', [head, body])
if k == 'walker':
head = [P(0.15 + 0.26 * math.cos(i * 2 * math.pi / 16),
-0.7 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)]
body = [
P(-0.05, -0.42), P(-0.65, 0.05), P(-0.45, 0.25), P(-0.05, -0.05),
P(-0.15, 0.35), P(-0.7, 0.95), P(-0.4, 1.08), P(0.05, 0.45),
P(0.45, 1.08), P(0.7, 0.85), P(0.25, 0.3), P(0.25, -0.05),
P(0.7, -0.25), P(0.5, -0.45), P(0.2, -0.42),
]
return ('polys', [head, body])
if k == 'hero':
# arms up in a V
head = [P(0.0 + 0.26 * math.cos(i * 2 * math.pi / 16),
-0.62 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)]
body = [
P(-0.18, -0.35), P(-0.95, -0.95), P(-0.7, -1.08), P(-0.1, -0.4),
P(-0.25, 0.35), P(-0.5, 1.08), P(-0.18, 1.08), P(0, 0.5),
P(0.18, 1.08), P(0.5, 1.08), P(0.25, 0.35), P(0.1, -0.4),
P(0.7, -1.08), P(0.95, -0.95), P(0.18, -0.35),
]
return ('polys', [head, body])
# Faces
if k == 'smile':
return ('face', 'smile')
if k == 'wink':
return ('face', 'wink')
if k == 'cool':
return ('face', 'cool')
if k == 'grin':
return ('face', 'grin')
# Icons
if k == 'heart':
pts = []
for i in range(32):
t = i * 2 * math.pi / 32
# classic heart parametric, scaled
x = 16 * math.sin(t) ** 3
y = -(13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t))
pts.append(P(x / 16.5, y / 16.5 + 0.08))
return ('poly', pts)
if k == 'lightning':
return ('poly', [
P(0.15, -1.1), P(0.55, -1.1), P(0.05, -0.1), P(0.45, -0.1),
P(-0.55, 1.15), P(-0.05, 0.15), P(-0.5, 0.15),
])
if k == 'shield':
return ('poly', [
P(0, -1.1), P(0.95, -0.7), P(0.85, 0.25), P(0, 1.1),
P(-0.85, 0.25), P(-0.95, -0.7),
])
if k == 'crown':
return ('poly', [
P(-0.95, 0.45), P(-0.95, -0.15), P(-0.5, 0.25), P(0, -0.95),
P(0.5, 0.25), P(0.95, -0.15), P(0.95, 0.45),
P(0.85, 0.85), P(-0.85, 0.85),
])
if k == 'eye':
return ('eye',)
if k == 'star6':
return ('poly', star_pts(cx, cy, r * 1.12, n=6, inner=0.48))
if k == 'spiral':
pts = []
for i in range(60):
t = i / 59 * 3.4 * math.pi
rr = 0.12 + 0.88 * (i / 59)
pts.append(P(rr * math.cos(t), rr * math.sin(t)))
return ('lines', [pts], 0.26)
if k == 'wave':
pts_top, pts_bot = [], []
for i in range(21):
x = -1.05 + i * 2.1 / 20
y = 0.28 * math.sin(x * math.pi * 1.4)
pts_top.append(P(x, y - 0.28))
pts_bot.append(P(x, y + 0.28))
return ('poly', pts_top + list(reversed(pts_bot)))
if k == 'mountain':
return ('poly', [
P(-1.1, 0.9), P(-0.45, -0.55), P(-0.15, -0.05),
P(0.15, -1.05), P(0.5, -0.25), P(0.7, -0.55),
P(1.1, 0.9),
])
if k == 'fish':
return ('poly', [
P(-1.05, 0), P(-0.55, -0.55), P(0.35, -0.55), P(0.75, -0.15),
P(1.1, -0.55), P(0.85, 0), P(1.1, 0.55), P(0.75, 0.15),
P(0.35, 0.55), P(-0.55, 0.55),
])
if k == 'bird':
return ('poly', [
P(-1.05, 0.15), P(-0.3, -0.15), P(-0.05, -0.85), P(0.2, -0.15),
P(0.55, -0.25), P(1.05, 0.05), P(0.45, 0.15),
P(0.2, 0.85), P(-0.05, 0.2), P(-0.55, 0.45),
])
if k == 'key':
# head circle + shaft + teeth as one poly
pts = []
for i in range(12):
a = -math.pi * 0.6 + i * 1.6 * math.pi / 11
pts.append(P(-0.55 + 0.42 * math.cos(a), -0.55 + 0.42 * math.sin(a)))
pts += [
P(-0.25, -0.2), P(1.05, -0.2), P(1.05, 0.15),
P(0.85, 0.15), P(0.85, 0.5), P(0.6, 0.5), P(0.6, 0.15),
P(0.4, 0.15), P(0.4, 0.38), P(0.15, 0.38), P(0.15, 0.15),
P(-0.25, 0.15),
]
return ('poly', pts)
if k == 'comet':
return ('poly', [
P(0.95, -0.95), P(0.35, -0.45), P(0.15, -0.7), P(-0.15, -0.15),
P(0.15, -0.05), P(-1.05, 1.05), P(-0.05, 0.15), P(0.15, 0.35),
P(0.55, -0.15), P(0.45, -0.45),
])
if k == 'clover':
lobes = []
for ang, ox, oy in ((0, 0, -0.42), (2.1, -0.4, 0.18), (4.2, 0.4, 0.18)):
pts = []
for i in range(16):
a = i * 2 * math.pi / 16
pts.append(P(ox + 0.42 * math.cos(a), oy + 0.42 * math.sin(a)))
lobes.append(pts)
stem = [P(-0.08, 0.35), P(0.08, 0.35), P(0.18, 1.05), P(-0.05, 1.05)]
lobes.append(stem)
return ('polys', lobes)
if k == 'paw':
pads = []
for ox, oy, rr in ((-0.5, -0.55, 0.28), (0, -0.75, 0.28), (0.5, -0.55, 0.28),
(0.0, 0.28, 0.52)):
pts = []
for i in range(16):
a = i * 2 * math.pi / 16
pts.append(P(ox + rr * math.cos(a), oy + rr * math.sin(a)))
pads.append(pts)
return ('polys', pads)
if k == 'sword':
return ('poly', [
P(-0.18, 1.1), P(-0.18, 0.45), P(-0.55, 0.45), P(-0.55, 0.22),
P(-0.18, 0.22), P(-0.18, -0.95), P(0, -1.15), P(0.18, -0.95),
P(0.18, 0.22), P(0.55, 0.22), P(0.55, 0.45), P(0.18, 0.45),
P(0.18, 1.1),
])
if k == 'bell':
pts = []
for i in range(18):
a = math.pi + i * math.pi / 17
pts.append(P(0.85 * math.cos(a), -0.25 + 0.85 * math.sin(a)))
pts += [P(0.95, 0.55), P(0.7, 0.75), P(0.15, 0.75), P(0.15, 0.95),
P(-0.15, 0.95), P(-0.15, 0.75), P(-0.7, 0.75), P(-0.95, 0.55)]
return ('poly', pts)
if k == 'mushroom':
cap = []
for i in range(18):
a = math.pi + i * math.pi / 17
cap.append(P(0.95 * math.cos(a), -0.25 + 0.7 * math.sin(a)))
cap += [P(0.95, 0.05), P(-0.95, 0.05)]
stem = [P(-0.32, 0.05), P(0.32, 0.05), P(0.38, 1.05), P(-0.38, 1.05)]
return ('polys', [cap, stem])
if k == 'cactus':
return ('poly', [
P(-0.22, 1.05), P(-0.22, 0.15), P(-0.75, 0.15), P(-0.75, -0.35),
P(-0.5, -0.35), P(-0.5, -0.05), P(-0.22, -0.05), P(-0.22, -1.05),
P(0.22, -1.05), P(0.22, -0.25), P(0.55, -0.25), P(0.55, -0.7),
P(0.8, -0.7), P(0.8, -0.02), P(0.22, -0.02), P(0.22, 1.05),
])
if k == 'ring':
return ('ring', 1.0, 0.55)
if k == 'flag':
return ('poly', [
P(-0.7, 1.1), P(-0.7, -1.05), P(-0.5, -1.05), P(-0.5, -0.85),
P(1.0, -0.85), P(0.7, -0.4), P(1.0, 0.05), P(-0.5, 0.05),
P(-0.5, 1.1),
])
if k == 'snowflake':
arms = []
for k0 in range(6):
a = k0 * math.pi / 3
c, s = math.cos(a), math.sin(a)
def rot(x, y):
return P(x * c - y * s, x * s + y * c)
arms.append([rot(0, 0), rot(0, -1.05)])
arms.append([rot(-0.28, -0.6), rot(0, -0.4), rot(0.28, -0.6)])
return ('lines', arms, 0.22)
if k == 'flame_icon':
return ('poly', [
P(0, -1.15), P(0.35, -0.45), P(0.55, -0.7), P(0.75, -0.15),
P(0.55, 0.55), P(0.2, 1.0), P(-0.25, 1.0), P(-0.6, 0.5),
P(-0.7, -0.05), P(-0.35, -0.55), P(-0.15, -0.2),
])
if k == 'ankh':
return ('lines', [
[P(0, 1.05), P(0, -0.25)],
[P(-0.55, 0.15), P(0.55, 0.15)],
], 0.28) # loop added in combo
if k == 'yinyang':
return ('yinyang',)
if k == 'crescent':
# moon
return ('crescent',)
# fallback
return ('ellipse', [-1, -1, 1, 1])
def draw_kind(draw, img, kind, cx, cy, r, fill, outline, width):
cmd = icon_path(cx, cy, r, kind)
kind_l = kind.lower()
def fill_poly(pts):
if len(pts) >= 3:
draw.polygon(pts, fill=fill, outline=outline, width=width)
def fill_lines(segs, wfrac):
w = max(width, int(r * wfrac))
# draw in outline color slightly thicker, then fill
thick_lines(draw, segs, outline, w + max(2, width // 2))
thick_lines(draw, segs, fill, w)
if cmd[0] == 'poly':
fill_poly(cmd[1])
elif cmd[0] == 'polys':
for pts in cmd[1]:
fill_poly(pts)
elif cmd[0] == 'lines':
fill_lines(cmd[1], cmd[2])
if kind_l == 'ankh':
# loop at top
box = [cx - r * 0.42, cy - r * 1.15, cx + r * 0.42, cy - r * 0.25]
draw.ellipse(box, outline=outline, width=int(r * 0.28) + width)
draw.ellipse([box[0] + r * 0.14, box[1] + r * 0.14,
box[2] - r * 0.14, box[3] - r * 0.14],
outline=fill, width=int(r * 0.16))
# fill ring by a second pass
# simpler: thick ellipse
w = int(r * 0.26)
draw.ellipse(box, outline=outline, width=w + width)
draw.ellipse(box, outline=fill, width=w)
elif cmd[0] == 'ellipse':
a, b, c, d = cmd[1]
box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r]
draw.ellipse(box, fill=fill, outline=outline, width=width)
elif cmd[0] == 'roundrect':
a, b, c, d = cmd[1]
box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r]
draw.rounded_rectangle(box, radius=r * cmd[2], fill=fill, outline=outline, width=width)
elif cmd[0] == 'ring':
_, ro, ri = cmd
outer = [cx - r * ro, cy - r * ro, cx + r * ro, cy + r * ro]
inner = [cx - r * ri, cy - r * ri, cx + r * ri, cy + r * ri]
draw.ellipse(outer, fill=fill, outline=outline, width=width)
# punch inner with destination-out
# We'll handle punch at a higher level; draw inner as transparent later
draw.ellipse(inner, fill=(0, 0, 0, 0), outline=outline, width=width)
elif cmd[0] == 'face':
box = [cx - r, cy - r, cx + r, cy + r]
draw.ellipse(box, fill=fill, outline=outline, width=width)
eye_c = outline
er = r * 0.12
if cmd[1] == 'wink':
draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er,
cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
draw.line([(cx + r * 0.18, cy - r * 0.28), (cx + r * 0.52, cy - r * 0.28)],
fill=eye_c, width=max(width, int(r * 0.12)))
elif cmd[1] == 'cool':
# sunglasses
draw.rounded_rectangle([cx - r * 0.7, cy - r * 0.42, cx - r * 0.08, cy - r * 0.08],
radius=r * 0.12, fill=eye_c)
draw.rounded_rectangle([cx + r * 0.08, cy - r * 0.42, cx + r * 0.7, cy - r * 0.08],
radius=r * 0.12, fill=eye_c)
draw.line([(cx - r * 0.08, cy - r * 0.25), (cx + r * 0.08, cy - r * 0.25)],
fill=eye_c, width=max(3, int(r * 0.1)))
else:
draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er,
cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
draw.ellipse([cx + r * 0.38 - er, cy - r * 0.28 - er,
cx + r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c)
# smile
smile = []
for i in range(9):
a = math.pi * 0.2 + i * math.pi * 0.6 / 8
smile.append((cx + r * 0.48 * math.cos(a), cy + r * 0.12 + r * 0.42 * math.sin(a)))
sw = max(width, int(r * 0.12))
if cmd[1] == 'grin':
draw.chord([cx - r * 0.5, cy + r * 0.05, cx + r * 0.5, cy + r * 0.65],
start=0, end=180, fill=eye_c, outline=eye_c)
else:
draw.line(smile, fill=eye_c, width=sw, joint='curve')
elif cmd[0] == 'eye':
# almond
pts = []
for i in range(24):
t = i * 2 * math.pi / 24
x = math.cos(t)
y = 0.5 * math.sin(t)
pts.append((cx + r * 1.05 * x, cy + r * 0.85 * y))
fill_poly(pts)
iris_c = outline
draw.ellipse([cx - r * 0.38, cy - r * 0.38, cx + r * 0.38, cy + r * 0.38],
fill=iris_c)
draw.ellipse([cx - r * 0.14, cy - r * 0.18, cx + r * 0.06, cy + r * 0.02],
fill=lighten(fill[:3] if isinstance(fill, tuple) else (255, 255, 255), 0.8) + (255,))
elif cmd[0] == 'yinyang':
draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)
# right half dark via chord is messy; draw a dark semicircle + two dots
# Use a path: top-center to bottom via right, with small circles
# We'll approximate with a pie and two discs
dark = outline
draw.pieslice([cx - r, cy - r, cx + r, cy + r], start=90, end=270, fill=dark)
draw.ellipse([cx - r * 0.5, cy - r, cx + r * 0.5, cy], fill=dark)
draw.ellipse([cx - r * 0.5, cy, cx + r * 0.5, cy + r], fill=fill)
# dots
draw.ellipse([cx - r * 0.16, cy - r * 0.58, cx + r * 0.16, cy - r * 0.26], fill=fill)
draw.ellipse([cx - r * 0.16, cy + r * 0.26, cx + r * 0.16, cy + r * 0.58], fill=dark)
draw.ellipse([cx - r, cy - r, cx + r, cy + r], outline=outline, width=width)
elif cmd[0] == 'crescent':
# moon: two circles, punch later — draw a crescent polygon
outer, inner = [], []
for i in range(24):
a = -math.pi * 0.75 + i * (1.5 * math.pi) / 23
outer.append((cx + r * math.cos(a) - r * 0.05, cy + r * math.sin(a)))
ox, oy = cx + r * 0.42, cy - r * 0.05
for i in range(20, -1, -1):
a = -math.pi * 0.7 + i * (1.4 * math.pi) / 20
inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a)))
fill_poly(outer + inner)
else:
draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)
def render_block(hex_color, shape):
rgb = hex_rgb(hex_color)
hi = lighten(rgb, 0.42)
lo = darken(rgb, 0.32)
img = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
cx = cy = SS / 2
r = SS * 0.36
width = max(2, SCALE)
# drop shadow
shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
sd = ImageDraw.Draw(shadow)
draw_kind(sd, shadow, shape, cx + SCALE * 1.2, cy + SCALE * 1.6, r,
(0, 0, 0, 90), None, 0)
shadow = shadow.filter(ImageFilter.GaussianBlur(radius=SCALE * 1.1))
img = Image.alpha_composite(img, shadow)
# For ring, punch a hole after drawing body
body = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
bd = ImageDraw.Draw(body)
draw_kind(bd, body, shape, cx, cy, r, rgb + (255,), lo + (255,), width)
if shape == 'ring':
# punch inner hole
mask = Image.new('L', (SS, SS), 0)
md = ImageDraw.Draw(mask)
ri = r * 0.55
md.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], fill=255)
clear = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
body = Image.composite(clear, body, mask)
# redraw inner outline
bd = ImageDraw.Draw(body)
bd.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], outline=lo + (255,), width=width)
img = Image.alpha_composite(img, body)
# highlight
hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
hd = ImageDraw.Draw(hi_layer)
draw_kind(hd, hi_layer, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55,
hi + (110,), None, 0)
hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6))
# clip highlight to body alpha
body_a = body.split()[3]
ha = hi_layer.split()[3]
from PIL import ImageChops
ha = ImageChops.multiply(ha, body_a)
hi_layer.putalpha(ha)
img = Image.alpha_composite(img, hi_layer)
return img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)
# New unlockable blocks, appended after official catalog colours.
# ids are stable and must never be reordered or reused.
NEW_BLOCKS = [
# Runes
{'id': 'rune-fehu', 'name': 'Fehu', 'hex': '#e8a44a', 'shape': 'rune_fehu'},
{'id': 'rune-ansuz', 'name': 'Ansuz', 'hex': '#6ab0e8', 'shape': 'rune_ansuz'},
{'id': 'rune-thurisaz', 'name': 'Thurisaz', 'hex': '#c05040', 'shape': 'rune_thurisaz'},
{'id': 'rune-raido', 'name': 'Raido', 'hex': '#d0c070', 'shape': 'rune_raido'},
{'id': 'rune-sowilo', 'name': 'Sowilo', 'hex': '#f0d040', 'shape': 'rune_sowilo'},
{'id': 'rune-algiz', 'name': 'Algiz', 'hex': '#80d0a0', 'shape': 'rune_algiz'},
# Arrows
{'id': 'arrow-up', 'name': 'Arrow', 'hex': '#f07040', 'shape': 'arrow'},
{'id': 'arrow-chevron', 'name': 'Chevron', 'hex': '#50c0e0', 'shape': 'chevron'},
{'id': 'arrow-double', 'name': 'Double Arrow', 'hex': '#e05080', 'shape': 'double_arrow'},
{'id': 'arrow-return', 'name': 'Return', 'hex': '#a080e0', 'shape': 'return_arrow'},
# Figures
{'id': 'fig-person', 'name': 'Figure', 'hex': '#f0c0a0', 'shape': 'person'},
{'id': 'fig-walker', 'name': 'Walker', 'hex': '#c09070', 'shape': 'walker'},
{'id': 'fig-hero', 'name': 'Hero', 'hex': '#e8b070', 'shape': 'hero'},
# Faces
{'id': 'face-smile', 'name': 'Smile', 'hex': '#f0d060', 'shape': 'smile'},
{'id': 'face-wink', 'name': 'Wink', 'hex': '#f0a050', 'shape': 'wink'},
{'id': 'face-cool', 'name': 'Cool', 'hex': '#6090d0', 'shape': 'cool'},
{'id': 'face-grin', 'name': 'Grin', 'hex': '#f0c848', 'shape': 'grin'},
# Icons
{'id': 'icon-heart', 'name': 'Heart', 'hex': '#e04060', 'shape': 'heart'},
{'id': 'icon-moon', 'name': 'Moon', 'hex': '#d0d8f0', 'shape': 'crescent'},
{'id': 'icon-bolt', 'name': 'Bolt', 'hex': '#f0e050', 'shape': 'lightning'},
{'id': 'icon-shield', 'name': 'Shield', 'hex': '#5080c0', 'shape': 'shield'},
{'id': 'icon-crown', 'name': 'Crown', 'hex': '#f0c030', 'shape': 'crown'},
{'id': 'icon-eye', 'name': 'Eye', 'hex': '#70d0c0', 'shape': 'eye'},
{'id': 'icon-star6', 'name': 'Hexastar', 'hex': '#f0e8a0', 'shape': 'star6'},
{'id': 'icon-spiral', 'name': 'Spiral', 'hex': '#c070d0', 'shape': 'spiral'},
{'id': 'icon-wave', 'name': 'Wave', 'hex': '#3090d0', 'shape': 'wave'},
{'id': 'icon-mountain', 'name': 'Mountain', 'hex': '#809070', 'shape': 'mountain'},
{'id': 'icon-fish', 'name': 'Fish', 'hex': '#40a8c8', 'shape': 'fish'},
{'id': 'icon-bird', 'name': 'Bird', 'hex': '#e07050', 'shape': 'bird'},
{'id': 'icon-key', 'name': 'Key', 'hex': '#d0b050', 'shape': 'key'},
{'id': 'icon-comet', 'name': 'Comet', 'hex': '#90d0f0', 'shape': 'comet'},
{'id': 'icon-clover', 'name': 'Clover', 'hex': '#40b060', 'shape': 'clover'},
{'id': 'icon-paw', 'name': 'Paw', 'hex': '#c08050', 'shape': 'paw'},
{'id': 'icon-sword', 'name': 'Sword', 'hex': '#b0b8c0', 'shape': 'sword'},
{'id': 'icon-bell', 'name': 'Bell', 'hex': '#f0c848', 'shape': 'bell'},
{'id': 'icon-mushroom', 'name': 'Mushroom', 'hex': '#e06050', 'shape': 'mushroom'},
{'id': 'icon-cactus', 'name': 'Cactus', 'hex': '#50b068', 'shape': 'cactus'},
{'id': 'icon-ring', 'name': 'Ring', 'hex': '#e8d080', 'shape': 'ring'},
{'id': 'icon-flag', 'name': 'Flag', 'hex': '#d04050', 'shape': 'flag'},
{'id': 'icon-snow', 'name': 'Snowflake', 'hex': '#c8e0f8', 'shape': 'snowflake'},
{'id': 'icon-flame', 'name': 'Flame', 'hex': '#ff7030', 'shape': 'flame_icon'},
{'id': 'icon-ankh', 'name': 'Ankh', 'hex': '#d0a060', 'shape': 'ankh'},
{'id': 'icon-yin', 'name': 'Yin Yang', 'hex': '#606080', 'shape': 'yinyang'},
]
def official_blocks(catalog):
out = []
seen = set()
for planet in catalog['planets']:
pid = planet['id']
for c in planet['colors']:
bid = f"{pid}-{c['name']}"
if bid in seen:
raise SystemExit(f'duplicate official id {bid}')
seen.add(bid)
out.append({
'id': bid,
'name': c['name'].capitalize() if pid == 'terra' else f"{planet['name']} {c['name']}",
'hex': c['hex'],
'shape': c.get('shape') or 'circle',
'image': c['image'],
'terra': pid == 'terra',
})
return out
def main():
catalog = json.loads(CATALOG.read_text())
official = official_blocks(catalog)
terra = [b for b in official if b.get('terra')]
others = [b for b in official if not b.get('terra')]
if len(terra) != 5 or terra[0]['id'] != 'terra-ember':
raise SystemExit(f'Terra five unexpected: {[b["id"] for b in terra]}')
new = []
seen = {b['id'] for b in official}
OUT_IMG.mkdir(parents=True, exist_ok=True)
for b in NEW_BLOCKS:
if b['id'] in seen:
raise SystemExit(f'duplicate new id {b["id"]}')
seen.add(b['id'])
image = f"images/block-{b['id']}.png"
path = ROOT / 'build' / image
img = render_block(b['hex'], b['shape'])
img.save(path, 'PNG', optimize=True)
new.append({
'id': b['id'],
'name': b['name'],
'hex': b['hex'],
'shape': b['shape'],
'image': image,
'terra': False,
})
print(f' wrote {path.relative_to(ROOT)} ({path.stat().st_size} bytes)')
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': terra + new + others,
}
OUT_JSON.write_text(json.dumps(registry, indent=2, ensure_ascii=False) + '\n')
print(f'wrote {OUT_JSON.relative_to(ROOT)}: {len(terra)} terra + {len(new)} new + {len(others)} official = {len(registry["blocks"])} total')
if __name__ == '__main__':
main()
@@ -0,0 +1,665 @@#!/usr/bin/env python3"""Build server/lib/blocks.json (append-only registry) and new unlockableblock PNGs in the existing 64×64 style: coloured silhouette, dark outline,soft highlight, drop shadow.Official catalog colours are listed first (Terra's five, then the otherplanets in catalog order) and their existing PNGs are left untouched.New icons are appended and rendered here.Run from the repo root: python3 scripts/gen_unlock_blocks.py"""from __future__ import annotationsimport jsonimport mathfrom pathlib import Pathfrom PIL import Image, ImageDraw, ImageFilterROOT = Path(__file__).resolve().parents[1]CATALOG = ROOT / 'server' / 'lib' / 'planets.json'OUT_JSON = ROOT / 'server' / 'lib' / 'blocks.json'OUT_IMG = ROOT / 'build' / 'images'SIZE = 64SCALE = 4SS = SIZE * SCALEdef hex_rgb(h): h = h.lstrip('#') return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))def lighten(rgb, f=0.35): return tuple(min(255, int(c + (255 - c) * f)) for c in rgb)def darken(rgb, f=0.28): return tuple(max(0, int(c * (1 - f))) for c in rgb)def regular_poly(cx, cy, r, n, rot=-math.pi / 2): pts = [] for i in range(n): a = rot + i * 2 * math.pi / n pts.append((cx + r * math.cos(a), cy + r * math.sin(a))) return ptsdef star_pts(cx, cy, r, n=5, inner=0.42, rot=-math.pi / 2): pts = [] for i in range(n * 2): a = rot + i * math.pi / n rr = r if i % 2 == 0 else r * inner pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a))) return pts# ---------- shape primitives (filled polygons / lines) ----------def poly_stroke(draw, pts, fill, outline, width): draw.polygon(pts, fill=fill, outline=outline, width=width)def thick_lines(draw, segs, color, width, closed=False): """segs: list of point lists.""" for pts in segs: if len(pts) < 2: continue draw.line(pts, fill=color, width=width, joint='curve') # round caps r = width / 2 for p in (pts[0], pts[-1]): draw.ellipse([p[0] - r, p[1] - r, p[0] + r, p[1] + r], fill=color) if closed and pts[0] != pts[-1]: draw.line([pts[-1], pts[0]], fill=color, width=width)def icon_path(cx, cy, r, kind): """Return ('poly', pts) or ('polys', [pts, ...]) or ('lines', [pts,...], wfrac) or ('combo', list of commands). Coordinates in actual pixels.""" def P(x, y): return (cx + x * r, cy + y * r) k = kind.lower() if k == 'circle': return ('ellipse', [-1, -1, 1, 1]) if k == 'square': s = 0.86 return ('roundrect', [-s, -s, s, s], 0.12) if k == 'triangle': return ('poly', regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2)) if k == 'diamond': return ('poly', regular_poly(cx, cy, r * 1.05, 4, 0)) if k == 'star': return ('poly', star_pts(cx, cy, r * 1.12)) if k == 'hexagon': return ('poly', regular_poly(cx, cy, r * 1.05, 6, 0)) if k == 'pentagon': return ('poly', regular_poly(cx, cy, r * 1.08, 5)) if k == 'arrow': return ('poly', [ P(0, -1.1), P(0.85, 0.05), P(0.28, 0.05), P(0.28, 1), P(-0.28, 1), P(-0.28, 0.05), P(-0.85, 0.05), ]) if k == 'chevron': return ('poly', [ P(0, -1.05), P(0.95, 0.15), P(0.95, 0.55), P(0, -0.15), P(-0.95, 0.55), P(-0.95, 0.15), ]) if k == 'double_arrow': return ('poly', [ P(0, -1.15), P(0.72, -0.25), P(0.28, -0.25), P(0.28, 0.05), P(0.72, 0.05), P(0, 1.15), P(-0.72, 0.05), P(-0.28, 0.05), P(-0.28, -0.25), P(-0.72, -0.25), ]) if k == 'return_arrow': return ('poly', [ P(-0.15, -1.1), P(0.7, -0.4), P(0.25, -0.4), P(0.25, 0.15), P(0.85, 0.15), P(0.85, 0.55), P(-0.25, 0.55), P(-0.25, -0.4), P(-0.7, -0.4), ]) # Runes — stylized, thick, readable if k == 'rune_fehu': return ('lines', [ [P(-0.15, 1.0), P(-0.15, -1.0)], [P(-0.15, -0.55), P(0.85, -0.95)], [P(-0.15, -0.05), P(0.85, -0.45)], ], 0.28) if k == 'rune_ansuz': return ('lines', [ [P(-0.2, 1.0), P(-0.2, -1.0)], [P(-0.2, -0.85), P(0.85, -0.25)], [P(-0.2, -0.15), P(0.7, 0.45)], ], 0.28) if k == 'rune_thurisaz': return ('lines', [ [P(-0.35, 1.0), P(-0.35, -1.0)], [P(-0.35, -0.55), P(0.7, 0), P(-0.35, 0.55)], ], 0.28) if k == 'rune_raido': return ('lines', [ [P(-0.3, 1.0), P(-0.3, -1.0)], [P(-0.3, -1.0), P(0.65, -0.55), P(-0.3, -0.1)], [P(-0.05, -0.1), P(0.7, 1.0)], ], 0.26) if k == 'rune_sowilo': return ('lines', [ [P(0.55, -1.05), P(-0.45, -0.25), P(0.45, 0.25), P(-0.55, 1.05)], ], 0.30) if k == 'rune_algiz': return ('lines', [ [P(0, 1.05), P(0, -1.05)], [P(0, -0.15), P(-0.75, -0.95)], [P(0, -0.15), P(0.75, -0.95)], ], 0.28) # Figures if k == 'person': # head + body + arms + legs as one silhouette head = [] for i in range(16): a = i * 2 * math.pi / 16 head.append(P(0.0 + 0.28 * math.cos(a), -0.72 + 0.28 * math.sin(a))) body = [ P(-0.22, -0.42), P(-0.72, -0.15), P(-0.72, 0.12), P(-0.22, -0.08), P(-0.28, 0.35), P(-0.55, 1.05), P(-0.22, 1.05), P(0, 0.5), P(0.22, 1.05), P(0.55, 1.05), P(0.28, 0.35), P(0.22, -0.08), P(0.72, 0.12), P(0.72, -0.15), P(0.22, -0.42), ] return ('polys', [head, body]) if k == 'walker': head = [P(0.15 + 0.26 * math.cos(i * 2 * math.pi / 16), -0.7 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)] body = [ P(-0.05, -0.42), P(-0.65, 0.05), P(-0.45, 0.25), P(-0.05, -0.05), P(-0.15, 0.35), P(-0.7, 0.95), P(-0.4, 1.08), P(0.05, 0.45), P(0.45, 1.08), P(0.7, 0.85), P(0.25, 0.3), P(0.25, -0.05), P(0.7, -0.25), P(0.5, -0.45), P(0.2, -0.42), ] return ('polys', [head, body]) if k == 'hero': # arms up in a V head = [P(0.0 + 0.26 * math.cos(i * 2 * math.pi / 16), -0.62 + 0.26 * math.sin(i * 2 * math.pi / 16)) for i in range(16)] body = [ P(-0.18, -0.35), P(-0.95, -0.95), P(-0.7, -1.08), P(-0.1, -0.4), P(-0.25, 0.35), P(-0.5, 1.08), P(-0.18, 1.08), P(0, 0.5), P(0.18, 1.08), P(0.5, 1.08), P(0.25, 0.35), P(0.1, -0.4), P(0.7, -1.08), P(0.95, -0.95), P(0.18, -0.35), ] return ('polys', [head, body]) # Faces if k == 'smile': return ('face', 'smile') if k == 'wink': return ('face', 'wink') if k == 'cool': return ('face', 'cool') if k == 'grin': return ('face', 'grin') # Icons if k == 'heart': pts = [] for i in range(32): t = i * 2 * math.pi / 32 # classic heart parametric, scaled x = 16 * math.sin(t) ** 3 y = -(13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t)) pts.append(P(x / 16.5, y / 16.5 + 0.08)) return ('poly', pts) if k == 'lightning': return ('poly', [ P(0.15, -1.1), P(0.55, -1.1), P(0.05, -0.1), P(0.45, -0.1), P(-0.55, 1.15), P(-0.05, 0.15), P(-0.5, 0.15), ]) if k == 'shield': return ('poly', [ P(0, -1.1), P(0.95, -0.7), P(0.85, 0.25), P(0, 1.1), P(-0.85, 0.25), P(-0.95, -0.7), ]) if k == 'crown': return ('poly', [ P(-0.95, 0.45), P(-0.95, -0.15), P(-0.5, 0.25), P(0, -0.95), P(0.5, 0.25), P(0.95, -0.15), P(0.95, 0.45), P(0.85, 0.85), P(-0.85, 0.85), ]) if k == 'eye': return ('eye',) if k == 'star6': return ('poly', star_pts(cx, cy, r * 1.12, n=6, inner=0.48)) if k == 'spiral': pts = [] for i in range(60): t = i / 59 * 3.4 * math.pi rr = 0.12 + 0.88 * (i / 59) pts.append(P(rr * math.cos(t), rr * math.sin(t))) return ('lines', [pts], 0.26) if k == 'wave': pts_top, pts_bot = [], [] for i in range(21): x = -1.05 + i * 2.1 / 20 y = 0.28 * math.sin(x * math.pi * 1.4) pts_top.append(P(x, y - 0.28)) pts_bot.append(P(x, y + 0.28)) return ('poly', pts_top + list(reversed(pts_bot))) if k == 'mountain': return ('poly', [ P(-1.1, 0.9), P(-0.45, -0.55), P(-0.15, -0.05), P(0.15, -1.05), P(0.5, -0.25), P(0.7, -0.55), P(1.1, 0.9), ]) if k == 'fish': return ('poly', [ P(-1.05, 0), P(-0.55, -0.55), P(0.35, -0.55), P(0.75, -0.15), P(1.1, -0.55), P(0.85, 0), P(1.1, 0.55), P(0.75, 0.15), P(0.35, 0.55), P(-0.55, 0.55), ]) if k == 'bird': return ('poly', [ P(-1.05, 0.15), P(-0.3, -0.15), P(-0.05, -0.85), P(0.2, -0.15), P(0.55, -0.25), P(1.05, 0.05), P(0.45, 0.15), P(0.2, 0.85), P(-0.05, 0.2), P(-0.55, 0.45), ]) if k == 'key': # head circle + shaft + teeth as one poly pts = [] for i in range(12): a = -math.pi * 0.6 + i * 1.6 * math.pi / 11 pts.append(P(-0.55 + 0.42 * math.cos(a), -0.55 + 0.42 * math.sin(a))) pts += [ P(-0.25, -0.2), P(1.05, -0.2), P(1.05, 0.15), P(0.85, 0.15), P(0.85, 0.5), P(0.6, 0.5), P(0.6, 0.15), P(0.4, 0.15), P(0.4, 0.38), P(0.15, 0.38), P(0.15, 0.15), P(-0.25, 0.15), ] return ('poly', pts) if k == 'comet': return ('poly', [ P(0.95, -0.95), P(0.35, -0.45), P(0.15, -0.7), P(-0.15, -0.15), P(0.15, -0.05), P(-1.05, 1.05), P(-0.05, 0.15), P(0.15, 0.35), P(0.55, -0.15), P(0.45, -0.45), ]) if k == 'clover': lobes = [] for ang, ox, oy in ((0, 0, -0.42), (2.1, -0.4, 0.18), (4.2, 0.4, 0.18)): pts = [] for i in range(16): a = i * 2 * math.pi / 16 pts.append(P(ox + 0.42 * math.cos(a), oy + 0.42 * math.sin(a))) lobes.append(pts) stem = [P(-0.08, 0.35), P(0.08, 0.35), P(0.18, 1.05), P(-0.05, 1.05)] lobes.append(stem) return ('polys', lobes) if k == 'paw': pads = [] for ox, oy, rr in ((-0.5, -0.55, 0.28), (0, -0.75, 0.28), (0.5, -0.55, 0.28), (0.0, 0.28, 0.52)): pts = [] for i in range(16): a = i * 2 * math.pi / 16 pts.append(P(ox + rr * math.cos(a), oy + rr * math.sin(a))) pads.append(pts) return ('polys', pads) if k == 'sword': return ('poly', [ P(-0.18, 1.1), P(-0.18, 0.45), P(-0.55, 0.45), P(-0.55, 0.22), P(-0.18, 0.22), P(-0.18, -0.95), P(0, -1.15), P(0.18, -0.95), P(0.18, 0.22), P(0.55, 0.22), P(0.55, 0.45), P(0.18, 0.45), P(0.18, 1.1), ]) if k == 'bell': pts = [] for i in range(18): a = math.pi + i * math.pi / 17 pts.append(P(0.85 * math.cos(a), -0.25 + 0.85 * math.sin(a))) pts += [P(0.95, 0.55), P(0.7, 0.75), P(0.15, 0.75), P(0.15, 0.95), P(-0.15, 0.95), P(-0.15, 0.75), P(-0.7, 0.75), P(-0.95, 0.55)] return ('poly', pts) if k == 'mushroom': cap = [] for i in range(18): a = math.pi + i * math.pi / 17 cap.append(P(0.95 * math.cos(a), -0.25 + 0.7 * math.sin(a))) cap += [P(0.95, 0.05), P(-0.95, 0.05)] stem = [P(-0.32, 0.05), P(0.32, 0.05), P(0.38, 1.05), P(-0.38, 1.05)] return ('polys', [cap, stem]) if k == 'cactus': return ('poly', [ P(-0.22, 1.05), P(-0.22, 0.15), P(-0.75, 0.15), P(-0.75, -0.35), P(-0.5, -0.35), P(-0.5, -0.05), P(-0.22, -0.05), P(-0.22, -1.05), P(0.22, -1.05), P(0.22, -0.25), P(0.55, -0.25), P(0.55, -0.7), P(0.8, -0.7), P(0.8, -0.02), P(0.22, -0.02), P(0.22, 1.05), ]) if k == 'ring': return ('ring', 1.0, 0.55) if k == 'flag': return ('poly', [ P(-0.7, 1.1), P(-0.7, -1.05), P(-0.5, -1.05), P(-0.5, -0.85), P(1.0, -0.85), P(0.7, -0.4), P(1.0, 0.05), P(-0.5, 0.05), P(-0.5, 1.1), ]) if k == 'snowflake': arms = [] for k0 in range(6): a = k0 * math.pi / 3 c, s = math.cos(a), math.sin(a) def rot(x, y): return P(x * c - y * s, x * s + y * c) arms.append([rot(0, 0), rot(0, -1.05)]) arms.append([rot(-0.28, -0.6), rot(0, -0.4), rot(0.28, -0.6)]) return ('lines', arms, 0.22) if k == 'flame_icon': return ('poly', [ P(0, -1.15), P(0.35, -0.45), P(0.55, -0.7), P(0.75, -0.15), P(0.55, 0.55), P(0.2, 1.0), P(-0.25, 1.0), P(-0.6, 0.5), P(-0.7, -0.05), P(-0.35, -0.55), P(-0.15, -0.2), ]) if k == 'ankh': return ('lines', [ [P(0, 1.05), P(0, -0.25)], [P(-0.55, 0.15), P(0.55, 0.15)], ], 0.28) # loop added in combo if k == 'yinyang': return ('yinyang',) if k == 'crescent': # moon return ('crescent',) # fallback return ('ellipse', [-1, -1, 1, 1])def draw_kind(draw, img, kind, cx, cy, r, fill, outline, width): cmd = icon_path(cx, cy, r, kind) kind_l = kind.lower() def fill_poly(pts): if len(pts) >= 3: draw.polygon(pts, fill=fill, outline=outline, width=width) def fill_lines(segs, wfrac): w = max(width, int(r * wfrac)) # draw in outline color slightly thicker, then fill thick_lines(draw, segs, outline, w + max(2, width // 2)) thick_lines(draw, segs, fill, w) if cmd[0] == 'poly': fill_poly(cmd[1]) elif cmd[0] == 'polys': for pts in cmd[1]: fill_poly(pts) elif cmd[0] == 'lines': fill_lines(cmd[1], cmd[2]) if kind_l == 'ankh': # loop at top box = [cx - r * 0.42, cy - r * 1.15, cx + r * 0.42, cy - r * 0.25] draw.ellipse(box, outline=outline, width=int(r * 0.28) + width) draw.ellipse([box[0] + r * 0.14, box[1] + r * 0.14, box[2] - r * 0.14, box[3] - r * 0.14], outline=fill, width=int(r * 0.16)) # fill ring by a second pass # simpler: thick ellipse w = int(r * 0.26) draw.ellipse(box, outline=outline, width=w + width) draw.ellipse(box, outline=fill, width=w) elif cmd[0] == 'ellipse': a, b, c, d = cmd[1] box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r] draw.ellipse(box, fill=fill, outline=outline, width=width) elif cmd[0] == 'roundrect': a, b, c, d = cmd[1] box = [cx + a * r, cy + b * r, cx + c * r, cy + d * r] draw.rounded_rectangle(box, radius=r * cmd[2], fill=fill, outline=outline, width=width) elif cmd[0] == 'ring': _, ro, ri = cmd outer = [cx - r * ro, cy - r * ro, cx + r * ro, cy + r * ro] inner = [cx - r * ri, cy - r * ri, cx + r * ri, cy + r * ri] draw.ellipse(outer, fill=fill, outline=outline, width=width) # punch inner with destination-out # We'll handle punch at a higher level; draw inner as transparent later draw.ellipse(inner, fill=(0, 0, 0, 0), outline=outline, width=width) elif cmd[0] == 'face': box = [cx - r, cy - r, cx + r, cy + r] draw.ellipse(box, fill=fill, outline=outline, width=width) eye_c = outline er = r * 0.12 if cmd[1] == 'wink': draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er, cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c) draw.line([(cx + r * 0.18, cy - r * 0.28), (cx + r * 0.52, cy - r * 0.28)], fill=eye_c, width=max(width, int(r * 0.12))) elif cmd[1] == 'cool': # sunglasses draw.rounded_rectangle([cx - r * 0.7, cy - r * 0.42, cx - r * 0.08, cy - r * 0.08], radius=r * 0.12, fill=eye_c) draw.rounded_rectangle([cx + r * 0.08, cy - r * 0.42, cx + r * 0.7, cy - r * 0.08], radius=r * 0.12, fill=eye_c) draw.line([(cx - r * 0.08, cy - r * 0.25), (cx + r * 0.08, cy - r * 0.25)], fill=eye_c, width=max(3, int(r * 0.1))) else: draw.ellipse([cx - r * 0.38 - er, cy - r * 0.28 - er, cx - r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c) draw.ellipse([cx + r * 0.38 - er, cy - r * 0.28 - er, cx + r * 0.38 + er, cy - r * 0.28 + er], fill=eye_c) # smile smile = [] for i in range(9): a = math.pi * 0.2 + i * math.pi * 0.6 / 8 smile.append((cx + r * 0.48 * math.cos(a), cy + r * 0.12 + r * 0.42 * math.sin(a))) sw = max(width, int(r * 0.12)) if cmd[1] == 'grin': draw.chord([cx - r * 0.5, cy + r * 0.05, cx + r * 0.5, cy + r * 0.65], start=0, end=180, fill=eye_c, outline=eye_c) else: draw.line(smile, fill=eye_c, width=sw, joint='curve') elif cmd[0] == 'eye': # almond pts = [] for i in range(24): t = i * 2 * math.pi / 24 x = math.cos(t) y = 0.5 * math.sin(t) pts.append((cx + r * 1.05 * x, cy + r * 0.85 * y)) fill_poly(pts) iris_c = outline draw.ellipse([cx - r * 0.38, cy - r * 0.38, cx + r * 0.38, cy + r * 0.38], fill=iris_c) draw.ellipse([cx - r * 0.14, cy - r * 0.18, cx + r * 0.06, cy + r * 0.02], fill=lighten(fill[:3] if isinstance(fill, tuple) else (255, 255, 255), 0.8) + (255,)) elif cmd[0] == 'yinyang': draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width) # right half dark via chord is messy; draw a dark semicircle + two dots # Use a path: top-center to bottom via right, with small circles # We'll approximate with a pie and two discs dark = outline draw.pieslice([cx - r, cy - r, cx + r, cy + r], start=90, end=270, fill=dark) draw.ellipse([cx - r * 0.5, cy - r, cx + r * 0.5, cy], fill=dark) draw.ellipse([cx - r * 0.5, cy, cx + r * 0.5, cy + r], fill=fill) # dots draw.ellipse([cx - r * 0.16, cy - r * 0.58, cx + r * 0.16, cy - r * 0.26], fill=fill) draw.ellipse([cx - r * 0.16, cy + r * 0.26, cx + r * 0.16, cy + r * 0.58], fill=dark) draw.ellipse([cx - r, cy - r, cx + r, cy + r], outline=outline, width=width) elif cmd[0] == 'crescent': # moon: two circles, punch later — draw a crescent polygon outer, inner = [], [] for i in range(24): a = -math.pi * 0.75 + i * (1.5 * math.pi) / 23 outer.append((cx + r * math.cos(a) - r * 0.05, cy + r * math.sin(a))) ox, oy = cx + r * 0.42, cy - r * 0.05 for i in range(20, -1, -1): a = -math.pi * 0.7 + i * (1.4 * math.pi) / 20 inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a))) fill_poly(outer + inner) else: draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)def render_block(hex_color, shape): rgb = hex_rgb(hex_color) hi = lighten(rgb, 0.42) lo = darken(rgb, 0.32) img = Image.new('RGBA', (SS, SS), (0, 0, 0, 0)) cx = cy = SS / 2 r = SS * 0.36 width = max(2, SCALE) # drop shadow shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0)) sd = ImageDraw.Draw(shadow) draw_kind(sd, shadow, shape, cx + SCALE * 1.2, cy + SCALE * 1.6, r, (0, 0, 0, 90), None, 0) shadow = shadow.filter(ImageFilter.GaussianBlur(radius=SCALE * 1.1)) img = Image.alpha_composite(img, shadow) # For ring, punch a hole after drawing body body = Image.new('RGBA', (SS, SS), (0, 0, 0, 0)) bd = ImageDraw.Draw(body) draw_kind(bd, body, shape, cx, cy, r, rgb + (255,), lo + (255,), width) if shape == 'ring': # punch inner hole mask = Image.new('L', (SS, SS), 0) md = ImageDraw.Draw(mask) ri = r * 0.55 md.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], fill=255) clear = Image.new('RGBA', (SS, SS), (0, 0, 0, 0)) body = Image.composite(clear, body, mask) # redraw inner outline bd = ImageDraw.Draw(body) bd.ellipse([cx - ri, cy - ri, cx + ri, cy + ri], outline=lo + (255,), width=width) img = Image.alpha_composite(img, body) # highlight hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0)) hd = ImageDraw.Draw(hi_layer) draw_kind(hd, hi_layer, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55, hi + (110,), None, 0) hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6)) # clip highlight to body alpha body_a = body.split()[3] ha = hi_layer.split()[3] from PIL import ImageChops ha = ImageChops.multiply(ha, body_a) hi_layer.putalpha(ha) img = Image.alpha_composite(img, hi_layer) return img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)# New unlockable blocks, appended after official catalog colours.# ids are stable and must never be reordered or reused.NEW_BLOCKS = [ # Runes {'id': 'rune-fehu', 'name': 'Fehu', 'hex': '#e8a44a', 'shape': 'rune_fehu'}, {'id': 'rune-ansuz', 'name': 'Ansuz', 'hex': '#6ab0e8', 'shape': 'rune_ansuz'}, {'id': 'rune-thurisaz', 'name': 'Thurisaz', 'hex': '#c05040', 'shape': 'rune_thurisaz'}, {'id': 'rune-raido', 'name': 'Raido', 'hex': '#d0c070', 'shape': 'rune_raido'}, {'id': 'rune-sowilo', 'name': 'Sowilo', 'hex': '#f0d040', 'shape': 'rune_sowilo'}, {'id': 'rune-algiz', 'name': 'Algiz', 'hex': '#80d0a0', 'shape': 'rune_algiz'}, # Arrows {'id': 'arrow-up', 'name': 'Arrow', 'hex': '#f07040', 'shape': 'arrow'}, {'id': 'arrow-chevron', 'name': 'Chevron', 'hex': '#50c0e0', 'shape': 'chevron'}, {'id': 'arrow-double', 'name': 'Double Arrow', 'hex': '#e05080', 'shape': 'double_arrow'}, {'id': 'arrow-return', 'name': 'Return', 'hex': '#a080e0', 'shape': 'return_arrow'}, # Figures {'id': 'fig-person', 'name': 'Figure', 'hex': '#f0c0a0', 'shape': 'person'}, {'id': 'fig-walker', 'name': 'Walker', 'hex': '#c09070', 'shape': 'walker'}, {'id': 'fig-hero', 'name': 'Hero', 'hex': '#e8b070', 'shape': 'hero'}, # Faces {'id': 'face-smile', 'name': 'Smile', 'hex': '#f0d060', 'shape': 'smile'}, {'id': 'face-wink', 'name': 'Wink', 'hex': '#f0a050', 'shape': 'wink'}, {'id': 'face-cool', 'name': 'Cool', 'hex': '#6090d0', 'shape': 'cool'}, {'id': 'face-grin', 'name': 'Grin', 'hex': '#f0c848', 'shape': 'grin'}, # Icons {'id': 'icon-heart', 'name': 'Heart', 'hex': '#e04060', 'shape': 'heart'}, {'id': 'icon-moon', 'name': 'Moon', 'hex': '#d0d8f0', 'shape': 'crescent'}, {'id': 'icon-bolt', 'name': 'Bolt', 'hex': '#f0e050', 'shape': 'lightning'}, {'id': 'icon-shield', 'name': 'Shield', 'hex': '#5080c0', 'shape': 'shield'}, {'id': 'icon-crown', 'name': 'Crown', 'hex': '#f0c030', 'shape': 'crown'}, {'id': 'icon-eye', 'name': 'Eye', 'hex': '#70d0c0', 'shape': 'eye'}, {'id': 'icon-star6', 'name': 'Hexastar', 'hex': '#f0e8a0', 'shape': 'star6'}, {'id': 'icon-spiral', 'name': 'Spiral', 'hex': '#c070d0', 'shape': 'spiral'}, {'id': 'icon-wave', 'name': 'Wave', 'hex': '#3090d0', 'shape': 'wave'}, {'id': 'icon-mountain', 'name': 'Mountain', 'hex': '#809070', 'shape': 'mountain'}, {'id': 'icon-fish', 'name': 'Fish', 'hex': '#40a8c8', 'shape': 'fish'}, {'id': 'icon-bird', 'name': 'Bird', 'hex': '#e07050', 'shape': 'bird'}, {'id': 'icon-key', 'name': 'Key', 'hex': '#d0b050', 'shape': 'key'}, {'id': 'icon-comet', 'name': 'Comet', 'hex': '#90d0f0', 'shape': 'comet'}, {'id': 'icon-clover', 'name': 'Clover', 'hex': '#40b060', 'shape': 'clover'}, {'id': 'icon-paw', 'name': 'Paw', 'hex': '#c08050', 'shape': 'paw'}, {'id': 'icon-sword', 'name': 'Sword', 'hex': '#b0b8c0', 'shape': 'sword'}, {'id': 'icon-bell', 'name': 'Bell', 'hex': '#f0c848', 'shape': 'bell'}, {'id': 'icon-mushroom', 'name': 'Mushroom', 'hex': '#e06050', 'shape': 'mushroom'}, {'id': 'icon-cactus', 'name': 'Cactus', 'hex': '#50b068', 'shape': 'cactus'}, {'id': 'icon-ring', 'name': 'Ring', 'hex': '#e8d080', 'shape': 'ring'}, {'id': 'icon-flag', 'name': 'Flag', 'hex': '#d04050', 'shape': 'flag'}, {'id': 'icon-snow', 'name': 'Snowflake', 'hex': '#c8e0f8', 'shape': 'snowflake'}, {'id': 'icon-flame', 'name': 'Flame', 'hex': '#ff7030', 'shape': 'flame_icon'}, {'id': 'icon-ankh', 'name': 'Ankh', 'hex': '#d0a060', 'shape': 'ankh'}, {'id': 'icon-yin', 'name': 'Yin Yang', 'hex': '#606080', 'shape': 'yinyang'},]def official_blocks(catalog): out = [] seen = set() for planet in catalog['planets']: pid = planet['id'] for c in planet['colors']: bid = f"{pid}-{c['name']}" if bid in seen: raise SystemExit(f'duplicate official id {bid}') seen.add(bid) out.append({ 'id': bid, 'name': c['name'].capitalize() if pid == 'terra' else f"{planet['name']} {c['name']}", 'hex': c['hex'], 'shape': c.get('shape') or 'circle', 'image': c['image'], 'terra': pid == 'terra', }) return outdef main(): catalog = json.loads(CATALOG.read_text()) official = official_blocks(catalog) terra = [b for b in official if b.get('terra')] others = [b for b in official if not b.get('terra')] if len(terra) != 5 or terra[0]['id'] != 'terra-ember': raise SystemExit(f'Terra five unexpected: {[b["id"] for b in terra]}') new = [] seen = {b['id'] for b in official} OUT_IMG.mkdir(parents=True, exist_ok=True) for b in NEW_BLOCKS: if b['id'] in seen: raise SystemExit(f'duplicate new id {b["id"]}') seen.add(b['id']) image = f"images/block-{b['id']}.png" path = ROOT / 'build' / image img = render_block(b['hex'], b['shape']) img.save(path, 'PNG', optimize=True) new.append({ 'id': b['id'], 'name': b['name'], 'hex': b['hex'], 'shape': b['shape'], 'image': image, 'terra': False, }) print(f' wrote {path.relative_to(ROOT)} ({path.stat().st_size} bytes)') 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': terra + new + others, } OUT_JSON.write_text(json.dumps(registry, indent=2, ensure_ascii=False) + '\n') print(f'wrote {OUT_JSON.relative_to(ROOT)}: {len(terra)} terra + {len(new)} new + {len(others)} official = {len(registry["blocks"])} total')if __name__ == '__main__': main()@@ -18,8 +18,16 @@ try {
if ($action === 'me' || $action === '') {
$view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []];
$profile = [
'lifetime_points' => 0,
'locale' => null,
'blocks' => [],
'planets' => [],
];
if ($user) {
$view = Store::open()->viewFor($user['id']);
$store = Store::open();
$view = $store->viewFor($user['id']);
$profile = $store->profilePayload($user['id']);
}
jsonOut([
'ok' => true,
@@ -35,6 +43,10 @@ try {
'flight_duration' => METEORS_FLIGHT_DURATION,
'login_url' => 'auth.php',
'logout_url' => 'logout.php',
'lifetime_points' => $profile['lifetime_points'],
'locale' => $profile['locale'],
'blocks' => $profile['blocks'],
'planets' => $profile['planets'],
]);
}
@@ -97,6 +109,7 @@ try {
$eliminated = !empty($body['eliminated']);
$outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
$view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
$profile = $store->profilePayload($userId);
jsonOut([
'ok' => true,
'csrf' => csrfToken(),
@@ -105,8 +118,51 @@ try {
'incoming' => $view['incoming'],
'shot_results' => $view['shot_results'],
'shot_flights' => $view['shot_flights'] ?? [],
'lifetime_points' => $profile['lifetime_points'],
'locale' => $profile['locale'],
'blocks' => $profile['blocks'],
'planets' => $profile['planets'],
]);
case 'play_begin':
$mode = (string) ($body['mode'] ?? 'solo');
$ses = $store->playBegin($userId, $mode);
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'token' => $ses['token']]);
case 'play_finish':
$token = (string) ($body['token'] ?? '');
$score = isset($body['score']) ? (int) $body['score'] : 0;
$result = $store->playFinish($userId, $token, $score);
jsonOut([
'ok' => true,
'csrf' => csrfToken(),
'lifetime_points' => $result['lifetime_points'],
'awarded' => $result['awarded'],
'already' => $result['already'],
'blocks' => Blocks::present($result['lifetime_points']),
]);
case 'planet_save':
$snap = $store->saveCustomPlanet($userId, is_array($body['planet'] ?? null) ? $body['planet'] : $body);
jsonOut([
'ok' => true,
'csrf' => csrfToken(),
'planet' => $snap,
'planets' => $store->listCustomPlanets($userId),
]);
case 'planet_delete':
$store->deleteCustomPlanet($userId, (string) ($body['id'] ?? $body['planet_id'] ?? ''));
jsonOut([
'ok' => true,
'csrf' => csrfToken(),
'planets' => $store->listCustomPlanets($userId),
]);
case 'set_locale':
$locale = $store->setLocale($userId, (string) ($body['locale'] ?? ''));
jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]);
default:
jsonFail('Onbekende actie.', 404);
}
@@ -18,8 +18,16 @@ try { if ($action === 'me' || $action === '') { if ($action === 'me' || $action === '') { $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []]; $view = ['lobby' => null, 'incoming' => [], 'shot_results' => [], 'shot_flights' => []]; $profile = [ 'lifetime_points' => 0, 'locale' => null, 'blocks' => [], 'planets' => [], ]; if ($user) { if ($user) { $view = Store::open()->viewFor($user['id']); $store = Store::open(); $view = $store->viewFor($user['id']); $profile = $store->profilePayload($user['id']); } } jsonOut([ jsonOut([ 'ok' => true, 'ok' => true,@@ -35,6 +43,10 @@ try { 'flight_duration' => METEORS_FLIGHT_DURATION, 'flight_duration' => METEORS_FLIGHT_DURATION, 'login_url' => 'auth.php', 'login_url' => 'auth.php', 'logout_url' => 'logout.php', 'logout_url' => 'logout.php', 'lifetime_points' => $profile['lifetime_points'], 'locale' => $profile['locale'], 'blocks' => $profile['blocks'], 'planets' => $profile['planets'], ]); ]); } }@@ -97,6 +109,7 @@ try { $eliminated = !empty($body['eliminated']); $eliminated = !empty($body['eliminated']); $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : []; $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : []; $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing); $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing); $profile = $store->profilePayload($userId); jsonOut([ jsonOut([ 'ok' => true, 'ok' => true, 'csrf' => csrfToken(), 'csrf' => csrfToken(),@@ -105,8 +118,51 @@ try { 'incoming' => $view['incoming'], 'incoming' => $view['incoming'], 'shot_results' => $view['shot_results'], 'shot_results' => $view['shot_results'], 'shot_flights' => $view['shot_flights'] ?? [], 'shot_flights' => $view['shot_flights'] ?? [], 'lifetime_points' => $profile['lifetime_points'], 'locale' => $profile['locale'], 'blocks' => $profile['blocks'], 'planets' => $profile['planets'], ]); ]); case 'play_begin': $mode = (string) ($body['mode'] ?? 'solo'); $ses = $store->playBegin($userId, $mode); jsonOut(['ok' => true, 'csrf' => csrfToken(), 'token' => $ses['token']]); case 'play_finish': $token = (string) ($body['token'] ?? ''); $score = isset($body['score']) ? (int) $body['score'] : 0; $result = $store->playFinish($userId, $token, $score); jsonOut([ 'ok' => true, 'csrf' => csrfToken(), 'lifetime_points' => $result['lifetime_points'], 'awarded' => $result['awarded'], 'already' => $result['already'], 'blocks' => Blocks::present($result['lifetime_points']), ]); case 'planet_save': $snap = $store->saveCustomPlanet($userId, is_array($body['planet'] ?? null) ? $body['planet'] : $body); jsonOut([ 'ok' => true, 'csrf' => csrfToken(), 'planet' => $snap, 'planets' => $store->listCustomPlanets($userId), ]); case 'planet_delete': $store->deleteCustomPlanet($userId, (string) ($body['id'] ?? $body['planet_id'] ?? '')); jsonOut([ 'ok' => true, 'csrf' => csrfToken(), 'planets' => $store->listCustomPlanets($userId), ]); case 'set_locale': $locale = $store->setLocale($userId, (string) ($body['locale'] ?? '')); jsonOut(['ok' => true, 'csrf' => csrfToken(), 'locale' => $locale]); default: default: jsonFail('Onbekende actie.', 404); jsonFail('Onbekende actie.', 404); } }@@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
/**
* Append-only block registry shared with the JS client (server/lib/blocks.json).
* Never reorder entries; new blocks are appended. Thresholds stay in lockstep
* with src/blocks.js: Terra's first five are free; index 5 costs 500 lifetime
* points, each next index costs 14.5% more (rounded to a strictly increasing int).
*/
final class Blocks
{
public const TERRA_COUNT = 5;
public const FIRST_THRESHOLD = 500;
public const GROWTH = 1.145;
private static ?array $all = null;
private static ?array $byId = null;
public static function path(): string
{
return __DIR__ . '/blocks.json';
}
/** @return list<array> */
public static function all(): array
{
if (self::$all !== null) {
return self::$all;
}
$raw = file_get_contents(self::path());
if ($raw === false) {
throw new RuntimeException('blocks.json ontbreekt.');
}
$data = json_decode($raw, true);
if (!is_array($data) || !isset($data['blocks']) || !is_array($data['blocks'])) {
throw new RuntimeException('blocks.json is ongeldig.');
}
self::$all = [];
self::$byId = [];
foreach ($data['blocks'] as $i => $row) {
if (!is_array($row) || empty($row['id'])) {
continue;
}
$row['_index'] = $i;
self::$all[] = $row;
self::$byId[(string) $row['id']] = $row;
}
if (count(self::$all) < self::TERRA_COUNT) {
throw new RuntimeException('blocks.json mist de Terra-blokjes.');
}
return self::$all;
}
public static function byId(string $id): ?array
{
if (self::$byId === null) {
self::all();
}
return self::$byId[$id] ?? null;
}
public static function known(string $id): bool
{
return self::byId($id) !== null;
}
public static function indexOf(string $id): ?int
{
$b = self::byId($id);
return $b !== null ? (int) $b['_index'] : null;
}
public static function isTerra(string $id): bool
{
$i = self::indexOf($id);
return $i !== null && $i < self::TERRA_COUNT;
}
/** Lifetime points required to unlock the block at $index (0-based). */
public static function threshold(int $index): int
{
if ($index < self::TERRA_COUNT) {
return 0;
}
$t = self::FIRST_THRESHOLD;
for ($i = self::TERRA_COUNT; $i < $index; $i++) {
$next = (int) round($t * self::GROWTH);
$t = max($t + 1, $next);
}
return $t;
}
public static function unlocked(int $index, int $points): bool
{
return $points >= self::threshold($index);
}
public static function unlockedId(string $id, int $points): bool
{
$i = self::indexOf($id);
return $i !== null && self::unlocked($i, $points);
}
/** Public list for the client: every block plus its threshold and unlock state. */
public static function present(int $points): array
{
$out = [];
foreach (self::all() as $i => $b) {
$need = self::threshold($i);
$out[] = [
'id' => (string) $b['id'],
'name' => (string) ($b['name'] ?? $b['id']),
'hex' => (string) ($b['hex'] ?? '#888'),
'shape' => (string) ($b['shape'] ?? ''),
'image' => (string) ($b['image'] ?? ''),
'terra' => !empty($b['terra']) || $i < self::TERRA_COUNT,
'index' => $i,
'threshold' => $need,
'unlocked' => $points >= $need,
];
}
return $out;
}
/** Resolve a registry id to a planet-slot colour (with a 0–4 slot id). */
public static function asColor(string $id, int $slot): ?array
{
$b = self::byId($id);
if ($b === null) {
return null;
}
return [
'id' => $slot,
'block' => (string) $b['id'],
'name' => (string) ($b['name'] ?? $b['id']),
'hex' => (string) ($b['hex'] ?? '#888'),
'shape' => (string) ($b['shape'] ?? ''),
'image' => (string) ($b['image'] ?? ''),
];
}
}
@@ -0,0 +1,141 @@<?phpdeclare(strict_types=1);/** * Append-only block registry shared with the JS client (server/lib/blocks.json). * Never reorder entries; new blocks are appended. Thresholds stay in lockstep * with src/blocks.js: Terra's first five are free; index 5 costs 500 lifetime * points, each next index costs 14.5% more (rounded to a strictly increasing int). */final class Blocks{ public const TERRA_COUNT = 5; public const FIRST_THRESHOLD = 500; public const GROWTH = 1.145; private static ?array $all = null; private static ?array $byId = null; public static function path(): string { return __DIR__ . '/blocks.json'; } /** @return list<array> */ public static function all(): array { if (self::$all !== null) { return self::$all; } $raw = file_get_contents(self::path()); if ($raw === false) { throw new RuntimeException('blocks.json ontbreekt.'); } $data = json_decode($raw, true); if (!is_array($data) || !isset($data['blocks']) || !is_array($data['blocks'])) { throw new RuntimeException('blocks.json is ongeldig.'); } self::$all = []; self::$byId = []; foreach ($data['blocks'] as $i => $row) { if (!is_array($row) || empty($row['id'])) { continue; } $row['_index'] = $i; self::$all[] = $row; self::$byId[(string) $row['id']] = $row; } if (count(self::$all) < self::TERRA_COUNT) { throw new RuntimeException('blocks.json mist de Terra-blokjes.'); } return self::$all; } public static function byId(string $id): ?array { if (self::$byId === null) { self::all(); } return self::$byId[$id] ?? null; } public static function known(string $id): bool { return self::byId($id) !== null; } public static function indexOf(string $id): ?int { $b = self::byId($id); return $b !== null ? (int) $b['_index'] : null; } public static function isTerra(string $id): bool { $i = self::indexOf($id); return $i !== null && $i < self::TERRA_COUNT; } /** Lifetime points required to unlock the block at $index (0-based). */ public static function threshold(int $index): int { if ($index < self::TERRA_COUNT) { return 0; } $t = self::FIRST_THRESHOLD; for ($i = self::TERRA_COUNT; $i < $index; $i++) { $next = (int) round($t * self::GROWTH); $t = max($t + 1, $next); } return $t; } public static function unlocked(int $index, int $points): bool { return $points >= self::threshold($index); } public static function unlockedId(string $id, int $points): bool { $i = self::indexOf($id); return $i !== null && self::unlocked($i, $points); } /** Public list for the client: every block plus its threshold and unlock state. */ public static function present(int $points): array { $out = []; foreach (self::all() as $i => $b) { $need = self::threshold($i); $out[] = [ 'id' => (string) $b['id'], 'name' => (string) ($b['name'] ?? $b['id']), 'hex' => (string) ($b['hex'] ?? '#888'), 'shape' => (string) ($b['shape'] ?? ''), 'image' => (string) ($b['image'] ?? ''), 'terra' => !empty($b['terra']) || $i < self::TERRA_COUNT, 'index' => $i, 'threshold' => $need, 'unlocked' => $points >= $need, ]; } return $out; } /** Resolve a registry id to a planet-slot colour (with a 0–4 slot id). */ public static function asColor(string $id, int $slot): ?array { $b = self::byId($id); if ($b === null) { return null; } return [ 'id' => $slot, 'block' => (string) $b['id'], 'name' => (string) ($b['name'] ?? $b['id']), 'hex' => (string) ($b['hex'] ?? '#888'), 'shape' => (string) ($b['shape'] ?? ''), 'image' => (string) ($b['image'] ?? ''), ]; }}@@ -149,6 +149,39 @@ final class Planets
];
}
/** Present a raw planet array (catalog or a validated custom snapshot). */
public static function presentData(array $p): array
{
$d = self::displayValues($p);
$colors = [];
foreach ($p['colors'] ?? [] as $c) {
if (!is_array($c)) {
continue;
}
$colors[] = [
'id' => (int) ($c['id'] ?? 0),
'block' => (string) ($c['block'] ?? $c['name'] ?? ''),
'name' => (string) ($c['name'] ?? ''),
'hex' => (string) ($c['hex'] ?? '#888'),
'shape' => (string) ($c['shape'] ?? ''),
'image' => (string) ($c['image'] ?? ''),
];
}
return [
'id' => (string) ($p['id'] ?? ''),
'name' => (string) ($p['name'] ?? ''),
'people' => (string) ($p['people'] ?? ''),
'jumpsToClear' => (float) ($p['jumpsToClear'] ?? 2),
'fallTime' => (float) ($p['fallTime'] ?? 3),
'riseTime' => (float) ($p['riseTime'] ?? 1.5),
'miss_chance' => $d['missChance'],
'display' => $d,
'colors' => $colors,
'custom' => !empty($p['custom']),
'owner_id' => isset($p['owner_id']) ? (string) $p['owner_id'] : null,
];
}
private static function clamp(float $value, float $lo, float $hi): float
{
return max($lo, min($hi, $value));
@@ -149,6 +149,39 @@ final class Planets ]; ]; } } /** Present a raw planet array (catalog or a validated custom snapshot). */ public static function presentData(array $p): array { $d = self::displayValues($p); $colors = []; foreach ($p['colors'] ?? [] as $c) { if (!is_array($c)) { continue; } $colors[] = [ 'id' => (int) ($c['id'] ?? 0), 'block' => (string) ($c['block'] ?? $c['name'] ?? ''), 'name' => (string) ($c['name'] ?? ''), 'hex' => (string) ($c['hex'] ?? '#888'), 'shape' => (string) ($c['shape'] ?? ''), 'image' => (string) ($c['image'] ?? ''), ]; } return [ 'id' => (string) ($p['id'] ?? ''), 'name' => (string) ($p['name'] ?? ''), 'people' => (string) ($p['people'] ?? ''), 'jumpsToClear' => (float) ($p['jumpsToClear'] ?? 2), 'fallTime' => (float) ($p['fallTime'] ?? 3), 'riseTime' => (float) ($p['riseTime'] ?? 1.5), 'miss_chance' => $d['missChance'], 'display' => $d, 'colors' => $colors, 'custom' => !empty($p['custom']), 'owner_id' => isset($p['owner_id']) ? (string) $p['owner_id'] : null, ]; } private static function clamp(float $value, float $lo, float $hi): float private static function clamp(float $value, float $lo, float $hi): float { { return max($lo, min($hi, $value)); return max($lo, min($hi, $value));@@ -2,6 +2,7 @@
declare(strict_types=1);
require_once __DIR__ . '/Planets.php';
require_once __DIR__ . '/Blocks.php';
final class Store
{
@@ -74,9 +75,46 @@ CREATE TABLE IF NOT EXISTS shots (
CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
SQL);
$this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
$this->ensureColumn('members', 'planet_json', 'TEXT');
$this->ensureColumn('shots', 'land_col', 'INTEGER');
$this->ensureColumn('shots', 'from_col', 'INTEGER');
$this->ensureColumn('shots', 'from_y', 'REAL');
$this->pdo->exec(<<<'SQL'
CREATE TABLE IF NOT EXISTS profiles (
user_id TEXT PRIMARY KEY,
lifetime_points INTEGER NOT NULL DEFAULT 0,
locale TEXT,
updated INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS point_awards (
award_key TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
mode TEXT NOT NULL,
points INTEGER NOT NULL,
created INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS point_awards_user ON point_awards (user_id);
CREATE TABLE IF NOT EXISTS play_sessions (
token TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
mode TEXT NOT NULL,
started INTEGER NOT NULL,
finished INTEGER
);
CREATE TABLE IF NOT EXISTS custom_planets (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
name TEXT NOT NULL,
people TEXT NOT NULL,
jumps_to_clear REAL NOT NULL,
fall_time REAL NOT NULL,
rise_time REAL NOT NULL,
colors TEXT NOT NULL,
created INTEGER NOT NULL,
updated INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS custom_planets_user ON custom_planets (user_id);
SQL);
}
private function ensureColumn(string $table, string $column, string $ddl): void
@@ -111,9 +149,12 @@ SQL);
}
}
/** Tests may freeze the clock without sleeping. */
public ?int $testNow = null;
private function now(): int
{
return time();
return $this->testNow ?? time();
}
private function nowf(): float
@@ -205,11 +246,11 @@ SQL);
'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
VALUES (?,?,?,?,?,?,?)'
)->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
$planet = Planets::known($planetId) ? $planetId : Planets::defaultId();
$choice = $this->choosePlanet($userId, $planetId, false);
$this->pdo->prepare(
'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id)
VALUES (?,?,?,0,?,?,?)'
)->execute([$id, $userId, $name, $now, $now, $planet]);
'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json)
VALUES (?,?,?,0,?,?,?,?)'
)->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
return $this->getLobby($id);
});
}
@@ -236,9 +277,10 @@ SQL);
throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
}
$now = $this->now();
$choice = $this->choosePlanet($userId, $planetId, false);
$this->pdo->prepare(
'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id)
VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?)
'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json)
VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?)
ON CONFLICT(lobby_id, user_id) DO UPDATE SET
name = excluded.name,
ready = 0,
@@ -249,8 +291,9 @@ SQL);
last_seen = excluded.last_seen,
score = 0,
snapshot = NULL,
planet_id = excluded.planet_id'
)->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]);
planet_id = excluded.planet_id,
planet_json = excluded.planet_json'
)->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]);
return $this->getLobby($lobby['id']);
});
}
@@ -352,12 +395,10 @@ SQL);
if ($lobby['status'] !== 'waiting') {
throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
}
if (!Planets::known($planetId)) {
throw new RuntimeException('Onbekende planeet.');
}
$choice = $this->choosePlanet($userId, $planetId, true);
$this->pdo->prepare(
'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
)->execute([$planetId, $this->now(), $lobby['id'], $userId]);
'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
)->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]);
return $this->getLobby($lobby['id']);
});
}
@@ -368,6 +409,12 @@ SQL);
if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
return max(0.0, min(1.0, $this->testMissOverride));
}
if (!empty($member['planet_json'])) {
$data = json_decode((string) $member['planet_json'], true);
if (is_array($data)) {
return Planets::missChance($data);
}
}
$id = (string) ($member['planet_id'] ?? Planets::defaultId());
return Planets::missChanceForId($id);
}
@@ -662,6 +709,7 @@ SQL);
if ($lobby['status'] === 'playing') {
$flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']);
}
$this->maybeAwardOnlineLobby($lobby);
return [
'lobby' => $this->presentLobby($lobby, $userId),
'incoming' => $incoming,
@@ -691,7 +739,7 @@ SQL);
'is_me' => $m['user_id'] === $userId,
'score' => (int) $m['score'],
'snapshot' => $m['user_id'] === $userId ? null : $snap,
'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())),
'planet' => $this->presentMemberPlanet($m),
];
}
$rankings = [];
@@ -725,4 +773,349 @@ SQL);
'podium_seconds' => METEORS_PODIUM_SECONDS,
];
}
public const MAX_CUSTOM_PLANETS = 30;
public const MAX_GAME_POINTS = 10000;
public const MAX_POINTS_PER_SEC = 4.0;
public const MIN_PLAY_SECONDS = 3;
public const PLAY_TOKEN_TTL = 21600;
public const NAME_MAX = 32;
/** @return array{planet_id:string,planet_json:?string} */
public function choosePlanet(string $userId, string $planetId, bool $strict): array
{
if ($planetId === '') {
if ($strict) {
throw new RuntimeException('Onbekende planeet.');
}
return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
}
if (Planets::known($planetId)) {
return ['planet_id' => $planetId, 'planet_json' => null];
}
$row = $this->ownedCustom($userId, $planetId);
if ($row) {
return [
'planet_id' => $planetId,
'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE),
];
}
if ($strict) {
throw new RuntimeException('Onbekende planeet.');
}
return ['planet_id' => Planets::defaultId(), 'planet_json' => null];
}
/** @param array<string,mixed> $member */
public function presentMemberPlanet(array $member): array
{
if (!empty($member['planet_json'])) {
$data = json_decode((string) $member['planet_json'], true);
if (is_array($data) && !empty($data['id'])) {
return Planets::presentData($data);
}
}
return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId()));
}
public function ensureProfile(string $userId): array
{
$stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?');
$stmt->execute([$userId]);
$row = $stmt->fetch();
if ($row) {
return $row;
}
$now = $this->now();
$this->pdo->prepare(
'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)'
)->execute([$userId, $now]);
return [
'user_id' => $userId,
'lifetime_points' => 0,
'locale' => null,
'updated' => $now,
];
}
public function lifetimePoints(string $userId): int
{
return (int) $this->ensureProfile($userId)['lifetime_points'];
}
public function locale(string $userId): ?string
{
$v = $this->ensureProfile($userId)['locale'] ?? null;
return is_string($v) && $v !== '' ? $v : null;
}
/** @var list<string> */
public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
public function setLocale(string $userId, string $locale): string
{
$locale = strtolower($locale);
if (!in_array($locale, self::LOCALES, true)) {
throw new RuntimeException('Onbekende taal.');
}
$this->ensureProfile($userId);
$this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?')
->execute([$locale, $this->now(), $userId]);
return $locale;
}
/**
* Add points once for a unique award_key. Returns the new lifetime total.
* $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op.
*/
public function awardPoints(string $userId, int $points, string $key, string $mode): int
{
return $this->transaction(function () use ($userId, $points, $key, $mode) {
$this->ensureProfile($userId);
$points = max(0, min(self::MAX_GAME_POINTS, $points));
$stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?');
$stmt->execute([$key]);
if ($stmt->fetch()) {
return $this->lifetimePoints($userId);
}
$this->pdo->prepare(
'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)'
)->execute([$key, $userId, $mode, $points, $this->now()]);
if ($points > 0) {
$this->pdo->prepare(
'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?'
)->execute([$points, $this->now(), $userId]);
}
return $this->lifetimePoints($userId);
});
}
public function playBegin(string $userId, string $mode): array
{
if (!in_array($mode, ['solo', 'offline'], true)) {
throw new RuntimeException('Onbekende speelmodus.');
}
$token = bin2hex(random_bytes(16));
$this->pdo->prepare(
'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)'
)->execute([$token, $userId, $mode, $this->now()]);
return ['token' => $token, 'started' => $this->now()];
}
public function playFinish(string $userId, string $token, int $score): array
{
return $this->transaction(function () use ($userId, $token, $score) {
$stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?');
$stmt->execute([$token]);
$ses = $stmt->fetch();
if (!$ses || $ses['user_id'] !== $userId) {
throw new RuntimeException('Ongeldige speelsessie.');
}
$key = 'play:' . $token;
if ($ses['finished'] !== null) {
return [
'lifetime_points' => $this->lifetimePoints($userId),
'awarded' => 0,
'already' => true,
];
}
$now = $this->now();
$started = (int) $ses['started'];
if ($now - $started > self::PLAY_TOKEN_TTL) {
$this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
->execute([$now, $token]);
throw new RuntimeException('Speelsessie is verlopen.');
}
$duration = max(0, $now - $started);
$score = max(0, $score);
$awarded = 0;
if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) {
$awarded = 0;
} else {
$cap = (int) floor($duration * self::MAX_POINTS_PER_SEC);
$awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0)));
}
$this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?')
->execute([$now, $token]);
$total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']);
return [
'lifetime_points' => $total,
'awarded' => $awarded,
'already' => false,
];
});
}
/** @param array<string,mixed> $lobby */
public function maybeAwardOnlineLobby(array $lobby): void
{
$finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']);
foreach ($this->members($lobby['id'], true) as $m) {
if (!$finished && empty($m['eliminated'])) {
continue;
}
$uid = (string) $m['user_id'];
$key = 'online:' . $lobby['id'] . ':' . $uid;
$this->awardPoints($uid, (int) $m['score'], $key, 'online');
}
}
/** @return ?array<string,mixed> */
public function ownedCustom(string $userId, string $id): ?array
{
$stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?');
$stmt->execute([$id, $userId]);
$row = $stmt->fetch();
return $row ?: null;
}
/** @return list<array<string,mixed>> */
public function listCustomPlanets(string $userId): array
{
$stmt = $this->pdo->prepare(
'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC'
);
$stmt->execute([$userId]);
$out = [];
foreach ($stmt->fetchAll() as $row) {
$out[] = $this->snapshotCustom($row);
}
return $out;
}
public static function sanitizeName(string $raw, string $field): string
{
$s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? '');
$s = strip_tags($s);
if ($s === '') {
throw new RuntimeException('Vul een ' . $field . ' in.');
}
if (mb_strlen($s) > self::NAME_MAX) {
$s = mb_substr($s, 0, self::NAME_MAX);
}
return $s;
}
/**
* Create or update a custom planet owned by $userId.
* @param array<string,mixed> $data
* @return array<string,mixed> snapshot
*/
public function saveCustomPlanet(string $userId, array $data): array
{
return $this->transaction(function () use ($userId, $data) {
$name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam');
$people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam');
$j = self::clampFloat((float) ($data['jumpsToClear'] ?? 2), 1, 4);
$f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5);
$r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3);
$ids = $data['colors'] ?? $data['blocks'] ?? [];
if (!is_array($ids) || count($ids) !== 5) {
throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.');
}
$points = $this->lifetimePoints($userId);
$blockIds = [];
foreach ($ids as $entry) {
if (is_array($entry)) {
$bid = (string) ($entry['block'] ?? $entry['id'] ?? '');
} else {
$bid = (string) $entry;
}
if ($bid === '' || !Blocks::known($bid)) {
throw new RuntimeException('Onbekend blokje.');
}
if (!Blocks::unlockedId($bid, $points)) {
throw new RuntimeException('Dit blokje is nog niet ontgrendeld.');
}
if (in_array($bid, $blockIds, true)) {
throw new RuntimeException('Elk blokje mag maar in één vak.');
}
$blockIds[] = $bid;
}
$now = $this->now();
$id = isset($data['id']) ? (string) $data['id'] : '';
if ($id !== '') {
$row = $this->ownedCustom($userId, $id);
if (!$row) {
throw new RuntimeException('Onbekende planeet.');
}
$this->pdo->prepare(
'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?'
)->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]);
} else {
$stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?');
$stmt->execute([$userId]);
if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) {
throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.');
}
$id = 'c_' . bin2hex(random_bytes(8));
$this->pdo->prepare(
'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated)
VALUES (?,?,?,?,?,?,?,?,?,?)'
)->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]);
}
$row = $this->ownedCustom($userId, $id);
if (!$row) {
throw new RuntimeException('Opslaan is mislukt.');
}
return $this->snapshotCustom($row);
});
}
public function deleteCustomPlanet(string $userId, string $id): void
{
$row = $this->ownedCustom($userId, $id);
if (!$row) {
throw new RuntimeException('Onbekende planeet.');
}
$this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?')
->execute([$id, $userId]);
}
/** @param array<string,mixed> $row */
public function snapshotCustom(array $row): array
{
$ids = json_decode((string) $row['colors'], true);
if (!is_array($ids)) {
$ids = [];
}
$colors = [];
foreach ($ids as $i => $id) {
$c = Blocks::asColor((string) $id, (int) $i);
if ($c === null) {
continue;
}
$colors[] = $c;
}
$p = [
'id' => (string) $row['id'],
'name' => (string) $row['name'],
'people' => (string) $row['people'],
'jumpsToClear' => (float) $row['jumps_to_clear'],
'fallTime' => (float) $row['fall_time'],
'riseTime' => (float) $row['rise_time'],
'colors' => $colors,
'custom' => true,
'owner_id' => (string) $row['user_id'],
];
return Planets::presentData($p);
}
public function profilePayload(string $userId): array
{
$points = $this->lifetimePoints($userId);
return [
'lifetime_points' => $points,
'locale' => $this->locale($userId),
'blocks' => Blocks::present($points),
'planets' => $this->listCustomPlanets($userId),
];
}
private static function clampFloat(float $value, float $lo, float $hi): float
{
return max($lo, min($hi, $value));
}
}
@@ -2,6 +2,7 @@declare(strict_types=1);declare(strict_types=1);require_once __DIR__ . '/Planets.php';require_once __DIR__ . '/Planets.php';require_once __DIR__ . '/Blocks.php';final class Storefinal class Store{{@@ -74,9 +75,46 @@ CREATE TABLE IF NOT EXISTS shots (CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);SQL);SQL); $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'"); $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'"); $this->ensureColumn('members', 'planet_json', 'TEXT'); $this->ensureColumn('shots', 'land_col', 'INTEGER'); $this->ensureColumn('shots', 'land_col', 'INTEGER'); $this->ensureColumn('shots', 'from_col', 'INTEGER'); $this->ensureColumn('shots', 'from_col', 'INTEGER'); $this->ensureColumn('shots', 'from_y', 'REAL'); $this->ensureColumn('shots', 'from_y', 'REAL'); $this->pdo->exec(<<<'SQL'CREATE TABLE IF NOT EXISTS profiles ( user_id TEXT PRIMARY KEY, lifetime_points INTEGER NOT NULL DEFAULT 0, locale TEXT, updated INTEGER NOT NULL);CREATE TABLE IF NOT EXISTS point_awards ( award_key TEXT PRIMARY KEY, user_id TEXT NOT NULL, mode TEXT NOT NULL, points INTEGER NOT NULL, created INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS point_awards_user ON point_awards (user_id);CREATE TABLE IF NOT EXISTS play_sessions ( token TEXT PRIMARY KEY, user_id TEXT NOT NULL, mode TEXT NOT NULL, started INTEGER NOT NULL, finished INTEGER);CREATE TABLE IF NOT EXISTS custom_planets ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, name TEXT NOT NULL, people TEXT NOT NULL, jumps_to_clear REAL NOT NULL, fall_time REAL NOT NULL, rise_time REAL NOT NULL, colors TEXT NOT NULL, created INTEGER NOT NULL, updated INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS custom_planets_user ON custom_planets (user_id);SQL); } } private function ensureColumn(string $table, string $column, string $ddl): void private function ensureColumn(string $table, string $column, string $ddl): void@@ -111,9 +149,12 @@ SQL); } } } } /** Tests may freeze the clock without sleeping. */ public ?int $testNow = null; private function now(): int private function now(): int { { return time(); return $this->testNow ?? time(); } } private function nowf(): float private function nowf(): float@@ -205,11 +246,11 @@ SQL); 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created) 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created) VALUES (?,?,?,?,?,?,?)' VALUES (?,?,?,?,?,?,?)' )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]); )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]); $planet = Planets::known($planetId) ? $planetId : Planets::defaultId(); $choice = $this->choosePlanet($userId, $planetId, false); $this->pdo->prepare( $this->pdo->prepare( 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id) 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id, planet_json) VALUES (?,?,?,0,?,?,?)' VALUES (?,?,?,0,?,?,?,?)' )->execute([$id, $userId, $name, $now, $now, $planet]); )->execute([$id, $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]); return $this->getLobby($id); return $this->getLobby($id); }); }); } }@@ -236,9 +277,10 @@ SQL); throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).'); throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).'); } } $now = $this->now(); $now = $this->now(); $choice = $this->choosePlanet($userId, $planetId, false); $this->pdo->prepare( $this->pdo->prepare( 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id) 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id, planet_json) VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?) VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?,?) ON CONFLICT(lobby_id, user_id) DO UPDATE SET ON CONFLICT(lobby_id, user_id) DO UPDATE SET name = excluded.name, name = excluded.name, ready = 0, ready = 0,@@ -249,8 +291,9 @@ SQL); last_seen = excluded.last_seen, last_seen = excluded.last_seen, score = 0, score = 0, snapshot = NULL, snapshot = NULL, planet_id = excluded.planet_id' planet_id = excluded.planet_id, )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]); planet_json = excluded.planet_json' )->execute([$lobby['id'], $userId, $name, $now, $now, $choice['planet_id'], $choice['planet_json']]); return $this->getLobby($lobby['id']); return $this->getLobby($lobby['id']); }); }); } }@@ -352,12 +395,10 @@ SQL); if ($lobby['status'] !== 'waiting') { if ($lobby['status'] !== 'waiting') { throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.'); throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.'); } } if (!Planets::known($planetId)) { $choice = $this->choosePlanet($userId, $planetId, true); throw new RuntimeException('Onbekende planeet.'); } $this->pdo->prepare( $this->pdo->prepare( 'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' 'UPDATE members SET planet_id = ?, planet_json = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL' )->execute([$planetId, $this->now(), $lobby['id'], $userId]); )->execute([$choice['planet_id'], $choice['planet_json'], $this->now(), $lobby['id'], $userId]); return $this->getLobby($lobby['id']); return $this->getLobby($lobby['id']); }); }); } }@@ -368,6 +409,12 @@ SQL); if (isset($this->testMissOverride) && is_float($this->testMissOverride)) { if (isset($this->testMissOverride) && is_float($this->testMissOverride)) { return max(0.0, min(1.0, $this->testMissOverride)); return max(0.0, min(1.0, $this->testMissOverride)); } } if (!empty($member['planet_json'])) { $data = json_decode((string) $member['planet_json'], true); if (is_array($data)) { return Planets::missChance($data); } } $id = (string) ($member['planet_id'] ?? Planets::defaultId()); $id = (string) ($member['planet_id'] ?? Planets::defaultId()); return Planets::missChanceForId($id); return Planets::missChanceForId($id); } }@@ -662,6 +709,7 @@ SQL); if ($lobby['status'] === 'playing') { if ($lobby['status'] === 'playing') { $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']); $flights = $this->recentFlights($lobby['id'], (float) $lobby['flight_duration']); } } $this->maybeAwardOnlineLobby($lobby); return [ return [ 'lobby' => $this->presentLobby($lobby, $userId), 'lobby' => $this->presentLobby($lobby, $userId), 'incoming' => $incoming, 'incoming' => $incoming,@@ -691,7 +739,7 @@ SQL); 'is_me' => $m['user_id'] === $userId, 'is_me' => $m['user_id'] === $userId, 'score' => (int) $m['score'], 'score' => (int) $m['score'], 'snapshot' => $m['user_id'] === $userId ? null : $snap, 'snapshot' => $m['user_id'] === $userId ? null : $snap, 'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())), 'planet' => $this->presentMemberPlanet($m), ]; ]; } } $rankings = []; $rankings = [];@@ -725,4 +773,349 @@ SQL); 'podium_seconds' => METEORS_PODIUM_SECONDS, 'podium_seconds' => METEORS_PODIUM_SECONDS, ]; ]; } } public const MAX_CUSTOM_PLANETS = 30; public const MAX_GAME_POINTS = 10000; public const MAX_POINTS_PER_SEC = 4.0; public const MIN_PLAY_SECONDS = 3; public const PLAY_TOKEN_TTL = 21600; public const NAME_MAX = 32; /** @return array{planet_id:string,planet_json:?string} */ public function choosePlanet(string $userId, string $planetId, bool $strict): array { if ($planetId === '') { if ($strict) { throw new RuntimeException('Onbekende planeet.'); } return ['planet_id' => Planets::defaultId(), 'planet_json' => null]; } if (Planets::known($planetId)) { return ['planet_id' => $planetId, 'planet_json' => null]; } $row = $this->ownedCustom($userId, $planetId); if ($row) { return [ 'planet_id' => $planetId, 'planet_json' => json_encode($this->snapshotCustom($row), JSON_UNESCAPED_UNICODE), ]; } if ($strict) { throw new RuntimeException('Onbekende planeet.'); } return ['planet_id' => Planets::defaultId(), 'planet_json' => null]; } /** @param array<string,mixed> $member */ public function presentMemberPlanet(array $member): array { if (!empty($member['planet_json'])) { $data = json_decode((string) $member['planet_json'], true); if (is_array($data) && !empty($data['id'])) { return Planets::presentData($data); } } return Planets::present((string) ($member['planet_id'] ?? Planets::defaultId())); } public function ensureProfile(string $userId): array { $stmt = $this->pdo->prepare('SELECT * FROM profiles WHERE user_id = ?'); $stmt->execute([$userId]); $row = $stmt->fetch(); if ($row) { return $row; } $now = $this->now(); $this->pdo->prepare( 'INSERT INTO profiles (user_id, lifetime_points, locale, updated) VALUES (?,0,NULL,?)' )->execute([$userId, $now]); return [ 'user_id' => $userId, 'lifetime_points' => 0, 'locale' => null, 'updated' => $now, ]; } public function lifetimePoints(string $userId): int { return (int) $this->ensureProfile($userId)['lifetime_points']; } public function locale(string $userId): ?string { $v = $this->ensureProfile($userId)['locale'] ?? null; return is_string($v) && $v !== '' ? $v : null; } /** @var list<string> */ public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es']; public function setLocale(string $userId, string $locale): string { $locale = strtolower($locale); if (!in_array($locale, self::LOCALES, true)) { throw new RuntimeException('Onbekende taal.'); } $this->ensureProfile($userId); $this->pdo->prepare('UPDATE profiles SET locale = ?, updated = ? WHERE user_id = ?') ->execute([$locale, $this->now(), $userId]); return $locale; } /** * Add points once for a unique award_key. Returns the new lifetime total. * $points is clamped to [0, MAX_GAME_POINTS]. A repeat key is a no-op. */ public function awardPoints(string $userId, int $points, string $key, string $mode): int { return $this->transaction(function () use ($userId, $points, $key, $mode) { $this->ensureProfile($userId); $points = max(0, min(self::MAX_GAME_POINTS, $points)); $stmt = $this->pdo->prepare('SELECT points FROM point_awards WHERE award_key = ?'); $stmt->execute([$key]); if ($stmt->fetch()) { return $this->lifetimePoints($userId); } $this->pdo->prepare( 'INSERT INTO point_awards (award_key, user_id, mode, points, created) VALUES (?,?,?,?,?)' )->execute([$key, $userId, $mode, $points, $this->now()]); if ($points > 0) { $this->pdo->prepare( 'UPDATE profiles SET lifetime_points = lifetime_points + ?, updated = ? WHERE user_id = ?' )->execute([$points, $this->now(), $userId]); } return $this->lifetimePoints($userId); }); } public function playBegin(string $userId, string $mode): array { if (!in_array($mode, ['solo', 'offline'], true)) { throw new RuntimeException('Onbekende speelmodus.'); } $token = bin2hex(random_bytes(16)); $this->pdo->prepare( 'INSERT INTO play_sessions (token, user_id, mode, started) VALUES (?,?,?,?)' )->execute([$token, $userId, $mode, $this->now()]); return ['token' => $token, 'started' => $this->now()]; } public function playFinish(string $userId, string $token, int $score): array { return $this->transaction(function () use ($userId, $token, $score) { $stmt = $this->pdo->prepare('SELECT * FROM play_sessions WHERE token = ?'); $stmt->execute([$token]); $ses = $stmt->fetch(); if (!$ses || $ses['user_id'] !== $userId) { throw new RuntimeException('Ongeldige speelsessie.'); } $key = 'play:' . $token; if ($ses['finished'] !== null) { return [ 'lifetime_points' => $this->lifetimePoints($userId), 'awarded' => 0, 'already' => true, ]; } $now = $this->now(); $started = (int) $ses['started']; if ($now - $started > self::PLAY_TOKEN_TTL) { $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?') ->execute([$now, $token]); throw new RuntimeException('Speelsessie is verlopen.'); } $duration = max(0, $now - $started); $score = max(0, $score); $awarded = 0; if ($score > 0 && $duration < self::MIN_PLAY_SECONDS) { $awarded = 0; } else { $cap = (int) floor($duration * self::MAX_POINTS_PER_SEC); $awarded = max(0, min(self::MAX_GAME_POINTS, $score, max($cap, 0))); } $this->pdo->prepare('UPDATE play_sessions SET finished = ? WHERE token = ?') ->execute([$now, $token]); $total = $this->awardPoints($userId, $awarded, $key, (string) $ses['mode']); return [ 'lifetime_points' => $total, 'awarded' => $awarded, 'already' => false, ]; }); } /** @param array<string,mixed> $lobby */ public function maybeAwardOnlineLobby(array $lobby): void { $finished = ($lobby['status'] ?? '') === 'finished' || !empty($lobby['finished']); foreach ($this->members($lobby['id'], true) as $m) { if (!$finished && empty($m['eliminated'])) { continue; } $uid = (string) $m['user_id']; $key = 'online:' . $lobby['id'] . ':' . $uid; $this->awardPoints($uid, (int) $m['score'], $key, 'online'); } } /** @return ?array<string,mixed> */ public function ownedCustom(string $userId, string $id): ?array { $stmt = $this->pdo->prepare('SELECT * FROM custom_planets WHERE id = ? AND user_id = ?'); $stmt->execute([$id, $userId]); $row = $stmt->fetch(); return $row ?: null; } /** @return list<array<string,mixed>> */ public function listCustomPlanets(string $userId): array { $stmt = $this->pdo->prepare( 'SELECT * FROM custom_planets WHERE user_id = ? ORDER BY updated DESC' ); $stmt->execute([$userId]); $out = []; foreach ($stmt->fetchAll() as $row) { $out[] = $this->snapshotCustom($row); } return $out; } public static function sanitizeName(string $raw, string $field): string { $s = trim(preg_replace('/[\x00-\x1F\x7F]+/u', '', $raw) ?? ''); $s = strip_tags($s); if ($s === '') { throw new RuntimeException('Vul een ' . $field . ' in.'); } if (mb_strlen($s) > self::NAME_MAX) { $s = mb_substr($s, 0, self::NAME_MAX); } return $s; } /** * Create or update a custom planet owned by $userId. * @param array<string,mixed> $data * @return array<string,mixed> snapshot */ public function saveCustomPlanet(string $userId, array $data): array { return $this->transaction(function () use ($userId, $data) { $name = self::sanitizeName((string) ($data['name'] ?? ''), 'planeetnaam'); $people = self::sanitizeName((string) ($data['people'] ?? ''), 'bevolkingsnaam'); $j = self::clampFloat((float) ($data['jumpsToClear'] ?? 2), 1, 4); $f = self::clampFloat((float) ($data['fallTime'] ?? 3), 1, 5); $r = self::clampFloat((float) ($data['riseTime'] ?? 1.5), 0.5, 3); $ids = $data['colors'] ?? $data['blocks'] ?? []; if (!is_array($ids) || count($ids) !== 5) { throw new RuntimeException('Een planeet heeft precies vijf blokjes nodig.'); } $points = $this->lifetimePoints($userId); $blockIds = []; foreach ($ids as $entry) { if (is_array($entry)) { $bid = (string) ($entry['block'] ?? $entry['id'] ?? ''); } else { $bid = (string) $entry; } if ($bid === '' || !Blocks::known($bid)) { throw new RuntimeException('Onbekend blokje.'); } if (!Blocks::unlockedId($bid, $points)) { throw new RuntimeException('Dit blokje is nog niet ontgrendeld.'); } if (in_array($bid, $blockIds, true)) { throw new RuntimeException('Elk blokje mag maar in één vak.'); } $blockIds[] = $bid; } $now = $this->now(); $id = isset($data['id']) ? (string) $data['id'] : ''; if ($id !== '') { $row = $this->ownedCustom($userId, $id); if (!$row) { throw new RuntimeException('Onbekende planeet.'); } $this->pdo->prepare( 'UPDATE custom_planets SET name=?, people=?, jumps_to_clear=?, fall_time=?, rise_time=?, colors=?, updated=? WHERE id=? AND user_id=?' )->execute([$name, $people, $j, $f, $r, json_encode($blockIds), $now, $id, $userId]); } else { $stmt = $this->pdo->prepare('SELECT COUNT(*) FROM custom_planets WHERE user_id = ?'); $stmt->execute([$userId]); if ((int) $stmt->fetchColumn() >= self::MAX_CUSTOM_PLANETS) { throw new RuntimeException('Je hebt het maximum van ' . self::MAX_CUSTOM_PLANETS . ' planeten bereikt.'); } $id = 'c_' . bin2hex(random_bytes(8)); $this->pdo->prepare( 'INSERT INTO custom_planets (id, user_id, name, people, jumps_to_clear, fall_time, rise_time, colors, created, updated) VALUES (?,?,?,?,?,?,?,?,?,?)' )->execute([$id, $userId, $name, $people, $j, $f, $r, json_encode($blockIds), $now, $now]); } $row = $this->ownedCustom($userId, $id); if (!$row) { throw new RuntimeException('Opslaan is mislukt.'); } return $this->snapshotCustom($row); }); } public function deleteCustomPlanet(string $userId, string $id): void { $row = $this->ownedCustom($userId, $id); if (!$row) { throw new RuntimeException('Onbekende planeet.'); } $this->pdo->prepare('DELETE FROM custom_planets WHERE id = ? AND user_id = ?') ->execute([$id, $userId]); } /** @param array<string,mixed> $row */ public function snapshotCustom(array $row): array { $ids = json_decode((string) $row['colors'], true); if (!is_array($ids)) { $ids = []; } $colors = []; foreach ($ids as $i => $id) { $c = Blocks::asColor((string) $id, (int) $i); if ($c === null) { continue; } $colors[] = $c; } $p = [ 'id' => (string) $row['id'], 'name' => (string) $row['name'], 'people' => (string) $row['people'], 'jumpsToClear' => (float) $row['jumps_to_clear'], 'fallTime' => (float) $row['fall_time'], 'riseTime' => (float) $row['rise_time'], 'colors' => $colors, 'custom' => true, 'owner_id' => (string) $row['user_id'], ]; return Planets::presentData($p); } public function profilePayload(string $userId): array { $points = $this->lifetimePoints($userId); return [ 'lifetime_points' => $points, 'locale' => $this->locale($userId), 'blocks' => Blocks::present($points), 'planets' => $this->listCustomPlanets($userId), ]; } private static function clampFloat(float $value, float $lo, float $hi): float { return max($lo, min($hi, $value)); }}}@@ -0,0 +1,832 @@
{
"_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
}
]
}
@@ -0,0 +1,832 @@{ "_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 } ]}@@ -297,8 +297,218 @@ $store->leaveLobby('local:test_user_1');
$store->leaveLobby('local:test_user_2');
$store->leaveLobby('local:test_user_3');
echo "\nBlocks registry and unlock thresholds\n";
require_once dirname(__DIR__) . '/lib/Blocks.php';
$allBlocks = Blocks::all();
expect(count($allBlocks) >= 48, 'registry has Terra + new icons (got ' . count($allBlocks) . ')');
for ($i = 0; $i < 5; $i++) {
expect(Blocks::threshold($i) === 0, "terra index $i is free");
}
expect(Blocks::threshold(5) === 500, 'first unlock is 500 points');
$prev = 500;
for ($i = 6; $i < count($allBlocks); $i++) {
$t = Blocks::threshold($i);
if ($t <= $prev) {
expect(false, "threshold at $i should be > $prev, got $t");
break;
}
$prev = $t;
}
expect($prev > 500, 'later thresholds grow');
expect(Blocks::unlocked(0, 0) === true, 'terra unlocked at 0 points');
expect(Blocks::unlocked(5, 499) === false, 'fehu locked at 499');
expect(Blocks::unlocked(5, 500) === true, 'fehu unlocked at 500');
$terraIds = [];
foreach ($allBlocks as $i => $b) {
if ($i >= 5) break;
$terraIds[] = $b['id'];
}
echo "\nLifetime points, anti-cheat, custom planets\n";
$ptsStore = Store::open($tmp);
$u = 'local:designer_a';
$v = 'local:designer_b';
expect($ptsStore->lifetimePoints($u) === 0, 'new profile starts at 0');
$t1 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
expect($t1 === 200, 'first award adds 200');
$t2 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
expect($t2 === 200, 'same award_key is idempotent');
$t3 = $ptsStore->awardPoints($u, 50, 'k-two', 'offline');
expect($t3 === 250, 'second key adds 50');
$ptsStore->testNow = 1_000_000;
$ses = $ptsStore->playBegin($u, 'solo');
expect(isset($ses['token']) && strlen($ses['token']) === 32, 'playBegin returns a token');
$ptsStore->testNow = 1_000_001;
$fin = $ptsStore->playFinish($u, $ses['token'], 9000);
expect($fin['awarded'] === 0, 'score with duration under 3s awards 0');
expect($fin['lifetime_points'] === 250, 'lifetime unchanged after clamped zero');
$again = $ptsStore->playFinish($u, $ses['token'], 9000);
expect(!empty($again['already']), 'second finish of same token is a no-op');
$ptsStore->testNow = 2_000_000;
$ses2 = $ptsStore->playBegin($u, 'offline');
$ptsStore->testNow = 2_000_010;
$fin2 = $ptsStore->playFinish($u, $ses2['token'], 9000);
expect($fin2['awarded'] === 40, 'cap is 4 points/s over 10s (got ' . $fin2['awarded'] . ')');
expect($fin2['lifetime_points'] === 290, 'capped award is added');
$ptsStore->testNow = 3_000_000;
$ses3 = $ptsStore->playBegin($u, 'solo');
$ptsStore->testNow = 3_000_020;
$fin3 = $ptsStore->playFinish($u, $ses3['token'], 17);
expect($fin3['awarded'] === 17, 'honest score under the cap is kept');
try {
$ptsStore->saveCustomPlanet($u, [
'name' => 'Lockworld', 'people' => 'Lockers',
'jumpsToClear' => 2, 'fallTime' => 3, 'riseTime' => 1.5,
'colors' => array_merge($terraIds, ['rune-fehu']),
]);
// 6 items? no that's 6. Use 4 terra + fehu
expect(false, 'should not reach (wrong colors count would throw first)');
} catch (RuntimeException $e) {
expect(str_contains($e->getMessage(), 'vijf') || str_contains($e->getMessage(), 'ontgrendeld') || str_contains($e->getMessage(), 'Onbekend'),
'invalid colors refused: ' . $e->getMessage());
}
try {
$ptsStore->saveCustomPlanet($u, [
'name' => 'Lockworld', 'people' => 'Lockers',
'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'rune-fehu'],
]);
expect(false, 'locked block should throw');
} catch (RuntimeException $e) {
expect(str_contains($e->getMessage(), 'ontgrendeld'), 'locked block refused: ' . $e->getMessage());
}
try {
$ptsStore->saveCustomPlanet($u, [
'name' => 'Ghost', 'people' => 'Ghosts',
'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'no-such-block'],
]);
expect(false, 'unknown block should throw');
} catch (RuntimeException $e) {
expect(str_contains($e->getMessage(), 'Onbekend'), 'unknown block refused: ' . $e->getMessage());
}
try {
$ptsStore->saveCustomPlanet($u, [
'name' => 'Twins', 'people' => 'Twins',
'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], $terraIds[0]],
]);
expect(false, 'duplicate block should throw');
} catch (RuntimeException $e) {
expect(str_contains($e->getMessage(), 'één vak') || str_contains($e->getMessage(), 'vak'),
'duplicate block refused: ' . $e->getMessage());
}
$snap = $ptsStore->saveCustomPlanet($u, [
'name' => 'My World', 'people' => 'My People',
'jumpsToClear' => 2.5, 'fallTime' => 2, 'riseTime' => 1,
'colors' => $terraIds,
]);
expect(!empty($snap['id']) && str_starts_with($snap['id'], 'c_'), 'custom id is c_ + hex');
expect($snap['custom'] === true, 'snapshot is marked custom');
expect($snap['name'] === 'My World', 'name stored');
expect(count($snap['colors']) === 5, 'five colors in snapshot');
expect($snap['colors'][0]['block'] === $terraIds[0], 'color has registry block id');
expect($snap['owner_id'] === $u, 'owner_id set');
$listed = $ptsStore->listCustomPlanets($u);
expect(count($listed) === 1, 'owner lists the planet');
expect($ptsStore->listCustomPlanets($v) === [], 'other user has no planets');
try {
$ptsStore->setPlanet($u, $snap['id']);
expect(false, 'setPlanet without a lobby should throw');
} catch (RuntimeException $e) {
expect(true, 'setPlanet requires a lobby: ' . $e->getMessage());
}
$lobby = $ptsStore->createLobby($u, 'A', 0.3, $snap['id']);
$view = $ptsStore->viewFor($u);
$meP = $view['lobby']['players'][0]['planet'] ?? null;
expect($meP && $meP['id'] === $snap['id'], 'createLobby stores custom planet');
expect(!empty($meP['custom']), 'presented planet is custom');
expect(count($meP['colors']) === 5 && $meP['colors'][0]['image'] !== '', 'presented colors include images');
expect(isset($meP['miss_chance']) && is_float($meP['miss_chance']), 'server sends miss_chance for custom');
$ptsStore->joinLobby($v, 'B', $lobby['code']);
$viewB = $ptsStore->viewFor($v);
$seen = null;
foreach ($viewB['lobby']['players'] as $plr) {
if ($plr['planet']['id'] === $snap['id']) { $seen = $plr['planet']; }
}
expect($seen !== null, 'other player sees the custom planet snapshot');
expect(($seen['colors'][2]['block'] ?? '') === $terraIds[2], 'opponent sees block ids');
try {
$ptsStore->setPlanet($v, $snap['id']);
expect(false, 'cannot pick someone else\'s custom planet');
} catch (RuntimeException $e) {
expect(str_contains($e->getMessage(), 'Onbekende'), 'foreign custom refused: ' . $e->getMessage());
}
$ptsStore->leaveLobby($u);
$ptsStore->leaveLobby($v);
$ptsStore->deleteCustomPlanet($u, $snap['id']);
expect($ptsStore->listCustomPlanets($u) === [], 'deleted planet is gone');
// Snapshot survives mid-match edits: create, join, start, then edit/delete, opponent still sees original.
$snap2 = $ptsStore->saveCustomPlanet($u, [
'name' => 'Frozen', 'people' => 'Ice',
'jumpsToClear' => 3, 'fallTime' => 2, 'riseTime' => 1,
'colors' => $terraIds,
]);
$lobby2 = $ptsStore->createLobby($u, 'A', 0.3, $snap2['id']);
$ptsStore->joinLobby($v, 'B', $lobby2['code']);
$ptsStore->setReady($u, true);
$ptsStore->setReady($v, true);
$ptsStore->startGame($u);
$ptsStore->saveCustomPlanet($u, [
'id' => $snap2['id'],
'name' => 'Changed', 'people' => 'Ice',
'jumpsToClear' => 1, 'fallTime' => 5, 'riseTime' => 3,
'colors' => $terraIds,
]);
$viewMid = $ptsStore->viewFor($v);
$midP = null;
foreach ($viewMid['lobby']['players'] as $plr) {
if (($plr['planet']['id'] ?? '') === $snap2['id']) { $midP = $plr['planet']; }
}
expect($midP && $midP['name'] === 'Frozen', 'in-match snapshot keeps the original name (got ' . ($midP['name'] ?? '?') . ')');
expect($midP && almostEqual((float) $midP['jumpsToClear'], 3.0), 'in-match snapshot keeps original gravity');
$ptsStore->leaveLobby($u);
$ptsStore->leaveLobby($v);
// Online award is idempotent and server-side.
$u3 = 'local:online_award_a';
$v3 = 'local:online_award_b';
$lob = $ptsStore->createLobby($u3, 'A', 0.0, 'terra');
$ptsStore->joinLobby($v3, 'B', $lob['code']);
$ptsStore->setReady($u3, true);
$ptsStore->setReady($v3, true);
$ptsStore->startGame($u3);
$ptsStore->viewFor($u3, null, 80, false, []);
$ptsStore->viewFor($u3, null, 80, true, []);
expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the score');
$ptsStore->viewFor($u3, null, 999, true, []);
expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');
$ptsStore->setLocale($u, 'nl');
expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');
try {
$ptsStore->setLocale($u, 'xx');
expect(false, 'unknown locale should throw');
} catch (RuntimeException $e) {
expect(true, 'unknown locale refused');
}
echo "\nConfig helpers\n";
$cfg = config();
expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
@@ -297,8 +297,218 @@ $store->leaveLobby('local:test_user_1');$store->leaveLobby('local:test_user_2');$store->leaveLobby('local:test_user_2');$store->leaveLobby('local:test_user_3');$store->leaveLobby('local:test_user_3');echo "\nBlocks registry and unlock thresholds\n";require_once dirname(__DIR__) . '/lib/Blocks.php';$allBlocks = Blocks::all();expect(count($allBlocks) >= 48, 'registry has Terra + new icons (got ' . count($allBlocks) . ')');for ($i = 0; $i < 5; $i++) { expect(Blocks::threshold($i) === 0, "terra index $i is free");}expect(Blocks::threshold(5) === 500, 'first unlock is 500 points');$prev = 500;for ($i = 6; $i < count($allBlocks); $i++) { $t = Blocks::threshold($i); if ($t <= $prev) { expect(false, "threshold at $i should be > $prev, got $t"); break; } $prev = $t;}expect($prev > 500, 'later thresholds grow');expect(Blocks::unlocked(0, 0) === true, 'terra unlocked at 0 points');expect(Blocks::unlocked(5, 499) === false, 'fehu locked at 499');expect(Blocks::unlocked(5, 500) === true, 'fehu unlocked at 500');$terraIds = [];foreach ($allBlocks as $i => $b) { if ($i >= 5) break; $terraIds[] = $b['id'];}echo "\nLifetime points, anti-cheat, custom planets\n";$ptsStore = Store::open($tmp);$u = 'local:designer_a';$v = 'local:designer_b';expect($ptsStore->lifetimePoints($u) === 0, 'new profile starts at 0');$t1 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');expect($t1 === 200, 'first award adds 200');$t2 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');expect($t2 === 200, 'same award_key is idempotent');$t3 = $ptsStore->awardPoints($u, 50, 'k-two', 'offline');expect($t3 === 250, 'second key adds 50');$ptsStore->testNow = 1_000_000;$ses = $ptsStore->playBegin($u, 'solo');expect(isset($ses['token']) && strlen($ses['token']) === 32, 'playBegin returns a token');$ptsStore->testNow = 1_000_001;$fin = $ptsStore->playFinish($u, $ses['token'], 9000);expect($fin['awarded'] === 0, 'score with duration under 3s awards 0');expect($fin['lifetime_points'] === 250, 'lifetime unchanged after clamped zero');$again = $ptsStore->playFinish($u, $ses['token'], 9000);expect(!empty($again['already']), 'second finish of same token is a no-op');$ptsStore->testNow = 2_000_000;$ses2 = $ptsStore->playBegin($u, 'offline');$ptsStore->testNow = 2_000_010;$fin2 = $ptsStore->playFinish($u, $ses2['token'], 9000);expect($fin2['awarded'] === 40, 'cap is 4 points/s over 10s (got ' . $fin2['awarded'] . ')');expect($fin2['lifetime_points'] === 290, 'capped award is added');$ptsStore->testNow = 3_000_000;$ses3 = $ptsStore->playBegin($u, 'solo');$ptsStore->testNow = 3_000_020;$fin3 = $ptsStore->playFinish($u, $ses3['token'], 17);expect($fin3['awarded'] === 17, 'honest score under the cap is kept');try { $ptsStore->saveCustomPlanet($u, [ 'name' => 'Lockworld', 'people' => 'Lockers', 'jumpsToClear' => 2, 'fallTime' => 3, 'riseTime' => 1.5, 'colors' => array_merge($terraIds, ['rune-fehu']), ]); // 6 items? no that's 6. Use 4 terra + fehu expect(false, 'should not reach (wrong colors count would throw first)');} catch (RuntimeException $e) { expect(str_contains($e->getMessage(), 'vijf') || str_contains($e->getMessage(), 'ontgrendeld') || str_contains($e->getMessage(), 'Onbekend'), 'invalid colors refused: ' . $e->getMessage());}try { $ptsStore->saveCustomPlanet($u, [ 'name' => 'Lockworld', 'people' => 'Lockers', 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'rune-fehu'], ]); expect(false, 'locked block should throw');} catch (RuntimeException $e) { expect(str_contains($e->getMessage(), 'ontgrendeld'), 'locked block refused: ' . $e->getMessage());}try { $ptsStore->saveCustomPlanet($u, [ 'name' => 'Ghost', 'people' => 'Ghosts', 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'no-such-block'], ]); expect(false, 'unknown block should throw');} catch (RuntimeException $e) { expect(str_contains($e->getMessage(), 'Onbekend'), 'unknown block refused: ' . $e->getMessage());}try { $ptsStore->saveCustomPlanet($u, [ 'name' => 'Twins', 'people' => 'Twins', 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], $terraIds[0]], ]); expect(false, 'duplicate block should throw');} catch (RuntimeException $e) { expect(str_contains($e->getMessage(), 'één vak') || str_contains($e->getMessage(), 'vak'), 'duplicate block refused: ' . $e->getMessage());}$snap = $ptsStore->saveCustomPlanet($u, [ 'name' => 'My World', 'people' => 'My People', 'jumpsToClear' => 2.5, 'fallTime' => 2, 'riseTime' => 1, 'colors' => $terraIds,]);expect(!empty($snap['id']) && str_starts_with($snap['id'], 'c_'), 'custom id is c_ + hex');expect($snap['custom'] === true, 'snapshot is marked custom');expect($snap['name'] === 'My World', 'name stored');expect(count($snap['colors']) === 5, 'five colors in snapshot');expect($snap['colors'][0]['block'] === $terraIds[0], 'color has registry block id');expect($snap['owner_id'] === $u, 'owner_id set');$listed = $ptsStore->listCustomPlanets($u);expect(count($listed) === 1, 'owner lists the planet');expect($ptsStore->listCustomPlanets($v) === [], 'other user has no planets');try { $ptsStore->setPlanet($u, $snap['id']); expect(false, 'setPlanet without a lobby should throw');} catch (RuntimeException $e) { expect(true, 'setPlanet requires a lobby: ' . $e->getMessage());}$lobby = $ptsStore->createLobby($u, 'A', 0.3, $snap['id']);$view = $ptsStore->viewFor($u);$meP = $view['lobby']['players'][0]['planet'] ?? null;expect($meP && $meP['id'] === $snap['id'], 'createLobby stores custom planet');expect(!empty($meP['custom']), 'presented planet is custom');expect(count($meP['colors']) === 5 && $meP['colors'][0]['image'] !== '', 'presented colors include images');expect(isset($meP['miss_chance']) && is_float($meP['miss_chance']), 'server sends miss_chance for custom');$ptsStore->joinLobby($v, 'B', $lobby['code']);$viewB = $ptsStore->viewFor($v);$seen = null;foreach ($viewB['lobby']['players'] as $plr) { if ($plr['planet']['id'] === $snap['id']) { $seen = $plr['planet']; }}expect($seen !== null, 'other player sees the custom planet snapshot');expect(($seen['colors'][2]['block'] ?? '') === $terraIds[2], 'opponent sees block ids');try { $ptsStore->setPlanet($v, $snap['id']); expect(false, 'cannot pick someone else\'s custom planet');} catch (RuntimeException $e) { expect(str_contains($e->getMessage(), 'Onbekende'), 'foreign custom refused: ' . $e->getMessage());}$ptsStore->leaveLobby($u);$ptsStore->leaveLobby($v);$ptsStore->deleteCustomPlanet($u, $snap['id']);expect($ptsStore->listCustomPlanets($u) === [], 'deleted planet is gone');// Snapshot survives mid-match edits: create, join, start, then edit/delete, opponent still sees original.$snap2 = $ptsStore->saveCustomPlanet($u, [ 'name' => 'Frozen', 'people' => 'Ice', 'jumpsToClear' => 3, 'fallTime' => 2, 'riseTime' => 1, 'colors' => $terraIds,]);$lobby2 = $ptsStore->createLobby($u, 'A', 0.3, $snap2['id']);$ptsStore->joinLobby($v, 'B', $lobby2['code']);$ptsStore->setReady($u, true);$ptsStore->setReady($v, true);$ptsStore->startGame($u);$ptsStore->saveCustomPlanet($u, [ 'id' => $snap2['id'], 'name' => 'Changed', 'people' => 'Ice', 'jumpsToClear' => 1, 'fallTime' => 5, 'riseTime' => 3, 'colors' => $terraIds,]);$viewMid = $ptsStore->viewFor($v);$midP = null;foreach ($viewMid['lobby']['players'] as $plr) { if (($plr['planet']['id'] ?? '') === $snap2['id']) { $midP = $plr['planet']; }}expect($midP && $midP['name'] === 'Frozen', 'in-match snapshot keeps the original name (got ' . ($midP['name'] ?? '?') . ')');expect($midP && almostEqual((float) $midP['jumpsToClear'], 3.0), 'in-match snapshot keeps original gravity');$ptsStore->leaveLobby($u);$ptsStore->leaveLobby($v);// Online award is idempotent and server-side.$u3 = 'local:online_award_a';$v3 = 'local:online_award_b';$lob = $ptsStore->createLobby($u3, 'A', 0.0, 'terra');$ptsStore->joinLobby($v3, 'B', $lob['code']);$ptsStore->setReady($u3, true);$ptsStore->setReady($v3, true);$ptsStore->startGame($u3);$ptsStore->viewFor($u3, null, 80, false, []);$ptsStore->viewFor($u3, null, 80, true, []);expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the score');$ptsStore->viewFor($u3, null, 999, true, []);expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');$ptsStore->setLocale($u, 'nl');expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');try { $ptsStore->setLocale($u, 'xx'); expect(false, 'unknown locale should throw');} catch (RuntimeException $e) { expect(true, 'unknown locale refused');}echo "\nConfig helpers\n";echo "\nConfig helpers\n";$cfg = config();$cfg = config();expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');@@ -0,0 +1,160 @@
'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; }
@@ -0,0 +1,160 @@'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; }@@ -15,11 +15,13 @@ rm -f "$BUILD_FILE"
FILES=(
"$SRC_DIR/rng.js"
"$SRC_DIR/planet.js"
"$SRC_DIR/blocks.js"
"$SRC_DIR/easing.js"
"$SRC_DIR/gameCore.js"
"$SRC_DIR/miniLayout.js"
"$SRC_DIR/online.js"
"$SRC_DIR/offline.js"
"$SRC_DIR/designer.js"
"$SRC_DIR/main.js"
)
@@ -31,6 +33,9 @@ FILES=(
printf '%s' "var PLANET_CATALOG = "
cat "$ROOT/server/lib/planets.json"
printf ';\n'
printf '%s' "var BLOCK_REGISTRY = "
cat "$ROOT/server/lib/blocks.json"
printf ';\n'
} >> "$BUILD_FILE"
for file in "${FILES[@]}"
@@ -55,6 +60,7 @@ cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
mkdir -p "$ROOT/build/lib"
cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \
"$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \
"$SERVER/lib/Blocks.php" "$SERVER/lib/blocks.json" \
"$ROOT/build/lib/"
mkdir -p "$ROOT/build/data"
cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
@@ -15,11 +15,13 @@ rm -f "$BUILD_FILE"FILES=(FILES=( "$SRC_DIR/rng.js" "$SRC_DIR/rng.js" "$SRC_DIR/planet.js" "$SRC_DIR/planet.js" "$SRC_DIR/blocks.js" "$SRC_DIR/easing.js" "$SRC_DIR/easing.js" "$SRC_DIR/gameCore.js" "$SRC_DIR/gameCore.js" "$SRC_DIR/miniLayout.js" "$SRC_DIR/miniLayout.js" "$SRC_DIR/online.js" "$SRC_DIR/online.js" "$SRC_DIR/offline.js" "$SRC_DIR/offline.js" "$SRC_DIR/designer.js" "$SRC_DIR/main.js" "$SRC_DIR/main.js"))@@ -31,6 +33,9 @@ FILES=( printf '%s' "var PLANET_CATALOG = " printf '%s' "var PLANET_CATALOG = " cat "$ROOT/server/lib/planets.json" cat "$ROOT/server/lib/planets.json" printf ';\n' printf ';\n' printf '%s' "var BLOCK_REGISTRY = " cat "$ROOT/server/lib/blocks.json" printf ';\n'} >> "$BUILD_FILE"} >> "$BUILD_FILE"for file in "${FILES[@]}"for file in "${FILES[@]}"@@ -55,6 +60,7 @@ cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \mkdir -p "$ROOT/build/lib"mkdir -p "$ROOT/build/lib"cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \ "$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \ "$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \ "$SERVER/lib/Blocks.php" "$SERVER/lib/blocks.json" \ "$ROOT/build/lib/" "$ROOT/build/lib/"mkdir -p "$ROOT/build/data"mkdir -p "$ROOT/build/data"cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"@@ -0,0 +1,529 @@
'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 = 'Je hebt nog geen eigen planeten. Maak er een aan.';
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 += '<img src="' + Designer.esc(colors[c].image) + '" alt="'
+ Designer.esc(colors[c].name) + '">';
}
var stats = (typeof Planet !== 'undefined' && Planet.formatStats)
? Planet.formatStats(pl) : '';
card.innerHTML = '<div class="planet-title">' + Designer.esc(pl.name) + '</div>'
+ '<div class="planet-people">' + Designer.esc(pl.people) + '</div>'
+ '<div class="planet-nums">' + Designer.esc(stats) + '</div>'
+ '<div class="planet-swatches">' + swatches + '</div>'
+ '<div class="designer-card-actions">'
+ '<button type="button" class="btn-tiny" data-edit>Bewerken</button>'
+ '<button type="button" class="btn-tiny btn-danger-lite" data-del>Verwijderen</button>'
+ '</div>';
(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;
if (!window.confirm('Wil je de planeet “' + name + '” verwijderen?'))
{ return; }
Online.deletePlanet(id).then(function (data)
{
if (!data || !data.ok)
{
window.alert((data && data.error) || 'Verwijderen is mislukt.');
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(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 = 'Planeet bewerken';
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 = 'Nieuwe planeet';
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, 1, 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 || 'Nieuwe planeet').trim() || 'Nieuwe planeet',
people: (document.getElementById('des-people').value || 'Volk').trim() || 'Volk',
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;
setText('des-gravity-val', Number(document.getElementById('des-gravity').value).toFixed(1)
+ (d ? ' · g ' + d.gravity.toFixed(2) : ''));
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', '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', 'Blokje ' + (i + 1));
if (b)
{
btn.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="' + Designer.esc(b.name) + '">'
+ '<span>' + Designer.esc(b.name) + '</span>';
}
else
{
btn.innerHTML = '<span class="des-slot-empty">Kies</span>';
}
(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 title = b.name;
if (locked)
{ title += ' — ' + b.threshold + ' punten nodig'; }
else if (taken)
{ title += ' — al in een ander vak'; }
cell.title = title;
cell.setAttribute('aria-label', title);
cell.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="">'
+ (locked ? '<span class="des-lock" aria-hidden="true">'
+ '<svg viewBox="0 0 18 18" width="16" height="16">'
+ '<rect x="4" y="8" width="10" height="8" rx="1.5" fill="#ffe27a"/>'
+ '<path d="M6 8 V6 a3 3 0 0 1 6 0 v2" fill="none" stroke="#ffe27a" stroke-width="1.8" stroke-linecap="round"/>'
+ '<circle cx="9" cy="12" r="1.2" fill="#1a1628"/>'
+ '</svg></span>' : '')
+ '<span class="des-block-name">' + Designer.esc(b.name) + '</span>'
+ (locked ? '<span class="des-block-need">' + b.threshold + '</span>' : '');
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('Vul een naam voor de planeet en voor de bevolking in.');
return;
}
for (var i = 0; i < 5; i++)
{
if (!Designer.slots[i])
{
window.alert('Kies vijf blokjes.');
return;
}
}
var payload = {
id: Designer.editingId || undefined,
name: name,
people: people,
jumpsToClear: clampNum(document.getElementById('des-gravity').value, 1, 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) || 'Opslaan is mislukt.');
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, '>')
.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; }
@@ -0,0 +1,529 @@'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 = 'Je hebt nog geen eigen planeten. Maak er een aan.'; 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 += '<img src="' + Designer.esc(colors[c].image) + '" alt="' + Designer.esc(colors[c].name) + '">'; } var stats = (typeof Planet !== 'undefined' && Planet.formatStats) ? Planet.formatStats(pl) : ''; card.innerHTML = '<div class="planet-title">' + Designer.esc(pl.name) + '</div>' + '<div class="planet-people">' + Designer.esc(pl.people) + '</div>' + '<div class="planet-nums">' + Designer.esc(stats) + '</div>' + '<div class="planet-swatches">' + swatches + '</div>' + '<div class="designer-card-actions">' + '<button type="button" class="btn-tiny" data-edit>Bewerken</button>' + '<button type="button" class="btn-tiny btn-danger-lite" data-del>Verwijderen</button>' + '</div>'; (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; if (!window.confirm('Wil je de planeet “' + name + '” verwijderen?')) { return; } Online.deletePlanet(id).then(function (data) { if (!data || !data.ok) { window.alert((data && data.error) || 'Verwijderen is mislukt.'); 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(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 = 'Planeet bewerken'; 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 = 'Nieuwe planeet'; 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, 1, 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 || 'Nieuwe planeet').trim() || 'Nieuwe planeet', people: (document.getElementById('des-people').value || 'Volk').trim() || 'Volk', 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; setText('des-gravity-val', Number(document.getElementById('des-gravity').value).toFixed(1) + (d ? ' · g ' + d.gravity.toFixed(2) : '')); 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', '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', 'Blokje ' + (i + 1)); if (b) { btn.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="' + Designer.esc(b.name) + '">' + '<span>' + Designer.esc(b.name) + '</span>'; } else { btn.innerHTML = '<span class="des-slot-empty">Kies</span>'; } (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 title = b.name; if (locked) { title += ' — ' + b.threshold + ' punten nodig'; } else if (taken) { title += ' — al in een ander vak'; } cell.title = title; cell.setAttribute('aria-label', title); cell.innerHTML = '<img src="' + Designer.esc(b.image) + '" alt="">' + (locked ? '<span class="des-lock" aria-hidden="true">' + '<svg viewBox="0 0 18 18" width="16" height="16">' + '<rect x="4" y="8" width="10" height="8" rx="1.5" fill="#ffe27a"/>' + '<path d="M6 8 V6 a3 3 0 0 1 6 0 v2" fill="none" stroke="#ffe27a" stroke-width="1.8" stroke-linecap="round"/>' + '<circle cx="9" cy="12" r="1.2" fill="#1a1628"/>' + '</svg></span>' : '') + '<span class="des-block-name">' + Designer.esc(b.name) + '</span>' + (locked ? '<span class="des-block-need">' + b.threshold + '</span>' : ''); 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('Vul een naam voor de planeet en voor de bevolking in.'); return; } for (var i = 0; i < 5; i++) { if (!Designer.slots[i]) { window.alert('Kies vijf blokjes.'); return; } } var payload = { id: Designer.editingId || undefined, name: name, people: people, jumpsToClear: clampNum(document.getElementById('des-gravity').value, 1, 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) || 'Opslaan is mislukt.'); 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, '>') .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; }@@ -36,6 +36,12 @@ function planetImages ()
});
}
}
if (typeof Blocks !== 'undefined' && Blocks.images)
{
var extra = Blocks.images();
for (var b = 0; b < extra.length; b++)
{ list.push(extra[b]); }
}
return list;
}
@@ -110,6 +116,20 @@ window.onload = function ()
bindOfflineUi();
bindPlanetSelect();
restoreSelectedPlanet();
if (typeof Designer !== 'undefined' && Designer.bind)
{ Designer.bind(); }
if (typeof Online !== 'undefined' && Online.refresh)
{
Online.refresh().then(function ()
{
refreshMenuAccount();
restoreSelectedPlanet();
renderPlanetGrid('planet-grid', false);
renderPlanetGrid('lobby-planet-grid', true);
});
}
else
{ refreshMenuAccount(); }
};
function onPlay ()
@@ -129,6 +149,10 @@ function startPlay (opts)
hideEl('podium');
hideEl('planet-select');
hideEl('offline-result');
hideEl('designer');
hideEl('designer-edit');
if (typeof Designer !== 'undefined' && Designer.closeModal)
{ Designer.closeModal(); }
showEl('hud');
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
@@ -192,6 +216,8 @@ function startPlay (opts)
buildColumnWarn();
refreshOfflineHud();
refreshChainIndicator();
if (!opts.online)
{ beginPlaySession(opts.offline ? 'offline' : 'solo'); }
}
function teardownPlay ()
@@ -784,7 +810,10 @@ function tickView (dt)
else if (app.offline)
{ /* Offline result is shown from tickOffline. */ }
else
{ showEl('game-over'); }
{
showEl('game-over');
finishPlaySession(app.lastScore);
}
}
if (!app.online && !app.offline && app.core.state === 'gameover'
&& app.core.gameOverTime >= GAME_OVER_DELAY)
@@ -1395,6 +1424,8 @@ function startNextOfflineRound ()
// 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;
@@ -1420,6 +1451,7 @@ function showOfflineResult ()
}
hideEl('game-over');
showEl('offline-result');
finishPlaySession(app.core ? app.core.score : 0);
}
function refreshOfflineHud ()
@@ -1731,10 +1763,18 @@ 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 && me.planet.id)
{ planet = Planet.planetById(me.planet.id); }
startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
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; }
}
startPlay({ online: true, planet: planet, missChance: miss });
if (typeof Online !== 'undefined')
{ Online.startPolling(onlinePayload); }
}
@@ -2112,19 +2152,22 @@ function renderPlanetGrid (containerId, compact)
var pl = all[i];
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
btn.className = 'planet-card' + (pl.id === current ? ' selected' : '')
+ (pl.custom ? ' custom' : '');
btn.setAttribute('role', 'listitem');
btn.dataset.planet = pl.id;
var swatches = '';
for (var c = 0; c < pl.colors.length; c++)
var colors = pl.colors || [];
for (var c = 0; c < colors.length; c++)
{
swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
+ escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
swatches += '<img src="' + escapeText(colors[c].image) + '" alt="'
+ escapeText(colors[c].name) + '" title="' + escapeText(colors[c].name) + '">';
}
btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
+ '<div class="planet-people">' + escapeText(pl.people) + '</div>'
+ '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
+ '<div class="planet-swatches">' + swatches + '</div>';
+ '<div class="planet-swatches">' + swatches + '</div>'
+ (pl.custom ? '<span class="custom-badge">Eigen</span>' : '');
btn.addEventListener('click', (function (id, isCompact)
{
return function ()
@@ -2185,3 +2228,64 @@ function bindPlanetSelect ()
back.addEventListener('click', cancelPlanetSelect);
}
}
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 || 'speler'; }
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); }
}
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; }
});
}
function finishPlaySession (score)
{
var token = app.playToken;
app.playToken = null;
if (!token || typeof Online === 'undefined' || !Online.playFinish)
{ return; }
Online.playFinish(token, score || 0).then(function ()
{ refreshMenuAccount(); });
}
@@ -36,6 +36,12 @@ function planetImages () }); }); } } } } if (typeof Blocks !== 'undefined' && Blocks.images) { var extra = Blocks.images(); for (var b = 0; b < extra.length; b++) { list.push(extra[b]); } } return list; return list;}}@@ -110,6 +116,20 @@ window.onload = function () bindOfflineUi(); bindOfflineUi(); bindPlanetSelect(); bindPlanetSelect(); restoreSelectedPlanet(); restoreSelectedPlanet(); if (typeof Designer !== 'undefined' && Designer.bind) { Designer.bind(); } if (typeof Online !== 'undefined' && Online.refresh) { Online.refresh().then(function () { refreshMenuAccount(); restoreSelectedPlanet(); renderPlanetGrid('planet-grid', false); renderPlanetGrid('lobby-planet-grid', true); }); } else { refreshMenuAccount(); }};};function onPlay ()function onPlay ()@@ -129,6 +149,10 @@ function startPlay (opts) hideEl('podium'); hideEl('podium'); hideEl('planet-select'); hideEl('planet-select'); hideEl('offline-result'); hideEl('offline-result'); hideEl('designer'); hideEl('designer-edit'); if (typeof Designer !== 'undefined' && Designer.closeModal) { Designer.closeModal(); } showEl('hud'); showEl('hud'); var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod; var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;@@ -192,6 +216,8 @@ function startPlay (opts) buildColumnWarn(); buildColumnWarn(); refreshOfflineHud(); refreshOfflineHud(); refreshChainIndicator(); refreshChainIndicator(); if (!opts.online) { beginPlaySession(opts.offline ? 'offline' : 'solo'); }}}function teardownPlay ()function teardownPlay ()@@ -784,7 +810,10 @@ function tickView (dt) else if (app.offline) else if (app.offline) { /* Offline result is shown from tickOffline. */ } { /* Offline result is shown from tickOffline. */ } else else { showEl('game-over'); } { showEl('game-over'); finishPlaySession(app.lastScore); } } } if (!app.online && !app.offline && app.core.state === 'gameover' if (!app.online && !app.offline && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY) && app.core.gameOverTime >= GAME_OVER_DELAY)@@ -1395,6 +1424,8 @@ function startNextOfflineRound () // Tear down the current scene then start a fresh player field, // Tear down the current scene then start a fresh player field, // keeping the same battle (already advanced). // keeping the same battle (already advanced). var planet = app.battle.playerPlanet; var planet = app.battle.playerPlanet; var roundScore = app.core ? app.core.score : 0; finishPlaySession(roundScore); app._keepBattleOnTeardown = true; app._keepBattleOnTeardown = true; teardownPlay(); teardownPlay(); app.offline = true; app.offline = true;@@ -1420,6 +1451,7 @@ function showOfflineResult () } } hideEl('game-over'); hideEl('game-over'); showEl('offline-result'); showEl('offline-result'); finishPlaySession(app.core ? app.core.score : 0);}}function refreshOfflineHud ()function refreshOfflineHud ()@@ -1731,10 +1763,18 @@ function startOnlineMatch () if (app.mode === 'playing' && app.online) if (app.mode === 'playing' && app.online) { return; } { return; } var planet = Planet.planetById(selectedPlanetId()); var planet = Planet.planetById(selectedPlanetId()); var miss = Planet.missChance(planet); var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null; var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null; if (me && me.planet && me.planet.id) if (me && me.planet) { planet = Planet.planetById(me.planet.id); } { startPlay({ online: true, planet: planet, missChance: Planet.missChance(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; } } startPlay({ online: true, planet: planet, missChance: miss }); if (typeof Online !== 'undefined') if (typeof Online !== 'undefined') { Online.startPolling(onlinePayload); } { Online.startPolling(onlinePayload); }}}@@ -2112,19 +2152,22 @@ function renderPlanetGrid (containerId, compact) var pl = all[i]; var pl = all[i]; var btn = document.createElement('button'); var btn = document.createElement('button'); btn.type = 'button'; btn.type = 'button'; btn.className = 'planet-card' + (pl.id === current ? ' selected' : ''); btn.className = 'planet-card' + (pl.id === current ? ' selected' : '') + (pl.custom ? ' custom' : ''); btn.setAttribute('role', 'listitem'); btn.setAttribute('role', 'listitem'); btn.dataset.planet = pl.id; btn.dataset.planet = pl.id; var swatches = ''; var swatches = ''; for (var c = 0; c < pl.colors.length; c++) var colors = pl.colors || []; for (var c = 0; c < colors.length; c++) { { swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="' swatches += '<img src="' + escapeText(colors[c].image) + '" alt="' + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">'; + escapeText(colors[c].name) + '" title="' + escapeText(colors[c].name) + '">'; } } btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>' btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>' + '<div class="planet-people">' + escapeText(pl.people) + '</div>' + '<div class="planet-people">' + escapeText(pl.people) + '</div>' + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>' + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>' + '<div class="planet-swatches">' + swatches + '</div>'; + '<div class="planet-swatches">' + swatches + '</div>' + (pl.custom ? '<span class="custom-badge">Eigen</span>' : ''); btn.addEventListener('click', (function (id, isCompact) btn.addEventListener('click', (function (id, isCompact) { { return function () return function ()@@ -2185,3 +2228,64 @@ function bindPlanetSelect () back.addEventListener('click', cancelPlanetSelect); back.addEventListener('click', cancelPlanetSelect); } }}}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 || 'speler'; } 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); }}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; } });}function finishPlaySession (score){ var token = app.playToken; app.playToken = null; if (!token || typeof Online === 'undefined' || !Online.playFinish) { return; } Online.playFinish(token, score || 0).then(function () { refreshMenuAccount(); });}@@ -14,6 +14,10 @@ var Online = {
local: false,
csrf: '',
me: null,
lifetimePoints: 0,
locale: null,
blocks: [],
planets: [],
lobby: null,
incoming: [],
shotResults: [],
@@ -65,6 +69,26 @@ Online._apply = function (data)
{ this.error = data.error; }
else if (data.ok)
{ this.error = ''; }
if (data.lifetime_points != null)
{ this.lifetimePoints = data.lifetime_points; }
if (data.locale !== undefined)
{ this.locale = data.locale; }
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)
@@ -136,6 +160,31 @@ 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 });
};
Online.setLocale = function (locale)
{
return this.request('set_locale', { locale: locale });
};
Online.leaveLobby = function ()
{
return this.request('lobby_leave');
@@ -14,6 +14,10 @@ var Online = { local: false, local: false, csrf: '', csrf: '', me: null, me: null, lifetimePoints: 0, locale: null, blocks: [], planets: [], lobby: null, lobby: null, incoming: [], incoming: [], shotResults: [], shotResults: [],@@ -65,6 +69,26 @@ Online._apply = function (data) { this.error = data.error; } { this.error = data.error; } else if (data.ok) else if (data.ok) { this.error = ''; } { this.error = ''; } if (data.lifetime_points != null) { this.lifetimePoints = data.lifetime_points; } if (data.locale !== undefined) { this.locale = data.locale; } 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)Online.request = function (action, body)@@ -136,6 +160,31 @@ Online.setPlanet = function (planetId) return this.request('lobby_set_planet', { planet_id: 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 });};Online.setLocale = function (locale){ return this.request('set_locale', { locale: locale });};Online.leaveLobby = function ()Online.leaveLobby = function (){{ return this.request('lobby_leave'); return this.request('lobby_leave');@@ -105,6 +105,34 @@ function loadCatalog ()
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({
@@ -116,6 +144,10 @@ function planetFromData (data)
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;
}
@@ -127,6 +159,8 @@ function allPlanets ()
{ 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;
}
@@ -138,9 +172,30 @@ function planetById (id)
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();
@@ -167,6 +222,11 @@ function spriteKey (planet, colorIndex)
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));
}
@@ -264,6 +324,12 @@ var Planet = {
defaultPlanet: defaultPlanet,
defaultColors: defaultColors,
allPlanets: allPlanets,
officialPlanets: officialPlanets,
customPlanets: customPlanets,
pickerPlanets: pickerPlanets,
setCustomPlanets: setCustomPlanets,
rememberPlanet: rememberPlanet,
forgetRemembered: forgetRemembered,
planetById: planetById,
planetFromData: planetFromData,
formatStats: formatStats,
@@ -105,6 +105,34 @@ function loadCatalog () return { planets: [] }; 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)function planetFromData (data){{ var planet = createPlanet({ var planet = createPlanet({@@ -116,6 +144,10 @@ function planetFromData (data) colors: data.colors colors: data.colors }); }); planet.id = data.id; planet.id = data.id; if (data.custom) { planet.custom = true; } if (data.owner_id) { planet.owner_id = data.owner_id; } return planet; return planet;}}@@ -127,6 +159,8 @@ function allPlanets () { out.push(planetFromData(raw[i])); } { out.push(planetFromData(raw[i])); } if (out.length === 0) if (out.length === 0) { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; } { 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; return out;}}@@ -138,9 +172,30 @@ function planetById (id) if (all[i].id === id) if (all[i].id === id) { return all[i]; } { return all[i]; } } } if (id && _remembered[id]) { return _remembered[id]; } return defaultPlanet(); 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 ()function defaultPlanet (){{ var all = allPlanets(); var all = allPlanets();@@ -167,6 +222,11 @@ function spriteKey (planet, colorIndex) var c = colors && colors[colorIndex]; var c = colors && colors[colorIndex]; if (!c) if (!c) { return 'gray'; } { 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)); return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));}}@@ -264,6 +324,12 @@ var Planet = { defaultPlanet: defaultPlanet, defaultPlanet: defaultPlanet, defaultColors: defaultColors, defaultColors: defaultColors, allPlanets: allPlanets, allPlanets: allPlanets, officialPlanets: officialPlanets, customPlanets: customPlanets, pickerPlanets: pickerPlanets, setCustomPlanets: setCustomPlanets, rememberPlanet: rememberPlanet, forgetRemembered: forgetRemembered, planetById: planetById, planetById: planetById, planetFromData: planetFromData, planetFromData: planetFromData, formatStats: formatStats, formatStats: formatStats,@@ -0,0 +1,184 @@
'use strict';
const { describe, it } = require('node:test');
const assert = require('node:assert/strict');
const Blocks = require('../src/blocks.js');
const Planet = require('../src/planet.js');
const Designer = require('../src/designer.js');
const fs = require('node:fs');
const path = require('node:path');
describe('Block registry (t1139)', () =>
{
it('loads the append-only registry with Terra first', () =>
{
const all = Blocks.all();
assert.ok(all.length >= 48, 'got ' + all.length);
assert.equal(all[0].id, 'terra-ember');
assert.equal(all[4].id, 'terra-orchid');
assert.equal(all[5].id, 'rune-fehu');
assert.equal(Blocks.TERRA_COUNT, 5);
assert.equal(Blocks.FIRST_THRESHOLD, 500);
assert.ok(Math.abs(Blocks.GROWTH - 1.145) < 1e-12);
});
it('Terra is free, the next block is 500, then 14.5% more and strictly increasing', () =>
{
for (let i = 0; i < 5; i++)
{ assert.equal(Blocks.threshold(i), 0, 'index ' + i); }
assert.equal(Blocks.threshold(5), 500);
let prev = 500;
const all = Blocks.all();
for (let i = 6; i < all.length; i++)
{
const t = Blocks.threshold(i);
assert.ok(t > prev, 'index ' + i + ': ' + t + ' vs ' + prev);
const expected = Math.max(prev + 1, Math.round(prev * 1.145));
assert.equal(t, expected);
prev = t;
}
});
it('unlock is a requirement, not a spend', () =>
{
assert.equal(Blocks.unlocked(0, 0), true);
assert.equal(Blocks.unlocked(5, 499), false);
assert.equal(Blocks.unlocked(5, 500), true);
assert.equal(Blocks.unlocked(6, 500), false);
assert.equal(Blocks.unlockedId('rune-fehu', 500), true);
assert.equal(Blocks.unlockedId('no-such', 999999), false);
});
it('present() marks each block with threshold and unlock state', () =>
{
const list = Blocks.present(500);
assert.equal(list.length, Blocks.all().length);
assert.equal(list[0].unlocked, true);
assert.equal(list[5].unlocked, true);
assert.equal(list[5].threshold, 500);
assert.equal(list[6].unlocked, false);
assert.ok(list[5].image.startsWith('images/'));
});
it('asColor() fills a planet slot from a registry id', () =>
{
const c = Blocks.asColor('terra-ember', 2);
assert.equal(c.id, 2);
assert.equal(c.block, 'terra-ember');
assert.equal(c.name, 'Ember');
assert.ok(c.hex && c.image);
});
it('every registry image file exists on disk', () =>
{
const root = path.join(__dirname, '..');
for (const b of Blocks.all())
{
const file = path.join(root, 'build', b.image);
assert.ok(fs.existsSync(file), 'missing ' + b.image);
}
});
});
describe('Custom planets in the picker (t1140)', () =>
{
it('allPlanets and pickerPlanets include owned customs, officialPlanets does not', () =>
{
const before = Planet.officialPlanets().length;
assert.ok(before >= 8 && before <= 12);
Planet.setCustomPlanets([
{
id: 'c_abc123',
name: 'Home',
people: 'Homers',
jumpsToClear: 2,
fallTime: 3,
riseTime: 1.5,
custom: true,
owner_id: 'u1',
colors: [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i))
}
]);
assert.equal(Planet.officialPlanets().length, before);
assert.equal(Planet.customPlanets().length, 1);
const all = Planet.allPlanets();
assert.equal(all.length, before + 1);
assert.equal(all[all.length - 1].id, 'c_abc123');
assert.equal(all[all.length - 1].custom, true);
const picker = Planet.pickerPlanets();
assert.ok(picker.some((p) => p.id === 'c_abc123'));
assert.equal(Planet.planetById('c_abc123').name, 'Home');
Planet.setCustomPlanets([]);
assert.equal(Planet.customPlanets().length, 0);
assert.equal(Planet.allPlanets().length, before);
});
it('rememberPlanet is used for opponents and is not in the picker', () =>
{
const opp = Planet.rememberPlanet({
id: 'c_opponent',
name: 'Rival',
people: 'Rivals',
jumpsToClear: 3,
fallTime: 2,
riseTime: 1,
custom: true,
owner_id: 'u2',
colors: [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i))
});
assert.equal(opp.name, 'Rival');
assert.equal(Planet.planetById('c_opponent').name, 'Rival');
assert.ok(!Planet.pickerPlanets().some((p) => p.id === 'c_opponent'));
assert.ok(!Planet.allPlanets().some((p) => p.id === 'c_opponent'));
Planet.forgetRemembered();
});
it('spriteKey for a registry colour uses the preloaded block: id', () =>
{
const colors = [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i));
const p = Planet.planetFromData({
id: 'c_key',
name: 'K',
people: 'K',
jumpsToClear: 2,
fallTime: 3,
riseTime: 1.5,
custom: true,
colors: colors
});
assert.equal(Planet.spriteKey(p, 0), 'block:terra-ember');
assert.equal(Planet.spriteKey(p, 4), 'block:terra-orchid');
const terra = Planet.planetById('terra');
assert.ok(!String(Planet.spriteKey(terra, 0)).startsWith('block:')
|| terra.colors[0].block,
'official Terra keeps its catalog sprite unless it has a block field');
});
});
describe('Designer draft uses the existing Power formula', () =>
{
it('displayPower matches Planet.displayPower on a draft', () =>
{
const colors = [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i));
const p = Planet.createPlanet({
name: 'Draft',
people: 'Drafts',
jumpsToClear: 3,
fallTime: 2,
riseTime: 1,
colors: colors
});
const power = Planet.displayPower(p);
assert.equal(typeof power, 'number');
assert.equal(power, Planet.displayValues(p).power);
assert.ok(power >= 0 && power <= 100);
});
it('Designer.defaultSlots returns Terra\'s five', () =>
{
const slots = Designer.defaultSlots();
assert.equal(slots.length, 5);
assert.equal(slots[0], 'terra-ember');
assert.equal(slots[4], 'terra-orchid');
});
});
@@ -0,0 +1,184 @@'use strict';const { describe, it } = require('node:test');const assert = require('node:assert/strict');const Blocks = require('../src/blocks.js');const Planet = require('../src/planet.js');const Designer = require('../src/designer.js');const fs = require('node:fs');const path = require('node:path');describe('Block registry (t1139)', () =>{ it('loads the append-only registry with Terra first', () => { const all = Blocks.all(); assert.ok(all.length >= 48, 'got ' + all.length); assert.equal(all[0].id, 'terra-ember'); assert.equal(all[4].id, 'terra-orchid'); assert.equal(all[5].id, 'rune-fehu'); assert.equal(Blocks.TERRA_COUNT, 5); assert.equal(Blocks.FIRST_THRESHOLD, 500); assert.ok(Math.abs(Blocks.GROWTH - 1.145) < 1e-12); }); it('Terra is free, the next block is 500, then 14.5% more and strictly increasing', () => { for (let i = 0; i < 5; i++) { assert.equal(Blocks.threshold(i), 0, 'index ' + i); } assert.equal(Blocks.threshold(5), 500); let prev = 500; const all = Blocks.all(); for (let i = 6; i < all.length; i++) { const t = Blocks.threshold(i); assert.ok(t > prev, 'index ' + i + ': ' + t + ' vs ' + prev); const expected = Math.max(prev + 1, Math.round(prev * 1.145)); assert.equal(t, expected); prev = t; } }); it('unlock is a requirement, not a spend', () => { assert.equal(Blocks.unlocked(0, 0), true); assert.equal(Blocks.unlocked(5, 499), false); assert.equal(Blocks.unlocked(5, 500), true); assert.equal(Blocks.unlocked(6, 500), false); assert.equal(Blocks.unlockedId('rune-fehu', 500), true); assert.equal(Blocks.unlockedId('no-such', 999999), false); }); it('present() marks each block with threshold and unlock state', () => { const list = Blocks.present(500); assert.equal(list.length, Blocks.all().length); assert.equal(list[0].unlocked, true); assert.equal(list[5].unlocked, true); assert.equal(list[5].threshold, 500); assert.equal(list[6].unlocked, false); assert.ok(list[5].image.startsWith('images/')); }); it('asColor() fills a planet slot from a registry id', () => { const c = Blocks.asColor('terra-ember', 2); assert.equal(c.id, 2); assert.equal(c.block, 'terra-ember'); assert.equal(c.name, 'Ember'); assert.ok(c.hex && c.image); }); it('every registry image file exists on disk', () => { const root = path.join(__dirname, '..'); for (const b of Blocks.all()) { const file = path.join(root, 'build', b.image); assert.ok(fs.existsSync(file), 'missing ' + b.image); } });});describe('Custom planets in the picker (t1140)', () =>{ it('allPlanets and pickerPlanets include owned customs, officialPlanets does not', () => { const before = Planet.officialPlanets().length; assert.ok(before >= 8 && before <= 12); Planet.setCustomPlanets([ { id: 'c_abc123', name: 'Home', people: 'Homers', jumpsToClear: 2, fallTime: 3, riseTime: 1.5, custom: true, owner_id: 'u1', colors: [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i)) } ]); assert.equal(Planet.officialPlanets().length, before); assert.equal(Planet.customPlanets().length, 1); const all = Planet.allPlanets(); assert.equal(all.length, before + 1); assert.equal(all[all.length - 1].id, 'c_abc123'); assert.equal(all[all.length - 1].custom, true); const picker = Planet.pickerPlanets(); assert.ok(picker.some((p) => p.id === 'c_abc123')); assert.equal(Planet.planetById('c_abc123').name, 'Home'); Planet.setCustomPlanets([]); assert.equal(Planet.customPlanets().length, 0); assert.equal(Planet.allPlanets().length, before); }); it('rememberPlanet is used for opponents and is not in the picker', () => { const opp = Planet.rememberPlanet({ id: 'c_opponent', name: 'Rival', people: 'Rivals', jumpsToClear: 3, fallTime: 2, riseTime: 1, custom: true, owner_id: 'u2', colors: [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i)) }); assert.equal(opp.name, 'Rival'); assert.equal(Planet.planetById('c_opponent').name, 'Rival'); assert.ok(!Planet.pickerPlanets().some((p) => p.id === 'c_opponent')); assert.ok(!Planet.allPlanets().some((p) => p.id === 'c_opponent')); Planet.forgetRemembered(); }); it('spriteKey for a registry colour uses the preloaded block: id', () => { const colors = [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i)); const p = Planet.planetFromData({ id: 'c_key', name: 'K', people: 'K', jumpsToClear: 2, fallTime: 3, riseTime: 1.5, custom: true, colors: colors }); assert.equal(Planet.spriteKey(p, 0), 'block:terra-ember'); assert.equal(Planet.spriteKey(p, 4), 'block:terra-orchid'); const terra = Planet.planetById('terra'); assert.ok(!String(Planet.spriteKey(terra, 0)).startsWith('block:') || terra.colors[0].block, 'official Terra keeps its catalog sprite unless it has a block field'); });});describe('Designer draft uses the existing Power formula', () =>{ it('displayPower matches Planet.displayPower on a draft', () => { const colors = [0, 1, 2, 3, 4].map((i) => Blocks.asColor(Blocks.all()[i].id, i)); const p = Planet.createPlanet({ name: 'Draft', people: 'Drafts', jumpsToClear: 3, fallTime: 2, riseTime: 1, colors: colors }); const power = Planet.displayPower(p); assert.equal(typeof power, 'number'); assert.equal(power, Planet.displayValues(p).power); assert.ok(power >= 0 && power <= 100); }); it('Designer.defaultSlots returns Terra\'s five', () => { const slots = Designer.defaultSlots(); assert.equal(slots.length, 5); assert.equal(slots[0], 'terra-ember'); assert.equal(slots[4], 'terra-orchid'); });});@@ -0,0 +1,404 @@
#!/usr/bin/env python3
"""t1139 / t1140: Planet Designer UI, locked modal, custom planets in every picker."""
from __future__ import annotations
import os
import socket
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from playwright.sync_api import sync_playwright
ROOT = Path("/workspace/meteors")
SHOTS = Path("/workspace/meteors-shots")
SHOTS.mkdir(parents=True, exist_ok=True)
PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
CHROME = "/usr/bin/google-chrome"
CHROME_ARGS = [
"--use-gl=angle",
"--use-angle=swiftshader",
"--no-sandbox",
"--disable-dev-shm-usage",
]
FAILURES = []
URL = None
MOBILE = {
"viewport": {"width": 390, "height": 844},
"device_scale_factor": 2,
"is_mobile": True,
"has_touch": True,
"user_agent": (
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
"AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
"Mobile/15E148 Safari/604.1"
),
}
def check(cond, msg):
if cond:
print("OK ", msg)
else:
print("FAIL", msg)
FAILURES.append(msg)
return cond
def shot(page, name):
path = SHOTS / name
page.screenshot(path=str(path), full_page=False)
print(f"wrote {path} ({path.stat().st_size} bytes)")
return path
def free_port():
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
return port
def start_php(port, data, log_path):
env = os.environ.copy()
env["METEORS_DATA_DIR"] = str(data)
log = open(log_path, "w")
proc = subprocess.Popen(
[PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
cwd=str(ROOT / "build"),
env=env,
stdout=log,
stderr=log,
)
time.sleep(0.5)
if proc.poll() is not None:
err = Path(log_path).read_text(errors="replace")
raise RuntimeError("php -S failed: " + err)
return proc
def seed_points(data, user="local:test_user_1", points=2000):
script = Path(data) / "seed.php"
script.write_text(f"""<?php
define('METEORS_NO_SESSION', true);
putenv('METEORS_DATA_DIR={data}');
require '{ROOT}/server/lib/bootstrap.php';
require '{ROOT}/server/lib/Store.php';
$s = Store::open('{data}');
echo $s->awardPoints('{user}', {points}, 'seed-playwright', 'solo');
""")
r = subprocess.run([PHP, str(script)], capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError("seed failed: " + r.stdout + "\n" + r.stderr)
print("seeded points, lifetime=", r.stdout.strip())
return r.stdout.strip()
def login(page, n=1):
page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=20000)
page.wait_for_timeout(200)
page.goto(f"{URL}index.html", wait_until="networkidle", timeout=20000)
page.wait_for_function(
"() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
timeout=10000,
)
page.wait_for_timeout(300)
def show_custom(page, grid=None):
try:
page.evaluate(
"""() => {
const c = document.querySelector('%s .planet-card.custom, .planet-card.custom');
if (c) c.scrollIntoView({block: 'center', behavior: 'instant'});
}""" % (grid or '#planet-select')
)
page.wait_for_timeout(250)
except Exception as e:
print("show_custom:", e)
def wait_vis(page, sel, timeout=8000):
page.locator(sel).wait_for(state="visible", timeout=timeout)
def fill_new_planet(page, name="Aurora", people="Aurorans"):
wait_vis(page, "#designer-edit")
page.locator("#des-name").fill(name)
page.locator("#des-people").fill(people)
page.locator("#des-gravity").fill("2.5")
page.locator("#des-air").fill("2")
page.locator("#des-mass").fill("1.2")
page.wait_for_timeout(150)
def main():
global URL
port = free_port()
URL = f"http://127.0.0.1:{port}/"
data = Path(tempfile.mkdtemp(prefix="meteors-designer-"))
log_path = data / "php.log"
print("data", data, "url", URL)
proc = start_php(port, data, log_path)
try:
with sync_playwright() as p:
browser = p.chromium.launch(
executable_path=CHROME, args=CHROME_ARGS, headless=True
)
desktop = browser.new_context(viewport={"width": 1280, "height": 800})
page = desktop.new_page()
errors = []
page.on("pageerror", lambda e: errors.append(str(e)))
page.on(
"console",
lambda m: errors.append(m.text) if m.type == "error" else None,
)
login(page)
check(page.locator("#btn-designer").is_visible(), "designer button on menu when logged in")
check("test_user_1" in page.locator("#menu-name").inner_text(), "menu shows login name")
shot(page, "t1139-menu-logged-in-1280.png")
page.locator("#btn-designer").click()
wait_vis(page, "#designer")
page.wait_for_timeout(200)
shot(page, "t1139-designer-empty-1280.png")
page.locator("#btn-designer-new").click()
fill_new_planet(page)
power = page.locator("#des-power").inner_text()
check("Power" in power, f"live Power preview: {power!r}")
check(page.locator(".des-slot").count() == 5, "five block slots")
shot(page, "t1139-designer-edit-1280.png")
# Modal: defaults are Terra, so opening slot 0: other four Terra used (grey), rest locked.
page.locator(".des-slot").nth(0).click()
wait_vis(page, "#des-modal")
page.wait_for_timeout(200)
locked = page.locator(".des-block.locked").count()
used = page.locator(".des-block.used").count()
locks = page.locator(".des-lock").count()
check(locked > 20, f"many locked blocks ({locked})")
check(locks == locked, f"lock icon on every locked block ({locks} vs {locked})")
check(used == 4, f"other four Terra slots greyed as used ({used})")
check(page.locator(".des-block:not(.locked):not(.used)").count() >= 1, "current terra is selectable")
shot(page, "t1139-modal-locked-grey-1280.png")
page.locator("#des-modal-close").click()
page.wait_for_timeout(150)
page.locator("#btn-designer-save").click()
wait_vis(page, "#designer")
page.wait_for_timeout(300)
cards = page.locator("#designer-list .designer-card")
check(cards.count() >= 1, "saved planet appears in the list")
check("Aurora" in page.locator("#designer-list").inner_text(), "list shows planet name")
shot(page, "t1139-designer-list-1280.png")
# Seed points so some later blocks unlock, then reopen the modal.
seed_points(data, points=2000)
page.reload(wait_until="networkidle")
page.wait_for_function(
"() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
timeout=10000,
)
pts = page.locator("#menu-points").inner_text().strip()
check(pts == "2000" or int(pts) >= 2000, f"menu points after seed ({pts})")
page.locator("#btn-designer").click()
wait_vis(page, "#designer")
page.locator("[data-edit]").first.click()
wait_vis(page, "#designer-edit")
page.locator(".des-slot").nth(4).click()
wait_vis(page, "#des-modal")
page.wait_for_timeout(250)
unlocked = page.locator(".des-block:not(.locked)").count()
locked = page.locator(".des-block.locked").count()
check(unlocked > 8, f"after 2000 points, several blocks unlocked ({unlocked})")
check(locked > 10, f"later blocks still locked ({locked})")
# Pick the first unlocked unused non-current block (Fehu etc.)
pick = page.locator(".des-block:not(.locked):not(.used):not(.current)").first
check(pick.count() == 1, "an unlocked unused block is clickable")
pick.click()
page.wait_for_timeout(200)
check(page.locator("#des-modal").is_hidden(), "modal closes after pick")
page.locator("#btn-designer-save").click()
wait_vis(page, "#designer")
page.wait_for_timeout(200)
shot(page, "t1139-modal-mixed-unlocked-1280.png") # will re-open for a clean shot
# Re-open modal just for a clear mixed locked/unlocked screenshot
page.locator("[data-edit]").first.click()
wait_vis(page, "#designer-edit")
page.locator(".des-slot").nth(0).click()
wait_vis(page, "#des-modal")
page.wait_for_timeout(200)
shot(page, "t1139-modal-mixed-unlocked-1280.png")
page.locator("#des-modal-close").click()
page.locator("#btn-designer-cancel").click()
page.locator("#btn-designer-back").click()
wait_vis(page, "#menu")
# --- pickers in all three modes ---
page.locator("#btn-play").click()
wait_vis(page, "#planet-select")
page.wait_for_timeout(250)
check(page.locator(".planet-card.custom").count() >= 1, "solo picker shows custom planet")
check("Aurora" in page.locator("#planet-grid").inner_text(), "solo picker lists Aurora")
check("Eigen" in page.locator(".custom-badge").first.inner_text(), "custom badge in solo picker")
shot(page, "t1139-picker-solo-1280.png")
page.locator("#btn-planet-back").click()
wait_vis(page, "#menu")
page.locator("#btn-offline").click()
wait_vis(page, "#planet-select")
page.wait_for_timeout(250)
check(page.locator(".planet-card.custom").count() >= 1, "offline picker shows custom planet")
shot(page, "t1139-picker-offline-1280.png")
page.locator("#btn-planet-back").click()
wait_vis(page, "#menu")
page.locator("#btn-online").click()
wait_vis(page, "#online-panel")
page.wait_for_timeout(400)
if page.locator("#btn-create").is_visible():
page.locator("#btn-create").click()
wait_vis(page, "#online-lobby")
page.wait_for_timeout(400)
check(page.locator("#lobby-planet-grid .planet-card.custom").count() >= 1,
"online lobby picker shows custom planet")
shot(page, "t1139-picker-online-1280.png")
if page.locator("#btn-leave-lobby").is_visible():
page.locator("#btn-leave-lobby").click()
page.wait_for_timeout(300)
# back to menu
back = page.locator("[data-back-menu]")
if back.count() and back.first.is_visible():
back.first.click()
else:
page.goto(f"{URL}index.html", wait_until="networkidle")
page.wait_for_timeout(400)
# Custom planet in play (solo)
wait_vis(page, "#menu")
page.locator("#btn-play").click()
wait_vis(page, "#planet-select")
page.locator(".planet-card.custom").first.click()
page.wait_for_timeout(150)
page.locator("#btn-planet-go").click()
page.wait_for_function(
"() => typeof app !== 'undefined' && app.mode === 'playing' && app.core",
timeout=10000,
)
page.wait_for_timeout(5500)
name = page.evaluate("() => app.planet && app.planet.name")
custom = page.evaluate("() => !!(app.planet && app.planet.custom)")
check(name == "Aurora", f"playing on custom planet ({name!r})")
check(custom is True, "planet.custom is true in play")
shot(page, "t1139-custom-in-play-1280.png")
# 1920 play + menu for consistency
page2 = desktop.new_page() # same context, still logged in? new page shares cookies
page2.set_viewport_size({"width": 1920, "height": 1080})
# already mid-play on page; start fresh on page2
page2.goto(f"{URL}index.html", wait_until="networkidle")
page2.wait_for_function(
"() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
timeout=10000,
)
shot(page2, "t1139-menu-logged-in-1920x1080.png")
page2.locator("#btn-play").click()
wait_vis(page2, "#planet-select")
page2.wait_for_timeout(200)
shot(page2, "t1139-picker-solo-1920x1080.png")
page2.locator(".planet-card.custom").first.click()
page2.locator("#btn-planet-go").click()
page2.wait_for_function(
"() => typeof app !== 'undefined' && app.mode === 'playing'",
timeout=10000,
)
page2.wait_for_timeout(5500)
shot(page2, "t1139-custom-in-play-1920x1080.png")
page2.close()
# --- mobile ---
mobile = browser.new_context(**MOBILE)
m = mobile.new_page()
login(m)
shot(m, "t1139-menu-logged-in-390.png")
m.locator("#btn-designer").click()
wait_vis(m, "#designer")
m.wait_for_timeout(200)
shot(m, "t1139-designer-list-390.png")
m.locator("[data-edit]").first.click()
wait_vis(m, "#designer-edit")
m.wait_for_timeout(200)
shot(m, "t1139-designer-edit-390.png")
m.locator(".des-slot").nth(0).click()
wait_vis(m, "#des-modal")
m.wait_for_timeout(200)
check(m.locator(".des-lock").count() > 0, "mobile modal shows lock icons")
shot(m, "t1139-modal-locked-grey-390.png")
m.locator("#des-modal-close").click()
m.wait_for_timeout(150)
m.evaluate("() => { if (typeof Designer !== 'undefined') Designer.close(); }")
m.wait_for_timeout(200)
if not m.locator("#menu").is_visible():
m.goto(f"{URL}index.html", wait_until="networkidle")
m.wait_for_function(
"() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }",
timeout=10000,
)
wait_vis(m, "#menu")
m.locator("#btn-play").click()
wait_vis(m, "#planet-select")
m.wait_for_timeout(200)
check(m.locator(".planet-card.custom").count() >= 1, "mobile solo picker shows custom")
show_custom(m)
shot(m, "t1139-picker-solo-390.png")
m.locator("#btn-planet-back").click()
wait_vis(m, "#menu")
m.locator("#btn-offline").click()
wait_vis(m, "#planet-select")
m.wait_for_timeout(200)
show_custom(m)
shot(m, "t1139-picker-offline-390.png")
m.locator("#btn-planet-back").click()
m.locator("#btn-online").click()
wait_vis(m, "#online-panel")
m.wait_for_timeout(400)
if m.locator("#btn-create").is_visible():
m.locator("#btn-create").click()
wait_vis(m, "#online-lobby")
m.wait_for_timeout(400)
check(m.locator("#lobby-planet-grid .planet-card.custom").count() >= 1,
"mobile online picker shows custom")
show_custom(m)
shot(m, "t1139-picker-online-390.png")
if errors:
print("page errors:", errors)
# fail only on real exceptions, not leftover console
real = [e for e in errors if "Failed to load" not in e]
if real:
FAILURES.append("page errors: " + "; ".join(real[:5]))
browser.close()
finally:
proc.terminate()
try:
proc.wait(timeout=3)
except Exception:
proc.kill()
print("php log:\n", log_path.read_text(errors="replace")[-2000:])
print("\n{} failures".format(len(FAILURES)))
for f in FAILURES:
print(" -", f)
return 0 if not FAILURES else 1
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,404 @@#!/usr/bin/env python3"""t1139 / t1140: Planet Designer UI, locked modal, custom planets in every picker."""from __future__ import annotationsimport osimport socketimport subprocessimport sysimport tempfileimport timefrom pathlib import Pathfrom playwright.sync_api import sync_playwrightROOT = Path("/workspace/meteors")SHOTS = Path("/workspace/meteors-shots")SHOTS.mkdir(parents=True, exist_ok=True)PHP = os.environ.get("PHP", "/home/box/.local/bin/php")CHROME = "/usr/bin/google-chrome"CHROME_ARGS = [ "--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage",]FAILURES = []URL = NoneMOBILE = { "viewport": {"width": 390, "height": 844}, "device_scale_factor": 2, "is_mobile": True, "has_touch": True, "user_agent": ( "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) " "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 " "Mobile/15E148 Safari/604.1" ),}def check(cond, msg): if cond: print("OK ", msg) else: print("FAIL", msg) FAILURES.append(msg) return conddef shot(page, name): path = SHOTS / name page.screenshot(path=str(path), full_page=False) print(f"wrote {path} ({path.stat().st_size} bytes)") return pathdef free_port(): s = socket.socket() s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] s.close() return portdef start_php(port, data, log_path): env = os.environ.copy() env["METEORS_DATA_DIR"] = str(data) log = open(log_path, "w") proc = subprocess.Popen( [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")], cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log, ) time.sleep(0.5) if proc.poll() is not None: err = Path(log_path).read_text(errors="replace") raise RuntimeError("php -S failed: " + err) return procdef seed_points(data, user="local:test_user_1", points=2000): script = Path(data) / "seed.php" script.write_text(f"""<?phpdefine('METEORS_NO_SESSION', true);putenv('METEORS_DATA_DIR={data}');require '{ROOT}/server/lib/bootstrap.php';require '{ROOT}/server/lib/Store.php';$s = Store::open('{data}');echo $s->awardPoints('{user}', {points}, 'seed-playwright', 'solo');""") r = subprocess.run([PHP, str(script)], capture_output=True, text=True) if r.returncode != 0: raise RuntimeError("seed failed: " + r.stdout + "\n" + r.stderr) print("seeded points, lifetime=", r.stdout.strip()) return r.stdout.strip()def login(page, n=1): page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=20000) page.wait_for_timeout(200) page.goto(f"{URL}index.html", wait_until="networkidle", timeout=20000) page.wait_for_function( "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }", timeout=10000, ) page.wait_for_timeout(300)def show_custom(page, grid=None): try: page.evaluate( """() => { const c = document.querySelector('%s .planet-card.custom, .planet-card.custom'); if (c) c.scrollIntoView({block: 'center', behavior: 'instant'}); }""" % (grid or '#planet-select') ) page.wait_for_timeout(250) except Exception as e: print("show_custom:", e)def wait_vis(page, sel, timeout=8000): page.locator(sel).wait_for(state="visible", timeout=timeout)def fill_new_planet(page, name="Aurora", people="Aurorans"): wait_vis(page, "#designer-edit") page.locator("#des-name").fill(name) page.locator("#des-people").fill(people) page.locator("#des-gravity").fill("2.5") page.locator("#des-air").fill("2") page.locator("#des-mass").fill("1.2") page.wait_for_timeout(150)def main(): global URL port = free_port() URL = f"http://127.0.0.1:{port}/" data = Path(tempfile.mkdtemp(prefix="meteors-designer-")) log_path = data / "php.log" print("data", data, "url", URL) proc = start_php(port, data, log_path) try: with sync_playwright() as p: browser = p.chromium.launch( executable_path=CHROME, args=CHROME_ARGS, headless=True ) desktop = browser.new_context(viewport={"width": 1280, "height": 800}) page = desktop.new_page() errors = [] page.on("pageerror", lambda e: errors.append(str(e))) page.on( "console", lambda m: errors.append(m.text) if m.type == "error" else None, ) login(page) check(page.locator("#btn-designer").is_visible(), "designer button on menu when logged in") check("test_user_1" in page.locator("#menu-name").inner_text(), "menu shows login name") shot(page, "t1139-menu-logged-in-1280.png") page.locator("#btn-designer").click() wait_vis(page, "#designer") page.wait_for_timeout(200) shot(page, "t1139-designer-empty-1280.png") page.locator("#btn-designer-new").click() fill_new_planet(page) power = page.locator("#des-power").inner_text() check("Power" in power, f"live Power preview: {power!r}") check(page.locator(".des-slot").count() == 5, "five block slots") shot(page, "t1139-designer-edit-1280.png") # Modal: defaults are Terra, so opening slot 0: other four Terra used (grey), rest locked. page.locator(".des-slot").nth(0).click() wait_vis(page, "#des-modal") page.wait_for_timeout(200) locked = page.locator(".des-block.locked").count() used = page.locator(".des-block.used").count() locks = page.locator(".des-lock").count() check(locked > 20, f"many locked blocks ({locked})") check(locks == locked, f"lock icon on every locked block ({locks} vs {locked})") check(used == 4, f"other four Terra slots greyed as used ({used})") check(page.locator(".des-block:not(.locked):not(.used)").count() >= 1, "current terra is selectable") shot(page, "t1139-modal-locked-grey-1280.png") page.locator("#des-modal-close").click() page.wait_for_timeout(150) page.locator("#btn-designer-save").click() wait_vis(page, "#designer") page.wait_for_timeout(300) cards = page.locator("#designer-list .designer-card") check(cards.count() >= 1, "saved planet appears in the list") check("Aurora" in page.locator("#designer-list").inner_text(), "list shows planet name") shot(page, "t1139-designer-list-1280.png") # Seed points so some later blocks unlock, then reopen the modal. seed_points(data, points=2000) page.reload(wait_until="networkidle") page.wait_for_function( "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }", timeout=10000, ) pts = page.locator("#menu-points").inner_text().strip() check(pts == "2000" or int(pts) >= 2000, f"menu points after seed ({pts})") page.locator("#btn-designer").click() wait_vis(page, "#designer") page.locator("[data-edit]").first.click() wait_vis(page, "#designer-edit") page.locator(".des-slot").nth(4).click() wait_vis(page, "#des-modal") page.wait_for_timeout(250) unlocked = page.locator(".des-block:not(.locked)").count() locked = page.locator(".des-block.locked").count() check(unlocked > 8, f"after 2000 points, several blocks unlocked ({unlocked})") check(locked > 10, f"later blocks still locked ({locked})") # Pick the first unlocked unused non-current block (Fehu etc.) pick = page.locator(".des-block:not(.locked):not(.used):not(.current)").first check(pick.count() == 1, "an unlocked unused block is clickable") pick.click() page.wait_for_timeout(200) check(page.locator("#des-modal").is_hidden(), "modal closes after pick") page.locator("#btn-designer-save").click() wait_vis(page, "#designer") page.wait_for_timeout(200) shot(page, "t1139-modal-mixed-unlocked-1280.png") # will re-open for a clean shot # Re-open modal just for a clear mixed locked/unlocked screenshot page.locator("[data-edit]").first.click() wait_vis(page, "#designer-edit") page.locator(".des-slot").nth(0).click() wait_vis(page, "#des-modal") page.wait_for_timeout(200) shot(page, "t1139-modal-mixed-unlocked-1280.png") page.locator("#des-modal-close").click() page.locator("#btn-designer-cancel").click() page.locator("#btn-designer-back").click() wait_vis(page, "#menu") # --- pickers in all three modes --- page.locator("#btn-play").click() wait_vis(page, "#planet-select") page.wait_for_timeout(250) check(page.locator(".planet-card.custom").count() >= 1, "solo picker shows custom planet") check("Aurora" in page.locator("#planet-grid").inner_text(), "solo picker lists Aurora") check("Eigen" in page.locator(".custom-badge").first.inner_text(), "custom badge in solo picker") shot(page, "t1139-picker-solo-1280.png") page.locator("#btn-planet-back").click() wait_vis(page, "#menu") page.locator("#btn-offline").click() wait_vis(page, "#planet-select") page.wait_for_timeout(250) check(page.locator(".planet-card.custom").count() >= 1, "offline picker shows custom planet") shot(page, "t1139-picker-offline-1280.png") page.locator("#btn-planet-back").click() wait_vis(page, "#menu") page.locator("#btn-online").click() wait_vis(page, "#online-panel") page.wait_for_timeout(400) if page.locator("#btn-create").is_visible(): page.locator("#btn-create").click() wait_vis(page, "#online-lobby") page.wait_for_timeout(400) check(page.locator("#lobby-planet-grid .planet-card.custom").count() >= 1, "online lobby picker shows custom planet") shot(page, "t1139-picker-online-1280.png") if page.locator("#btn-leave-lobby").is_visible(): page.locator("#btn-leave-lobby").click() page.wait_for_timeout(300) # back to menu back = page.locator("[data-back-menu]") if back.count() and back.first.is_visible(): back.first.click() else: page.goto(f"{URL}index.html", wait_until="networkidle") page.wait_for_timeout(400) # Custom planet in play (solo) wait_vis(page, "#menu") page.locator("#btn-play").click() wait_vis(page, "#planet-select") page.locator(".planet-card.custom").first.click() page.wait_for_timeout(150) page.locator("#btn-planet-go").click() page.wait_for_function( "() => typeof app !== 'undefined' && app.mode === 'playing' && app.core", timeout=10000, ) page.wait_for_timeout(5500) name = page.evaluate("() => app.planet && app.planet.name") custom = page.evaluate("() => !!(app.planet && app.planet.custom)") check(name == "Aurora", f"playing on custom planet ({name!r})") check(custom is True, "planet.custom is true in play") shot(page, "t1139-custom-in-play-1280.png") # 1920 play + menu for consistency page2 = desktop.new_page() # same context, still logged in? new page shares cookies page2.set_viewport_size({"width": 1920, "height": 1080}) # already mid-play on page; start fresh on page2 page2.goto(f"{URL}index.html", wait_until="networkidle") page2.wait_for_function( "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }", timeout=10000, ) shot(page2, "t1139-menu-logged-in-1920x1080.png") page2.locator("#btn-play").click() wait_vis(page2, "#planet-select") page2.wait_for_timeout(200) shot(page2, "t1139-picker-solo-1920x1080.png") page2.locator(".planet-card.custom").first.click() page2.locator("#btn-planet-go").click() page2.wait_for_function( "() => typeof app !== 'undefined' && app.mode === 'playing'", timeout=10000, ) page2.wait_for_timeout(5500) shot(page2, "t1139-custom-in-play-1920x1080.png") page2.close() # --- mobile --- mobile = browser.new_context(**MOBILE) m = mobile.new_page() login(m) shot(m, "t1139-menu-logged-in-390.png") m.locator("#btn-designer").click() wait_vis(m, "#designer") m.wait_for_timeout(200) shot(m, "t1139-designer-list-390.png") m.locator("[data-edit]").first.click() wait_vis(m, "#designer-edit") m.wait_for_timeout(200) shot(m, "t1139-designer-edit-390.png") m.locator(".des-slot").nth(0).click() wait_vis(m, "#des-modal") m.wait_for_timeout(200) check(m.locator(".des-lock").count() > 0, "mobile modal shows lock icons") shot(m, "t1139-modal-locked-grey-390.png") m.locator("#des-modal-close").click() m.wait_for_timeout(150) m.evaluate("() => { if (typeof Designer !== 'undefined') Designer.close(); }") m.wait_for_timeout(200) if not m.locator("#menu").is_visible(): m.goto(f"{URL}index.html", wait_until="networkidle") m.wait_for_function( "() => { const u = document.getElementById('menu-user'); return u && !u.hidden; }", timeout=10000, ) wait_vis(m, "#menu") m.locator("#btn-play").click() wait_vis(m, "#planet-select") m.wait_for_timeout(200) check(m.locator(".planet-card.custom").count() >= 1, "mobile solo picker shows custom") show_custom(m) shot(m, "t1139-picker-solo-390.png") m.locator("#btn-planet-back").click() wait_vis(m, "#menu") m.locator("#btn-offline").click() wait_vis(m, "#planet-select") m.wait_for_timeout(200) show_custom(m) shot(m, "t1139-picker-offline-390.png") m.locator("#btn-planet-back").click() m.locator("#btn-online").click() wait_vis(m, "#online-panel") m.wait_for_timeout(400) if m.locator("#btn-create").is_visible(): m.locator("#btn-create").click() wait_vis(m, "#online-lobby") m.wait_for_timeout(400) check(m.locator("#lobby-planet-grid .planet-card.custom").count() >= 1, "mobile online picker shows custom") show_custom(m) shot(m, "t1139-picker-online-390.png") if errors: print("page errors:", errors) # fail only on real exceptions, not leftover console real = [e for e in errors if "Failed to load" not in e] if real: FAILURES.append("page errors: " + "; ".join(real[:5])) browser.close() finally: proc.terminate() try: proc.wait(timeout=3) except Exception: proc.kill() print("php log:\n", log_path.read_text(errors="replace")[-2000:]) print("\n{} failures".format(len(FAILURES))) for f in FAILURES: print(" -", f) return 0 if not FAILURES else 1if __name__ == "__main__": sys.exit(main())