Merge branch 'feature/stage3-planets'
@@ -61,6 +61,7 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |
| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |
| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |
| `docs/ASSUMPTIONS.md` | Ingevulde aannames waar de specificatie ruimte liet |
| `src/build.sh` | Concateneert de bronnen naar `build/game.js` en kopieert de PHP-API naar `build/` |
| `build/` | Speelbare output: `index.html`, `style.css`, `framework.js`, `game.js`, `images/`, PHP-API |
@@ -69,6 +70,23 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToClear` tegels hoog; een verticale match van 3 krijgt 120 % daarvan, en elk extra blokje +5 % (wordt nergens in het spel uitgelegd). De massa bepaalt hoe lang de sprong omhoog duurt (onafhankelijk van de hoogte). Op de apex versnelt de cluster geleidelijk tot de valsnelheid (`apexEaseTime = 0,15 × fallTime`); daarna is de daal snelheid constant. De luchtweerstand (`fallTime`) bepaalt die valsnelheid én hoe snel de visuele landing-bounce is (`bounceDuration = 0,12 × fallTime`). Een vastgehouden blokje krijgt dezelfde schaal-tween als Tim's KWin Click Tween (150 ms easeOutBack naar 80 %, 720 ms easeOutElastic terug). Zie `docs/ASSUMPTIONS.md`.
## Planeten (stage 3)
Voor je gaat spelen — solo en in de lobby — kies je een **veld**. Elk veld
is een planeet met een volk, vijf eigen kleuren/vormen, en drie natuurwetten:
- zwaartekracht — hoe hoog de eerste sprong is (`g`, m/s²)
- luchtweerstand — hoe snel blokjes weer vallen (`d`)
- massa — hoe snel de sprong omhoog gaat (`F`, newton)
Power is het gemiddelde van die drie, als percentage. Hoe hoger de Power,
hoe kleiner de kans dat een afgeschoten blokje een andere speler mist.
In een online wedstrijd telt **jouw** planeet voor de blokjes die jij
verstuurt. De twaalf werelden en hun getallen staan in
`server/lib/planets.json`. De blokplaatjes zijn unieke placeholders
(`build/images/block-{planeet}-{kleur}.png`); Tim kan ze zelf vervangen.
## 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.
@@ -86,8 +104,8 @@ zijn en iedereen gereed is.
Je eigen veld is het hoofdspel; miniaturen van de tegenstanders staan erboven.
Blokjes die van je veld afschieten kiezen een willekeurige andere (nog niet
uitgeschakelde) speler en vliegen daar in een korte tween naartoe (draaien en
krimpen). Met 30 % kans (`missChance`, een parameter; in stage 3 wordt dit
`Planet.missChance` via Power) missen ze en verdwijnen ze in de verte. Een raak
krimpen). De kans dat ze missen komt uit de **Power van jouw planeet** (60 % op het
makkelijkste veld, 5 % op het moeilijkste); dat gooit de server. Een raak
schot komt bij de ander aan als een vallend donkergrijs blokje dat na 3 seconden
op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschouwer
en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
@@ -61,6 +61,7 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby || `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby || `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes || `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes || `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) || `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) || `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) || `docs/ASSUMPTIONS.md` | Ingevulde aannames waar de specificatie ruimte liet || `docs/ASSUMPTIONS.md` | Ingevulde aannames waar de specificatie ruimte liet || `src/build.sh` | Concateneert de bronnen naar `build/game.js` en kopieert de PHP-API naar `build/` || `src/build.sh` | Concateneert de bronnen naar `build/game.js` en kopieert de PHP-API naar `build/` || `build/` | Speelbare output: `index.html`, `style.css`, `framework.js`, `game.js`, `images/`, PHP-API || `build/` | Speelbare output: `index.html`, `style.css`, `framework.js`, `game.js`, `images/`, PHP-API |@@ -69,6 +70,23 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToClear` tegels hoog; een verticale match van 3 krijgt 120 % daarvan, en elk extra blokje +5 % (wordt nergens in het spel uitgelegd). De massa bepaalt hoe lang de sprong omhoog duurt (onafhankelijk van de hoogte). Op de apex versnelt de cluster geleidelijk tot de valsnelheid (`apexEaseTime = 0,15 × fallTime`); daarna is de daal snelheid constant. De luchtweerstand (`fallTime`) bepaalt die valsnelheid én hoe snel de visuele landing-bounce is (`bounceDuration = 0,12 × fallTime`). Een vastgehouden blokje krijgt dezelfde schaal-tween als Tim's KWin Click Tween (150 ms easeOutBack naar 80 %, 720 ms easeOutElastic terug). Zie `docs/ASSUMPTIONS.md`.Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToClear` tegels hoog; een verticale match van 3 krijgt 120 % daarvan, en elk extra blokje +5 % (wordt nergens in het spel uitgelegd). De massa bepaalt hoe lang de sprong omhoog duurt (onafhankelijk van de hoogte). Op de apex versnelt de cluster geleidelijk tot de valsnelheid (`apexEaseTime = 0,15 × fallTime`); daarna is de daal snelheid constant. De luchtweerstand (`fallTime`) bepaalt die valsnelheid én hoe snel de visuele landing-bounce is (`bounceDuration = 0,12 × fallTime`). Een vastgehouden blokje krijgt dezelfde schaal-tween als Tim's KWin Click Tween (150 ms easeOutBack naar 80 %, 720 ms easeOutElastic terug). Zie `docs/ASSUMPTIONS.md`.## Planeten (stage 3)Voor je gaat spelen — solo en in de lobby — kies je een **veld**. Elk veldis een planeet met een volk, vijf eigen kleuren/vormen, en drie natuurwetten:- zwaartekracht — hoe hoog de eerste sprong is (`g`, m/s²)- luchtweerstand — hoe snel blokjes weer vallen (`d`)- massa — hoe snel de sprong omhoog gaat (`F`, newton)Power is het gemiddelde van die drie, als percentage. Hoe hoger de Power,hoe kleiner de kans dat een afgeschoten blokje een andere speler mist.In een online wedstrijd telt **jouw** planeet voor de blokjes die jijverstuurt. De twaalf werelden en hun getallen staan in`server/lib/planets.json`. De blokplaatjes zijn unieke placeholders(`build/images/block-{planeet}-{kleur}.png`); Tim kan ze zelf vervangen.## 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.@@ -86,8 +104,8 @@ zijn en iedereen gereed is.Je eigen veld is het hoofdspel; miniaturen van de tegenstanders staan erboven.Je eigen veld is het hoofdspel; miniaturen van de tegenstanders staan erboven.Blokjes die van je veld afschieten kiezen een willekeurige andere (nog nietBlokjes die van je veld afschieten kiezen een willekeurige andere (nog nietuitgeschakelde) speler en vliegen daar in een korte tween naartoe (draaien enuitgeschakelde) speler en vliegen daar in een korte tween naartoe (draaien enkrimpen). Met 30 % kans (`missChance`, een parameter; in stage 3 wordt ditkrimpen). De kans dat ze missen komt uit de **Power van jouw planeet** (60 % op het`Planet.missChance` via Power) missen ze en verdwijnen ze in de verte. Een raakmakkelijkste veld, 5 % op het moeilijkste); dat gooit de server. Een raakschot komt bij de ander aan als een vallend donkergrijs blokje dat na 3 secondenschot komt bij de ander aan als een vallend donkergrijs blokje dat na 3 secondenop een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschouwerop een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschouweren geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 secondenen geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden@@ -53,6 +53,10 @@ build_game:
- test -f build/.htaccess
- test -f build/lib/bootstrap.php
- test -f build/lib/Store.php
- test -f build/lib/Planets.php
- test -f build/lib/planets.json
- test -f build/images/block-terra-ember.png
- test -f build/images/block-cinder-magma.png
- test -f build/data/.htaccess
- test ! -f build/data/config.php
- test ! -e build/data/*.sqlite
@@ -84,6 +88,8 @@ build_game:
- build/.htaccess
- build/lib/bootstrap.php
- build/lib/Store.php
- build/lib/Planets.php
- build/lib/planets.json
- build/data/.htaccess
expire_in: 7d
@@ -53,6 +53,10 @@ build_game: - test -f build/.htaccess - test -f build/.htaccess - test -f build/lib/bootstrap.php - test -f build/lib/bootstrap.php - test -f build/lib/Store.php - test -f build/lib/Store.php - test -f build/lib/Planets.php - test -f build/lib/planets.json - test -f build/images/block-terra-ember.png - test -f build/images/block-cinder-magma.png - test -f build/data/.htaccess - test -f build/data/.htaccess - test ! -f build/data/config.php - test ! -f build/data/config.php - test ! -e build/data/*.sqlite - test ! -e build/data/*.sqlite@@ -84,6 +88,8 @@ build_game: - build/.htaccess - build/.htaccess - build/lib/bootstrap.php - build/lib/bootstrap.php - build/lib/Store.php - build/lib/Store.php - build/lib/Planets.php - build/lib/planets.json - build/data/.htaccess - build/data/.htaccess expire_in: 7d expire_in: 7d@@ -2,6 +2,191 @@
* AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
* Built by src/build.sh from the sources in src/.
*/
var PLANET_CATALOG = {
"planets": [
{
"id": "terra",
"name": "Terra",
"people": "Terrans",
"jumpsToClear": 2,
"fallTime": 3,
"riseTime": 1.5,
"colors": [
{"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"},
{"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"},
{"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"},
{"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"},
{"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"}
]
},
{
"id": "aurel",
"name": "Aurel",
"people": "Aurelians",
"jumpsToClear": 1,
"fallTime": 5,
"riseTime": 3,
"colors": [
{"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"},
{"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"},
{"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"},
{"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"},
{"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"}
]
},
{
"id": "cinder",
"name": "Cinder",
"people": "Cindari",
"jumpsToClear": 4,
"fallTime": 1,
"riseTime": 0.5,
"colors": [
{"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"},
{"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"},
{"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"},
{"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"},
{"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"}
]
},
{
"id": "lunara",
"name": "Lunara",
"people": "Lunarites",
"jumpsToClear": 1,
"fallTime": 2,
"riseTime": 1.2,
"colors": [
{"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"},
{"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"},
{"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"},
{"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"},
{"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"}
]
},
{
"id": "mire",
"name": "Mire",
"people": "Mirians",
"jumpsToClear": 2,
"fallTime": 5,
"riseTime": 2.5,
"colors": [
{"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"},
{"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"},
{"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"},
{"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"},
{"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"}
]
},
{
"id": "galeon",
"name": "Galeon",
"people": "Galeoni",
"jumpsToClear": 3,
"fallTime": 1,
"riseTime": 1.8,
"colors": [
{"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"},
{"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"},
{"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"},
{"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"},
{"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"}
]
},
{
"id": "obsid",
"name": "Obsid",
"people": "Obsidians",
"jumpsToClear": 4,
"fallTime": 3.5,
"riseTime": 2.2,
"colors": [
{"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"},
{"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"},
{"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"},
{"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"},
{"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"}
]
},
{
"id": "wisp",
"name": "Wisp",
"people": "Wisplings",
"jumpsToClear": 2,
"fallTime": 3.5,
"riseTime": 0.5,
"colors": [
{"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"},
{"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"},
{"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"},
{"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"},
{"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"}
]
},
{
"id": "thorn",
"name": "Thorn",
"people": "Thornfolk",
"jumpsToClear": 3,
"fallTime": 2,
"riseTime": 1.0,
"colors": [
{"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"},
{"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"},
{"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"},
{"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"},
{"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"}
]
},
{
"id": "zephyr",
"name": "Zephyr",
"people": "Zephyrites",
"jumpsToClear": 1,
"fallTime": 1.2,
"riseTime": 2.8,
"colors": [
{"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"},
{"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"},
{"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"},
{"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"},
{"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"}
]
},
{
"id": "frore",
"name": "Frore",
"people": "Frorians",
"jumpsToClear": 3,
"fallTime": 4.5,
"riseTime": 0.8,
"colors": [
{"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"},
{"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"},
{"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"},
{"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"},
{"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"}
]
},
{
"id": "forge",
"name": "Forge",
"people": "Forgelings",
"jumpsToClear": 4,
"fallTime": 2,
"riseTime": 1.5,
"colors": [
{"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"},
{"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"},
{"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"},
{"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"},
{"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"}
]
}
]
}
;
/*
* Start File:
@@ -114,6 +299,7 @@ function createPlanet (opts)
var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
var colors = opts.colors || defaultColors();
var planet = {
id: opts.id || null,
name: opts.name || 'Terra',
people: opts.people || 'Terrans',
jumpsToClear: jumpsToClear,
@@ -133,15 +319,82 @@ function createPlanet (opts)
return planet;
}
function defaultPlanet ()
function loadCatalog ()
{
if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
{ return PLANET_CATALOG; }
if (typeof require !== 'undefined')
{
try
{ return require('../server/lib/planets.json'); }
catch (e) {}
}
return { planets: [] };
}
function planetFromData (data)
{
return createPlanet({
name: 'Terra',
people: 'Terrans',
jumpsToClear: 2,
fallTime: 3,
riseTime: 1.5
var planet = createPlanet({
name: data.name,
people: data.people,
jumpsToClear: data.jumpsToClear,
fallTime: data.fallTime,
riseTime: data.riseTime,
colors: data.colors
});
planet.id = data.id;
return planet;
}
function allPlanets ()
{
var raw = loadCatalog().planets || [];
var out = [];
for (var i = 0; i < raw.length; i++)
{ out.push(planetFromData(raw[i])); }
if (out.length === 0)
{ out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
return out;
}
function planetById (id)
{
var all = allPlanets();
for (var i = 0; i < all.length; i++)
{
if (all[i].id === id)
{ return all[i]; }
}
return defaultPlanet();
}
function defaultPlanet ()
{
var all = allPlanets();
for (var i = 0; i < all.length; i++)
{
if (all[i].id === 'terra')
{ return all[i]; }
}
return all[0];
}
function formatStats (planet)
{
var d = displayValues(planet);
return 'g ' + d.gravity.toFixed(2)
+ ' d ' + d.density.toFixed(2)
+ ' F ' + Math.round(d.newtons) + ' N'
+ ' Power ' + d.power + '%';
}
function spriteKey (planet, colorIndex)
{
var colors = planet && planet.colors;
var c = colors && colors[colorIndex];
if (!c)
{ return 'gray'; }
return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
}
/**
@@ -221,6 +474,11 @@ var Planet = {
createPlanet: createPlanet,
defaultPlanet: defaultPlanet,
defaultColors: defaultColors,
allPlanets: allPlanets,
planetById: planetById,
planetFromData: planetFromData,
formatStats: formatStats,
spriteKey: spriteKey,
jumpHeight: jumpHeight,
launchVelocity: launchVelocity,
launchDeceleration: launchDeceleration,
@@ -453,6 +711,9 @@ function optsMissChance (args)
// GameCore(planet, rng, missChance) — third arg is optional.
if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
{ return Math.max(0, Math.min(1, args[2])); }
var planet = args[0];
if (planet && typeof PlanetMod.missChance === 'function')
{ return PlanetMod.missChance(planet); }
return GameCore.DEFAULT_MISS_CHANCE;
}
@@ -2400,14 +2661,25 @@ Online.testLogin = function (who)
return this.request('test_login', { user: who });
};
Online.createLobby = function ()
Online.createLobby = function (planetId)
{
return this.request('lobby_create', {
miss_chance: this.DEFAULT_MISS_CHANCE,
planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
});
};
Online.joinLobby = function (code, planetId)
{
return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
return this.request('lobby_join', {
code: code,
planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
});
};
Online.joinLobby = function (code)
Online.setPlanet = function (planetId)
{
return this.request('lobby_join', { code: code });
return this.request('lobby_set_planet', { planet_id: planetId });
};
Online.leaveLobby = function ()
@@ -2574,7 +2846,7 @@ Online.renderMinis = function (container)
el.querySelector('.mini-meta').textContent = p.eliminated
? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
: ('Punten ' + (p.score || 0));
this._drawMini(el.querySelector('canvas'), p.snapshot);
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
}
for (var id in existing)
{
@@ -2585,7 +2857,15 @@ Online.renderMinis = function (container)
var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
Online._drawMini = function (canvas, snapshot)
function miniColor (planet, color)
{
if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
{ return planet.colors[color].hex; }
return MINI_COLORS[color] || '#888';
}
Online._drawMini = function (canvas, snapshot, planet)
{
if (!canvas)
{ return; }
@@ -2625,7 +2905,7 @@ Online._drawMini = function (canvas, snapshot)
else if (b.color < 0)
{ ctx.fillStyle = '#5a5d66'; }
else
{ ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
{ ctx.fillStyle = miniColor(planet, b.color); }
ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
}
};
@@ -2637,12 +2917,16 @@ Online.miniElement = function (playerId)
/* ---------- flight tweens ------------------------------------------ */
function colorSpriteUrl (color)
function colorSpriteUrl (color, planetId)
{
if (color < 0)
{ return 'images/block-gray.png'; }
var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
return 'images/block-' + (names[color] || 'gray') + '.png';
var planet = null;
if (typeof Planet !== 'undefined')
{ planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
{ return planet.colors[color].image; }
return 'images/block-gray.png';
}
/**
@@ -2824,20 +3108,37 @@ if (typeof module !== 'undefined' && module.exports)
* through Online (src/online.js) and the same GameCore.
*/
var IMAGES = [
{ name: 'ember', url: 'images/block-ember.png' },
{ name: 'aqua', url: 'images/block-aqua.png' },
{ name: 'leaf', url: 'images/block-leaf.png' },
{ name: 'sun', url: 'images/block-sun.png' },
{ name: 'orchid', url: 'images/block-orchid.png' },
{ name: 'gray', url: 'images/block-gray.png' },
{ name: 'locked', url: 'images/block-locked.png' },
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
{ name: 'cell', url: 'images/cell.png' },
{ name: 'pixel', url: 'images/pixel.png' }
];
var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
function planetImages ()
{
var list = [
{ name: 'gray', url: 'images/block-gray.png' },
{ name: 'locked', url: 'images/block-locked.png' },
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
{ name: 'cell', url: 'images/cell.png' },
{ name: 'pixel', url: 'images/pixel.png' },
// Keep the original Terra placeholders as aliases (Tim may still have them).
{ name: 'ember', url: 'images/block-ember.png' },
{ name: 'aqua', url: 'images/block-aqua.png' },
{ name: 'leaf', url: 'images/block-leaf.png' },
{ name: 'sun', url: 'images/block-sun.png' },
{ name: 'orchid', url: 'images/block-orchid.png' }
];
var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
for (var i = 0; i < planets.length; i++)
{
var pl = planets[i];
for (var c = 0; c < pl.colors.length; c++)
{
list.push({
name: Planet.spriteKey(pl, c),
url: pl.colors[c].image
});
}
}
return list;
}
var IMAGES = planetImages();
var GAME_OVER_DELAY = 2;
var game = new Game();
@@ -2863,7 +3164,9 @@ var app = {
online: false,
eliminatedReported: false,
spectating: false,
miniH: 0
miniH: 0,
selectedPlanetId: 'terra',
planetSelectContext: 'solo'
};
window.onload = function ()
@@ -2888,13 +3191,15 @@ window.onload = function ()
});
bindOnlineUi();
bindPlanetSelect();
restoreSelectedPlanet();
};
function onPlay ()
{
if (app.mode === 'playing')
{ return; }
startPlay();
openPlanetSelect('solo');
}
function startPlay (opts)
@@ -2905,14 +3210,15 @@ function startPlay (opts)
hideEl('online-panel');
hideEl('spectator');
hideEl('podium');
hideEl('planet-select');
showEl('hud');
app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
var miss = opts.missChance;
if (typeof miss === 'number' && isFinite(miss))
{ app.core = new GameCore(app.planet, Math.random, miss); }
else
{ app.core = new GameCore(app.planet, Math.random); }
if (typeof miss !== 'number' || !isFinite(miss))
{ miss = planetMod.missChance(app.planet); }
app.core = new GameCore(app.planet, Math.random, miss);
app.mode = 'playing';
app.online = !!opts.online;
app.gameOverShown = false;
@@ -2981,6 +3287,7 @@ function returnToMenu ()
teardownPlay();
app.mode = 'menu';
app.online = false;
hideEl('planet-select');
showEl('menu');
var last = document.getElementById('last-score');
if (app.lastScore > 0)
@@ -3064,7 +3371,8 @@ function spriteFor (block)
{ return game.images.locked; }
if (block.color < 0)
{ return game.images.gray; }
return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
var key = Planet.spriteKey(app.planet, block.color);
return game.images[key] || game.images.gray;
}
function syncSprites ()
@@ -3223,10 +3531,7 @@ function refreshHud ()
document.getElementById('score').textContent = String(app.core.score);
var planet = app.planet;
document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
var d = Planet.displayValues(planet);
document.getElementById('planet-stats').textContent =
'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
}
function makeManager ()
@@ -3504,10 +3809,11 @@ function startOnlineMatch ()
{
if (app.mode === 'playing' && app.online)
{ return; }
var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
? Online.lobby.miss_chance
: (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
startPlay({ online: true, missChance: miss });
var planet = Planet.planetById(selectedPlanetId());
var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
if (me && me.planet && me.planet.id)
{ planet = Planet.planetById(me.planet.id); }
startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
if (typeof Online !== 'undefined')
{ Online.startPolling(onlinePayload); }
}
@@ -3664,6 +3970,7 @@ function openOnlinePanel ()
hideEl('game-over');
hideEl('podium');
hideEl('spectator');
hideEl('planet-select');
showEl('online-panel');
app.mode = 'online';
setOnlineStatus('Even kijken of online spelen beschikbaar is…');
@@ -3765,10 +4072,14 @@ function renderOnline ()
{ li.classList.add('you'); }
var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
var state = p.ready ? 'Gereed' : 'Wacht…';
li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
li.innerHTML = '<span>' + escapeText(label)
+ (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
+ '</span><span class="'
+ (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
list.appendChild(li);
}
renderPlanetGrid('lobby-planet-grid', true);
var me = Online.mePlayer();
document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
var start = document.getElementById('btn-start');
@@ -3802,6 +4113,150 @@ function escapeText (s)
.replace(/"/g, '"');
}
function selectedPlanetId ()
{
if (app.selectedPlanetId)
{ return app.selectedPlanetId; }
return 'terra';
}
function restoreSelectedPlanet ()
{
var id = 'terra';
try
{ id = localStorage.getItem('meteors-planet') || 'terra'; }
catch (e) {}
setSelectedPlanet(id, true);
}
function setSelectedPlanet (id, silent)
{
var all = Planet.allPlanets();
var found = null;
for (var i = 0; i < all.length; i++)
{
if (all[i].id === id)
{ found = all[i]; break; }
}
if (!found)
{ found = Planet.defaultPlanet(); }
app.selectedPlanetId = found.id;
try
{ localStorage.setItem('meteors-planet', found.id); }
catch (e) {}
if (!silent)
{
var grid = document.getElementById('planet-grid');
if (grid && !grid.hidden && grid.children.length)
{ renderPlanetGrid('planet-grid', false); }
var lobby = document.getElementById('lobby-planet-grid');
if (lobby && lobby.children.length)
{ renderPlanetGrid('lobby-planet-grid', true); }
}
return found;
}
function openPlanetSelect (context)
{
if (app.mode === 'playing')
{ return; }
app.planetSelectContext = context || 'solo';
app.mode = 'planet-select';
hideEl('menu');
hideEl('online-panel');
hideEl('game-over');
showEl('planet-select');
renderPlanetGrid('planet-grid', false);
var go = document.getElementById('btn-planet-go');
if (go)
{ go.textContent = 'Spelen'; }
}
function renderPlanetGrid (containerId, compact)
{
var grid = document.getElementById(containerId);
if (!grid)
{ return; }
var current = selectedPlanetId();
var all = Planet.allPlanets();
grid.innerHTML = '';
if (compact)
{ grid.classList.add('compact'); }
for (var i = 0; i < all.length; i++)
{
var pl = all[i];
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
btn.setAttribute('role', 'listitem');
btn.dataset.planet = pl.id;
var swatches = '';
for (var c = 0; c < pl.colors.length; c++)
{
swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
+ escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.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>';
btn.addEventListener('click', (function (id, isCompact)
{
return function ()
{ onPlanetPicked(id, isCompact); };
})(pl.id, !!compact));
grid.appendChild(btn);
}
}
function onPlanetPicked (id, fromLobby)
{
setSelectedPlanet(id);
if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
{
Online.setPlanet(id).then(function ()
{ renderOnline(); });
}
else
{
renderPlanetGrid('planet-grid', false);
}
}
function confirmPlanetSelect ()
{
var planet = setSelectedPlanet(selectedPlanetId());
hideEl('planet-select');
if (app.planetSelectContext === 'online')
{
openOnlinePanel();
return;
}
startPlay({ planet: planet });
}
function cancelPlanetSelect ()
{
hideEl('planet-select');
app.mode = 'menu';
showEl('menu');
}
function bindPlanetSelect ()
{
var go = document.getElementById('btn-planet-go');
var back = document.getElementById('btn-planet-back');
if (go)
{
go.addEventListener('click', confirmPlanetSelect);
}
if (back)
{
back.addEventListener('click', cancelPlanetSelect);
}
}
/*
* End File:
* /workspace/meteors/src/main.js
@@ -2,6 +2,191 @@ * AUTO-GENERATED FILE — DO NOT EDIT BY HAND. * AUTO-GENERATED FILE — DO NOT EDIT BY HAND. * Built by src/build.sh from the sources in src/. * Built by src/build.sh from the sources in src/. */ */var PLANET_CATALOG = { "planets": [ { "id": "terra", "name": "Terra", "people": "Terrans", "jumpsToClear": 2, "fallTime": 3, "riseTime": 1.5, "colors": [ {"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"}, {"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"}, {"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"}, {"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"}, {"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"} ] }, { "id": "aurel", "name": "Aurel", "people": "Aurelians", "jumpsToClear": 1, "fallTime": 5, "riseTime": 3, "colors": [ {"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"}, {"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"}, {"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"}, {"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"}, {"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"} ] }, { "id": "cinder", "name": "Cinder", "people": "Cindari", "jumpsToClear": 4, "fallTime": 1, "riseTime": 0.5, "colors": [ {"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"}, {"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"}, {"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"}, {"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"}, {"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"} ] }, { "id": "lunara", "name": "Lunara", "people": "Lunarites", "jumpsToClear": 1, "fallTime": 2, "riseTime": 1.2, "colors": [ {"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"}, {"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"}, {"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"}, {"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"}, {"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"} ] }, { "id": "mire", "name": "Mire", "people": "Mirians", "jumpsToClear": 2, "fallTime": 5, "riseTime": 2.5, "colors": [ {"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"}, {"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"}, {"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"}, {"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"}, {"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"} ] }, { "id": "galeon", "name": "Galeon", "people": "Galeoni", "jumpsToClear": 3, "fallTime": 1, "riseTime": 1.8, "colors": [ {"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"}, {"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"}, {"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"}, {"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"}, {"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"} ] }, { "id": "obsid", "name": "Obsid", "people": "Obsidians", "jumpsToClear": 4, "fallTime": 3.5, "riseTime": 2.2, "colors": [ {"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"}, {"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"}, {"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"}, {"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"}, {"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"} ] }, { "id": "wisp", "name": "Wisp", "people": "Wisplings", "jumpsToClear": 2, "fallTime": 3.5, "riseTime": 0.5, "colors": [ {"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"}, {"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"}, {"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"}, {"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"}, {"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"} ] }, { "id": "thorn", "name": "Thorn", "people": "Thornfolk", "jumpsToClear": 3, "fallTime": 2, "riseTime": 1.0, "colors": [ {"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"}, {"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"}, {"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"}, {"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"}, {"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"} ] }, { "id": "zephyr", "name": "Zephyr", "people": "Zephyrites", "jumpsToClear": 1, "fallTime": 1.2, "riseTime": 2.8, "colors": [ {"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"}, {"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"}, {"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"}, {"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"}, {"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"} ] }, { "id": "frore", "name": "Frore", "people": "Frorians", "jumpsToClear": 3, "fallTime": 4.5, "riseTime": 0.8, "colors": [ {"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"}, {"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"}, {"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"}, {"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"}, {"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"} ] }, { "id": "forge", "name": "Forge", "people": "Forgelings", "jumpsToClear": 4, "fallTime": 2, "riseTime": 1.5, "colors": [ {"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"}, {"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"}, {"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"}, {"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"}, {"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"} ] } ]};/*/* * Start File: * Start File:@@ -114,6 +299,7 @@ function createPlanet (opts) var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3); var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3); var colors = opts.colors || defaultColors(); var colors = opts.colors || defaultColors(); var planet = { var planet = { id: opts.id || null, name: opts.name || 'Terra', name: opts.name || 'Terra', people: opts.people || 'Terrans', people: opts.people || 'Terrans', jumpsToClear: jumpsToClear, jumpsToClear: jumpsToClear,@@ -133,15 +319,82 @@ function createPlanet (opts) return planet; return planet;}}function defaultPlanet ()function loadCatalog (){ if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets) { return PLANET_CATALOG; } if (typeof require !== 'undefined') { try { return require('../server/lib/planets.json'); } catch (e) {} } return { planets: [] };}function planetFromData (data){{ return createPlanet({ var planet = createPlanet({ name: 'Terra', name: data.name, people: 'Terrans', people: data.people, jumpsToClear: 2, jumpsToClear: data.jumpsToClear, fallTime: 3, fallTime: data.fallTime, riseTime: 1.5 riseTime: data.riseTime, colors: data.colors }); }); planet.id = data.id; return planet;}function allPlanets (){ var raw = loadCatalog().planets || []; var out = []; for (var i = 0; i < raw.length; i++) { out.push(planetFromData(raw[i])); } if (out.length === 0) { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; } return out;}function planetById (id){ var all = allPlanets(); for (var i = 0; i < all.length; i++) { if (all[i].id === id) { return all[i]; } } return defaultPlanet();}function defaultPlanet (){ var all = allPlanets(); for (var i = 0; i < all.length; i++) { if (all[i].id === 'terra') { return all[i]; } } return all[0];}function formatStats (planet){ var d = displayValues(planet); return 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) + ' F ' + Math.round(d.newtons) + ' N' + ' Power ' + d.power + '%';}function spriteKey (planet, colorIndex){ var colors = planet && planet.colors; var c = colors && colors[colorIndex]; if (!c) { return 'gray'; } return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));}}/**/**@@ -221,6 +474,11 @@ var Planet = { createPlanet: createPlanet, createPlanet: createPlanet, defaultPlanet: defaultPlanet, defaultPlanet: defaultPlanet, defaultColors: defaultColors, defaultColors: defaultColors, allPlanets: allPlanets, planetById: planetById, planetFromData: planetFromData, formatStats: formatStats, spriteKey: spriteKey, jumpHeight: jumpHeight, jumpHeight: jumpHeight, launchVelocity: launchVelocity, launchVelocity: launchVelocity, launchDeceleration: launchDeceleration, launchDeceleration: launchDeceleration,@@ -453,6 +711,9 @@ function optsMissChance (args) // GameCore(planet, rng, missChance) — third arg is optional. // GameCore(planet, rng, missChance) — third arg is optional. if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2])) if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2])) { return Math.max(0, Math.min(1, args[2])); } { return Math.max(0, Math.min(1, args[2])); } var planet = args[0]; if (planet && typeof PlanetMod.missChance === 'function') { return PlanetMod.missChance(planet); } return GameCore.DEFAULT_MISS_CHANCE; return GameCore.DEFAULT_MISS_CHANCE;}}@@ -2400,14 +2661,25 @@ Online.testLogin = function (who) return this.request('test_login', { user: who }); return this.request('test_login', { user: who });};};Online.createLobby = function ()Online.createLobby = function (planetId){ return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') });};Online.joinLobby = function (code, planetId){{ return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE }); return this.request('lobby_join', { code: code, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') });};};Online.joinLobby = function (code)Online.setPlanet = function (planetId){{ return this.request('lobby_join', { code: code }); return this.request('lobby_set_planet', { planet_id: planetId });};};Online.leaveLobby = function ()Online.leaveLobby = function ()@@ -2574,7 +2846,7 @@ Online.renderMinis = function (container) el.querySelector('.mini-meta').textContent = p.eliminated el.querySelector('.mini-meta').textContent = p.eliminated ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : '')) ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : '')) : ('Punten ' + (p.score || 0)); : ('Punten ' + (p.score || 0)); this._drawMini(el.querySelector('canvas'), p.snapshot); this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet); } } for (var id in existing) for (var id in existing) { {@@ -2585,7 +2857,15 @@ Online.renderMinis = function (container)var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];Online._drawMini = function (canvas, snapshot)function miniColor (planet, color){ if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex) { return planet.colors[color].hex; } return MINI_COLORS[color] || '#888';}Online._drawMini = function (canvas, snapshot, planet){{ if (!canvas) if (!canvas) { return; } { return; }@@ -2625,7 +2905,7 @@ Online._drawMini = function (canvas, snapshot) else if (b.color < 0) else if (b.color < 0) { ctx.fillStyle = '#5a5d66'; } { ctx.fillStyle = '#5a5d66'; } else else { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; } { ctx.fillStyle = miniColor(planet, b.color); } ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1); ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1); } }};};@@ -2637,12 +2917,16 @@ Online.miniElement = function (playerId)/* ---------- flight tweens ------------------------------------------ *//* ---------- flight tweens ------------------------------------------ */function colorSpriteUrl (color)function colorSpriteUrl (color, planetId){{ if (color < 0) if (color < 0) { return 'images/block-gray.png'; } { return 'images/block-gray.png'; } var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid']; var planet = null; return 'images/block-' + (names[color] || 'gray') + '.png'; if (typeof Planet !== 'undefined') { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); } if (planet && planet.colors && planet.colors[color] && planet.colors[color].image) { return planet.colors[color].image; } return 'images/block-gray.png';}}/**/**@@ -2824,20 +3108,37 @@ if (typeof module !== 'undefined' && module.exports) * through Online (src/online.js) and the same GameCore. * through Online (src/online.js) and the same GameCore. */ */var IMAGES = [function planetImages () { name: 'ember', url: 'images/block-ember.png' },{ { name: 'aqua', url: 'images/block-aqua.png' }, var list = [ { name: 'leaf', url: 'images/block-leaf.png' }, { name: 'gray', url: 'images/block-gray.png' }, { name: 'sun', url: 'images/block-sun.png' }, { name: 'locked', url: 'images/block-locked.png' }, { name: 'orchid', url: 'images/block-orchid.png' }, { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 }, { name: 'gray', url: 'images/block-gray.png' }, { name: 'cell', url: 'images/cell.png' }, { name: 'locked', url: 'images/block-locked.png' }, { name: 'pixel', url: 'images/pixel.png' }, { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 }, // Keep the original Terra placeholders as aliases (Tim may still have them). { name: 'cell', url: 'images/cell.png' }, { name: 'ember', url: 'images/block-ember.png' }, { name: 'pixel', url: 'images/pixel.png' } { name: 'aqua', url: 'images/block-aqua.png' },]; { name: 'leaf', url: 'images/block-leaf.png' }, { name: 'sun', url: 'images/block-sun.png' },var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid']; { name: 'orchid', url: 'images/block-orchid.png' } ]; var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []); for (var i = 0; i < planets.length; i++) { var pl = planets[i]; for (var c = 0; c < pl.colors.length; c++) { list.push({ name: Planet.spriteKey(pl, c), url: pl.colors[c].image }); } } return list;}var IMAGES = planetImages();var GAME_OVER_DELAY = 2;var GAME_OVER_DELAY = 2;var game = new Game();var game = new Game();@@ -2863,7 +3164,9 @@ var app = { online: false, online: false, eliminatedReported: false, eliminatedReported: false, spectating: false, spectating: false, miniH: 0 miniH: 0, selectedPlanetId: 'terra', planetSelectContext: 'solo'};};window.onload = function ()window.onload = function ()@@ -2888,13 +3191,15 @@ window.onload = function () }); }); bindOnlineUi(); bindOnlineUi(); bindPlanetSelect(); restoreSelectedPlanet();};};function onPlay ()function onPlay (){{ if (app.mode === 'playing') if (app.mode === 'playing') { return; } { return; } startPlay(); openPlanetSelect('solo');}}function startPlay (opts)function startPlay (opts)@@ -2905,14 +3210,15 @@ function startPlay (opts) hideEl('online-panel'); hideEl('online-panel'); hideEl('spectator'); hideEl('spectator'); hideEl('podium'); hideEl('podium'); hideEl('planet-select'); showEl('hud'); showEl('hud'); app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet()); var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod; app.planet = opts.planet || planetMod.planetById(selectedPlanetId()); var miss = opts.missChance; var miss = opts.missChance; if (typeof miss === 'number' && isFinite(miss)) if (typeof miss !== 'number' || !isFinite(miss)) { app.core = new GameCore(app.planet, Math.random, miss); } { miss = planetMod.missChance(app.planet); } else app.core = new GameCore(app.planet, Math.random, miss); { app.core = new GameCore(app.planet, Math.random); } app.mode = 'playing'; app.mode = 'playing'; app.online = !!opts.online; app.online = !!opts.online; app.gameOverShown = false; app.gameOverShown = false;@@ -2981,6 +3287,7 @@ function returnToMenu () teardownPlay(); teardownPlay(); app.mode = 'menu'; app.mode = 'menu'; app.online = false; app.online = false; hideEl('planet-select'); showEl('menu'); showEl('menu'); var last = document.getElementById('last-score'); var last = document.getElementById('last-score'); if (app.lastScore > 0) if (app.lastScore > 0)@@ -3064,7 +3371,8 @@ function spriteFor (block) { return game.images.locked; } { return game.images.locked; } if (block.color < 0) if (block.color < 0) { return game.images.gray; } { return game.images.gray; } return game.images[COLOR_SPRITES[block.color]] || game.images.gray; var key = Planet.spriteKey(app.planet, block.color); return game.images[key] || game.images.gray;}}function syncSprites ()function syncSprites ()@@ -3223,10 +3531,7 @@ function refreshHud () document.getElementById('score').textContent = String(app.core.score); document.getElementById('score').textContent = String(app.core.score); var planet = app.planet; var planet = app.planet; document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people; document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people; var d = Planet.displayValues(planet); document.getElementById('planet-stats').textContent = Planet.formatStats(planet); document.getElementById('planet-stats').textContent = 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) + ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';}}function makeManager ()function makeManager ()@@ -3504,10 +3809,11 @@ function startOnlineMatch (){{ if (app.mode === 'playing' && app.online) if (app.mode === 'playing' && app.online) { return; } { return; } var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null) var planet = Planet.planetById(selectedPlanetId()); ? Online.lobby.miss_chance var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null; : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30); if (me && me.planet && me.planet.id) startPlay({ online: true, missChance: miss }); { planet = Planet.planetById(me.planet.id); } startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) }); if (typeof Online !== 'undefined') if (typeof Online !== 'undefined') { Online.startPolling(onlinePayload); } { Online.startPolling(onlinePayload); }}}@@ -3664,6 +3970,7 @@ function openOnlinePanel () hideEl('game-over'); hideEl('game-over'); hideEl('podium'); hideEl('podium'); hideEl('spectator'); hideEl('spectator'); hideEl('planet-select'); showEl('online-panel'); showEl('online-panel'); app.mode = 'online'; app.mode = 'online'; setOnlineStatus('Even kijken of online spelen beschikbaar is…'); setOnlineStatus('Even kijken of online spelen beschikbaar is…');@@ -3765,10 +4072,14 @@ function renderOnline () { li.classList.add('you'); } { li.classList.add('you'); } var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : ''); var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : ''); var state = p.ready ? 'Gereed' : 'Wacht…'; var state = p.ready ? 'Gereed' : 'Wacht…'; li.innerHTML = '<span>' + escapeText(label) + '</span><span class="' var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : ''; li.innerHTML = '<span>' + escapeText(label) + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '') + '</span><span class="' + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>'; + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>'; list.appendChild(li); list.appendChild(li); } } renderPlanetGrid('lobby-planet-grid', true); var me = Online.mePlayer(); var me = Online.mePlayer(); document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed'; document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed'; var start = document.getElementById('btn-start'); var start = document.getElementById('btn-start');@@ -3802,6 +4113,150 @@ function escapeText (s) .replace(/"/g, '"'); .replace(/"/g, '"');}}function selectedPlanetId (){ if (app.selectedPlanetId) { return app.selectedPlanetId; } return 'terra';}function restoreSelectedPlanet (){ var id = 'terra'; try { id = localStorage.getItem('meteors-planet') || 'terra'; } catch (e) {} setSelectedPlanet(id, true);}function setSelectedPlanet (id, silent){ var all = Planet.allPlanets(); var found = null; for (var i = 0; i < all.length; i++) { if (all[i].id === id) { found = all[i]; break; } } if (!found) { found = Planet.defaultPlanet(); } app.selectedPlanetId = found.id; try { localStorage.setItem('meteors-planet', found.id); } catch (e) {} if (!silent) { var grid = document.getElementById('planet-grid'); if (grid && !grid.hidden && grid.children.length) { renderPlanetGrid('planet-grid', false); } var lobby = document.getElementById('lobby-planet-grid'); if (lobby && lobby.children.length) { renderPlanetGrid('lobby-planet-grid', true); } } return found;}function openPlanetSelect (context){ if (app.mode === 'playing') { return; } app.planetSelectContext = context || 'solo'; app.mode = 'planet-select'; hideEl('menu'); hideEl('online-panel'); hideEl('game-over'); showEl('planet-select'); renderPlanetGrid('planet-grid', false); var go = document.getElementById('btn-planet-go'); if (go) { go.textContent = 'Spelen'; }}function renderPlanetGrid (containerId, compact){ var grid = document.getElementById(containerId); if (!grid) { return; } var current = selectedPlanetId(); var all = Planet.allPlanets(); grid.innerHTML = ''; if (compact) { grid.classList.add('compact'); } for (var i = 0; i < all.length; i++) { var pl = all[i]; var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'planet-card' + (pl.id === current ? ' selected' : ''); btn.setAttribute('role', 'listitem'); btn.dataset.planet = pl.id; var swatches = ''; for (var c = 0; c < pl.colors.length; c++) { swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="' + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.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>'; btn.addEventListener('click', (function (id, isCompact) { return function () { onPlanetPicked(id, isCompact); }; })(pl.id, !!compact)); grid.appendChild(btn); }}function onPlanetPicked (id, fromLobby){ setSelectedPlanet(id); if (fromLobby && typeof Online !== 'undefined' && Online.lobby) { Online.setPlanet(id).then(function () { renderOnline(); }); } else { renderPlanetGrid('planet-grid', false); }}function confirmPlanetSelect (){ var planet = setSelectedPlanet(selectedPlanetId()); hideEl('planet-select'); if (app.planetSelectContext === 'online') { openOnlinePanel(); return; } startPlay({ planet: planet });}function cancelPlanetSelect (){ hideEl('planet-select'); app.mode = 'menu'; showEl('menu');}function bindPlanetSelect (){ var go = document.getElementById('btn-planet-go'); var back = document.getElementById('btn-planet-back'); if (go) { go.addEventListener('click', confirmPlanetSelect); } if (back) { back.addEventListener('click', cancelPlanetSelect); }}/*/* * End File: * 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.
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.
@@ -23,6 +23,16 @@
<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>
<div id="planet-select" class="screen" hidden>
<h1>Kies een veld</h1>
<p class="tagline">Elk veld is een planeet, met een eigen volk, zwaartekracht, lucht en massa.</p>
<div id="planet-grid" class="planet-grid" role="list"></div>
<div class="planet-actions">
<button type="button" id="btn-planet-go">Spelen</button>
<button type="button" id="btn-planet-back" class="btn-secondary">Terug</button>
</div>
</div>
<div id="online-panel" class="screen" hidden>
<h1>Online</h1>
<p id="online-status" class="tagline">Even kijken of online spelen beschikbaar is…</p>
@@ -61,6 +71,8 @@
<div id="online-lobby" hidden>
<p class="who">Ingelogd als <strong id="lobby-me-name"></strong></p>
<p class="lobby-code">Code: <strong id="lobby-code"></strong> <button type="button" id="btn-copy-code" class="btn-tiny">Kopieer</button></p>
<p class="hint lobby-planet-label">Jouw veld</p>
<div id="lobby-planet-grid" class="planet-grid compact" role="list"></div>
<ul id="lobby-players" class="player-list"></ul>
<p id="lobby-hint" class="hint"></p>
<div class="lobby-actions">
@@ -23,6 +23,16 @@ <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> </div> <div id="planet-select" class="screen" hidden> <h1>Kies een veld</h1> <p class="tagline">Elk veld is een planeet, met een eigen volk, zwaartekracht, lucht en massa.</p> <div id="planet-grid" class="planet-grid" role="list"></div> <div class="planet-actions"> <button type="button" id="btn-planet-go">Spelen</button> <button type="button" id="btn-planet-back" class="btn-secondary">Terug</button> </div> </div> <div id="online-panel" class="screen" hidden> <div id="online-panel" class="screen" hidden> <h1>Online</h1> <h1>Online</h1> <p id="online-status" class="tagline">Even kijken of online spelen beschikbaar is…</p> <p id="online-status" class="tagline">Even kijken of online spelen beschikbaar is…</p>@@ -61,6 +71,8 @@ <div id="online-lobby" hidden> <div id="online-lobby" hidden> <p class="who">Ingelogd als <strong id="lobby-me-name"></strong></p> <p class="who">Ingelogd als <strong id="lobby-me-name"></strong></p> <p class="lobby-code">Code: <strong id="lobby-code"></strong> <button type="button" id="btn-copy-code" class="btn-tiny">Kopieer</button></p> <p class="lobby-code">Code: <strong id="lobby-code"></strong> <button type="button" id="btn-copy-code" class="btn-tiny">Kopieer</button></p> <p class="hint lobby-planet-label">Jouw veld</p> <div id="lobby-planet-grid" class="planet-grid compact" role="list"></div> <ul id="lobby-players" class="player-list"></ul> <ul id="lobby-players" class="player-list"></ul> <p id="lobby-hint" class="hint"></p> <p id="lobby-hint" class="hint"></p> <div class="lobby-actions"> <div class="lobby-actions">@@ -45,7 +45,7 @@ html, body {
text-align: center;
}
.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden] { display: none !important; }
.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #planet-select[hidden] { display: none !important; }
h1 {
font-size: clamp(48px, 14vw, 96px);
@@ -66,7 +66,7 @@ h1 {
max-width: 28em;
}
#btn-play {
#btn-play, #btn-planet-go {
appearance: none;
border: 0;
cursor: pointer;
@@ -87,14 +87,14 @@ h1 {
min-width: 200px;
}
#btn-play:is(:hover, :focus-visible) {
#btn-play:is(:hover, :focus-visible), #btn-planet-go:is(:hover, :focus-visible) {
transform: translateY(-1px);
box-shadow:
0 0 0 3px rgba(255, 220, 120, 0.4),
0 10px 28px rgba(240, 197, 58, 0.6);
}
#btn-play:active { transform: translateY(1px); }
#btn-play:active, #btn-planet-go:active { transform: translateY(1px); }
.last-score {
margin: 22px 0 0;
@@ -181,7 +181,7 @@ canvas {
@media (max-height: 520px) {
.hint { display: none; }
h1 { font-size: 42px; }
#btn-play { padding: 10px 36px; }
#btn-play, #btn-planet-go { padding: 10px 36px; }
}
@@ -207,7 +207,7 @@ a.button:is(:hover, :focus-visible) {
color: #fff6c8;
}
#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
#btn-play {
#btn-play, #btn-planet-go {
/* play already styled */
}
@@ -227,16 +227,21 @@ a.button:is(:hover, :focus-visible) {
cursor: default;
}
#online-panel h1 {
font-size: clamp(36px, 9vw, 64px);
}
#online-panel {
z-index: 5;
overflow: auto;
text-align: center;
padding: 32px 16px 48px;
padding: 16px 16px 24px;
}
#online-panel .who {
color: #c5cae0;
margin: 0 0 16px;
margin: 0 0 8px;
}
#online-lobby .tagline { margin-bottom: 8px; }
#online-lobby .lobby-code { margin: 4px 0 6px; }
#online-panel .notice {
max-width: 36em;
margin: 0 auto 16px;
@@ -408,3 +413,129 @@ a.button:is(:hover, :focus-visible) {
#online-panel .hint, #online-panel .tagline { display: block; }
.mini-canvas { width: 56px; height: 73px; }
}
/* Stage 3: planet (field) selection */
#planet-select {
justify-content: flex-start;
overflow-y: auto;
touch-action: pan-y;
-webkit-overflow-scrolling: touch;
padding-top: 20px;
padding-bottom: 32px;
}
#planet-select h1 {
font-size: clamp(32px, 9vw, 64px);
margin-bottom: 4px;
}
#planet-select .tagline { margin-bottom: 16px; }
.planet-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
gap: 12px;
width: min(1000px, 100%);
margin: 0 auto 16px;
text-align: left;
touch-action: pan-y;
}
.planet-card {
appearance: none;
display: block;
width: 100%;
margin: 0;
padding: 12px 14px 10px;
border: 1px solid rgba(200, 210, 240, 0.16);
border-radius: 14px;
background: rgba(16, 20, 40, 0.72);
color: inherit;
font: inherit;
text-align: left;
cursor: pointer;
touch-action: manipulation;
transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
}
.planet-card:hover, .planet-card:focus-visible {
border-color: rgba(255, 226, 122, 0.55);
outline: none;
}
.planet-card.selected {
border-color: #ffe27a;
box-shadow: 0 0 0 2px rgba(255, 226, 122, 0.35), 0 8px 24px rgba(0,0,0,0.35);
background: rgba(40, 32, 16, 0.78);
}
.planet-card .planet-title {
font-size: 1.15rem;
font-weight: 700;
letter-spacing: 0.03em;
color: #fff6c8;
}
.planet-card .planet-people {
font-size: 0.85rem;
color: #8e95b3;
margin: 0 0 6px;
}
.planet-card .planet-nums {
font-variant-numeric: tabular-nums;
font-size: 0.78rem;
color: #c5cae0;
letter-spacing: 0.01em;
line-height: 1.35;
margin: 0 0 8px;
}
.planet-card .planet-swatches {
display: flex;
gap: 6px;
align-items: center;
}
.planet-card .planet-swatches img {
width: 26px;
height: 26px;
image-rendering: auto;
flex: 0 0 auto;
}
.planet-actions {
display: flex;
gap: 12px;
flex-wrap: wrap;
justify-content: center;
margin-top: 8px;
flex-shrink: 0;
}
.planet-grid.compact {
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
width: min(920px, 92vw);
min-width: min(920px, 92vw);
max-height: none;
overflow: visible;
touch-action: pan-y;
margin-bottom: 10px;
align-self: center;
}
@media (max-width: 720px) {
.planet-grid.compact {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
.planet-grid.compact .planet-card { padding: 6px 8px; }
.planet-grid.compact .planet-title { font-size: 1rem; }
.planet-grid.compact .planet-nums { font-size: 0.7rem; margin-bottom: 6px; }
.planet-grid.compact .planet-swatches img { width: 20px; height: 20px; }
.lobby-planet-label { margin: 8px 0 6px; }
.player-list .planet-tag {
display: block;
font-size: 0.78rem;
font-weight: 500;
color: #9aa3c4;
}
#online-lobby {
overflow-y: auto;
touch-action: pan-y;
-webkit-overflow-scrolling: touch;
justify-content: flex-start;
padding-top: 8px;
}
@media (max-width: 520px) {
.planet-grid { grid-template-columns: 1fr 1fr; gap: 8px; }
.planet-card .planet-nums { font-size: 0.68rem; }
.planet-card { padding: 10px 8px 8px; }
}
@@ -45,7 +45,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] { display: none !important; }.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #planet-select[hidden] { display: none !important; }h1 {h1 { font-size: clamp(48px, 14vw, 96px); font-size: clamp(48px, 14vw, 96px);@@ -66,7 +66,7 @@ h1 { max-width: 28em; max-width: 28em;}}#btn-play {#btn-play, #btn-planet-go { appearance: none; appearance: none; border: 0; border: 0; cursor: pointer; cursor: pointer;@@ -87,14 +87,14 @@ h1 { min-width: 200px; min-width: 200px;}}#btn-play:is(:hover, :focus-visible) {#btn-play:is(:hover, :focus-visible), #btn-planet-go:is(:hover, :focus-visible) { transform: translateY(-1px); transform: translateY(-1px); box-shadow: box-shadow: 0 0 0 3px rgba(255, 220, 120, 0.4), 0 0 0 3px rgba(255, 220, 120, 0.4), 0 10px 28px rgba(240, 197, 58, 0.6); 0 10px 28px rgba(240, 197, 58, 0.6);}}#btn-play:active { transform: translateY(1px); }#btn-play:active, #btn-planet-go:active { transform: translateY(1px); }.last-score {.last-score { margin: 22px 0 0; margin: 22px 0 0;@@ -181,7 +181,7 @@ canvas {@media (max-height: 520px) {@media (max-height: 520px) { .hint { display: none; } .hint { display: none; } h1 { font-size: 42px; } h1 { font-size: 42px; } #btn-play { padding: 10px 36px; } #btn-play, #btn-planet-go { padding: 10px 36px; }}}@@ -207,7 +207,7 @@ 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-play, #btn-planet-go { /* play already styled */ /* play already styled */}}@@ -227,16 +227,21 @@ a.button:is(:hover, :focus-visible) { cursor: default; cursor: default;}}#online-panel h1 { font-size: clamp(36px, 9vw, 64px);}#online-panel {#online-panel { z-index: 5; z-index: 5; overflow: auto; overflow: auto; text-align: center; text-align: center; padding: 32px 16px 48px; padding: 16px 16px 24px;}}#online-panel .who {#online-panel .who { color: #c5cae0; color: #c5cae0; margin: 0 0 16px; margin: 0 0 8px;}}#online-lobby .tagline { margin-bottom: 8px; }#online-lobby .lobby-code { margin: 4px 0 6px; }#online-panel .notice {#online-panel .notice { max-width: 36em; max-width: 36em; margin: 0 auto 16px; margin: 0 auto 16px;@@ -408,3 +413,129 @@ a.button:is(:hover, :focus-visible) { #online-panel .hint, #online-panel .tagline { display: block; } #online-panel .hint, #online-panel .tagline { display: block; } .mini-canvas { width: 56px; height: 73px; } .mini-canvas { width: 56px; height: 73px; }}}/* Stage 3: planet (field) selection */#planet-select { justify-content: flex-start; overflow-y: auto; touch-action: pan-y; -webkit-overflow-scrolling: touch; padding-top: 20px; padding-bottom: 32px;}#planet-select h1 { font-size: clamp(32px, 9vw, 64px); margin-bottom: 4px;}#planet-select .tagline { margin-bottom: 16px; }.planet-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(230px, 1fr)); gap: 12px; width: min(1000px, 100%); margin: 0 auto 16px; text-align: left; touch-action: pan-y;}.planet-card { appearance: none; display: block; width: 100%; margin: 0; padding: 12px 14px 10px; border: 1px solid rgba(200, 210, 240, 0.16); border-radius: 14px; background: rgba(16, 20, 40, 0.72); color: inherit; font: inherit; text-align: left; cursor: pointer; touch-action: manipulation; transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;}.planet-card:hover, .planet-card:focus-visible { border-color: rgba(255, 226, 122, 0.55); outline: none;}.planet-card.selected { border-color: #ffe27a; box-shadow: 0 0 0 2px rgba(255, 226, 122, 0.35), 0 8px 24px rgba(0,0,0,0.35); background: rgba(40, 32, 16, 0.78);}.planet-card .planet-title { font-size: 1.15rem; font-weight: 700; letter-spacing: 0.03em; color: #fff6c8;}.planet-card .planet-people { font-size: 0.85rem; color: #8e95b3; margin: 0 0 6px;}.planet-card .planet-nums { font-variant-numeric: tabular-nums; font-size: 0.78rem; color: #c5cae0; letter-spacing: 0.01em; line-height: 1.35; margin: 0 0 8px;}.planet-card .planet-swatches { display: flex; gap: 6px; align-items: center;}.planet-card .planet-swatches img { width: 26px; height: 26px; image-rendering: auto; flex: 0 0 auto;}.planet-actions { display: flex; gap: 12px; flex-wrap: wrap; justify-content: center; margin-top: 8px; flex-shrink: 0;}.planet-grid.compact { grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; width: min(920px, 92vw); min-width: min(920px, 92vw); max-height: none; overflow: visible; touch-action: pan-y; margin-bottom: 10px; align-self: center;}@media (max-width: 720px) { .planet-grid.compact { grid-template-columns: repeat(2, minmax(0, 1fr)); }}.planet-grid.compact .planet-card { padding: 6px 8px; }.planet-grid.compact .planet-title { font-size: 1rem; }.planet-grid.compact .planet-nums { font-size: 0.7rem; margin-bottom: 6px; }.planet-grid.compact .planet-swatches img { width: 20px; height: 20px; }.lobby-planet-label { margin: 8px 0 6px; }.player-list .planet-tag { display: block; font-size: 0.78rem; font-weight: 500; color: #9aa3c4;}#online-lobby { overflow-y: auto; touch-action: pan-y; -webkit-overflow-scrolling: touch; justify-content: flex-start; padding-top: 8px;}@media (max-width: 520px) { .planet-grid { grid-template-columns: 1fr 1fr; gap: 8px; } .planet-card .planet-nums { font-size: 0.68rem; } .planet-card { padding: 10px 8px 8px; }}@@ -117,9 +117,9 @@ Het blok blijft op 80% zolang het geselecteerd is, en veert bij loslaten
terug (ook als het ondertussen gelanceerd wordt). Muis en touch gebruiken
dezelfde tween.
## Fase 2 — multiplayer (volgt)
## Fase 2 — multiplayer (samenvatting)
Zie latere secties zodra fase 2 landt. De miss-kans van 30% wordt een
De miss-kans van 30% was de stage-2-parameter; stage 3 vervangt die door
parameter (`missChance`, standaard 0,30); de planeetformule
`Planet.missChance` (60%–5% via Power) is voor fase 3.
@@ -248,3 +248,32 @@ Aanname:
FTP); Tim zet het op het meteors-project. Optioneel: `auth_client_id`
(standaard `projects.timfalken.com`). `favicon.ico` blijft ongemoeid.
`router.php` is alleen voor lokale `php -S` en gaat niet mee naar live.
## Fase 3 — planeten (velden)
- Een veld is een planeet, met een naam voor de planeet en voor het volk.
De catalogus staat in `server/lib/planets.json` (bron voor JS én PHP) en
telt **12** werelden, van makkelijk (Aurel: Power 0 %, 60 % miss) tot
moeilijk (Cinder: Power 100 %, 5 % miss). Terra blijft de standaard.
- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt `1/jumpsToClear` van
de veldhoogte. Luchtweerstand (`fallTime` 1–5 s tot de bodem). Massa
(`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en
hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al
met `fallTime` (gebouwd in stage 1).
- Power is het gemiddelde van die drie assen, genormaliseerd 0–1, getoond
als percentage. Miss-kans = `0,60 − 0,55 × Power` (60 % bij Power 0,
5 % bij Power 1). In multiplayer gebruikt de **server** de Power van
**jouw** planeet voor de blokjes die jij afschiet (niet de lobby-waarde,
niet de planeet van het doel). De client kan dat niet vervalsen.
- De vier getallen op de kiezers en in de HUD: `g` als
zwaartekrachtsconstante (m/s²), `d` als luchtdichtheid, `F` in newton,
Power als percentage. Alleen de getallen, zonder uitleg. Verticale match
van 3 = 120 % sprong, +5 % per extra blokje (al gebouwd, nergens uitgelegd).
- Elk veld heeft een eigen set van 5 kleuren, elk met een uniek vormpje
en een uniek placeholder-PNG (`build/images/block-{planeet}-{kleur}.png`).
Tim kan die bestanden zelf vervangen; de namen blijven gelijk. Te
(her)genereren met `python3 scripts/gen_planet_blocks.py`.
- Planeetkeuze komt vóór solo-spel (`Spelen` opent de kiezer) en in de
lobby (iedereen kiest zelf; zichtbaar voor de anderen). De keuze wordt
onthouden in `localStorage` (`meteors-planet`). Na de start van een
wedstrijd kun je niet meer wisselen.
@@ -117,9 +117,9 @@ Het blok blijft op 80% zolang het geselecteerd is, en veert bij loslatenterug (ook als het ondertussen gelanceerd wordt). Muis en touch gebruikenterug (ook als het ondertussen gelanceerd wordt). Muis en touch gebruikendezelfde tween.dezelfde tween.## Fase 2 — multiplayer (volgt)## Fase 2 — multiplayer (samenvatting)Zie latere secties zodra fase 2 landt. De miss-kans van 30% wordt eenDe miss-kans van 30% was de stage-2-parameter; stage 3 vervangt die doorparameter (`missChance`, standaard 0,30); de planeetformuleparameter (`missChance`, standaard 0,30); de planeetformule`Planet.missChance` (60%–5% via Power) is voor fase 3.`Planet.missChance` (60%–5% via Power) is voor fase 3.@@ -248,3 +248,32 @@ Aanname: FTP); Tim zet het op het meteors-project. Optioneel: `auth_client_id` FTP); Tim zet het op het meteors-project. Optioneel: `auth_client_id` (standaard `projects.timfalken.com`). `favicon.ico` blijft ongemoeid. (standaard `projects.timfalken.com`). `favicon.ico` blijft ongemoeid. `router.php` is alleen voor lokale `php -S` en gaat niet mee naar live. `router.php` is alleen voor lokale `php -S` en gaat niet mee naar live.## Fase 3 — planeten (velden)- Een veld is een planeet, met een naam voor de planeet en voor het volk. De catalogus staat in `server/lib/planets.json` (bron voor JS én PHP) en telt **12** werelden, van makkelijk (Aurel: Power 0 %, 60 % miss) tot moeilijk (Cinder: Power 100 %, 5 % miss). Terra blijft de standaard.- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt `1/jumpsToClear` van de veldhoogte. Luchtweerstand (`fallTime` 1–5 s tot de bodem). Massa (`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al met `fallTime` (gebouwd in stage 1).- Power is het gemiddelde van die drie assen, genormaliseerd 0–1, getoond als percentage. Miss-kans = `0,60 − 0,55 × Power` (60 % bij Power 0, 5 % bij Power 1). In multiplayer gebruikt de **server** de Power van **jouw** planeet voor de blokjes die jij afschiet (niet de lobby-waarde, niet de planeet van het doel). De client kan dat niet vervalsen.- De vier getallen op de kiezers en in de HUD: `g` als zwaartekrachtsconstante (m/s²), `d` als luchtdichtheid, `F` in newton, Power als percentage. Alleen de getallen, zonder uitleg. Verticale match van 3 = 120 % sprong, +5 % per extra blokje (al gebouwd, nergens uitgelegd).- Elk veld heeft een eigen set van 5 kleuren, elk met een uniek vormpje en een uniek placeholder-PNG (`build/images/block-{planeet}-{kleur}.png`). Tim kan die bestanden zelf vervangen; de namen blijven gelijk. Te (her)genereren met `python3 scripts/gen_planet_blocks.py`.- Planeetkeuze komt vóór solo-spel (`Spelen` opent de kiezer) en in de lobby (iedereen kiest zelf; zichtbaar voor de anderen). De keuze wordt onthouden in `localStorage` (`meteors-planet`). Na de start van een wedstrijd kun je niet meer wisselen.@@ -0,0 +1,175 @@
#!/usr/bin/env python3
"""Unique placeholder block images for each planet color.
Tim can replace any of these PNGs in build/images/. Filenames stay stable.
Run from the repo root: python3 scripts/gen_planet_blocks.py
"""
from __future__ import annotations
import json
import math
from pathlib import Path
from PIL import Image, ImageDraw, ImageFilter, ImageChops
ROOT = Path(__file__).resolve().parents[1]
CATALOG = ROOT / 'server' / 'lib' / 'planets.json'
OUT = ROOT / 'build' / 'images'
SIZE = 64
SCALE = 4 # supersample
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
def draw_shape(draw, shape, cx, cy, r, fill, outline, width):
shape = shape.lower()
if shape == 'circle':
box = [cx - r, cy - r, cx + r, cy + r]
draw.ellipse(box, fill=fill, outline=outline, width=width)
elif shape == 'square':
s = r * 0.86
box = [cx - s, cy - s, cx + s, cy + s]
draw.rounded_rectangle(box, radius=r * 0.12, fill=fill, outline=outline, width=width)
elif shape == 'triangle':
pts = regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2)
draw.polygon(pts, fill=fill, outline=outline, width=width)
elif shape == 'diamond':
pts = regular_poly(cx, cy, r * 1.05, 4, 0)
draw.polygon(pts, fill=fill, outline=outline, width=width)
elif shape == 'star':
draw.polygon(star_pts(cx, cy, r * 1.12), fill=fill, outline=outline, width=width)
elif shape == 'hexagon':
draw.polygon(regular_poly(cx, cy, r * 1.05, 6, 0), fill=fill, outline=outline, width=width)
elif shape == 'pentagon':
draw.polygon(regular_poly(cx, cy, r * 1.08, 5), fill=fill, outline=outline, width=width)
elif shape == 'teardrop':
# circle + top point
pts = []
for i in range(24):
a = math.pi * 0.22 + i * (2 * math.pi * 0.78) / 23
pts.append((cx + r * 0.85 * math.cos(a), cy + r * 0.25 + r * 0.85 * math.sin(a)))
pts.insert(0, (cx, cy - r * 1.1))
draw.polygon(pts, fill=fill, outline=outline, width=width)
elif shape == 'crescent':
# Draw a moon by punching a circle out of another.
# ImageDraw can't punch; caller uses a mask. Fallback: thick arc-like poly.
outer = []
inner = []
for i in range(22):
a = -math.pi * 0.7 + i * (1.4 * math.pi) / 21
outer.append((cx + r * math.cos(a) - r * 0.08, cy + r * math.sin(a)))
ox, oy = cx + r * 0.42, cy - r * 0.05
for i in range(18, -1, -1):
a = -math.pi * 0.65 + i * (1.3 * math.pi) / 18
inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a)))
draw.polygon(outer + inner, fill=fill, outline=outline, width=width)
elif shape == 'plus':
t = r * 0.38
pts = [
(cx - t, cy - r), (cx + t, cy - r), (cx + t, cy - t),
(cx + r, cy - t), (cx + r, cy + t), (cx + t, cy + t),
(cx + t, cy + r), (cx - t, cy + r), (cx - t, cy + t),
(cx - r, cy + t), (cx - r, cy - t), (cx - t, cy - t),
]
draw.polygon(pts, fill=fill, outline=outline, width=width)
elif shape == 'gem':
pts = [
(cx, cy - r), (cx + r * 0.72, cy - r * 0.15),
(cx + r * 0.5, cy + r * 0.95), (cx - r * 0.5, cy + r * 0.95),
(cx - r * 0.72, cy - r * 0.15),
]
draw.polygon(pts, fill=fill, outline=outline, width=width)
elif shape == 'arrow':
pts = [
(cx, cy - r * 1.1), (cx + r * 0.85, cy + r * 0.05),
(cx + r * 0.28, cy + r * 0.05), (cx + r * 0.28, cy + r),
(cx - r * 0.28, cy + r), (cx - r * 0.28, cy + r * 0.05),
(cx - r * 0.85, cy + r * 0.05),
]
draw.polygon(pts, fill=fill, outline=outline, width=width)
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))
draw = ImageDraw.Draw(img)
cx = cy = SS / 2
r = SS * 0.36
# drop shadow
shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
sd = ImageDraw.Draw(shadow)
draw_shape(sd, 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)
draw = ImageDraw.Draw(img)
# body
draw_shape(draw, shape, cx, cy, r, rgb + (255,), lo + (255,), max(2, SCALE))
# highlight (smaller, offset, semi)
hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
hd = ImageDraw.Draw(hi_layer)
draw_shape(hd, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55, hi + (110,), None, 0)
# clip highlight to the body roughly by multiplying alpha later is hard;
# a soft blob is fine for a placeholder.
hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6))
img = Image.alpha_composite(img, hi_layer)
out = img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)
return out
def main():
data = json.loads(CATALOG.read_text())
OUT.mkdir(parents=True, exist_ok=True)
written = []
seen = set()
for planet in data['planets']:
shapes = [c['shape'] for c in planet['colors']]
if len(set(shapes)) != 5:
raise SystemExit(f'{planet["id"]} does not have 5 unique shapes')
for color in planet['colors']:
path = ROOT / 'build' / color['image']
if path.name in seen:
raise SystemExit(f'duplicate filename {path}')
seen.add(path.name)
img = render_block(color['hex'], color['shape'])
img.save(path, 'PNG', optimize=True)
written.append(path.relative_to(ROOT))
print(f'wrote {len(written)} placeholders to {OUT}')
for p in written:
print(' ', p)
if __name__ == '__main__':
main()
@@ -0,0 +1,175 @@#!/usr/bin/env python3"""Unique placeholder block images for each planet color.Tim can replace any of these PNGs in build/images/. Filenames stay stable.Run from the repo root: python3 scripts/gen_planet_blocks.py"""from __future__ import annotationsimport jsonimport mathfrom pathlib import Pathfrom PIL import Image, ImageDraw, ImageFilter, ImageChopsROOT = Path(__file__).resolve().parents[1]CATALOG = ROOT / 'server' / 'lib' / 'planets.json'OUT = ROOT / 'build' / 'images'SIZE = 64SCALE = 4 # supersampleSS = 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 ptsdef draw_shape(draw, shape, cx, cy, r, fill, outline, width): shape = shape.lower() if shape == 'circle': box = [cx - r, cy - r, cx + r, cy + r] draw.ellipse(box, fill=fill, outline=outline, width=width) elif shape == 'square': s = r * 0.86 box = [cx - s, cy - s, cx + s, cy + s] draw.rounded_rectangle(box, radius=r * 0.12, fill=fill, outline=outline, width=width) elif shape == 'triangle': pts = regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2) draw.polygon(pts, fill=fill, outline=outline, width=width) elif shape == 'diamond': pts = regular_poly(cx, cy, r * 1.05, 4, 0) draw.polygon(pts, fill=fill, outline=outline, width=width) elif shape == 'star': draw.polygon(star_pts(cx, cy, r * 1.12), fill=fill, outline=outline, width=width) elif shape == 'hexagon': draw.polygon(regular_poly(cx, cy, r * 1.05, 6, 0), fill=fill, outline=outline, width=width) elif shape == 'pentagon': draw.polygon(regular_poly(cx, cy, r * 1.08, 5), fill=fill, outline=outline, width=width) elif shape == 'teardrop': # circle + top point pts = [] for i in range(24): a = math.pi * 0.22 + i * (2 * math.pi * 0.78) / 23 pts.append((cx + r * 0.85 * math.cos(a), cy + r * 0.25 + r * 0.85 * math.sin(a))) pts.insert(0, (cx, cy - r * 1.1)) draw.polygon(pts, fill=fill, outline=outline, width=width) elif shape == 'crescent': # Draw a moon by punching a circle out of another. # ImageDraw can't punch; caller uses a mask. Fallback: thick arc-like poly. outer = [] inner = [] for i in range(22): a = -math.pi * 0.7 + i * (1.4 * math.pi) / 21 outer.append((cx + r * math.cos(a) - r * 0.08, cy + r * math.sin(a))) ox, oy = cx + r * 0.42, cy - r * 0.05 for i in range(18, -1, -1): a = -math.pi * 0.65 + i * (1.3 * math.pi) / 18 inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a))) draw.polygon(outer + inner, fill=fill, outline=outline, width=width) elif shape == 'plus': t = r * 0.38 pts = [ (cx - t, cy - r), (cx + t, cy - r), (cx + t, cy - t), (cx + r, cy - t), (cx + r, cy + t), (cx + t, cy + t), (cx + t, cy + r), (cx - t, cy + r), (cx - t, cy + t), (cx - r, cy + t), (cx - r, cy - t), (cx - t, cy - t), ] draw.polygon(pts, fill=fill, outline=outline, width=width) elif shape == 'gem': pts = [ (cx, cy - r), (cx + r * 0.72, cy - r * 0.15), (cx + r * 0.5, cy + r * 0.95), (cx - r * 0.5, cy + r * 0.95), (cx - r * 0.72, cy - r * 0.15), ] draw.polygon(pts, fill=fill, outline=outline, width=width) elif shape == 'arrow': pts = [ (cx, cy - r * 1.1), (cx + r * 0.85, cy + r * 0.05), (cx + r * 0.28, cy + r * 0.05), (cx + r * 0.28, cy + r), (cx - r * 0.28, cy + r), (cx - r * 0.28, cy + r * 0.05), (cx - r * 0.85, cy + r * 0.05), ] draw.polygon(pts, fill=fill, outline=outline, width=width) 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)) draw = ImageDraw.Draw(img) cx = cy = SS / 2 r = SS * 0.36 # drop shadow shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0)) sd = ImageDraw.Draw(shadow) draw_shape(sd, 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) draw = ImageDraw.Draw(img) # body draw_shape(draw, shape, cx, cy, r, rgb + (255,), lo + (255,), max(2, SCALE)) # highlight (smaller, offset, semi) hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0)) hd = ImageDraw.Draw(hi_layer) draw_shape(hd, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55, hi + (110,), None, 0) # clip highlight to the body roughly by multiplying alpha later is hard; # a soft blob is fine for a placeholder. hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6)) img = Image.alpha_composite(img, hi_layer) out = img.resize((SIZE, SIZE), Image.Resampling.LANCZOS) return outdef main(): data = json.loads(CATALOG.read_text()) OUT.mkdir(parents=True, exist_ok=True) written = [] seen = set() for planet in data['planets']: shapes = [c['shape'] for c in planet['colors']] if len(set(shapes)) != 5: raise SystemExit(f'{planet["id"]} does not have 5 unique shapes') for color in planet['colors']: path = ROOT / 'build' / color['image'] if path.name in seen: raise SystemExit(f'duplicate filename {path}') seen.add(path.name) img = render_block(color['hex'], color['shape']) img.save(path, 'PNG', optimize=True) written.append(path.relative_to(ROOT)) print(f'wrote {len(written)} placeholders to {OUT}') for p in written: print(' ', p)if __name__ == '__main__': main()@@ -62,12 +62,19 @@ try {
switch ($action) {
case 'lobby_create':
$miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;
$lobby = $store->createLobby($userId, $name, $miss);
$planet = (string) ($body['planet_id'] ?? '');
$lobby = $store->createLobby($userId, $name, $miss, $planet);
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
case 'lobby_join':
$code = (string) ($body['code'] ?? '');
$lobby = $store->joinLobby($userId, $name, $code);
$planet = (string) ($body['planet_id'] ?? '');
$lobby = $store->joinLobby($userId, $name, $code, $planet);
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
case 'lobby_set_planet':
$planet = (string) ($body['planet_id'] ?? '');
$lobby = $store->setPlanet($userId, $planet);
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
case 'lobby_leave':
@@ -62,12 +62,19 @@ try { switch ($action) { switch ($action) { case 'lobby_create': case 'lobby_create': $miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS; $miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS; $lobby = $store->createLobby($userId, $name, $miss); $planet = (string) ($body['planet_id'] ?? ''); $lobby = $store->createLobby($userId, $name, $miss, $planet); jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]); jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]); case 'lobby_join': case 'lobby_join': $code = (string) ($body['code'] ?? ''); $code = (string) ($body['code'] ?? ''); $lobby = $store->joinLobby($userId, $name, $code); $planet = (string) ($body['planet_id'] ?? ''); $lobby = $store->joinLobby($userId, $name, $code, $planet); jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]); case 'lobby_set_planet': $planet = (string) ($body['planet_id'] ?? ''); $lobby = $store->setPlanet($userId, $planet); jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]); jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]); case 'lobby_leave': case 'lobby_leave':@@ -0,0 +1,147 @@
<?php
declare(strict_types=1);
/**
* Planet catalog shared with the JS client (server/lib/planets.json).
* Power and miss-chance formulas must stay in lockstep with src/planet.js.
*/
final class Planets
{
private static ?array $all = null;
public static function path(): string
{
return __DIR__ . '/planets.json';
}
/** @return list<array> raw catalog entries */
public static function all(): array
{
if (self::$all !== null) {
return self::$all;
}
$raw = file_get_contents(self::path());
if ($raw === false) {
throw new RuntimeException('planets.json ontbreekt.');
}
$data = json_decode($raw, true);
if (!is_array($data) || !isset($data['planets']) || !is_array($data['planets'])) {
throw new RuntimeException('planets.json is ongeldig.');
}
self::$all = [];
foreach ($data['planets'] as $row) {
if (!is_array($row) || empty($row['id'])) {
continue;
}
self::$all[] = $row;
}
return self::$all;
}
public static function byId(string $id): ?array
{
foreach (self::all() as $p) {
if (($p['id'] ?? '') === $id) {
return $p;
}
}
return null;
}
public static function defaultId(): string
{
return 'terra';
}
public static function default(): array
{
return self::byId(self::defaultId()) ?? self::all()[0];
}
public static function known(string $id): bool
{
return self::byId($id) !== null;
}
/** Difficulty in 0..1. Higher is harder. */
public static function power(array $planet): float
{
$j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);
$f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
$r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
$gravity = ($j - 1) / 3;
$air = (5 - $f) / 4;
$mass = (3 - $r) / 2.5;
return ($gravity + $air + $mass) / 3;
}
/** Miss chance: 0.60 at power 0, 0.05 at power 1. */
public static function missChance(array $planet): float
{
return 0.60 - 0.55 * self::power($planet);
}
public static function missChanceForId(string $id): float
{
$p = self::byId($id);
if ($p === null) {
$p = self::default();
}
return self::missChance($p);
}
/** @return array{gravity:float,density:float,newtons:float,power:int,missChance:float} */
public static function displayValues(array $planet): array
{
$j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);
$f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
$r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
$power = self::power($planet);
return [
'gravity' => 9.81 * $j / 2,
'density' => 0.25 + ((5 - $f) / 4) * 1.60,
'newtons' => 40 + (($r - 0.5) / 2.5) * 160,
'power' => (int) round($power * 100),
'missChance' => 0.60 - 0.55 * $power,
];
}
/** Public subset sent to clients (no need to ship the full catalog again). */
public static function present(?string $id): array
{
$p = $id ? self::byId($id) : null;
if ($p === null) {
$p = self::default();
}
$d = self::displayValues($p);
$colors = [];
foreach ($p['colors'] ?? [] as $c) {
if (!is_array($c)) {
continue;
}
$colors[] = [
'id' => (int) ($c['id'] ?? 0),
'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'],
'fallTime' => (float) $p['fallTime'],
'riseTime' => (float) $p['riseTime'],
'miss_chance' => $d['missChance'],
'display' => $d,
'colors' => $colors,
];
}
private static function clamp(float $value, float $lo, float $hi): float
{
return max($lo, min($hi, $value));
}
}
@@ -0,0 +1,147 @@<?phpdeclare(strict_types=1);/** * Planet catalog shared with the JS client (server/lib/planets.json). * Power and miss-chance formulas must stay in lockstep with src/planet.js. */final class Planets{ private static ?array $all = null; public static function path(): string { return __DIR__ . '/planets.json'; } /** @return list<array> raw catalog entries */ public static function all(): array { if (self::$all !== null) { return self::$all; } $raw = file_get_contents(self::path()); if ($raw === false) { throw new RuntimeException('planets.json ontbreekt.'); } $data = json_decode($raw, true); if (!is_array($data) || !isset($data['planets']) || !is_array($data['planets'])) { throw new RuntimeException('planets.json is ongeldig.'); } self::$all = []; foreach ($data['planets'] as $row) { if (!is_array($row) || empty($row['id'])) { continue; } self::$all[] = $row; } return self::$all; } public static function byId(string $id): ?array { foreach (self::all() as $p) { if (($p['id'] ?? '') === $id) { return $p; } } return null; } public static function defaultId(): string { return 'terra'; } public static function default(): array { return self::byId(self::defaultId()) ?? self::all()[0]; } public static function known(string $id): bool { return self::byId($id) !== null; } /** Difficulty in 0..1. Higher is harder. */ public static function power(array $planet): float { $j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4); $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5); $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3); $gravity = ($j - 1) / 3; $air = (5 - $f) / 4; $mass = (3 - $r) / 2.5; return ($gravity + $air + $mass) / 3; } /** Miss chance: 0.60 at power 0, 0.05 at power 1. */ public static function missChance(array $planet): float { return 0.60 - 0.55 * self::power($planet); } public static function missChanceForId(string $id): float { $p = self::byId($id); if ($p === null) { $p = self::default(); } return self::missChance($p); } /** @return array{gravity:float,density:float,newtons:float,power:int,missChance:float} */ public static function displayValues(array $planet): array { $j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4); $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5); $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3); $power = self::power($planet); return [ 'gravity' => 9.81 * $j / 2, 'density' => 0.25 + ((5 - $f) / 4) * 1.60, 'newtons' => 40 + (($r - 0.5) / 2.5) * 160, 'power' => (int) round($power * 100), 'missChance' => 0.60 - 0.55 * $power, ]; } /** Public subset sent to clients (no need to ship the full catalog again). */ public static function present(?string $id): array { $p = $id ? self::byId($id) : null; if ($p === null) { $p = self::default(); } $d = self::displayValues($p); $colors = []; foreach ($p['colors'] ?? [] as $c) { if (!is_array($c)) { continue; } $colors[] = [ 'id' => (int) ($c['id'] ?? 0), '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'], 'fallTime' => (float) $p['fallTime'], 'riseTime' => (float) $p['riseTime'], 'miss_chance' => $d['missChance'], 'display' => $d, 'colors' => $colors, ]; } private static function clamp(float $value, float $lo, float $hi): float { return max($lo, min($hi, $value)); }}@@ -1,6 +1,8 @@
<?php
declare(strict_types=1);
require_once __DIR__ . '/Planets.php';
final class Store
{
private PDO $pdo;
@@ -71,6 +73,18 @@ 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'");
}
private function ensureColumn(string $table, string $column, string $ddl): void
{
$cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
foreach ($cols as $c) {
if (($c['name'] ?? '') === $column) {
return;
}
}
$this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl);
}
public function transaction(callable $fn): mixed
@@ -170,9 +184,9 @@ SQL);
return $stmt->fetchAll();
}
public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS): array
public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array
{
return $this->transaction(function () use ($userId, $name, $missChance) {
return $this->transaction(function () use ($userId, $name, $missChance, $planetId) {
$existing = $this->lobbyForUser($userId);
if ($existing && $existing['status'] !== 'finished') {
throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
@@ -188,17 +202,18 @@ 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();
$this->pdo->prepare(
'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen)
VALUES (?,?,?,0,?,?)'
)->execute([$id, $userId, $name, $now, $now]);
'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id)
VALUES (?,?,?,0,?,?,?)'
)->execute([$id, $userId, $name, $now, $now, $planet]);
return $this->getLobby($id);
});
}
public function joinLobby(string $userId, string $name, string $code): array
public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array
{
return $this->transaction(function () use ($userId, $name, $code) {
return $this->transaction(function () use ($userId, $name, $code, $planetId) {
$existing = $this->lobbyForUser($userId);
if ($existing && $existing['status'] !== 'finished') {
if (strcasecmp($existing['code'], $code) === 0) {
@@ -219,8 +234,8 @@ SQL);
}
$now = $this->now();
$this->pdo->prepare(
'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot)
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)
VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?)
ON CONFLICT(lobby_id, user_id) DO UPDATE SET
name = excluded.name,
ready = 0,
@@ -230,8 +245,9 @@ SQL);
joined = excluded.joined,
last_seen = excluded.last_seen,
score = 0,
snapshot = NULL'
)->execute([$lobby['id'], $userId, $name, $now, $now]);
snapshot = NULL,
planet_id = excluded.planet_id'
)->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]);
return $this->getLobby($lobby['id']);
});
}
@@ -323,6 +339,39 @@ SQL);
}
/** @param list<array{client_id?:string,color?:int}> $shots */
public function setPlanet(string $userId, string $planetId): array
{
return $this->transaction(function () use ($userId, $planetId) {
$lobby = $this->lobbyForUser($userId);
if (!$lobby) {
throw new RuntimeException('Je zit in geen lobby.');
}
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.');
}
$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]);
return $this->getLobby($lobby['id']);
});
}
/** @param array<string,mixed> $member */
public function missChanceForMember(array $member): float
{
if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
return max(0.0, min(1.0, $this->testMissOverride));
}
$id = (string) ($member['planet_id'] ?? Planets::defaultId());
return Planets::missChanceForId($id);
}
/** @var ?float Tests may force a miss chance without changing the catalog. */
public ?float $testMissOverride = null;
public function recordShots(string $userId, array $shots): array
{
return $this->transaction(function () use ($userId, $shots) {
@@ -341,7 +390,7 @@ SQL);
}
}
$results = [];
$missChance = (float) $lobby['miss_chance'];
$missChance = $this->missChanceForMember($me);
$flight = (float) $lobby['flight_duration'];
$now = $this->nowf();
$ins = $this->pdo->prepare(
@@ -580,6 +629,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())),
];
}
$rankings = [];
@@ -1,6 +1,8 @@<?php<?phpdeclare(strict_types=1);declare(strict_types=1);require_once __DIR__ . '/Planets.php';final class Storefinal class Store{{ private PDO $pdo; private PDO $pdo;@@ -71,6 +73,18 @@ 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'"); } private function ensureColumn(string $table, string $column, string $ddl): void { $cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll(); foreach ($cols as $c) { if (($c['name'] ?? '') === $column) { return; } } $this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl); } } public function transaction(callable $fn): mixed public function transaction(callable $fn): mixed@@ -170,9 +184,9 @@ SQL); return $stmt->fetchAll(); return $stmt->fetchAll(); } } public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS): array public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array { { return $this->transaction(function () use ($userId, $name, $missChance) { return $this->transaction(function () use ($userId, $name, $missChance, $planetId) { $existing = $this->lobbyForUser($userId); $existing = $this->lobbyForUser($userId); if ($existing && $existing['status'] !== 'finished') { if ($existing && $existing['status'] !== 'finished') { throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.'); throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');@@ -188,17 +202,18 @@ 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(); $this->pdo->prepare( $this->pdo->prepare( 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen) 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id) VALUES (?,?,?,0,?,?)' VALUES (?,?,?,0,?,?,?)' )->execute([$id, $userId, $name, $now, $now]); )->execute([$id, $userId, $name, $now, $now, $planet]); return $this->getLobby($id); return $this->getLobby($id); }); }); } } public function joinLobby(string $userId, string $name, string $code): array public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array { { return $this->transaction(function () use ($userId, $name, $code) { return $this->transaction(function () use ($userId, $name, $code, $planetId) { $existing = $this->lobbyForUser($userId); $existing = $this->lobbyForUser($userId); if ($existing && $existing['status'] !== 'finished') { if ($existing && $existing['status'] !== 'finished') { if (strcasecmp($existing['code'], $code) === 0) { if (strcasecmp($existing['code'], $code) === 0) {@@ -219,8 +234,8 @@ SQL); } } $now = $this->now(); $now = $this->now(); $this->pdo->prepare( $this->pdo->prepare( 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot) '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) 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,@@ -230,8 +245,9 @@ SQL); joined = excluded.joined, joined = excluded.joined, last_seen = excluded.last_seen, last_seen = excluded.last_seen, score = 0, score = 0, snapshot = NULL' snapshot = NULL, )->execute([$lobby['id'], $userId, $name, $now, $now]); planet_id = excluded.planet_id' )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]); return $this->getLobby($lobby['id']); return $this->getLobby($lobby['id']); }); }); } }@@ -323,6 +339,39 @@ SQL); } } /** @param list<array{client_id?:string,color?:int}> $shots */ /** @param list<array{client_id?:string,color?:int}> $shots */ public function setPlanet(string $userId, string $planetId): array { return $this->transaction(function () use ($userId, $planetId) { $lobby = $this->lobbyForUser($userId); if (!$lobby) { throw new RuntimeException('Je zit in geen lobby.'); } 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.'); } $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]); return $this->getLobby($lobby['id']); }); } /** @param array<string,mixed> $member */ public function missChanceForMember(array $member): float { if (isset($this->testMissOverride) && is_float($this->testMissOverride)) { return max(0.0, min(1.0, $this->testMissOverride)); } $id = (string) ($member['planet_id'] ?? Planets::defaultId()); return Planets::missChanceForId($id); } /** @var ?float Tests may force a miss chance without changing the catalog. */ public ?float $testMissOverride = null; public function recordShots(string $userId, array $shots): array public function recordShots(string $userId, array $shots): array { { return $this->transaction(function () use ($userId, $shots) { return $this->transaction(function () use ($userId, $shots) {@@ -341,7 +390,7 @@ SQL); } } } } $results = []; $results = []; $missChance = (float) $lobby['miss_chance']; $missChance = $this->missChanceForMember($me); $flight = (float) $lobby['flight_duration']; $flight = (float) $lobby['flight_duration']; $now = $this->nowf(); $now = $this->nowf(); $ins = $this->pdo->prepare( $ins = $this->pdo->prepare(@@ -580,6 +629,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())), ]; ]; } } $rankings = []; $rankings = [];@@ -0,0 +1,184 @@
{
"planets": [
{
"id": "terra",
"name": "Terra",
"people": "Terrans",
"jumpsToClear": 2,
"fallTime": 3,
"riseTime": 1.5,
"colors": [
{"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"},
{"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"},
{"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"},
{"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"},
{"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"}
]
},
{
"id": "aurel",
"name": "Aurel",
"people": "Aurelians",
"jumpsToClear": 1,
"fallTime": 5,
"riseTime": 3,
"colors": [
{"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"},
{"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"},
{"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"},
{"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"},
{"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"}
]
},
{
"id": "cinder",
"name": "Cinder",
"people": "Cindari",
"jumpsToClear": 4,
"fallTime": 1,
"riseTime": 0.5,
"colors": [
{"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"},
{"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"},
{"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"},
{"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"},
{"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"}
]
},
{
"id": "lunara",
"name": "Lunara",
"people": "Lunarites",
"jumpsToClear": 1,
"fallTime": 2,
"riseTime": 1.2,
"colors": [
{"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"},
{"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"},
{"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"},
{"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"},
{"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"}
]
},
{
"id": "mire",
"name": "Mire",
"people": "Mirians",
"jumpsToClear": 2,
"fallTime": 5,
"riseTime": 2.5,
"colors": [
{"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"},
{"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"},
{"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"},
{"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"},
{"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"}
]
},
{
"id": "galeon",
"name": "Galeon",
"people": "Galeoni",
"jumpsToClear": 3,
"fallTime": 1,
"riseTime": 1.8,
"colors": [
{"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"},
{"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"},
{"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"},
{"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"},
{"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"}
]
},
{
"id": "obsid",
"name": "Obsid",
"people": "Obsidians",
"jumpsToClear": 4,
"fallTime": 3.5,
"riseTime": 2.2,
"colors": [
{"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"},
{"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"},
{"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"},
{"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"},
{"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"}
]
},
{
"id": "wisp",
"name": "Wisp",
"people": "Wisplings",
"jumpsToClear": 2,
"fallTime": 3.5,
"riseTime": 0.5,
"colors": [
{"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"},
{"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"},
{"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"},
{"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"},
{"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"}
]
},
{
"id": "thorn",
"name": "Thorn",
"people": "Thornfolk",
"jumpsToClear": 3,
"fallTime": 2,
"riseTime": 1.0,
"colors": [
{"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"},
{"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"},
{"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"},
{"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"},
{"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"}
]
},
{
"id": "zephyr",
"name": "Zephyr",
"people": "Zephyrites",
"jumpsToClear": 1,
"fallTime": 1.2,
"riseTime": 2.8,
"colors": [
{"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"},
{"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"},
{"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"},
{"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"},
{"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"}
]
},
{
"id": "frore",
"name": "Frore",
"people": "Frorians",
"jumpsToClear": 3,
"fallTime": 4.5,
"riseTime": 0.8,
"colors": [
{"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"},
{"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"},
{"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"},
{"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"},
{"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"}
]
},
{
"id": "forge",
"name": "Forge",
"people": "Forgelings",
"jumpsToClear": 4,
"fallTime": 2,
"riseTime": 1.5,
"colors": [
{"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"},
{"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"},
{"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"},
{"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"},
{"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"}
]
}
]
}
@@ -0,0 +1,184 @@{ "planets": [ { "id": "terra", "name": "Terra", "people": "Terrans", "jumpsToClear": 2, "fallTime": 3, "riseTime": 1.5, "colors": [ {"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"}, {"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"}, {"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"}, {"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"}, {"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"} ] }, { "id": "aurel", "name": "Aurel", "people": "Aurelians", "jumpsToClear": 1, "fallTime": 5, "riseTime": 3, "colors": [ {"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"}, {"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"}, {"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"}, {"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"}, {"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"} ] }, { "id": "cinder", "name": "Cinder", "people": "Cindari", "jumpsToClear": 4, "fallTime": 1, "riseTime": 0.5, "colors": [ {"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"}, {"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"}, {"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"}, {"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"}, {"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"} ] }, { "id": "lunara", "name": "Lunara", "people": "Lunarites", "jumpsToClear": 1, "fallTime": 2, "riseTime": 1.2, "colors": [ {"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"}, {"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"}, {"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"}, {"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"}, {"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"} ] }, { "id": "mire", "name": "Mire", "people": "Mirians", "jumpsToClear": 2, "fallTime": 5, "riseTime": 2.5, "colors": [ {"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"}, {"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"}, {"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"}, {"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"}, {"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"} ] }, { "id": "galeon", "name": "Galeon", "people": "Galeoni", "jumpsToClear": 3, "fallTime": 1, "riseTime": 1.8, "colors": [ {"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"}, {"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"}, {"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"}, {"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"}, {"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"} ] }, { "id": "obsid", "name": "Obsid", "people": "Obsidians", "jumpsToClear": 4, "fallTime": 3.5, "riseTime": 2.2, "colors": [ {"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"}, {"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"}, {"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"}, {"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"}, {"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"} ] }, { "id": "wisp", "name": "Wisp", "people": "Wisplings", "jumpsToClear": 2, "fallTime": 3.5, "riseTime": 0.5, "colors": [ {"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"}, {"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"}, {"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"}, {"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"}, {"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"} ] }, { "id": "thorn", "name": "Thorn", "people": "Thornfolk", "jumpsToClear": 3, "fallTime": 2, "riseTime": 1.0, "colors": [ {"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"}, {"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"}, {"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"}, {"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"}, {"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"} ] }, { "id": "zephyr", "name": "Zephyr", "people": "Zephyrites", "jumpsToClear": 1, "fallTime": 1.2, "riseTime": 2.8, "colors": [ {"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"}, {"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"}, {"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"}, {"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"}, {"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"} ] }, { "id": "frore", "name": "Frore", "people": "Frorians", "jumpsToClear": 3, "fallTime": 4.5, "riseTime": 0.8, "colors": [ {"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"}, {"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"}, {"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"}, {"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"}, {"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"} ] }, { "id": "forge", "name": "Forge", "people": "Forgelings", "jumpsToClear": 4, "fallTime": 2, "riseTime": 1.5, "colors": [ {"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"}, {"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"}, {"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"}, {"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"}, {"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"} ] } ]}@@ -147,12 +147,14 @@ $store->joinLobby('local:test_user_2', 'test_user_2', $c['code']);
$store->setReady('local:test_user_1', true);
$store->setReady('local:test_user_2', true);
$store->startGame('local:test_user_1');
$store->testMissOverride = 1.0;
$allMiss = $store->recordShots('local:test_user_1', [
['client_id' => 'm1', 'color' => 0],
['client_id' => 'm2', 'color' => 1],
['client_id' => 'm3', 'color' => 2],
]);
expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'miss_chance 1.0 → all miss');
$store->testMissOverride = null;
expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'forced miss 1.0 → all miss');
$d = null;
$store->leaveLobby('local:test_user_1');
@@ -162,11 +164,13 @@ $store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);
$store->setReady('local:test_user_1', true);
$store->setReady('local:test_user_2', true);
$store->startGame('local:test_user_1');
$store->testMissOverride = 0.0;
$allHit = $store->recordShots('local:test_user_1', [
['client_id' => 'h1', 'color' => 0],
['client_id' => 'h2', 'color' => 1],
]);
expect(count($allHit) === 2 && array_reduce($allHit, fn ($ok, $r) => $ok && !$r['miss'] && $r['target_id'] === 'local:test_user_2', true), 'miss_chance 0 → all hit the other player');
$store->testMissOverride = null;
expect(count($allHit) === 2 && array_reduce($allHit, fn ($ok, $r) => $ok && !$r['miss'] && $r['target_id'] === 'local:test_user_2', true), 'forced miss 0 → all hit the other player');
// Eliminated player is not a target.
$store->updateSnapshot('local:test_user_2', null, 0, true);
@@ -174,7 +178,62 @@ $none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' =
// Game may already be finished; recordShots on finished returns [].
expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');
echo "\nPlanets and per-sender Power miss\n";
expect(count(Planets::all()) >= 8 && count(Planets::all()) <= 12, 'catalog has 8–12 planets');
expect(Planets::known('terra') && Planets::known('cinder') && Planets::known('aurel'), 'terra, cinder, aurel exist');
expect(almostEqual(Planets::power(Planets::byId('aurel')), 0.0), 'Aurel power 0');
expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60), 'Aurel miss 60%');
expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');
expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');
$td = Planets::displayValues(Planets::byId('terra'));
expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 48, 'Terra display g/d/F/Power');
$store->leaveLobby('local:test_user_1');
$store->leaveLobby('local:test_user_2');
$pl = $store->createLobby('local:test_user_1', 'test_user_1', 0.30, 'aurel');
$store->joinLobby('local:test_user_2', 'test_user_2', $pl['code'], 'cinder');
$presented = $store->presentLobby($pl, 'local:test_user_1');
$byId = [];
foreach ($presented['players'] as $plr) { $byId[$plr['id']] = $plr; }
expect($byId['local:test_user_1']['planet']['id'] === 'aurel', 'host planet aurel');
expect($byId['local:test_user_2']['planet']['id'] === 'cinder', 'guest planet cinder');
expect(almostEqual($byId['local:test_user_1']['planet']['miss_chance'], 0.60), 'host miss from Aurel Power');
expect(almostEqual($byId['local:test_user_2']['planet']['miss_chance'], 0.05), 'guest miss from Cinder Power');
$store->setPlanet('local:test_user_1', 'wisp');
$presented = $store->presentLobby($store->getLobby($pl['id']), 'local:test_user_1');
foreach ($presented['players'] as $plr) {
if ($plr['is_me']) {
expect($plr['planet']['id'] === 'wisp', 'setPlanet updates host to Wisp');
}
}
try {
$store->setPlanet('local:test_user_1', 'no-such-world');
expect(false, 'unknown planet must throw');
} catch (RuntimeException $e) {
expect(true, 'unknown planet rejected');
}
$store->setReady('local:test_user_1', true);
$store->setReady('local:test_user_2', true);
$store->startGame('local:test_user_1');
$me = $store->member($pl['id'], 'local:test_user_1');
expect(almostEqual($store->missChanceForMember($me), Planets::missChanceForId('wisp')), 'in-game miss uses the sender planet');
$guest = $store->member($pl['id'], 'local:test_user_2');
expect(almostEqual($store->missChanceForMember($guest), 0.05), 'guest still uses Cinder Power');
try {
$store->setPlanet('local:test_user_1', 'terra');
expect(false, 'setPlanet during play must throw');
} catch (RuntimeException $e) {
expect(true, 'planet locked once the match starts');
}
$store->leaveLobby('local:test_user_1');
$store->leaveLobby('local:test_user_2');
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');
@@ -147,12 +147,14 @@ $store->joinLobby('local:test_user_2', 'test_user_2', $c['code']);$store->setReady('local:test_user_1', true);$store->setReady('local:test_user_1', true);$store->setReady('local:test_user_2', true);$store->setReady('local:test_user_2', true);$store->startGame('local:test_user_1');$store->startGame('local:test_user_1');$store->testMissOverride = 1.0;$allMiss = $store->recordShots('local:test_user_1', [$allMiss = $store->recordShots('local:test_user_1', [ ['client_id' => 'm1', 'color' => 0], ['client_id' => 'm1', 'color' => 0], ['client_id' => 'm2', 'color' => 1], ['client_id' => 'm2', 'color' => 1], ['client_id' => 'm3', 'color' => 2], ['client_id' => 'm3', 'color' => 2],]);]);expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'miss_chance 1.0 → all miss');$store->testMissOverride = null;expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'forced miss 1.0 → all miss');$d = null;$d = null;$store->leaveLobby('local:test_user_1');$store->leaveLobby('local:test_user_1');@@ -162,11 +164,13 @@ $store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);$store->setReady('local:test_user_1', true);$store->setReady('local:test_user_1', true);$store->setReady('local:test_user_2', true);$store->setReady('local:test_user_2', true);$store->startGame('local:test_user_1');$store->startGame('local:test_user_1');$store->testMissOverride = 0.0;$allHit = $store->recordShots('local:test_user_1', [$allHit = $store->recordShots('local:test_user_1', [ ['client_id' => 'h1', 'color' => 0], ['client_id' => 'h1', 'color' => 0], ['client_id' => 'h2', 'color' => 1], ['client_id' => 'h2', 'color' => 1],]);]);expect(count($allHit) === 2 && array_reduce($allHit, fn ($ok, $r) => $ok && !$r['miss'] && $r['target_id'] === 'local:test_user_2', true), 'miss_chance 0 → all hit the other player');$store->testMissOverride = null;expect(count($allHit) === 2 && array_reduce($allHit, fn ($ok, $r) => $ok && !$r['miss'] && $r['target_id'] === 'local:test_user_2', true), 'forced miss 0 → all hit the other player');// Eliminated player is not a target.// Eliminated player is not a target.$store->updateSnapshot('local:test_user_2', null, 0, true);$store->updateSnapshot('local:test_user_2', null, 0, true);@@ -174,7 +178,62 @@ $none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' =// Game may already be finished; recordShots on finished returns [].// Game may already be finished; recordShots on finished returns [].expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');echo "\nPlanets and per-sender Power miss\n";expect(count(Planets::all()) >= 8 && count(Planets::all()) <= 12, 'catalog has 8–12 planets');expect(Planets::known('terra') && Planets::known('cinder') && Planets::known('aurel'), 'terra, cinder, aurel exist');expect(almostEqual(Planets::power(Planets::byId('aurel')), 0.0), 'Aurel power 0');expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60), 'Aurel miss 60%');expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');$td = Planets::displayValues(Planets::byId('terra'));expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 48, 'Terra display g/d/F/Power');$store->leaveLobby('local:test_user_1');$store->leaveLobby('local:test_user_2');$pl = $store->createLobby('local:test_user_1', 'test_user_1', 0.30, 'aurel');$store->joinLobby('local:test_user_2', 'test_user_2', $pl['code'], 'cinder');$presented = $store->presentLobby($pl, 'local:test_user_1');$byId = [];foreach ($presented['players'] as $plr) { $byId[$plr['id']] = $plr; }expect($byId['local:test_user_1']['planet']['id'] === 'aurel', 'host planet aurel');expect($byId['local:test_user_2']['planet']['id'] === 'cinder', 'guest planet cinder');expect(almostEqual($byId['local:test_user_1']['planet']['miss_chance'], 0.60), 'host miss from Aurel Power');expect(almostEqual($byId['local:test_user_2']['planet']['miss_chance'], 0.05), 'guest miss from Cinder Power');$store->setPlanet('local:test_user_1', 'wisp');$presented = $store->presentLobby($store->getLobby($pl['id']), 'local:test_user_1');foreach ($presented['players'] as $plr) { if ($plr['is_me']) { expect($plr['planet']['id'] === 'wisp', 'setPlanet updates host to Wisp'); }}try { $store->setPlanet('local:test_user_1', 'no-such-world'); expect(false, 'unknown planet must throw');} catch (RuntimeException $e) { expect(true, 'unknown planet rejected');}$store->setReady('local:test_user_1', true);$store->setReady('local:test_user_2', true);$store->startGame('local:test_user_1');$me = $store->member($pl['id'], 'local:test_user_1');expect(almostEqual($store->missChanceForMember($me), Planets::missChanceForId('wisp')), 'in-game miss uses the sender planet');$guest = $store->member($pl['id'], 'local:test_user_2');expect(almostEqual($store->missChanceForMember($guest), 0.05), 'guest still uses Cinder Power');try { $store->setPlanet('local:test_user_1', 'terra'); expect(false, 'setPlanet during play must throw');} catch (RuntimeException $e) { expect(true, 'planet locked once the match starts');}$store->leaveLobby('local:test_user_1');$store->leaveLobby('local:test_user_2');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');@@ -26,6 +26,9 @@ FILES=(
printf '%s\n' " * AUTO-GENERATED FILE — DO NOT EDIT BY HAND."
printf '%s\n' " * Built by src/build.sh from the sources in src/."
printf '%s\n' " */"
printf '%s' "var PLANET_CATALOG = "
cat "$ROOT/server/lib/planets.json"
printf ';\n'
} >> "$BUILD_FILE"
for file in "${FILES[@]}"
@@ -48,7 +51,9 @@ cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
"$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
"$ROOT/build/"
mkdir -p "$ROOT/build/lib"
cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" "$ROOT/build/lib/"
cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \
"$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \
"$ROOT/build/lib/"
mkdir -p "$ROOT/build/data"
cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
# Belt and braces: a leftover local config or db must never enter build/.
@@ -26,6 +26,9 @@ FILES=( printf '%s\n' " * AUTO-GENERATED FILE — DO NOT EDIT BY HAND." printf '%s\n' " * AUTO-GENERATED FILE — DO NOT EDIT BY HAND." printf '%s\n' " * Built by src/build.sh from the sources in src/." printf '%s\n' " * Built by src/build.sh from the sources in src/." printf '%s\n' " */" printf '%s\n' " */" printf '%s' "var PLANET_CATALOG = " cat "$ROOT/server/lib/planets.json" printf ';\n'} >> "$BUILD_FILE"} >> "$BUILD_FILE"for file in "${FILES[@]}"for file in "${FILES[@]}"@@ -48,7 +51,9 @@ cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \ "$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \ "$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \ "$ROOT/build/" "$ROOT/build/"mkdir -p "$ROOT/build/lib"mkdir -p "$ROOT/build/lib"cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" "$ROOT/build/lib/"cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \ "$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \ "$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"# Belt and braces: a leftover local config or db must never enter build/.# Belt and braces: a leftover local config or db must never enter build/.@@ -87,6 +87,9 @@ function optsMissChance (args)
// GameCore(planet, rng, missChance) — third arg is optional.
if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
{ return Math.max(0, Math.min(1, args[2])); }
var planet = args[0];
if (planet && typeof PlanetMod.missChance === 'function')
{ return PlanetMod.missChance(planet); }
return GameCore.DEFAULT_MISS_CHANCE;
}
@@ -87,6 +87,9 @@ function optsMissChance (args) // GameCore(planet, rng, missChance) — third arg is optional. // GameCore(planet, rng, missChance) — third arg is optional. if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2])) if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2])) { return Math.max(0, Math.min(1, args[2])); } { return Math.max(0, Math.min(1, args[2])); } var planet = args[0]; if (planet && typeof PlanetMod.missChance === 'function') { return PlanetMod.missChance(planet); } return GameCore.DEFAULT_MISS_CHANCE; return GameCore.DEFAULT_MISS_CHANCE;}}@@ -7,20 +7,37 @@
* through Online (src/online.js) and the same GameCore.
*/
var IMAGES = [
{ name: 'ember', url: 'images/block-ember.png' },
{ name: 'aqua', url: 'images/block-aqua.png' },
{ name: 'leaf', url: 'images/block-leaf.png' },
{ name: 'sun', url: 'images/block-sun.png' },
{ name: 'orchid', url: 'images/block-orchid.png' },
{ name: 'gray', url: 'images/block-gray.png' },
{ name: 'locked', url: 'images/block-locked.png' },
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
{ name: 'cell', url: 'images/cell.png' },
{ name: 'pixel', url: 'images/pixel.png' }
];
var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
function planetImages ()
{
var list = [
{ name: 'gray', url: 'images/block-gray.png' },
{ name: 'locked', url: 'images/block-locked.png' },
{ name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
{ name: 'cell', url: 'images/cell.png' },
{ name: 'pixel', url: 'images/pixel.png' },
// Keep the original Terra placeholders as aliases (Tim may still have them).
{ name: 'ember', url: 'images/block-ember.png' },
{ name: 'aqua', url: 'images/block-aqua.png' },
{ name: 'leaf', url: 'images/block-leaf.png' },
{ name: 'sun', url: 'images/block-sun.png' },
{ name: 'orchid', url: 'images/block-orchid.png' }
];
var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
for (var i = 0; i < planets.length; i++)
{
var pl = planets[i];
for (var c = 0; c < pl.colors.length; c++)
{
list.push({
name: Planet.spriteKey(pl, c),
url: pl.colors[c].image
});
}
}
return list;
}
var IMAGES = planetImages();
var GAME_OVER_DELAY = 2;
var game = new Game();
@@ -46,7 +63,9 @@ var app = {
online: false,
eliminatedReported: false,
spectating: false,
miniH: 0
miniH: 0,
selectedPlanetId: 'terra',
planetSelectContext: 'solo'
};
window.onload = function ()
@@ -71,13 +90,15 @@ window.onload = function ()
});
bindOnlineUi();
bindPlanetSelect();
restoreSelectedPlanet();
};
function onPlay ()
{
if (app.mode === 'playing')
{ return; }
startPlay();
openPlanetSelect('solo');
}
function startPlay (opts)
@@ -88,14 +109,15 @@ function startPlay (opts)
hideEl('online-panel');
hideEl('spectator');
hideEl('podium');
hideEl('planet-select');
showEl('hud');
app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
var miss = opts.missChance;
if (typeof miss === 'number' && isFinite(miss))
{ app.core = new GameCore(app.planet, Math.random, miss); }
else
{ app.core = new GameCore(app.planet, Math.random); }
if (typeof miss !== 'number' || !isFinite(miss))
{ miss = planetMod.missChance(app.planet); }
app.core = new GameCore(app.planet, Math.random, miss);
app.mode = 'playing';
app.online = !!opts.online;
app.gameOverShown = false;
@@ -164,6 +186,7 @@ function returnToMenu ()
teardownPlay();
app.mode = 'menu';
app.online = false;
hideEl('planet-select');
showEl('menu');
var last = document.getElementById('last-score');
if (app.lastScore > 0)
@@ -247,7 +270,8 @@ function spriteFor (block)
{ return game.images.locked; }
if (block.color < 0)
{ return game.images.gray; }
return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
var key = Planet.spriteKey(app.planet, block.color);
return game.images[key] || game.images.gray;
}
function syncSprites ()
@@ -406,10 +430,7 @@ function refreshHud ()
document.getElementById('score').textContent = String(app.core.score);
var planet = app.planet;
document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
var d = Planet.displayValues(planet);
document.getElementById('planet-stats').textContent =
'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
}
function makeManager ()
@@ -687,10 +708,11 @@ function startOnlineMatch ()
{
if (app.mode === 'playing' && app.online)
{ return; }
var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
? Online.lobby.miss_chance
: (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
startPlay({ online: true, missChance: miss });
var planet = Planet.planetById(selectedPlanetId());
var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
if (me && me.planet && me.planet.id)
{ planet = Planet.planetById(me.planet.id); }
startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
if (typeof Online !== 'undefined')
{ Online.startPolling(onlinePayload); }
}
@@ -847,6 +869,7 @@ function openOnlinePanel ()
hideEl('game-over');
hideEl('podium');
hideEl('spectator');
hideEl('planet-select');
showEl('online-panel');
app.mode = 'online';
setOnlineStatus('Even kijken of online spelen beschikbaar is…');
@@ -948,10 +971,14 @@ function renderOnline ()
{ li.classList.add('you'); }
var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
var state = p.ready ? 'Gereed' : 'Wacht…';
li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
li.innerHTML = '<span>' + escapeText(label)
+ (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
+ '</span><span class="'
+ (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
list.appendChild(li);
}
renderPlanetGrid('lobby-planet-grid', true);
var me = Online.mePlayer();
document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
var start = document.getElementById('btn-start');
@@ -984,3 +1011,147 @@ function escapeText (s)
.replace(/>/g, '>')
.replace(/"/g, '"');
}
function selectedPlanetId ()
{
if (app.selectedPlanetId)
{ return app.selectedPlanetId; }
return 'terra';
}
function restoreSelectedPlanet ()
{
var id = 'terra';
try
{ id = localStorage.getItem('meteors-planet') || 'terra'; }
catch (e) {}
setSelectedPlanet(id, true);
}
function setSelectedPlanet (id, silent)
{
var all = Planet.allPlanets();
var found = null;
for (var i = 0; i < all.length; i++)
{
if (all[i].id === id)
{ found = all[i]; break; }
}
if (!found)
{ found = Planet.defaultPlanet(); }
app.selectedPlanetId = found.id;
try
{ localStorage.setItem('meteors-planet', found.id); }
catch (e) {}
if (!silent)
{
var grid = document.getElementById('planet-grid');
if (grid && !grid.hidden && grid.children.length)
{ renderPlanetGrid('planet-grid', false); }
var lobby = document.getElementById('lobby-planet-grid');
if (lobby && lobby.children.length)
{ renderPlanetGrid('lobby-planet-grid', true); }
}
return found;
}
function openPlanetSelect (context)
{
if (app.mode === 'playing')
{ return; }
app.planetSelectContext = context || 'solo';
app.mode = 'planet-select';
hideEl('menu');
hideEl('online-panel');
hideEl('game-over');
showEl('planet-select');
renderPlanetGrid('planet-grid', false);
var go = document.getElementById('btn-planet-go');
if (go)
{ go.textContent = 'Spelen'; }
}
function renderPlanetGrid (containerId, compact)
{
var grid = document.getElementById(containerId);
if (!grid)
{ return; }
var current = selectedPlanetId();
var all = Planet.allPlanets();
grid.innerHTML = '';
if (compact)
{ grid.classList.add('compact'); }
for (var i = 0; i < all.length; i++)
{
var pl = all[i];
var btn = document.createElement('button');
btn.type = 'button';
btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
btn.setAttribute('role', 'listitem');
btn.dataset.planet = pl.id;
var swatches = '';
for (var c = 0; c < pl.colors.length; c++)
{
swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
+ escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.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>';
btn.addEventListener('click', (function (id, isCompact)
{
return function ()
{ onPlanetPicked(id, isCompact); };
})(pl.id, !!compact));
grid.appendChild(btn);
}
}
function onPlanetPicked (id, fromLobby)
{
setSelectedPlanet(id);
if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
{
Online.setPlanet(id).then(function ()
{ renderOnline(); });
}
else
{
renderPlanetGrid('planet-grid', false);
}
}
function confirmPlanetSelect ()
{
var planet = setSelectedPlanet(selectedPlanetId());
hideEl('planet-select');
if (app.planetSelectContext === 'online')
{
openOnlinePanel();
return;
}
startPlay({ planet: planet });
}
function cancelPlanetSelect ()
{
hideEl('planet-select');
app.mode = 'menu';
showEl('menu');
}
function bindPlanetSelect ()
{
var go = document.getElementById('btn-planet-go');
var back = document.getElementById('btn-planet-back');
if (go)
{
go.addEventListener('click', confirmPlanetSelect);
}
if (back)
{
back.addEventListener('click', cancelPlanetSelect);
}
}
@@ -7,20 +7,37 @@ * through Online (src/online.js) and the same GameCore. * through Online (src/online.js) and the same GameCore. */ */var IMAGES = [function planetImages () { name: 'ember', url: 'images/block-ember.png' },{ { name: 'aqua', url: 'images/block-aqua.png' }, var list = [ { name: 'leaf', url: 'images/block-leaf.png' }, { name: 'gray', url: 'images/block-gray.png' }, { name: 'sun', url: 'images/block-sun.png' }, { name: 'locked', url: 'images/block-locked.png' }, { name: 'orchid', url: 'images/block-orchid.png' }, { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 }, { name: 'gray', url: 'images/block-gray.png' }, { name: 'cell', url: 'images/cell.png' }, { name: 'locked', url: 'images/block-locked.png' }, { name: 'pixel', url: 'images/pixel.png' }, { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 }, // Keep the original Terra placeholders as aliases (Tim may still have them). { name: 'cell', url: 'images/cell.png' }, { name: 'ember', url: 'images/block-ember.png' }, { name: 'pixel', url: 'images/pixel.png' } { name: 'aqua', url: 'images/block-aqua.png' },]; { name: 'leaf', url: 'images/block-leaf.png' }, { name: 'sun', url: 'images/block-sun.png' },var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid']; { name: 'orchid', url: 'images/block-orchid.png' } ]; var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []); for (var i = 0; i < planets.length; i++) { var pl = planets[i]; for (var c = 0; c < pl.colors.length; c++) { list.push({ name: Planet.spriteKey(pl, c), url: pl.colors[c].image }); } } return list;}var IMAGES = planetImages();var GAME_OVER_DELAY = 2;var GAME_OVER_DELAY = 2;var game = new Game();var game = new Game();@@ -46,7 +63,9 @@ var app = { online: false, online: false, eliminatedReported: false, eliminatedReported: false, spectating: false, spectating: false, miniH: 0 miniH: 0, selectedPlanetId: 'terra', planetSelectContext: 'solo'};};window.onload = function ()window.onload = function ()@@ -71,13 +90,15 @@ window.onload = function () }); }); bindOnlineUi(); bindOnlineUi(); bindPlanetSelect(); restoreSelectedPlanet();};};function onPlay ()function onPlay (){{ if (app.mode === 'playing') if (app.mode === 'playing') { return; } { return; } startPlay(); openPlanetSelect('solo');}}function startPlay (opts)function startPlay (opts)@@ -88,14 +109,15 @@ function startPlay (opts) hideEl('online-panel'); hideEl('online-panel'); hideEl('spectator'); hideEl('spectator'); hideEl('podium'); hideEl('podium'); hideEl('planet-select'); showEl('hud'); showEl('hud'); app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet()); var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod; app.planet = opts.planet || planetMod.planetById(selectedPlanetId()); var miss = opts.missChance; var miss = opts.missChance; if (typeof miss === 'number' && isFinite(miss)) if (typeof miss !== 'number' || !isFinite(miss)) { app.core = new GameCore(app.planet, Math.random, miss); } { miss = planetMod.missChance(app.planet); } else app.core = new GameCore(app.planet, Math.random, miss); { app.core = new GameCore(app.planet, Math.random); } app.mode = 'playing'; app.mode = 'playing'; app.online = !!opts.online; app.online = !!opts.online; app.gameOverShown = false; app.gameOverShown = false;@@ -164,6 +186,7 @@ function returnToMenu () teardownPlay(); teardownPlay(); app.mode = 'menu'; app.mode = 'menu'; app.online = false; app.online = false; hideEl('planet-select'); showEl('menu'); showEl('menu'); var last = document.getElementById('last-score'); var last = document.getElementById('last-score'); if (app.lastScore > 0) if (app.lastScore > 0)@@ -247,7 +270,8 @@ function spriteFor (block) { return game.images.locked; } { return game.images.locked; } if (block.color < 0) if (block.color < 0) { return game.images.gray; } { return game.images.gray; } return game.images[COLOR_SPRITES[block.color]] || game.images.gray; var key = Planet.spriteKey(app.planet, block.color); return game.images[key] || game.images.gray;}}function syncSprites ()function syncSprites ()@@ -406,10 +430,7 @@ function refreshHud () document.getElementById('score').textContent = String(app.core.score); document.getElementById('score').textContent = String(app.core.score); var planet = app.planet; var planet = app.planet; document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people; document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people; var d = Planet.displayValues(planet); document.getElementById('planet-stats').textContent = Planet.formatStats(planet); document.getElementById('planet-stats').textContent = 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) + ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';}}function makeManager ()function makeManager ()@@ -687,10 +708,11 @@ function startOnlineMatch (){{ if (app.mode === 'playing' && app.online) if (app.mode === 'playing' && app.online) { return; } { return; } var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null) var planet = Planet.planetById(selectedPlanetId()); ? Online.lobby.miss_chance var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null; : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30); if (me && me.planet && me.planet.id) startPlay({ online: true, missChance: miss }); { planet = Planet.planetById(me.planet.id); } startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) }); if (typeof Online !== 'undefined') if (typeof Online !== 'undefined') { Online.startPolling(onlinePayload); } { Online.startPolling(onlinePayload); }}}@@ -847,6 +869,7 @@ function openOnlinePanel () hideEl('game-over'); hideEl('game-over'); hideEl('podium'); hideEl('podium'); hideEl('spectator'); hideEl('spectator'); hideEl('planet-select'); showEl('online-panel'); showEl('online-panel'); app.mode = 'online'; app.mode = 'online'; setOnlineStatus('Even kijken of online spelen beschikbaar is…'); setOnlineStatus('Even kijken of online spelen beschikbaar is…');@@ -948,10 +971,14 @@ function renderOnline () { li.classList.add('you'); } { li.classList.add('you'); } var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : ''); var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : ''); var state = p.ready ? 'Gereed' : 'Wacht…'; var state = p.ready ? 'Gereed' : 'Wacht…'; li.innerHTML = '<span>' + escapeText(label) + '</span><span class="' var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : ''; li.innerHTML = '<span>' + escapeText(label) + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '') + '</span><span class="' + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>'; + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>'; list.appendChild(li); list.appendChild(li); } } renderPlanetGrid('lobby-planet-grid', true); var me = Online.mePlayer(); var me = Online.mePlayer(); document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed'; document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed'; var start = document.getElementById('btn-start'); var start = document.getElementById('btn-start');@@ -984,3 +1011,147 @@ function escapeText (s) .replace(/>/g, '>') .replace(/>/g, '>') .replace(/"/g, '"'); .replace(/"/g, '"');}}function selectedPlanetId (){ if (app.selectedPlanetId) { return app.selectedPlanetId; } return 'terra';}function restoreSelectedPlanet (){ var id = 'terra'; try { id = localStorage.getItem('meteors-planet') || 'terra'; } catch (e) {} setSelectedPlanet(id, true);}function setSelectedPlanet (id, silent){ var all = Planet.allPlanets(); var found = null; for (var i = 0; i < all.length; i++) { if (all[i].id === id) { found = all[i]; break; } } if (!found) { found = Planet.defaultPlanet(); } app.selectedPlanetId = found.id; try { localStorage.setItem('meteors-planet', found.id); } catch (e) {} if (!silent) { var grid = document.getElementById('planet-grid'); if (grid && !grid.hidden && grid.children.length) { renderPlanetGrid('planet-grid', false); } var lobby = document.getElementById('lobby-planet-grid'); if (lobby && lobby.children.length) { renderPlanetGrid('lobby-planet-grid', true); } } return found;}function openPlanetSelect (context){ if (app.mode === 'playing') { return; } app.planetSelectContext = context || 'solo'; app.mode = 'planet-select'; hideEl('menu'); hideEl('online-panel'); hideEl('game-over'); showEl('planet-select'); renderPlanetGrid('planet-grid', false); var go = document.getElementById('btn-planet-go'); if (go) { go.textContent = 'Spelen'; }}function renderPlanetGrid (containerId, compact){ var grid = document.getElementById(containerId); if (!grid) { return; } var current = selectedPlanetId(); var all = Planet.allPlanets(); grid.innerHTML = ''; if (compact) { grid.classList.add('compact'); } for (var i = 0; i < all.length; i++) { var pl = all[i]; var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'planet-card' + (pl.id === current ? ' selected' : ''); btn.setAttribute('role', 'listitem'); btn.dataset.planet = pl.id; var swatches = ''; for (var c = 0; c < pl.colors.length; c++) { swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="' + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.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>'; btn.addEventListener('click', (function (id, isCompact) { return function () { onPlanetPicked(id, isCompact); }; })(pl.id, !!compact)); grid.appendChild(btn); }}function onPlanetPicked (id, fromLobby){ setSelectedPlanet(id); if (fromLobby && typeof Online !== 'undefined' && Online.lobby) { Online.setPlanet(id).then(function () { renderOnline(); }); } else { renderPlanetGrid('planet-grid', false); }}function confirmPlanetSelect (){ var planet = setSelectedPlanet(selectedPlanetId()); hideEl('planet-select'); if (app.planetSelectContext === 'online') { openOnlinePanel(); return; } startPlay({ planet: planet });}function cancelPlanetSelect (){ hideEl('planet-select'); app.mode = 'menu'; showEl('menu');}function bindPlanetSelect (){ var go = document.getElementById('btn-planet-go'); var back = document.getElementById('btn-planet-back'); if (go) { go.addEventListener('click', confirmPlanetSelect); } if (back) { back.addEventListener('click', cancelPlanetSelect); }}@@ -115,14 +115,25 @@ Online.testLogin = function (who)
return this.request('test_login', { user: who });
};
Online.createLobby = function ()
Online.createLobby = function (planetId)
{
return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
return this.request('lobby_create', {
miss_chance: this.DEFAULT_MISS_CHANCE,
planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
});
};
Online.joinLobby = function (code, planetId)
{
return this.request('lobby_join', {
code: code,
planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
});
};
Online.joinLobby = function (code)
Online.setPlanet = function (planetId)
{
return this.request('lobby_join', { code: code });
return this.request('lobby_set_planet', { planet_id: planetId });
};
Online.leaveLobby = function ()
@@ -289,7 +300,7 @@ Online.renderMinis = function (container)
el.querySelector('.mini-meta').textContent = p.eliminated
? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
: ('Punten ' + (p.score || 0));
this._drawMini(el.querySelector('canvas'), p.snapshot);
this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
}
for (var id in existing)
{
@@ -300,7 +311,15 @@ Online.renderMinis = function (container)
var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
Online._drawMini = function (canvas, snapshot)
function miniColor (planet, color)
{
if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
{ return planet.colors[color].hex; }
return MINI_COLORS[color] || '#888';
}
Online._drawMini = function (canvas, snapshot, planet)
{
if (!canvas)
{ return; }
@@ -340,7 +359,7 @@ Online._drawMini = function (canvas, snapshot)
else if (b.color < 0)
{ ctx.fillStyle = '#5a5d66'; }
else
{ ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
{ ctx.fillStyle = miniColor(planet, b.color); }
ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
}
};
@@ -352,12 +371,16 @@ Online.miniElement = function (playerId)
/* ---------- flight tweens ------------------------------------------ */
function colorSpriteUrl (color)
function colorSpriteUrl (color, planetId)
{
if (color < 0)
{ return 'images/block-gray.png'; }
var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
return 'images/block-' + (names[color] || 'gray') + '.png';
var planet = null;
if (typeof Planet !== 'undefined')
{ planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
{ return planet.colors[color].image; }
return 'images/block-gray.png';
}
/**
@@ -115,14 +115,25 @@ Online.testLogin = function (who) return this.request('test_login', { user: who }); return this.request('test_login', { user: who });};};Online.createLobby = function ()Online.createLobby = function (planetId){{ return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE }); return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') });};Online.joinLobby = function (code, planetId){ return this.request('lobby_join', { code: code, planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra') });};};Online.joinLobby = function (code)Online.setPlanet = function (planetId){{ return this.request('lobby_join', { code: code }); return this.request('lobby_set_planet', { planet_id: planetId });};};Online.leaveLobby = function ()Online.leaveLobby = function ()@@ -289,7 +300,7 @@ Online.renderMinis = function (container) el.querySelector('.mini-meta').textContent = p.eliminated el.querySelector('.mini-meta').textContent = p.eliminated ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : '')) ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : '')) : ('Punten ' + (p.score || 0)); : ('Punten ' + (p.score || 0)); this._drawMini(el.querySelector('canvas'), p.snapshot); this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet); } } for (var id in existing) for (var id in existing) { {@@ -300,7 +311,15 @@ Online.renderMinis = function (container)var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];Online._drawMini = function (canvas, snapshot)function miniColor (planet, color){ if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex) { return planet.colors[color].hex; } return MINI_COLORS[color] || '#888';}Online._drawMini = function (canvas, snapshot, planet){{ if (!canvas) if (!canvas) { return; } { return; }@@ -340,7 +359,7 @@ Online._drawMini = function (canvas, snapshot) else if (b.color < 0) else if (b.color < 0) { ctx.fillStyle = '#5a5d66'; } { ctx.fillStyle = '#5a5d66'; } else else { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; } { ctx.fillStyle = miniColor(planet, b.color); } ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1); ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1); } }};};@@ -352,12 +371,16 @@ Online.miniElement = function (playerId)/* ---------- flight tweens ------------------------------------------ *//* ---------- flight tweens ------------------------------------------ */function colorSpriteUrl (color)function colorSpriteUrl (color, planetId){{ if (color < 0) if (color < 0) { return 'images/block-gray.png'; } { return 'images/block-gray.png'; } var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid']; var planet = null; return 'images/block-' + (names[color] || 'gray') + '.png'; if (typeof Planet !== 'undefined') { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); } if (planet && planet.colors && planet.colors[color] && planet.colors[color].image) { return planet.colors[color].image; } return 'images/block-gray.png';}}/**/**@@ -51,6 +51,7 @@ function createPlanet (opts)
var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
var colors = opts.colors || defaultColors();
var planet = {
id: opts.id || null,
name: opts.name || 'Terra',
people: opts.people || 'Terrans',
jumpsToClear: jumpsToClear,
@@ -70,15 +71,82 @@ function createPlanet (opts)
return planet;
}
function defaultPlanet ()
function loadCatalog ()
{
if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
{ return PLANET_CATALOG; }
if (typeof require !== 'undefined')
{
try
{ return require('../server/lib/planets.json'); }
catch (e) {}
}
return { planets: [] };
}
function planetFromData (data)
{
return createPlanet({
name: 'Terra',
people: 'Terrans',
jumpsToClear: 2,
fallTime: 3,
riseTime: 1.5
var planet = createPlanet({
name: data.name,
people: data.people,
jumpsToClear: data.jumpsToClear,
fallTime: data.fallTime,
riseTime: data.riseTime,
colors: data.colors
});
planet.id = data.id;
return planet;
}
function allPlanets ()
{
var raw = loadCatalog().planets || [];
var out = [];
for (var i = 0; i < raw.length; i++)
{ out.push(planetFromData(raw[i])); }
if (out.length === 0)
{ out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
return out;
}
function planetById (id)
{
var all = allPlanets();
for (var i = 0; i < all.length; i++)
{
if (all[i].id === id)
{ return all[i]; }
}
return defaultPlanet();
}
function defaultPlanet ()
{
var all = allPlanets();
for (var i = 0; i < all.length; i++)
{
if (all[i].id === 'terra')
{ return all[i]; }
}
return all[0];
}
function formatStats (planet)
{
var d = displayValues(planet);
return 'g ' + d.gravity.toFixed(2)
+ ' d ' + d.density.toFixed(2)
+ ' F ' + Math.round(d.newtons) + ' N'
+ ' Power ' + d.power + '%';
}
function spriteKey (planet, colorIndex)
{
var colors = planet && planet.colors;
var c = colors && colors[colorIndex];
if (!c)
{ return 'gray'; }
return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
}
/**
@@ -158,6 +226,11 @@ var Planet = {
createPlanet: createPlanet,
defaultPlanet: defaultPlanet,
defaultColors: defaultColors,
allPlanets: allPlanets,
planetById: planetById,
planetFromData: planetFromData,
formatStats: formatStats,
spriteKey: spriteKey,
jumpHeight: jumpHeight,
launchVelocity: launchVelocity,
launchDeceleration: launchDeceleration,
@@ -51,6 +51,7 @@ function createPlanet (opts) var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3); var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3); var colors = opts.colors || defaultColors(); var colors = opts.colors || defaultColors(); var planet = { var planet = { id: opts.id || null, name: opts.name || 'Terra', name: opts.name || 'Terra', people: opts.people || 'Terrans', people: opts.people || 'Terrans', jumpsToClear: jumpsToClear, jumpsToClear: jumpsToClear,@@ -70,15 +71,82 @@ function createPlanet (opts) return planet; return planet;}}function defaultPlanet ()function loadCatalog (){ if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets) { return PLANET_CATALOG; } if (typeof require !== 'undefined') { try { return require('../server/lib/planets.json'); } catch (e) {} } return { planets: [] };}function planetFromData (data){{ return createPlanet({ var planet = createPlanet({ name: 'Terra', name: data.name, people: 'Terrans', people: data.people, jumpsToClear: 2, jumpsToClear: data.jumpsToClear, fallTime: 3, fallTime: data.fallTime, riseTime: 1.5 riseTime: data.riseTime, colors: data.colors }); }); planet.id = data.id; return planet;}function allPlanets (){ var raw = loadCatalog().planets || []; var out = []; for (var i = 0; i < raw.length; i++) { out.push(planetFromData(raw[i])); } if (out.length === 0) { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; } return out;}function planetById (id){ var all = allPlanets(); for (var i = 0; i < all.length; i++) { if (all[i].id === id) { return all[i]; } } return defaultPlanet();}function defaultPlanet (){ var all = allPlanets(); for (var i = 0; i < all.length; i++) { if (all[i].id === 'terra') { return all[i]; } } return all[0];}function formatStats (planet){ var d = displayValues(planet); return 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) + ' F ' + Math.round(d.newtons) + ' N' + ' Power ' + d.power + '%';}function spriteKey (planet, colorIndex){ var colors = planet && planet.colors; var c = colors && colors[colorIndex]; if (!c) { return 'gray'; } return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));}}/**/**@@ -158,6 +226,11 @@ var Planet = { createPlanet: createPlanet, createPlanet: createPlanet, defaultPlanet: defaultPlanet, defaultPlanet: defaultPlanet, defaultColors: defaultColors, defaultColors: defaultColors, allPlanets: allPlanets, planetById: planetById, planetFromData: planetFromData, formatStats: formatStats, spriteKey: spriteKey, jumpHeight: jumpHeight, jumpHeight: jumpHeight, launchVelocity: launchVelocity, launchVelocity: launchVelocity, launchDeceleration: launchDeceleration, launchDeceleration: launchDeceleration,@@ -67,18 +67,21 @@ describe('Outgoing shots and incoming garbage', () =>
assert.equal(g.ingestGarbage(), null);
});
it('missChance is a parameter defaulting to 0.30, independent of planet Power', () =>
it('missChance defaults to the planet Power formula and can still be overridden', () =>
{
const g = makeGame({ noSpawn: true });
assert.equal(g.missChance, 0.30);
const terraMiss = Planet.missChance(Planet.defaultPlanet());
assert.ok(Math.abs(g.missChance - terraMiss) < 1e-12);
assert.ok(Math.abs(terraMiss - 0.30) > 0.01, 'Terra Power miss is not the old flat 30%');
assert.equal(GameCore.DEFAULT_MISS_CHANCE, 0.30);
const custom = new GameCore(Planet.defaultPlanet(), Math.random, 0.05);
assert.equal(custom.missChance, 0.05);
const clamped = new GameCore(Planet.defaultPlanet(), Math.random, 2);
assert.equal(clamped.missChance, 1);
// Planet.missChance stays the stage-3 Power formula, unused here.
const terraMiss = Planet.missChance(Planet.defaultPlanet());
assert.ok(Math.abs(terraMiss - 0.30) > 0.01, 'Terra Power miss is not the stage-2 30%');
const cinder = new GameCore(Planet.planetById('cinder'), Math.random);
assert.ok(Math.abs(cinder.missChance - 0.05) < 1e-12);
const aurel = new GameCore(Planet.planetById('aurel'), Math.random);
assert.ok(Math.abs(aurel.missChance - 0.60) < 1e-12);
});
it('fieldSnapshot lists every block for opponent miniatures', () =>
@@ -67,18 +67,21 @@ describe('Outgoing shots and incoming garbage', () => assert.equal(g.ingestGarbage(), null); assert.equal(g.ingestGarbage(), null); }); }); it('missChance is a parameter defaulting to 0.30, independent of planet Power', () => it('missChance defaults to the planet Power formula and can still be overridden', () => { { const g = makeGame({ noSpawn: true }); const g = makeGame({ noSpawn: true }); assert.equal(g.missChance, 0.30); const terraMiss = Planet.missChance(Planet.defaultPlanet()); assert.ok(Math.abs(g.missChance - terraMiss) < 1e-12); assert.ok(Math.abs(terraMiss - 0.30) > 0.01, 'Terra Power miss is not the old flat 30%'); assert.equal(GameCore.DEFAULT_MISS_CHANCE, 0.30); assert.equal(GameCore.DEFAULT_MISS_CHANCE, 0.30); const custom = new GameCore(Planet.defaultPlanet(), Math.random, 0.05); const custom = new GameCore(Planet.defaultPlanet(), Math.random, 0.05); assert.equal(custom.missChance, 0.05); assert.equal(custom.missChance, 0.05); const clamped = new GameCore(Planet.defaultPlanet(), Math.random, 2); const clamped = new GameCore(Planet.defaultPlanet(), Math.random, 2); assert.equal(clamped.missChance, 1); assert.equal(clamped.missChance, 1); // Planet.missChance stays the stage-3 Power formula, unused here. const cinder = new GameCore(Planet.planetById('cinder'), Math.random); const terraMiss = Planet.missChance(Planet.defaultPlanet()); assert.ok(Math.abs(cinder.missChance - 0.05) < 1e-12); assert.ok(Math.abs(terraMiss - 0.30) > 0.01, 'Terra Power miss is not the stage-2 30%'); const aurel = new GameCore(Planet.planetById('aurel'), Math.random); assert.ok(Math.abs(aurel.missChance - 0.60) < 1e-12); }); }); it('fieldSnapshot lists every block for opponent miniatures', () => it('fieldSnapshot lists every block for opponent miniatures', () =>@@ -202,7 +202,10 @@ def run_live(browser):
shot(page, "stage2-live-menu.png")
# Solo still works.
page.locator("#btn-play").click()
page.wait_for_timeout(800)
page.wait_for_timeout(600)
if page.locator("#planet-select").is_visible():
page.locator("#btn-planet-go").click()
page.wait_for_timeout(800)
playing = page.evaluate("() => app && app.mode === 'playing'")
check(playing, "live solo Play still starts a game")
shot(page, "stage2-live-solo.png")
@@ -202,7 +202,10 @@ def run_live(browser): shot(page, "stage2-live-menu.png") shot(page, "stage2-live-menu.png") # Solo still works. # Solo still works. page.locator("#btn-play").click() page.locator("#btn-play").click() page.wait_for_timeout(800) page.wait_for_timeout(600) if page.locator("#planet-select").is_visible(): page.locator("#btn-planet-go").click() page.wait_for_timeout(800) playing = page.evaluate("() => app && app.mode === 'playing'") playing = page.evaluate("() => app && app.mode === 'playing'") check(playing, "live solo Play still starts a game") check(playing, "live solo Play still starts a game") shot(page, "stage2-live-solo.png") shot(page, "stage2-live-solo.png")@@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""Stage 3: planet selection on desktop and mobile, plus two-player lobby picks."""
from __future__ import annotations
import os
import shutil
import socket
import subprocess
import sys
import tempfile
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"]
LIVE = "https://projects.timfalken.com/meteors/"
URL = None
FAILURES = []
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)")
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):
env = os.environ.copy()
env["METEORS_DATA_DIR"] = str(data)
return 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=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def open_picker(page):
page.goto(URL, wait_until="networkidle", timeout=25000)
page.wait_for_timeout(500)
page.locator("#btn-play").click()
page.locator("#planet-select").wait_for(state="visible", timeout=8000)
page.wait_for_timeout(300)
def cards(page):
return page.locator("#planet-grid .planet-card")
def run_desktop(browser):
print("\n======== desktop planet select ========")
ctx = browser.new_context(viewport={"width": 1280, "height": 900})
page = ctx.new_page()
open_picker(page)
n = cards(page).count()
check(n >= 8 and n <= 12, f"catalog has 8–12 cards (got {n})")
texts = [cards(page).nth(i).inner_text() for i in range(n)]
joined = "\n".join(texts)
for name in ("Terra", "Aurel", "Cinder", "Lunara", "Forge"):
check(name in joined, f"desktop grid lists {name}")
# Numeric stats, no long explanation — Terra mid values.
terra = next(t for t in texts if t.startswith("Terra"))
check("Terrans" in terra, "Terra people name")
check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 48%" in terra,
"Terra numeric stats on the card")
cinder = next(t for t in texts if t.startswith("Cinder"))
check("Cindari" in cinder and "Power 100%" in cinder and "g 19.62" in cinder,
"Cinder is the hardest (Power 100%)")
aurel = next(t for t in texts if t.startswith("Aurel"))
check("Aurelians" in aurel and "Power 0%" in aurel, "Aurel is the easiest (Power 0%)")
# Each card has 5 unique placeholder images.
imgs = page.locator("#planet-grid .planet-card").nth(0).locator("img")
check(imgs.count() == 5, "five color placeholders on a card")
shot(page, "stage3-planet-select-desktop.png")
# Pick Cinder and start.
page.locator('.planet-card[data-planet="cinder"]').click()
page.wait_for_timeout(200)
check("selected" in (page.locator('.planet-card[data-planet="cinder"]').get_attribute("class") or ""),
"Cinder card is selected")
page.locator("#btn-planet-go").click()
page.wait_for_function("() => app && app.mode === 'playing' && app.core", timeout=8000)
hud = page.evaluate("""() => ({
name: document.getElementById('planet-name').textContent,
stats: document.getElementById('planet-stats').textContent,
id: app.planet && app.planet.id,
miss: app.core && app.core.missChance,
power: Planet.power(app.planet)
})""")
print("HUD", hud)
check(hud["id"] == "cinder" and "Cinder" in hud["name"] and "Cindari" in hud["name"],
"HUD shows Cinder · Cindari")
check("Power 100%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers")
check(abs(hud["miss"] - 0.05) < 1e-9, "GameCore missChance is Cinder's 5%")
shot(page, "stage3-play-cinder-desktop.png")
ctx.close()
def run_mobile(browser):
print("\n======== mobile planet select ========")
ctx = browser.new_context(**MOBILE)
page = ctx.new_page()
open_picker(page)
n = cards(page).count()
check(n >= 8, f"mobile grid has the catalog (got {n})")
# Scroll to Cinder if needed, then pick it.
card = page.locator('.planet-card[data-planet="cinder"]')
card.scroll_into_view_if_needed()
page.wait_for_timeout(200)
shot(page, "stage3-planet-select-mobile.png")
card.click()
page.locator("#btn-planet-go").click()
page.wait_for_function("() => app && app.mode === 'playing' && app.planet && app.planet.id === 'cinder'", timeout=8000)
playing = page.evaluate("() => ({mode: app.mode, id: app.planet.id, w: window.innerWidth})")
print("mobile play", playing)
check(playing["mode"] == "playing" and playing["id"] == "cinder", "mobile starts Cinder after the picker")
shot(page, "stage3-play-cinder-mobile.png")
ctx.close()
def login(page, n):
# test login, then land on the game with online panel openable
page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="networkidle", timeout=20000)
page.wait_for_timeout(300)
page.goto(f"{URL}index.html?online=1", wait_until="networkidle", timeout=20000)
page.wait_for_timeout(600)
# If the online panel isn't auto-opened, click the button.
if not page.locator("#online-panel").is_visible():
if page.locator("#btn-online").is_visible():
page.locator("#btn-online").click()
page.wait_for_timeout(800)
def run_lobby(browser):
print("\n======== lobby planet picks (two contexts) ========")
c1 = browser.new_context(viewport={"width": 1280, "height": 900})
c2 = browser.new_context(viewport={"width": 1100, "height": 900})
p1 = c1.new_page()
p2 = c2.new_page()
login(p1, 1)
login(p2, 2)
# Host creates a lobby (default planet), then picks Aurel.
p1.locator("#btn-create").wait_for(state="visible", timeout=8000)
p1.locator("#btn-create").click()
p1.locator("#online-lobby").wait_for(state="visible", timeout=8000)
p1.wait_for_timeout(400)
p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').scroll_into_view_if_needed()
p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').click()
p1.wait_for_timeout(600)
code = p1.locator("#lobby-code").inner_text().strip()
check(len(code) == 4, f"lobby code {code}")
# Guest joins and picks Cinder.
p2.locator("#join-code").fill(code)
p2.locator("#btn-join").click()
p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
p2.wait_for_timeout(500)
p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').scroll_into_view_if_needed()
p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').click()
p2.wait_for_timeout(800)
# Poll so both see each other's pick.
p1.wait_for_timeout(1000)
p2.wait_for_timeout(400)
host_list = p1.locator("#lobby-players").inner_text()
guest_list = p2.locator("#lobby-players").inner_text()
print("host list:", host_list.replace("\n", " | "))
print("guest list:", guest_list.replace("\n", " | "))
check("Aurel" in host_list and "Cinder" in host_list, "host lobby shows both planet names")
check("Aurel" in guest_list and "Cinder" in guest_list, "guest lobby shows both planet names")
shot(p1, "stage3-lobby-planets-host.png")
shot(p2, "stage3-lobby-planets-guest.png")
# Ready and start; each plays their own planet.
p1.locator("#btn-ready").click()
p2.locator("#btn-ready").click()
p1.wait_for_timeout(800)
p1.locator("#btn-start").click()
p1.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
p2.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
ids = {
"host": p1.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
"guest": p2.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
}
print("match planets", ids)
check(ids["host"]["id"] == "aurel" and abs(ids["host"]["miss"] - 0.60) < 1e-9,
"host plays Aurel (60% miss from own Power)")
check(ids["guest"]["id"] == "cinder" and abs(ids["guest"]["miss"] - 0.05) < 1e-9,
"guest plays Cinder (5% miss from own Power)")
shot(p1, "stage3-game-aurel-host.png")
shot(p2, "stage3-game-cinder-guest.png")
c1.close()
c2.close()
def run_live(browser):
print("\n======== live site ========")
try:
ctx = browser.new_context(viewport={"width": 1280, "height": 900})
page = ctx.new_page()
page.goto(LIVE, wait_until="networkidle", timeout=25000)
page.wait_for_timeout(800)
if not page.locator("#btn-play").is_visible():
check(False, "live menu not reachable")
ctx.close()
return
page.locator("#btn-play").click()
page.wait_for_timeout(1000)
if page.locator("#planet-select").is_visible():
n = page.locator("#planet-grid .planet-card").count()
check(n >= 8, f"live planet grid has the catalog (got {n})")
shot(page, "stage3-live-planet-select.png")
page.locator('.planet-card[data-planet="terra"]').click()
page.locator("#btn-planet-go").click()
page.wait_for_timeout(800)
playing = page.evaluate("() => app && app.mode === 'playing' && app.planet && app.planet.id")
check(playing == "terra", "live solo starts on the chosen planet")
shot(page, "stage3-live-play-terra.png")
else:
# Not deployed yet: just note it; this check is re-run after deploy.
print("live planet select not present yet (expected before this deploy)")
shot(page, "stage3-live-planet-select.png")
ctx.close()
except Exception as e:
check(False, f"live site check: {e}")
def main():
global URL
if not Path(PHP).is_file():
print("php not found at", PHP)
return 1
port = free_port()
URL = f"http://127.0.0.1:{port}/"
data = Path(tempfile.mkdtemp(prefix="meteors-pw3-"))
print("PHP", PHP, "URL", URL)
proc = start_php(port, data)
try:
with sync_playwright() as p:
browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
run_desktop(browser)
run_mobile(browser)
run_lobby(browser)
run_live(browser)
browser.close()
finally:
proc.terminate()
try:
proc.wait(timeout=3)
except Exception:
proc.kill()
shutil.rmtree(data, ignore_errors=True)
print("\n======== summary ========")
if FAILURES:
print(f"{len(FAILURES)} failure(s):")
for f in FAILURES:
print(" -", f)
return 1
print("all stage-3 playwright checks passed")
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,296 @@#!/usr/bin/env python3"""Stage 3: planet selection on desktop and mobile, plus two-player lobby picks."""from __future__ import annotationsimport osimport shutilimport socketimport subprocessimport sysimport tempfilefrom 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"]LIVE = "https://projects.timfalken.com/meteors/"URL = NoneFAILURES = []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 conddef shot(page, name): path = SHOTS / name page.screenshot(path=str(path), full_page=False) print(f"wrote {path} ({path.stat().st_size} bytes)")def free_port(): s = socket.socket() s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] s.close() return portdef start_php(port, data): env = os.environ.copy() env["METEORS_DATA_DIR"] = str(data) return 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=subprocess.DEVNULL, stderr=subprocess.DEVNULL, )def open_picker(page): page.goto(URL, wait_until="networkidle", timeout=25000) page.wait_for_timeout(500) page.locator("#btn-play").click() page.locator("#planet-select").wait_for(state="visible", timeout=8000) page.wait_for_timeout(300)def cards(page): return page.locator("#planet-grid .planet-card")def run_desktop(browser): print("\n======== desktop planet select ========") ctx = browser.new_context(viewport={"width": 1280, "height": 900}) page = ctx.new_page() open_picker(page) n = cards(page).count() check(n >= 8 and n <= 12, f"catalog has 8–12 cards (got {n})") texts = [cards(page).nth(i).inner_text() for i in range(n)] joined = "\n".join(texts) for name in ("Terra", "Aurel", "Cinder", "Lunara", "Forge"): check(name in joined, f"desktop grid lists {name}") # Numeric stats, no long explanation — Terra mid values. terra = next(t for t in texts if t.startswith("Terra")) check("Terrans" in terra, "Terra people name") check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 48%" in terra, "Terra numeric stats on the card") cinder = next(t for t in texts if t.startswith("Cinder")) check("Cindari" in cinder and "Power 100%" in cinder and "g 19.62" in cinder, "Cinder is the hardest (Power 100%)") aurel = next(t for t in texts if t.startswith("Aurel")) check("Aurelians" in aurel and "Power 0%" in aurel, "Aurel is the easiest (Power 0%)") # Each card has 5 unique placeholder images. imgs = page.locator("#planet-grid .planet-card").nth(0).locator("img") check(imgs.count() == 5, "five color placeholders on a card") shot(page, "stage3-planet-select-desktop.png") # Pick Cinder and start. page.locator('.planet-card[data-planet="cinder"]').click() page.wait_for_timeout(200) check("selected" in (page.locator('.planet-card[data-planet="cinder"]').get_attribute("class") or ""), "Cinder card is selected") page.locator("#btn-planet-go").click() page.wait_for_function("() => app && app.mode === 'playing' && app.core", timeout=8000) hud = page.evaluate("""() => ({ name: document.getElementById('planet-name').textContent, stats: document.getElementById('planet-stats').textContent, id: app.planet && app.planet.id, miss: app.core && app.core.missChance, power: Planet.power(app.planet) })""") print("HUD", hud) check(hud["id"] == "cinder" and "Cinder" in hud["name"] and "Cindari" in hud["name"], "HUD shows Cinder · Cindari") check("Power 100%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers") check(abs(hud["miss"] - 0.05) < 1e-9, "GameCore missChance is Cinder's 5%") shot(page, "stage3-play-cinder-desktop.png") ctx.close()def run_mobile(browser): print("\n======== mobile planet select ========") ctx = browser.new_context(**MOBILE) page = ctx.new_page() open_picker(page) n = cards(page).count() check(n >= 8, f"mobile grid has the catalog (got {n})") # Scroll to Cinder if needed, then pick it. card = page.locator('.planet-card[data-planet="cinder"]') card.scroll_into_view_if_needed() page.wait_for_timeout(200) shot(page, "stage3-planet-select-mobile.png") card.click() page.locator("#btn-planet-go").click() page.wait_for_function("() => app && app.mode === 'playing' && app.planet && app.planet.id === 'cinder'", timeout=8000) playing = page.evaluate("() => ({mode: app.mode, id: app.planet.id, w: window.innerWidth})") print("mobile play", playing) check(playing["mode"] == "playing" and playing["id"] == "cinder", "mobile starts Cinder after the picker") shot(page, "stage3-play-cinder-mobile.png") ctx.close()def login(page, n): # test login, then land on the game with online panel openable page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="networkidle", timeout=20000) page.wait_for_timeout(300) page.goto(f"{URL}index.html?online=1", wait_until="networkidle", timeout=20000) page.wait_for_timeout(600) # If the online panel isn't auto-opened, click the button. if not page.locator("#online-panel").is_visible(): if page.locator("#btn-online").is_visible(): page.locator("#btn-online").click() page.wait_for_timeout(800)def run_lobby(browser): print("\n======== lobby planet picks (two contexts) ========") c1 = browser.new_context(viewport={"width": 1280, "height": 900}) c2 = browser.new_context(viewport={"width": 1100, "height": 900}) p1 = c1.new_page() p2 = c2.new_page() login(p1, 1) login(p2, 2) # Host creates a lobby (default planet), then picks Aurel. p1.locator("#btn-create").wait_for(state="visible", timeout=8000) p1.locator("#btn-create").click() p1.locator("#online-lobby").wait_for(state="visible", timeout=8000) p1.wait_for_timeout(400) p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').scroll_into_view_if_needed() p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').click() p1.wait_for_timeout(600) code = p1.locator("#lobby-code").inner_text().strip() check(len(code) == 4, f"lobby code {code}") # Guest joins and picks Cinder. p2.locator("#join-code").fill(code) p2.locator("#btn-join").click() p2.locator("#online-lobby").wait_for(state="visible", timeout=8000) p2.wait_for_timeout(500) p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').scroll_into_view_if_needed() p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').click() p2.wait_for_timeout(800) # Poll so both see each other's pick. p1.wait_for_timeout(1000) p2.wait_for_timeout(400) host_list = p1.locator("#lobby-players").inner_text() guest_list = p2.locator("#lobby-players").inner_text() print("host list:", host_list.replace("\n", " | ")) print("guest list:", guest_list.replace("\n", " | ")) check("Aurel" in host_list and "Cinder" in host_list, "host lobby shows both planet names") check("Aurel" in guest_list and "Cinder" in guest_list, "guest lobby shows both planet names") shot(p1, "stage3-lobby-planets-host.png") shot(p2, "stage3-lobby-planets-guest.png") # Ready and start; each plays their own planet. p1.locator("#btn-ready").click() p2.locator("#btn-ready").click() p1.wait_for_timeout(800) p1.locator("#btn-start").click() p1.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000) p2.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000) ids = { "host": p1.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"), "guest": p2.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"), } print("match planets", ids) check(ids["host"]["id"] == "aurel" and abs(ids["host"]["miss"] - 0.60) < 1e-9, "host plays Aurel (60% miss from own Power)") check(ids["guest"]["id"] == "cinder" and abs(ids["guest"]["miss"] - 0.05) < 1e-9, "guest plays Cinder (5% miss from own Power)") shot(p1, "stage3-game-aurel-host.png") shot(p2, "stage3-game-cinder-guest.png") c1.close() c2.close()def run_live(browser): print("\n======== live site ========") try: ctx = browser.new_context(viewport={"width": 1280, "height": 900}) page = ctx.new_page() page.goto(LIVE, wait_until="networkidle", timeout=25000) page.wait_for_timeout(800) if not page.locator("#btn-play").is_visible(): check(False, "live menu not reachable") ctx.close() return page.locator("#btn-play").click() page.wait_for_timeout(1000) if page.locator("#planet-select").is_visible(): n = page.locator("#planet-grid .planet-card").count() check(n >= 8, f"live planet grid has the catalog (got {n})") shot(page, "stage3-live-planet-select.png") page.locator('.planet-card[data-planet="terra"]').click() page.locator("#btn-planet-go").click() page.wait_for_timeout(800) playing = page.evaluate("() => app && app.mode === 'playing' && app.planet && app.planet.id") check(playing == "terra", "live solo starts on the chosen planet") shot(page, "stage3-live-play-terra.png") else: # Not deployed yet: just note it; this check is re-run after deploy. print("live planet select not present yet (expected before this deploy)") shot(page, "stage3-live-planet-select.png") ctx.close() except Exception as e: check(False, f"live site check: {e}")def main(): global URL if not Path(PHP).is_file(): print("php not found at", PHP) return 1 port = free_port() URL = f"http://127.0.0.1:{port}/" data = Path(tempfile.mkdtemp(prefix="meteors-pw3-")) print("PHP", PHP, "URL", URL) proc = start_php(port, data) try: with sync_playwright() as p: browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True) run_desktop(browser) run_mobile(browser) run_lobby(browser) run_live(browser) browser.close() finally: proc.terminate() try: proc.wait(timeout=3) except Exception: proc.kill() shutil.rmtree(data, ignore_errors=True) print("\n======== summary ========") if FAILURES: print(f"{len(FAILURES)} failure(s):") for f in FAILURES: print(" -", f) return 1 print("all stage-3 playwright checks passed") return 0if __name__ == "__main__": sys.exit(main())@@ -157,3 +157,47 @@ describe('Power and display values', () =>
assert.ok(Math.abs(d.gravity - 9.81) < 1e-9);
});
});
describe('Planet catalog', () =>
{
it('has 8–12 named worlds, each with a people name and five unique shapes', () =>
{
const all = Planet.allPlanets();
assert.ok(all.length >= 8 && all.length <= 12, 'catalog size ' + all.length);
const ids = new Set();
const images = new Set();
for (const p of all)
{
assert.ok(p.id && p.name && p.people, p.id);
assert.ok(!ids.has(p.id), 'duplicate id ' + p.id);
ids.add(p.id);
assert.equal(p.colors.length, 5);
const shapes = new Set(p.colors.map((c) => c.shape));
assert.equal(shapes.size, 5, p.id + ' shapes');
for (const c of p.colors)
{
assert.ok(c.image.startsWith('images/block-' + p.id + '-'), c.image);
assert.ok(!images.has(c.image), 'duplicate image ' + c.image);
images.add(c.image);
}
assert.ok(p.jumpsToClear >= 1 && p.jumpsToClear <= 4);
assert.ok(p.fallTime >= 1 && p.fallTime <= 5);
assert.ok(p.riseTime >= 0.5 && p.riseTime <= 3);
}
assert.ok(ids.has('terra'));
assert.equal(Planet.defaultPlanet().id, 'terra');
assert.equal(Planet.planetById('cinder').name, 'Cinder');
});
it('Aurel is the easiest (Power 0, 60% miss) and Cinder the hardest (Power 1, 5% miss)', () =>
{
const aurel = Planet.planetById('aurel');
const cinder = Planet.planetById('cinder');
assert.equal(Planet.power(aurel), 0);
assert.equal(Planet.missChance(aurel), 0.60);
assert.ok(Math.abs(Planet.power(cinder) - 1) < 1e-12);
assert.ok(Math.abs(Planet.missChance(cinder) - 0.05) < 1e-12);
assert.equal(Planet.displayValues(aurel).power, 0);
assert.equal(Planet.displayValues(cinder).power, 100);
});
});
@@ -157,3 +157,47 @@ describe('Power and display values', () => assert.ok(Math.abs(d.gravity - 9.81) < 1e-9); assert.ok(Math.abs(d.gravity - 9.81) < 1e-9); }); });});});describe('Planet catalog', () =>{ it('has 8–12 named worlds, each with a people name and five unique shapes', () => { const all = Planet.allPlanets(); assert.ok(all.length >= 8 && all.length <= 12, 'catalog size ' + all.length); const ids = new Set(); const images = new Set(); for (const p of all) { assert.ok(p.id && p.name && p.people, p.id); assert.ok(!ids.has(p.id), 'duplicate id ' + p.id); ids.add(p.id); assert.equal(p.colors.length, 5); const shapes = new Set(p.colors.map((c) => c.shape)); assert.equal(shapes.size, 5, p.id + ' shapes'); for (const c of p.colors) { assert.ok(c.image.startsWith('images/block-' + p.id + '-'), c.image); assert.ok(!images.has(c.image), 'duplicate image ' + c.image); images.add(c.image); } assert.ok(p.jumpsToClear >= 1 && p.jumpsToClear <= 4); assert.ok(p.fallTime >= 1 && p.fallTime <= 5); assert.ok(p.riseTime >= 0.5 && p.riseTime <= 3); } assert.ok(ids.has('terra')); assert.equal(Planet.defaultPlanet().id, 'terra'); assert.equal(Planet.planetById('cinder').name, 'Cinder'); }); it('Aurel is the easiest (Power 0, 60% miss) and Cinder the hardest (Power 1, 5% miss)', () => { const aurel = Planet.planetById('aurel'); const cinder = Planet.planetById('cinder'); assert.equal(Planet.power(aurel), 0); assert.equal(Planet.missChance(aurel), 0.60); assert.ok(Math.abs(Planet.power(cinder) - 1) < 1e-12); assert.ok(Math.abs(Planet.missChance(cinder) - 0.05) < 1e-12); assert.equal(Planet.displayValues(aurel).power, 0); assert.equal(Planet.displayValues(cinder).power, 100); });});@@ -186,10 +186,20 @@ def start_play(page):
steps=1,
)
page.wait_for_timeout(400)
# Stage 3: Spelen opens the planet picker first.
if page.evaluate("() => app && app.mode") == "planet-select":
go = page.locator("#btn-planet-go")
go.wait_for(state="visible", timeout=5000)
go.click()
page.wait_for_timeout(400)
# Fallback if the touch didn't start the game (desktop-like click path).
if page.evaluate("() => app.mode") != "playing":
btn.click()
page.wait_for_timeout(400)
if page.locator("#btn-play").is_visible():
btn.click()
page.wait_for_timeout(400)
if page.locator("#btn-planet-go").is_visible():
page.locator("#btn-planet-go").click()
page.wait_for_timeout(400)
page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)
page.wait_for_selector("canvas", state="visible", timeout=5000)
return cdp
@@ -186,10 +186,20 @@ def start_play(page): steps=1, steps=1, ) ) page.wait_for_timeout(400) page.wait_for_timeout(400) # Stage 3: Spelen opens the planet picker first. if page.evaluate("() => app && app.mode") == "planet-select": go = page.locator("#btn-planet-go") go.wait_for(state="visible", timeout=5000) go.click() page.wait_for_timeout(400) # Fallback if the touch didn't start the game (desktop-like click path). # Fallback if the touch didn't start the game (desktop-like click path). if page.evaluate("() => app.mode") != "playing": if page.evaluate("() => app.mode") != "playing": btn.click() if page.locator("#btn-play").is_visible(): page.wait_for_timeout(400) btn.click() page.wait_for_timeout(400) if page.locator("#btn-planet-go").is_visible(): page.locator("#btn-planet-go").click() page.wait_for_timeout(400) page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000) page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000) page.wait_for_selector("canvas", state="visible", timeout=5000) page.wait_for_selector("canvas", state="visible", timeout=5000) return cdp return cdp