BlueGit

projects-timfalken-com meteors

Merge branch 'feature/stage3-planets'

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
82378f35b6d65a91ad555b7e5bc1473112493d8d
Pipeline
Passed
82 files changed +2037 −133
README.md +20 −2
@@ -61,6 +61,7 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
61 61 | `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |
62 62 | `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |
63 63 | `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
64 | `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |
64 65 | `docs/ASSUMPTIONS.md` | Ingevulde aannames waar de specificatie ruimte liet |
65 66 | `src/build.sh` | Concateneert de bronnen naar `build/game.js` en kopieert de PHP-API naar `build/` |
66 67 | `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
69 70
70 71 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`.
71 72
73
74 ## Planeten (stage 3)
75
76 Voor je gaat spelen — solo en in de lobby — kies je een **veld**. Elk veld
77 is een planeet met een volk, vijf eigen kleuren/vormen, en drie natuurwetten:
78
79 - zwaartekracht — hoe hoog de eerste sprong is (`g`, m/s²)
80 - luchtweerstand — hoe snel blokjes weer vallen (`d`)
81 - massa — hoe snel de sprong omhoog gaat (`F`, newton)
82
83 Power is het gemiddelde van die drie, als percentage. Hoe hoger de Power,
84 hoe kleiner de kans dat een afgeschoten blokje een andere speler mist.
85 In een online wedstrijd telt **jouw** planeet voor de blokjes die jij
86 verstuurt. De twaalf werelden en hun getallen staan in
87 `server/lib/planets.json`. De blokplaatjes zijn unieke placeholders
88 (`build/images/block-{planeet}-{kleur}.png`); Tim kan ze zelf vervangen.
89
72 90 ## Deploy
73 91
74 92 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.
86 104 Je eigen veld is het hoofdspel; miniaturen van de tegenstanders staan erboven.
87 105 Blokjes die van je veld afschieten kiezen een willekeurige andere (nog niet
88 106 uitgeschakelde) speler en vliegen daar in een korte tween naartoe (draaien en
89 krimpen). Met 30 % kans (`missChance`, een parameter; in stage 3 wordt dit
90 `Planet.missChance` via Power) missen ze en verdwijnen ze in de verte. Een raak
107 krimpen). De kans dat ze missen komt uit de **Power van jouw planeet** (60 % op het
108 makkelijkste veld, 5 % op het moeilijkste); dat gooit de server. Een raak
91 109 schot komt bij de ander aan als een vallend donkergrijs blokje dat na 3 seconden
92 110 op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschouwer
93 111 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
61| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |
61| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween, online-lobby |
62| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |
62| `src/online.js` | API-client, polling, opponent-miniaturen, vlucht-tweens van afgeschoten blokjes |
63| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
63| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
64| `server/lib/planets.json` | Catalogus van 12 planeten (JS en PHP delen dit bestand) |
64| `docs/ASSUMPTIONS.md` | Ingevulde aannames waar de specificatie ruimte liet |
65| `docs/ASSUMPTIONS.md` | Ingevulde aannames waar de specificatie ruimte liet |
65| `src/build.sh` | Concateneert de bronnen naar `build/game.js` en kopieert de PHP-API naar `build/` |
66| `src/build.sh` | Concateneert de bronnen naar `build/game.js` en kopieert de PHP-API naar `build/` |
66| `build/` | Speelbare output: `index.html`, `style.css`, `framework.js`, `game.js`, `images/`, PHP-API |
67| `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
69
70
70Sprongfysica 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`.
71Sprongfysica 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`.
71
72
73
74## Planeten (stage 3)
75
76Voor je gaat spelen — solo en in de lobby — kies je een **veld**. Elk veld
77is een planeet met een volk, vijf eigen kleuren/vormen, en drie natuurwetten:
78
79- zwaartekracht — hoe hoog de eerste sprong is (`g`, m/s²)
80- luchtweerstand — hoe snel blokjes weer vallen (`d`)
81- massa — hoe snel de sprong omhoog gaat (`F`, newton)
82
83Power is het gemiddelde van die drie, als percentage. Hoe hoger de Power,
84hoe kleiner de kans dat een afgeschoten blokje een andere speler mist.
85In een online wedstrijd telt **jouw** planeet voor de blokjes die jij
86verstuurt. De twaalf werelden en hun getallen staan in
87`server/lib/planets.json`. De blokplaatjes zijn unieke placeholders
88(`build/images/block-{planeet}-{kleur}.png`); Tim kan ze zelf vervangen.
89
72## Deploy
90## Deploy
73
91
74BlueGit 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.
92BlueGit 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.
86Je eigen veld is het hoofdspel; miniaturen van de tegenstanders staan erboven.
104Je eigen veld is het hoofdspel; miniaturen van de tegenstanders staan erboven.
87Blokjes die van je veld afschieten kiezen een willekeurige andere (nog niet
105Blokjes die van je veld afschieten kiezen een willekeurige andere (nog niet
88uitgeschakelde) speler en vliegen daar in een korte tween naartoe (draaien en
106uitgeschakelde) speler en vliegen daar in een korte tween naartoe (draaien en
89krimpen). Met 30 % kans (`missChance`, een parameter; in stage 3 wordt dit
107krimpen). De kans dat ze missen komt uit de **Power van jouw planeet** (60 % op het
90`Planet.missChance` via Power) missen ze en verdwijnen ze in de verte. Een raak
108makkelijkste veld, 5 % op het moeilijkste); dat gooit de server. Een raak
91schot komt bij de ander aan als een vallend donkergrijs blokje dat na 3 seconden
109schot komt bij de ander aan als een vallend donkergrijs blokje dat na 3 seconden
92op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschouwer
110op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschouwer
93en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
111en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
blue-ci-cd.yml +6 −0
@@ -53,6 +53,10 @@ build_game:
53 53 - test -f build/.htaccess
54 54 - test -f build/lib/bootstrap.php
55 55 - test -f build/lib/Store.php
56 - test -f build/lib/Planets.php
57 - test -f build/lib/planets.json
58 - test -f build/images/block-terra-ember.png
59 - test -f build/images/block-cinder-magma.png
56 60 - test -f build/data/.htaccess
57 61 - test ! -f build/data/config.php
58 62 - test ! -e build/data/*.sqlite
@@ -84,6 +88,8 @@ build_game:
84 88 - build/.htaccess
85 89 - build/lib/bootstrap.php
86 90 - build/lib/Store.php
91 - build/lib/Planets.php
92 - build/lib/planets.json
87 93 - build/data/.htaccess
88 94 expire_in: 7d
89 95
@@ -53,6 +53,10 @@ build_game:
53 - test -f build/.htaccess
53 - test -f build/.htaccess
54 - test -f build/lib/bootstrap.php
54 - test -f build/lib/bootstrap.php
55 - test -f build/lib/Store.php
55 - test -f build/lib/Store.php
56 - test -f build/lib/Planets.php
57 - test -f build/lib/planets.json
58 - test -f build/images/block-terra-ember.png
59 - test -f build/images/block-cinder-magma.png
56 - test -f build/data/.htaccess
60 - test -f build/data/.htaccess
57 - test ! -f build/data/config.php
61 - test ! -f build/data/config.php
58 - test ! -e build/data/*.sqlite
62 - test ! -e build/data/*.sqlite
@@ -84,6 +88,8 @@ build_game:
84 - build/.htaccess
88 - build/.htaccess
85 - build/lib/bootstrap.php
89 - build/lib/bootstrap.php
86 - build/lib/Store.php
90 - build/lib/Store.php
91 - build/lib/Planets.php
92 - build/lib/planets.json
87 - build/data/.htaccess
93 - build/data/.htaccess
88 expire_in: 7d
94 expire_in: 7d
89
95
build/game.js +503 −48
@@ -2,6 +2,191 @@
2 2 * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
3 3 * Built by src/build.sh from the sources in src/.
4 4 */
5 var PLANET_CATALOG = {
6 "planets": [
7 {
8 "id": "terra",
9 "name": "Terra",
10 "people": "Terrans",
11 "jumpsToClear": 2,
12 "fallTime": 3,
13 "riseTime": 1.5,
14 "colors": [
15 {"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"},
16 {"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"},
17 {"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"},
18 {"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"},
19 {"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"}
20 ]
21 },
22 {
23 "id": "aurel",
24 "name": "Aurel",
25 "people": "Aurelians",
26 "jumpsToClear": 1,
27 "fallTime": 5,
28 "riseTime": 3,
29 "colors": [
30 {"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"},
31 {"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"},
32 {"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"},
33 {"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"},
34 {"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"}
35 ]
36 },
37 {
38 "id": "cinder",
39 "name": "Cinder",
40 "people": "Cindari",
41 "jumpsToClear": 4,
42 "fallTime": 1,
43 "riseTime": 0.5,
44 "colors": [
45 {"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"},
46 {"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"},
47 {"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"},
48 {"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"},
49 {"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"}
50 ]
51 },
52 {
53 "id": "lunara",
54 "name": "Lunara",
55 "people": "Lunarites",
56 "jumpsToClear": 1,
57 "fallTime": 2,
58 "riseTime": 1.2,
59 "colors": [
60 {"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"},
61 {"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"},
62 {"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"},
63 {"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"},
64 {"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"}
65 ]
66 },
67 {
68 "id": "mire",
69 "name": "Mire",
70 "people": "Mirians",
71 "jumpsToClear": 2,
72 "fallTime": 5,
73 "riseTime": 2.5,
74 "colors": [
75 {"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"},
76 {"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"},
77 {"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"},
78 {"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"},
79 {"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"}
80 ]
81 },
82 {
83 "id": "galeon",
84 "name": "Galeon",
85 "people": "Galeoni",
86 "jumpsToClear": 3,
87 "fallTime": 1,
88 "riseTime": 1.8,
89 "colors": [
90 {"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"},
91 {"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"},
92 {"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"},
93 {"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"},
94 {"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"}
95 ]
96 },
97 {
98 "id": "obsid",
99 "name": "Obsid",
100 "people": "Obsidians",
101 "jumpsToClear": 4,
102 "fallTime": 3.5,
103 "riseTime": 2.2,
104 "colors": [
105 {"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"},
106 {"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"},
107 {"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"},
108 {"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"},
109 {"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"}
110 ]
111 },
112 {
113 "id": "wisp",
114 "name": "Wisp",
115 "people": "Wisplings",
116 "jumpsToClear": 2,
117 "fallTime": 3.5,
118 "riseTime": 0.5,
119 "colors": [
120 {"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"},
121 {"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"},
122 {"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"},
123 {"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"},
124 {"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"}
125 ]
126 },
127 {
128 "id": "thorn",
129 "name": "Thorn",
130 "people": "Thornfolk",
131 "jumpsToClear": 3,
132 "fallTime": 2,
133 "riseTime": 1.0,
134 "colors": [
135 {"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"},
136 {"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"},
137 {"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"},
138 {"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"},
139 {"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"}
140 ]
141 },
142 {
143 "id": "zephyr",
144 "name": "Zephyr",
145 "people": "Zephyrites",
146 "jumpsToClear": 1,
147 "fallTime": 1.2,
148 "riseTime": 2.8,
149 "colors": [
150 {"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"},
151 {"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"},
152 {"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"},
153 {"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"},
154 {"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"}
155 ]
156 },
157 {
158 "id": "frore",
159 "name": "Frore",
160 "people": "Frorians",
161 "jumpsToClear": 3,
162 "fallTime": 4.5,
163 "riseTime": 0.8,
164 "colors": [
165 {"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"},
166 {"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"},
167 {"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"},
168 {"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"},
169 {"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"}
170 ]
171 },
172 {
173 "id": "forge",
174 "name": "Forge",
175 "people": "Forgelings",
176 "jumpsToClear": 4,
177 "fallTime": 2,
178 "riseTime": 1.5,
179 "colors": [
180 {"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"},
181 {"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"},
182 {"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"},
183 {"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"},
184 {"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"}
185 ]
186 }
187 ]
188 }
189 ;
5 190
6 191 /*
7 192 * Start File:
@@ -114,6 +299,7 @@ function createPlanet (opts)
114 299 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
115 300 var colors = opts.colors || defaultColors();
116 301 var planet = {
302 id: opts.id || null,
117 303 name: opts.name || 'Terra',
118 304 people: opts.people || 'Terrans',
119 305 jumpsToClear: jumpsToClear,
@@ -133,15 +319,82 @@ function createPlanet (opts)
133 319 return planet;
134 320 }
135 321
136 function defaultPlanet ()
322 function loadCatalog ()
323 {
324 if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
325 { return PLANET_CATALOG; }
326 if (typeof require !== 'undefined')
327 {
328 try
329 { return require('../server/lib/planets.json'); }
330 catch (e) {}
331 }
332 return { planets: [] };
333 }
334
335 function planetFromData (data)
137 336 {
138 return createPlanet({
139 name: 'Terra',
140 people: 'Terrans',
141 jumpsToClear: 2,
142 fallTime: 3,
143 riseTime: 1.5
337 var planet = createPlanet({
338 name: data.name,
339 people: data.people,
340 jumpsToClear: data.jumpsToClear,
341 fallTime: data.fallTime,
342 riseTime: data.riseTime,
343 colors: data.colors
144 344 });
345 planet.id = data.id;
346 return planet;
347 }
348
349 function allPlanets ()
350 {
351 var raw = loadCatalog().planets || [];
352 var out = [];
353 for (var i = 0; i < raw.length; i++)
354 { out.push(planetFromData(raw[i])); }
355 if (out.length === 0)
356 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
357 return out;
358 }
359
360 function planetById (id)
361 {
362 var all = allPlanets();
363 for (var i = 0; i < all.length; i++)
364 {
365 if (all[i].id === id)
366 { return all[i]; }
367 }
368 return defaultPlanet();
369 }
370
371 function defaultPlanet ()
372 {
373 var all = allPlanets();
374 for (var i = 0; i < all.length; i++)
375 {
376 if (all[i].id === 'terra')
377 { return all[i]; }
378 }
379 return all[0];
380 }
381
382 function formatStats (planet)
383 {
384 var d = displayValues(planet);
385 return 'g ' + d.gravity.toFixed(2)
386 + ' d ' + d.density.toFixed(2)
387 + ' F ' + Math.round(d.newtons) + ' N'
388 + ' Power ' + d.power + '%';
389 }
390
391 function spriteKey (planet, colorIndex)
392 {
393 var colors = planet && planet.colors;
394 var c = colors && colors[colorIndex];
395 if (!c)
396 { return 'gray'; }
397 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
145 398 }
146 399
147 400 /**
@@ -221,6 +474,11 @@ var Planet = {
221 474 createPlanet: createPlanet,
222 475 defaultPlanet: defaultPlanet,
223 476 defaultColors: defaultColors,
477 allPlanets: allPlanets,
478 planetById: planetById,
479 planetFromData: planetFromData,
480 formatStats: formatStats,
481 spriteKey: spriteKey,
224 482 jumpHeight: jumpHeight,
225 483 launchVelocity: launchVelocity,
226 484 launchDeceleration: launchDeceleration,
@@ -453,6 +711,9 @@ function optsMissChance (args)
453 711 // GameCore(planet, rng, missChance) — third arg is optional.
454 712 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
455 713 { return Math.max(0, Math.min(1, args[2])); }
714 var planet = args[0];
715 if (planet && typeof PlanetMod.missChance === 'function')
716 { return PlanetMod.missChance(planet); }
456 717 return GameCore.DEFAULT_MISS_CHANCE;
457 718 }
458 719
@@ -2400,14 +2661,25 @@ Online.testLogin = function (who)
2400 2661 return this.request('test_login', { user: who });
2401 2662 };
2402 2663
2403 Online.createLobby = function ()
2664 Online.createLobby = function (planetId)
2665 {
2666 return this.request('lobby_create', {
2667 miss_chance: this.DEFAULT_MISS_CHANCE,
2668 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
2669 });
2670 };
2671
2672 Online.joinLobby = function (code, planetId)
2404 2673 {
2405 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
2674 return this.request('lobby_join', {
2675 code: code,
2676 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
2677 });
2406 2678 };
2407 2679
2408 Online.joinLobby = function (code)
2680 Online.setPlanet = function (planetId)
2409 2681 {
2410 return this.request('lobby_join', { code: code });
2682 return this.request('lobby_set_planet', { planet_id: planetId });
2411 2683 };
2412 2684
2413 2685 Online.leaveLobby = function ()
@@ -2574,7 +2846,7 @@ Online.renderMinis = function (container)
2574 2846 el.querySelector('.mini-meta').textContent = p.eliminated
2575 2847 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
2576 2848 : ('Punten ' + (p.score || 0));
2577 this._drawMini(el.querySelector('canvas'), p.snapshot);
2849 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
2578 2850 }
2579 2851 for (var id in existing)
2580 2852 {
@@ -2585,7 +2857,15 @@ Online.renderMinis = function (container)
2585 2857
2586 2858 var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
2587 2859
2588 Online._drawMini = function (canvas, snapshot)
2860 function miniColor (planet, color)
2861 {
2862 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
2863 { return planet.colors[color].hex; }
2864 return MINI_COLORS[color] || '#888';
2865 }
2866
2867
2868 Online._drawMini = function (canvas, snapshot, planet)
2589 2869 {
2590 2870 if (!canvas)
2591 2871 { return; }
@@ -2625,7 +2905,7 @@ Online._drawMini = function (canvas, snapshot)
2625 2905 else if (b.color < 0)
2626 2906 { ctx.fillStyle = '#5a5d66'; }
2627 2907 else
2628 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
2908 { ctx.fillStyle = miniColor(planet, b.color); }
2629 2909 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
2630 2910 }
2631 2911 };
@@ -2637,12 +2917,16 @@ Online.miniElement = function (playerId)
2637 2917
2638 2918 /* ---------- flight tweens ------------------------------------------ */
2639 2919
2640 function colorSpriteUrl (color)
2920 function colorSpriteUrl (color, planetId)
2641 2921 {
2642 2922 if (color < 0)
2643 2923 { return 'images/block-gray.png'; }
2644 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
2645 return 'images/block-' + (names[color] || 'gray') + '.png';
2924 var planet = null;
2925 if (typeof Planet !== 'undefined')
2926 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
2927 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
2928 { return planet.colors[color].image; }
2929 return 'images/block-gray.png';
2646 2930 }
2647 2931
2648 2932 /**
@@ -2824,20 +3108,37 @@ if (typeof module !== 'undefined' && module.exports)
2824 3108 * through Online (src/online.js) and the same GameCore.
2825 3109 */
2826 3110
2827 var IMAGES = [
2828 { name: 'ember', url: 'images/block-ember.png' },
2829 { name: 'aqua', url: 'images/block-aqua.png' },
2830 { name: 'leaf', url: 'images/block-leaf.png' },
2831 { name: 'sun', url: 'images/block-sun.png' },
2832 { name: 'orchid', url: 'images/block-orchid.png' },
2833 { name: 'gray', url: 'images/block-gray.png' },
2834 { name: 'locked', url: 'images/block-locked.png' },
2835 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
2836 { name: 'cell', url: 'images/cell.png' },
2837 { name: 'pixel', url: 'images/pixel.png' }
2838 ];
2839
2840 var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
3111 function planetImages ()
3112 {
3113 var list = [
3114 { name: 'gray', url: 'images/block-gray.png' },
3115 { name: 'locked', url: 'images/block-locked.png' },
3116 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
3117 { name: 'cell', url: 'images/cell.png' },
3118 { name: 'pixel', url: 'images/pixel.png' },
3119 // Keep the original Terra placeholders as aliases (Tim may still have them).
3120 { name: 'ember', url: 'images/block-ember.png' },
3121 { name: 'aqua', url: 'images/block-aqua.png' },
3122 { name: 'leaf', url: 'images/block-leaf.png' },
3123 { name: 'sun', url: 'images/block-sun.png' },
3124 { name: 'orchid', url: 'images/block-orchid.png' }
3125 ];
3126 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
3127 for (var i = 0; i < planets.length; i++)
3128 {
3129 var pl = planets[i];
3130 for (var c = 0; c < pl.colors.length; c++)
3131 {
3132 list.push({
3133 name: Planet.spriteKey(pl, c),
3134 url: pl.colors[c].image
3135 });
3136 }
3137 }
3138 return list;
3139 }
3140
3141 var IMAGES = planetImages();
2841 3142 var GAME_OVER_DELAY = 2;
2842 3143
2843 3144 var game = new Game();
@@ -2863,7 +3164,9 @@ var app = {
2863 3164 online: false,
2864 3165 eliminatedReported: false,
2865 3166 spectating: false,
2866 miniH: 0
3167 miniH: 0,
3168 selectedPlanetId: 'terra',
3169 planetSelectContext: 'solo'
2867 3170 };
2868 3171
2869 3172 window.onload = function ()
@@ -2888,13 +3191,15 @@ window.onload = function ()
2888 3191 });
2889 3192
2890 3193 bindOnlineUi();
3194 bindPlanetSelect();
3195 restoreSelectedPlanet();
2891 3196 };
2892 3197
2893 3198 function onPlay ()
2894 3199 {
2895 3200 if (app.mode === 'playing')
2896 3201 { return; }
2897 startPlay();
3202 openPlanetSelect('solo');
2898 3203 }
2899 3204
2900 3205 function startPlay (opts)
@@ -2905,14 +3210,15 @@ function startPlay (opts)
2905 3210 hideEl('online-panel');
2906 3211 hideEl('spectator');
2907 3212 hideEl('podium');
3213 hideEl('planet-select');
2908 3214 showEl('hud');
2909 3215
2910 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
3216 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
3217 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
2911 3218 var miss = opts.missChance;
2912 if (typeof miss === 'number' && isFinite(miss))
2913 { app.core = new GameCore(app.planet, Math.random, miss); }
2914 else
2915 { app.core = new GameCore(app.planet, Math.random); }
3219 if (typeof miss !== 'number' || !isFinite(miss))
3220 { miss = planetMod.missChance(app.planet); }
3221 app.core = new GameCore(app.planet, Math.random, miss);
2916 3222 app.mode = 'playing';
2917 3223 app.online = !!opts.online;
2918 3224 app.gameOverShown = false;
@@ -2981,6 +3287,7 @@ function returnToMenu ()
2981 3287 teardownPlay();
2982 3288 app.mode = 'menu';
2983 3289 app.online = false;
3290 hideEl('planet-select');
2984 3291 showEl('menu');
2985 3292 var last = document.getElementById('last-score');
2986 3293 if (app.lastScore > 0)
@@ -3064,7 +3371,8 @@ function spriteFor (block)
3064 3371 { return game.images.locked; }
3065 3372 if (block.color < 0)
3066 3373 { return game.images.gray; }
3067 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
3374 var key = Planet.spriteKey(app.planet, block.color);
3375 return game.images[key] || game.images.gray;
3068 3376 }
3069 3377
3070 3378 function syncSprites ()
@@ -3223,10 +3531,7 @@ function refreshHud ()
3223 3531 document.getElementById('score').textContent = String(app.core.score);
3224 3532 var planet = app.planet;
3225 3533 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
3226 var d = Planet.displayValues(planet);
3227 document.getElementById('planet-stats').textContent =
3228 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
3229 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
3534 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
3230 3535 }
3231 3536
3232 3537 function makeManager ()
@@ -3504,10 +3809,11 @@ function startOnlineMatch ()
3504 3809 {
3505 3810 if (app.mode === 'playing' && app.online)
3506 3811 { return; }
3507 var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
3508 ? Online.lobby.miss_chance
3509 : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
3510 startPlay({ online: true, missChance: miss });
3812 var planet = Planet.planetById(selectedPlanetId());
3813 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
3814 if (me && me.planet && me.planet.id)
3815 { planet = Planet.planetById(me.planet.id); }
3816 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
3511 3817 if (typeof Online !== 'undefined')
3512 3818 { Online.startPolling(onlinePayload); }
3513 3819 }
@@ -3664,6 +3970,7 @@ function openOnlinePanel ()
3664 3970 hideEl('game-over');
3665 3971 hideEl('podium');
3666 3972 hideEl('spectator');
3973 hideEl('planet-select');
3667 3974 showEl('online-panel');
3668 3975 app.mode = 'online';
3669 3976 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
@@ -3765,10 +4072,14 @@ function renderOnline ()
3765 4072 { li.classList.add('you'); }
3766 4073 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
3767 4074 var state = p.ready ? 'Gereed' : 'Wacht…';
3768 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
4075 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
4076 li.innerHTML = '<span>' + escapeText(label)
4077 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
4078 + '</span><span class="'
3769 4079 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
3770 4080 list.appendChild(li);
3771 4081 }
4082 renderPlanetGrid('lobby-planet-grid', true);
3772 4083 var me = Online.mePlayer();
3773 4084 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
3774 4085 var start = document.getElementById('btn-start');
@@ -3802,6 +4113,150 @@ function escapeText (s)
3802 4113 .replace(/"/g, '&quot;');
3803 4114 }
3804 4115
4116
4117 function selectedPlanetId ()
4118 {
4119 if (app.selectedPlanetId)
4120 { return app.selectedPlanetId; }
4121 return 'terra';
4122 }
4123
4124 function restoreSelectedPlanet ()
4125 {
4126 var id = 'terra';
4127 try
4128 { id = localStorage.getItem('meteors-planet') || 'terra'; }
4129 catch (e) {}
4130 setSelectedPlanet(id, true);
4131 }
4132
4133 function setSelectedPlanet (id, silent)
4134 {
4135 var all = Planet.allPlanets();
4136 var found = null;
4137 for (var i = 0; i < all.length; i++)
4138 {
4139 if (all[i].id === id)
4140 { found = all[i]; break; }
4141 }
4142 if (!found)
4143 { found = Planet.defaultPlanet(); }
4144 app.selectedPlanetId = found.id;
4145 try
4146 { localStorage.setItem('meteors-planet', found.id); }
4147 catch (e) {}
4148 if (!silent)
4149 {
4150 var grid = document.getElementById('planet-grid');
4151 if (grid && !grid.hidden && grid.children.length)
4152 { renderPlanetGrid('planet-grid', false); }
4153 var lobby = document.getElementById('lobby-planet-grid');
4154 if (lobby && lobby.children.length)
4155 { renderPlanetGrid('lobby-planet-grid', true); }
4156 }
4157 return found;
4158 }
4159
4160 function openPlanetSelect (context)
4161 {
4162 if (app.mode === 'playing')
4163 { return; }
4164 app.planetSelectContext = context || 'solo';
4165 app.mode = 'planet-select';
4166 hideEl('menu');
4167 hideEl('online-panel');
4168 hideEl('game-over');
4169 showEl('planet-select');
4170 renderPlanetGrid('planet-grid', false);
4171 var go = document.getElementById('btn-planet-go');
4172 if (go)
4173 { go.textContent = 'Spelen'; }
4174 }
4175
4176 function renderPlanetGrid (containerId, compact)
4177 {
4178 var grid = document.getElementById(containerId);
4179 if (!grid)
4180 { return; }
4181 var current = selectedPlanetId();
4182 var all = Planet.allPlanets();
4183 grid.innerHTML = '';
4184 if (compact)
4185 { grid.classList.add('compact'); }
4186 for (var i = 0; i < all.length; i++)
4187 {
4188 var pl = all[i];
4189 var btn = document.createElement('button');
4190 btn.type = 'button';
4191 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
4192 btn.setAttribute('role', 'listitem');
4193 btn.dataset.planet = pl.id;
4194 var swatches = '';
4195 for (var c = 0; c < pl.colors.length; c++)
4196 {
4197 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
4198 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
4199 }
4200 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
4201 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
4202 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
4203 + '<div class="planet-swatches">' + swatches + '</div>';
4204 btn.addEventListener('click', (function (id, isCompact)
4205 {
4206 return function ()
4207 { onPlanetPicked(id, isCompact); };
4208 })(pl.id, !!compact));
4209 grid.appendChild(btn);
4210 }
4211 }
4212
4213 function onPlanetPicked (id, fromLobby)
4214 {
4215 setSelectedPlanet(id);
4216 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
4217 {
4218 Online.setPlanet(id).then(function ()
4219 { renderOnline(); });
4220 }
4221 else
4222 {
4223 renderPlanetGrid('planet-grid', false);
4224 }
4225 }
4226
4227 function confirmPlanetSelect ()
4228 {
4229 var planet = setSelectedPlanet(selectedPlanetId());
4230 hideEl('planet-select');
4231 if (app.planetSelectContext === 'online')
4232 {
4233 openOnlinePanel();
4234 return;
4235 }
4236 startPlay({ planet: planet });
4237 }
4238
4239 function cancelPlanetSelect ()
4240 {
4241 hideEl('planet-select');
4242 app.mode = 'menu';
4243 showEl('menu');
4244 }
4245
4246 function bindPlanetSelect ()
4247 {
4248 var go = document.getElementById('btn-planet-go');
4249 var back = document.getElementById('btn-planet-back');
4250 if (go)
4251 {
4252 go.addEventListener('click', confirmPlanetSelect);
4253 }
4254 if (back)
4255 {
4256 back.addEventListener('click', cancelPlanetSelect);
4257 }
4258 }
4259
3805 4260 /*
3806 4261 * End File:
3807 4262 * /workspace/meteors/src/main.js
@@ -2,6 +2,191 @@
2 * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
2 * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.
3 * Built by src/build.sh from the sources in src/.
3 * Built by src/build.sh from the sources in src/.
4 */
4 */
5var PLANET_CATALOG = {
6 "planets": [
7 {
8 "id": "terra",
9 "name": "Terra",
10 "people": "Terrans",
11 "jumpsToClear": 2,
12 "fallTime": 3,
13 "riseTime": 1.5,
14 "colors": [
15 {"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"},
16 {"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"},
17 {"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"},
18 {"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"},
19 {"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"}
20 ]
21 },
22 {
23 "id": "aurel",
24 "name": "Aurel",
25 "people": "Aurelians",
26 "jumpsToClear": 1,
27 "fallTime": 5,
28 "riseTime": 3,
29 "colors": [
30 {"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"},
31 {"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"},
32 {"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"},
33 {"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"},
34 {"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"}
35 ]
36 },
37 {
38 "id": "cinder",
39 "name": "Cinder",
40 "people": "Cindari",
41 "jumpsToClear": 4,
42 "fallTime": 1,
43 "riseTime": 0.5,
44 "colors": [
45 {"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"},
46 {"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"},
47 {"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"},
48 {"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"},
49 {"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"}
50 ]
51 },
52 {
53 "id": "lunara",
54 "name": "Lunara",
55 "people": "Lunarites",
56 "jumpsToClear": 1,
57 "fallTime": 2,
58 "riseTime": 1.2,
59 "colors": [
60 {"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"},
61 {"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"},
62 {"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"},
63 {"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"},
64 {"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"}
65 ]
66 },
67 {
68 "id": "mire",
69 "name": "Mire",
70 "people": "Mirians",
71 "jumpsToClear": 2,
72 "fallTime": 5,
73 "riseTime": 2.5,
74 "colors": [
75 {"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"},
76 {"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"},
77 {"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"},
78 {"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"},
79 {"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"}
80 ]
81 },
82 {
83 "id": "galeon",
84 "name": "Galeon",
85 "people": "Galeoni",
86 "jumpsToClear": 3,
87 "fallTime": 1,
88 "riseTime": 1.8,
89 "colors": [
90 {"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"},
91 {"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"},
92 {"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"},
93 {"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"},
94 {"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"}
95 ]
96 },
97 {
98 "id": "obsid",
99 "name": "Obsid",
100 "people": "Obsidians",
101 "jumpsToClear": 4,
102 "fallTime": 3.5,
103 "riseTime": 2.2,
104 "colors": [
105 {"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"},
106 {"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"},
107 {"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"},
108 {"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"},
109 {"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"}
110 ]
111 },
112 {
113 "id": "wisp",
114 "name": "Wisp",
115 "people": "Wisplings",
116 "jumpsToClear": 2,
117 "fallTime": 3.5,
118 "riseTime": 0.5,
119 "colors": [
120 {"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"},
121 {"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"},
122 {"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"},
123 {"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"},
124 {"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"}
125 ]
126 },
127 {
128 "id": "thorn",
129 "name": "Thorn",
130 "people": "Thornfolk",
131 "jumpsToClear": 3,
132 "fallTime": 2,
133 "riseTime": 1.0,
134 "colors": [
135 {"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"},
136 {"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"},
137 {"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"},
138 {"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"},
139 {"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"}
140 ]
141 },
142 {
143 "id": "zephyr",
144 "name": "Zephyr",
145 "people": "Zephyrites",
146 "jumpsToClear": 1,
147 "fallTime": 1.2,
148 "riseTime": 2.8,
149 "colors": [
150 {"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"},
151 {"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"},
152 {"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"},
153 {"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"},
154 {"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"}
155 ]
156 },
157 {
158 "id": "frore",
159 "name": "Frore",
160 "people": "Frorians",
161 "jumpsToClear": 3,
162 "fallTime": 4.5,
163 "riseTime": 0.8,
164 "colors": [
165 {"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"},
166 {"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"},
167 {"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"},
168 {"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"},
169 {"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"}
170 ]
171 },
172 {
173 "id": "forge",
174 "name": "Forge",
175 "people": "Forgelings",
176 "jumpsToClear": 4,
177 "fallTime": 2,
178 "riseTime": 1.5,
179 "colors": [
180 {"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"},
181 {"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"},
182 {"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"},
183 {"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"},
184 {"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"}
185 ]
186 }
187 ]
188}
189;
5
190
6/*
191/*
7 * Start File:
192 * Start File:
@@ -114,6 +299,7 @@ function createPlanet (opts)
114 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
299 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
115 var colors = opts.colors || defaultColors();
300 var colors = opts.colors || defaultColors();
116 var planet = {
301 var planet = {
302 id: opts.id || null,
117 name: opts.name || 'Terra',
303 name: opts.name || 'Terra',
118 people: opts.people || 'Terrans',
304 people: opts.people || 'Terrans',
119 jumpsToClear: jumpsToClear,
305 jumpsToClear: jumpsToClear,
@@ -133,15 +319,82 @@ function createPlanet (opts)
133 return planet;
319 return planet;
134}
320}
135
321
136function defaultPlanet ()
322function loadCatalog ()
323{
324 if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
325 { return PLANET_CATALOG; }
326 if (typeof require !== 'undefined')
327 {
328 try
329 { return require('../server/lib/planets.json'); }
330 catch (e) {}
331 }
332 return { planets: [] };
333}
334
335function planetFromData (data)
137{
336{
138 return createPlanet({
337 var planet = createPlanet({
139 name: 'Terra',
338 name: data.name,
140 people: 'Terrans',
339 people: data.people,
141 jumpsToClear: 2,
340 jumpsToClear: data.jumpsToClear,
142 fallTime: 3,
341 fallTime: data.fallTime,
143 riseTime: 1.5
342 riseTime: data.riseTime,
343 colors: data.colors
144 });
344 });
345 planet.id = data.id;
346 return planet;
347}
348
349function allPlanets ()
350{
351 var raw = loadCatalog().planets || [];
352 var out = [];
353 for (var i = 0; i < raw.length; i++)
354 { out.push(planetFromData(raw[i])); }
355 if (out.length === 0)
356 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
357 return out;
358}
359
360function planetById (id)
361{
362 var all = allPlanets();
363 for (var i = 0; i < all.length; i++)
364 {
365 if (all[i].id === id)
366 { return all[i]; }
367 }
368 return defaultPlanet();
369}
370
371function defaultPlanet ()
372{
373 var all = allPlanets();
374 for (var i = 0; i < all.length; i++)
375 {
376 if (all[i].id === 'terra')
377 { return all[i]; }
378 }
379 return all[0];
380}
381
382function formatStats (planet)
383{
384 var d = displayValues(planet);
385 return 'g ' + d.gravity.toFixed(2)
386 + ' d ' + d.density.toFixed(2)
387 + ' F ' + Math.round(d.newtons) + ' N'
388 + ' Power ' + d.power + '%';
389}
390
391function spriteKey (planet, colorIndex)
392{
393 var colors = planet && planet.colors;
394 var c = colors && colors[colorIndex];
395 if (!c)
396 { return 'gray'; }
397 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
145}
398}
146
399
147/**
400/**
@@ -221,6 +474,11 @@ var Planet = {
221 createPlanet: createPlanet,
474 createPlanet: createPlanet,
222 defaultPlanet: defaultPlanet,
475 defaultPlanet: defaultPlanet,
223 defaultColors: defaultColors,
476 defaultColors: defaultColors,
477 allPlanets: allPlanets,
478 planetById: planetById,
479 planetFromData: planetFromData,
480 formatStats: formatStats,
481 spriteKey: spriteKey,
224 jumpHeight: jumpHeight,
482 jumpHeight: jumpHeight,
225 launchVelocity: launchVelocity,
483 launchVelocity: launchVelocity,
226 launchDeceleration: launchDeceleration,
484 launchDeceleration: launchDeceleration,
@@ -453,6 +711,9 @@ function optsMissChance (args)
453 // GameCore(planet, rng, missChance) — third arg is optional.
711 // GameCore(planet, rng, missChance) — third arg is optional.
454 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
712 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
455 { return Math.max(0, Math.min(1, args[2])); }
713 { return Math.max(0, Math.min(1, args[2])); }
714 var planet = args[0];
715 if (planet && typeof PlanetMod.missChance === 'function')
716 { return PlanetMod.missChance(planet); }
456 return GameCore.DEFAULT_MISS_CHANCE;
717 return GameCore.DEFAULT_MISS_CHANCE;
457}
718}
458
719
@@ -2400,14 +2661,25 @@ Online.testLogin = function (who)
2400 return this.request('test_login', { user: who });
2661 return this.request('test_login', { user: who });
2401};
2662};
2402
2663
2403Online.createLobby = function ()
2664Online.createLobby = function (planetId)
2665{
2666 return this.request('lobby_create', {
2667 miss_chance: this.DEFAULT_MISS_CHANCE,
2668 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
2669 });
2670};
2671
2672Online.joinLobby = function (code, planetId)
2404{
2673{
2405 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
2674 return this.request('lobby_join', {
2675 code: code,
2676 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
2677 });
2406};
2678};
2407
2679
2408Online.joinLobby = function (code)
2680Online.setPlanet = function (planetId)
2409{
2681{
2410 return this.request('lobby_join', { code: code });
2682 return this.request('lobby_set_planet', { planet_id: planetId });
2411};
2683};
2412
2684
2413Online.leaveLobby = function ()
2685Online.leaveLobby = function ()
@@ -2574,7 +2846,7 @@ Online.renderMinis = function (container)
2574 el.querySelector('.mini-meta').textContent = p.eliminated
2846 el.querySelector('.mini-meta').textContent = p.eliminated
2575 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
2847 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
2576 : ('Punten ' + (p.score || 0));
2848 : ('Punten ' + (p.score || 0));
2577 this._drawMini(el.querySelector('canvas'), p.snapshot);
2849 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
2578 }
2850 }
2579 for (var id in existing)
2851 for (var id in existing)
2580 {
2852 {
@@ -2585,7 +2857,15 @@ Online.renderMinis = function (container)
2585
2857
2586var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
2858var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
2587
2859
2588Online._drawMini = function (canvas, snapshot)
2860function miniColor (planet, color)
2861{
2862 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
2863 { return planet.colors[color].hex; }
2864 return MINI_COLORS[color] || '#888';
2865}
2866
2867
2868Online._drawMini = function (canvas, snapshot, planet)
2589{
2869{
2590 if (!canvas)
2870 if (!canvas)
2591 { return; }
2871 { return; }
@@ -2625,7 +2905,7 @@ Online._drawMini = function (canvas, snapshot)
2625 else if (b.color < 0)
2905 else if (b.color < 0)
2626 { ctx.fillStyle = '#5a5d66'; }
2906 { ctx.fillStyle = '#5a5d66'; }
2627 else
2907 else
2628 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
2908 { ctx.fillStyle = miniColor(planet, b.color); }
2629 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
2909 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
2630 }
2910 }
2631};
2911};
@@ -2637,12 +2917,16 @@ Online.miniElement = function (playerId)
2637
2917
2638/* ---------- flight tweens ------------------------------------------ */
2918/* ---------- flight tweens ------------------------------------------ */
2639
2919
2640function colorSpriteUrl (color)
2920function colorSpriteUrl (color, planetId)
2641{
2921{
2642 if (color < 0)
2922 if (color < 0)
2643 { return 'images/block-gray.png'; }
2923 { return 'images/block-gray.png'; }
2644 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
2924 var planet = null;
2645 return 'images/block-' + (names[color] || 'gray') + '.png';
2925 if (typeof Planet !== 'undefined')
2926 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
2927 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
2928 { return planet.colors[color].image; }
2929 return 'images/block-gray.png';
2646}
2930}
2647
2931
2648/**
2932/**
@@ -2824,20 +3108,37 @@ if (typeof module !== 'undefined' && module.exports)
2824 * through Online (src/online.js) and the same GameCore.
3108 * through Online (src/online.js) and the same GameCore.
2825 */
3109 */
2826
3110
2827var IMAGES = [
3111function planetImages ()
2828 { name: 'ember', url: 'images/block-ember.png' },
3112{
2829 { name: 'aqua', url: 'images/block-aqua.png' },
3113 var list = [
2830 { name: 'leaf', url: 'images/block-leaf.png' },
3114 { name: 'gray', url: 'images/block-gray.png' },
2831 { name: 'sun', url: 'images/block-sun.png' },
3115 { name: 'locked', url: 'images/block-locked.png' },
2832 { name: 'orchid', url: 'images/block-orchid.png' },
3116 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
2833 { name: 'gray', url: 'images/block-gray.png' },
3117 { name: 'cell', url: 'images/cell.png' },
2834 { name: 'locked', url: 'images/block-locked.png' },
3118 { name: 'pixel', url: 'images/pixel.png' },
2835 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
3119 // Keep the original Terra placeholders as aliases (Tim may still have them).
2836 { name: 'cell', url: 'images/cell.png' },
3120 { name: 'ember', url: 'images/block-ember.png' },
2837 { name: 'pixel', url: 'images/pixel.png' }
3121 { name: 'aqua', url: 'images/block-aqua.png' },
2838];
3122 { name: 'leaf', url: 'images/block-leaf.png' },
2839
3123 { name: 'sun', url: 'images/block-sun.png' },
2840var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
3124 { name: 'orchid', url: 'images/block-orchid.png' }
3125 ];
3126 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
3127 for (var i = 0; i < planets.length; i++)
3128 {
3129 var pl = planets[i];
3130 for (var c = 0; c < pl.colors.length; c++)
3131 {
3132 list.push({
3133 name: Planet.spriteKey(pl, c),
3134 url: pl.colors[c].image
3135 });
3136 }
3137 }
3138 return list;
3139}
3140
3141var IMAGES = planetImages();
2841var GAME_OVER_DELAY = 2;
3142var GAME_OVER_DELAY = 2;
2842
3143
2843var game = new Game();
3144var game = new Game();
@@ -2863,7 +3164,9 @@ var app = {
2863 online: false,
3164 online: false,
2864 eliminatedReported: false,
3165 eliminatedReported: false,
2865 spectating: false,
3166 spectating: false,
2866 miniH: 0
3167 miniH: 0,
3168 selectedPlanetId: 'terra',
3169 planetSelectContext: 'solo'
2867};
3170};
2868
3171
2869window.onload = function ()
3172window.onload = function ()
@@ -2888,13 +3191,15 @@ window.onload = function ()
2888 });
3191 });
2889
3192
2890 bindOnlineUi();
3193 bindOnlineUi();
3194 bindPlanetSelect();
3195 restoreSelectedPlanet();
2891};
3196};
2892
3197
2893function onPlay ()
3198function onPlay ()
2894{
3199{
2895 if (app.mode === 'playing')
3200 if (app.mode === 'playing')
2896 { return; }
3201 { return; }
2897 startPlay();
3202 openPlanetSelect('solo');
2898}
3203}
2899
3204
2900function startPlay (opts)
3205function startPlay (opts)
@@ -2905,14 +3210,15 @@ function startPlay (opts)
2905 hideEl('online-panel');
3210 hideEl('online-panel');
2906 hideEl('spectator');
3211 hideEl('spectator');
2907 hideEl('podium');
3212 hideEl('podium');
3213 hideEl('planet-select');
2908 showEl('hud');
3214 showEl('hud');
2909
3215
2910 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
3216 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
3217 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
2911 var miss = opts.missChance;
3218 var miss = opts.missChance;
2912 if (typeof miss === 'number' && isFinite(miss))
3219 if (typeof miss !== 'number' || !isFinite(miss))
2913 { app.core = new GameCore(app.planet, Math.random, miss); }
3220 { miss = planetMod.missChance(app.planet); }
2914 else
3221 app.core = new GameCore(app.planet, Math.random, miss);
2915 { app.core = new GameCore(app.planet, Math.random); }
2916 app.mode = 'playing';
3222 app.mode = 'playing';
2917 app.online = !!opts.online;
3223 app.online = !!opts.online;
2918 app.gameOverShown = false;
3224 app.gameOverShown = false;
@@ -2981,6 +3287,7 @@ function returnToMenu ()
2981 teardownPlay();
3287 teardownPlay();
2982 app.mode = 'menu';
3288 app.mode = 'menu';
2983 app.online = false;
3289 app.online = false;
3290 hideEl('planet-select');
2984 showEl('menu');
3291 showEl('menu');
2985 var last = document.getElementById('last-score');
3292 var last = document.getElementById('last-score');
2986 if (app.lastScore > 0)
3293 if (app.lastScore > 0)
@@ -3064,7 +3371,8 @@ function spriteFor (block)
3064 { return game.images.locked; }
3371 { return game.images.locked; }
3065 if (block.color < 0)
3372 if (block.color < 0)
3066 { return game.images.gray; }
3373 { return game.images.gray; }
3067 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
3374 var key = Planet.spriteKey(app.planet, block.color);
3375 return game.images[key] || game.images.gray;
3068}
3376}
3069
3377
3070function syncSprites ()
3378function syncSprites ()
@@ -3223,10 +3531,7 @@ function refreshHud ()
3223 document.getElementById('score').textContent = String(app.core.score);
3531 document.getElementById('score').textContent = String(app.core.score);
3224 var planet = app.planet;
3532 var planet = app.planet;
3225 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
3533 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
3226 var d = Planet.displayValues(planet);
3534 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
3227 document.getElementById('planet-stats').textContent =
3228 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
3229 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
3230}
3535}
3231
3536
3232function makeManager ()
3537function makeManager ()
@@ -3504,10 +3809,11 @@ function startOnlineMatch ()
3504{
3809{
3505 if (app.mode === 'playing' && app.online)
3810 if (app.mode === 'playing' && app.online)
3506 { return; }
3811 { return; }
3507 var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
3812 var planet = Planet.planetById(selectedPlanetId());
3508 ? Online.lobby.miss_chance
3813 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
3509 : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
3814 if (me && me.planet && me.planet.id)
3510 startPlay({ online: true, missChance: miss });
3815 { planet = Planet.planetById(me.planet.id); }
3816 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
3511 if (typeof Online !== 'undefined')
3817 if (typeof Online !== 'undefined')
3512 { Online.startPolling(onlinePayload); }
3818 { Online.startPolling(onlinePayload); }
3513}
3819}
@@ -3664,6 +3970,7 @@ function openOnlinePanel ()
3664 hideEl('game-over');
3970 hideEl('game-over');
3665 hideEl('podium');
3971 hideEl('podium');
3666 hideEl('spectator');
3972 hideEl('spectator');
3973 hideEl('planet-select');
3667 showEl('online-panel');
3974 showEl('online-panel');
3668 app.mode = 'online';
3975 app.mode = 'online';
3669 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
3976 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
@@ -3765,10 +4072,14 @@ function renderOnline ()
3765 { li.classList.add('you'); }
4072 { li.classList.add('you'); }
3766 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
4073 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
3767 var state = p.ready ? 'Gereed' : 'Wacht…';
4074 var state = p.ready ? 'Gereed' : 'Wacht…';
3768 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
4075 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
4076 li.innerHTML = '<span>' + escapeText(label)
4077 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
4078 + '</span><span class="'
3769 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
4079 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
3770 list.appendChild(li);
4080 list.appendChild(li);
3771 }
4081 }
4082 renderPlanetGrid('lobby-planet-grid', true);
3772 var me = Online.mePlayer();
4083 var me = Online.mePlayer();
3773 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
4084 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
3774 var start = document.getElementById('btn-start');
4085 var start = document.getElementById('btn-start');
@@ -3802,6 +4113,150 @@ function escapeText (s)
3802 .replace(/"/g, '&quot;');
4113 .replace(/"/g, '&quot;');
3803}
4114}
3804
4115
4116
4117function selectedPlanetId ()
4118{
4119 if (app.selectedPlanetId)
4120 { return app.selectedPlanetId; }
4121 return 'terra';
4122}
4123
4124function restoreSelectedPlanet ()
4125{
4126 var id = 'terra';
4127 try
4128 { id = localStorage.getItem('meteors-planet') || 'terra'; }
4129 catch (e) {}
4130 setSelectedPlanet(id, true);
4131}
4132
4133function setSelectedPlanet (id, silent)
4134{
4135 var all = Planet.allPlanets();
4136 var found = null;
4137 for (var i = 0; i < all.length; i++)
4138 {
4139 if (all[i].id === id)
4140 { found = all[i]; break; }
4141 }
4142 if (!found)
4143 { found = Planet.defaultPlanet(); }
4144 app.selectedPlanetId = found.id;
4145 try
4146 { localStorage.setItem('meteors-planet', found.id); }
4147 catch (e) {}
4148 if (!silent)
4149 {
4150 var grid = document.getElementById('planet-grid');
4151 if (grid && !grid.hidden && grid.children.length)
4152 { renderPlanetGrid('planet-grid', false); }
4153 var lobby = document.getElementById('lobby-planet-grid');
4154 if (lobby && lobby.children.length)
4155 { renderPlanetGrid('lobby-planet-grid', true); }
4156 }
4157 return found;
4158}
4159
4160function openPlanetSelect (context)
4161{
4162 if (app.mode === 'playing')
4163 { return; }
4164 app.planetSelectContext = context || 'solo';
4165 app.mode = 'planet-select';
4166 hideEl('menu');
4167 hideEl('online-panel');
4168 hideEl('game-over');
4169 showEl('planet-select');
4170 renderPlanetGrid('planet-grid', false);
4171 var go = document.getElementById('btn-planet-go');
4172 if (go)
4173 { go.textContent = 'Spelen'; }
4174}
4175
4176function renderPlanetGrid (containerId, compact)
4177{
4178 var grid = document.getElementById(containerId);
4179 if (!grid)
4180 { return; }
4181 var current = selectedPlanetId();
4182 var all = Planet.allPlanets();
4183 grid.innerHTML = '';
4184 if (compact)
4185 { grid.classList.add('compact'); }
4186 for (var i = 0; i < all.length; i++)
4187 {
4188 var pl = all[i];
4189 var btn = document.createElement('button');
4190 btn.type = 'button';
4191 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
4192 btn.setAttribute('role', 'listitem');
4193 btn.dataset.planet = pl.id;
4194 var swatches = '';
4195 for (var c = 0; c < pl.colors.length; c++)
4196 {
4197 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
4198 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
4199 }
4200 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
4201 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
4202 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
4203 + '<div class="planet-swatches">' + swatches + '</div>';
4204 btn.addEventListener('click', (function (id, isCompact)
4205 {
4206 return function ()
4207 { onPlanetPicked(id, isCompact); };
4208 })(pl.id, !!compact));
4209 grid.appendChild(btn);
4210 }
4211}
4212
4213function onPlanetPicked (id, fromLobby)
4214{
4215 setSelectedPlanet(id);
4216 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
4217 {
4218 Online.setPlanet(id).then(function ()
4219 { renderOnline(); });
4220 }
4221 else
4222 {
4223 renderPlanetGrid('planet-grid', false);
4224 }
4225}
4226
4227function confirmPlanetSelect ()
4228{
4229 var planet = setSelectedPlanet(selectedPlanetId());
4230 hideEl('planet-select');
4231 if (app.planetSelectContext === 'online')
4232 {
4233 openOnlinePanel();
4234 return;
4235 }
4236 startPlay({ planet: planet });
4237}
4238
4239function cancelPlanetSelect ()
4240{
4241 hideEl('planet-select');
4242 app.mode = 'menu';
4243 showEl('menu');
4244}
4245
4246function bindPlanetSelect ()
4247{
4248 var go = document.getElementById('btn-planet-go');
4249 var back = document.getElementById('btn-planet-back');
4250 if (go)
4251 {
4252 go.addEventListener('click', confirmPlanetSelect);
4253 }
4254 if (back)
4255 {
4256 back.addEventListener('click', cancelPlanetSelect);
4257 }
4258}
4259
3805/*
4260/*
3806 * End File:
4261 * End File:
3807 * /workspace/meteors/src/main.js
4262 * /workspace/meteors/src/main.js
build/images/block-aurel-amber.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-aurel-cream.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-aurel-gold.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-aurel-rose.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-aurel-sage.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-cinder-ash.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-cinder-coal.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-cinder-core.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-cinder-magma.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-cinder-spark.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-forge-brass.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-forge-iron.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-forge-slag.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-forge-soot.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-forge-spark.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-frore-aurora.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-frore-deep.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-frore-frost.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-frore-ice.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-frore-rime.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-galeon-cloud.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-galeon-kite.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-galeon-sand.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-galeon-sky.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-galeon-storm.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-lunara-dust.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-lunara-lilac.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-lunara-pale.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-lunara-silver.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-lunara-void.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-mire-bog.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-mire-moss.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-mire-murk.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-mire-rust.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-mire-spore.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-obsid-basalt.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-obsid-glass.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-obsid-shard.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-obsid-vein.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-obsid-violet.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-terra-aqua.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-terra-ember.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-terra-leaf.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-terra-orchid.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-terra-sun.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-thorn-bark.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-thorn-berry.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-thorn-briar.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-thorn-gold.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-thorn-petal.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-wisp-gleam.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-wisp-glow.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-wisp-mist.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-wisp-sparkle.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-wisp-veil.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-zephyr-azure.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-zephyr-breeze.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-zephyr-cirrus.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-zephyr-dusk.png added Binary file +0 −0

The contents of this binary file are not shown.

build/images/block-zephyr-haze.png added Binary file +0 −0

The contents of this binary file are not shown.

build/index.html +12 −0
@@ -23,6 +23,16 @@
23 23 <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>
24 24 </div>
25 25
26 <div id="planet-select" class="screen" hidden>
27 <h1>Kies een veld</h1>
28 <p class="tagline">Elk veld is een planeet, met een eigen volk, zwaartekracht, lucht en massa.</p>
29 <div id="planet-grid" class="planet-grid" role="list"></div>
30 <div class="planet-actions">
31 <button type="button" id="btn-planet-go">Spelen</button>
32 <button type="button" id="btn-planet-back" class="btn-secondary">Terug</button>
33 </div>
34 </div>
35
26 36 <div id="online-panel" class="screen" hidden>
27 37 <h1>Online</h1>
28 38 <p id="online-status" class="tagline">Even kijken of online spelen beschikbaar is…</p>
@@ -61,6 +71,8 @@
61 71 <div id="online-lobby" hidden>
62 72 <p class="who">Ingelogd als <strong id="lobby-me-name"></strong></p>
63 73 <p class="lobby-code">Code: <strong id="lobby-code"></strong> <button type="button" id="btn-copy-code" class="btn-tiny">Kopieer</button></p>
74 <p class="hint lobby-planet-label">Jouw veld</p>
75 <div id="lobby-planet-grid" class="planet-grid compact" role="list"></div>
64 76 <ul id="lobby-players" class="player-list"></ul>
65 77 <p id="lobby-hint" class="hint"></p>
66 78 <div class="lobby-actions">
@@ -23,6 +23,16 @@
23 <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>
23 <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>
24 </div>
24 </div>
25
25
26 <div id="planet-select" class="screen" hidden>
27 <h1>Kies een veld</h1>
28 <p class="tagline">Elk veld is een planeet, met een eigen volk, zwaartekracht, lucht en massa.</p>
29 <div id="planet-grid" class="planet-grid" role="list"></div>
30 <div class="planet-actions">
31 <button type="button" id="btn-planet-go">Spelen</button>
32 <button type="button" id="btn-planet-back" class="btn-secondary">Terug</button>
33 </div>
34 </div>
35
26 <div id="online-panel" class="screen" hidden>
36 <div id="online-panel" class="screen" hidden>
27 <h1>Online</h1>
37 <h1>Online</h1>
28 <p id="online-status" class="tagline">Even kijken of online spelen beschikbaar is…</p>
38 <p id="online-status" class="tagline">Even kijken of online spelen beschikbaar is…</p>
@@ -61,6 +71,8 @@
61 <div id="online-lobby" hidden>
71 <div id="online-lobby" hidden>
62 <p class="who">Ingelogd als <strong id="lobby-me-name"></strong></p>
72 <p class="who">Ingelogd als <strong id="lobby-me-name"></strong></p>
63 <p class="lobby-code">Code: <strong id="lobby-code"></strong> <button type="button" id="btn-copy-code" class="btn-tiny">Kopieer</button></p>
73 <p class="lobby-code">Code: <strong id="lobby-code"></strong> <button type="button" id="btn-copy-code" class="btn-tiny">Kopieer</button></p>
74 <p class="hint lobby-planet-label">Jouw veld</p>
75 <div id="lobby-planet-grid" class="planet-grid compact" role="list"></div>
64 <ul id="lobby-players" class="player-list"></ul>
76 <ul id="lobby-players" class="player-list"></ul>
65 <p id="lobby-hint" class="hint"></p>
77 <p id="lobby-hint" class="hint"></p>
66 <div class="lobby-actions">
78 <div class="lobby-actions">
build/style.css +139 −8
@@ -45,7 +45,7 @@ html, body {
45 45 text-align: center;
46 46 }
47 47
48 .screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden] { display: none !important; }
48 .screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #planet-select[hidden] { display: none !important; }
49 49
50 50 h1 {
51 51 font-size: clamp(48px, 14vw, 96px);
@@ -66,7 +66,7 @@ h1 {
66 66 max-width: 28em;
67 67 }
68 68
69 #btn-play {
69 #btn-play, #btn-planet-go {
70 70 appearance: none;
71 71 border: 0;
72 72 cursor: pointer;
@@ -87,14 +87,14 @@ h1 {
87 87 min-width: 200px;
88 88 }
89 89
90 #btn-play:is(:hover, :focus-visible) {
90 #btn-play:is(:hover, :focus-visible), #btn-planet-go:is(:hover, :focus-visible) {
91 91 transform: translateY(-1px);
92 92 box-shadow:
93 93 0 0 0 3px rgba(255, 220, 120, 0.4),
94 94 0 10px 28px rgba(240, 197, 58, 0.6);
95 95 }
96 96
97 #btn-play:active { transform: translateY(1px); }
97 #btn-play:active, #btn-planet-go:active { transform: translateY(1px); }
98 98
99 99 .last-score {
100 100 margin: 22px 0 0;
@@ -181,7 +181,7 @@ canvas {
181 181 @media (max-height: 520px) {
182 182 .hint { display: none; }
183 183 h1 { font-size: 42px; }
184 #btn-play { padding: 10px 36px; }
184 #btn-play, #btn-planet-go { padding: 10px 36px; }
185 185 }
186 186
187 187
@@ -207,7 +207,7 @@ a.button:is(:hover, :focus-visible) {
207 207 color: #fff6c8;
208 208 }
209 209 #btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
210 #btn-play {
210 #btn-play, #btn-planet-go {
211 211 /* play already styled */
212 212 }
213 213
@@ -227,16 +227,21 @@ a.button:is(:hover, :focus-visible) {
227 227 cursor: default;
228 228 }
229 229
230 #online-panel h1 {
231 font-size: clamp(36px, 9vw, 64px);
232 }
230 233 #online-panel {
231 234 z-index: 5;
232 235 overflow: auto;
233 236 text-align: center;
234 padding: 32px 16px 48px;
237 padding: 16px 16px 24px;
235 238 }
236 239 #online-panel .who {
237 240 color: #c5cae0;
238 margin: 0 0 16px;
241 margin: 0 0 8px;
239 242 }
243 #online-lobby .tagline { margin-bottom: 8px; }
244 #online-lobby .lobby-code { margin: 4px 0 6px; }
240 245 #online-panel .notice {
241 246 max-width: 36em;
242 247 margin: 0 auto 16px;
@@ -408,3 +413,129 @@ a.button:is(:hover, :focus-visible) {
408 413 #online-panel .hint, #online-panel .tagline { display: block; }
409 414 .mini-canvas { width: 56px; height: 73px; }
410 415 }
416
417 /* Stage 3: planet (field) selection */
418 #planet-select {
419 justify-content: flex-start;
420 overflow-y: auto;
421 touch-action: pan-y;
422 -webkit-overflow-scrolling: touch;
423 padding-top: 20px;
424 padding-bottom: 32px;
425 }
426 #planet-select h1 {
427 font-size: clamp(32px, 9vw, 64px);
428 margin-bottom: 4px;
429 }
430 #planet-select .tagline { margin-bottom: 16px; }
431 .planet-grid {
432 display: grid;
433 grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
434 gap: 12px;
435 width: min(1000px, 100%);
436 margin: 0 auto 16px;
437 text-align: left;
438 touch-action: pan-y;
439 }
440 .planet-card {
441 appearance: none;
442 display: block;
443 width: 100%;
444 margin: 0;
445 padding: 12px 14px 10px;
446 border: 1px solid rgba(200, 210, 240, 0.16);
447 border-radius: 14px;
448 background: rgba(16, 20, 40, 0.72);
449 color: inherit;
450 font: inherit;
451 text-align: left;
452 cursor: pointer;
453 touch-action: manipulation;
454 transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
455 }
456 .planet-card:hover, .planet-card:focus-visible {
457 border-color: rgba(255, 226, 122, 0.55);
458 outline: none;
459 }
460 .planet-card.selected {
461 border-color: #ffe27a;
462 box-shadow: 0 0 0 2px rgba(255, 226, 122, 0.35), 0 8px 24px rgba(0,0,0,0.35);
463 background: rgba(40, 32, 16, 0.78);
464 }
465 .planet-card .planet-title {
466 font-size: 1.15rem;
467 font-weight: 700;
468 letter-spacing: 0.03em;
469 color: #fff6c8;
470 }
471 .planet-card .planet-people {
472 font-size: 0.85rem;
473 color: #8e95b3;
474 margin: 0 0 6px;
475 }
476 .planet-card .planet-nums {
477 font-variant-numeric: tabular-nums;
478 font-size: 0.78rem;
479 color: #c5cae0;
480 letter-spacing: 0.01em;
481 line-height: 1.35;
482 margin: 0 0 8px;
483 }
484 .planet-card .planet-swatches {
485 display: flex;
486 gap: 6px;
487 align-items: center;
488 }
489 .planet-card .planet-swatches img {
490 width: 26px;
491 height: 26px;
492 image-rendering: auto;
493 flex: 0 0 auto;
494 }
495 .planet-actions {
496 display: flex;
497 gap: 12px;
498 flex-wrap: wrap;
499 justify-content: center;
500 margin-top: 8px;
501 flex-shrink: 0;
502 }
503 .planet-grid.compact {
504 grid-template-columns: repeat(4, minmax(0, 1fr));
505 gap: 8px;
506 width: min(920px, 92vw);
507 min-width: min(920px, 92vw);
508 max-height: none;
509 overflow: visible;
510 touch-action: pan-y;
511 margin-bottom: 10px;
512 align-self: center;
513 }
514 @media (max-width: 720px) {
515 .planet-grid.compact {
516 grid-template-columns: repeat(2, minmax(0, 1fr));
517 }
518 }
519 .planet-grid.compact .planet-card { padding: 6px 8px; }
520 .planet-grid.compact .planet-title { font-size: 1rem; }
521 .planet-grid.compact .planet-nums { font-size: 0.7rem; margin-bottom: 6px; }
522 .planet-grid.compact .planet-swatches img { width: 20px; height: 20px; }
523 .lobby-planet-label { margin: 8px 0 6px; }
524 .player-list .planet-tag {
525 display: block;
526 font-size: 0.78rem;
527 font-weight: 500;
528 color: #9aa3c4;
529 }
530 #online-lobby {
531 overflow-y: auto;
532 touch-action: pan-y;
533 -webkit-overflow-scrolling: touch;
534 justify-content: flex-start;
535 padding-top: 8px;
536 }
537 @media (max-width: 520px) {
538 .planet-grid { grid-template-columns: 1fr 1fr; gap: 8px; }
539 .planet-card .planet-nums { font-size: 0.68rem; }
540 .planet-card { padding: 10px 8px 8px; }
541 }
@@ -45,7 +45,7 @@ html, body {
45 text-align: center;
45 text-align: center;
46}
46}
47
47
48.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden] { display: none !important; }
48.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden], #planet-select[hidden] { display: none !important; }
49
49
50h1 {
50h1 {
51 font-size: clamp(48px, 14vw, 96px);
51 font-size: clamp(48px, 14vw, 96px);
@@ -66,7 +66,7 @@ h1 {
66 max-width: 28em;
66 max-width: 28em;
67}
67}
68
68
69#btn-play {
69#btn-play, #btn-planet-go {
70 appearance: none;
70 appearance: none;
71 border: 0;
71 border: 0;
72 cursor: pointer;
72 cursor: pointer;
@@ -87,14 +87,14 @@ h1 {
87 min-width: 200px;
87 min-width: 200px;
88}
88}
89
89
90#btn-play:is(:hover, :focus-visible) {
90#btn-play:is(:hover, :focus-visible), #btn-planet-go:is(:hover, :focus-visible) {
91 transform: translateY(-1px);
91 transform: translateY(-1px);
92 box-shadow:
92 box-shadow:
93 0 0 0 3px rgba(255, 220, 120, 0.4),
93 0 0 0 3px rgba(255, 220, 120, 0.4),
94 0 10px 28px rgba(240, 197, 58, 0.6);
94 0 10px 28px rgba(240, 197, 58, 0.6);
95}
95}
96
96
97#btn-play:active { transform: translateY(1px); }
97#btn-play:active, #btn-planet-go:active { transform: translateY(1px); }
98
98
99.last-score {
99.last-score {
100 margin: 22px 0 0;
100 margin: 22px 0 0;
@@ -181,7 +181,7 @@ canvas {
181@media (max-height: 520px) {
181@media (max-height: 520px) {
182 .hint { display: none; }
182 .hint { display: none; }
183 h1 { font-size: 42px; }
183 h1 { font-size: 42px; }
184 #btn-play { padding: 10px 36px; }
184 #btn-play, #btn-planet-go { padding: 10px 36px; }
185}
185}
186
186
187
187
@@ -207,7 +207,7 @@ a.button:is(:hover, :focus-visible) {
207 color: #fff6c8;
207 color: #fff6c8;
208}
208}
209#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
209#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
210#btn-play {
210#btn-play, #btn-planet-go {
211 /* play already styled */
211 /* play already styled */
212}
212}
213
213
@@ -227,16 +227,21 @@ a.button:is(:hover, :focus-visible) {
227 cursor: default;
227 cursor: default;
228}
228}
229
229
230#online-panel h1 {
231 font-size: clamp(36px, 9vw, 64px);
232}
230#online-panel {
233#online-panel {
231 z-index: 5;
234 z-index: 5;
232 overflow: auto;
235 overflow: auto;
233 text-align: center;
236 text-align: center;
234 padding: 32px 16px 48px;
237 padding: 16px 16px 24px;
235}
238}
236#online-panel .who {
239#online-panel .who {
237 color: #c5cae0;
240 color: #c5cae0;
238 margin: 0 0 16px;
241 margin: 0 0 8px;
239}
242}
243#online-lobby .tagline { margin-bottom: 8px; }
244#online-lobby .lobby-code { margin: 4px 0 6px; }
240#online-panel .notice {
245#online-panel .notice {
241 max-width: 36em;
246 max-width: 36em;
242 margin: 0 auto 16px;
247 margin: 0 auto 16px;
@@ -408,3 +413,129 @@ a.button:is(:hover, :focus-visible) {
408 #online-panel .hint, #online-panel .tagline { display: block; }
413 #online-panel .hint, #online-panel .tagline { display: block; }
409 .mini-canvas { width: 56px; height: 73px; }
414 .mini-canvas { width: 56px; height: 73px; }
410}
415}
416
417/* Stage 3: planet (field) selection */
418#planet-select {
419 justify-content: flex-start;
420 overflow-y: auto;
421 touch-action: pan-y;
422 -webkit-overflow-scrolling: touch;
423 padding-top: 20px;
424 padding-bottom: 32px;
425}
426#planet-select h1 {
427 font-size: clamp(32px, 9vw, 64px);
428 margin-bottom: 4px;
429}
430#planet-select .tagline { margin-bottom: 16px; }
431.planet-grid {
432 display: grid;
433 grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
434 gap: 12px;
435 width: min(1000px, 100%);
436 margin: 0 auto 16px;
437 text-align: left;
438 touch-action: pan-y;
439}
440.planet-card {
441 appearance: none;
442 display: block;
443 width: 100%;
444 margin: 0;
445 padding: 12px 14px 10px;
446 border: 1px solid rgba(200, 210, 240, 0.16);
447 border-radius: 14px;
448 background: rgba(16, 20, 40, 0.72);
449 color: inherit;
450 font: inherit;
451 text-align: left;
452 cursor: pointer;
453 touch-action: manipulation;
454 transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
455}
456.planet-card:hover, .planet-card:focus-visible {
457 border-color: rgba(255, 226, 122, 0.55);
458 outline: none;
459}
460.planet-card.selected {
461 border-color: #ffe27a;
462 box-shadow: 0 0 0 2px rgba(255, 226, 122, 0.35), 0 8px 24px rgba(0,0,0,0.35);
463 background: rgba(40, 32, 16, 0.78);
464}
465.planet-card .planet-title {
466 font-size: 1.15rem;
467 font-weight: 700;
468 letter-spacing: 0.03em;
469 color: #fff6c8;
470}
471.planet-card .planet-people {
472 font-size: 0.85rem;
473 color: #8e95b3;
474 margin: 0 0 6px;
475}
476.planet-card .planet-nums {
477 font-variant-numeric: tabular-nums;
478 font-size: 0.78rem;
479 color: #c5cae0;
480 letter-spacing: 0.01em;
481 line-height: 1.35;
482 margin: 0 0 8px;
483}
484.planet-card .planet-swatches {
485 display: flex;
486 gap: 6px;
487 align-items: center;
488}
489.planet-card .planet-swatches img {
490 width: 26px;
491 height: 26px;
492 image-rendering: auto;
493 flex: 0 0 auto;
494}
495.planet-actions {
496 display: flex;
497 gap: 12px;
498 flex-wrap: wrap;
499 justify-content: center;
500 margin-top: 8px;
501 flex-shrink: 0;
502}
503.planet-grid.compact {
504 grid-template-columns: repeat(4, minmax(0, 1fr));
505 gap: 8px;
506 width: min(920px, 92vw);
507 min-width: min(920px, 92vw);
508 max-height: none;
509 overflow: visible;
510 touch-action: pan-y;
511 margin-bottom: 10px;
512 align-self: center;
513}
514@media (max-width: 720px) {
515 .planet-grid.compact {
516 grid-template-columns: repeat(2, minmax(0, 1fr));
517 }
518}
519.planet-grid.compact .planet-card { padding: 6px 8px; }
520.planet-grid.compact .planet-title { font-size: 1rem; }
521.planet-grid.compact .planet-nums { font-size: 0.7rem; margin-bottom: 6px; }
522.planet-grid.compact .planet-swatches img { width: 20px; height: 20px; }
523.lobby-planet-label { margin: 8px 0 6px; }
524.player-list .planet-tag {
525 display: block;
526 font-size: 0.78rem;
527 font-weight: 500;
528 color: #9aa3c4;
529}
530#online-lobby {
531 overflow-y: auto;
532 touch-action: pan-y;
533 -webkit-overflow-scrolling: touch;
534 justify-content: flex-start;
535 padding-top: 8px;
536}
537@media (max-width: 520px) {
538 .planet-grid { grid-template-columns: 1fr 1fr; gap: 8px; }
539 .planet-card .planet-nums { font-size: 0.68rem; }
540 .planet-card { padding: 10px 8px 8px; }
541}
docs/ASSUMPTIONS.md +31 −2
@@ -117,9 +117,9 @@ Het blok blijft op 80% zolang het geselecteerd is, en veert bij loslaten
117 117 terug (ook als het ondertussen gelanceerd wordt). Muis en touch gebruiken
118 118 dezelfde tween.
119 119
120 ## Fase 2 — multiplayer (volgt)
120 ## Fase 2 — multiplayer (samenvatting)
121 121
122 Zie latere secties zodra fase 2 landt. De miss-kans van 30% wordt een
122 De miss-kans van 30% was de stage-2-parameter; stage 3 vervangt die door
123 123 parameter (`missChance`, standaard 0,30); de planeetformule
124 124 `Planet.missChance` (60%–5% via Power) is voor fase 3.
125 125
@@ -248,3 +248,32 @@ Aanname:
248 248 FTP); Tim zet het op het meteors-project. Optioneel: `auth_client_id`
249 249 (standaard `projects.timfalken.com`). `favicon.ico` blijft ongemoeid.
250 250 `router.php` is alleen voor lokale `php -S` en gaat niet mee naar live.
251
252 ## Fase 3 — planeten (velden)
253
254 - Een veld is een planeet, met een naam voor de planeet en voor het volk.
255 De catalogus staat in `server/lib/planets.json` (bron voor JS én PHP) en
256 telt **12** werelden, van makkelijk (Aurel: Power 0 %, 60 % miss) tot
257 moeilijk (Cinder: Power 100 %, 5 % miss). Terra blijft de standaard.
258 - Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt `1/jumpsToClear` van
259 de veldhoogte. Luchtweerstand (`fallTime` 1–5 s tot de bodem). Massa
260 (`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en
261 hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al
262 met `fallTime` (gebouwd in stage 1).
263 - Power is het gemiddelde van die drie assen, genormaliseerd 0–1, getoond
264 als percentage. Miss-kans = `0,60 − 0,55 × Power` (60 % bij Power 0,
265 5 % bij Power 1). In multiplayer gebruikt de **server** de Power van
266 **jouw** planeet voor de blokjes die jij afschiet (niet de lobby-waarde,
267 niet de planeet van het doel). De client kan dat niet vervalsen.
268 - De vier getallen op de kiezers en in de HUD: `g` als
269 zwaartekrachtsconstante (m/s²), `d` als luchtdichtheid, `F` in newton,
270 Power als percentage. Alleen de getallen, zonder uitleg. Verticale match
271 van 3 = 120 % sprong, +5 % per extra blokje (al gebouwd, nergens uitgelegd).
272 - Elk veld heeft een eigen set van 5 kleuren, elk met een uniek vormpje
273 en een uniek placeholder-PNG (`build/images/block-{planeet}-{kleur}.png`).
274 Tim kan die bestanden zelf vervangen; de namen blijven gelijk. Te
275 (her)genereren met `python3 scripts/gen_planet_blocks.py`.
276 - Planeetkeuze komt vóór solo-spel (`Spelen` opent de kiezer) en in de
277 lobby (iedereen kiest zelf; zichtbaar voor de anderen). De keuze wordt
278 onthouden in `localStorage` (`meteors-planet`). Na de start van een
279 wedstrijd kun je niet meer wisselen.
@@ -117,9 +117,9 @@ Het blok blijft op 80% zolang het geselecteerd is, en veert bij loslaten
117terug (ook als het ondertussen gelanceerd wordt). Muis en touch gebruiken
117terug (ook als het ondertussen gelanceerd wordt). Muis en touch gebruiken
118dezelfde tween.
118dezelfde tween.
119
119
120## Fase 2 — multiplayer (volgt)
120## Fase 2 — multiplayer (samenvatting)
121
121
122Zie latere secties zodra fase 2 landt. De miss-kans van 30% wordt een
122De miss-kans van 30% was de stage-2-parameter; stage 3 vervangt die door
123parameter (`missChance`, standaard 0,30); de planeetformule
123parameter (`missChance`, standaard 0,30); de planeetformule
124`Planet.missChance` (60%–5% via Power) is voor fase 3.
124`Planet.missChance` (60%–5% via Power) is voor fase 3.
125
125
@@ -248,3 +248,32 @@ Aanname:
248 FTP); Tim zet het op het meteors-project. Optioneel: `auth_client_id`
248 FTP); Tim zet het op het meteors-project. Optioneel: `auth_client_id`
249 (standaard `projects.timfalken.com`). `favicon.ico` blijft ongemoeid.
249 (standaard `projects.timfalken.com`). `favicon.ico` blijft ongemoeid.
250 `router.php` is alleen voor lokale `php -S` en gaat niet mee naar live.
250 `router.php` is alleen voor lokale `php -S` en gaat niet mee naar live.
251
252## Fase 3 — planeten (velden)
253
254- Een veld is een planeet, met een naam voor de planeet en voor het volk.
255 De catalogus staat in `server/lib/planets.json` (bron voor JS én PHP) en
256 telt **12** werelden, van makkelijk (Aurel: Power 0 %, 60 % miss) tot
257 moeilijk (Cinder: Power 100 %, 5 % miss). Terra blijft de standaard.
258- Zwaartekracht (`jumpsToClear` 1–4): één sprong haalt `1/jumpsToClear` van
259 de veldhoogte. Luchtweerstand (`fallTime` 1–5 s tot de bodem). Massa
260 (`riseTime` 0,5–3 s tot de apex). Lage massa en lage luchtweerstand en
261 hoge zwaartekracht zijn moeilijker. Bounce-duur en apex-ease schalen al
262 met `fallTime` (gebouwd in stage 1).
263- Power is het gemiddelde van die drie assen, genormaliseerd 0–1, getoond
264 als percentage. Miss-kans = `0,60 − 0,55 × Power` (60 % bij Power 0,
265 5 % bij Power 1). In multiplayer gebruikt de **server** de Power van
266 **jouw** planeet voor de blokjes die jij afschiet (niet de lobby-waarde,
267 niet de planeet van het doel). De client kan dat niet vervalsen.
268- De vier getallen op de kiezers en in de HUD: `g` als
269 zwaartekrachtsconstante (m/s²), `d` als luchtdichtheid, `F` in newton,
270 Power als percentage. Alleen de getallen, zonder uitleg. Verticale match
271 van 3 = 120 % sprong, +5 % per extra blokje (al gebouwd, nergens uitgelegd).
272- Elk veld heeft een eigen set van 5 kleuren, elk met een uniek vormpje
273 en een uniek placeholder-PNG (`build/images/block-{planeet}-{kleur}.png`).
274 Tim kan die bestanden zelf vervangen; de namen blijven gelijk. Te
275 (her)genereren met `python3 scripts/gen_planet_blocks.py`.
276- Planeetkeuze komt vóór solo-spel (`Spelen` opent de kiezer) en in de
277 lobby (iedereen kiest zelf; zichtbaar voor de anderen). De keuze wordt
278 onthouden in `localStorage` (`meteors-planet`). Na de start van een
279 wedstrijd kun je niet meer wisselen.
scripts/gen_planet_blocks.py added +175 −0
@@ -0,0 +1,175 @@
1 #!/usr/bin/env python3
2 """Unique placeholder block images for each planet color.
3
4 Tim can replace any of these PNGs in build/images/. Filenames stay stable.
5 Run from the repo root: python3 scripts/gen_planet_blocks.py
6 """
7 from __future__ import annotations
8
9 import json
10 import math
11 from pathlib import Path
12
13 from PIL import Image, ImageDraw, ImageFilter, ImageChops
14
15 ROOT = Path(__file__).resolve().parents[1]
16 CATALOG = ROOT / 'server' / 'lib' / 'planets.json'
17 OUT = ROOT / 'build' / 'images'
18 SIZE = 64
19 SCALE = 4 # supersample
20 SS = SIZE * SCALE
21
22
23 def hex_rgb(h):
24 h = h.lstrip('#')
25 return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
26
27
28 def lighten(rgb, f=0.35):
29 return tuple(min(255, int(c + (255 - c) * f)) for c in rgb)
30
31
32 def darken(rgb, f=0.28):
33 return tuple(max(0, int(c * (1 - f))) for c in rgb)
34
35
36 def regular_poly(cx, cy, r, n, rot=-math.pi / 2):
37 pts = []
38 for i in range(n):
39 a = rot + i * 2 * math.pi / n
40 pts.append((cx + r * math.cos(a), cy + r * math.sin(a)))
41 return pts
42
43
44 def star_pts(cx, cy, r, n=5, inner=0.42, rot=-math.pi / 2):
45 pts = []
46 for i in range(n * 2):
47 a = rot + i * math.pi / n
48 rr = r if i % 2 == 0 else r * inner
49 pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
50 return pts
51
52
53 def draw_shape(draw, shape, cx, cy, r, fill, outline, width):
54 shape = shape.lower()
55 if shape == 'circle':
56 box = [cx - r, cy - r, cx + r, cy + r]
57 draw.ellipse(box, fill=fill, outline=outline, width=width)
58 elif shape == 'square':
59 s = r * 0.86
60 box = [cx - s, cy - s, cx + s, cy + s]
61 draw.rounded_rectangle(box, radius=r * 0.12, fill=fill, outline=outline, width=width)
62 elif shape == 'triangle':
63 pts = regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2)
64 draw.polygon(pts, fill=fill, outline=outline, width=width)
65 elif shape == 'diamond':
66 pts = regular_poly(cx, cy, r * 1.05, 4, 0)
67 draw.polygon(pts, fill=fill, outline=outline, width=width)
68 elif shape == 'star':
69 draw.polygon(star_pts(cx, cy, r * 1.12), fill=fill, outline=outline, width=width)
70 elif shape == 'hexagon':
71 draw.polygon(regular_poly(cx, cy, r * 1.05, 6, 0), fill=fill, outline=outline, width=width)
72 elif shape == 'pentagon':
73 draw.polygon(regular_poly(cx, cy, r * 1.08, 5), fill=fill, outline=outline, width=width)
74 elif shape == 'teardrop':
75 # circle + top point
76 pts = []
77 for i in range(24):
78 a = math.pi * 0.22 + i * (2 * math.pi * 0.78) / 23
79 pts.append((cx + r * 0.85 * math.cos(a), cy + r * 0.25 + r * 0.85 * math.sin(a)))
80 pts.insert(0, (cx, cy - r * 1.1))
81 draw.polygon(pts, fill=fill, outline=outline, width=width)
82 elif shape == 'crescent':
83 # Draw a moon by punching a circle out of another.
84 # ImageDraw can't punch; caller uses a mask. Fallback: thick arc-like poly.
85 outer = []
86 inner = []
87 for i in range(22):
88 a = -math.pi * 0.7 + i * (1.4 * math.pi) / 21
89 outer.append((cx + r * math.cos(a) - r * 0.08, cy + r * math.sin(a)))
90 ox, oy = cx + r * 0.42, cy - r * 0.05
91 for i in range(18, -1, -1):
92 a = -math.pi * 0.65 + i * (1.3 * math.pi) / 18
93 inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a)))
94 draw.polygon(outer + inner, fill=fill, outline=outline, width=width)
95 elif shape == 'plus':
96 t = r * 0.38
97 pts = [
98 (cx - t, cy - r), (cx + t, cy - r), (cx + t, cy - t),
99 (cx + r, cy - t), (cx + r, cy + t), (cx + t, cy + t),
100 (cx + t, cy + r), (cx - t, cy + r), (cx - t, cy + t),
101 (cx - r, cy + t), (cx - r, cy - t), (cx - t, cy - t),
102 ]
103 draw.polygon(pts, fill=fill, outline=outline, width=width)
104 elif shape == 'gem':
105 pts = [
106 (cx, cy - r), (cx + r * 0.72, cy - r * 0.15),
107 (cx + r * 0.5, cy + r * 0.95), (cx - r * 0.5, cy + r * 0.95),
108 (cx - r * 0.72, cy - r * 0.15),
109 ]
110 draw.polygon(pts, fill=fill, outline=outline, width=width)
111 elif shape == 'arrow':
112 pts = [
113 (cx, cy - r * 1.1), (cx + r * 0.85, cy + r * 0.05),
114 (cx + r * 0.28, cy + r * 0.05), (cx + r * 0.28, cy + r),
115 (cx - r * 0.28, cy + r), (cx - r * 0.28, cy + r * 0.05),
116 (cx - r * 0.85, cy + r * 0.05),
117 ]
118 draw.polygon(pts, fill=fill, outline=outline, width=width)
119 else:
120 draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)
121
122
123 def render_block(hex_color, shape):
124 rgb = hex_rgb(hex_color)
125 hi = lighten(rgb, 0.42)
126 lo = darken(rgb, 0.32)
127 img = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
128 draw = ImageDraw.Draw(img)
129 cx = cy = SS / 2
130 r = SS * 0.36
131 # drop shadow
132 shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
133 sd = ImageDraw.Draw(shadow)
134 draw_shape(sd, shape, cx + SCALE * 1.2, cy + SCALE * 1.6, r, (0, 0, 0, 90), None, 0)
135 shadow = shadow.filter(ImageFilter.GaussianBlur(radius=SCALE * 1.1))
136 img = Image.alpha_composite(img, shadow)
137 draw = ImageDraw.Draw(img)
138 # body
139 draw_shape(draw, shape, cx, cy, r, rgb + (255,), lo + (255,), max(2, SCALE))
140 # highlight (smaller, offset, semi)
141 hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
142 hd = ImageDraw.Draw(hi_layer)
143 draw_shape(hd, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55, hi + (110,), None, 0)
144 # clip highlight to the body roughly by multiplying alpha later is hard;
145 # a soft blob is fine for a placeholder.
146 hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6))
147 img = Image.alpha_composite(img, hi_layer)
148 out = img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)
149 return out
150
151
152 def main():
153 data = json.loads(CATALOG.read_text())
154 OUT.mkdir(parents=True, exist_ok=True)
155 written = []
156 seen = set()
157 for planet in data['planets']:
158 shapes = [c['shape'] for c in planet['colors']]
159 if len(set(shapes)) != 5:
160 raise SystemExit(f'{planet["id"]} does not have 5 unique shapes')
161 for color in planet['colors']:
162 path = ROOT / 'build' / color['image']
163 if path.name in seen:
164 raise SystemExit(f'duplicate filename {path}')
165 seen.add(path.name)
166 img = render_block(color['hex'], color['shape'])
167 img.save(path, 'PNG', optimize=True)
168 written.append(path.relative_to(ROOT))
169 print(f'wrote {len(written)} placeholders to {OUT}')
170 for p in written:
171 print(' ', p)
172
173
174 if __name__ == '__main__':
175 main()
@@ -0,0 +1,175 @@
1#!/usr/bin/env python3
2"""Unique placeholder block images for each planet color.
3
4Tim can replace any of these PNGs in build/images/. Filenames stay stable.
5Run from the repo root: python3 scripts/gen_planet_blocks.py
6"""
7from __future__ import annotations
8
9import json
10import math
11from pathlib import Path
12
13from PIL import Image, ImageDraw, ImageFilter, ImageChops
14
15ROOT = Path(__file__).resolve().parents[1]
16CATALOG = ROOT / 'server' / 'lib' / 'planets.json'
17OUT = ROOT / 'build' / 'images'
18SIZE = 64
19SCALE = 4 # supersample
20SS = SIZE * SCALE
21
22
23def hex_rgb(h):
24 h = h.lstrip('#')
25 return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4))
26
27
28def lighten(rgb, f=0.35):
29 return tuple(min(255, int(c + (255 - c) * f)) for c in rgb)
30
31
32def darken(rgb, f=0.28):
33 return tuple(max(0, int(c * (1 - f))) for c in rgb)
34
35
36def regular_poly(cx, cy, r, n, rot=-math.pi / 2):
37 pts = []
38 for i in range(n):
39 a = rot + i * 2 * math.pi / n
40 pts.append((cx + r * math.cos(a), cy + r * math.sin(a)))
41 return pts
42
43
44def star_pts(cx, cy, r, n=5, inner=0.42, rot=-math.pi / 2):
45 pts = []
46 for i in range(n * 2):
47 a = rot + i * math.pi / n
48 rr = r if i % 2 == 0 else r * inner
49 pts.append((cx + rr * math.cos(a), cy + rr * math.sin(a)))
50 return pts
51
52
53def draw_shape(draw, shape, cx, cy, r, fill, outline, width):
54 shape = shape.lower()
55 if shape == 'circle':
56 box = [cx - r, cy - r, cx + r, cy + r]
57 draw.ellipse(box, fill=fill, outline=outline, width=width)
58 elif shape == 'square':
59 s = r * 0.86
60 box = [cx - s, cy - s, cx + s, cy + s]
61 draw.rounded_rectangle(box, radius=r * 0.12, fill=fill, outline=outline, width=width)
62 elif shape == 'triangle':
63 pts = regular_poly(cx, cy + r * 0.08, r * 1.08, 3, -math.pi / 2)
64 draw.polygon(pts, fill=fill, outline=outline, width=width)
65 elif shape == 'diamond':
66 pts = regular_poly(cx, cy, r * 1.05, 4, 0)
67 draw.polygon(pts, fill=fill, outline=outline, width=width)
68 elif shape == 'star':
69 draw.polygon(star_pts(cx, cy, r * 1.12), fill=fill, outline=outline, width=width)
70 elif shape == 'hexagon':
71 draw.polygon(regular_poly(cx, cy, r * 1.05, 6, 0), fill=fill, outline=outline, width=width)
72 elif shape == 'pentagon':
73 draw.polygon(regular_poly(cx, cy, r * 1.08, 5), fill=fill, outline=outline, width=width)
74 elif shape == 'teardrop':
75 # circle + top point
76 pts = []
77 for i in range(24):
78 a = math.pi * 0.22 + i * (2 * math.pi * 0.78) / 23
79 pts.append((cx + r * 0.85 * math.cos(a), cy + r * 0.25 + r * 0.85 * math.sin(a)))
80 pts.insert(0, (cx, cy - r * 1.1))
81 draw.polygon(pts, fill=fill, outline=outline, width=width)
82 elif shape == 'crescent':
83 # Draw a moon by punching a circle out of another.
84 # ImageDraw can't punch; caller uses a mask. Fallback: thick arc-like poly.
85 outer = []
86 inner = []
87 for i in range(22):
88 a = -math.pi * 0.7 + i * (1.4 * math.pi) / 21
89 outer.append((cx + r * math.cos(a) - r * 0.08, cy + r * math.sin(a)))
90 ox, oy = cx + r * 0.42, cy - r * 0.05
91 for i in range(18, -1, -1):
92 a = -math.pi * 0.65 + i * (1.3 * math.pi) / 18
93 inner.append((ox + r * 0.72 * math.cos(a), oy + r * 0.72 * math.sin(a)))
94 draw.polygon(outer + inner, fill=fill, outline=outline, width=width)
95 elif shape == 'plus':
96 t = r * 0.38
97 pts = [
98 (cx - t, cy - r), (cx + t, cy - r), (cx + t, cy - t),
99 (cx + r, cy - t), (cx + r, cy + t), (cx + t, cy + t),
100 (cx + t, cy + r), (cx - t, cy + r), (cx - t, cy + t),
101 (cx - r, cy + t), (cx - r, cy - t), (cx - t, cy - t),
102 ]
103 draw.polygon(pts, fill=fill, outline=outline, width=width)
104 elif shape == 'gem':
105 pts = [
106 (cx, cy - r), (cx + r * 0.72, cy - r * 0.15),
107 (cx + r * 0.5, cy + r * 0.95), (cx - r * 0.5, cy + r * 0.95),
108 (cx - r * 0.72, cy - r * 0.15),
109 ]
110 draw.polygon(pts, fill=fill, outline=outline, width=width)
111 elif shape == 'arrow':
112 pts = [
113 (cx, cy - r * 1.1), (cx + r * 0.85, cy + r * 0.05),
114 (cx + r * 0.28, cy + r * 0.05), (cx + r * 0.28, cy + r),
115 (cx - r * 0.28, cy + r), (cx - r * 0.28, cy + r * 0.05),
116 (cx - r * 0.85, cy + r * 0.05),
117 ]
118 draw.polygon(pts, fill=fill, outline=outline, width=width)
119 else:
120 draw.ellipse([cx - r, cy - r, cx + r, cy + r], fill=fill, outline=outline, width=width)
121
122
123def render_block(hex_color, shape):
124 rgb = hex_rgb(hex_color)
125 hi = lighten(rgb, 0.42)
126 lo = darken(rgb, 0.32)
127 img = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
128 draw = ImageDraw.Draw(img)
129 cx = cy = SS / 2
130 r = SS * 0.36
131 # drop shadow
132 shadow = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
133 sd = ImageDraw.Draw(shadow)
134 draw_shape(sd, shape, cx + SCALE * 1.2, cy + SCALE * 1.6, r, (0, 0, 0, 90), None, 0)
135 shadow = shadow.filter(ImageFilter.GaussianBlur(radius=SCALE * 1.1))
136 img = Image.alpha_composite(img, shadow)
137 draw = ImageDraw.Draw(img)
138 # body
139 draw_shape(draw, shape, cx, cy, r, rgb + (255,), lo + (255,), max(2, SCALE))
140 # highlight (smaller, offset, semi)
141 hi_layer = Image.new('RGBA', (SS, SS), (0, 0, 0, 0))
142 hd = ImageDraw.Draw(hi_layer)
143 draw_shape(hd, shape, cx - r * 0.06, cy - r * 0.10, r * 0.55, hi + (110,), None, 0)
144 # clip highlight to the body roughly by multiplying alpha later is hard;
145 # a soft blob is fine for a placeholder.
146 hi_layer = hi_layer.filter(ImageFilter.GaussianBlur(radius=SCALE * 0.6))
147 img = Image.alpha_composite(img, hi_layer)
148 out = img.resize((SIZE, SIZE), Image.Resampling.LANCZOS)
149 return out
150
151
152def main():
153 data = json.loads(CATALOG.read_text())
154 OUT.mkdir(parents=True, exist_ok=True)
155 written = []
156 seen = set()
157 for planet in data['planets']:
158 shapes = [c['shape'] for c in planet['colors']]
159 if len(set(shapes)) != 5:
160 raise SystemExit(f'{planet["id"]} does not have 5 unique shapes')
161 for color in planet['colors']:
162 path = ROOT / 'build' / color['image']
163 if path.name in seen:
164 raise SystemExit(f'duplicate filename {path}')
165 seen.add(path.name)
166 img = render_block(color['hex'], color['shape'])
167 img.save(path, 'PNG', optimize=True)
168 written.append(path.relative_to(ROOT))
169 print(f'wrote {len(written)} placeholders to {OUT}')
170 for p in written:
171 print(' ', p)
172
173
174if __name__ == '__main__':
175 main()
server/api.php +9 −2
@@ -62,12 +62,19 @@ try {
62 62 switch ($action) {
63 63 case 'lobby_create':
64 64 $miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;
65 $lobby = $store->createLobby($userId, $name, $miss);
65 $planet = (string) ($body['planet_id'] ?? '');
66 $lobby = $store->createLobby($userId, $name, $miss, $planet);
66 67 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
67 68
68 69 case 'lobby_join':
69 70 $code = (string) ($body['code'] ?? '');
70 $lobby = $store->joinLobby($userId, $name, $code);
71 $planet = (string) ($body['planet_id'] ?? '');
72 $lobby = $store->joinLobby($userId, $name, $code, $planet);
73 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
74
75 case 'lobby_set_planet':
76 $planet = (string) ($body['planet_id'] ?? '');
77 $lobby = $store->setPlanet($userId, $planet);
71 78 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
72 79
73 80 case 'lobby_leave':
@@ -62,12 +62,19 @@ try {
62 switch ($action) {
62 switch ($action) {
63 case 'lobby_create':
63 case 'lobby_create':
64 $miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;
64 $miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;
65 $lobby = $store->createLobby($userId, $name, $miss);
65 $planet = (string) ($body['planet_id'] ?? '');
66 $lobby = $store->createLobby($userId, $name, $miss, $planet);
66 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
67 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
67
68
68 case 'lobby_join':
69 case 'lobby_join':
69 $code = (string) ($body['code'] ?? '');
70 $code = (string) ($body['code'] ?? '');
70 $lobby = $store->joinLobby($userId, $name, $code);
71 $planet = (string) ($body['planet_id'] ?? '');
72 $lobby = $store->joinLobby($userId, $name, $code, $planet);
73 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
74
75 case 'lobby_set_planet':
76 $planet = (string) ($body['planet_id'] ?? '');
77 $lobby = $store->setPlanet($userId, $planet);
71 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
78 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
72
79
73 case 'lobby_leave':
80 case 'lobby_leave':
server/lib/Planets.php added +147 −0
@@ -0,0 +1,147 @@
1 <?php
2 declare(strict_types=1);
3
4 /**
5 * Planet catalog shared with the JS client (server/lib/planets.json).
6 * Power and miss-chance formulas must stay in lockstep with src/planet.js.
7 */
8 final class Planets
9 {
10 private static ?array $all = null;
11
12 public static function path(): string
13 {
14 return __DIR__ . '/planets.json';
15 }
16
17 /** @return list<array> raw catalog entries */
18 public static function all(): array
19 {
20 if (self::$all !== null) {
21 return self::$all;
22 }
23 $raw = file_get_contents(self::path());
24 if ($raw === false) {
25 throw new RuntimeException('planets.json ontbreekt.');
26 }
27 $data = json_decode($raw, true);
28 if (!is_array($data) || !isset($data['planets']) || !is_array($data['planets'])) {
29 throw new RuntimeException('planets.json is ongeldig.');
30 }
31 self::$all = [];
32 foreach ($data['planets'] as $row) {
33 if (!is_array($row) || empty($row['id'])) {
34 continue;
35 }
36 self::$all[] = $row;
37 }
38 return self::$all;
39 }
40
41 public static function byId(string $id): ?array
42 {
43 foreach (self::all() as $p) {
44 if (($p['id'] ?? '') === $id) {
45 return $p;
46 }
47 }
48 return null;
49 }
50
51 public static function defaultId(): string
52 {
53 return 'terra';
54 }
55
56 public static function default(): array
57 {
58 return self::byId(self::defaultId()) ?? self::all()[0];
59 }
60
61 public static function known(string $id): bool
62 {
63 return self::byId($id) !== null;
64 }
65
66 /** Difficulty in 0..1. Higher is harder. */
67 public static function power(array $planet): float
68 {
69 $j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);
70 $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
71 $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
72 $gravity = ($j - 1) / 3;
73 $air = (5 - $f) / 4;
74 $mass = (3 - $r) / 2.5;
75 return ($gravity + $air + $mass) / 3;
76 }
77
78 /** Miss chance: 0.60 at power 0, 0.05 at power 1. */
79 public static function missChance(array $planet): float
80 {
81 return 0.60 - 0.55 * self::power($planet);
82 }
83
84 public static function missChanceForId(string $id): float
85 {
86 $p = self::byId($id);
87 if ($p === null) {
88 $p = self::default();
89 }
90 return self::missChance($p);
91 }
92
93 /** @return array{gravity:float,density:float,newtons:float,power:int,missChance:float} */
94 public static function displayValues(array $planet): array
95 {
96 $j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);
97 $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
98 $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
99 $power = self::power($planet);
100 return [
101 'gravity' => 9.81 * $j / 2,
102 'density' => 0.25 + ((5 - $f) / 4) * 1.60,
103 'newtons' => 40 + (($r - 0.5) / 2.5) * 160,
104 'power' => (int) round($power * 100),
105 'missChance' => 0.60 - 0.55 * $power,
106 ];
107 }
108
109 /** Public subset sent to clients (no need to ship the full catalog again). */
110 public static function present(?string $id): array
111 {
112 $p = $id ? self::byId($id) : null;
113 if ($p === null) {
114 $p = self::default();
115 }
116 $d = self::displayValues($p);
117 $colors = [];
118 foreach ($p['colors'] ?? [] as $c) {
119 if (!is_array($c)) {
120 continue;
121 }
122 $colors[] = [
123 'id' => (int) ($c['id'] ?? 0),
124 'name' => (string) ($c['name'] ?? ''),
125 'hex' => (string) ($c['hex'] ?? '#888'),
126 'shape' => (string) ($c['shape'] ?? ''),
127 'image' => (string) ($c['image'] ?? ''),
128 ];
129 }
130 return [
131 'id' => (string) $p['id'],
132 'name' => (string) $p['name'],
133 'people' => (string) $p['people'],
134 'jumpsToClear' => (float) $p['jumpsToClear'],
135 'fallTime' => (float) $p['fallTime'],
136 'riseTime' => (float) $p['riseTime'],
137 'miss_chance' => $d['missChance'],
138 'display' => $d,
139 'colors' => $colors,
140 ];
141 }
142
143 private static function clamp(float $value, float $lo, float $hi): float
144 {
145 return max($lo, min($hi, $value));
146 }
147 }
@@ -0,0 +1,147 @@
1<?php
2declare(strict_types=1);
3
4/**
5 * Planet catalog shared with the JS client (server/lib/planets.json).
6 * Power and miss-chance formulas must stay in lockstep with src/planet.js.
7 */
8final class Planets
9{
10 private static ?array $all = null;
11
12 public static function path(): string
13 {
14 return __DIR__ . '/planets.json';
15 }
16
17 /** @return list<array> raw catalog entries */
18 public static function all(): array
19 {
20 if (self::$all !== null) {
21 return self::$all;
22 }
23 $raw = file_get_contents(self::path());
24 if ($raw === false) {
25 throw new RuntimeException('planets.json ontbreekt.');
26 }
27 $data = json_decode($raw, true);
28 if (!is_array($data) || !isset($data['planets']) || !is_array($data['planets'])) {
29 throw new RuntimeException('planets.json is ongeldig.');
30 }
31 self::$all = [];
32 foreach ($data['planets'] as $row) {
33 if (!is_array($row) || empty($row['id'])) {
34 continue;
35 }
36 self::$all[] = $row;
37 }
38 return self::$all;
39 }
40
41 public static function byId(string $id): ?array
42 {
43 foreach (self::all() as $p) {
44 if (($p['id'] ?? '') === $id) {
45 return $p;
46 }
47 }
48 return null;
49 }
50
51 public static function defaultId(): string
52 {
53 return 'terra';
54 }
55
56 public static function default(): array
57 {
58 return self::byId(self::defaultId()) ?? self::all()[0];
59 }
60
61 public static function known(string $id): bool
62 {
63 return self::byId($id) !== null;
64 }
65
66 /** Difficulty in 0..1. Higher is harder. */
67 public static function power(array $planet): float
68 {
69 $j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);
70 $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
71 $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
72 $gravity = ($j - 1) / 3;
73 $air = (5 - $f) / 4;
74 $mass = (3 - $r) / 2.5;
75 return ($gravity + $air + $mass) / 3;
76 }
77
78 /** Miss chance: 0.60 at power 0, 0.05 at power 1. */
79 public static function missChance(array $planet): float
80 {
81 return 0.60 - 0.55 * self::power($planet);
82 }
83
84 public static function missChanceForId(string $id): float
85 {
86 $p = self::byId($id);
87 if ($p === null) {
88 $p = self::default();
89 }
90 return self::missChance($p);
91 }
92
93 /** @return array{gravity:float,density:float,newtons:float,power:int,missChance:float} */
94 public static function displayValues(array $planet): array
95 {
96 $j = self::clamp((float) ($planet['jumpsToClear'] ?? 2), 1, 4);
97 $f = self::clamp((float) ($planet['fallTime'] ?? 3), 1, 5);
98 $r = self::clamp((float) ($planet['riseTime'] ?? 1.5), 0.5, 3);
99 $power = self::power($planet);
100 return [
101 'gravity' => 9.81 * $j / 2,
102 'density' => 0.25 + ((5 - $f) / 4) * 1.60,
103 'newtons' => 40 + (($r - 0.5) / 2.5) * 160,
104 'power' => (int) round($power * 100),
105 'missChance' => 0.60 - 0.55 * $power,
106 ];
107 }
108
109 /** Public subset sent to clients (no need to ship the full catalog again). */
110 public static function present(?string $id): array
111 {
112 $p = $id ? self::byId($id) : null;
113 if ($p === null) {
114 $p = self::default();
115 }
116 $d = self::displayValues($p);
117 $colors = [];
118 foreach ($p['colors'] ?? [] as $c) {
119 if (!is_array($c)) {
120 continue;
121 }
122 $colors[] = [
123 'id' => (int) ($c['id'] ?? 0),
124 'name' => (string) ($c['name'] ?? ''),
125 'hex' => (string) ($c['hex'] ?? '#888'),
126 'shape' => (string) ($c['shape'] ?? ''),
127 'image' => (string) ($c['image'] ?? ''),
128 ];
129 }
130 return [
131 'id' => (string) $p['id'],
132 'name' => (string) $p['name'],
133 'people' => (string) $p['people'],
134 'jumpsToClear' => (float) $p['jumpsToClear'],
135 'fallTime' => (float) $p['fallTime'],
136 'riseTime' => (float) $p['riseTime'],
137 'miss_chance' => $d['missChance'],
138 'display' => $d,
139 'colors' => $colors,
140 ];
141 }
142
143 private static function clamp(float $value, float $lo, float $hi): float
144 {
145 return max($lo, min($hi, $value));
146 }
147}
server/lib/Store.php +62 −12
@@ -1,6 +1,8 @@
1 1 <?php
2 2 declare(strict_types=1);
3 3
4 require_once __DIR__ . '/Planets.php';
5
4 6 final class Store
5 7 {
6 8 private PDO $pdo;
@@ -71,6 +73,18 @@ CREATE TABLE IF NOT EXISTS shots (
71 73 );
72 74 CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
73 75 SQL);
76 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
77 }
78
79 private function ensureColumn(string $table, string $column, string $ddl): void
80 {
81 $cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
82 foreach ($cols as $c) {
83 if (($c['name'] ?? '') === $column) {
84 return;
85 }
86 }
87 $this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl);
74 88 }
75 89
76 90 public function transaction(callable $fn): mixed
@@ -170,9 +184,9 @@ SQL);
170 184 return $stmt->fetchAll();
171 185 }
172 186
173 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS): array
187 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array
174 188 {
175 return $this->transaction(function () use ($userId, $name, $missChance) {
189 return $this->transaction(function () use ($userId, $name, $missChance, $planetId) {
176 190 $existing = $this->lobbyForUser($userId);
177 191 if ($existing && $existing['status'] !== 'finished') {
178 192 throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
@@ -188,17 +202,18 @@ SQL);
188 202 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
189 203 VALUES (?,?,?,?,?,?,?)'
190 204 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
205 $planet = Planets::known($planetId) ? $planetId : Planets::defaultId();
191 206 $this->pdo->prepare(
192 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen)
193 VALUES (?,?,?,0,?,?)'
194 )->execute([$id, $userId, $name, $now, $now]);
207 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id)
208 VALUES (?,?,?,0,?,?,?)'
209 )->execute([$id, $userId, $name, $now, $now, $planet]);
195 210 return $this->getLobby($id);
196 211 });
197 212 }
198 213
199 public function joinLobby(string $userId, string $name, string $code): array
214 public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array
200 215 {
201 return $this->transaction(function () use ($userId, $name, $code) {
216 return $this->transaction(function () use ($userId, $name, $code, $planetId) {
202 217 $existing = $this->lobbyForUser($userId);
203 218 if ($existing && $existing['status'] !== 'finished') {
204 219 if (strcasecmp($existing['code'], $code) === 0) {
@@ -219,8 +234,8 @@ SQL);
219 234 }
220 235 $now = $this->now();
221 236 $this->pdo->prepare(
222 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot)
223 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL)
237 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id)
238 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?)
224 239 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
225 240 name = excluded.name,
226 241 ready = 0,
@@ -230,8 +245,9 @@ SQL);
230 245 joined = excluded.joined,
231 246 last_seen = excluded.last_seen,
232 247 score = 0,
233 snapshot = NULL'
234 )->execute([$lobby['id'], $userId, $name, $now, $now]);
248 snapshot = NULL,
249 planet_id = excluded.planet_id'
250 )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]);
235 251 return $this->getLobby($lobby['id']);
236 252 });
237 253 }
@@ -323,6 +339,39 @@ SQL);
323 339 }
324 340
325 341 /** @param list<array{client_id?:string,color?:int}> $shots */
342 public function setPlanet(string $userId, string $planetId): array
343 {
344 return $this->transaction(function () use ($userId, $planetId) {
345 $lobby = $this->lobbyForUser($userId);
346 if (!$lobby) {
347 throw new RuntimeException('Je zit in geen lobby.');
348 }
349 if ($lobby['status'] !== 'waiting') {
350 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
351 }
352 if (!Planets::known($planetId)) {
353 throw new RuntimeException('Onbekende planeet.');
354 }
355 $this->pdo->prepare(
356 'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
357 )->execute([$planetId, $this->now(), $lobby['id'], $userId]);
358 return $this->getLobby($lobby['id']);
359 });
360 }
361
362 /** @param array<string,mixed> $member */
363 public function missChanceForMember(array $member): float
364 {
365 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
366 return max(0.0, min(1.0, $this->testMissOverride));
367 }
368 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
369 return Planets::missChanceForId($id);
370 }
371
372 /** @var ?float Tests may force a miss chance without changing the catalog. */
373 public ?float $testMissOverride = null;
374
326 375 public function recordShots(string $userId, array $shots): array
327 376 {
328 377 return $this->transaction(function () use ($userId, $shots) {
@@ -341,7 +390,7 @@ SQL);
341 390 }
342 391 }
343 392 $results = [];
344 $missChance = (float) $lobby['miss_chance'];
393 $missChance = $this->missChanceForMember($me);
345 394 $flight = (float) $lobby['flight_duration'];
346 395 $now = $this->nowf();
347 396 $ins = $this->pdo->prepare(
@@ -580,6 +629,7 @@ SQL);
580 629 'is_me' => $m['user_id'] === $userId,
581 630 'score' => (int) $m['score'],
582 631 'snapshot' => $m['user_id'] === $userId ? null : $snap,
632 'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())),
583 633 ];
584 634 }
585 635 $rankings = [];
@@ -1,6 +1,8 @@
1<?php
1<?php
2declare(strict_types=1);
2declare(strict_types=1);
3
3
4require_once __DIR__ . '/Planets.php';
5
4final class Store
6final class Store
5{
7{
6 private PDO $pdo;
8 private PDO $pdo;
@@ -71,6 +73,18 @@ CREATE TABLE IF NOT EXISTS shots (
71);
73);
72CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
74CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
73SQL);
75SQL);
76 $this->ensureColumn('members', 'planet_id', "TEXT NOT NULL DEFAULT 'terra'");
77 }
78
79 private function ensureColumn(string $table, string $column, string $ddl): void
80 {
81 $cols = $this->pdo->query('PRAGMA table_info(' . $table . ')')->fetchAll();
82 foreach ($cols as $c) {
83 if (($c['name'] ?? '') === $column) {
84 return;
85 }
86 }
87 $this->pdo->exec('ALTER TABLE ' . $table . ' ADD COLUMN ' . $column . ' ' . $ddl);
74 }
88 }
75
89
76 public function transaction(callable $fn): mixed
90 public function transaction(callable $fn): mixed
@@ -170,9 +184,9 @@ SQL);
170 return $stmt->fetchAll();
184 return $stmt->fetchAll();
171 }
185 }
172
186
173 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS): array
187 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS, string $planetId = ''): array
174 {
188 {
175 return $this->transaction(function () use ($userId, $name, $missChance) {
189 return $this->transaction(function () use ($userId, $name, $missChance, $planetId) {
176 $existing = $this->lobbyForUser($userId);
190 $existing = $this->lobbyForUser($userId);
177 if ($existing && $existing['status'] !== 'finished') {
191 if ($existing && $existing['status'] !== 'finished') {
178 throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
192 throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
@@ -188,17 +202,18 @@ SQL);
188 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
202 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
189 VALUES (?,?,?,?,?,?,?)'
203 VALUES (?,?,?,?,?,?,?)'
190 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
204 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
205 $planet = Planets::known($planetId) ? $planetId : Planets::defaultId();
191 $this->pdo->prepare(
206 $this->pdo->prepare(
192 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen)
207 'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen, planet_id)
193 VALUES (?,?,?,0,?,?)'
208 VALUES (?,?,?,0,?,?,?)'
194 )->execute([$id, $userId, $name, $now, $now]);
209 )->execute([$id, $userId, $name, $now, $now, $planet]);
195 return $this->getLobby($id);
210 return $this->getLobby($id);
196 });
211 });
197 }
212 }
198
213
199 public function joinLobby(string $userId, string $name, string $code): array
214 public function joinLobby(string $userId, string $name, string $code, string $planetId = ''): array
200 {
215 {
201 return $this->transaction(function () use ($userId, $name, $code) {
216 return $this->transaction(function () use ($userId, $name, $code, $planetId) {
202 $existing = $this->lobbyForUser($userId);
217 $existing = $this->lobbyForUser($userId);
203 if ($existing && $existing['status'] !== 'finished') {
218 if ($existing && $existing['status'] !== 'finished') {
204 if (strcasecmp($existing['code'], $code) === 0) {
219 if (strcasecmp($existing['code'], $code) === 0) {
@@ -219,8 +234,8 @@ SQL);
219 }
234 }
220 $now = $this->now();
235 $now = $this->now();
221 $this->pdo->prepare(
236 $this->pdo->prepare(
222 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot)
237 'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot, planet_id)
223 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL)
238 VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL,?)
224 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
239 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
225 name = excluded.name,
240 name = excluded.name,
226 ready = 0,
241 ready = 0,
@@ -230,8 +245,9 @@ SQL);
230 joined = excluded.joined,
245 joined = excluded.joined,
231 last_seen = excluded.last_seen,
246 last_seen = excluded.last_seen,
232 score = 0,
247 score = 0,
233 snapshot = NULL'
248 snapshot = NULL,
234 )->execute([$lobby['id'], $userId, $name, $now, $now]);
249 planet_id = excluded.planet_id'
250 )->execute([$lobby['id'], $userId, $name, $now, $now, Planets::known($planetId) ? $planetId : Planets::defaultId()]);
235 return $this->getLobby($lobby['id']);
251 return $this->getLobby($lobby['id']);
236 });
252 });
237 }
253 }
@@ -323,6 +339,39 @@ SQL);
323 }
339 }
324
340
325 /** @param list<array{client_id?:string,color?:int}> $shots */
341 /** @param list<array{client_id?:string,color?:int}> $shots */
342 public function setPlanet(string $userId, string $planetId): array
343 {
344 return $this->transaction(function () use ($userId, $planetId) {
345 $lobby = $this->lobbyForUser($userId);
346 if (!$lobby) {
347 throw new RuntimeException('Je zit in geen lobby.');
348 }
349 if ($lobby['status'] !== 'waiting') {
350 throw new RuntimeException('De planeet kun je alleen kiezen voordat het spel start.');
351 }
352 if (!Planets::known($planetId)) {
353 throw new RuntimeException('Onbekende planeet.');
354 }
355 $this->pdo->prepare(
356 'UPDATE members SET planet_id = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
357 )->execute([$planetId, $this->now(), $lobby['id'], $userId]);
358 return $this->getLobby($lobby['id']);
359 });
360 }
361
362 /** @param array<string,mixed> $member */
363 public function missChanceForMember(array $member): float
364 {
365 if (isset($this->testMissOverride) && is_float($this->testMissOverride)) {
366 return max(0.0, min(1.0, $this->testMissOverride));
367 }
368 $id = (string) ($member['planet_id'] ?? Planets::defaultId());
369 return Planets::missChanceForId($id);
370 }
371
372 /** @var ?float Tests may force a miss chance without changing the catalog. */
373 public ?float $testMissOverride = null;
374
326 public function recordShots(string $userId, array $shots): array
375 public function recordShots(string $userId, array $shots): array
327 {
376 {
328 return $this->transaction(function () use ($userId, $shots) {
377 return $this->transaction(function () use ($userId, $shots) {
@@ -341,7 +390,7 @@ SQL);
341 }
390 }
342 }
391 }
343 $results = [];
392 $results = [];
344 $missChance = (float) $lobby['miss_chance'];
393 $missChance = $this->missChanceForMember($me);
345 $flight = (float) $lobby['flight_duration'];
394 $flight = (float) $lobby['flight_duration'];
346 $now = $this->nowf();
395 $now = $this->nowf();
347 $ins = $this->pdo->prepare(
396 $ins = $this->pdo->prepare(
@@ -580,6 +629,7 @@ SQL);
580 'is_me' => $m['user_id'] === $userId,
629 'is_me' => $m['user_id'] === $userId,
581 'score' => (int) $m['score'],
630 'score' => (int) $m['score'],
582 'snapshot' => $m['user_id'] === $userId ? null : $snap,
631 'snapshot' => $m['user_id'] === $userId ? null : $snap,
632 'planet' => Planets::present((string) ($m['planet_id'] ?? Planets::defaultId())),
583 ];
633 ];
584 }
634 }
585 $rankings = [];
635 $rankings = [];
server/lib/planets.json added +184 −0
@@ -0,0 +1,184 @@
1 {
2 "planets": [
3 {
4 "id": "terra",
5 "name": "Terra",
6 "people": "Terrans",
7 "jumpsToClear": 2,
8 "fallTime": 3,
9 "riseTime": 1.5,
10 "colors": [
11 {"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"},
12 {"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"},
13 {"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"},
14 {"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"},
15 {"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"}
16 ]
17 },
18 {
19 "id": "aurel",
20 "name": "Aurel",
21 "people": "Aurelians",
22 "jumpsToClear": 1,
23 "fallTime": 5,
24 "riseTime": 3,
25 "colors": [
26 {"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"},
27 {"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"},
28 {"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"},
29 {"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"},
30 {"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"}
31 ]
32 },
33 {
34 "id": "cinder",
35 "name": "Cinder",
36 "people": "Cindari",
37 "jumpsToClear": 4,
38 "fallTime": 1,
39 "riseTime": 0.5,
40 "colors": [
41 {"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"},
42 {"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"},
43 {"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"},
44 {"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"},
45 {"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"}
46 ]
47 },
48 {
49 "id": "lunara",
50 "name": "Lunara",
51 "people": "Lunarites",
52 "jumpsToClear": 1,
53 "fallTime": 2,
54 "riseTime": 1.2,
55 "colors": [
56 {"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"},
57 {"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"},
58 {"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"},
59 {"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"},
60 {"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"}
61 ]
62 },
63 {
64 "id": "mire",
65 "name": "Mire",
66 "people": "Mirians",
67 "jumpsToClear": 2,
68 "fallTime": 5,
69 "riseTime": 2.5,
70 "colors": [
71 {"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"},
72 {"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"},
73 {"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"},
74 {"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"},
75 {"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"}
76 ]
77 },
78 {
79 "id": "galeon",
80 "name": "Galeon",
81 "people": "Galeoni",
82 "jumpsToClear": 3,
83 "fallTime": 1,
84 "riseTime": 1.8,
85 "colors": [
86 {"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"},
87 {"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"},
88 {"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"},
89 {"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"},
90 {"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"}
91 ]
92 },
93 {
94 "id": "obsid",
95 "name": "Obsid",
96 "people": "Obsidians",
97 "jumpsToClear": 4,
98 "fallTime": 3.5,
99 "riseTime": 2.2,
100 "colors": [
101 {"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"},
102 {"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"},
103 {"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"},
104 {"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"},
105 {"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"}
106 ]
107 },
108 {
109 "id": "wisp",
110 "name": "Wisp",
111 "people": "Wisplings",
112 "jumpsToClear": 2,
113 "fallTime": 3.5,
114 "riseTime": 0.5,
115 "colors": [
116 {"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"},
117 {"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"},
118 {"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"},
119 {"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"},
120 {"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"}
121 ]
122 },
123 {
124 "id": "thorn",
125 "name": "Thorn",
126 "people": "Thornfolk",
127 "jumpsToClear": 3,
128 "fallTime": 2,
129 "riseTime": 1.0,
130 "colors": [
131 {"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"},
132 {"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"},
133 {"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"},
134 {"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"},
135 {"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"}
136 ]
137 },
138 {
139 "id": "zephyr",
140 "name": "Zephyr",
141 "people": "Zephyrites",
142 "jumpsToClear": 1,
143 "fallTime": 1.2,
144 "riseTime": 2.8,
145 "colors": [
146 {"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"},
147 {"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"},
148 {"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"},
149 {"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"},
150 {"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"}
151 ]
152 },
153 {
154 "id": "frore",
155 "name": "Frore",
156 "people": "Frorians",
157 "jumpsToClear": 3,
158 "fallTime": 4.5,
159 "riseTime": 0.8,
160 "colors": [
161 {"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"},
162 {"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"},
163 {"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"},
164 {"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"},
165 {"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"}
166 ]
167 },
168 {
169 "id": "forge",
170 "name": "Forge",
171 "people": "Forgelings",
172 "jumpsToClear": 4,
173 "fallTime": 2,
174 "riseTime": 1.5,
175 "colors": [
176 {"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"},
177 {"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"},
178 {"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"},
179 {"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"},
180 {"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"}
181 ]
182 }
183 ]
184 }
@@ -0,0 +1,184 @@
1{
2 "planets": [
3 {
4 "id": "terra",
5 "name": "Terra",
6 "people": "Terrans",
7 "jumpsToClear": 2,
8 "fallTime": 3,
9 "riseTime": 1.5,
10 "colors": [
11 {"id": 0, "name": "ember", "hex": "#e85d3a", "shape": "triangle", "image": "images/block-terra-ember.png"},
12 {"id": 1, "name": "aqua", "hex": "#3db8e8", "shape": "circle", "image": "images/block-terra-aqua.png"},
13 {"id": 2, "name": "leaf", "hex": "#4cbf4c", "shape": "square", "image": "images/block-terra-leaf.png"},
14 {"id": 3, "name": "sun", "hex": "#f0c53a", "shape": "diamond", "image": "images/block-terra-sun.png"},
15 {"id": 4, "name": "orchid", "hex": "#c45ad4", "shape": "star", "image": "images/block-terra-orchid.png"}
16 ]
17 },
18 {
19 "id": "aurel",
20 "name": "Aurel",
21 "people": "Aurelians",
22 "jumpsToClear": 1,
23 "fallTime": 5,
24 "riseTime": 3,
25 "colors": [
26 {"id": 0, "name": "gold", "hex": "#f4c860", "shape": "hexagon", "image": "images/block-aurel-gold.png"},
27 {"id": 1, "name": "cream", "hex": "#f6e7c1", "shape": "circle", "image": "images/block-aurel-cream.png"},
28 {"id": 2, "name": "amber", "hex": "#e09a3e", "shape": "teardrop", "image": "images/block-aurel-amber.png"},
29 {"id": 3, "name": "sage", "hex": "#8fb86f", "shape": "plus", "image": "images/block-aurel-sage.png"},
30 {"id": 4, "name": "rose", "hex": "#e8a0a8", "shape": "pentagon", "image": "images/block-aurel-rose.png"}
31 ]
32 },
33 {
34 "id": "cinder",
35 "name": "Cinder",
36 "people": "Cindari",
37 "jumpsToClear": 4,
38 "fallTime": 1,
39 "riseTime": 0.5,
40 "colors": [
41 {"id": 0, "name": "magma", "hex": "#ff3b1f", "shape": "triangle", "image": "images/block-cinder-magma.png"},
42 {"id": 1, "name": "coal", "hex": "#3a3232", "shape": "square", "image": "images/block-cinder-coal.png"},
43 {"id": 2, "name": "spark", "hex": "#ffb347", "shape": "diamond", "image": "images/block-cinder-spark.png"},
44 {"id": 3, "name": "ash", "hex": "#8a7a76", "shape": "circle", "image": "images/block-cinder-ash.png"},
45 {"id": 4, "name": "core", "hex": "#ff6a00", "shape": "star", "image": "images/block-cinder-core.png"}
46 ]
47 },
48 {
49 "id": "lunara",
50 "name": "Lunara",
51 "people": "Lunarites",
52 "jumpsToClear": 1,
53 "fallTime": 2,
54 "riseTime": 1.2,
55 "colors": [
56 {"id": 0, "name": "silver", "hex": "#c5d0e0", "shape": "circle", "image": "images/block-lunara-silver.png"},
57 {"id": 1, "name": "dust", "hex": "#8b90a0", "shape": "diamond", "image": "images/block-lunara-dust.png"},
58 {"id": 2, "name": "pale", "hex": "#e8d9a8", "shape": "crescent", "image": "images/block-lunara-pale.png"},
59 {"id": 3, "name": "void", "hex": "#2c3348", "shape": "square", "image": "images/block-lunara-void.png"},
60 {"id": 4, "name": "lilac", "hex": "#b9a4d4", "shape": "star", "image": "images/block-lunara-lilac.png"}
61 ]
62 },
63 {
64 "id": "mire",
65 "name": "Mire",
66 "people": "Mirians",
67 "jumpsToClear": 2,
68 "fallTime": 5,
69 "riseTime": 2.5,
70 "colors": [
71 {"id": 0, "name": "moss", "hex": "#3d7a45", "shape": "hexagon", "image": "images/block-mire-moss.png"},
72 {"id": 1, "name": "bog", "hex": "#1f4d3a", "shape": "teardrop", "image": "images/block-mire-bog.png"},
73 {"id": 2, "name": "rust", "hex": "#8b5a2b", "shape": "pentagon", "image": "images/block-mire-rust.png"},
74 {"id": 3, "name": "spore", "hex": "#9cbf5a", "shape": "circle", "image": "images/block-mire-spore.png"},
75 {"id": 4, "name": "murk", "hex": "#2e3b2f", "shape": "diamond", "image": "images/block-mire-murk.png"}
76 ]
77 },
78 {
79 "id": "galeon",
80 "name": "Galeon",
81 "people": "Galeoni",
82 "jumpsToClear": 3,
83 "fallTime": 1,
84 "riseTime": 1.8,
85 "colors": [
86 {"id": 0, "name": "sky", "hex": "#4aa3ff", "shape": "arrow", "image": "images/block-galeon-sky.png"},
87 {"id": 1, "name": "cloud", "hex": "#e8eef6", "shape": "circle", "image": "images/block-galeon-cloud.png"},
88 {"id": 2, "name": "storm", "hex": "#3d4d6e", "shape": "square", "image": "images/block-galeon-storm.png"},
89 {"id": 3, "name": "sand", "hex": "#d4b483", "shape": "diamond","image": "images/block-galeon-sand.png"},
90 {"id": 4, "name": "kite", "hex": "#7fd0c0", "shape": "star", "image": "images/block-galeon-kite.png"}
91 ]
92 },
93 {
94 "id": "obsid",
95 "name": "Obsid",
96 "people": "Obsidians",
97 "jumpsToClear": 4,
98 "fallTime": 3.5,
99 "riseTime": 2.2,
100 "colors": [
101 {"id": 0, "name": "glass", "hex": "#1a1a22", "shape": "gem", "image": "images/block-obsid-glass.png"},
102 {"id": 1, "name": "violet","hex": "#5a3d8a", "shape": "hexagon", "image": "images/block-obsid-violet.png"},
103 {"id": 2, "name": "shard", "hex": "#8a8aa0", "shape": "triangle", "image": "images/block-obsid-shard.png"},
104 {"id": 3, "name": "vein", "hex": "#c45a3a", "shape": "diamond", "image": "images/block-obsid-vein.png"},
105 {"id": 4, "name": "basalt","hex": "#3a3a42", "shape": "square", "image": "images/block-obsid-basalt.png"}
106 ]
107 },
108 {
109 "id": "wisp",
110 "name": "Wisp",
111 "people": "Wisplings",
112 "jumpsToClear": 2,
113 "fallTime": 3.5,
114 "riseTime": 0.5,
115 "colors": [
116 {"id": 0, "name": "glow", "hex": "#c8ffe0", "shape": "circle", "image": "images/block-wisp-glow.png"},
117 {"id": 1, "name": "mist", "hex": "#a8d4e8", "shape": "diamond", "image": "images/block-wisp-mist.png"},
118 {"id": 2, "name": "sparkle", "hex": "#fff6a8", "shape": "star", "image": "images/block-wisp-sparkle.png"},
119 {"id": 3, "name": "veil", "hex": "#d0b8f0", "shape": "teardrop", "image": "images/block-wisp-veil.png"},
120 {"id": 4, "name": "gleam", "hex": "#f4f7ff", "shape": "plus", "image": "images/block-wisp-gleam.png"}
121 ]
122 },
123 {
124 "id": "thorn",
125 "name": "Thorn",
126 "people": "Thornfolk",
127 "jumpsToClear": 3,
128 "fallTime": 2,
129 "riseTime": 1.0,
130 "colors": [
131 {"id": 0, "name": "briar", "hex": "#5a7a30", "shape": "triangle", "image": "images/block-thorn-briar.png"},
132 {"id": 1, "name": "berry", "hex": "#8b1a4a", "shape": "circle", "image": "images/block-thorn-berry.png"},
133 {"id": 2, "name": "bark", "hex": "#5a3a20", "shape": "square", "image": "images/block-thorn-bark.png"},
134 {"id": 3, "name": "petal", "hex": "#e89ab0", "shape": "diamond", "image": "images/block-thorn-petal.png"},
135 {"id": 4, "name": "gold", "hex": "#c8a030", "shape": "star", "image": "images/block-thorn-gold.png"}
136 ]
137 },
138 {
139 "id": "zephyr",
140 "name": "Zephyr",
141 "people": "Zephyrites",
142 "jumpsToClear": 1,
143 "fallTime": 1.2,
144 "riseTime": 2.8,
145 "colors": [
146 {"id": 0, "name": "azure", "hex": "#6ec8ff", "shape": "crescent", "image": "images/block-zephyr-azure.png"},
147 {"id": 1, "name": "breeze","hex": "#b8e8ff", "shape": "circle", "image": "images/block-zephyr-breeze.png"},
148 {"id": 2, "name": "cirrus","hex": "#f0f7ff", "shape": "plus", "image": "images/block-zephyr-cirrus.png"},
149 {"id": 3, "name": "dusk", "hex": "#7a6ab0", "shape": "diamond", "image": "images/block-zephyr-dusk.png"},
150 {"id": 4, "name": "haze", "hex": "#ffe08a", "shape": "star", "image": "images/block-zephyr-haze.png"}
151 ]
152 },
153 {
154 "id": "frore",
155 "name": "Frore",
156 "people": "Frorians",
157 "jumpsToClear": 3,
158 "fallTime": 4.5,
159 "riseTime": 0.8,
160 "colors": [
161 {"id": 0, "name": "ice", "hex": "#a8d8f0", "shape": "hexagon", "image": "images/block-frore-ice.png"},
162 {"id": 1, "name": "frost", "hex": "#eef7ff", "shape": "circle", "image": "images/block-frore-frost.png"},
163 {"id": 2, "name": "deep", "hex": "#3a6a8a", "shape": "diamond", "image": "images/block-frore-deep.png"},
164 {"id": 3, "name": "aurora", "hex": "#5ae8c0", "shape": "star", "image": "images/block-frore-aurora.png"},
165 {"id": 4, "name": "rime", "hex": "#d0e4f0", "shape": "triangle", "image": "images/block-frore-rime.png"}
166 ]
167 },
168 {
169 "id": "forge",
170 "name": "Forge",
171 "people": "Forgelings",
172 "jumpsToClear": 4,
173 "fallTime": 2,
174 "riseTime": 1.5,
175 "colors": [
176 {"id": 0, "name": "iron", "hex": "#6a6a72", "shape": "square", "image": "images/block-forge-iron.png"},
177 {"id": 1, "name": "slag", "hex": "#3a3028", "shape": "hexagon", "image": "images/block-forge-slag.png"},
178 {"id": 2, "name": "spark", "hex": "#ff7a1a", "shape": "triangle", "image": "images/block-forge-spark.png"},
179 {"id": 3, "name": "brass", "hex": "#c8a048", "shape": "diamond", "image": "images/block-forge-brass.png"},
180 {"id": 4, "name": "soot", "hex": "#2a2a28", "shape": "circle", "image": "images/block-forge-soot.png"}
181 ]
182 }
183 ]
184}
server/tests/run.php +61 −2
@@ -147,12 +147,14 @@ $store->joinLobby('local:test_user_2', 'test_user_2', $c['code']);
147 147 $store->setReady('local:test_user_1', true);
148 148 $store->setReady('local:test_user_2', true);
149 149 $store->startGame('local:test_user_1');
150 $store->testMissOverride = 1.0;
150 151 $allMiss = $store->recordShots('local:test_user_1', [
151 152 ['client_id' => 'm1', 'color' => 0],
152 153 ['client_id' => 'm2', 'color' => 1],
153 154 ['client_id' => 'm3', 'color' => 2],
154 155 ]);
155 expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'miss_chance 1.0 → all miss');
156 $store->testMissOverride = null;
157 expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'forced miss 1.0 → all miss');
156 158
157 159 $d = null;
158 160 $store->leaveLobby('local:test_user_1');
@@ -162,11 +164,13 @@ $store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);
162 164 $store->setReady('local:test_user_1', true);
163 165 $store->setReady('local:test_user_2', true);
164 166 $store->startGame('local:test_user_1');
167 $store->testMissOverride = 0.0;
165 168 $allHit = $store->recordShots('local:test_user_1', [
166 169 ['client_id' => 'h1', 'color' => 0],
167 170 ['client_id' => 'h2', 'color' => 1],
168 171 ]);
169 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');
172 $store->testMissOverride = null;
173 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');
170 174
171 175 // Eliminated player is not a target.
172 176 $store->updateSnapshot('local:test_user_2', null, 0, true);
@@ -174,7 +178,62 @@ $none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' =
174 178 // Game may already be finished; recordShots on finished returns [].
175 179 expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');
176 180
181
182 echo "\nPlanets and per-sender Power miss\n";
183 expect(count(Planets::all()) >= 8 && count(Planets::all()) <= 12, 'catalog has 8–12 planets');
184 expect(Planets::known('terra') && Planets::known('cinder') && Planets::known('aurel'), 'terra, cinder, aurel exist');
185 expect(almostEqual(Planets::power(Planets::byId('aurel')), 0.0), 'Aurel power 0');
186 expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60), 'Aurel miss 60%');
187 expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');
188 expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');
189 $td = Planets::displayValues(Planets::byId('terra'));
190 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');
191
192 $store->leaveLobby('local:test_user_1');
193 $store->leaveLobby('local:test_user_2');
194 $pl = $store->createLobby('local:test_user_1', 'test_user_1', 0.30, 'aurel');
195 $store->joinLobby('local:test_user_2', 'test_user_2', $pl['code'], 'cinder');
196 $presented = $store->presentLobby($pl, 'local:test_user_1');
197 $byId = [];
198 foreach ($presented['players'] as $plr) { $byId[$plr['id']] = $plr; }
199 expect($byId['local:test_user_1']['planet']['id'] === 'aurel', 'host planet aurel');
200 expect($byId['local:test_user_2']['planet']['id'] === 'cinder', 'guest planet cinder');
201 expect(almostEqual($byId['local:test_user_1']['planet']['miss_chance'], 0.60), 'host miss from Aurel Power');
202 expect(almostEqual($byId['local:test_user_2']['planet']['miss_chance'], 0.05), 'guest miss from Cinder Power');
203
204 $store->setPlanet('local:test_user_1', 'wisp');
205 $presented = $store->presentLobby($store->getLobby($pl['id']), 'local:test_user_1');
206 foreach ($presented['players'] as $plr) {
207 if ($plr['is_me']) {
208 expect($plr['planet']['id'] === 'wisp', 'setPlanet updates host to Wisp');
209 }
210 }
211
212 try {
213 $store->setPlanet('local:test_user_1', 'no-such-world');
214 expect(false, 'unknown planet must throw');
215 } catch (RuntimeException $e) {
216 expect(true, 'unknown planet rejected');
217 }
218
219 $store->setReady('local:test_user_1', true);
220 $store->setReady('local:test_user_2', true);
221 $store->startGame('local:test_user_1');
222 $me = $store->member($pl['id'], 'local:test_user_1');
223 expect(almostEqual($store->missChanceForMember($me), Planets::missChanceForId('wisp')), 'in-game miss uses the sender planet');
224 $guest = $store->member($pl['id'], 'local:test_user_2');
225 expect(almostEqual($store->missChanceForMember($guest), 0.05), 'guest still uses Cinder Power');
226 try {
227 $store->setPlanet('local:test_user_1', 'terra');
228 expect(false, 'setPlanet during play must throw');
229 } catch (RuntimeException $e) {
230 expect(true, 'planet locked once the match starts');
231 }
232 $store->leaveLobby('local:test_user_1');
233 $store->leaveLobby('local:test_user_2');
234
177 235 echo "\nConfig helpers\n";
236
178 237 $cfg = config();
179 238 expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
180 239 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']);
147$store->setReady('local:test_user_1', true);
147$store->setReady('local:test_user_1', true);
148$store->setReady('local:test_user_2', true);
148$store->setReady('local:test_user_2', true);
149$store->startGame('local:test_user_1');
149$store->startGame('local:test_user_1');
150$store->testMissOverride = 1.0;
150$allMiss = $store->recordShots('local:test_user_1', [
151$allMiss = $store->recordShots('local:test_user_1', [
151 ['client_id' => 'm1', 'color' => 0],
152 ['client_id' => 'm1', 'color' => 0],
152 ['client_id' => 'm2', 'color' => 1],
153 ['client_id' => 'm2', 'color' => 1],
153 ['client_id' => 'm3', 'color' => 2],
154 ['client_id' => 'm3', 'color' => 2],
154]);
155]);
155expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'miss_chance 1.0 → all miss');
156$store->testMissOverride = null;
157expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'forced miss 1.0 → all miss');
156
158
157$d = null;
159$d = null;
158$store->leaveLobby('local:test_user_1');
160$store->leaveLobby('local:test_user_1');
@@ -162,11 +164,13 @@ $store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);
162$store->setReady('local:test_user_1', true);
164$store->setReady('local:test_user_1', true);
163$store->setReady('local:test_user_2', true);
165$store->setReady('local:test_user_2', true);
164$store->startGame('local:test_user_1');
166$store->startGame('local:test_user_1');
167$store->testMissOverride = 0.0;
165$allHit = $store->recordShots('local:test_user_1', [
168$allHit = $store->recordShots('local:test_user_1', [
166 ['client_id' => 'h1', 'color' => 0],
169 ['client_id' => 'h1', 'color' => 0],
167 ['client_id' => 'h2', 'color' => 1],
170 ['client_id' => 'h2', 'color' => 1],
168]);
171]);
169expect(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');
172$store->testMissOverride = null;
173expect(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');
170
174
171// Eliminated player is not a target.
175// Eliminated player is not a target.
172$store->updateSnapshot('local:test_user_2', null, 0, true);
176$store->updateSnapshot('local:test_user_2', null, 0, true);
@@ -174,7 +178,62 @@ $none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' =
174// Game may already be finished; recordShots on finished returns [].
178// Game may already be finished; recordShots on finished returns [].
175expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');
179expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');
176
180
181
182echo "\nPlanets and per-sender Power miss\n";
183expect(count(Planets::all()) >= 8 && count(Planets::all()) <= 12, 'catalog has 8–12 planets');
184expect(Planets::known('terra') && Planets::known('cinder') && Planets::known('aurel'), 'terra, cinder, aurel exist');
185expect(almostEqual(Planets::power(Planets::byId('aurel')), 0.0), 'Aurel power 0');
186expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60), 'Aurel miss 60%');
187expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');
188expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');
189$td = Planets::displayValues(Planets::byId('terra'));
190expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 48, 'Terra display g/d/F/Power');
191
192$store->leaveLobby('local:test_user_1');
193$store->leaveLobby('local:test_user_2');
194$pl = $store->createLobby('local:test_user_1', 'test_user_1', 0.30, 'aurel');
195$store->joinLobby('local:test_user_2', 'test_user_2', $pl['code'], 'cinder');
196$presented = $store->presentLobby($pl, 'local:test_user_1');
197$byId = [];
198foreach ($presented['players'] as $plr) { $byId[$plr['id']] = $plr; }
199expect($byId['local:test_user_1']['planet']['id'] === 'aurel', 'host planet aurel');
200expect($byId['local:test_user_2']['planet']['id'] === 'cinder', 'guest planet cinder');
201expect(almostEqual($byId['local:test_user_1']['planet']['miss_chance'], 0.60), 'host miss from Aurel Power');
202expect(almostEqual($byId['local:test_user_2']['planet']['miss_chance'], 0.05), 'guest miss from Cinder Power');
203
204$store->setPlanet('local:test_user_1', 'wisp');
205$presented = $store->presentLobby($store->getLobby($pl['id']), 'local:test_user_1');
206foreach ($presented['players'] as $plr) {
207 if ($plr['is_me']) {
208 expect($plr['planet']['id'] === 'wisp', 'setPlanet updates host to Wisp');
209 }
210}
211
212try {
213 $store->setPlanet('local:test_user_1', 'no-such-world');
214 expect(false, 'unknown planet must throw');
215} catch (RuntimeException $e) {
216 expect(true, 'unknown planet rejected');
217}
218
219$store->setReady('local:test_user_1', true);
220$store->setReady('local:test_user_2', true);
221$store->startGame('local:test_user_1');
222$me = $store->member($pl['id'], 'local:test_user_1');
223expect(almostEqual($store->missChanceForMember($me), Planets::missChanceForId('wisp')), 'in-game miss uses the sender planet');
224$guest = $store->member($pl['id'], 'local:test_user_2');
225expect(almostEqual($store->missChanceForMember($guest), 0.05), 'guest still uses Cinder Power');
226try {
227 $store->setPlanet('local:test_user_1', 'terra');
228 expect(false, 'setPlanet during play must throw');
229} catch (RuntimeException $e) {
230 expect(true, 'planet locked once the match starts');
231}
232$store->leaveLobby('local:test_user_1');
233$store->leaveLobby('local:test_user_2');
234
177echo "\nConfig helpers\n";
235echo "\nConfig helpers\n";
236
178$cfg = config();
237$cfg = config();
179expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
238expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
180expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
239expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
src/build.sh +6 −1
@@ -26,6 +26,9 @@ FILES=(
26 26 printf '%s\n' " * AUTO-GENERATED FILE — DO NOT EDIT BY HAND."
27 27 printf '%s\n' " * Built by src/build.sh from the sources in src/."
28 28 printf '%s\n' " */"
29 printf '%s' "var PLANET_CATALOG = "
30 cat "$ROOT/server/lib/planets.json"
31 printf ';\n'
29 32 } >> "$BUILD_FILE"
30 33
31 34 for file in "${FILES[@]}"
@@ -48,7 +51,9 @@ cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
48 51 "$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
49 52 "$ROOT/build/"
50 53 mkdir -p "$ROOT/build/lib"
51 cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" "$ROOT/build/lib/"
54 cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \
55 "$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \
56 "$ROOT/build/lib/"
52 57 mkdir -p "$ROOT/build/data"
53 58 cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
54 59 # Belt and braces: a leftover local config or db must never enter build/.
@@ -26,6 +26,9 @@ FILES=(
26 printf '%s\n' " * AUTO-GENERATED FILE — DO NOT EDIT BY HAND."
26 printf '%s\n' " * AUTO-GENERATED FILE — DO NOT EDIT BY HAND."
27 printf '%s\n' " * Built by src/build.sh from the sources in src/."
27 printf '%s\n' " * Built by src/build.sh from the sources in src/."
28 printf '%s\n' " */"
28 printf '%s\n' " */"
29 printf '%s' "var PLANET_CATALOG = "
30 cat "$ROOT/server/lib/planets.json"
31 printf ';\n'
29} >> "$BUILD_FILE"
32} >> "$BUILD_FILE"
30
33
31for file in "${FILES[@]}"
34for file in "${FILES[@]}"
@@ -48,7 +51,9 @@ cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
48 "$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
51 "$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
49 "$ROOT/build/"
52 "$ROOT/build/"
50mkdir -p "$ROOT/build/lib"
53mkdir -p "$ROOT/build/lib"
51cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" "$ROOT/build/lib/"
54cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" \
55 "$SERVER/lib/Planets.php" "$SERVER/lib/planets.json" \
56 "$ROOT/build/lib/"
52mkdir -p "$ROOT/build/data"
57mkdir -p "$ROOT/build/data"
53cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
58cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
54# Belt and braces: a leftover local config or db must never enter build/.
59# Belt and braces: a leftover local config or db must never enter build/.
src/gameCore.js +3 −0
@@ -87,6 +87,9 @@ function optsMissChance (args)
87 87 // GameCore(planet, rng, missChance) — third arg is optional.
88 88 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
89 89 { return Math.max(0, Math.min(1, args[2])); }
90 var planet = args[0];
91 if (planet && typeof PlanetMod.missChance === 'function')
92 { return PlanetMod.missChance(planet); }
90 93 return GameCore.DEFAULT_MISS_CHANCE;
91 94 }
92 95
@@ -87,6 +87,9 @@ function optsMissChance (args)
87 // GameCore(planet, rng, missChance) — third arg is optional.
87 // GameCore(planet, rng, missChance) — third arg is optional.
88 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
88 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
89 { return Math.max(0, Math.min(1, args[2])); }
89 { return Math.max(0, Math.min(1, args[2])); }
90 var planet = args[0];
91 if (planet && typeof PlanetMod.missChance === 'function')
92 { return PlanetMod.missChance(planet); }
90 return GameCore.DEFAULT_MISS_CHANCE;
93 return GameCore.DEFAULT_MISS_CHANCE;
91}
94}
92
95
src/main.js +202 −31
@@ -7,20 +7,37 @@
7 7 * through Online (src/online.js) and the same GameCore.
8 8 */
9 9
10 var IMAGES = [
11 { name: 'ember', url: 'images/block-ember.png' },
12 { name: 'aqua', url: 'images/block-aqua.png' },
13 { name: 'leaf', url: 'images/block-leaf.png' },
14 { name: 'sun', url: 'images/block-sun.png' },
15 { name: 'orchid', url: 'images/block-orchid.png' },
16 { name: 'gray', url: 'images/block-gray.png' },
17 { name: 'locked', url: 'images/block-locked.png' },
18 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
19 { name: 'cell', url: 'images/cell.png' },
20 { name: 'pixel', url: 'images/pixel.png' }
21 ];
22
23 var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
10 function planetImages ()
11 {
12 var list = [
13 { name: 'gray', url: 'images/block-gray.png' },
14 { name: 'locked', url: 'images/block-locked.png' },
15 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
16 { name: 'cell', url: 'images/cell.png' },
17 { name: 'pixel', url: 'images/pixel.png' },
18 // Keep the original Terra placeholders as aliases (Tim may still have them).
19 { name: 'ember', url: 'images/block-ember.png' },
20 { name: 'aqua', url: 'images/block-aqua.png' },
21 { name: 'leaf', url: 'images/block-leaf.png' },
22 { name: 'sun', url: 'images/block-sun.png' },
23 { name: 'orchid', url: 'images/block-orchid.png' }
24 ];
25 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
26 for (var i = 0; i < planets.length; i++)
27 {
28 var pl = planets[i];
29 for (var c = 0; c < pl.colors.length; c++)
30 {
31 list.push({
32 name: Planet.spriteKey(pl, c),
33 url: pl.colors[c].image
34 });
35 }
36 }
37 return list;
38 }
39
40 var IMAGES = planetImages();
24 41 var GAME_OVER_DELAY = 2;
25 42
26 43 var game = new Game();
@@ -46,7 +63,9 @@ var app = {
46 63 online: false,
47 64 eliminatedReported: false,
48 65 spectating: false,
49 miniH: 0
66 miniH: 0,
67 selectedPlanetId: 'terra',
68 planetSelectContext: 'solo'
50 69 };
51 70
52 71 window.onload = function ()
@@ -71,13 +90,15 @@ window.onload = function ()
71 90 });
72 91
73 92 bindOnlineUi();
93 bindPlanetSelect();
94 restoreSelectedPlanet();
74 95 };
75 96
76 97 function onPlay ()
77 98 {
78 99 if (app.mode === 'playing')
79 100 { return; }
80 startPlay();
101 openPlanetSelect('solo');
81 102 }
82 103
83 104 function startPlay (opts)
@@ -88,14 +109,15 @@ function startPlay (opts)
88 109 hideEl('online-panel');
89 110 hideEl('spectator');
90 111 hideEl('podium');
112 hideEl('planet-select');
91 113 showEl('hud');
92 114
93 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
115 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
116 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
94 117 var miss = opts.missChance;
95 if (typeof miss === 'number' && isFinite(miss))
96 { app.core = new GameCore(app.planet, Math.random, miss); }
97 else
98 { app.core = new GameCore(app.planet, Math.random); }
118 if (typeof miss !== 'number' || !isFinite(miss))
119 { miss = planetMod.missChance(app.planet); }
120 app.core = new GameCore(app.planet, Math.random, miss);
99 121 app.mode = 'playing';
100 122 app.online = !!opts.online;
101 123 app.gameOverShown = false;
@@ -164,6 +186,7 @@ function returnToMenu ()
164 186 teardownPlay();
165 187 app.mode = 'menu';
166 188 app.online = false;
189 hideEl('planet-select');
167 190 showEl('menu');
168 191 var last = document.getElementById('last-score');
169 192 if (app.lastScore > 0)
@@ -247,7 +270,8 @@ function spriteFor (block)
247 270 { return game.images.locked; }
248 271 if (block.color < 0)
249 272 { return game.images.gray; }
250 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
273 var key = Planet.spriteKey(app.planet, block.color);
274 return game.images[key] || game.images.gray;
251 275 }
252 276
253 277 function syncSprites ()
@@ -406,10 +430,7 @@ function refreshHud ()
406 430 document.getElementById('score').textContent = String(app.core.score);
407 431 var planet = app.planet;
408 432 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
409 var d = Planet.displayValues(planet);
410 document.getElementById('planet-stats').textContent =
411 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
412 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
433 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
413 434 }
414 435
415 436 function makeManager ()
@@ -687,10 +708,11 @@ function startOnlineMatch ()
687 708 {
688 709 if (app.mode === 'playing' && app.online)
689 710 { return; }
690 var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
691 ? Online.lobby.miss_chance
692 : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
693 startPlay({ online: true, missChance: miss });
711 var planet = Planet.planetById(selectedPlanetId());
712 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
713 if (me && me.planet && me.planet.id)
714 { planet = Planet.planetById(me.planet.id); }
715 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
694 716 if (typeof Online !== 'undefined')
695 717 { Online.startPolling(onlinePayload); }
696 718 }
@@ -847,6 +869,7 @@ function openOnlinePanel ()
847 869 hideEl('game-over');
848 870 hideEl('podium');
849 871 hideEl('spectator');
872 hideEl('planet-select');
850 873 showEl('online-panel');
851 874 app.mode = 'online';
852 875 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
@@ -948,10 +971,14 @@ function renderOnline ()
948 971 { li.classList.add('you'); }
949 972 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
950 973 var state = p.ready ? 'Gereed' : 'Wacht…';
951 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
974 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
975 li.innerHTML = '<span>' + escapeText(label)
976 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
977 + '</span><span class="'
952 978 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
953 979 list.appendChild(li);
954 980 }
981 renderPlanetGrid('lobby-planet-grid', true);
955 982 var me = Online.mePlayer();
956 983 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
957 984 var start = document.getElementById('btn-start');
@@ -984,3 +1011,147 @@ function escapeText (s)
984 1011 .replace(/>/g, '&gt;')
985 1012 .replace(/"/g, '&quot;');
986 1013 }
1014
1015
1016 function selectedPlanetId ()
1017 {
1018 if (app.selectedPlanetId)
1019 { return app.selectedPlanetId; }
1020 return 'terra';
1021 }
1022
1023 function restoreSelectedPlanet ()
1024 {
1025 var id = 'terra';
1026 try
1027 { id = localStorage.getItem('meteors-planet') || 'terra'; }
1028 catch (e) {}
1029 setSelectedPlanet(id, true);
1030 }
1031
1032 function setSelectedPlanet (id, silent)
1033 {
1034 var all = Planet.allPlanets();
1035 var found = null;
1036 for (var i = 0; i < all.length; i++)
1037 {
1038 if (all[i].id === id)
1039 { found = all[i]; break; }
1040 }
1041 if (!found)
1042 { found = Planet.defaultPlanet(); }
1043 app.selectedPlanetId = found.id;
1044 try
1045 { localStorage.setItem('meteors-planet', found.id); }
1046 catch (e) {}
1047 if (!silent)
1048 {
1049 var grid = document.getElementById('planet-grid');
1050 if (grid && !grid.hidden && grid.children.length)
1051 { renderPlanetGrid('planet-grid', false); }
1052 var lobby = document.getElementById('lobby-planet-grid');
1053 if (lobby && lobby.children.length)
1054 { renderPlanetGrid('lobby-planet-grid', true); }
1055 }
1056 return found;
1057 }
1058
1059 function openPlanetSelect (context)
1060 {
1061 if (app.mode === 'playing')
1062 { return; }
1063 app.planetSelectContext = context || 'solo';
1064 app.mode = 'planet-select';
1065 hideEl('menu');
1066 hideEl('online-panel');
1067 hideEl('game-over');
1068 showEl('planet-select');
1069 renderPlanetGrid('planet-grid', false);
1070 var go = document.getElementById('btn-planet-go');
1071 if (go)
1072 { go.textContent = 'Spelen'; }
1073 }
1074
1075 function renderPlanetGrid (containerId, compact)
1076 {
1077 var grid = document.getElementById(containerId);
1078 if (!grid)
1079 { return; }
1080 var current = selectedPlanetId();
1081 var all = Planet.allPlanets();
1082 grid.innerHTML = '';
1083 if (compact)
1084 { grid.classList.add('compact'); }
1085 for (var i = 0; i < all.length; i++)
1086 {
1087 var pl = all[i];
1088 var btn = document.createElement('button');
1089 btn.type = 'button';
1090 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
1091 btn.setAttribute('role', 'listitem');
1092 btn.dataset.planet = pl.id;
1093 var swatches = '';
1094 for (var c = 0; c < pl.colors.length; c++)
1095 {
1096 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
1097 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
1098 }
1099 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
1100 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
1101 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
1102 + '<div class="planet-swatches">' + swatches + '</div>';
1103 btn.addEventListener('click', (function (id, isCompact)
1104 {
1105 return function ()
1106 { onPlanetPicked(id, isCompact); };
1107 })(pl.id, !!compact));
1108 grid.appendChild(btn);
1109 }
1110 }
1111
1112 function onPlanetPicked (id, fromLobby)
1113 {
1114 setSelectedPlanet(id);
1115 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
1116 {
1117 Online.setPlanet(id).then(function ()
1118 { renderOnline(); });
1119 }
1120 else
1121 {
1122 renderPlanetGrid('planet-grid', false);
1123 }
1124 }
1125
1126 function confirmPlanetSelect ()
1127 {
1128 var planet = setSelectedPlanet(selectedPlanetId());
1129 hideEl('planet-select');
1130 if (app.planetSelectContext === 'online')
1131 {
1132 openOnlinePanel();
1133 return;
1134 }
1135 startPlay({ planet: planet });
1136 }
1137
1138 function cancelPlanetSelect ()
1139 {
1140 hideEl('planet-select');
1141 app.mode = 'menu';
1142 showEl('menu');
1143 }
1144
1145 function bindPlanetSelect ()
1146 {
1147 var go = document.getElementById('btn-planet-go');
1148 var back = document.getElementById('btn-planet-back');
1149 if (go)
1150 {
1151 go.addEventListener('click', confirmPlanetSelect);
1152 }
1153 if (back)
1154 {
1155 back.addEventListener('click', cancelPlanetSelect);
1156 }
1157 }
@@ -7,20 +7,37 @@
7 * through Online (src/online.js) and the same GameCore.
7 * through Online (src/online.js) and the same GameCore.
8 */
8 */
9
9
10var IMAGES = [
10function planetImages ()
11 { name: 'ember', url: 'images/block-ember.png' },
11{
12 { name: 'aqua', url: 'images/block-aqua.png' },
12 var list = [
13 { name: 'leaf', url: 'images/block-leaf.png' },
13 { name: 'gray', url: 'images/block-gray.png' },
14 { name: 'sun', url: 'images/block-sun.png' },
14 { name: 'locked', url: 'images/block-locked.png' },
15 { name: 'orchid', url: 'images/block-orchid.png' },
15 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
16 { name: 'gray', url: 'images/block-gray.png' },
16 { name: 'cell', url: 'images/cell.png' },
17 { name: 'locked', url: 'images/block-locked.png' },
17 { name: 'pixel', url: 'images/pixel.png' },
18 { name: 'flame', url: 'images/flame.png', subImgTotal: 4, perRow: 4 },
18 // Keep the original Terra placeholders as aliases (Tim may still have them).
19 { name: 'cell', url: 'images/cell.png' },
19 { name: 'ember', url: 'images/block-ember.png' },
20 { name: 'pixel', url: 'images/pixel.png' }
20 { name: 'aqua', url: 'images/block-aqua.png' },
21];
21 { name: 'leaf', url: 'images/block-leaf.png' },
22
22 { name: 'sun', url: 'images/block-sun.png' },
23var COLOR_SPRITES = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
23 { name: 'orchid', url: 'images/block-orchid.png' }
24 ];
25 var planets = (typeof Planet !== 'undefined' ? Planet.allPlanets() : []);
26 for (var i = 0; i < planets.length; i++)
27 {
28 var pl = planets[i];
29 for (var c = 0; c < pl.colors.length; c++)
30 {
31 list.push({
32 name: Planet.spriteKey(pl, c),
33 url: pl.colors[c].image
34 });
35 }
36 }
37 return list;
38}
39
40var IMAGES = planetImages();
24var GAME_OVER_DELAY = 2;
41var GAME_OVER_DELAY = 2;
25
42
26var game = new Game();
43var game = new Game();
@@ -46,7 +63,9 @@ var app = {
46 online: false,
63 online: false,
47 eliminatedReported: false,
64 eliminatedReported: false,
48 spectating: false,
65 spectating: false,
49 miniH: 0
66 miniH: 0,
67 selectedPlanetId: 'terra',
68 planetSelectContext: 'solo'
50};
69};
51
70
52window.onload = function ()
71window.onload = function ()
@@ -71,13 +90,15 @@ window.onload = function ()
71 });
90 });
72
91
73 bindOnlineUi();
92 bindOnlineUi();
93 bindPlanetSelect();
94 restoreSelectedPlanet();
74};
95};
75
96
76function onPlay ()
97function onPlay ()
77{
98{
78 if (app.mode === 'playing')
99 if (app.mode === 'playing')
79 { return; }
100 { return; }
80 startPlay();
101 openPlanetSelect('solo');
81}
102}
82
103
83function startPlay (opts)
104function startPlay (opts)
@@ -88,14 +109,15 @@ function startPlay (opts)
88 hideEl('online-panel');
109 hideEl('online-panel');
89 hideEl('spectator');
110 hideEl('spectator');
90 hideEl('podium');
111 hideEl('podium');
112 hideEl('planet-select');
91 showEl('hud');
113 showEl('hud');
92
114
93 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
115 var planetMod = typeof Planet !== 'undefined' ? Planet : PlanetMod;
116 app.planet = opts.planet || planetMod.planetById(selectedPlanetId());
94 var miss = opts.missChance;
117 var miss = opts.missChance;
95 if (typeof miss === 'number' && isFinite(miss))
118 if (typeof miss !== 'number' || !isFinite(miss))
96 { app.core = new GameCore(app.planet, Math.random, miss); }
119 { miss = planetMod.missChance(app.planet); }
97 else
120 app.core = new GameCore(app.planet, Math.random, miss);
98 { app.core = new GameCore(app.planet, Math.random); }
99 app.mode = 'playing';
121 app.mode = 'playing';
100 app.online = !!opts.online;
122 app.online = !!opts.online;
101 app.gameOverShown = false;
123 app.gameOverShown = false;
@@ -164,6 +186,7 @@ function returnToMenu ()
164 teardownPlay();
186 teardownPlay();
165 app.mode = 'menu';
187 app.mode = 'menu';
166 app.online = false;
188 app.online = false;
189 hideEl('planet-select');
167 showEl('menu');
190 showEl('menu');
168 var last = document.getElementById('last-score');
191 var last = document.getElementById('last-score');
169 if (app.lastScore > 0)
192 if (app.lastScore > 0)
@@ -247,7 +270,8 @@ function spriteFor (block)
247 { return game.images.locked; }
270 { return game.images.locked; }
248 if (block.color < 0)
271 if (block.color < 0)
249 { return game.images.gray; }
272 { return game.images.gray; }
250 return game.images[COLOR_SPRITES[block.color]] || game.images.gray;
273 var key = Planet.spriteKey(app.planet, block.color);
274 return game.images[key] || game.images.gray;
251}
275}
252
276
253function syncSprites ()
277function syncSprites ()
@@ -406,10 +430,7 @@ function refreshHud ()
406 document.getElementById('score').textContent = String(app.core.score);
430 document.getElementById('score').textContent = String(app.core.score);
407 var planet = app.planet;
431 var planet = app.planet;
408 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
432 document.getElementById('planet-name').textContent = planet.name + ' · ' + planet.people;
409 var d = Planet.displayValues(planet);
433 document.getElementById('planet-stats').textContent = Planet.formatStats(planet);
410 document.getElementById('planet-stats').textContent =
411 'g ' + d.gravity.toFixed(2) + ' d ' + d.density.toFixed(2) +
412 ' F ' + Math.round(d.newtons) + ' N Power ' + d.power + '%';
413}
434}
414
435
415function makeManager ()
436function makeManager ()
@@ -687,10 +708,11 @@ function startOnlineMatch ()
687{
708{
688 if (app.mode === 'playing' && app.online)
709 if (app.mode === 'playing' && app.online)
689 { return; }
710 { return; }
690 var miss = (typeof Online !== 'undefined' && Online.lobby && Online.lobby.miss_chance != null)
711 var planet = Planet.planetById(selectedPlanetId());
691 ? Online.lobby.miss_chance
712 var me = (typeof Online !== 'undefined' && Online.mePlayer) ? Online.mePlayer() : null;
692 : (typeof Online !== 'undefined' ? Online.DEFAULT_MISS_CHANCE : 0.30);
713 if (me && me.planet && me.planet.id)
693 startPlay({ online: true, missChance: miss });
714 { planet = Planet.planetById(me.planet.id); }
715 startPlay({ online: true, planet: planet, missChance: Planet.missChance(planet) });
694 if (typeof Online !== 'undefined')
716 if (typeof Online !== 'undefined')
695 { Online.startPolling(onlinePayload); }
717 { Online.startPolling(onlinePayload); }
696}
718}
@@ -847,6 +869,7 @@ function openOnlinePanel ()
847 hideEl('game-over');
869 hideEl('game-over');
848 hideEl('podium');
870 hideEl('podium');
849 hideEl('spectator');
871 hideEl('spectator');
872 hideEl('planet-select');
850 showEl('online-panel');
873 showEl('online-panel');
851 app.mode = 'online';
874 app.mode = 'online';
852 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
875 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
@@ -948,10 +971,14 @@ function renderOnline ()
948 { li.classList.add('you'); }
971 { li.classList.add('you'); }
949 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
972 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
950 var state = p.ready ? 'Gereed' : 'Wacht…';
973 var state = p.ready ? 'Gereed' : 'Wacht…';
951 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
974 var world = (p.planet && p.planet.name) ? (p.planet.name + ' · ' + p.planet.people) : '';
975 li.innerHTML = '<span>' + escapeText(label)
976 + (world ? '<span class="planet-tag">' + escapeText(world) + '</span>' : '')
977 + '</span><span class="'
952 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
978 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
953 list.appendChild(li);
979 list.appendChild(li);
954 }
980 }
981 renderPlanetGrid('lobby-planet-grid', true);
955 var me = Online.mePlayer();
982 var me = Online.mePlayer();
956 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
983 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
957 var start = document.getElementById('btn-start');
984 var start = document.getElementById('btn-start');
@@ -984,3 +1011,147 @@ function escapeText (s)
984 .replace(/>/g, '&gt;')
1011 .replace(/>/g, '&gt;')
985 .replace(/"/g, '&quot;');
1012 .replace(/"/g, '&quot;');
986}
1013}
1014
1015
1016function selectedPlanetId ()
1017{
1018 if (app.selectedPlanetId)
1019 { return app.selectedPlanetId; }
1020 return 'terra';
1021}
1022
1023function restoreSelectedPlanet ()
1024{
1025 var id = 'terra';
1026 try
1027 { id = localStorage.getItem('meteors-planet') || 'terra'; }
1028 catch (e) {}
1029 setSelectedPlanet(id, true);
1030}
1031
1032function setSelectedPlanet (id, silent)
1033{
1034 var all = Planet.allPlanets();
1035 var found = null;
1036 for (var i = 0; i < all.length; i++)
1037 {
1038 if (all[i].id === id)
1039 { found = all[i]; break; }
1040 }
1041 if (!found)
1042 { found = Planet.defaultPlanet(); }
1043 app.selectedPlanetId = found.id;
1044 try
1045 { localStorage.setItem('meteors-planet', found.id); }
1046 catch (e) {}
1047 if (!silent)
1048 {
1049 var grid = document.getElementById('planet-grid');
1050 if (grid && !grid.hidden && grid.children.length)
1051 { renderPlanetGrid('planet-grid', false); }
1052 var lobby = document.getElementById('lobby-planet-grid');
1053 if (lobby && lobby.children.length)
1054 { renderPlanetGrid('lobby-planet-grid', true); }
1055 }
1056 return found;
1057}
1058
1059function openPlanetSelect (context)
1060{
1061 if (app.mode === 'playing')
1062 { return; }
1063 app.planetSelectContext = context || 'solo';
1064 app.mode = 'planet-select';
1065 hideEl('menu');
1066 hideEl('online-panel');
1067 hideEl('game-over');
1068 showEl('planet-select');
1069 renderPlanetGrid('planet-grid', false);
1070 var go = document.getElementById('btn-planet-go');
1071 if (go)
1072 { go.textContent = 'Spelen'; }
1073}
1074
1075function renderPlanetGrid (containerId, compact)
1076{
1077 var grid = document.getElementById(containerId);
1078 if (!grid)
1079 { return; }
1080 var current = selectedPlanetId();
1081 var all = Planet.allPlanets();
1082 grid.innerHTML = '';
1083 if (compact)
1084 { grid.classList.add('compact'); }
1085 for (var i = 0; i < all.length; i++)
1086 {
1087 var pl = all[i];
1088 var btn = document.createElement('button');
1089 btn.type = 'button';
1090 btn.className = 'planet-card' + (pl.id === current ? ' selected' : '');
1091 btn.setAttribute('role', 'listitem');
1092 btn.dataset.planet = pl.id;
1093 var swatches = '';
1094 for (var c = 0; c < pl.colors.length; c++)
1095 {
1096 swatches += '<img src="' + escapeText(pl.colors[c].image) + '" alt="'
1097 + escapeText(pl.colors[c].name) + '" title="' + escapeText(pl.colors[c].name) + '">';
1098 }
1099 btn.innerHTML = '<div class="planet-title">' + escapeText(pl.name) + '</div>'
1100 + '<div class="planet-people">' + escapeText(pl.people) + '</div>'
1101 + '<div class="planet-nums">' + escapeText(Planet.formatStats(pl)) + '</div>'
1102 + '<div class="planet-swatches">' + swatches + '</div>';
1103 btn.addEventListener('click', (function (id, isCompact)
1104 {
1105 return function ()
1106 { onPlanetPicked(id, isCompact); };
1107 })(pl.id, !!compact));
1108 grid.appendChild(btn);
1109 }
1110}
1111
1112function onPlanetPicked (id, fromLobby)
1113{
1114 setSelectedPlanet(id);
1115 if (fromLobby && typeof Online !== 'undefined' && Online.lobby)
1116 {
1117 Online.setPlanet(id).then(function ()
1118 { renderOnline(); });
1119 }
1120 else
1121 {
1122 renderPlanetGrid('planet-grid', false);
1123 }
1124}
1125
1126function confirmPlanetSelect ()
1127{
1128 var planet = setSelectedPlanet(selectedPlanetId());
1129 hideEl('planet-select');
1130 if (app.planetSelectContext === 'online')
1131 {
1132 openOnlinePanel();
1133 return;
1134 }
1135 startPlay({ planet: planet });
1136}
1137
1138function cancelPlanetSelect ()
1139{
1140 hideEl('planet-select');
1141 app.mode = 'menu';
1142 showEl('menu');
1143}
1144
1145function bindPlanetSelect ()
1146{
1147 var go = document.getElementById('btn-planet-go');
1148 var back = document.getElementById('btn-planet-back');
1149 if (go)
1150 {
1151 go.addEventListener('click', confirmPlanetSelect);
1152 }
1153 if (back)
1154 {
1155 back.addEventListener('click', cancelPlanetSelect);
1156 }
1157}
src/online.js +33 −10
@@ -115,14 +115,25 @@ Online.testLogin = function (who)
115 115 return this.request('test_login', { user: who });
116 116 };
117 117
118 Online.createLobby = function ()
118 Online.createLobby = function (planetId)
119 119 {
120 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
120 return this.request('lobby_create', {
121 miss_chance: this.DEFAULT_MISS_CHANCE,
122 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
123 });
124 };
125
126 Online.joinLobby = function (code, planetId)
127 {
128 return this.request('lobby_join', {
129 code: code,
130 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
131 });
121 132 };
122 133
123 Online.joinLobby = function (code)
134 Online.setPlanet = function (planetId)
124 135 {
125 return this.request('lobby_join', { code: code });
136 return this.request('lobby_set_planet', { planet_id: planetId });
126 137 };
127 138
128 139 Online.leaveLobby = function ()
@@ -289,7 +300,7 @@ Online.renderMinis = function (container)
289 300 el.querySelector('.mini-meta').textContent = p.eliminated
290 301 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
291 302 : ('Punten ' + (p.score || 0));
292 this._drawMini(el.querySelector('canvas'), p.snapshot);
303 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
293 304 }
294 305 for (var id in existing)
295 306 {
@@ -300,7 +311,15 @@ Online.renderMinis = function (container)
300 311
301 312 var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
302 313
303 Online._drawMini = function (canvas, snapshot)
314 function miniColor (planet, color)
315 {
316 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
317 { return planet.colors[color].hex; }
318 return MINI_COLORS[color] || '#888';
319 }
320
321
322 Online._drawMini = function (canvas, snapshot, planet)
304 323 {
305 324 if (!canvas)
306 325 { return; }
@@ -340,7 +359,7 @@ Online._drawMini = function (canvas, snapshot)
340 359 else if (b.color < 0)
341 360 { ctx.fillStyle = '#5a5d66'; }
342 361 else
343 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
362 { ctx.fillStyle = miniColor(planet, b.color); }
344 363 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
345 364 }
346 365 };
@@ -352,12 +371,16 @@ Online.miniElement = function (playerId)
352 371
353 372 /* ---------- flight tweens ------------------------------------------ */
354 373
355 function colorSpriteUrl (color)
374 function colorSpriteUrl (color, planetId)
356 375 {
357 376 if (color < 0)
358 377 { return 'images/block-gray.png'; }
359 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
360 return 'images/block-' + (names[color] || 'gray') + '.png';
378 var planet = null;
379 if (typeof Planet !== 'undefined')
380 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
381 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
382 { return planet.colors[color].image; }
383 return 'images/block-gray.png';
361 384 }
362 385
363 386 /**
@@ -115,14 +115,25 @@ Online.testLogin = function (who)
115 return this.request('test_login', { user: who });
115 return this.request('test_login', { user: who });
116};
116};
117
117
118Online.createLobby = function ()
118Online.createLobby = function (planetId)
119{
119{
120 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
120 return this.request('lobby_create', {
121 miss_chance: this.DEFAULT_MISS_CHANCE,
122 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
123 });
124};
125
126Online.joinLobby = function (code, planetId)
127{
128 return this.request('lobby_join', {
129 code: code,
130 planet_id: planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')
131 });
121};
132};
122
133
123Online.joinLobby = function (code)
134Online.setPlanet = function (planetId)
124{
135{
125 return this.request('lobby_join', { code: code });
136 return this.request('lobby_set_planet', { planet_id: planetId });
126};
137};
127
138
128Online.leaveLobby = function ()
139Online.leaveLobby = function ()
@@ -289,7 +300,7 @@ Online.renderMinis = function (container)
289 el.querySelector('.mini-meta').textContent = p.eliminated
300 el.querySelector('.mini-meta').textContent = p.eliminated
290 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
301 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
291 : ('Punten ' + (p.score || 0));
302 : ('Punten ' + (p.score || 0));
292 this._drawMini(el.querySelector('canvas'), p.snapshot);
303 this._drawMini(el.querySelector('canvas'), p.snapshot, p.planet);
293 }
304 }
294 for (var id in existing)
305 for (var id in existing)
295 {
306 {
@@ -300,7 +311,15 @@ Online.renderMinis = function (container)
300
311
301var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
312var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
302
313
303Online._drawMini = function (canvas, snapshot)
314function miniColor (planet, color)
315{
316 if (planet && planet.colors && planet.colors[color] && planet.colors[color].hex)
317 { return planet.colors[color].hex; }
318 return MINI_COLORS[color] || '#888';
319}
320
321
322Online._drawMini = function (canvas, snapshot, planet)
304{
323{
305 if (!canvas)
324 if (!canvas)
306 { return; }
325 { return; }
@@ -340,7 +359,7 @@ Online._drawMini = function (canvas, snapshot)
340 else if (b.color < 0)
359 else if (b.color < 0)
341 { ctx.fillStyle = '#5a5d66'; }
360 { ctx.fillStyle = '#5a5d66'; }
342 else
361 else
343 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
362 { ctx.fillStyle = miniColor(planet, b.color); }
344 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
363 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
345 }
364 }
346};
365};
@@ -352,12 +371,16 @@ Online.miniElement = function (playerId)
352
371
353/* ---------- flight tweens ------------------------------------------ */
372/* ---------- flight tweens ------------------------------------------ */
354
373
355function colorSpriteUrl (color)
374function colorSpriteUrl (color, planetId)
356{
375{
357 if (color < 0)
376 if (color < 0)
358 { return 'images/block-gray.png'; }
377 { return 'images/block-gray.png'; }
359 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
378 var planet = null;
360 return 'images/block-' + (names[color] || 'gray') + '.png';
379 if (typeof Planet !== 'undefined')
380 { planet = Planet.planetById(planetId || (typeof selectedPlanetId === 'function' ? selectedPlanetId() : 'terra')); }
381 if (planet && planet.colors && planet.colors[color] && planet.colors[color].image)
382 { return planet.colors[color].image; }
383 return 'images/block-gray.png';
361}
384}
362
385
363/**
386/**
src/planet.js +80 −7
@@ -51,6 +51,7 @@ function createPlanet (opts)
51 51 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
52 52 var colors = opts.colors || defaultColors();
53 53 var planet = {
54 id: opts.id || null,
54 55 name: opts.name || 'Terra',
55 56 people: opts.people || 'Terrans',
56 57 jumpsToClear: jumpsToClear,
@@ -70,15 +71,82 @@ function createPlanet (opts)
70 71 return planet;
71 72 }
72 73
73 function defaultPlanet ()
74 function loadCatalog ()
75 {
76 if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
77 { return PLANET_CATALOG; }
78 if (typeof require !== 'undefined')
79 {
80 try
81 { return require('../server/lib/planets.json'); }
82 catch (e) {}
83 }
84 return { planets: [] };
85 }
86
87 function planetFromData (data)
74 88 {
75 return createPlanet({
76 name: 'Terra',
77 people: 'Terrans',
78 jumpsToClear: 2,
79 fallTime: 3,
80 riseTime: 1.5
89 var planet = createPlanet({
90 name: data.name,
91 people: data.people,
92 jumpsToClear: data.jumpsToClear,
93 fallTime: data.fallTime,
94 riseTime: data.riseTime,
95 colors: data.colors
81 96 });
97 planet.id = data.id;
98 return planet;
99 }
100
101 function allPlanets ()
102 {
103 var raw = loadCatalog().planets || [];
104 var out = [];
105 for (var i = 0; i < raw.length; i++)
106 { out.push(planetFromData(raw[i])); }
107 if (out.length === 0)
108 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
109 return out;
110 }
111
112 function planetById (id)
113 {
114 var all = allPlanets();
115 for (var i = 0; i < all.length; i++)
116 {
117 if (all[i].id === id)
118 { return all[i]; }
119 }
120 return defaultPlanet();
121 }
122
123 function defaultPlanet ()
124 {
125 var all = allPlanets();
126 for (var i = 0; i < all.length; i++)
127 {
128 if (all[i].id === 'terra')
129 { return all[i]; }
130 }
131 return all[0];
132 }
133
134 function formatStats (planet)
135 {
136 var d = displayValues(planet);
137 return 'g ' + d.gravity.toFixed(2)
138 + ' d ' + d.density.toFixed(2)
139 + ' F ' + Math.round(d.newtons) + ' N'
140 + ' Power ' + d.power + '%';
141 }
142
143 function spriteKey (planet, colorIndex)
144 {
145 var colors = planet && planet.colors;
146 var c = colors && colors[colorIndex];
147 if (!c)
148 { return 'gray'; }
149 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
82 150 }
83 151
84 152 /**
@@ -158,6 +226,11 @@ var Planet = {
158 226 createPlanet: createPlanet,
159 227 defaultPlanet: defaultPlanet,
160 228 defaultColors: defaultColors,
229 allPlanets: allPlanets,
230 planetById: planetById,
231 planetFromData: planetFromData,
232 formatStats: formatStats,
233 spriteKey: spriteKey,
161 234 jumpHeight: jumpHeight,
162 235 launchVelocity: launchVelocity,
163 236 launchDeceleration: launchDeceleration,
@@ -51,6 +51,7 @@ function createPlanet (opts)
51 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
51 var riseTime = clamp(opts.riseTime == null ? 1.5 : opts.riseTime, 0.5, 3);
52 var colors = opts.colors || defaultColors();
52 var colors = opts.colors || defaultColors();
53 var planet = {
53 var planet = {
54 id: opts.id || null,
54 name: opts.name || 'Terra',
55 name: opts.name || 'Terra',
55 people: opts.people || 'Terrans',
56 people: opts.people || 'Terrans',
56 jumpsToClear: jumpsToClear,
57 jumpsToClear: jumpsToClear,
@@ -70,15 +71,82 @@ function createPlanet (opts)
70 return planet;
71 return planet;
71}
72}
72
73
73function defaultPlanet ()
74function loadCatalog ()
75{
76 if (typeof PLANET_CATALOG !== 'undefined' && PLANET_CATALOG && PLANET_CATALOG.planets)
77 { return PLANET_CATALOG; }
78 if (typeof require !== 'undefined')
79 {
80 try
81 { return require('../server/lib/planets.json'); }
82 catch (e) {}
83 }
84 return { planets: [] };
85}
86
87function planetFromData (data)
74{
88{
75 return createPlanet({
89 var planet = createPlanet({
76 name: 'Terra',
90 name: data.name,
77 people: 'Terrans',
91 people: data.people,
78 jumpsToClear: 2,
92 jumpsToClear: data.jumpsToClear,
79 fallTime: 3,
93 fallTime: data.fallTime,
80 riseTime: 1.5
94 riseTime: data.riseTime,
95 colors: data.colors
81 });
96 });
97 planet.id = data.id;
98 return planet;
99}
100
101function allPlanets ()
102{
103 var raw = loadCatalog().planets || [];
104 var out = [];
105 for (var i = 0; i < raw.length; i++)
106 { out.push(planetFromData(raw[i])); }
107 if (out.length === 0)
108 { out.push(createPlanet({ name: 'Terra', people: 'Terrans', jumpsToClear: 2, fallTime: 3, riseTime: 1.5 })); out[0].id = 'terra'; }
109 return out;
110}
111
112function planetById (id)
113{
114 var all = allPlanets();
115 for (var i = 0; i < all.length; i++)
116 {
117 if (all[i].id === id)
118 { return all[i]; }
119 }
120 return defaultPlanet();
121}
122
123function defaultPlanet ()
124{
125 var all = allPlanets();
126 for (var i = 0; i < all.length; i++)
127 {
128 if (all[i].id === 'terra')
129 { return all[i]; }
130 }
131 return all[0];
132}
133
134function formatStats (planet)
135{
136 var d = displayValues(planet);
137 return 'g ' + d.gravity.toFixed(2)
138 + ' d ' + d.density.toFixed(2)
139 + ' F ' + Math.round(d.newtons) + ' N'
140 + ' Power ' + d.power + '%';
141}
142
143function spriteKey (planet, colorIndex)
144{
145 var colors = planet && planet.colors;
146 var c = colors && colors[colorIndex];
147 if (!c)
148 { return 'gray'; }
149 return (planet.id || 'planet') + '-' + (c.name || String(colorIndex));
82}
150}
83
151
84/**
152/**
@@ -158,6 +226,11 @@ var Planet = {
158 createPlanet: createPlanet,
226 createPlanet: createPlanet,
159 defaultPlanet: defaultPlanet,
227 defaultPlanet: defaultPlanet,
160 defaultColors: defaultColors,
228 defaultColors: defaultColors,
229 allPlanets: allPlanets,
230 planetById: planetById,
231 planetFromData: planetFromData,
232 formatStats: formatStats,
233 spriteKey: spriteKey,
161 jumpHeight: jumpHeight,
234 jumpHeight: jumpHeight,
162 launchVelocity: launchVelocity,
235 launchVelocity: launchVelocity,
163 launchDeceleration: launchDeceleration,
236 launchDeceleration: launchDeceleration,
test/multiplayer-core.test.js +8 −5
@@ -67,18 +67,21 @@ describe('Outgoing shots and incoming garbage', () =>
67 67 assert.equal(g.ingestGarbage(), null);
68 68 });
69 69
70 it('missChance is a parameter defaulting to 0.30, independent of planet Power', () =>
70 it('missChance defaults to the planet Power formula and can still be overridden', () =>
71 71 {
72 72 const g = makeGame({ noSpawn: true });
73 assert.equal(g.missChance, 0.30);
73 const terraMiss = Planet.missChance(Planet.defaultPlanet());
74 assert.ok(Math.abs(g.missChance - terraMiss) < 1e-12);
75 assert.ok(Math.abs(terraMiss - 0.30) > 0.01, 'Terra Power miss is not the old flat 30%');
74 76 assert.equal(GameCore.DEFAULT_MISS_CHANCE, 0.30);
75 77 const custom = new GameCore(Planet.defaultPlanet(), Math.random, 0.05);
76 78 assert.equal(custom.missChance, 0.05);
77 79 const clamped = new GameCore(Planet.defaultPlanet(), Math.random, 2);
78 80 assert.equal(clamped.missChance, 1);
79 // Planet.missChance stays the stage-3 Power formula, unused here.
80 const terraMiss = Planet.missChance(Planet.defaultPlanet());
81 assert.ok(Math.abs(terraMiss - 0.30) > 0.01, 'Terra Power miss is not the stage-2 30%');
81 const cinder = new GameCore(Planet.planetById('cinder'), Math.random);
82 assert.ok(Math.abs(cinder.missChance - 0.05) < 1e-12);
83 const aurel = new GameCore(Planet.planetById('aurel'), Math.random);
84 assert.ok(Math.abs(aurel.missChance - 0.60) < 1e-12);
82 85 });
83 86
84 87 it('fieldSnapshot lists every block for opponent miniatures', () =>
@@ -67,18 +67,21 @@ describe('Outgoing shots and incoming garbage', () =>
67 assert.equal(g.ingestGarbage(), null);
67 assert.equal(g.ingestGarbage(), null);
68 });
68 });
69
69
70 it('missChance is a parameter defaulting to 0.30, independent of planet Power', () =>
70 it('missChance defaults to the planet Power formula and can still be overridden', () =>
71 {
71 {
72 const g = makeGame({ noSpawn: true });
72 const g = makeGame({ noSpawn: true });
73 assert.equal(g.missChance, 0.30);
73 const terraMiss = Planet.missChance(Planet.defaultPlanet());
74 assert.ok(Math.abs(g.missChance - terraMiss) < 1e-12);
75 assert.ok(Math.abs(terraMiss - 0.30) > 0.01, 'Terra Power miss is not the old flat 30%');
74 assert.equal(GameCore.DEFAULT_MISS_CHANCE, 0.30);
76 assert.equal(GameCore.DEFAULT_MISS_CHANCE, 0.30);
75 const custom = new GameCore(Planet.defaultPlanet(), Math.random, 0.05);
77 const custom = new GameCore(Planet.defaultPlanet(), Math.random, 0.05);
76 assert.equal(custom.missChance, 0.05);
78 assert.equal(custom.missChance, 0.05);
77 const clamped = new GameCore(Planet.defaultPlanet(), Math.random, 2);
79 const clamped = new GameCore(Planet.defaultPlanet(), Math.random, 2);
78 assert.equal(clamped.missChance, 1);
80 assert.equal(clamped.missChance, 1);
79 // Planet.missChance stays the stage-3 Power formula, unused here.
81 const cinder = new GameCore(Planet.planetById('cinder'), Math.random);
80 const terraMiss = Planet.missChance(Planet.defaultPlanet());
82 assert.ok(Math.abs(cinder.missChance - 0.05) < 1e-12);
81 assert.ok(Math.abs(terraMiss - 0.30) > 0.01, 'Terra Power miss is not the stage-2 30%');
83 const aurel = new GameCore(Planet.planetById('aurel'), Math.random);
84 assert.ok(Math.abs(aurel.missChance - 0.60) < 1e-12);
82 });
85 });
83
86
84 it('fieldSnapshot lists every block for opponent miniatures', () =>
87 it('fieldSnapshot lists every block for opponent miniatures', () =>
test/online-playwright.py +4 −1
@@ -202,7 +202,10 @@ def run_live(browser):
202 202 shot(page, "stage2-live-menu.png")
203 203 # Solo still works.
204 204 page.locator("#btn-play").click()
205 page.wait_for_timeout(800)
205 page.wait_for_timeout(600)
206 if page.locator("#planet-select").is_visible():
207 page.locator("#btn-planet-go").click()
208 page.wait_for_timeout(800)
206 209 playing = page.evaluate("() => app && app.mode === 'playing'")
207 210 check(playing, "live solo Play still starts a game")
208 211 shot(page, "stage2-live-solo.png")
@@ -202,7 +202,10 @@ def run_live(browser):
202 shot(page, "stage2-live-menu.png")
202 shot(page, "stage2-live-menu.png")
203 # Solo still works.
203 # Solo still works.
204 page.locator("#btn-play").click()
204 page.locator("#btn-play").click()
205 page.wait_for_timeout(800)
205 page.wait_for_timeout(600)
206 if page.locator("#planet-select").is_visible():
207 page.locator("#btn-planet-go").click()
208 page.wait_for_timeout(800)
206 playing = page.evaluate("() => app && app.mode === 'playing'")
209 playing = page.evaluate("() => app && app.mode === 'playing'")
207 check(playing, "live solo Play still starts a game")
210 check(playing, "live solo Play still starts a game")
208 shot(page, "stage2-live-solo.png")
211 shot(page, "stage2-live-solo.png")
test/planet-playwright.py added +296 −0
@@ -0,0 +1,296 @@
1 #!/usr/bin/env python3
2 """Stage 3: planet selection on desktop and mobile, plus two-player lobby picks."""
3 from __future__ import annotations
4
5 import os
6 import shutil
7 import socket
8 import subprocess
9 import sys
10 import tempfile
11 from pathlib import Path
12
13 from playwright.sync_api import sync_playwright
14
15 ROOT = Path("/workspace/meteors")
16 SHOTS = Path("/workspace/meteors-shots")
17 SHOTS.mkdir(parents=True, exist_ok=True)
18 PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
19 CHROME = "/usr/bin/google-chrome"
20 CHROME_ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]
21 LIVE = "https://projects.timfalken.com/meteors/"
22 URL = None
23 FAILURES = []
24
25 MOBILE = {
26 "viewport": {"width": 390, "height": 844},
27 "device_scale_factor": 2,
28 "is_mobile": True,
29 "has_touch": True,
30 "user_agent": (
31 "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
32 "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
33 "Mobile/15E148 Safari/604.1"
34 ),
35 }
36
37
38 def check(cond, msg):
39 if cond:
40 print("OK ", msg)
41 else:
42 print("FAIL", msg)
43 FAILURES.append(msg)
44 return cond
45
46
47 def shot(page, name):
48 path = SHOTS / name
49 page.screenshot(path=str(path), full_page=False)
50 print(f"wrote {path} ({path.stat().st_size} bytes)")
51
52
53 def free_port():
54 s = socket.socket()
55 s.bind(("127.0.0.1", 0))
56 port = s.getsockname()[1]
57 s.close()
58 return port
59
60
61 def start_php(port, data):
62 env = os.environ.copy()
63 env["METEORS_DATA_DIR"] = str(data)
64 return subprocess.Popen(
65 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
66 cwd=str(ROOT / "build"),
67 env=env,
68 stdout=subprocess.DEVNULL,
69 stderr=subprocess.DEVNULL,
70 )
71
72
73 def open_picker(page):
74 page.goto(URL, wait_until="networkidle", timeout=25000)
75 page.wait_for_timeout(500)
76 page.locator("#btn-play").click()
77 page.locator("#planet-select").wait_for(state="visible", timeout=8000)
78 page.wait_for_timeout(300)
79
80
81 def cards(page):
82 return page.locator("#planet-grid .planet-card")
83
84
85 def run_desktop(browser):
86 print("\n======== desktop planet select ========")
87 ctx = browser.new_context(viewport={"width": 1280, "height": 900})
88 page = ctx.new_page()
89 open_picker(page)
90 n = cards(page).count()
91 check(n >= 8 and n <= 12, f"catalog has 8–12 cards (got {n})")
92 texts = [cards(page).nth(i).inner_text() for i in range(n)]
93 joined = "\n".join(texts)
94 for name in ("Terra", "Aurel", "Cinder", "Lunara", "Forge"):
95 check(name in joined, f"desktop grid lists {name}")
96 # Numeric stats, no long explanation — Terra mid values.
97 terra = next(t for t in texts if t.startswith("Terra"))
98 check("Terrans" in terra, "Terra people name")
99 check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 48%" in terra,
100 "Terra numeric stats on the card")
101 cinder = next(t for t in texts if t.startswith("Cinder"))
102 check("Cindari" in cinder and "Power 100%" in cinder and "g 19.62" in cinder,
103 "Cinder is the hardest (Power 100%)")
104 aurel = next(t for t in texts if t.startswith("Aurel"))
105 check("Aurelians" in aurel and "Power 0%" in aurel, "Aurel is the easiest (Power 0%)")
106 # Each card has 5 unique placeholder images.
107 imgs = page.locator("#planet-grid .planet-card").nth(0).locator("img")
108 check(imgs.count() == 5, "five color placeholders on a card")
109 shot(page, "stage3-planet-select-desktop.png")
110
111 # Pick Cinder and start.
112 page.locator('.planet-card[data-planet="cinder"]').click()
113 page.wait_for_timeout(200)
114 check("selected" in (page.locator('.planet-card[data-planet="cinder"]').get_attribute("class") or ""),
115 "Cinder card is selected")
116 page.locator("#btn-planet-go").click()
117 page.wait_for_function("() => app && app.mode === 'playing' && app.core", timeout=8000)
118 hud = page.evaluate("""() => ({
119 name: document.getElementById('planet-name').textContent,
120 stats: document.getElementById('planet-stats').textContent,
121 id: app.planet && app.planet.id,
122 miss: app.core && app.core.missChance,
123 power: Planet.power(app.planet)
124 })""")
125 print("HUD", hud)
126 check(hud["id"] == "cinder" and "Cinder" in hud["name"] and "Cindari" in hud["name"],
127 "HUD shows Cinder · Cindari")
128 check("Power 100%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers")
129 check(abs(hud["miss"] - 0.05) < 1e-9, "GameCore missChance is Cinder's 5%")
130 shot(page, "stage3-play-cinder-desktop.png")
131 ctx.close()
132
133
134 def run_mobile(browser):
135 print("\n======== mobile planet select ========")
136 ctx = browser.new_context(**MOBILE)
137 page = ctx.new_page()
138 open_picker(page)
139 n = cards(page).count()
140 check(n >= 8, f"mobile grid has the catalog (got {n})")
141 # Scroll to Cinder if needed, then pick it.
142 card = page.locator('.planet-card[data-planet="cinder"]')
143 card.scroll_into_view_if_needed()
144 page.wait_for_timeout(200)
145 shot(page, "stage3-planet-select-mobile.png")
146 card.click()
147 page.locator("#btn-planet-go").click()
148 page.wait_for_function("() => app && app.mode === 'playing' && app.planet && app.planet.id === 'cinder'", timeout=8000)
149 playing = page.evaluate("() => ({mode: app.mode, id: app.planet.id, w: window.innerWidth})")
150 print("mobile play", playing)
151 check(playing["mode"] == "playing" and playing["id"] == "cinder", "mobile starts Cinder after the picker")
152 shot(page, "stage3-play-cinder-mobile.png")
153 ctx.close()
154
155
156 def login(page, n):
157 # test login, then land on the game with online panel openable
158 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="networkidle", timeout=20000)
159 page.wait_for_timeout(300)
160 page.goto(f"{URL}index.html?online=1", wait_until="networkidle", timeout=20000)
161 page.wait_for_timeout(600)
162 # If the online panel isn't auto-opened, click the button.
163 if not page.locator("#online-panel").is_visible():
164 if page.locator("#btn-online").is_visible():
165 page.locator("#btn-online").click()
166 page.wait_for_timeout(800)
167
168
169 def run_lobby(browser):
170 print("\n======== lobby planet picks (two contexts) ========")
171 c1 = browser.new_context(viewport={"width": 1280, "height": 900})
172 c2 = browser.new_context(viewport={"width": 1100, "height": 900})
173 p1 = c1.new_page()
174 p2 = c2.new_page()
175 login(p1, 1)
176 login(p2, 2)
177 # Host creates a lobby (default planet), then picks Aurel.
178 p1.locator("#btn-create").wait_for(state="visible", timeout=8000)
179 p1.locator("#btn-create").click()
180 p1.locator("#online-lobby").wait_for(state="visible", timeout=8000)
181 p1.wait_for_timeout(400)
182 p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').scroll_into_view_if_needed()
183 p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').click()
184 p1.wait_for_timeout(600)
185 code = p1.locator("#lobby-code").inner_text().strip()
186 check(len(code) == 4, f"lobby code {code}")
187 # Guest joins and picks Cinder.
188 p2.locator("#join-code").fill(code)
189 p2.locator("#btn-join").click()
190 p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
191 p2.wait_for_timeout(500)
192 p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').scroll_into_view_if_needed()
193 p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').click()
194 p2.wait_for_timeout(800)
195 # Poll so both see each other's pick.
196 p1.wait_for_timeout(1000)
197 p2.wait_for_timeout(400)
198 host_list = p1.locator("#lobby-players").inner_text()
199 guest_list = p2.locator("#lobby-players").inner_text()
200 print("host list:", host_list.replace("\n", " | "))
201 print("guest list:", guest_list.replace("\n", " | "))
202 check("Aurel" in host_list and "Cinder" in host_list, "host lobby shows both planet names")
203 check("Aurel" in guest_list and "Cinder" in guest_list, "guest lobby shows both planet names")
204 shot(p1, "stage3-lobby-planets-host.png")
205 shot(p2, "stage3-lobby-planets-guest.png")
206 # Ready and start; each plays their own planet.
207 p1.locator("#btn-ready").click()
208 p2.locator("#btn-ready").click()
209 p1.wait_for_timeout(800)
210 p1.locator("#btn-start").click()
211 p1.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
212 p2.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
213 ids = {
214 "host": p1.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
215 "guest": p2.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
216 }
217 print("match planets", ids)
218 check(ids["host"]["id"] == "aurel" and abs(ids["host"]["miss"] - 0.60) < 1e-9,
219 "host plays Aurel (60% miss from own Power)")
220 check(ids["guest"]["id"] == "cinder" and abs(ids["guest"]["miss"] - 0.05) < 1e-9,
221 "guest plays Cinder (5% miss from own Power)")
222 shot(p1, "stage3-game-aurel-host.png")
223 shot(p2, "stage3-game-cinder-guest.png")
224 c1.close()
225 c2.close()
226
227
228 def run_live(browser):
229 print("\n======== live site ========")
230 try:
231 ctx = browser.new_context(viewport={"width": 1280, "height": 900})
232 page = ctx.new_page()
233 page.goto(LIVE, wait_until="networkidle", timeout=25000)
234 page.wait_for_timeout(800)
235 if not page.locator("#btn-play").is_visible():
236 check(False, "live menu not reachable")
237 ctx.close()
238 return
239 page.locator("#btn-play").click()
240 page.wait_for_timeout(1000)
241 if page.locator("#planet-select").is_visible():
242 n = page.locator("#planet-grid .planet-card").count()
243 check(n >= 8, f"live planet grid has the catalog (got {n})")
244 shot(page, "stage3-live-planet-select.png")
245 page.locator('.planet-card[data-planet="terra"]').click()
246 page.locator("#btn-planet-go").click()
247 page.wait_for_timeout(800)
248 playing = page.evaluate("() => app && app.mode === 'playing' && app.planet && app.planet.id")
249 check(playing == "terra", "live solo starts on the chosen planet")
250 shot(page, "stage3-live-play-terra.png")
251 else:
252 # Not deployed yet: just note it; this check is re-run after deploy.
253 print("live planet select not present yet (expected before this deploy)")
254 shot(page, "stage3-live-planet-select.png")
255 ctx.close()
256 except Exception as e:
257 check(False, f"live site check: {e}")
258
259
260 def main():
261 global URL
262 if not Path(PHP).is_file():
263 print("php not found at", PHP)
264 return 1
265 port = free_port()
266 URL = f"http://127.0.0.1:{port}/"
267 data = Path(tempfile.mkdtemp(prefix="meteors-pw3-"))
268 print("PHP", PHP, "URL", URL)
269 proc = start_php(port, data)
270 try:
271 with sync_playwright() as p:
272 browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
273 run_desktop(browser)
274 run_mobile(browser)
275 run_lobby(browser)
276 run_live(browser)
277 browser.close()
278 finally:
279 proc.terminate()
280 try:
281 proc.wait(timeout=3)
282 except Exception:
283 proc.kill()
284 shutil.rmtree(data, ignore_errors=True)
285 print("\n======== summary ========")
286 if FAILURES:
287 print(f"{len(FAILURES)} failure(s):")
288 for f in FAILURES:
289 print(" -", f)
290 return 1
291 print("all stage-3 playwright checks passed")
292 return 0
293
294
295 if __name__ == "__main__":
296 sys.exit(main())
@@ -0,0 +1,296 @@
1#!/usr/bin/env python3
2"""Stage 3: planet selection on desktop and mobile, plus two-player lobby picks."""
3from __future__ import annotations
4
5import os
6import shutil
7import socket
8import subprocess
9import sys
10import tempfile
11from pathlib import Path
12
13from playwright.sync_api import sync_playwright
14
15ROOT = Path("/workspace/meteors")
16SHOTS = Path("/workspace/meteors-shots")
17SHOTS.mkdir(parents=True, exist_ok=True)
18PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
19CHROME = "/usr/bin/google-chrome"
20CHROME_ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]
21LIVE = "https://projects.timfalken.com/meteors/"
22URL = None
23FAILURES = []
24
25MOBILE = {
26 "viewport": {"width": 390, "height": 844},
27 "device_scale_factor": 2,
28 "is_mobile": True,
29 "has_touch": True,
30 "user_agent": (
31 "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
32 "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
33 "Mobile/15E148 Safari/604.1"
34 ),
35}
36
37
38def check(cond, msg):
39 if cond:
40 print("OK ", msg)
41 else:
42 print("FAIL", msg)
43 FAILURES.append(msg)
44 return cond
45
46
47def shot(page, name):
48 path = SHOTS / name
49 page.screenshot(path=str(path), full_page=False)
50 print(f"wrote {path} ({path.stat().st_size} bytes)")
51
52
53def free_port():
54 s = socket.socket()
55 s.bind(("127.0.0.1", 0))
56 port = s.getsockname()[1]
57 s.close()
58 return port
59
60
61def start_php(port, data):
62 env = os.environ.copy()
63 env["METEORS_DATA_DIR"] = str(data)
64 return subprocess.Popen(
65 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
66 cwd=str(ROOT / "build"),
67 env=env,
68 stdout=subprocess.DEVNULL,
69 stderr=subprocess.DEVNULL,
70 )
71
72
73def open_picker(page):
74 page.goto(URL, wait_until="networkidle", timeout=25000)
75 page.wait_for_timeout(500)
76 page.locator("#btn-play").click()
77 page.locator("#planet-select").wait_for(state="visible", timeout=8000)
78 page.wait_for_timeout(300)
79
80
81def cards(page):
82 return page.locator("#planet-grid .planet-card")
83
84
85def run_desktop(browser):
86 print("\n======== desktop planet select ========")
87 ctx = browser.new_context(viewport={"width": 1280, "height": 900})
88 page = ctx.new_page()
89 open_picker(page)
90 n = cards(page).count()
91 check(n >= 8 and n <= 12, f"catalog has 8–12 cards (got {n})")
92 texts = [cards(page).nth(i).inner_text() for i in range(n)]
93 joined = "\n".join(texts)
94 for name in ("Terra", "Aurel", "Cinder", "Lunara", "Forge"):
95 check(name in joined, f"desktop grid lists {name}")
96 # Numeric stats, no long explanation — Terra mid values.
97 terra = next(t for t in texts if t.startswith("Terra"))
98 check("Terrans" in terra, "Terra people name")
99 check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 48%" in terra,
100 "Terra numeric stats on the card")
101 cinder = next(t for t in texts if t.startswith("Cinder"))
102 check("Cindari" in cinder and "Power 100%" in cinder and "g 19.62" in cinder,
103 "Cinder is the hardest (Power 100%)")
104 aurel = next(t for t in texts if t.startswith("Aurel"))
105 check("Aurelians" in aurel and "Power 0%" in aurel, "Aurel is the easiest (Power 0%)")
106 # Each card has 5 unique placeholder images.
107 imgs = page.locator("#planet-grid .planet-card").nth(0).locator("img")
108 check(imgs.count() == 5, "five color placeholders on a card")
109 shot(page, "stage3-planet-select-desktop.png")
110
111 # Pick Cinder and start.
112 page.locator('.planet-card[data-planet="cinder"]').click()
113 page.wait_for_timeout(200)
114 check("selected" in (page.locator('.planet-card[data-planet="cinder"]').get_attribute("class") or ""),
115 "Cinder card is selected")
116 page.locator("#btn-planet-go").click()
117 page.wait_for_function("() => app && app.mode === 'playing' && app.core", timeout=8000)
118 hud = page.evaluate("""() => ({
119 name: document.getElementById('planet-name').textContent,
120 stats: document.getElementById('planet-stats').textContent,
121 id: app.planet && app.planet.id,
122 miss: app.core && app.core.missChance,
123 power: Planet.power(app.planet)
124 })""")
125 print("HUD", hud)
126 check(hud["id"] == "cinder" and "Cinder" in hud["name"] and "Cindari" in hud["name"],
127 "HUD shows Cinder · Cindari")
128 check("Power 100%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers")
129 check(abs(hud["miss"] - 0.05) < 1e-9, "GameCore missChance is Cinder's 5%")
130 shot(page, "stage3-play-cinder-desktop.png")
131 ctx.close()
132
133
134def run_mobile(browser):
135 print("\n======== mobile planet select ========")
136 ctx = browser.new_context(**MOBILE)
137 page = ctx.new_page()
138 open_picker(page)
139 n = cards(page).count()
140 check(n >= 8, f"mobile grid has the catalog (got {n})")
141 # Scroll to Cinder if needed, then pick it.
142 card = page.locator('.planet-card[data-planet="cinder"]')
143 card.scroll_into_view_if_needed()
144 page.wait_for_timeout(200)
145 shot(page, "stage3-planet-select-mobile.png")
146 card.click()
147 page.locator("#btn-planet-go").click()
148 page.wait_for_function("() => app && app.mode === 'playing' && app.planet && app.planet.id === 'cinder'", timeout=8000)
149 playing = page.evaluate("() => ({mode: app.mode, id: app.planet.id, w: window.innerWidth})")
150 print("mobile play", playing)
151 check(playing["mode"] == "playing" and playing["id"] == "cinder", "mobile starts Cinder after the picker")
152 shot(page, "stage3-play-cinder-mobile.png")
153 ctx.close()
154
155
156def login(page, n):
157 # test login, then land on the game with online panel openable
158 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="networkidle", timeout=20000)
159 page.wait_for_timeout(300)
160 page.goto(f"{URL}index.html?online=1", wait_until="networkidle", timeout=20000)
161 page.wait_for_timeout(600)
162 # If the online panel isn't auto-opened, click the button.
163 if not page.locator("#online-panel").is_visible():
164 if page.locator("#btn-online").is_visible():
165 page.locator("#btn-online").click()
166 page.wait_for_timeout(800)
167
168
169def run_lobby(browser):
170 print("\n======== lobby planet picks (two contexts) ========")
171 c1 = browser.new_context(viewport={"width": 1280, "height": 900})
172 c2 = browser.new_context(viewport={"width": 1100, "height": 900})
173 p1 = c1.new_page()
174 p2 = c2.new_page()
175 login(p1, 1)
176 login(p2, 2)
177 # Host creates a lobby (default planet), then picks Aurel.
178 p1.locator("#btn-create").wait_for(state="visible", timeout=8000)
179 p1.locator("#btn-create").click()
180 p1.locator("#online-lobby").wait_for(state="visible", timeout=8000)
181 p1.wait_for_timeout(400)
182 p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').scroll_into_view_if_needed()
183 p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').click()
184 p1.wait_for_timeout(600)
185 code = p1.locator("#lobby-code").inner_text().strip()
186 check(len(code) == 4, f"lobby code {code}")
187 # Guest joins and picks Cinder.
188 p2.locator("#join-code").fill(code)
189 p2.locator("#btn-join").click()
190 p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
191 p2.wait_for_timeout(500)
192 p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').scroll_into_view_if_needed()
193 p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').click()
194 p2.wait_for_timeout(800)
195 # Poll so both see each other's pick.
196 p1.wait_for_timeout(1000)
197 p2.wait_for_timeout(400)
198 host_list = p1.locator("#lobby-players").inner_text()
199 guest_list = p2.locator("#lobby-players").inner_text()
200 print("host list:", host_list.replace("\n", " | "))
201 print("guest list:", guest_list.replace("\n", " | "))
202 check("Aurel" in host_list and "Cinder" in host_list, "host lobby shows both planet names")
203 check("Aurel" in guest_list and "Cinder" in guest_list, "guest lobby shows both planet names")
204 shot(p1, "stage3-lobby-planets-host.png")
205 shot(p2, "stage3-lobby-planets-guest.png")
206 # Ready and start; each plays their own planet.
207 p1.locator("#btn-ready").click()
208 p2.locator("#btn-ready").click()
209 p1.wait_for_timeout(800)
210 p1.locator("#btn-start").click()
211 p1.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
212 p2.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
213 ids = {
214 "host": p1.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
215 "guest": p2.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
216 }
217 print("match planets", ids)
218 check(ids["host"]["id"] == "aurel" and abs(ids["host"]["miss"] - 0.60) < 1e-9,
219 "host plays Aurel (60% miss from own Power)")
220 check(ids["guest"]["id"] == "cinder" and abs(ids["guest"]["miss"] - 0.05) < 1e-9,
221 "guest plays Cinder (5% miss from own Power)")
222 shot(p1, "stage3-game-aurel-host.png")
223 shot(p2, "stage3-game-cinder-guest.png")
224 c1.close()
225 c2.close()
226
227
228def run_live(browser):
229 print("\n======== live site ========")
230 try:
231 ctx = browser.new_context(viewport={"width": 1280, "height": 900})
232 page = ctx.new_page()
233 page.goto(LIVE, wait_until="networkidle", timeout=25000)
234 page.wait_for_timeout(800)
235 if not page.locator("#btn-play").is_visible():
236 check(False, "live menu not reachable")
237 ctx.close()
238 return
239 page.locator("#btn-play").click()
240 page.wait_for_timeout(1000)
241 if page.locator("#planet-select").is_visible():
242 n = page.locator("#planet-grid .planet-card").count()
243 check(n >= 8, f"live planet grid has the catalog (got {n})")
244 shot(page, "stage3-live-planet-select.png")
245 page.locator('.planet-card[data-planet="terra"]').click()
246 page.locator("#btn-planet-go").click()
247 page.wait_for_timeout(800)
248 playing = page.evaluate("() => app && app.mode === 'playing' && app.planet && app.planet.id")
249 check(playing == "terra", "live solo starts on the chosen planet")
250 shot(page, "stage3-live-play-terra.png")
251 else:
252 # Not deployed yet: just note it; this check is re-run after deploy.
253 print("live planet select not present yet (expected before this deploy)")
254 shot(page, "stage3-live-planet-select.png")
255 ctx.close()
256 except Exception as e:
257 check(False, f"live site check: {e}")
258
259
260def main():
261 global URL
262 if not Path(PHP).is_file():
263 print("php not found at", PHP)
264 return 1
265 port = free_port()
266 URL = f"http://127.0.0.1:{port}/"
267 data = Path(tempfile.mkdtemp(prefix="meteors-pw3-"))
268 print("PHP", PHP, "URL", URL)
269 proc = start_php(port, data)
270 try:
271 with sync_playwright() as p:
272 browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
273 run_desktop(browser)
274 run_mobile(browser)
275 run_lobby(browser)
276 run_live(browser)
277 browser.close()
278 finally:
279 proc.terminate()
280 try:
281 proc.wait(timeout=3)
282 except Exception:
283 proc.kill()
284 shutil.rmtree(data, ignore_errors=True)
285 print("\n======== summary ========")
286 if FAILURES:
287 print(f"{len(FAILURES)} failure(s):")
288 for f in FAILURES:
289 print(" -", f)
290 return 1
291 print("all stage-3 playwright checks passed")
292 return 0
293
294
295if __name__ == "__main__":
296 sys.exit(main())
test/planet.test.js +44 −0
@@ -157,3 +157,47 @@ describe('Power and display values', () =>
157 157 assert.ok(Math.abs(d.gravity - 9.81) < 1e-9);
158 158 });
159 159 });
160
161 describe('Planet catalog', () =>
162 {
163 it('has 8–12 named worlds, each with a people name and five unique shapes', () =>
164 {
165 const all = Planet.allPlanets();
166 assert.ok(all.length >= 8 && all.length <= 12, 'catalog size ' + all.length);
167 const ids = new Set();
168 const images = new Set();
169 for (const p of all)
170 {
171 assert.ok(p.id && p.name && p.people, p.id);
172 assert.ok(!ids.has(p.id), 'duplicate id ' + p.id);
173 ids.add(p.id);
174 assert.equal(p.colors.length, 5);
175 const shapes = new Set(p.colors.map((c) => c.shape));
176 assert.equal(shapes.size, 5, p.id + ' shapes');
177 for (const c of p.colors)
178 {
179 assert.ok(c.image.startsWith('images/block-' + p.id + '-'), c.image);
180 assert.ok(!images.has(c.image), 'duplicate image ' + c.image);
181 images.add(c.image);
182 }
183 assert.ok(p.jumpsToClear >= 1 && p.jumpsToClear <= 4);
184 assert.ok(p.fallTime >= 1 && p.fallTime <= 5);
185 assert.ok(p.riseTime >= 0.5 && p.riseTime <= 3);
186 }
187 assert.ok(ids.has('terra'));
188 assert.equal(Planet.defaultPlanet().id, 'terra');
189 assert.equal(Planet.planetById('cinder').name, 'Cinder');
190 });
191
192 it('Aurel is the easiest (Power 0, 60% miss) and Cinder the hardest (Power 1, 5% miss)', () =>
193 {
194 const aurel = Planet.planetById('aurel');
195 const cinder = Planet.planetById('cinder');
196 assert.equal(Planet.power(aurel), 0);
197 assert.equal(Planet.missChance(aurel), 0.60);
198 assert.ok(Math.abs(Planet.power(cinder) - 1) < 1e-12);
199 assert.ok(Math.abs(Planet.missChance(cinder) - 0.05) < 1e-12);
200 assert.equal(Planet.displayValues(aurel).power, 0);
201 assert.equal(Planet.displayValues(cinder).power, 100);
202 });
203 });
@@ -157,3 +157,47 @@ describe('Power and display values', () =>
157 assert.ok(Math.abs(d.gravity - 9.81) < 1e-9);
157 assert.ok(Math.abs(d.gravity - 9.81) < 1e-9);
158 });
158 });
159});
159});
160
161describe('Planet catalog', () =>
162{
163 it('has 8–12 named worlds, each with a people name and five unique shapes', () =>
164 {
165 const all = Planet.allPlanets();
166 assert.ok(all.length >= 8 && all.length <= 12, 'catalog size ' + all.length);
167 const ids = new Set();
168 const images = new Set();
169 for (const p of all)
170 {
171 assert.ok(p.id && p.name && p.people, p.id);
172 assert.ok(!ids.has(p.id), 'duplicate id ' + p.id);
173 ids.add(p.id);
174 assert.equal(p.colors.length, 5);
175 const shapes = new Set(p.colors.map((c) => c.shape));
176 assert.equal(shapes.size, 5, p.id + ' shapes');
177 for (const c of p.colors)
178 {
179 assert.ok(c.image.startsWith('images/block-' + p.id + '-'), c.image);
180 assert.ok(!images.has(c.image), 'duplicate image ' + c.image);
181 images.add(c.image);
182 }
183 assert.ok(p.jumpsToClear >= 1 && p.jumpsToClear <= 4);
184 assert.ok(p.fallTime >= 1 && p.fallTime <= 5);
185 assert.ok(p.riseTime >= 0.5 && p.riseTime <= 3);
186 }
187 assert.ok(ids.has('terra'));
188 assert.equal(Planet.defaultPlanet().id, 'terra');
189 assert.equal(Planet.planetById('cinder').name, 'Cinder');
190 });
191
192 it('Aurel is the easiest (Power 0, 60% miss) and Cinder the hardest (Power 1, 5% miss)', () =>
193 {
194 const aurel = Planet.planetById('aurel');
195 const cinder = Planet.planetById('cinder');
196 assert.equal(Planet.power(aurel), 0);
197 assert.equal(Planet.missChance(aurel), 0.60);
198 assert.ok(Math.abs(Planet.power(cinder) - 1) < 1e-12);
199 assert.ok(Math.abs(Planet.missChance(cinder) - 0.05) < 1e-12);
200 assert.equal(Planet.displayValues(aurel).power, 0);
201 assert.equal(Planet.displayValues(cinder).power, 100);
202 });
203});
test/touch-playwright.py +12 −2
@@ -186,10 +186,20 @@ def start_play(page):
186 186 steps=1,
187 187 )
188 188 page.wait_for_timeout(400)
189 # Stage 3: Spelen opens the planet picker first.
190 if page.evaluate("() => app && app.mode") == "planet-select":
191 go = page.locator("#btn-planet-go")
192 go.wait_for(state="visible", timeout=5000)
193 go.click()
194 page.wait_for_timeout(400)
189 195 # Fallback if the touch didn't start the game (desktop-like click path).
190 196 if page.evaluate("() => app.mode") != "playing":
191 btn.click()
192 page.wait_for_timeout(400)
197 if page.locator("#btn-play").is_visible():
198 btn.click()
199 page.wait_for_timeout(400)
200 if page.locator("#btn-planet-go").is_visible():
201 page.locator("#btn-planet-go").click()
202 page.wait_for_timeout(400)
193 203 page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)
194 204 page.wait_for_selector("canvas", state="visible", timeout=5000)
195 205 return cdp
@@ -186,10 +186,20 @@ def start_play(page):
186 steps=1,
186 steps=1,
187 )
187 )
188 page.wait_for_timeout(400)
188 page.wait_for_timeout(400)
189 # Stage 3: Spelen opens the planet picker first.
190 if page.evaluate("() => app && app.mode") == "planet-select":
191 go = page.locator("#btn-planet-go")
192 go.wait_for(state="visible", timeout=5000)
193 go.click()
194 page.wait_for_timeout(400)
189 # Fallback if the touch didn't start the game (desktop-like click path).
195 # Fallback if the touch didn't start the game (desktop-like click path).
190 if page.evaluate("() => app.mode") != "playing":
196 if page.evaluate("() => app.mode") != "playing":
191 btn.click()
197 if page.locator("#btn-play").is_visible():
192 page.wait_for_timeout(400)
198 btn.click()
199 page.wait_for_timeout(400)
200 if page.locator("#btn-planet-go").is_visible():
201 page.locator("#btn-planet-go").click()
202 page.wait_for_timeout(400)
193 page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)
203 page.wait_for_function("() => app && app.mode === 'playing' && app.core && app.scene", timeout=8000)
194 page.wait_for_selector("canvas", state="visible", timeout=5000)
204 page.wait_for_selector("canvas", state="visible", timeout=5000)
195 return cdp
205 return cdp