BlueGit

projects-timfalken-com meteors

Merge branch 'feature/stage2-online'

timfa Grok Bot · pushed by timfa

Authored 2026-11-13 · 4 days ago

Hash
4dac4f2ab177c07aa998aa90783079650c492763
Pipeline
Passed
26 files changed +4349 −42
.gitignore +10 −0
@@ -3,3 +3,13 @@ node_modules/
3 3 .DS_Store
4 4 __pycache__/
5 5 *.pyc
6
7 # Generated by src/build.sh — sources live in server/.
8 build/api.php
9 build/auth.php
10 build/callback.php
11 build/logout.php
12 build/router.php
13 build/.htaccess
14 build/lib/
15 build/data/
@@ -3,3 +3,13 @@ node_modules/
3.DS_Store
3.DS_Store
4__pycache__/
4__pycache__/
5*.pyc
5*.pyc
6
7# Generated by src/build.sh — sources live in server/.
8build/api.php
9build/auth.php
10build/callback.php
11build/logout.php
12build/router.php
13build/.htaccess
14build/lib/
15build/data/
README.md +64 −7
@@ -29,6 +29,7 @@ Het standaardveld is de planeet **Terra** (volk: Terrans), met middelmatige zwaa
29 29
30 30 # Tests
31 31 node --test test/*.test.js
32 php server/tests/run.php
32 33
33 34 # Game-bundel (src/ → build/game.js)
34 35 ./src/build.sh
@@ -37,9 +38,13 @@ node --test test/*.test.js
37 38 # Placeholder-plaatjes opnieuw maken (optioneel; Tim kan ze zelf vervangen)
38 39 python3 scripts/make-placeholders.py
39 40
40 # Statische server
41 # Alleen het solo-spel (zonder online-API)
41 42 python3 -m http.server 8080 --directory build
42 43 # spel: http://localhost:8080/
44
45 # Met lobby-API (lokale testers: auth.php?test=1 en ?test=2)
46 php -S 127.0.0.1:8080 -t build build/router.php
47 # spel: http://127.0.0.1:8080/
43 48 ```
44 49
45 50 ## Architectuur
@@ -52,13 +57,15 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
52 57 | `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power, apex-ease, bounce |
53 58 | `src/rng.js` | Seedable RNG (tests en later replays) |
54 59 | `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |
55 | `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten |
56 | `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween |
60 | `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |
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 |
63 | `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
57 64 | `docs/ASSUMPTIONS.md` | Ingevulde aannames waar de specificatie ruimte liet |
58 | `src/build.sh` | Concateneert de bronnen naar `build/game.js` (zelfde patroon als de raytracer) |
59 | `build/` | Speelbare output: `index.html`, `style.css`, `framework.js`, `game.js`, `images/` |
60 | `test/` | Unit tests (`node --test`) voor de kern en de deploy-guard |
61 | `ci/` | FTP-deploy, **zonder** `--delete`. Expandeert `$timftproot` zelf. Weigert een map die niet leeg is of niet van Meteors is. |
65 | `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 | `test/` | Unit tests (`node --test`) voor de kern en de deploy-guard; `server/tests/run.php` voor de API |
68 | `ci/` | FTP-deploy, **zonder** `--delete`. Expandeert `$timftproot` zelf. Raakt `favicon.ico` en `data/` (config, database) niet aan. |
62 69
63 70 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`.
64 71
@@ -67,3 +74,53 @@ Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToC
67 74 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.
68 75
69 76 Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project).
77
78 ## Online spelen (stage 2)
79
80 Solo blijft werken, ook als online nog niet is ingesteld. Op het menu kies je
81 **Online spelen**. Na inloggen via [auth.timfalken.com](https://auth.timfalken.com)
82 maak je een lobby (of val je in met een code). Onbeperkt aantal spelers, praktisch
83 maximum 32. Iedereen drukt op Gereed; de host start als er minstens twee spelers
84 zijn en iedereen gereed is.
85
86 Je eigen veld is het hoofdspel; miniaturen van de tegenstanders staan erboven.
87 Blokjes die van je veld afschieten kiezen een willekeurige andere (nog niet
88 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
91 schot komt bij de ander aan als een vallend donkergrijs blokje dat na 3 seconden
92 op een stapel weer een kleur krijgt. Wie al zijn kolommen vol heeft, is toeschouwer
93 en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
94 op het podium en daarna ga je terug naar de lobby.
95
96 ### Wat Tim op de server moet instellen
97
98 Online werkt pas als OAuth is ingesteld. Zolang dat niet zo is, blijft solo
99 beschikbaar en toont **Online spelen** een duidelijke boodschap.
100
101 1. Ga naar https://auth.timfalken.com/admin, bij de **bestaande** client
102 `projects.timfalken.com` (dezelfde als de andere sites op dit domein).
103 2. Voeg het callback-pad **`/meteors/callback.php`** toe. Volledige URL:
104 `https://projects.timfalken.com/meteors/callback.php`.
105 3. Kopieer het **bestaande** client-geheim. **Genereer het niet opnieuw** —
106 dat breekt de andere sites die dit geheim al gebruiken.
107 4. Zet op de FTP-server, in de map `data/` naast het spel (niet in git, wordt
108 nooit gedeployed), een bestand `config.php`:
109
110 ```php
111 <?php
112 return [
113 'auth_url' => 'https://auth.timfalken.com',
114 'base_url' => 'https://projects.timfalken.com/meteors',
115 'client_id' => 'projects.timfalken.com',
116 'client_secret' => 'HIER_HET_BESTAANDE_GEHEIM',
117 ];
118 ```
119
120 De eerste keer dat de PHP-API draait, maakt ze een sjabloon van dit bestand
121 als het nog niet bestaat. `data/.htaccess` weigert alle toegang tot die map.
122 De deploy raakt `data/config.php` en de SQLite-database nooit aan, en
123 overschrijft `favicon.ico` niet.
124
125 Lokaal (alleen op loopback, host én remote-adres) kun je zonder geheim
126 inloggen als `auth.php?test=1` of `auth.php?test=2`.
@@ -29,6 +29,7 @@ Het standaardveld is de planeet **Terra** (volk: Terrans), met middelmatige zwaa
29
29
30# Tests
30# Tests
31node --test test/*.test.js
31node --test test/*.test.js
32php server/tests/run.php
32
33
33# Game-bundel (src/ → build/game.js)
34# Game-bundel (src/ → build/game.js)
34./src/build.sh
35./src/build.sh
@@ -37,9 +38,13 @@ node --test test/*.test.js
37# Placeholder-plaatjes opnieuw maken (optioneel; Tim kan ze zelf vervangen)
38# Placeholder-plaatjes opnieuw maken (optioneel; Tim kan ze zelf vervangen)
38python3 scripts/make-placeholders.py
39python3 scripts/make-placeholders.py
39
40
40# Statische server
41# Alleen het solo-spel (zonder online-API)
41python3 -m http.server 8080 --directory build
42python3 -m http.server 8080 --directory build
42# spel: http://localhost:8080/
43# spel: http://localhost:8080/
44
45# Met lobby-API (lokale testers: auth.php?test=1 en ?test=2)
46php -S 127.0.0.1:8080 -t build build/router.php
47# spel: http://127.0.0.1:8080/
43```
48```
44
49
45## Architectuur
50## Architectuur
@@ -52,13 +57,15 @@ De spelkern is deterministisch en staat los van tekenen en invoer, zodat stage 2
52| `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power, apex-ease, bounce |
57| `src/planet.js` | Planeet: zwaartekracht, luchtweerstand, massa, kleuren/vormen, spronghoogte, Power, apex-ease, bounce |
53| `src/rng.js` | Seedable RNG (tests en later replays) |
58| `src/rng.js` | Seedable RNG (tests en later replays) |
54| `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |
59| `src/easing.js` | Qt-eases (easeOutBack / easeOutElastic) en Click-Tween-defaults voor de selectie-animatie |
55| `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten |
60| `src/gameCore.js` | Simulatie: vallen, wisselen, match-3, raketsprong, linken, push-up + her-sprong, landen als starre groep + 3 s wachten, kolom-slot, game over, punten; stage 2: `outgoingShots`, `ingestGarbage`, `missChance`, `fieldSnapshot` |
56| `src/main.js` | Menu, HUD, frameworkv3-scene, muis/touch, schaal naar het scherm, landing-bounce, selectie-tween |
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 |
63| `server/` | PHP API: OAuth, lobby, shots, SQLite in `data/` (niet gedeployed) |
57| `docs/ASSUMPTIONS.md` | Ingevulde aannames waar de specificatie ruimte liet |
64| `docs/ASSUMPTIONS.md` | Ingevulde aannames waar de specificatie ruimte liet |
58| `src/build.sh` | Concateneert de bronnen naar `build/game.js` (zelfde patroon als de raytracer) |
65| `src/build.sh` | Concateneert de bronnen naar `build/game.js` en kopieert de PHP-API naar `build/` |
59| `build/` | Speelbare output: `index.html`, `style.css`, `framework.js`, `game.js`, `images/` |
66| `build/` | Speelbare output: `index.html`, `style.css`, `framework.js`, `game.js`, `images/`, PHP-API |
60| `test/` | Unit tests (`node --test`) voor de kern en de deploy-guard |
67| `test/` | Unit tests (`node --test`) voor de kern en de deploy-guard; `server/tests/run.php` voor de API |
61| `ci/` | FTP-deploy, **zonder** `--delete`. Expandeert `$timftproot` zelf. Weigert een map die niet leeg is of niet van Meteors is. |
68| `ci/` | FTP-deploy, **zonder** `--delete`. Expandeert `$timftproot` zelf. Raakt `favicon.ico` en `data/` (config, database) niet aan. |
62
69
63Sprongfysica 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`.
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`.
64
71
@@ -67,3 +74,53 @@ Sprongfysica is parametrisch. Een horizontale match van 3 springt `13 / jumpsToC
67BlueGit 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.
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.
68
75
69Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project).
76Secrets: `timftphost` / `timftpuser` / `timftppassword` / `timftproot` (groep), `projectftp` (dit project).
77
78## Online spelen (stage 2)
79
80Solo blijft werken, ook als online nog niet is ingesteld. Op het menu kies je
81**Online spelen**. Na inloggen via [auth.timfalken.com](https://auth.timfalken.com)
82maak je een lobby (of val je in met een code). Onbeperkt aantal spelers, praktisch
83maximum 32. Iedereen drukt op Gereed; de host start als er minstens twee spelers
84zijn en iedereen gereed is.
85
86Je eigen veld is het hoofdspel; miniaturen van de tegenstanders staan erboven.
87Blokjes die van je veld afschieten kiezen een willekeurige andere (nog niet
88uitgeschakelde) speler en vliegen daar in een korte tween naartoe (draaien en
89krimpen). 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
91schot 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
93en geen doelwit meer. De laatste die overblijft wint; 1e/2e/3e staan 5 seconden
94op het podium en daarna ga je terug naar de lobby.
95
96### Wat Tim op de server moet instellen
97
98Online werkt pas als OAuth is ingesteld. Zolang dat niet zo is, blijft solo
99beschikbaar en toont **Online spelen** een duidelijke boodschap.
100
1011. Ga naar https://auth.timfalken.com/admin, bij de **bestaande** client
102 `projects.timfalken.com` (dezelfde als de andere sites op dit domein).
1032. Voeg het callback-pad **`/meteors/callback.php`** toe. Volledige URL:
104 `https://projects.timfalken.com/meteors/callback.php`.
1053. Kopieer het **bestaande** client-geheim. **Genereer het niet opnieuw** —
106 dat breekt de andere sites die dit geheim al gebruiken.
1074. Zet op de FTP-server, in de map `data/` naast het spel (niet in git, wordt
108 nooit gedeployed), een bestand `config.php`:
109
110```php
111<?php
112return [
113 'auth_url' => 'https://auth.timfalken.com',
114 'base_url' => 'https://projects.timfalken.com/meteors',
115 'client_id' => 'projects.timfalken.com',
116 'client_secret' => 'HIER_HET_BESTAANDE_GEHEIM',
117];
118```
119
120De eerste keer dat de PHP-API draait, maakt ze een sjabloon van dit bestand
121als het nog niet bestaat. `data/.htaccess` weigert alle toegang tot die map.
122De deploy raakt `data/config.php` en de SQLite-database nooit aan, en
123overschrijft `favicon.ico` niet.
124
125Lokaal (alleen op loopback, host én remote-adres) kun je zonder geheim
126inloggen als `auth.php?test=1` of `auth.php?test=2`.
blue-ci-cd.yml +23 −1
@@ -2,7 +2,9 @@
2 2 # Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).
3 3 # Repo secret: projectftp (protected; Tim set this to $timftproot/meteors).
4 4 # GEEN mirror --delete: live files mogen niet verdwijnen.
5 # Deployt map build/ (NIET de repo-root).
5 # Deployt map build/ (NIET de repo-root). data/ (config, sqlite) wordt
6 # niet geüpload; alleen data/.htaccess wordt naderhand gezet.
7 # favicon.ico wordt nooit geüpload.
6 8 stages: [test, build, deploy]
7 9
8 10 workflow:
@@ -17,7 +19,9 @@ unit_tests:
17 19 stage: test
18 20 image: node:20-bookworm
19 21 script:
22 - apt-get update -qq && apt-get install -y -qq php-cli php-sqlite3 php-curl php-mbstring >/dev/null
20 23 - node --test test/*.test.js
24 - php server/tests/run.php
21 25
22 26 build_game:
23 27 stage: build
@@ -34,6 +38,16 @@ build_game:
34 38 - test -d build/images
35 39 - test -f build/images/block-ember.png
36 40 - test -f build/images/flame.png
41 - test -f build/api.php
42 - test -f build/auth.php
43 - test -f build/callback.php
44 - test -f build/logout.php
45 - test -f build/.htaccess
46 - test -f build/lib/bootstrap.php
47 - test -f build/lib/Store.php
48 - test -f build/data/.htaccess
49 - test ! -f build/data/config.php
50 - test ! -e build/data/*.sqlite
37 51 # BlueGit weigert directory-artifacts (IsDir → "ontbreekt"). Alleen bestanden.
38 52 # Afbeeldingen staan in git en zitten zo ook in de deploy-checkout.
39 53 artifacts:
@@ -55,6 +69,14 @@ build_game:
55 69 - build/images/pixel.png
56 70 - build/images/favicon-16.png
57 71 - build/images/favicon-32.png
72 - build/api.php
73 - build/auth.php
74 - build/callback.php
75 - build/logout.php
76 - build/.htaccess
77 - build/lib/bootstrap.php
78 - build/lib/Store.php
79 - build/data/.htaccess
58 80 expire_in: 7d
59 81
60 82 ftp_upload:
@@ -2,7 +2,9 @@
2# Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).
2# Group secrets: timftphost, timftpuser, timftppassword, timftproot (protected).
3# Repo secret: projectftp (protected; Tim set this to $timftproot/meteors).
3# Repo secret: projectftp (protected; Tim set this to $timftproot/meteors).
4# GEEN mirror --delete: live files mogen niet verdwijnen.
4# GEEN mirror --delete: live files mogen niet verdwijnen.
5# Deployt map build/ (NIET de repo-root).
5# Deployt map build/ (NIET de repo-root). data/ (config, sqlite) wordt
6# niet geüpload; alleen data/.htaccess wordt naderhand gezet.
7# favicon.ico wordt nooit geüpload.
6stages: [test, build, deploy]
8stages: [test, build, deploy]
7
9
8workflow:
10workflow:
@@ -17,7 +19,9 @@ unit_tests:
17 stage: test
19 stage: test
18 image: node:20-bookworm
20 image: node:20-bookworm
19 script:
21 script:
22 - apt-get update -qq && apt-get install -y -qq php-cli php-sqlite3 php-curl php-mbstring >/dev/null
20 - node --test test/*.test.js
23 - node --test test/*.test.js
24 - php server/tests/run.php
21
25
22build_game:
26build_game:
23 stage: build
27 stage: build
@@ -34,6 +38,16 @@ build_game:
34 - test -d build/images
38 - test -d build/images
35 - test -f build/images/block-ember.png
39 - test -f build/images/block-ember.png
36 - test -f build/images/flame.png
40 - test -f build/images/flame.png
41 - test -f build/api.php
42 - test -f build/auth.php
43 - test -f build/callback.php
44 - test -f build/logout.php
45 - test -f build/.htaccess
46 - test -f build/lib/bootstrap.php
47 - test -f build/lib/Store.php
48 - test -f build/data/.htaccess
49 - test ! -f build/data/config.php
50 - test ! -e build/data/*.sqlite
37 # BlueGit weigert directory-artifacts (IsDir → "ontbreekt"). Alleen bestanden.
51 # BlueGit weigert directory-artifacts (IsDir → "ontbreekt"). Alleen bestanden.
38 # Afbeeldingen staan in git en zitten zo ook in de deploy-checkout.
52 # Afbeeldingen staan in git en zitten zo ook in de deploy-checkout.
39 artifacts:
53 artifacts:
@@ -55,6 +69,14 @@ build_game:
55 - build/images/pixel.png
69 - build/images/pixel.png
56 - build/images/favicon-16.png
70 - build/images/favicon-16.png
57 - build/images/favicon-32.png
71 - build/images/favicon-32.png
72 - build/api.php
73 - build/auth.php
74 - build/callback.php
75 - build/logout.php
76 - build/.htaccess
77 - build/lib/bootstrap.php
78 - build/lib/Store.php
79 - build/data/.htaccess
58 expire_in: 7d
80 expire_in: 7d
59
81
60ftp_upload:
82ftp_upload:
build/game.js +1079 −16
@@ -443,6 +443,17 @@ function GameCore (planet, rng)
443 443 this.state = 'playing';
444 444 this.drag = null;
445 445 this.gameOverTime = 0;
446 this.outgoingShots = [];
447 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
448 this.missChance = optsMissChance(arguments);
449 }
450
451 function optsMissChance (args)
452 {
453 // GameCore(planet, rng, missChance) — third arg is optional.
454 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
455 { return Math.max(0, Math.min(1, args[2])); }
456 return GameCore.DEFAULT_MISS_CHANCE;
446 457 }
447 458
448 459 GameCore.COLOR_GRAY = COLOR_GRAY;
@@ -450,6 +461,7 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
450 461 GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
451 462 GameCore.SNAP_Y = SNAP_Y;
452 463 GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
464 GameCore.DEFAULT_MISS_CHANCE = 0.30;
453 465 GameCore.STATE_STILL = STATE_STILL;
454 466 GameCore.STATE_FALLING = STATE_FALLING;
455 467 GameCore.STATE_FLYING = STATE_FLYING;
@@ -1508,9 +1520,88 @@ GameCore.prototype.cullOffTop = function ()
1508 1520 }
1509 1521 for (var i = 0; i < gone.length; i++)
1510 1522 {
1523 var block = gone[i];
1524 this.outgoingShots.push({
1525 id: block.id,
1526 color: block.color,
1527 col: block.col,
1528 y: block.y
1529 });
1511 1530 this.score += 1;
1512 this.removeBlock(gone[i]);
1531 this.removeBlock(block);
1532 }
1533 };
1534
1535 GameCore.prototype.consumeOutgoingShots = function ()
1536 {
1537 var shots = this.outgoingShots;
1538 this.outgoingShots = [];
1539 return shots;
1540 };
1541
1542 /**
1543 * A compact field picture for the multiplayer snapshot (miniatures).
1544 * Includes every block's col, y, color, state and flame.
1545 */
1546 GameCore.prototype.fieldSnapshot = function ()
1547 {
1548 var blocks = [];
1549 for (var i = 0; i < this.blocks.length; i++)
1550 {
1551 var b = this.blocks[i];
1552 blocks.push({
1553 id: b.id,
1554 col: b.col,
1555 y: Math.round(b.y * 1000) / 1000,
1556 color: b.color,
1557 state: b.state,
1558 flame: !!b.flame
1559 });
1560 }
1561 return {
1562 score: this.score,
1563 state: this.state,
1564 width: this.width,
1565 height: this.height,
1566 locked: this.lockedColumnCount(),
1567 blocks: blocks
1568 };
1569 };
1570
1571 /**
1572 * Incoming garbage from another player: a dark-grey block that falls
1573 * normally from the top of an open column. After landing it uses the
1574 * usual 3s settle and then a random colour (landFallingBlock).
1575 * `col` is optional; a random eligible column is used otherwise.
1576 * Returns the new block, or null if every column is locked or full.
1577 */
1578 GameCore.prototype.ingestGarbage = function (col)
1579 {
1580 if (this.state !== 'playing')
1581 { return null; }
1582 var chosen = null;
1583 if (col != null && col >= 0 && col < this.width
1584 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
1585 { chosen = col | 0; }
1586 else
1587 {
1588 var eligible = [];
1589 for (var c = 0; c < this.width; c++)
1590 {
1591 if (this.isColumnLocked(c))
1592 { continue; }
1593 if (this.groundedCount(c) >= this.height)
1594 { continue; }
1595 eligible.push(c);
1596 }
1597 if (!eligible.length)
1598 { return null; }
1599 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1513 1600 }
1601 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
1602 block.vy = -this.planet.fallSpeed;
1603 block.flame = false;
1604 return block;
1514 1605 };
1515 1606
1516 1607 GameCore.prototype.advanceSettle = function (dt)
@@ -2188,6 +2279,538 @@ else if (typeof globalThis !== 'undefined')
2188 2279 * /workspace/meteors/src/gameCore.js
2189 2280 */
2190 2281
2282 /*
2283 * Start File:
2284 * /workspace/meteors/src/online.js
2285 */
2286 'use strict';
2287
2288 /**
2289 * Online play: talks to api.php (cookie session), polls lobby and game
2290 * state, and draws opponent miniatures plus flying-block tweens.
2291 * Real-time sync is not required; a 0.75 s poll is enough.
2292 */
2293
2294 var Online = {
2295 POLL_MS: 750,
2296 DEFAULT_MISS_CHANCE: 0.30,
2297 FLIGHT_DURATION: 1.2,
2298 configured: false,
2299 local: false,
2300 csrf: '',
2301 me: null,
2302 lobby: null,
2303 incoming: [],
2304 shotResults: [],
2305 error: '',
2306 _timer: null,
2307 _pendingShots: [],
2308 _flights: [],
2309 _lastStatus: null,
2310 onChange: null,
2311 onGameStart: null,
2312 onIncoming: null,
2313 onFinished: null,
2314 onLobbyReturn: null
2315 };
2316
2317 Online._headers = function (json)
2318 {
2319 var h = { 'Accept': 'application/json' };
2320 if (json)
2321 { h['Content-Type'] = 'application/json'; }
2322 if (this.csrf)
2323 { h['X-CSRF-Token'] = this.csrf; }
2324 return h;
2325 };
2326
2327 Online._apply = function (data)
2328 {
2329 if (!data)
2330 { return; }
2331 if (typeof data.configured === 'boolean')
2332 { this.configured = data.configured; }
2333 if (typeof data.local === 'boolean')
2334 { this.local = data.local; }
2335 if (data.csrf)
2336 { this.csrf = data.csrf; }
2337 if (data.me !== undefined)
2338 { this.me = data.me; }
2339 if (data.lobby !== undefined)
2340 { this.lobby = data.lobby; }
2341 if (data.incoming)
2342 { this.incoming = data.incoming; }
2343 if (data.shot_results)
2344 { this.shotResults = data.shot_results; }
2345 if (data.miss_chance_default != null)
2346 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
2347 if (data.flight_duration != null)
2348 { this.FLIGHT_DURATION = data.flight_duration; }
2349 if (data.error)
2350 { this.error = data.error; }
2351 else if (data.ok)
2352 { this.error = ''; }
2353 };
2354
2355 Online.request = function (action, body)
2356 {
2357 var self = this;
2358 var isGet = action === 'me' || action === '';
2359 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
2360 var opts = {
2361 method: isGet && !body ? 'GET' : 'POST',
2362 credentials: 'same-origin',
2363 headers: this._headers(!!body || !isGet)
2364 };
2365 if (opts.method === 'POST')
2366 {
2367 var payload = body ? Object.assign({ action: action }, body) : { action: action };
2368 opts.body = JSON.stringify(payload);
2369 }
2370 return fetch(url, opts).then(function (res)
2371 {
2372 return res.json().then(function (data)
2373 {
2374 data = data || {};
2375 if (!res.ok && !data.error)
2376 { data.error = 'De server gaf ' + res.status; data.ok = false; }
2377 self._apply(data);
2378 return data;
2379 }, function ()
2380 {
2381 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
2382 self.error = fail.error;
2383 return fail;
2384 });
2385 }).catch(function (err)
2386 {
2387 var fail = { ok: false, error: 'Geen verbinding met de server.' };
2388 self.error = fail.error;
2389 return fail;
2390 });
2391 };
2392
2393 Online.refresh = function ()
2394 {
2395 return this.request('me');
2396 };
2397
2398 Online.testLogin = function (who)
2399 {
2400 return this.request('test_login', { user: who });
2401 };
2402
2403 Online.createLobby = function ()
2404 {
2405 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
2406 };
2407
2408 Online.joinLobby = function (code)
2409 {
2410 return this.request('lobby_join', { code: code });
2411 };
2412
2413 Online.leaveLobby = function ()
2414 {
2415 return this.request('lobby_leave');
2416 };
2417
2418 Online.setReady = function (ready)
2419 {
2420 return this.request('lobby_ready', { ready: !!ready });
2421 };
2422
2423 Online.startGame = function ()
2424 {
2425 var self = this;
2426 var prev = this.lobby && this.lobby.status;
2427 return this.request('lobby_start').then(function (data)
2428 {
2429 self._handleTransitions(prev, data);
2430 return data;
2431 });
2432 };
2433
2434 Online.queueShots = function (shots)
2435 {
2436 for (var i = 0; i < shots.length; i++)
2437 {
2438 this._pendingShots.push({
2439 client_id: String(shots[i].id),
2440 color: shots[i].color,
2441 col: shots[i].col,
2442 y: shots[i].y
2443 });
2444 }
2445 };
2446
2447 Online.poll = function (opts)
2448 {
2449 opts = opts || {};
2450 var body = {};
2451 if (opts.snapshot)
2452 { body.snapshot = opts.snapshot; }
2453 if (opts.score != null)
2454 { body.score = opts.score; }
2455 if (opts.eliminated)
2456 { body.eliminated = true; }
2457 if (this._pendingShots.length)
2458 {
2459 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
2460 }
2461 var self = this;
2462 var prevStatus = this.lobby && this.lobby.status;
2463 return this.request('poll', body).then(function (data)
2464 {
2465 self._handleTransitions(prevStatus, data);
2466 if (self.onChange)
2467 { self.onChange(self); }
2468 return data;
2469 });
2470 };
2471
2472 Online._handleTransitions = function (prevStatus, data)
2473 {
2474 var lobby = this.lobby;
2475 var status = lobby && lobby.status;
2476 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
2477 { this.onGameStart(lobby); }
2478 if (data && data.incoming && data.incoming.length && this.onIncoming)
2479 { this.onIncoming(data.incoming); }
2480 if (data && data.shot_results && data.shot_results.length)
2481 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
2482 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
2483 { this.onFinished(lobby); }
2484 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
2485 { this.onLobbyReturn(lobby); }
2486 };
2487
2488 Online.startPolling = function (getPayload)
2489 {
2490 this.stopPolling();
2491 var self = this;
2492 var tick = function ()
2493 {
2494 var payload = getPayload ? getPayload() : {};
2495 self.poll(payload);
2496 };
2497 tick();
2498 this._timer = setInterval(tick, this.POLL_MS);
2499 };
2500
2501 Online.stopPolling = function ()
2502 {
2503 if (this._timer)
2504 {
2505 clearInterval(this._timer);
2506 this._timer = null;
2507 }
2508 };
2509
2510 Online.loginUrl = function ()
2511 {
2512 return 'auth.php';
2513 };
2514
2515 Online.logoutUrl = function ()
2516 {
2517 return 'logout.php';
2518 };
2519
2520 Online.opponents = function ()
2521 {
2522 if (!this.lobby || !this.lobby.players)
2523 { return []; }
2524 return this.lobby.players.filter(function (p) { return !p.is_me; });
2525 };
2526
2527 Online.aliveOpponents = function ()
2528 {
2529 return this.opponents().filter(function (p) { return !p.eliminated; });
2530 };
2531
2532 Online.mePlayer = function ()
2533 {
2534 if (!this.lobby || !this.lobby.players)
2535 { return null; }
2536 for (var i = 0; i < this.lobby.players.length; i++)
2537 {
2538 if (this.lobby.players[i].is_me)
2539 { return this.lobby.players[i]; }
2540 }
2541 return null;
2542 };
2543
2544 /* ---------- miniatures --------------------------------------------- */
2545
2546 Online.renderMinis = function (container)
2547 {
2548 if (!container)
2549 { return; }
2550 var opponents = this.opponents();
2551 var existing = {};
2552 var kids = container.querySelectorAll('[data-player]');
2553 for (var i = 0; i < kids.length; i++)
2554 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
2555
2556 var seen = Object.create(null);
2557 for (var i = 0; i < opponents.length; i++)
2558 {
2559 var p = opponents[i];
2560 seen[p.id] = true;
2561 var el = existing[p.id];
2562 if (!el)
2563 {
2564 el = document.createElement('div');
2565 el.className = 'mini';
2566 el.setAttribute('data-player', p.id);
2567 el.innerHTML = '<div class="mini-name"></div>'
2568 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
2569 + '<div class="mini-meta"></div>';
2570 container.appendChild(el);
2571 }
2572 el.classList.toggle('eliminated', !!p.eliminated);
2573 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
2574 el.querySelector('.mini-meta').textContent = p.eliminated
2575 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
2576 : ('Punten ' + (p.score || 0));
2577 this._drawMini(el.querySelector('canvas'), p.snapshot);
2578 }
2579 for (var id in existing)
2580 {
2581 if (!seen[id])
2582 { existing[id].remove(); }
2583 }
2584 };
2585
2586 var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
2587
2588 Online._drawMini = function (canvas, snapshot)
2589 {
2590 if (!canvas)
2591 { return; }
2592 var ctx = canvas.getContext('2d');
2593 var w = 10;
2594 var h = 13;
2595 var tw = canvas.width / w;
2596 var th = canvas.height / h;
2597 ctx.fillStyle = '#0c1020';
2598 ctx.fillRect(0, 0, canvas.width, canvas.height);
2599 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
2600 ctx.lineWidth = 1;
2601 for (var c = 0; c <= w; c++)
2602 {
2603 ctx.beginPath();
2604 ctx.moveTo(c * tw + 0.5, 0);
2605 ctx.lineTo(c * tw + 0.5, canvas.height);
2606 ctx.stroke();
2607 }
2608 for (var r = 0; r <= h; r++)
2609 {
2610 ctx.beginPath();
2611 ctx.moveTo(0, r * th + 0.5);
2612 ctx.lineTo(canvas.width, r * th + 0.5);
2613 ctx.stroke();
2614 }
2615 if (!snapshot || !snapshot.blocks)
2616 { return; }
2617 var blocks = snapshot.blocks;
2618 for (var i = 0; i < blocks.length; i++)
2619 {
2620 var b = blocks[i];
2621 var x = b.col * tw;
2622 var y = canvas.height - (b.y + 1) * th;
2623 if (b.state === 'locked')
2624 { ctx.fillStyle = '#3a3d4a'; }
2625 else if (b.color < 0)
2626 { ctx.fillStyle = '#5a5d66'; }
2627 else
2628 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
2629 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
2630 }
2631 };
2632
2633 Online.miniElement = function (playerId)
2634 {
2635 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
2636 };
2637
2638 /* ---------- flight tweens ------------------------------------------ */
2639
2640 function colorSpriteUrl (color)
2641 {
2642 if (color < 0)
2643 { return 'images/block-gray.png'; }
2644 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
2645 return 'images/block-' + (names[color] || 'gray') + '.png';
2646 }
2647
2648 /**
2649 * Animate shot results. `locals` is a map of client_id → {col, y, color,
2650 * startX, startY} in viewport pixels, filled by the view just after
2651 * consumeOutgoingShots.
2652 */
2653 Online.spawnFlights = function (results, locals)
2654 {
2655 locals = locals || this._flightLocals || {};
2656 var layer = document.getElementById('flights');
2657 if (!layer)
2658 { return; }
2659 for (var i = 0; i < results.length; i++)
2660 {
2661 var r = results[i];
2662 var meta = locals[r.client_id] || {};
2663 var start = this._flightStart(meta.col);
2664 var end;
2665 var miss = !!r.miss;
2666 if (miss)
2667 { end = this._missEnd(start); }
2668 else
2669 { end = this._targetEnd(r.target_id, start); }
2670 var el = document.createElement('img');
2671 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
2672 el.alt = '';
2673 el.className = 'flight';
2674 layer.appendChild(el);
2675 var spin = (Math.random() * 2 - 1) * 720;
2676 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
2677 this._flights.push({
2678 el: el,
2679 start: start,
2680 end: end,
2681 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
2682 t0: performance.now(),
2683 duration: duration,
2684 spin: spin,
2685 miss: miss,
2686 angle: Math.random() * 360
2687 });
2688 }
2689 this._flightLocals = {};
2690 };
2691
2692 Online.rememberFlightLocal = function (shot, startX, startY)
2693 {
2694 if (!this._flightLocals)
2695 { this._flightLocals = {}; }
2696 this._flightLocals[String(shot.id)] = {
2697 col: shot.col,
2698 y: shot.y,
2699 color: shot.color,
2700 startX: startX,
2701 startY: startY
2702 };
2703 };
2704
2705 Online._flightStart = function (col)
2706 {
2707 var field = document.querySelector('canvas');
2708 var appRef = typeof app !== 'undefined' ? app : null;
2709 if (appRef && appRef.scene && appRef.scene.canvas)
2710 {
2711 var canvas = appRef.scene.canvas;
2712 var rect = canvas.getBoundingClientRect();
2713 var c = col == null ? 4.5 : col;
2714 return {
2715 x: rect.left + (c + 0.5) * (rect.width / 10),
2716 y: rect.top + 4
2717 };
2718 }
2719 if (field)
2720 {
2721 var rect = field.getBoundingClientRect();
2722 return { x: rect.left + rect.width / 2, y: rect.top };
2723 }
2724 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
2725 };
2726
2727 Online._targetEnd = function (targetId, start)
2728 {
2729 var el = targetId && this.miniElement(targetId);
2730 if (el)
2731 {
2732 var r = el.getBoundingClientRect();
2733 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
2734 }
2735 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
2736 };
2737
2738 Online._missEnd = function (start)
2739 {
2740 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
2741 return {
2742 x: start.x + dx,
2743 y: start.y - (120 + Math.random() * 220)
2744 };
2745 };
2746
2747 Online._missCtrl = function (start, end)
2748 {
2749 return {
2750 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
2751 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
2752 };
2753 };
2754
2755 Online._hitCtrl = function (start, end)
2756 {
2757 return {
2758 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
2759 y: (start.y + end.y) / 2 - 30
2760 };
2761 };
2762
2763 Online.tickFlights = function (now)
2764 {
2765 now = now || performance.now();
2766 var leftover = [];
2767 for (var i = 0; i < this._flights.length; i++)
2768 {
2769 var f = this._flights[i];
2770 var u = (now - f.t0) / f.duration;
2771 if (u >= 1)
2772 {
2773 if (f.el && f.el.parentNode)
2774 { f.el.parentNode.removeChild(f.el); }
2775 continue;
2776 }
2777 // Quadratic bezier, ease-in so they feel like they recede.
2778 var e = u * u;
2779 var mt = 1 - e;
2780 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
2781 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
2782 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
2783 var angle = f.angle + f.spin * u;
2784 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
2785 + angle + 'deg) scale(' + scale + ')';
2786 f.el.style.opacity = f.miss ? String(1 - e) : '1';
2787 leftover.push(f);
2788 }
2789 this._flights = leftover;
2790 };
2791
2792 Online.clearFlights = function ()
2793 {
2794 for (var i = 0; i < this._flights.length; i++)
2795 {
2796 var el = this._flights[i].el;
2797 if (el && el.parentNode)
2798 { el.parentNode.removeChild(el); }
2799 }
2800 this._flights = [];
2801 this._flightLocals = {};
2802 };
2803
2804 if (typeof globalThis !== 'undefined')
2805 { globalThis.Online = Online; }
2806 if (typeof module !== 'undefined' && module.exports)
2807 { module.exports = Online; }
2808
2809 /*
2810 * End File:
2811 * /workspace/meteors/src/online.js
2812 */
2813
2191 2814 /*
2192 2815 * Start File:
2193 2816 * /workspace/meteors/src/main.js
@@ -2197,8 +2820,8 @@ else if (typeof globalThis !== 'undefined')
2197 2820 /**
2198 2821 * View and input for Meteors. The simulation lives in GameCore; this file
2199 2822 * only draws it, scales it to the viewport, and translates pointer events
2200 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
2201 * that reuses the same core.
2823 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
2824 * through Online (src/online.js) and the same GameCore.
2202 2825 */
2203 2826
2204 2827 var IMAGES = [
@@ -2236,7 +2859,11 @@ var app = {
2236 2859 cells: [],
2237 2860 pointerId: null,
2238 2861 gameOverShown: false,
2239 selectTween: null
2862 selectTween: null,
2863 online: false,
2864 eliminatedReported: false,
2865 spectating: false,
2866 miniH: 0
2240 2867 };
2241 2868
2242 2869 window.onload = function ()
@@ -2259,6 +2886,8 @@ window.onload = function ()
2259 2886 if (game.images.flame && game.images.flame.addAnimationCycle)
2260 2887 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
2261 2888 });
2889
2890 bindOnlineUi();
2262 2891 };
2263 2892
2264 2893 function onPlay ()
@@ -2268,16 +2897,27 @@ function onPlay ()
2268 2897 startPlay();
2269 2898 }
2270 2899
2271 function startPlay ()
2900 function startPlay (opts)
2272 2901 {
2902 opts = opts || {};
2273 2903 hideEl('menu');
2274 2904 hideEl('game-over');
2905 hideEl('online-panel');
2906 hideEl('spectator');
2907 hideEl('podium');
2275 2908 showEl('hud');
2276 2909
2277 2910 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
2278 app.core = new GameCore(app.planet, Math.random);
2911 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); }
2279 2916 app.mode = 'playing';
2917 app.online = !!opts.online;
2280 2918 app.gameOverShown = false;
2919 app.eliminatedReported = false;
2920 app.spectating = false;
2281 2921 app.sprites = Object.create(null);
2282 2922 app.flames = Object.create(null);
2283 2923 app.cells = [];
@@ -2285,6 +2925,11 @@ function startPlay ()
2285 2925 app.selectTween = null;
2286 2926
2287 2927 layout();
2928 if (app.scene)
2929 {
2930 app.scene.destroy();
2931 app.scene = null;
2932 }
2288 2933 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
2289 2934 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
2290 2935 app.scene.renderBackground = true;
@@ -2292,11 +2937,16 @@ function startPlay ()
2292 2937
2293 2938 buildCells();
2294 2939 app.manager = app.scene.addObject(makeManager());
2295 bindPointer(app.scene.canvas);
2940 if (!app.spectating)
2941 { bindPointer(app.scene.canvas); }
2296 2942 refreshHud();
2943 if (app.online)
2944 { showEl('minis'); }
2945 else
2946 { hideEl('minis'); }
2297 2947 }
2298 2948
2299 function returnToMenu ()
2949 function teardownPlay ()
2300 2950 {
2301 2951 unbindPointer();
2302 2952 if (app.scene)
@@ -2306,14 +2956,31 @@ function returnToMenu ()
2306 2956 }
2307 2957 app.manager = null;
2308 2958 app.core = null;
2309 app.mode = 'menu';
2310 2959 app.sprites = Object.create(null);
2311 2960 app.flames = Object.create(null);
2312 2961 app.cells = [];
2313 2962 app.selectTween = null;
2314
2963 app.pointerId = null;
2964 app.gameOverShown = false;
2315 2965 hideEl('hud');
2316 2966 hideEl('game-over');
2967 hideEl('spectator');
2968 hideEl('minis');
2969 if (typeof Online !== 'undefined')
2970 { Online.clearFlights(); }
2971 }
2972
2973 function returnToMenu ()
2974 {
2975 if (app.online && typeof Online !== 'undefined')
2976 {
2977 // Online matches do not dump you back to the solo menu:
2978 // elimination becomes spectating; a finished match shows the podium.
2979 return;
2980 }
2981 teardownPlay();
2982 app.mode = 'menu';
2983 app.online = false;
2317 2984 showEl('menu');
2318 2985 var last = document.getElementById('last-score');
2319 2986 if (app.lastScore > 0)
@@ -2361,16 +3028,26 @@ function layout ()
2361 3028 }
2362 3029 catch (e) { /* ignore */ }
2363 3030 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
3031 app.miniH = 0;
3032 if (app.online)
3033 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
2364 3034 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
2365 3035 var availW = Math.max(80, vw - margin * 2);
2366 var availH = Math.max(80, vh - app.hudH - margin);
3036 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
2367 3037 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
2368 3038 app.fieldW = app.tile * 10;
2369 3039 app.fieldH = app.tile * 13;
2370 3040 app.fieldX = Math.floor((vw - app.fieldW) / 2);
2371 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
2372 if (app.fieldY < app.hudH)
2373 { app.fieldY = app.hudH; }
3041 var topBand = app.hudH + app.miniH;
3042 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
3043 if (app.fieldY < topBand)
3044 { app.fieldY = topBand; }
3045 var minis = document.getElementById('minis');
3046 if (minis)
3047 {
3048 minis.style.top = app.hudH + 'px';
3049 minis.style.maxHeight = app.miniH + 'px';
3050 }
2374 3051
2375 3052 if (app.scene)
2376 3053 {
@@ -2582,15 +3259,19 @@ function tickView (dt)
2582 3259 updateSelectTween(dt);
2583 3260 syncSprites();
2584 3261 refreshHud();
3262 tickOnline(dt);
2585 3263
2586 3264 if (app.core.state === 'gameover' && !app.gameOverShown)
2587 3265 {
2588 3266 app.gameOverShown = true;
2589 3267 app.lastScore = app.core.score;
2590 3268 document.getElementById('go-score').textContent = String(app.lastScore);
2591 showEl('game-over');
3269 if (app.online)
3270 { onOnlineEliminated(); }
3271 else
3272 { showEl('game-over'); }
2592 3273 }
2593 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
3274 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
2594 3275 { returnToMenu(); }
2595 3276 }
2596 3277
@@ -2739,6 +3420,388 @@ window.addEventListener('orientationchange', function ()
2739 3420 }, 120);
2740 3421 });
2741 3422
3423 /* ---------- online play (stage 2) ---------------------------------- */
3424
3425 function tickOnline (dt)
3426 {
3427 if (!app.online || typeof Online === 'undefined')
3428 { return; }
3429 if (app.core)
3430 {
3431 var shots = app.core.consumeOutgoingShots();
3432 for (var i = 0; i < shots.length; i++)
3433 {
3434 var s = shots[i];
3435 var start = fieldToViewport(s.col, s.y + 1);
3436 Online.rememberFlightLocal(s, start.x, start.y);
3437 }
3438 Online.queueShots(shots);
3439 }
3440 Online.tickFlights();
3441 Online.renderMinis(document.getElementById('minis'));
3442 }
3443
3444 function fieldToViewport (col, fieldY)
3445 {
3446 var canvas = app.scene && app.scene.canvas;
3447 if (!canvas)
3448 { return { x: window.innerWidth / 2, y: 40 }; }
3449 var rect = canvas.getBoundingClientRect();
3450 var x = rect.left + ((col + 0.5) / 10) * rect.width;
3451 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
3452 return { x: x, y: y };
3453 }
3454
3455 function onlinePayload ()
3456 {
3457 if (!app.online || !app.core)
3458 { return {}; }
3459 return {
3460 snapshot: app.core.fieldSnapshot(),
3461 score: app.core.score,
3462 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
3463 };
3464 }
3465
3466 function onOnlineEliminated ()
3467 {
3468 app.eliminatedReported = true;
3469 app.spectating = true;
3470 unbindPointer();
3471 hideEl('game-over');
3472 var lobby = typeof Online !== 'undefined' && Online.lobby;
3473 if (lobby && lobby.status === 'finished')
3474 {
3475 showPodium(lobby);
3476 return;
3477 }
3478 showEl('spectator');
3479 }
3480
3481 function showPodium (lobby)
3482 {
3483 hideEl('spectator');
3484 hideEl('game-over');
3485 hideEl('online-panel');
3486 showEl('podium');
3487 var list = document.getElementById('podium-list');
3488 list.innerHTML = '';
3489 var ranks = (lobby && lobby.rankings) || [];
3490 for (var i = 0; i < ranks.length; i++)
3491 {
3492 var r = ranks[i];
3493 var li = document.createElement('li');
3494 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
3495 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
3496 list.appendChild(li);
3497 }
3498 var hint = document.getElementById('podium-hint');
3499 var secs = (lobby && lobby.podium_seconds) || 5;
3500 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
3501 }
3502
3503 function startOnlineMatch ()
3504 {
3505 if (app.mode === 'playing' && app.online)
3506 { 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 });
3511 if (typeof Online !== 'undefined')
3512 { Online.startPolling(onlinePayload); }
3513 }
3514
3515 function leaveOnlineMatch (goMenu)
3516 {
3517 if (typeof Online !== 'undefined')
3518 {
3519 Online.stopPolling();
3520 Online.leaveLobby();
3521 Online.clearFlights();
3522 }
3523 teardownPlay();
3524 app.online = false;
3525 if (goMenu)
3526 {
3527 app.mode = 'menu';
3528 showEl('menu');
3529 }
3530 else
3531 {
3532 app.mode = 'online';
3533 openOnlinePanel();
3534 }
3535 }
3536
3537 function bindOnlineUi ()
3538 {
3539 var onlineBtn = document.getElementById('btn-online');
3540 if (!onlineBtn)
3541 { return; }
3542 onlineBtn.addEventListener('click', function ()
3543 { openOnlinePanel(); });
3544
3545 var backs = document.querySelectorAll('[data-back-menu]');
3546 for (var i = 0; i < backs.length; i++)
3547 {
3548 backs[i].addEventListener('click', function ()
3549 {
3550 if (typeof Online !== 'undefined')
3551 { Online.stopPolling(); }
3552 hideEl('online-panel');
3553 app.mode = 'menu';
3554 app.online = false;
3555 showEl('menu');
3556 });
3557 }
3558
3559 document.getElementById('btn-create').addEventListener('click', function ()
3560 {
3561 Online.createLobby().then(function (data)
3562 {
3563 if (data && data.ok)
3564 {
3565 renderOnline();
3566 Online.startPolling(onlinePayload);
3567 }
3568 else
3569 { renderOnline(); }
3570 });
3571 });
3572
3573 document.getElementById('join-form').addEventListener('submit', function (e)
3574 {
3575 e.preventDefault();
3576 var code = (document.getElementById('join-code').value || '').trim();
3577 if (!code)
3578 { return; }
3579 Online.joinLobby(code).then(function ()
3580 {
3581 renderOnline();
3582 if (Online.lobby)
3583 { Online.startPolling(onlinePayload); }
3584 });
3585 });
3586
3587 document.getElementById('btn-ready').addEventListener('click', function ()
3588 {
3589 var me = Online.mePlayer();
3590 Online.setReady(!(me && me.ready)).then(renderOnline);
3591 });
3592
3593 document.getElementById('btn-start').addEventListener('click', function ()
3594 {
3595 Online.startGame().then(function (data)
3596 {
3597 if (data && data.ok)
3598 { startOnlineMatch(); }
3599 else
3600 { renderOnline(); }
3601 });
3602 });
3603
3604 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
3605 {
3606 Online.leaveLobby().then(function ()
3607 {
3608 Online.stopPolling();
3609 renderOnline();
3610 });
3611 });
3612
3613 document.getElementById('btn-copy-code').addEventListener('click', function ()
3614 {
3615 var code = document.getElementById('lobby-code').textContent;
3616 if (navigator.clipboard && navigator.clipboard.writeText)
3617 { navigator.clipboard.writeText(code); }
3618 });
3619
3620 document.getElementById('btn-spectate').addEventListener('click', function ()
3621 {
3622 hideEl('spectator');
3623 app.spectating = true;
3624 });
3625
3626 document.getElementById('btn-leave-game').addEventListener('click', function ()
3627 { leaveOnlineMatch(false); });
3628
3629 if (typeof Online !== 'undefined')
3630 {
3631 Online.onChange = function ()
3632 { renderOnline(); };
3633 Online.onGameStart = function ()
3634 { startOnlineMatch(); };
3635 Online.onIncoming = function (incoming)
3636 {
3637 if (!app.core || app.core.state !== 'playing')
3638 { return; }
3639 for (var i = 0; i < incoming.length; i++)
3640 { app.core.ingestGarbage(); }
3641 };
3642 Online.onFinished = function (lobby)
3643 { showPodium(lobby); };
3644 Online.onLobbyReturn = function (lobby)
3645 {
3646 teardownPlay();
3647 app.online = false;
3648 app.mode = 'online';
3649 hideEl('podium');
3650 showEl('online-panel');
3651 renderOnline();
3652 Online.startPolling(onlinePayload);
3653 };
3654 }
3655
3656 var params = new URLSearchParams(window.location.search);
3657 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
3658 { openOnlinePanel(); }
3659 }
3660
3661 function openOnlinePanel ()
3662 {
3663 hideEl('menu');
3664 hideEl('game-over');
3665 hideEl('podium');
3666 hideEl('spectator');
3667 showEl('online-panel');
3668 app.mode = 'online';
3669 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
3670 if (typeof Online === 'undefined')
3671 {
3672 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
3673 showOnly('online-unconfigured');
3674 return;
3675 }
3676 Online.refresh().then(function (data)
3677 {
3678 if (!data || data.ok === false)
3679 {
3680 var msg = (data && data.error) || 'Geen verbinding met de server.';
3681 showOnlineError(msg + ' Je kunt wel alleen spelen.');
3682 if (data && data.configured === false)
3683 { showOnly('online-unconfigured'); }
3684 else
3685 { showOnly('online-login'); }
3686 document.getElementById('btn-login').style.display = 'none';
3687 return;
3688 }
3689 renderOnline();
3690 if (Online.lobby)
3691 { Online.startPolling(onlinePayload); }
3692 });
3693 }
3694
3695 function setOnlineStatus (text)
3696 {
3697 var el = document.getElementById('online-status');
3698 if (el)
3699 { el.textContent = text; }
3700 }
3701
3702 function showOnlineError (text)
3703 {
3704 var el = document.getElementById('online-error');
3705 if (!el)
3706 { return; }
3707 if (!text)
3708 {
3709 el.hidden = true;
3710 el.textContent = '';
3711 return;
3712 }
3713 el.hidden = false;
3714 el.textContent = text;
3715 }
3716
3717 function showOnly (id)
3718 {
3719 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
3720 for (var i = 0; i < ids.length; i++)
3721 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
3722 }
3723
3724 function renderOnline ()
3725 {
3726 if (typeof Online === 'undefined')
3727 { return; }
3728 if (app.mode === 'playing' && app.online)
3729 {
3730 Online.renderMinis(document.getElementById('minis'));
3731 if (Online.lobby && Online.lobby.status === 'finished')
3732 { showPodium(Online.lobby); }
3733 return;
3734 }
3735 showOnlineError(Online.error);
3736 if (!Online.configured && !Online.me && !Online.local)
3737 {
3738 setOnlineStatus('Online spelen is nog niet ingesteld.');
3739 showOnly('online-unconfigured');
3740 return;
3741 }
3742 if (!Online.me)
3743 {
3744 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
3745 showOnly('online-login');
3746 document.getElementById('btn-login').style.display = '';
3747 document.getElementById('btn-login').href = Online.loginUrl();
3748 document.getElementById('local-login').hidden = !Online.local;
3749 return;
3750 }
3751 if (Online.lobby)
3752 {
3753 setOnlineStatus('Lobby');
3754 showOnly('online-lobby');
3755 document.getElementById('lobby-me-name').textContent = Online.me.name;
3756 document.getElementById('lobby-code').textContent = Online.lobby.code;
3757 var list = document.getElementById('lobby-players');
3758 list.innerHTML = '';
3759 var players = Online.lobby.players || [];
3760 for (var i = 0; i < players.length; i++)
3761 {
3762 var p = players[i];
3763 var li = document.createElement('li');
3764 if (p.is_me)
3765 { li.classList.add('you'); }
3766 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
3767 var state = p.ready ? 'Gereed' : 'Wacht…';
3768 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
3769 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
3770 list.appendChild(li);
3771 }
3772 var me = Online.mePlayer();
3773 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
3774 var start = document.getElementById('btn-start');
3775 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
3776 start.disabled = !Online.lobby.can_start;
3777 var hint = document.getElementById('lobby-hint');
3778 if (Online.lobby.status === 'playing')
3779 { hint.textContent = 'Het spel start…'; }
3780 else if (players.length < 2)
3781 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
3782 else if (!Online.lobby.all_ready)
3783 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
3784 else if (Online.lobby.can_start)
3785 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
3786 else
3787 { hint.textContent = 'Wachten tot de host start.'; }
3788 return;
3789 }
3790 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
3791 showOnly('online-home');
3792 document.getElementById('me-name').textContent = Online.me.name;
3793 document.getElementById('local-login').hidden = !Online.local;
3794 }
3795
3796 function escapeText (s)
3797 {
3798 return String(s)
3799 .replace(/&/g, '&amp;')
3800 .replace(/</g, '&lt;')
3801 .replace(/>/g, '&gt;')
3802 .replace(/"/g, '&quot;');
3803 }
3804
2742 3805 /*
2743 3806 * End File:
2744 3807 * /workspace/meteors/src/main.js
@@ -443,6 +443,17 @@ function GameCore (planet, rng)
443 this.state = 'playing';
443 this.state = 'playing';
444 this.drag = null;
444 this.drag = null;
445 this.gameOverTime = 0;
445 this.gameOverTime = 0;
446 this.outgoingShots = [];
447 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
448 this.missChance = optsMissChance(arguments);
449}
450
451function optsMissChance (args)
452{
453 // GameCore(planet, rng, missChance) — third arg is optional.
454 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
455 { return Math.max(0, Math.min(1, args[2])); }
456 return GameCore.DEFAULT_MISS_CHANCE;
446}
457}
447
458
448GameCore.COLOR_GRAY = COLOR_GRAY;
459GameCore.COLOR_GRAY = COLOR_GRAY;
@@ -450,6 +461,7 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
450GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
461GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
451GameCore.SNAP_Y = SNAP_Y;
462GameCore.SNAP_Y = SNAP_Y;
452GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
463GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
464GameCore.DEFAULT_MISS_CHANCE = 0.30;
453GameCore.STATE_STILL = STATE_STILL;
465GameCore.STATE_STILL = STATE_STILL;
454GameCore.STATE_FALLING = STATE_FALLING;
466GameCore.STATE_FALLING = STATE_FALLING;
455GameCore.STATE_FLYING = STATE_FLYING;
467GameCore.STATE_FLYING = STATE_FLYING;
@@ -1508,9 +1520,88 @@ GameCore.prototype.cullOffTop = function ()
1508 }
1520 }
1509 for (var i = 0; i < gone.length; i++)
1521 for (var i = 0; i < gone.length; i++)
1510 {
1522 {
1523 var block = gone[i];
1524 this.outgoingShots.push({
1525 id: block.id,
1526 color: block.color,
1527 col: block.col,
1528 y: block.y
1529 });
1511 this.score += 1;
1530 this.score += 1;
1512 this.removeBlock(gone[i]);
1531 this.removeBlock(block);
1532 }
1533};
1534
1535GameCore.prototype.consumeOutgoingShots = function ()
1536{
1537 var shots = this.outgoingShots;
1538 this.outgoingShots = [];
1539 return shots;
1540};
1541
1542/**
1543 * A compact field picture for the multiplayer snapshot (miniatures).
1544 * Includes every block's col, y, color, state and flame.
1545 */
1546GameCore.prototype.fieldSnapshot = function ()
1547{
1548 var blocks = [];
1549 for (var i = 0; i < this.blocks.length; i++)
1550 {
1551 var b = this.blocks[i];
1552 blocks.push({
1553 id: b.id,
1554 col: b.col,
1555 y: Math.round(b.y * 1000) / 1000,
1556 color: b.color,
1557 state: b.state,
1558 flame: !!b.flame
1559 });
1560 }
1561 return {
1562 score: this.score,
1563 state: this.state,
1564 width: this.width,
1565 height: this.height,
1566 locked: this.lockedColumnCount(),
1567 blocks: blocks
1568 };
1569};
1570
1571/**
1572 * Incoming garbage from another player: a dark-grey block that falls
1573 * normally from the top of an open column. After landing it uses the
1574 * usual 3s settle and then a random colour (landFallingBlock).
1575 * `col` is optional; a random eligible column is used otherwise.
1576 * Returns the new block, or null if every column is locked or full.
1577 */
1578GameCore.prototype.ingestGarbage = function (col)
1579{
1580 if (this.state !== 'playing')
1581 { return null; }
1582 var chosen = null;
1583 if (col != null && col >= 0 && col < this.width
1584 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
1585 { chosen = col | 0; }
1586 else
1587 {
1588 var eligible = [];
1589 for (var c = 0; c < this.width; c++)
1590 {
1591 if (this.isColumnLocked(c))
1592 { continue; }
1593 if (this.groundedCount(c) >= this.height)
1594 { continue; }
1595 eligible.push(c);
1596 }
1597 if (!eligible.length)
1598 { return null; }
1599 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1513 }
1600 }
1601 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
1602 block.vy = -this.planet.fallSpeed;
1603 block.flame = false;
1604 return block;
1514};
1605};
1515
1606
1516GameCore.prototype.advanceSettle = function (dt)
1607GameCore.prototype.advanceSettle = function (dt)
@@ -2188,6 +2279,538 @@ else if (typeof globalThis !== 'undefined')
2188 * /workspace/meteors/src/gameCore.js
2279 * /workspace/meteors/src/gameCore.js
2189 */
2280 */
2190
2281
2282/*
2283 * Start File:
2284 * /workspace/meteors/src/online.js
2285 */
2286'use strict';
2287
2288/**
2289 * Online play: talks to api.php (cookie session), polls lobby and game
2290 * state, and draws opponent miniatures plus flying-block tweens.
2291 * Real-time sync is not required; a 0.75 s poll is enough.
2292 */
2293
2294var Online = {
2295 POLL_MS: 750,
2296 DEFAULT_MISS_CHANCE: 0.30,
2297 FLIGHT_DURATION: 1.2,
2298 configured: false,
2299 local: false,
2300 csrf: '',
2301 me: null,
2302 lobby: null,
2303 incoming: [],
2304 shotResults: [],
2305 error: '',
2306 _timer: null,
2307 _pendingShots: [],
2308 _flights: [],
2309 _lastStatus: null,
2310 onChange: null,
2311 onGameStart: null,
2312 onIncoming: null,
2313 onFinished: null,
2314 onLobbyReturn: null
2315};
2316
2317Online._headers = function (json)
2318{
2319 var h = { 'Accept': 'application/json' };
2320 if (json)
2321 { h['Content-Type'] = 'application/json'; }
2322 if (this.csrf)
2323 { h['X-CSRF-Token'] = this.csrf; }
2324 return h;
2325};
2326
2327Online._apply = function (data)
2328{
2329 if (!data)
2330 { return; }
2331 if (typeof data.configured === 'boolean')
2332 { this.configured = data.configured; }
2333 if (typeof data.local === 'boolean')
2334 { this.local = data.local; }
2335 if (data.csrf)
2336 { this.csrf = data.csrf; }
2337 if (data.me !== undefined)
2338 { this.me = data.me; }
2339 if (data.lobby !== undefined)
2340 { this.lobby = data.lobby; }
2341 if (data.incoming)
2342 { this.incoming = data.incoming; }
2343 if (data.shot_results)
2344 { this.shotResults = data.shot_results; }
2345 if (data.miss_chance_default != null)
2346 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
2347 if (data.flight_duration != null)
2348 { this.FLIGHT_DURATION = data.flight_duration; }
2349 if (data.error)
2350 { this.error = data.error; }
2351 else if (data.ok)
2352 { this.error = ''; }
2353};
2354
2355Online.request = function (action, body)
2356{
2357 var self = this;
2358 var isGet = action === 'me' || action === '';
2359 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
2360 var opts = {
2361 method: isGet && !body ? 'GET' : 'POST',
2362 credentials: 'same-origin',
2363 headers: this._headers(!!body || !isGet)
2364 };
2365 if (opts.method === 'POST')
2366 {
2367 var payload = body ? Object.assign({ action: action }, body) : { action: action };
2368 opts.body = JSON.stringify(payload);
2369 }
2370 return fetch(url, opts).then(function (res)
2371 {
2372 return res.json().then(function (data)
2373 {
2374 data = data || {};
2375 if (!res.ok && !data.error)
2376 { data.error = 'De server gaf ' + res.status; data.ok = false; }
2377 self._apply(data);
2378 return data;
2379 }, function ()
2380 {
2381 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
2382 self.error = fail.error;
2383 return fail;
2384 });
2385 }).catch(function (err)
2386 {
2387 var fail = { ok: false, error: 'Geen verbinding met de server.' };
2388 self.error = fail.error;
2389 return fail;
2390 });
2391};
2392
2393Online.refresh = function ()
2394{
2395 return this.request('me');
2396};
2397
2398Online.testLogin = function (who)
2399{
2400 return this.request('test_login', { user: who });
2401};
2402
2403Online.createLobby = function ()
2404{
2405 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
2406};
2407
2408Online.joinLobby = function (code)
2409{
2410 return this.request('lobby_join', { code: code });
2411};
2412
2413Online.leaveLobby = function ()
2414{
2415 return this.request('lobby_leave');
2416};
2417
2418Online.setReady = function (ready)
2419{
2420 return this.request('lobby_ready', { ready: !!ready });
2421};
2422
2423Online.startGame = function ()
2424{
2425 var self = this;
2426 var prev = this.lobby && this.lobby.status;
2427 return this.request('lobby_start').then(function (data)
2428 {
2429 self._handleTransitions(prev, data);
2430 return data;
2431 });
2432};
2433
2434Online.queueShots = function (shots)
2435{
2436 for (var i = 0; i < shots.length; i++)
2437 {
2438 this._pendingShots.push({
2439 client_id: String(shots[i].id),
2440 color: shots[i].color,
2441 col: shots[i].col,
2442 y: shots[i].y
2443 });
2444 }
2445};
2446
2447Online.poll = function (opts)
2448{
2449 opts = opts || {};
2450 var body = {};
2451 if (opts.snapshot)
2452 { body.snapshot = opts.snapshot; }
2453 if (opts.score != null)
2454 { body.score = opts.score; }
2455 if (opts.eliminated)
2456 { body.eliminated = true; }
2457 if (this._pendingShots.length)
2458 {
2459 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
2460 }
2461 var self = this;
2462 var prevStatus = this.lobby && this.lobby.status;
2463 return this.request('poll', body).then(function (data)
2464 {
2465 self._handleTransitions(prevStatus, data);
2466 if (self.onChange)
2467 { self.onChange(self); }
2468 return data;
2469 });
2470};
2471
2472Online._handleTransitions = function (prevStatus, data)
2473{
2474 var lobby = this.lobby;
2475 var status = lobby && lobby.status;
2476 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
2477 { this.onGameStart(lobby); }
2478 if (data && data.incoming && data.incoming.length && this.onIncoming)
2479 { this.onIncoming(data.incoming); }
2480 if (data && data.shot_results && data.shot_results.length)
2481 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
2482 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
2483 { this.onFinished(lobby); }
2484 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
2485 { this.onLobbyReturn(lobby); }
2486};
2487
2488Online.startPolling = function (getPayload)
2489{
2490 this.stopPolling();
2491 var self = this;
2492 var tick = function ()
2493 {
2494 var payload = getPayload ? getPayload() : {};
2495 self.poll(payload);
2496 };
2497 tick();
2498 this._timer = setInterval(tick, this.POLL_MS);
2499};
2500
2501Online.stopPolling = function ()
2502{
2503 if (this._timer)
2504 {
2505 clearInterval(this._timer);
2506 this._timer = null;
2507 }
2508};
2509
2510Online.loginUrl = function ()
2511{
2512 return 'auth.php';
2513};
2514
2515Online.logoutUrl = function ()
2516{
2517 return 'logout.php';
2518};
2519
2520Online.opponents = function ()
2521{
2522 if (!this.lobby || !this.lobby.players)
2523 { return []; }
2524 return this.lobby.players.filter(function (p) { return !p.is_me; });
2525};
2526
2527Online.aliveOpponents = function ()
2528{
2529 return this.opponents().filter(function (p) { return !p.eliminated; });
2530};
2531
2532Online.mePlayer = function ()
2533{
2534 if (!this.lobby || !this.lobby.players)
2535 { return null; }
2536 for (var i = 0; i < this.lobby.players.length; i++)
2537 {
2538 if (this.lobby.players[i].is_me)
2539 { return this.lobby.players[i]; }
2540 }
2541 return null;
2542};
2543
2544/* ---------- miniatures --------------------------------------------- */
2545
2546Online.renderMinis = function (container)
2547{
2548 if (!container)
2549 { return; }
2550 var opponents = this.opponents();
2551 var existing = {};
2552 var kids = container.querySelectorAll('[data-player]');
2553 for (var i = 0; i < kids.length; i++)
2554 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
2555
2556 var seen = Object.create(null);
2557 for (var i = 0; i < opponents.length; i++)
2558 {
2559 var p = opponents[i];
2560 seen[p.id] = true;
2561 var el = existing[p.id];
2562 if (!el)
2563 {
2564 el = document.createElement('div');
2565 el.className = 'mini';
2566 el.setAttribute('data-player', p.id);
2567 el.innerHTML = '<div class="mini-name"></div>'
2568 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
2569 + '<div class="mini-meta"></div>';
2570 container.appendChild(el);
2571 }
2572 el.classList.toggle('eliminated', !!p.eliminated);
2573 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
2574 el.querySelector('.mini-meta').textContent = p.eliminated
2575 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
2576 : ('Punten ' + (p.score || 0));
2577 this._drawMini(el.querySelector('canvas'), p.snapshot);
2578 }
2579 for (var id in existing)
2580 {
2581 if (!seen[id])
2582 { existing[id].remove(); }
2583 }
2584};
2585
2586var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
2587
2588Online._drawMini = function (canvas, snapshot)
2589{
2590 if (!canvas)
2591 { return; }
2592 var ctx = canvas.getContext('2d');
2593 var w = 10;
2594 var h = 13;
2595 var tw = canvas.width / w;
2596 var th = canvas.height / h;
2597 ctx.fillStyle = '#0c1020';
2598 ctx.fillRect(0, 0, canvas.width, canvas.height);
2599 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
2600 ctx.lineWidth = 1;
2601 for (var c = 0; c <= w; c++)
2602 {
2603 ctx.beginPath();
2604 ctx.moveTo(c * tw + 0.5, 0);
2605 ctx.lineTo(c * tw + 0.5, canvas.height);
2606 ctx.stroke();
2607 }
2608 for (var r = 0; r <= h; r++)
2609 {
2610 ctx.beginPath();
2611 ctx.moveTo(0, r * th + 0.5);
2612 ctx.lineTo(canvas.width, r * th + 0.5);
2613 ctx.stroke();
2614 }
2615 if (!snapshot || !snapshot.blocks)
2616 { return; }
2617 var blocks = snapshot.blocks;
2618 for (var i = 0; i < blocks.length; i++)
2619 {
2620 var b = blocks[i];
2621 var x = b.col * tw;
2622 var y = canvas.height - (b.y + 1) * th;
2623 if (b.state === 'locked')
2624 { ctx.fillStyle = '#3a3d4a'; }
2625 else if (b.color < 0)
2626 { ctx.fillStyle = '#5a5d66'; }
2627 else
2628 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
2629 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
2630 }
2631};
2632
2633Online.miniElement = function (playerId)
2634{
2635 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
2636};
2637
2638/* ---------- flight tweens ------------------------------------------ */
2639
2640function colorSpriteUrl (color)
2641{
2642 if (color < 0)
2643 { return 'images/block-gray.png'; }
2644 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
2645 return 'images/block-' + (names[color] || 'gray') + '.png';
2646}
2647
2648/**
2649 * Animate shot results. `locals` is a map of client_id → {col, y, color,
2650 * startX, startY} in viewport pixels, filled by the view just after
2651 * consumeOutgoingShots.
2652 */
2653Online.spawnFlights = function (results, locals)
2654{
2655 locals = locals || this._flightLocals || {};
2656 var layer = document.getElementById('flights');
2657 if (!layer)
2658 { return; }
2659 for (var i = 0; i < results.length; i++)
2660 {
2661 var r = results[i];
2662 var meta = locals[r.client_id] || {};
2663 var start = this._flightStart(meta.col);
2664 var end;
2665 var miss = !!r.miss;
2666 if (miss)
2667 { end = this._missEnd(start); }
2668 else
2669 { end = this._targetEnd(r.target_id, start); }
2670 var el = document.createElement('img');
2671 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
2672 el.alt = '';
2673 el.className = 'flight';
2674 layer.appendChild(el);
2675 var spin = (Math.random() * 2 - 1) * 720;
2676 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
2677 this._flights.push({
2678 el: el,
2679 start: start,
2680 end: end,
2681 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
2682 t0: performance.now(),
2683 duration: duration,
2684 spin: spin,
2685 miss: miss,
2686 angle: Math.random() * 360
2687 });
2688 }
2689 this._flightLocals = {};
2690};
2691
2692Online.rememberFlightLocal = function (shot, startX, startY)
2693{
2694 if (!this._flightLocals)
2695 { this._flightLocals = {}; }
2696 this._flightLocals[String(shot.id)] = {
2697 col: shot.col,
2698 y: shot.y,
2699 color: shot.color,
2700 startX: startX,
2701 startY: startY
2702 };
2703};
2704
2705Online._flightStart = function (col)
2706{
2707 var field = document.querySelector('canvas');
2708 var appRef = typeof app !== 'undefined' ? app : null;
2709 if (appRef && appRef.scene && appRef.scene.canvas)
2710 {
2711 var canvas = appRef.scene.canvas;
2712 var rect = canvas.getBoundingClientRect();
2713 var c = col == null ? 4.5 : col;
2714 return {
2715 x: rect.left + (c + 0.5) * (rect.width / 10),
2716 y: rect.top + 4
2717 };
2718 }
2719 if (field)
2720 {
2721 var rect = field.getBoundingClientRect();
2722 return { x: rect.left + rect.width / 2, y: rect.top };
2723 }
2724 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
2725};
2726
2727Online._targetEnd = function (targetId, start)
2728{
2729 var el = targetId && this.miniElement(targetId);
2730 if (el)
2731 {
2732 var r = el.getBoundingClientRect();
2733 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
2734 }
2735 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
2736};
2737
2738Online._missEnd = function (start)
2739{
2740 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
2741 return {
2742 x: start.x + dx,
2743 y: start.y - (120 + Math.random() * 220)
2744 };
2745};
2746
2747Online._missCtrl = function (start, end)
2748{
2749 return {
2750 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
2751 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
2752 };
2753};
2754
2755Online._hitCtrl = function (start, end)
2756{
2757 return {
2758 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
2759 y: (start.y + end.y) / 2 - 30
2760 };
2761};
2762
2763Online.tickFlights = function (now)
2764{
2765 now = now || performance.now();
2766 var leftover = [];
2767 for (var i = 0; i < this._flights.length; i++)
2768 {
2769 var f = this._flights[i];
2770 var u = (now - f.t0) / f.duration;
2771 if (u >= 1)
2772 {
2773 if (f.el && f.el.parentNode)
2774 { f.el.parentNode.removeChild(f.el); }
2775 continue;
2776 }
2777 // Quadratic bezier, ease-in so they feel like they recede.
2778 var e = u * u;
2779 var mt = 1 - e;
2780 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
2781 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
2782 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
2783 var angle = f.angle + f.spin * u;
2784 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
2785 + angle + 'deg) scale(' + scale + ')';
2786 f.el.style.opacity = f.miss ? String(1 - e) : '1';
2787 leftover.push(f);
2788 }
2789 this._flights = leftover;
2790};
2791
2792Online.clearFlights = function ()
2793{
2794 for (var i = 0; i < this._flights.length; i++)
2795 {
2796 var el = this._flights[i].el;
2797 if (el && el.parentNode)
2798 { el.parentNode.removeChild(el); }
2799 }
2800 this._flights = [];
2801 this._flightLocals = {};
2802};
2803
2804if (typeof globalThis !== 'undefined')
2805{ globalThis.Online = Online; }
2806if (typeof module !== 'undefined' && module.exports)
2807{ module.exports = Online; }
2808
2809/*
2810 * End File:
2811 * /workspace/meteors/src/online.js
2812 */
2813
2191/*
2814/*
2192 * Start File:
2815 * Start File:
2193 * /workspace/meteors/src/main.js
2816 * /workspace/meteors/src/main.js
@@ -2197,8 +2820,8 @@ else if (typeof globalThis !== 'undefined')
2197/**
2820/**
2198 * View and input for Meteors. The simulation lives in GameCore; this file
2821 * View and input for Meteors. The simulation lives in GameCore; this file
2199 * only draws it, scales it to the viewport, and translates pointer events
2822 * only draws it, scales it to the viewport, and translates pointer events
2200 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
2823 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
2201 * that reuses the same core.
2824 * through Online (src/online.js) and the same GameCore.
2202 */
2825 */
2203
2826
2204var IMAGES = [
2827var IMAGES = [
@@ -2236,7 +2859,11 @@ var app = {
2236 cells: [],
2859 cells: [],
2237 pointerId: null,
2860 pointerId: null,
2238 gameOverShown: false,
2861 gameOverShown: false,
2239 selectTween: null
2862 selectTween: null,
2863 online: false,
2864 eliminatedReported: false,
2865 spectating: false,
2866 miniH: 0
2240};
2867};
2241
2868
2242window.onload = function ()
2869window.onload = function ()
@@ -2259,6 +2886,8 @@ window.onload = function ()
2259 if (game.images.flame && game.images.flame.addAnimationCycle)
2886 if (game.images.flame && game.images.flame.addAnimationCycle)
2260 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
2887 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
2261 });
2888 });
2889
2890 bindOnlineUi();
2262};
2891};
2263
2892
2264function onPlay ()
2893function onPlay ()
@@ -2268,16 +2897,27 @@ function onPlay ()
2268 startPlay();
2897 startPlay();
2269}
2898}
2270
2899
2271function startPlay ()
2900function startPlay (opts)
2272{
2901{
2902 opts = opts || {};
2273 hideEl('menu');
2903 hideEl('menu');
2274 hideEl('game-over');
2904 hideEl('game-over');
2905 hideEl('online-panel');
2906 hideEl('spectator');
2907 hideEl('podium');
2275 showEl('hud');
2908 showEl('hud');
2276
2909
2277 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
2910 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
2278 app.core = new GameCore(app.planet, Math.random);
2911 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); }
2279 app.mode = 'playing';
2916 app.mode = 'playing';
2917 app.online = !!opts.online;
2280 app.gameOverShown = false;
2918 app.gameOverShown = false;
2919 app.eliminatedReported = false;
2920 app.spectating = false;
2281 app.sprites = Object.create(null);
2921 app.sprites = Object.create(null);
2282 app.flames = Object.create(null);
2922 app.flames = Object.create(null);
2283 app.cells = [];
2923 app.cells = [];
@@ -2285,6 +2925,11 @@ function startPlay ()
2285 app.selectTween = null;
2925 app.selectTween = null;
2286
2926
2287 layout();
2927 layout();
2928 if (app.scene)
2929 {
2930 app.scene.destroy();
2931 app.scene = null;
2932 }
2288 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
2933 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
2289 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
2934 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
2290 app.scene.renderBackground = true;
2935 app.scene.renderBackground = true;
@@ -2292,11 +2937,16 @@ function startPlay ()
2292
2937
2293 buildCells();
2938 buildCells();
2294 app.manager = app.scene.addObject(makeManager());
2939 app.manager = app.scene.addObject(makeManager());
2295 bindPointer(app.scene.canvas);
2940 if (!app.spectating)
2941 { bindPointer(app.scene.canvas); }
2296 refreshHud();
2942 refreshHud();
2943 if (app.online)
2944 { showEl('minis'); }
2945 else
2946 { hideEl('minis'); }
2297}
2947}
2298
2948
2299function returnToMenu ()
2949function teardownPlay ()
2300{
2950{
2301 unbindPointer();
2951 unbindPointer();
2302 if (app.scene)
2952 if (app.scene)
@@ -2306,14 +2956,31 @@ function returnToMenu ()
2306 }
2956 }
2307 app.manager = null;
2957 app.manager = null;
2308 app.core = null;
2958 app.core = null;
2309 app.mode = 'menu';
2310 app.sprites = Object.create(null);
2959 app.sprites = Object.create(null);
2311 app.flames = Object.create(null);
2960 app.flames = Object.create(null);
2312 app.cells = [];
2961 app.cells = [];
2313 app.selectTween = null;
2962 app.selectTween = null;
2314
2963 app.pointerId = null;
2964 app.gameOverShown = false;
2315 hideEl('hud');
2965 hideEl('hud');
2316 hideEl('game-over');
2966 hideEl('game-over');
2967 hideEl('spectator');
2968 hideEl('minis');
2969 if (typeof Online !== 'undefined')
2970 { Online.clearFlights(); }
2971}
2972
2973function returnToMenu ()
2974{
2975 if (app.online && typeof Online !== 'undefined')
2976 {
2977 // Online matches do not dump you back to the solo menu:
2978 // elimination becomes spectating; a finished match shows the podium.
2979 return;
2980 }
2981 teardownPlay();
2982 app.mode = 'menu';
2983 app.online = false;
2317 showEl('menu');
2984 showEl('menu');
2318 var last = document.getElementById('last-score');
2985 var last = document.getElementById('last-score');
2319 if (app.lastScore > 0)
2986 if (app.lastScore > 0)
@@ -2361,16 +3028,26 @@ function layout ()
2361 }
3028 }
2362 catch (e) { /* ignore */ }
3029 catch (e) { /* ignore */ }
2363 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
3030 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
3031 app.miniH = 0;
3032 if (app.online)
3033 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
2364 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
3034 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
2365 var availW = Math.max(80, vw - margin * 2);
3035 var availW = Math.max(80, vw - margin * 2);
2366 var availH = Math.max(80, vh - app.hudH - margin);
3036 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
2367 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
3037 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
2368 app.fieldW = app.tile * 10;
3038 app.fieldW = app.tile * 10;
2369 app.fieldH = app.tile * 13;
3039 app.fieldH = app.tile * 13;
2370 app.fieldX = Math.floor((vw - app.fieldW) / 2);
3040 app.fieldX = Math.floor((vw - app.fieldW) / 2);
2371 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
3041 var topBand = app.hudH + app.miniH;
2372 if (app.fieldY < app.hudH)
3042 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
2373 { app.fieldY = app.hudH; }
3043 if (app.fieldY < topBand)
3044 { app.fieldY = topBand; }
3045 var minis = document.getElementById('minis');
3046 if (minis)
3047 {
3048 minis.style.top = app.hudH + 'px';
3049 minis.style.maxHeight = app.miniH + 'px';
3050 }
2374
3051
2375 if (app.scene)
3052 if (app.scene)
2376 {
3053 {
@@ -2582,15 +3259,19 @@ function tickView (dt)
2582 updateSelectTween(dt);
3259 updateSelectTween(dt);
2583 syncSprites();
3260 syncSprites();
2584 refreshHud();
3261 refreshHud();
3262 tickOnline(dt);
2585
3263
2586 if (app.core.state === 'gameover' && !app.gameOverShown)
3264 if (app.core.state === 'gameover' && !app.gameOverShown)
2587 {
3265 {
2588 app.gameOverShown = true;
3266 app.gameOverShown = true;
2589 app.lastScore = app.core.score;
3267 app.lastScore = app.core.score;
2590 document.getElementById('go-score').textContent = String(app.lastScore);
3268 document.getElementById('go-score').textContent = String(app.lastScore);
2591 showEl('game-over');
3269 if (app.online)
3270 { onOnlineEliminated(); }
3271 else
3272 { showEl('game-over'); }
2592 }
3273 }
2593 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
3274 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
2594 { returnToMenu(); }
3275 { returnToMenu(); }
2595}
3276}
2596
3277
@@ -2739,6 +3420,388 @@ window.addEventListener('orientationchange', function ()
2739 }, 120);
3420 }, 120);
2740});
3421});
2741
3422
3423/* ---------- online play (stage 2) ---------------------------------- */
3424
3425function tickOnline (dt)
3426{
3427 if (!app.online || typeof Online === 'undefined')
3428 { return; }
3429 if (app.core)
3430 {
3431 var shots = app.core.consumeOutgoingShots();
3432 for (var i = 0; i < shots.length; i++)
3433 {
3434 var s = shots[i];
3435 var start = fieldToViewport(s.col, s.y + 1);
3436 Online.rememberFlightLocal(s, start.x, start.y);
3437 }
3438 Online.queueShots(shots);
3439 }
3440 Online.tickFlights();
3441 Online.renderMinis(document.getElementById('minis'));
3442}
3443
3444function fieldToViewport (col, fieldY)
3445{
3446 var canvas = app.scene && app.scene.canvas;
3447 if (!canvas)
3448 { return { x: window.innerWidth / 2, y: 40 }; }
3449 var rect = canvas.getBoundingClientRect();
3450 var x = rect.left + ((col + 0.5) / 10) * rect.width;
3451 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
3452 return { x: x, y: y };
3453}
3454
3455function onlinePayload ()
3456{
3457 if (!app.online || !app.core)
3458 { return {}; }
3459 return {
3460 snapshot: app.core.fieldSnapshot(),
3461 score: app.core.score,
3462 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
3463 };
3464}
3465
3466function onOnlineEliminated ()
3467{
3468 app.eliminatedReported = true;
3469 app.spectating = true;
3470 unbindPointer();
3471 hideEl('game-over');
3472 var lobby = typeof Online !== 'undefined' && Online.lobby;
3473 if (lobby && lobby.status === 'finished')
3474 {
3475 showPodium(lobby);
3476 return;
3477 }
3478 showEl('spectator');
3479}
3480
3481function showPodium (lobby)
3482{
3483 hideEl('spectator');
3484 hideEl('game-over');
3485 hideEl('online-panel');
3486 showEl('podium');
3487 var list = document.getElementById('podium-list');
3488 list.innerHTML = '';
3489 var ranks = (lobby && lobby.rankings) || [];
3490 for (var i = 0; i < ranks.length; i++)
3491 {
3492 var r = ranks[i];
3493 var li = document.createElement('li');
3494 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
3495 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
3496 list.appendChild(li);
3497 }
3498 var hint = document.getElementById('podium-hint');
3499 var secs = (lobby && lobby.podium_seconds) || 5;
3500 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
3501}
3502
3503function startOnlineMatch ()
3504{
3505 if (app.mode === 'playing' && app.online)
3506 { 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 });
3511 if (typeof Online !== 'undefined')
3512 { Online.startPolling(onlinePayload); }
3513}
3514
3515function leaveOnlineMatch (goMenu)
3516{
3517 if (typeof Online !== 'undefined')
3518 {
3519 Online.stopPolling();
3520 Online.leaveLobby();
3521 Online.clearFlights();
3522 }
3523 teardownPlay();
3524 app.online = false;
3525 if (goMenu)
3526 {
3527 app.mode = 'menu';
3528 showEl('menu');
3529 }
3530 else
3531 {
3532 app.mode = 'online';
3533 openOnlinePanel();
3534 }
3535}
3536
3537function bindOnlineUi ()
3538{
3539 var onlineBtn = document.getElementById('btn-online');
3540 if (!onlineBtn)
3541 { return; }
3542 onlineBtn.addEventListener('click', function ()
3543 { openOnlinePanel(); });
3544
3545 var backs = document.querySelectorAll('[data-back-menu]');
3546 for (var i = 0; i < backs.length; i++)
3547 {
3548 backs[i].addEventListener('click', function ()
3549 {
3550 if (typeof Online !== 'undefined')
3551 { Online.stopPolling(); }
3552 hideEl('online-panel');
3553 app.mode = 'menu';
3554 app.online = false;
3555 showEl('menu');
3556 });
3557 }
3558
3559 document.getElementById('btn-create').addEventListener('click', function ()
3560 {
3561 Online.createLobby().then(function (data)
3562 {
3563 if (data && data.ok)
3564 {
3565 renderOnline();
3566 Online.startPolling(onlinePayload);
3567 }
3568 else
3569 { renderOnline(); }
3570 });
3571 });
3572
3573 document.getElementById('join-form').addEventListener('submit', function (e)
3574 {
3575 e.preventDefault();
3576 var code = (document.getElementById('join-code').value || '').trim();
3577 if (!code)
3578 { return; }
3579 Online.joinLobby(code).then(function ()
3580 {
3581 renderOnline();
3582 if (Online.lobby)
3583 { Online.startPolling(onlinePayload); }
3584 });
3585 });
3586
3587 document.getElementById('btn-ready').addEventListener('click', function ()
3588 {
3589 var me = Online.mePlayer();
3590 Online.setReady(!(me && me.ready)).then(renderOnline);
3591 });
3592
3593 document.getElementById('btn-start').addEventListener('click', function ()
3594 {
3595 Online.startGame().then(function (data)
3596 {
3597 if (data && data.ok)
3598 { startOnlineMatch(); }
3599 else
3600 { renderOnline(); }
3601 });
3602 });
3603
3604 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
3605 {
3606 Online.leaveLobby().then(function ()
3607 {
3608 Online.stopPolling();
3609 renderOnline();
3610 });
3611 });
3612
3613 document.getElementById('btn-copy-code').addEventListener('click', function ()
3614 {
3615 var code = document.getElementById('lobby-code').textContent;
3616 if (navigator.clipboard && navigator.clipboard.writeText)
3617 { navigator.clipboard.writeText(code); }
3618 });
3619
3620 document.getElementById('btn-spectate').addEventListener('click', function ()
3621 {
3622 hideEl('spectator');
3623 app.spectating = true;
3624 });
3625
3626 document.getElementById('btn-leave-game').addEventListener('click', function ()
3627 { leaveOnlineMatch(false); });
3628
3629 if (typeof Online !== 'undefined')
3630 {
3631 Online.onChange = function ()
3632 { renderOnline(); };
3633 Online.onGameStart = function ()
3634 { startOnlineMatch(); };
3635 Online.onIncoming = function (incoming)
3636 {
3637 if (!app.core || app.core.state !== 'playing')
3638 { return; }
3639 for (var i = 0; i < incoming.length; i++)
3640 { app.core.ingestGarbage(); }
3641 };
3642 Online.onFinished = function (lobby)
3643 { showPodium(lobby); };
3644 Online.onLobbyReturn = function (lobby)
3645 {
3646 teardownPlay();
3647 app.online = false;
3648 app.mode = 'online';
3649 hideEl('podium');
3650 showEl('online-panel');
3651 renderOnline();
3652 Online.startPolling(onlinePayload);
3653 };
3654 }
3655
3656 var params = new URLSearchParams(window.location.search);
3657 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
3658 { openOnlinePanel(); }
3659}
3660
3661function openOnlinePanel ()
3662{
3663 hideEl('menu');
3664 hideEl('game-over');
3665 hideEl('podium');
3666 hideEl('spectator');
3667 showEl('online-panel');
3668 app.mode = 'online';
3669 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
3670 if (typeof Online === 'undefined')
3671 {
3672 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
3673 showOnly('online-unconfigured');
3674 return;
3675 }
3676 Online.refresh().then(function (data)
3677 {
3678 if (!data || data.ok === false)
3679 {
3680 var msg = (data && data.error) || 'Geen verbinding met de server.';
3681 showOnlineError(msg + ' Je kunt wel alleen spelen.');
3682 if (data && data.configured === false)
3683 { showOnly('online-unconfigured'); }
3684 else
3685 { showOnly('online-login'); }
3686 document.getElementById('btn-login').style.display = 'none';
3687 return;
3688 }
3689 renderOnline();
3690 if (Online.lobby)
3691 { Online.startPolling(onlinePayload); }
3692 });
3693}
3694
3695function setOnlineStatus (text)
3696{
3697 var el = document.getElementById('online-status');
3698 if (el)
3699 { el.textContent = text; }
3700}
3701
3702function showOnlineError (text)
3703{
3704 var el = document.getElementById('online-error');
3705 if (!el)
3706 { return; }
3707 if (!text)
3708 {
3709 el.hidden = true;
3710 el.textContent = '';
3711 return;
3712 }
3713 el.hidden = false;
3714 el.textContent = text;
3715}
3716
3717function showOnly (id)
3718{
3719 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
3720 for (var i = 0; i < ids.length; i++)
3721 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
3722}
3723
3724function renderOnline ()
3725{
3726 if (typeof Online === 'undefined')
3727 { return; }
3728 if (app.mode === 'playing' && app.online)
3729 {
3730 Online.renderMinis(document.getElementById('minis'));
3731 if (Online.lobby && Online.lobby.status === 'finished')
3732 { showPodium(Online.lobby); }
3733 return;
3734 }
3735 showOnlineError(Online.error);
3736 if (!Online.configured && !Online.me && !Online.local)
3737 {
3738 setOnlineStatus('Online spelen is nog niet ingesteld.');
3739 showOnly('online-unconfigured');
3740 return;
3741 }
3742 if (!Online.me)
3743 {
3744 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
3745 showOnly('online-login');
3746 document.getElementById('btn-login').style.display = '';
3747 document.getElementById('btn-login').href = Online.loginUrl();
3748 document.getElementById('local-login').hidden = !Online.local;
3749 return;
3750 }
3751 if (Online.lobby)
3752 {
3753 setOnlineStatus('Lobby');
3754 showOnly('online-lobby');
3755 document.getElementById('lobby-me-name').textContent = Online.me.name;
3756 document.getElementById('lobby-code').textContent = Online.lobby.code;
3757 var list = document.getElementById('lobby-players');
3758 list.innerHTML = '';
3759 var players = Online.lobby.players || [];
3760 for (var i = 0; i < players.length; i++)
3761 {
3762 var p = players[i];
3763 var li = document.createElement('li');
3764 if (p.is_me)
3765 { li.classList.add('you'); }
3766 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
3767 var state = p.ready ? 'Gereed' : 'Wacht…';
3768 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
3769 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
3770 list.appendChild(li);
3771 }
3772 var me = Online.mePlayer();
3773 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
3774 var start = document.getElementById('btn-start');
3775 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
3776 start.disabled = !Online.lobby.can_start;
3777 var hint = document.getElementById('lobby-hint');
3778 if (Online.lobby.status === 'playing')
3779 { hint.textContent = 'Het spel start…'; }
3780 else if (players.length < 2)
3781 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
3782 else if (!Online.lobby.all_ready)
3783 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
3784 else if (Online.lobby.can_start)
3785 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
3786 else
3787 { hint.textContent = 'Wachten tot de host start.'; }
3788 return;
3789 }
3790 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
3791 showOnly('online-home');
3792 document.getElementById('me-name').textContent = Online.me.name;
3793 document.getElementById('local-login').hidden = !Online.local;
3794}
3795
3796function escapeText (s)
3797{
3798 return String(s)
3799 .replace(/&/g, '&amp;')
3800 .replace(/</g, '&lt;')
3801 .replace(/>/g, '&gt;')
3802 .replace(/"/g, '&quot;');
3803}
3804
2742/*
3805/*
2743 * End File:
3806 * End File:
2744 * /workspace/meteors/src/main.js
3807 * /workspace/meteors/src/main.js
build/index.html +68 −0
@@ -12,15 +12,67 @@
12 12 </head>
13 13 <body>
14 14 <div id="stars" aria-hidden="true"></div>
15 <div id="flights" aria-hidden="true"></div>
15 16
16 17 <div id="menu" class="screen">
17 18 <h1>Meteors</h1>
18 19 <p class="tagline">Drie op een rij, en je blokjes krijgen raketmotoren.</p>
19 20 <button type="button" id="btn-play">Spelen</button>
21 <button type="button" id="btn-online" class="btn-secondary">Online spelen</button>
20 22 <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
21 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>
22 24 </div>
23 25
26 <div id="online-panel" class="screen" hidden>
27 <h1>Online</h1>
28 <p id="online-status" class="tagline">Even kijken of online spelen beschikbaar is…</p>
29 <p id="online-error" class="error" hidden></p>
30
31 <div id="online-unconfigured" hidden>
32 <p class="notice">Online spelen is nog niet ingesteld. De beheerder moet bij <a href="https://auth.timfalken.com/admin" target="_blank" rel="noopener">auth.timfalken.com/admin</a> het callback-pad <code>/meteors/callback.php</code> toevoegen (zelfde client als de andere sites op dit domein; het geheim <strong>niet</strong> opnieuw genereren) en dat geheim in <code>data/config.php</code> op de server zetten. Zie de README.</p>
33 <p>Je kunt wel alleen spelen.</p>
34 <button type="button" class="btn-secondary" data-back-menu>Terug</button>
35 </div>
36
37 <div id="online-login" hidden>
38 <p>Om online te spelen log je in met je account op auth.timfalken.com.</p>
39 <a id="btn-login" class="button" href="auth.php">Inloggen</a>
40 <button type="button" class="btn-secondary" data-back-menu>Terug</button>
41 <p id="local-login" class="hint" hidden>
42 Lokale test:
43 <a href="auth.php?test=1">test_user_1</a> ·
44 <a href="auth.php?test=2">test_user_2</a>
45 </p>
46 </div>
47
48 <div id="online-home" hidden>
49 <p class="who">Ingelogd als <strong id="me-name"></strong> · <a href="logout.php">Uitloggen</a></p>
50 <button type="button" id="btn-create">Lobby maken</button>
51 <form id="join-form" class="join-form">
52 <label>
53 <span>Lobbycode</span>
54 <input id="join-code" type="text" maxlength="6" autocomplete="off" spellcheck="false" placeholder="ABCD">
55 </label>
56 <button type="submit" id="btn-join">Deelnemen</button>
57 </form>
58 <button type="button" class="btn-secondary" data-back-menu>Terug</button>
59 </div>
60
61 <div id="online-lobby" hidden>
62 <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>
64 <ul id="lobby-players" class="player-list"></ul>
65 <p id="lobby-hint" class="hint"></p>
66 <div class="lobby-actions">
67 <button type="button" id="btn-ready">Gereed</button>
68 <button type="button" id="btn-start" hidden>Starten</button>
69 <button type="button" id="btn-leave-lobby" class="btn-secondary">Verlaten</button>
70 </div>
71 </div>
72 </div>
73
74 <div id="minis" hidden></div>
75
24 76 <div id="hud" hidden>
25 77 <div class="hud-left">
26 78 <div class="hud-label">Punten</div>
@@ -38,6 +90,22 @@
38 90 <p class="go-score">Score: <strong id="go-score">0</strong></p>
39 91 </div>
40 92
93 <div id="spectator" class="screen overlay" hidden>
94 <h2>Je ligt eruit</h2>
95 <p>Al je kolommen zitten vol. Je kunt toekijken of de wedstrijd verlaten.</p>
96 <div class="lobby-actions">
97 <button type="button" id="btn-spectate">Toekijken</button>
98 <button type="button" id="btn-leave-game" class="btn-secondary">Verlaten</button>
99 </div>
100 </div>
101
102 <div id="podium" class="screen overlay" hidden>
103 <h2>Gewonnen!</h2>
104 <p id="podium-title" class="tagline">De laatste speler staat overeind.</p>
105 <ol id="podium-list" class="podium-list"></ol>
106 <p class="hint" id="podium-hint">Over 5 seconden teruggaan naar de lobby…</p>
107 </div>
108
41 109 <script src="framework.js"></script>
42 110 <script src="game.js"></script>
43 111 </body>
@@ -12,15 +12,67 @@
12</head>
12</head>
13<body>
13<body>
14 <div id="stars" aria-hidden="true"></div>
14 <div id="stars" aria-hidden="true"></div>
15 <div id="flights" aria-hidden="true"></div>
15
16
16 <div id="menu" class="screen">
17 <div id="menu" class="screen">
17 <h1>Meteors</h1>
18 <h1>Meteors</h1>
18 <p class="tagline">Drie op een rij, en je blokjes krijgen raketmotoren.</p>
19 <p class="tagline">Drie op een rij, en je blokjes krijgen raketmotoren.</p>
19 <button type="button" id="btn-play">Spelen</button>
20 <button type="button" id="btn-play">Spelen</button>
21 <button type="button" id="btn-online" class="btn-secondary">Online spelen</button>
20 <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
22 <p id="last-score" class="last-score" hidden>Laatste score: <strong>0</strong></p>
21 <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>
22 </div>
24 </div>
23
25
26 <div id="online-panel" class="screen" hidden>
27 <h1>Online</h1>
28 <p id="online-status" class="tagline">Even kijken of online spelen beschikbaar is…</p>
29 <p id="online-error" class="error" hidden></p>
30
31 <div id="online-unconfigured" hidden>
32 <p class="notice">Online spelen is nog niet ingesteld. De beheerder moet bij <a href="https://auth.timfalken.com/admin" target="_blank" rel="noopener">auth.timfalken.com/admin</a> het callback-pad <code>/meteors/callback.php</code> toevoegen (zelfde client als de andere sites op dit domein; het geheim <strong>niet</strong> opnieuw genereren) en dat geheim in <code>data/config.php</code> op de server zetten. Zie de README.</p>
33 <p>Je kunt wel alleen spelen.</p>
34 <button type="button" class="btn-secondary" data-back-menu>Terug</button>
35 </div>
36
37 <div id="online-login" hidden>
38 <p>Om online te spelen log je in met je account op auth.timfalken.com.</p>
39 <a id="btn-login" class="button" href="auth.php">Inloggen</a>
40 <button type="button" class="btn-secondary" data-back-menu>Terug</button>
41 <p id="local-login" class="hint" hidden>
42 Lokale test:
43 <a href="auth.php?test=1">test_user_1</a> ·
44 <a href="auth.php?test=2">test_user_2</a>
45 </p>
46 </div>
47
48 <div id="online-home" hidden>
49 <p class="who">Ingelogd als <strong id="me-name"></strong> · <a href="logout.php">Uitloggen</a></p>
50 <button type="button" id="btn-create">Lobby maken</button>
51 <form id="join-form" class="join-form">
52 <label>
53 <span>Lobbycode</span>
54 <input id="join-code" type="text" maxlength="6" autocomplete="off" spellcheck="false" placeholder="ABCD">
55 </label>
56 <button type="submit" id="btn-join">Deelnemen</button>
57 </form>
58 <button type="button" class="btn-secondary" data-back-menu>Terug</button>
59 </div>
60
61 <div id="online-lobby" hidden>
62 <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>
64 <ul id="lobby-players" class="player-list"></ul>
65 <p id="lobby-hint" class="hint"></p>
66 <div class="lobby-actions">
67 <button type="button" id="btn-ready">Gereed</button>
68 <button type="button" id="btn-start" hidden>Starten</button>
69 <button type="button" id="btn-leave-lobby" class="btn-secondary">Verlaten</button>
70 </div>
71 </div>
72 </div>
73
74 <div id="minis" hidden></div>
75
24 <div id="hud" hidden>
76 <div id="hud" hidden>
25 <div class="hud-left">
77 <div class="hud-left">
26 <div class="hud-label">Punten</div>
78 <div class="hud-label">Punten</div>
@@ -38,6 +90,22 @@
38 <p class="go-score">Score: <strong id="go-score">0</strong></p>
90 <p class="go-score">Score: <strong id="go-score">0</strong></p>
39 </div>
91 </div>
40
92
93 <div id="spectator" class="screen overlay" hidden>
94 <h2>Je ligt eruit</h2>
95 <p>Al je kolommen zitten vol. Je kunt toekijken of de wedstrijd verlaten.</p>
96 <div class="lobby-actions">
97 <button type="button" id="btn-spectate">Toekijken</button>
98 <button type="button" id="btn-leave-game" class="btn-secondary">Verlaten</button>
99 </div>
100 </div>
101
102 <div id="podium" class="screen overlay" hidden>
103 <h2>Gewonnen!</h2>
104 <p id="podium-title" class="tagline">De laatste speler staat overeind.</p>
105 <ol id="podium-list" class="podium-list"></ol>
106 <p class="hint" id="podium-hint">Over 5 seconden teruggaan naar de lobby…</p>
107 </div>
108
41 <script src="framework.js"></script>
109 <script src="framework.js"></script>
42 <script src="game.js"></script>
110 <script src="game.js"></script>
43</body>
111</body>
build/style.css +226 −1
@@ -45,7 +45,7 @@ html, body {
45 45 text-align: center;
46 46 }
47 47
48 .screen[hidden], #hud[hidden], #game-over[hidden] { display: none !important; }
48 .screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden] { display: none !important; }
49 49
50 50 h1 {
51 51 font-size: clamp(48px, 14vw, 96px);
@@ -183,3 +183,228 @@ canvas {
183 183 h1 { font-size: 42px; }
184 184 #btn-play { padding: 10px 36px; }
185 185 }
186
187
188 /* ---- Stage 2: online, lobby, miniatures, flights, podium ---- */
189
190 #btn-online, .btn-secondary, a.button {
191 margin-top: 12px;
192 padding: 10px 36px;
193 font-size: clamp(16px, 4vw, 20px);
194 border: 1px solid #6a7394;
195 border-radius: 999px;
196 color: #e8eaf2;
197 background: linear-gradient(180deg, #2a3150, #1b2038);
198 cursor: pointer;
199 text-decoration: none;
200 display: inline-block;
201 font-family: inherit;
202 }
203 #btn-online:is(:hover, :focus-visible),
204 .btn-secondary:is(:hover, :focus-visible),
205 a.button:is(:hover, :focus-visible) {
206 border-color: #ffe27a;
207 color: #fff6c8;
208 }
209 #btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
210 #btn-play {
211 /* play already styled */
212 }
213
214 #btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate {
215 padding: 10px 28px;
216 font-size: clamp(16px, 4vw, 20px);
217 border: 0;
218 border-radius: 999px;
219 color: #1a1020;
220 background: linear-gradient(180deg, #ffe27a, #f0c53a 40%, #e89a20);
221 cursor: pointer;
222 font-weight: 700;
223 font-family: inherit;
224 }
225 #btn-start:disabled, #btn-ready:disabled {
226 opacity: 0.45;
227 cursor: default;
228 }
229
230 #online-panel {
231 z-index: 5;
232 overflow: auto;
233 text-align: center;
234 padding: 32px 16px 48px;
235 }
236 #online-panel .who {
237 color: #c5cae0;
238 margin: 0 0 16px;
239 }
240 #online-panel .notice {
241 max-width: 36em;
242 margin: 0 auto 16px;
243 text-align: left;
244 line-height: 1.45;
245 color: #c5cae0;
246 }
247 #online-panel code {
248 font-size: 0.92em;
249 color: #ffe27a;
250 }
251 #online-panel a { color: #9ec5ff; }
252 .error {
253 color: #ffb0a0;
254 margin: 8px 0;
255 }
256 .notice {
257 background: rgba(20, 24, 48, 0.7);
258 border: 1px solid #3a4268;
259 border-radius: 12px;
260 padding: 14px 16px;
261 }
262 .join-form {
263 display: flex;
264 gap: 8px;
265 justify-content: center;
266 align-items: flex-end;
267 flex-wrap: wrap;
268 margin: 16px 0;
269 }
270 .join-form label {
271 display: flex;
272 flex-direction: column;
273 align-items: flex-start;
274 font-size: 13px;
275 color: #9aa3c2;
276 }
277 .join-form input {
278 font-size: 22px;
279 letter-spacing: 0.2em;
280 text-transform: uppercase;
281 width: 8em;
282 padding: 8px 10px;
283 border-radius: 8px;
284 border: 1px solid #6a7394;
285 background: #141a33;
286 color: #fff6c8;
287 font-family: inherit;
288 text-align: center;
289 }
290 .lobby-code {
291 font-size: clamp(22px, 6vw, 34px);
292 margin: 8px 0 16px;
293 color: #ffe27a;
294 }
295 .btn-tiny {
296 font-size: 13px;
297 padding: 4px 10px;
298 margin-left: 8px;
299 border-radius: 999px;
300 border: 1px solid #6a7394;
301 background: #1b2038;
302 color: #e8eaf2;
303 cursor: pointer;
304 font-family: inherit;
305 letter-spacing: 0;
306 vertical-align: middle;
307 }
308 .player-list {
309 list-style: none;
310 padding: 0;
311 margin: 0 auto 18px;
312 max-width: 22em;
313 text-align: left;
314 }
315 .player-list li {
316 display: flex;
317 justify-content: space-between;
318 padding: 8px 12px;
319 border-bottom: 1px solid #2a3150;
320 color: #e8eaf2;
321 }
322 .player-list .ready { color: #8eec9a; }
323 .player-list .waiting { color: #8e95b3; }
324 .player-list .you { font-weight: 700; }
325 .lobby-actions {
326 display: flex;
327 gap: 10px;
328 justify-content: center;
329 flex-wrap: wrap;
330 margin-top: 12px;
331 }
332
333 #minis {
334 position: fixed;
335 top: 0;
336 left: 0;
337 right: 0;
338 z-index: 4;
339 display: flex;
340 gap: 10px;
341 justify-content: center;
342 align-items: flex-end;
343 flex-wrap: wrap;
344 padding: 6px 8px 0;
345 pointer-events: none;
346 }
347 .mini {
348 text-align: center;
349 color: #c5cae0;
350 font-size: 11px;
351 min-width: 72px;
352 }
353 .mini-name {
354 max-width: 90px;
355 overflow: hidden;
356 text-overflow: ellipsis;
357 white-space: nowrap;
358 font-weight: 700;
359 }
360 .mini-canvas {
361 display: block;
362 width: 80px;
363 height: 104px;
364 background: #0c1020;
365 border: 1px solid #2a3150;
366 border-radius: 4px;
367 image-rendering: pixelated;
368 }
369 .mini.eliminated { opacity: 0.45; }
370 .mini.eliminated .mini-meta { color: #ffb0a0; }
371
372 #flights {
373 position: fixed;
374 inset: 0;
375 z-index: 6;
376 pointer-events: none;
377 overflow: visible;
378 }
379 #flights .flight {
380 position: fixed;
381 top: 0;
382 left: 0;
383 width: 40px;
384 height: 40px;
385 will-change: transform;
386 pointer-events: none;
387 }
388
389 #spectator h2, #podium h2 {
390 color: #ffe27a;
391 }
392 .podium-list {
393 list-style: none;
394 padding: 0;
395 margin: 16px auto;
396 max-width: 16em;
397 font-size: clamp(20px, 5vw, 28px);
398 }
399 .podium-list li {
400 padding: 6px 0;
401 color: #e8eaf2;
402 }
403 .podium-list li:first-child { color: #ffe27a; font-size: 1.2em; font-weight: 700; }
404 .podium-list li:nth-child(2) { color: #d0d6ea; }
405 .podium-list li:nth-child(3) { color: #e0a878; }
406
407 @media (max-height: 520px) {
408 #online-panel .hint, #online-panel .tagline { display: block; }
409 .mini-canvas { width: 56px; height: 73px; }
410 }
@@ -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] { display: none !important; }
48.screen[hidden], #hud[hidden], #game-over[hidden], #online-panel[hidden], #minis[hidden], #spectator[hidden], #podium[hidden], #flights[hidden] { display: none !important; }
49
49
50h1 {
50h1 {
51 font-size: clamp(48px, 14vw, 96px);
51 font-size: clamp(48px, 14vw, 96px);
@@ -183,3 +183,228 @@ canvas {
183 h1 { font-size: 42px; }
183 h1 { font-size: 42px; }
184 #btn-play { padding: 10px 36px; }
184 #btn-play { padding: 10px 36px; }
185}
185}
186
187
188/* ---- Stage 2: online, lobby, miniatures, flights, podium ---- */
189
190#btn-online, .btn-secondary, a.button {
191 margin-top: 12px;
192 padding: 10px 36px;
193 font-size: clamp(16px, 4vw, 20px);
194 border: 1px solid #6a7394;
195 border-radius: 999px;
196 color: #e8eaf2;
197 background: linear-gradient(180deg, #2a3150, #1b2038);
198 cursor: pointer;
199 text-decoration: none;
200 display: inline-block;
201 font-family: inherit;
202}
203#btn-online:is(:hover, :focus-visible),
204.btn-secondary:is(:hover, :focus-visible),
205a.button:is(:hover, :focus-visible) {
206 border-color: #ffe27a;
207 color: #fff6c8;
208}
209#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate,
210#btn-play {
211 /* play already styled */
212}
213
214#btn-create, #btn-join, #btn-ready, #btn-start, #btn-spectate {
215 padding: 10px 28px;
216 font-size: clamp(16px, 4vw, 20px);
217 border: 0;
218 border-radius: 999px;
219 color: #1a1020;
220 background: linear-gradient(180deg, #ffe27a, #f0c53a 40%, #e89a20);
221 cursor: pointer;
222 font-weight: 700;
223 font-family: inherit;
224}
225#btn-start:disabled, #btn-ready:disabled {
226 opacity: 0.45;
227 cursor: default;
228}
229
230#online-panel {
231 z-index: 5;
232 overflow: auto;
233 text-align: center;
234 padding: 32px 16px 48px;
235}
236#online-panel .who {
237 color: #c5cae0;
238 margin: 0 0 16px;
239}
240#online-panel .notice {
241 max-width: 36em;
242 margin: 0 auto 16px;
243 text-align: left;
244 line-height: 1.45;
245 color: #c5cae0;
246}
247#online-panel code {
248 font-size: 0.92em;
249 color: #ffe27a;
250}
251#online-panel a { color: #9ec5ff; }
252.error {
253 color: #ffb0a0;
254 margin: 8px 0;
255}
256.notice {
257 background: rgba(20, 24, 48, 0.7);
258 border: 1px solid #3a4268;
259 border-radius: 12px;
260 padding: 14px 16px;
261}
262.join-form {
263 display: flex;
264 gap: 8px;
265 justify-content: center;
266 align-items: flex-end;
267 flex-wrap: wrap;
268 margin: 16px 0;
269}
270.join-form label {
271 display: flex;
272 flex-direction: column;
273 align-items: flex-start;
274 font-size: 13px;
275 color: #9aa3c2;
276}
277.join-form input {
278 font-size: 22px;
279 letter-spacing: 0.2em;
280 text-transform: uppercase;
281 width: 8em;
282 padding: 8px 10px;
283 border-radius: 8px;
284 border: 1px solid #6a7394;
285 background: #141a33;
286 color: #fff6c8;
287 font-family: inherit;
288 text-align: center;
289}
290.lobby-code {
291 font-size: clamp(22px, 6vw, 34px);
292 margin: 8px 0 16px;
293 color: #ffe27a;
294}
295.btn-tiny {
296 font-size: 13px;
297 padding: 4px 10px;
298 margin-left: 8px;
299 border-radius: 999px;
300 border: 1px solid #6a7394;
301 background: #1b2038;
302 color: #e8eaf2;
303 cursor: pointer;
304 font-family: inherit;
305 letter-spacing: 0;
306 vertical-align: middle;
307}
308.player-list {
309 list-style: none;
310 padding: 0;
311 margin: 0 auto 18px;
312 max-width: 22em;
313 text-align: left;
314}
315.player-list li {
316 display: flex;
317 justify-content: space-between;
318 padding: 8px 12px;
319 border-bottom: 1px solid #2a3150;
320 color: #e8eaf2;
321}
322.player-list .ready { color: #8eec9a; }
323.player-list .waiting { color: #8e95b3; }
324.player-list .you { font-weight: 700; }
325.lobby-actions {
326 display: flex;
327 gap: 10px;
328 justify-content: center;
329 flex-wrap: wrap;
330 margin-top: 12px;
331}
332
333#minis {
334 position: fixed;
335 top: 0;
336 left: 0;
337 right: 0;
338 z-index: 4;
339 display: flex;
340 gap: 10px;
341 justify-content: center;
342 align-items: flex-end;
343 flex-wrap: wrap;
344 padding: 6px 8px 0;
345 pointer-events: none;
346}
347.mini {
348 text-align: center;
349 color: #c5cae0;
350 font-size: 11px;
351 min-width: 72px;
352}
353.mini-name {
354 max-width: 90px;
355 overflow: hidden;
356 text-overflow: ellipsis;
357 white-space: nowrap;
358 font-weight: 700;
359}
360.mini-canvas {
361 display: block;
362 width: 80px;
363 height: 104px;
364 background: #0c1020;
365 border: 1px solid #2a3150;
366 border-radius: 4px;
367 image-rendering: pixelated;
368}
369.mini.eliminated { opacity: 0.45; }
370.mini.eliminated .mini-meta { color: #ffb0a0; }
371
372#flights {
373 position: fixed;
374 inset: 0;
375 z-index: 6;
376 pointer-events: none;
377 overflow: visible;
378}
379#flights .flight {
380 position: fixed;
381 top: 0;
382 left: 0;
383 width: 40px;
384 height: 40px;
385 will-change: transform;
386 pointer-events: none;
387}
388
389#spectator h2, #podium h2 {
390 color: #ffe27a;
391}
392.podium-list {
393 list-style: none;
394 padding: 0;
395 margin: 16px auto;
396 max-width: 16em;
397 font-size: clamp(20px, 5vw, 28px);
398}
399.podium-list li {
400 padding: 6px 0;
401 color: #e8eaf2;
402}
403.podium-list li:first-child { color: #ffe27a; font-size: 1.2em; font-weight: 700; }
404.podium-list li:nth-child(2) { color: #d0d6ea; }
405.podium-list li:nth-child(3) { color: #e0a878; }
406
407@media (max-height: 520px) {
408 #online-panel .hint, #online-panel .tagline { display: block; }
409 .mini-canvas { width: 56px; height: 73px; }
410}
ci/deploy.py +10 −0
@@ -21,6 +21,8 @@ ROOT = Path(__file__).resolve().parents[1]
21 21 # log; foreign names no longer abort the deploy (we never --delete).
22 22 OURS = {
23 23 'index.html', 'game.js', 'framework.js', 'style.css', 'images',
24 'api.php', 'auth.php', 'callback.php', 'logout.php', '.htaccess',
25 'lib', 'data', 'router.php',
24 26 '.', '..',
25 27 }
26 28
@@ -148,11 +150,19 @@ def deploy_commands(environ, target, webroot):
148 150 f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
149 151 f'cd {quoted(target)}',
150 152 # GEEN --delete. Never upload favicon.ico (leave Tim's / the host's).
153 # Never mirror data/: that folder holds Tim's config.php and the
154 # sqlite database. We only ensure data/.htaccess afterwards.
151 155 'mirror --reverse --no-perms --no-symlinks --max-errors=1 '
152 156 '--exclude-glob ".git/" --exclude-glob ".git/**" '
153 157 '--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '
154 158 '--exclude-glob "favicon.ico" --exclude-glob "**/favicon.ico" '
159 '--exclude-glob "router.php" '
160 '--exclude-glob "data/" --exclude-glob "data/**" '
161 '--exclude-glob "**/config.php" --exclude-glob "**/*.sqlite" '
155 162 f'{quoted(str(webroot))} .',
163 # Ensure the deny-all htaccess exists; do not touch any other data file.
164 'mkdir -p data || echo "data exists"',
165 f'put {quoted(str(webroot / "data" / ".htaccess"))} -o data/.htaccess',
156 166 'bye',
157 167 ]
158 168
@@ -21,6 +21,8 @@ ROOT = Path(__file__).resolve().parents[1]
21# log; foreign names no longer abort the deploy (we never --delete).
21# log; foreign names no longer abort the deploy (we never --delete).
22OURS = {
22OURS = {
23 'index.html', 'game.js', 'framework.js', 'style.css', 'images',
23 'index.html', 'game.js', 'framework.js', 'style.css', 'images',
24 'api.php', 'auth.php', 'callback.php', 'logout.php', '.htaccess',
25 'lib', 'data', 'router.php',
24 '.', '..',
26 '.', '..',
25}
27}
26
28
@@ -148,11 +150,19 @@ def deploy_commands(environ, target, webroot):
148 f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
150 f'mkdir -p {quoted(target)} || echo "Using existing project directory"',
149 f'cd {quoted(target)}',
151 f'cd {quoted(target)}',
150 # GEEN --delete. Never upload favicon.ico (leave Tim's / the host's).
152 # GEEN --delete. Never upload favicon.ico (leave Tim's / the host's).
153 # Never mirror data/: that folder holds Tim's config.php and the
154 # sqlite database. We only ensure data/.htaccess afterwards.
151 'mirror --reverse --no-perms --no-symlinks --max-errors=1 '
155 'mirror --reverse --no-perms --no-symlinks --max-errors=1 '
152 '--exclude-glob ".git/" --exclude-glob ".git/**" '
156 '--exclude-glob ".git/" --exclude-glob ".git/**" '
153 '--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '
157 '--exclude-glob "blue-ci-cd.yml" --exclude-glob "README.md" '
154 '--exclude-glob "favicon.ico" --exclude-glob "**/favicon.ico" '
158 '--exclude-glob "favicon.ico" --exclude-glob "**/favicon.ico" '
159 '--exclude-glob "router.php" '
160 '--exclude-glob "data/" --exclude-glob "data/**" '
161 '--exclude-glob "**/config.php" --exclude-glob "**/*.sqlite" '
155 f'{quoted(str(webroot))} .',
162 f'{quoted(str(webroot))} .',
163 # Ensure the deny-all htaccess exists; do not touch any other data file.
164 'mkdir -p data || echo "data exists"',
165 f'put {quoted(str(webroot / "data" / ".htaccess"))} -o data/.htaccess',
156 'bye',
166 'bye',
157 ]
167 ]
158
168
docs/ASSUMPTIONS.md +44 −0
@@ -198,3 +198,47 @@ Aanname:
198 198 - `touch-action: none` op canvas en pagina, `preventDefault` op
199 199 pointer-events met `{ passive: false }`, `setPointerCapture`,
200 200 en window-listeners voor move/up (zoals al bij t1100).
201
202 ## Fase 2 — multiplayer
203
204 ### Polling en autorisatie
205
206 - De client pollt elke **0,75 s** (`Online.POLL_MS`). Dat valt in de gevraagde
207 0,5–1 s. Er is geen websocket.
208 - Login via auth.timfalken.com (`/oauth/authorize`, `/oauth/token`, `/api/me`),
209 client_id `projects.timfalken.com`. Callback
210 `https://projects.timfalken.com/meteors/callback.php`. Het geheim zet Tim
211 zelf in `data/config.php`; wij genereren het nooit opnieuw. Zonder geheim
212 blijft solo werken, met een duidelijke online-melding.
213 - Testers `auth.php?test=1` / `?test=2` alleen als `localDev()` waar is:
214 loopback-host **én** loopback-remote-adres (zelfde regel als verhalenboek).
215 - Sessies staan in `data/sessions`, cookie-pad is de map van het script
216 (`/meteors/` live). CSRF-token op elke POST (`X-CSRF-Token`).
217
218 ### Lobby en wedstrijd
219
220 - Onbeperkt in de zin van de regel; praktisch maximum **32** (`METEORS_MAX_PLAYERS`).
221 - De host start alleen als iedereen gereed is en er minstens twee spelers zijn.
222 - Eigen veld is het hoofdspel; miniaturen van anderen staan in een strook
223 boven het veld (onder de HUD).
224 - Afgeschoten blokjes gaan als `outgoingShots` mee in de volgende poll. De
225 **server** kiest het doel en gooit de miss-kans (niet de client, zodat die
226 niet kan valsspelen). Doel is een willekeurige andere speler die nog niet
227 is uitgeschakeld.
228 - `missChance` is een **parameter**, standaard **0,30**, op de lobby én op
229 `GameCore`. `Planet.missChance` (Power, 60 %–5 %) blijft voor stage 3 en
230 wordt hier niet gebruikt.
231 - Een raak schot komt na `flight_duration = 1,2 s` bij de ontvanger aan als
232 vallend donkergrijs vuil (`ingestGarbage`), dat na de gewone 3 s settle
233 een willekeurige kleur krijgt.
234 - De vlucht-tween is een kwadratische Bézier, met semi-willekeurige rotatie
235 (tot ±720°) en krimpen (“de verte in”). Een miss vliegt het scherm af en
236 vervaagt; een raak schot landt in de miniatuur van het doel.
237 - Uitgeschakelde spelers zijn toeschouwer (geen doelwit, geen shots). De
238 laatste die overblijft is 1e; de eerder uitgeschakelden 2e, 3e, … Het
239 podium blijft **5 seconden** (`METEORS_PODIUM_SECONDS`) en daarna gaat de
240 lobby terug naar `waiting` (ready-vlaggen gereset).
241 - `data/` (config, sqlite, sessies) wordt nooit gedeployed of gewist. Alleen
242 `data/.htaccess` (Require all denied) wordt na de mirror gezet.
243 `favicon.ico` blijft ongemoeid. `router.php` is alleen voor lokale `php -S`
244 en gaat niet mee naar live.
@@ -198,3 +198,47 @@ Aanname:
198- `touch-action: none` op canvas en pagina, `preventDefault` op
198- `touch-action: none` op canvas en pagina, `preventDefault` op
199 pointer-events met `{ passive: false }`, `setPointerCapture`,
199 pointer-events met `{ passive: false }`, `setPointerCapture`,
200 en window-listeners voor move/up (zoals al bij t1100).
200 en window-listeners voor move/up (zoals al bij t1100).
201
202## Fase 2 — multiplayer
203
204### Polling en autorisatie
205
206- De client pollt elke **0,75 s** (`Online.POLL_MS`). Dat valt in de gevraagde
207 0,5–1 s. Er is geen websocket.
208- Login via auth.timfalken.com (`/oauth/authorize`, `/oauth/token`, `/api/me`),
209 client_id `projects.timfalken.com`. Callback
210 `https://projects.timfalken.com/meteors/callback.php`. Het geheim zet Tim
211 zelf in `data/config.php`; wij genereren het nooit opnieuw. Zonder geheim
212 blijft solo werken, met een duidelijke online-melding.
213- Testers `auth.php?test=1` / `?test=2` alleen als `localDev()` waar is:
214 loopback-host **én** loopback-remote-adres (zelfde regel als verhalenboek).
215- Sessies staan in `data/sessions`, cookie-pad is de map van het script
216 (`/meteors/` live). CSRF-token op elke POST (`X-CSRF-Token`).
217
218### Lobby en wedstrijd
219
220- Onbeperkt in de zin van de regel; praktisch maximum **32** (`METEORS_MAX_PLAYERS`).
221- De host start alleen als iedereen gereed is en er minstens twee spelers zijn.
222- Eigen veld is het hoofdspel; miniaturen van anderen staan in een strook
223 boven het veld (onder de HUD).
224- Afgeschoten blokjes gaan als `outgoingShots` mee in de volgende poll. De
225 **server** kiest het doel en gooit de miss-kans (niet de client, zodat die
226 niet kan valsspelen). Doel is een willekeurige andere speler die nog niet
227 is uitgeschakeld.
228- `missChance` is een **parameter**, standaard **0,30**, op de lobby én op
229 `GameCore`. `Planet.missChance` (Power, 60 %–5 %) blijft voor stage 3 en
230 wordt hier niet gebruikt.
231- Een raak schot komt na `flight_duration = 1,2 s` bij de ontvanger aan als
232 vallend donkergrijs vuil (`ingestGarbage`), dat na de gewone 3 s settle
233 een willekeurige kleur krijgt.
234- De vlucht-tween is een kwadratische Bézier, met semi-willekeurige rotatie
235 (tot ±720°) en krimpen (“de verte in”). Een miss vliegt het scherm af en
236 vervaagt; een raak schot landt in de miniatuur van het doel.
237- Uitgeschakelde spelers zijn toeschouwer (geen doelwit, geen shots). De
238 laatste die overblijft is 1e; de eerder uitgeschakelden 2e, 3e, … Het
239 podium blijft **5 seconden** (`METEORS_PODIUM_SECONDS`) en daarna gaat de
240 lobby terug naar `waiting` (ready-vlaggen gereset).
241- `data/` (config, sqlite, sessies) wordt nooit gedeployed of gewist. Alleen
242 `data/.htaccess` (Require all denied) wordt na de mirror gezet.
243 `favicon.ico` blijft ongemoeid. `router.php` is alleen voor lokale `php -S`
244 en gaat niet mee naar live.
server/.htaccess added +18 −0
@@ -0,0 +1,18 @@
1 Options -Indexes
2 DirectoryIndex index.html index.php
3
4 <FilesMatch "^(router\.php|README\.md)$">
5 Require all denied
6 </FilesMatch>
7
8 <IfModule mod_headers.c>
9 Header always set X-Content-Type-Options "nosniff"
10 Header always set Referrer-Policy "same-origin"
11 </IfModule>
12
13 # PHP endpoints should not be cached.
14 <IfModule mod_headers.c>
15 <FilesMatch "\.(php)$">
16 Header set Cache-Control "no-store"
17 </FilesMatch>
18 </IfModule>
@@ -0,0 +1,18 @@
1Options -Indexes
2DirectoryIndex index.html index.php
3
4<FilesMatch "^(router\.php|README\.md)$">
5 Require all denied
6</FilesMatch>
7
8<IfModule mod_headers.c>
9 Header always set X-Content-Type-Options "nosniff"
10 Header always set Referrer-Policy "same-origin"
11</IfModule>
12
13# PHP endpoints should not be cached.
14<IfModule mod_headers.c>
15 <FilesMatch "\.(php)$">
16 Header set Cache-Control "no-store"
17 </FilesMatch>
18</IfModule>
server/api.php added +108 −0
@@ -0,0 +1,108 @@
1 <?php
2 declare(strict_types=1);
3 require __DIR__ . '/lib/bootstrap.php';
4 require __DIR__ . '/lib/Store.php';
5
6 $action = $_GET['action'] ?? $_POST['action'] ?? '';
7 if ($action === '') {
8 $body = readJsonBody();
9 $action = (string) ($body['action'] ?? '');
10 } else {
11 $body = readJsonBody();
12 }
13
14 try {
15 $configured = authConfigured();
16 $local = localDev();
17 $user = currentUser();
18
19 if ($action === 'me' || $action === '') {
20 $view = ['lobby' => null, 'incoming' => [], 'shot_results' => []];
21 if ($user) {
22 $view = Store::open()->viewFor($user['id']);
23 }
24 jsonOut([
25 'ok' => true,
26 'configured' => $configured,
27 'local' => $local,
28 'csrf' => csrfToken(),
29 'me' => $user,
30 'lobby' => $view['lobby'],
31 'incoming' => $view['incoming'],
32 'shot_results' => $view['shot_results'],
33 'miss_chance_default' => METEORS_DEFAULT_MISS,
34 'flight_duration' => METEORS_FLIGHT_DURATION,
35 'login_url' => 'auth.php',
36 'logout_url' => 'logout.php',
37 ]);
38 }
39
40 if ($action === 'test_login') {
41 if (!localDev()) {
42 jsonFail('Niet beschikbaar.', 403);
43 }
44 requireCsrf();
45 $who = (string) ($body['user'] ?? $_GET['user'] ?? '');
46 if (!in_array($who, ['test_user_1', 'test_user_2'], true)) {
47 jsonFail('Onbekende testgebruiker.');
48 }
49 loginUser('local:' . $who, $who);
50 jsonOut(['ok' => true, 'me' => currentUser(), 'csrf' => csrfToken()]);
51 }
52
53 if (!$user && $action !== 'me') {
54 jsonFail('Log in om verder te gaan.', 401);
55 }
56
57 requireCsrf();
58 $store = Store::open();
59 $userId = $user['id'];
60 $name = $user['name'];
61
62 switch ($action) {
63 case 'lobby_create':
64 $miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;
65 $lobby = $store->createLobby($userId, $name, $miss);
66 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
67
68 case 'lobby_join':
69 $code = (string) ($body['code'] ?? '');
70 $lobby = $store->joinLobby($userId, $name, $code);
71 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
72
73 case 'lobby_leave':
74 $store->leaveLobby($userId);
75 jsonOut(['ok' => true, 'lobby' => null, 'csrf' => csrfToken()]);
76
77 case 'lobby_ready':
78 $ready = (bool) ($body['ready'] ?? true);
79 $lobby = $store->setReady($userId, $ready);
80 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
81
82 case 'lobby_start':
83 $lobby = $store->startGame($userId);
84 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
85
86 case 'poll':
87 $snapshot = isset($body['snapshot']) && is_array($body['snapshot']) ? $body['snapshot'] : null;
88 $score = isset($body['score']) ? (int) $body['score'] : null;
89 $eliminated = !empty($body['eliminated']);
90 $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
91 $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
92 jsonOut([
93 'ok' => true,
94 'csrf' => csrfToken(),
95 'me' => $user,
96 'lobby' => $view['lobby'],
97 'incoming' => $view['incoming'],
98 'shot_results' => $view['shot_results'],
99 ]);
100
101 default:
102 jsonFail('Onbekende actie.', 404);
103 }
104 } catch (RuntimeException $e) {
105 jsonFail($e->getMessage(), 400);
106 } catch (Throwable $e) {
107 jsonFail('Interne fout.', 500);
108 }
@@ -0,0 +1,108 @@
1<?php
2declare(strict_types=1);
3require __DIR__ . '/lib/bootstrap.php';
4require __DIR__ . '/lib/Store.php';
5
6$action = $_GET['action'] ?? $_POST['action'] ?? '';
7if ($action === '') {
8 $body = readJsonBody();
9 $action = (string) ($body['action'] ?? '');
10} else {
11 $body = readJsonBody();
12}
13
14try {
15 $configured = authConfigured();
16 $local = localDev();
17 $user = currentUser();
18
19 if ($action === 'me' || $action === '') {
20 $view = ['lobby' => null, 'incoming' => [], 'shot_results' => []];
21 if ($user) {
22 $view = Store::open()->viewFor($user['id']);
23 }
24 jsonOut([
25 'ok' => true,
26 'configured' => $configured,
27 'local' => $local,
28 'csrf' => csrfToken(),
29 'me' => $user,
30 'lobby' => $view['lobby'],
31 'incoming' => $view['incoming'],
32 'shot_results' => $view['shot_results'],
33 'miss_chance_default' => METEORS_DEFAULT_MISS,
34 'flight_duration' => METEORS_FLIGHT_DURATION,
35 'login_url' => 'auth.php',
36 'logout_url' => 'logout.php',
37 ]);
38 }
39
40 if ($action === 'test_login') {
41 if (!localDev()) {
42 jsonFail('Niet beschikbaar.', 403);
43 }
44 requireCsrf();
45 $who = (string) ($body['user'] ?? $_GET['user'] ?? '');
46 if (!in_array($who, ['test_user_1', 'test_user_2'], true)) {
47 jsonFail('Onbekende testgebruiker.');
48 }
49 loginUser('local:' . $who, $who);
50 jsonOut(['ok' => true, 'me' => currentUser(), 'csrf' => csrfToken()]);
51 }
52
53 if (!$user && $action !== 'me') {
54 jsonFail('Log in om verder te gaan.', 401);
55 }
56
57 requireCsrf();
58 $store = Store::open();
59 $userId = $user['id'];
60 $name = $user['name'];
61
62 switch ($action) {
63 case 'lobby_create':
64 $miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;
65 $lobby = $store->createLobby($userId, $name, $miss);
66 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
67
68 case 'lobby_join':
69 $code = (string) ($body['code'] ?? '');
70 $lobby = $store->joinLobby($userId, $name, $code);
71 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
72
73 case 'lobby_leave':
74 $store->leaveLobby($userId);
75 jsonOut(['ok' => true, 'lobby' => null, 'csrf' => csrfToken()]);
76
77 case 'lobby_ready':
78 $ready = (bool) ($body['ready'] ?? true);
79 $lobby = $store->setReady($userId, $ready);
80 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
81
82 case 'lobby_start':
83 $lobby = $store->startGame($userId);
84 jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
85
86 case 'poll':
87 $snapshot = isset($body['snapshot']) && is_array($body['snapshot']) ? $body['snapshot'] : null;
88 $score = isset($body['score']) ? (int) $body['score'] : null;
89 $eliminated = !empty($body['eliminated']);
90 $outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
91 $view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
92 jsonOut([
93 'ok' => true,
94 'csrf' => csrfToken(),
95 'me' => $user,
96 'lobby' => $view['lobby'],
97 'incoming' => $view['incoming'],
98 'shot_results' => $view['shot_results'],
99 ]);
100
101 default:
102 jsonFail('Onbekende actie.', 404);
103 }
104} catch (RuntimeException $e) {
105 jsonFail($e->getMessage(), 400);
106} catch (Throwable $e) {
107 jsonFail('Interne fout.', 500);
108}
server/auth.php added +32 −0
@@ -0,0 +1,32 @@
1 <?php
2 declare(strict_types=1);
3 require __DIR__ . '/lib/bootstrap.php';
4
5 try {
6 if (localDev() && isset($_GET['test'])) {
7 $who = $_GET['test'] === '2' ? 'test_user_2' : 'test_user_1';
8 loginUser('local:' . $who, $who);
9 $next = isset($_GET['next']) && is_string($_GET['next']) ? $_GET['next'] : 'index.html';
10 header('Location: ' . $next);
11 exit;
12 }
13 if (!authConfigured()) {
14 header('Location: index.html?auth=unconfigured');
15 exit;
16 }
17 $cfg = config();
18 $_SESSION['oauth_state'] = bin2hex(random_bytes(32));
19 $_SESSION['oauth_started'] = time();
20 header('Location: ' . authUrl() . '/oauth/authorize?' . http_build_query([
21 'client_id' => $cfg['client_id'],
22 'redirect_uri' => baseUrl() . '/callback.php',
23 'response_type' => 'code',
24 'state' => $_SESSION['oauth_state'],
25 ]));
26 } catch (Throwable $e) {
27 http_response_code(503);
28 header('Content-Type: text/html; charset=utf-8');
29 echo '<!DOCTYPE html><meta charset="utf-8"><title>Meteors</title>';
30 echo '<p>Inloggen is nu niet mogelijk. ' . htmlspecialchars($e->getMessage()) . '</p>';
31 echo '<p><a href="index.html">Terug naar het spel</a></p>';
32 }
@@ -0,0 +1,32 @@
1<?php
2declare(strict_types=1);
3require __DIR__ . '/lib/bootstrap.php';
4
5try {
6 if (localDev() && isset($_GET['test'])) {
7 $who = $_GET['test'] === '2' ? 'test_user_2' : 'test_user_1';
8 loginUser('local:' . $who, $who);
9 $next = isset($_GET['next']) && is_string($_GET['next']) ? $_GET['next'] : 'index.html';
10 header('Location: ' . $next);
11 exit;
12 }
13 if (!authConfigured()) {
14 header('Location: index.html?auth=unconfigured');
15 exit;
16 }
17 $cfg = config();
18 $_SESSION['oauth_state'] = bin2hex(random_bytes(32));
19 $_SESSION['oauth_started'] = time();
20 header('Location: ' . authUrl() . '/oauth/authorize?' . http_build_query([
21 'client_id' => $cfg['client_id'],
22 'redirect_uri' => baseUrl() . '/callback.php',
23 'response_type' => 'code',
24 'state' => $_SESSION['oauth_state'],
25 ]));
26} catch (Throwable $e) {
27 http_response_code(503);
28 header('Content-Type: text/html; charset=utf-8');
29 echo '<!DOCTYPE html><meta charset="utf-8"><title>Meteors</title>';
30 echo '<p>Inloggen is nu niet mogelijk. ' . htmlspecialchars($e->getMessage()) . '</p>';
31 echo '<p><a href="index.html">Terug naar het spel</a></p>';
32}
server/callback.php added +43 −0
@@ -0,0 +1,43 @@
1 <?php
2 declare(strict_types=1);
3 require __DIR__ . '/lib/bootstrap.php';
4
5 try {
6 $state = $_GET['state'] ?? null;
7 if (!is_string($state) || !isset($_SESSION['oauth_state'])
8 || !hash_equals((string) $_SESSION['oauth_state'], $state)
9 || time() - (int) ($_SESSION['oauth_started'] ?? 0) > 600) {
10 throw new RuntimeException('Ongeldige of verlopen login.');
11 }
12 unset($_SESSION['oauth_state'], $_SESSION['oauth_started']);
13 $code = $_GET['code'] ?? null;
14 if (!is_string($code) || $code === '') {
15 throw new RuntimeException('De login is niet afgerond.');
16 }
17 $cfg = config();
18 $token = authRequest('/oauth/token', [
19 'grant_type' => 'authorization_code',
20 'code' => $code,
21 'client_id' => $cfg['client_id'],
22 'client_secret' => $cfg['client_secret'],
23 'redirect_uri' => baseUrl() . '/callback.php',
24 ]);
25 if (!isset($token['access_token'], $token['expires_in']) || !is_string($token['access_token'])) {
26 throw new RuntimeException('Geen toegangstoken ontvangen.');
27 }
28 $me = authRequest('/api/me', null, $token['access_token']);
29 if (!isset($me['user']) || !is_array($me['user'])) {
30 throw new RuntimeException('Het profiel ontbreekt.');
31 }
32 [$id, $name] = authIdentity($me['user']);
33 loginUser($id, $name);
34 $_SESSION['token'] = $token['access_token'];
35 $_SESSION['expires'] = time() + (int) $token['expires_in'];
36 header('Location: ' . baseUrl() . '/index.html?online=1');
37 } catch (Throwable $e) {
38 http_response_code(401);
39 header('Content-Type: text/html; charset=utf-8');
40 echo '<!DOCTYPE html><meta charset="utf-8"><title>Meteors</title>';
41 echo 'Inloggen is mislukt. ' . htmlspecialchars($e->getMessage());
42 echo ' <a href="auth.php">Opnieuw proberen</a> · <a href="index.html">Terug</a>';
43 }
@@ -0,0 +1,43 @@
1<?php
2declare(strict_types=1);
3require __DIR__ . '/lib/bootstrap.php';
4
5try {
6 $state = $_GET['state'] ?? null;
7 if (!is_string($state) || !isset($_SESSION['oauth_state'])
8 || !hash_equals((string) $_SESSION['oauth_state'], $state)
9 || time() - (int) ($_SESSION['oauth_started'] ?? 0) > 600) {
10 throw new RuntimeException('Ongeldige of verlopen login.');
11 }
12 unset($_SESSION['oauth_state'], $_SESSION['oauth_started']);
13 $code = $_GET['code'] ?? null;
14 if (!is_string($code) || $code === '') {
15 throw new RuntimeException('De login is niet afgerond.');
16 }
17 $cfg = config();
18 $token = authRequest('/oauth/token', [
19 'grant_type' => 'authorization_code',
20 'code' => $code,
21 'client_id' => $cfg['client_id'],
22 'client_secret' => $cfg['client_secret'],
23 'redirect_uri' => baseUrl() . '/callback.php',
24 ]);
25 if (!isset($token['access_token'], $token['expires_in']) || !is_string($token['access_token'])) {
26 throw new RuntimeException('Geen toegangstoken ontvangen.');
27 }
28 $me = authRequest('/api/me', null, $token['access_token']);
29 if (!isset($me['user']) || !is_array($me['user'])) {
30 throw new RuntimeException('Het profiel ontbreekt.');
31 }
32 [$id, $name] = authIdentity($me['user']);
33 loginUser($id, $name);
34 $_SESSION['token'] = $token['access_token'];
35 $_SESSION['expires'] = time() + (int) $token['expires_in'];
36 header('Location: ' . baseUrl() . '/index.html?online=1');
37} catch (Throwable $e) {
38 http_response_code(401);
39 header('Content-Type: text/html; charset=utf-8');
40 echo '<!DOCTYPE html><meta charset="utf-8"><title>Meteors</title>';
41 echo 'Inloggen is mislukt. ' . htmlspecialchars($e->getMessage());
42 echo ' <a href="auth.php">Opnieuw proberen</a> · <a href="index.html">Terug</a>';
43}
server/data/.gitignore added +3 −0
@@ -0,0 +1,3 @@
1 *
2 !.htaccess
3 !.gitignore
@@ -0,0 +1,3 @@
1*
2!.htaccess
3!.gitignore
server/data/.htaccess added +2 −0
@@ -0,0 +1,2 @@
1 # The data directory is never served. This file is also written on first run.
2 Require all denied
@@ -0,0 +1,2 @@
1# The data directory is never served. This file is also written on first run.
2Require all denied
server/lib/Store.php added +616 −0
@@ -0,0 +1,616 @@
1 <?php
2 declare(strict_types=1);
3
4 final class Store
5 {
6 private PDO $pdo;
7 private int $txDepth = 0;
8
9 public function __construct(PDO $pdo)
10 {
11 $this->pdo = $pdo;
12 $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
13 $this->migrate();
14 }
15
16 public static function open(?string $dir = null): self
17 {
18 $dir = $dir ?? dataDir();
19 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
20 throw new RuntimeException('De datamap moet schrijfbaar zijn.');
21 }
22 $path = $dir . '/meteors.sqlite';
23 $pdo = new PDO('sqlite:' . $path, null, null, [
24 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
25 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
26 ]);
27 $pdo->exec('PRAGMA journal_mode = WAL');
28 $pdo->exec('PRAGMA foreign_keys = ON');
29 $pdo->exec('PRAGMA busy_timeout = 4000');
30 return new self($pdo);
31 }
32
33 private function migrate(): void
34 {
35 $this->pdo->exec(<<<'SQL'
36 CREATE TABLE IF NOT EXISTS lobbies (
37 id TEXT PRIMARY KEY,
38 code TEXT UNIQUE NOT NULL,
39 host_id TEXT NOT NULL,
40 status TEXT NOT NULL DEFAULT 'waiting',
41 miss_chance REAL NOT NULL DEFAULT 0.30,
42 flight_duration REAL NOT NULL DEFAULT 1.2,
43 created INTEGER NOT NULL,
44 started INTEGER,
45 finished INTEGER
46 );
47 CREATE TABLE IF NOT EXISTS members (
48 lobby_id TEXT NOT NULL,
49 user_id TEXT NOT NULL,
50 name TEXT NOT NULL,
51 ready INTEGER NOT NULL DEFAULT 0,
52 eliminated INTEGER NOT NULL DEFAULT 0,
53 place INTEGER,
54 left_at INTEGER,
55 joined INTEGER NOT NULL,
56 last_seen INTEGER NOT NULL,
57 score INTEGER NOT NULL DEFAULT 0,
58 snapshot TEXT,
59 PRIMARY KEY (lobby_id, user_id)
60 );
61 CREATE TABLE IF NOT EXISTS shots (
62 id INTEGER PRIMARY KEY AUTOINCREMENT,
63 lobby_id TEXT NOT NULL,
64 from_user TEXT NOT NULL,
65 to_user TEXT,
66 color INTEGER NOT NULL,
67 client_id TEXT,
68 created REAL NOT NULL,
69 deliver_at REAL NOT NULL,
70 delivered INTEGER NOT NULL DEFAULT 0
71 );
72 CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
73 SQL);
74 }
75
76 public function transaction(callable $fn): mixed
77 {
78 if ($this->txDepth > 0) {
79 return $fn();
80 }
81 $this->pdo->beginTransaction();
82 $this->txDepth++;
83 try {
84 $result = $fn();
85 $this->pdo->commit();
86 $this->txDepth--;
87 return $result;
88 } catch (Throwable $e) {
89 $this->txDepth--;
90 if ($this->pdo->inTransaction()) {
91 $this->pdo->rollBack();
92 }
93 throw $e;
94 }
95 }
96
97 private function now(): int
98 {
99 return time();
100 }
101
102 private function nowf(): float
103 {
104 return microtime(true);
105 }
106
107 private function newId(): string
108 {
109 return bin2hex(random_bytes(12));
110 }
111
112 private function newCode(): string
113 {
114 $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
115 $len = strlen($alphabet);
116 for ($attempt = 0; $attempt < 16; $attempt++) {
117 $code = '';
118 for ($i = 0; $i < 4; $i++) {
119 $code .= $alphabet[random_int(0, $len - 1)];
120 }
121 $exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?');
122 $exists->execute([$code]);
123 if (!$exists->fetch()) {
124 return $code;
125 }
126 }
127 throw new RuntimeException('Kon geen unieke lobbycode maken.');
128 }
129
130 public function lobbyForUser(string $userId): ?array
131 {
132 $stmt = $this->pdo->prepare(
133 'SELECT l.* FROM lobbies l
134 JOIN members m ON m.lobby_id = l.id
135 WHERE m.user_id = ? AND m.left_at IS NULL
136 ORDER BY l.created DESC LIMIT 1'
137 );
138 $stmt->execute([$userId]);
139 $row = $stmt->fetch();
140 return $row ?: null;
141 }
142
143 public function getLobby(string $id): ?array
144 {
145 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?');
146 $stmt->execute([$id]);
147 $row = $stmt->fetch();
148 return $row ?: null;
149 }
150
151 public function getLobbyByCode(string $code): ?array
152 {
153 $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? '');
154 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?');
155 $stmt->execute([$code]);
156 $row = $stmt->fetch();
157 return $row ?: null;
158 }
159
160 /** @return list<array> */
161 public function members(string $lobbyId, bool $includeLeft = false): array
162 {
163 $sql = 'SELECT * FROM members WHERE lobby_id = ?';
164 if (!$includeLeft) {
165 $sql .= ' AND left_at IS NULL';
166 }
167 $sql .= ' ORDER BY joined ASC';
168 $stmt = $this->pdo->prepare($sql);
169 $stmt->execute([$lobbyId]);
170 return $stmt->fetchAll();
171 }
172
173 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS): array
174 {
175 return $this->transaction(function () use ($userId, $name, $missChance) {
176 $existing = $this->lobbyForUser($userId);
177 if ($existing && $existing['status'] !== 'finished') {
178 throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
179 }
180 if ($existing && $existing['status'] === 'finished') {
181 $this->leaveMember($existing['id'], $userId);
182 }
183 $id = $this->newId();
184 $code = $this->newCode();
185 $now = $this->now();
186 $miss = max(0.0, min(1.0, $missChance));
187 $this->pdo->prepare(
188 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
189 VALUES (?,?,?,?,?,?,?)'
190 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
191 $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]);
195 return $this->getLobby($id);
196 });
197 }
198
199 public function joinLobby(string $userId, string $name, string $code): array
200 {
201 return $this->transaction(function () use ($userId, $name, $code) {
202 $existing = $this->lobbyForUser($userId);
203 if ($existing && $existing['status'] !== 'finished') {
204 if (strcasecmp($existing['code'], $code) === 0) {
205 return $existing;
206 }
207 throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.');
208 }
209 $lobby = $this->getLobbyByCode($code);
210 if (!$lobby) {
211 throw new RuntimeException('Onbekende lobbycode.');
212 }
213 if ($lobby['status'] !== 'waiting') {
214 throw new RuntimeException('Deze lobby is al begonnen.');
215 }
216 $members = $this->members($lobby['id']);
217 if (count($members) >= METEORS_MAX_PLAYERS) {
218 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
219 }
220 $now = $this->now();
221 $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)
224 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
225 name = excluded.name,
226 ready = 0,
227 eliminated = 0,
228 place = NULL,
229 left_at = NULL,
230 joined = excluded.joined,
231 last_seen = excluded.last_seen,
232 score = 0,
233 snapshot = NULL'
234 )->execute([$lobby['id'], $userId, $name, $now, $now]);
235 return $this->getLobby($lobby['id']);
236 });
237 }
238
239 private function leaveMember(string $lobbyId, string $userId): void
240 {
241 $this->pdo->prepare(
242 'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
243 )->execute([$this->now(), $lobbyId, $userId]);
244 $lobby = $this->getLobby($lobbyId);
245 if (!$lobby) {
246 return;
247 }
248 $remaining = $this->members($lobbyId);
249 if ($lobby['host_id'] === $userId) {
250 if ($remaining) {
251 $this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?')
252 ->execute([$remaining[0]['user_id'], $lobbyId]);
253 } elseif ($lobby['status'] === 'waiting') {
254 // Empty waiting lobby can stay; a later join by code still works until we want to close it.
255 }
256 }
257 if ($lobby['status'] === 'playing') {
258 $this->assignPlaceIfNeeded($lobbyId, $userId, true);
259 $this->maybeFinish($lobbyId);
260 }
261 }
262
263 public function leaveLobby(string $userId): void
264 {
265 $this->transaction(function () use ($userId) {
266 $lobby = $this->lobbyForUser($userId);
267 if (!$lobby) {
268 return;
269 }
270 $this->leaveMember($lobby['id'], $userId);
271 });
272 }
273
274 public function setReady(string $userId, bool $ready): array
275 {
276 return $this->transaction(function () use ($userId, $ready) {
277 $lobby = $this->lobbyForUser($userId);
278 if (!$lobby) {
279 throw new RuntimeException('Je zit niet in een lobby.');
280 }
281 if ($lobby['status'] !== 'waiting') {
282 throw new RuntimeException('Het spel is al begonnen.');
283 }
284 $this->pdo->prepare(
285 'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
286 )->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]);
287 return $this->getLobby($lobby['id']);
288 });
289 }
290
291 public function startGame(string $userId): array
292 {
293 return $this->transaction(function () use ($userId) {
294 $lobby = $this->lobbyForUser($userId);
295 if (!$lobby) {
296 throw new RuntimeException('Je zit niet in een lobby.');
297 }
298 if ($lobby['host_id'] !== $userId) {
299 throw new RuntimeException('Alleen de host kan het spel starten.');
300 }
301 if ($lobby['status'] !== 'waiting') {
302 throw new RuntimeException('Het spel is al begonnen.');
303 }
304 $members = $this->members($lobby['id']);
305 if (count($members) < 2) {
306 throw new RuntimeException('Er zijn minstens twee spelers nodig.');
307 }
308 foreach ($members as $m) {
309 if (!(int) $m['ready']) {
310 throw new RuntimeException('Niet iedereen is gereed.');
311 }
312 }
313 $this->pdo->prepare(
314 'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?'
315 )->execute(['playing', $this->now(), $lobby['id']]);
316 $this->pdo->prepare(
317 'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL
318 WHERE lobby_id = ? AND left_at IS NULL'
319 )->execute([$lobby['id']]);
320 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]);
321 return $this->getLobby($lobby['id']);
322 });
323 }
324
325 /** @param list<array{client_id?:string,color?:int}> $shots */
326 public function recordShots(string $userId, array $shots): array
327 {
328 return $this->transaction(function () use ($userId, $shots) {
329 $lobby = $this->lobbyForUser($userId);
330 if (!$lobby || $lobby['status'] !== 'playing') {
331 return [];
332 }
333 $me = $this->member($lobby['id'], $userId);
334 if (!$me || (int) $me['eliminated']) {
335 return [];
336 }
337 $targets = [];
338 foreach ($this->members($lobby['id']) as $m) {
339 if ($m['user_id'] !== $userId && !(int) $m['eliminated']) {
340 $targets[] = $m;
341 }
342 }
343 $results = [];
344 $missChance = (float) $lobby['miss_chance'];
345 $flight = (float) $lobby['flight_duration'];
346 $now = $this->nowf();
347 $ins = $this->pdo->prepare(
348 'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered)
349 VALUES (?,?,?,?,?,?,?,0)'
350 );
351 foreach ($shots as $shot) {
352 $color = isset($shot['color']) ? (int) $shot['color'] : -1;
353 $clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');
354 $miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;
355 $to = null;
356 $toName = null;
357 if (!$miss) {
358 $pick = $targets[random_int(0, count($targets) - 1)];
359 $to = $pick['user_id'];
360 $toName = $pick['name'];
361 }
362 $deliver = $now + $flight;
363 $ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver]);
364 $results[] = [
365 'id' => (int) $this->pdo->lastInsertId(),
366 'client_id' => $clientId,
367 'miss' => $miss,
368 'target_id' => $to,
369 'target_name' => $toName,
370 'deliver_at' => $deliver,
371 'color' => $color,
372 'flight_duration' => $flight,
373 ];
374 }
375 return $results;
376 });
377 }
378
379 /** @return list<array> undelivered shots whose time has come, marked delivered. */
380 public function takeIncoming(string $lobbyId, string $userId): array
381 {
382 $now = $this->nowf();
383 $stmt = $this->pdo->prepare(
384 'SELECT * FROM shots
385 WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ?
386 ORDER BY deliver_at ASC, id ASC'
387 );
388 $stmt->execute([$lobbyId, $userId, $now]);
389 $rows = $stmt->fetchAll();
390 if (!$rows) {
391 return [];
392 }
393 $ids = array_column($rows, 'id');
394 $in = implode(',', array_fill(0, count($ids), '?'));
395 $this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids);
396 $incoming = [];
397 foreach ($rows as $r) {
398 $incoming[] = [
399 'id' => (int) $r['id'],
400 'color' => (int) $r['color'],
401 'from_user' => $r['from_user'],
402 'client_id' => $r['client_id'],
403 ];
404 }
405 return $incoming;
406 }
407
408 public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void
409 {
410 $lobby = $this->lobbyForUser($userId);
411 if (!$lobby || $lobby['status'] !== 'playing') {
412 return;
413 }
414 $json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null;
415 $fields = 'last_seen = ?';
416 $args = [$this->now()];
417 if ($json !== null) {
418 $fields .= ', snapshot = ?';
419 $args[] = $json;
420 }
421 if ($score !== null) {
422 $fields .= ', score = ?';
423 $args[] = $score;
424 }
425 $args[] = $lobby['id'];
426 $args[] = $userId;
427 $this->pdo->prepare(
428 "UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL"
429 )->execute($args);
430 if ($eliminated) {
431 $this->assignPlaceIfNeeded($lobby['id'], $userId, false);
432 $this->maybeFinish($lobby['id']);
433 }
434 }
435
436 public function member(string $lobbyId, string $userId): ?array
437 {
438 $stmt = $this->pdo->prepare(
439 'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?'
440 );
441 $stmt->execute([$lobbyId, $userId]);
442 $row = $stmt->fetch();
443 return $row ?: null;
444 }
445
446 private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void
447 {
448 $m = $this->member($lobbyId, $userId);
449 if (!$m || $m['place'] !== null) {
450 return;
451 }
452 $active = 0;
453 foreach ($this->members($lobbyId) as $row) {
454 if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) {
455 $active++;
456 }
457 }
458 // First out gets last place = number of current (incl. this) non-left players.
459 $total = count($this->members($lobbyId));
460 $alreadyPlaced = 0;
461 foreach ($this->members($lobbyId, true) as $row) {
462 if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) {
463 if ($row['place'] !== null) {
464 $alreadyPlaced++;
465 }
466 }
467 }
468 $place = $active + 1; // remaining others + self → this player's place
469 $this->pdo->prepare(
470 'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?'
471 )->execute([$place, $lobbyId, $userId]);
472 }
473
474 public function maybeFinish(string $lobbyId): void
475 {
476 $lobby = $this->getLobby($lobbyId);
477 if (!$lobby || $lobby['status'] !== 'playing') {
478 return;
479 }
480 $alive = [];
481 foreach ($this->members($lobbyId) as $m) {
482 if (!(int) $m['eliminated']) {
483 $alive[] = $m;
484 }
485 }
486 if (count($alive) > 1) {
487 return;
488 }
489 if (count($alive) === 1) {
490 $winner = $alive[0];
491 if ($winner['place'] === null) {
492 $this->pdo->prepare(
493 'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?'
494 )->execute([$lobbyId, $winner['user_id']]);
495 }
496 }
497 $this->pdo->prepare(
498 'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?'
499 )->execute(['finished', $this->now(), $lobbyId]);
500 }
501
502 public function maybeResetLobby(string $lobbyId): void
503 {
504 $lobby = $this->getLobby($lobbyId);
505 if (!$lobby || $lobby['status'] !== 'finished') {
506 return;
507 }
508 $finished = (int) ($lobby['finished'] ?? 0);
509 if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {
510 return;
511 }
512 $this->pdo->prepare(
513 'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?'
514 )->execute(['waiting', $lobbyId]);
515 $this->pdo->prepare(
516 'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0
517 WHERE lobby_id = ? AND left_at IS NULL'
518 )->execute([$lobbyId]);
519 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]);
520 }
521
522 /** Public view of a lobby for the given user, including incoming shots. */
523 public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array
524 {
525 return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) {
526 $touch = $this->lobbyForUser($userId);
527 if ($touch && $touch['status'] === 'finished') {
528 $this->maybeResetLobby($touch['id']);
529 }
530 if ($touch && $touch['status'] === 'playing') {
531 if ($snapshot !== null || $score !== null || $eliminated) {
532 $this->updateSnapshot($userId, $snapshot, $score, $eliminated);
533 } else {
534 $this->pdo->prepare(
535 'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
536 )->execute([$this->now(), $touch['id'], $userId]);
537 }
538 }
539 $shotResults = [];
540 if ($outgoing && $touch && $touch['status'] === 'playing') {
541 $shotResults = $this->recordShots($userId, $outgoing);
542 }
543 $lobby = $this->lobbyForUser($userId);
544 if (!$lobby) {
545 return [
546 'lobby' => null,
547 'incoming' => [],
548 'shot_results' => $shotResults,
549 ];
550 }
551 $incoming = [];
552 if ($lobby['status'] === 'playing') {
553 $incoming = $this->takeIncoming($lobby['id'], $userId);
554 }
555 return [
556 'lobby' => $this->presentLobby($lobby, $userId),
557 'incoming' => $incoming,
558 'shot_results' => $shotResults,
559 ];
560 });
561 }
562
563 public function presentLobby(array $lobby, string $userId): array
564 {
565 $members = $this->members($lobby['id']);
566 $players = [];
567 foreach ($members as $m) {
568 $snap = null;
569 if (is_string($m['snapshot']) && $m['snapshot'] !== '') {
570 $decoded = json_decode($m['snapshot'], true);
571 $snap = is_array($decoded) ? $decoded : null;
572 }
573 $players[] = [
574 'id' => $m['user_id'],
575 'name' => $m['name'],
576 'ready' => (bool) (int) $m['ready'],
577 'eliminated' => (bool) (int) $m['eliminated'],
578 'place' => $m['place'] !== null ? (int) $m['place'] : null,
579 'is_host' => $m['user_id'] === $lobby['host_id'],
580 'is_me' => $m['user_id'] === $userId,
581 'score' => (int) $m['score'],
582 'snapshot' => $m['user_id'] === $userId ? null : $snap,
583 ];
584 }
585 $rankings = [];
586 if ($lobby['status'] === 'finished' || $lobby['finished']) {
587 $all = $this->members($lobby['id'], true);
588 foreach ($all as $m) {
589 if ($m['place'] !== null) {
590 $rankings[] = [
591 'place' => (int) $m['place'],
592 'id' => $m['user_id'],
593 'name' => $m['name'],
594 'score' => (int) $m['score'],
595 ];
596 }
597 }
598 usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']);
599 }
600 $allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true);
601 return [
602 'id' => $lobby['id'],
603 'code' => $lobby['code'],
604 'status' => $lobby['status'],
605 'host_id' => $lobby['host_id'],
606 'miss_chance' => (float) $lobby['miss_chance'],
607 'flight_duration' => (float) $lobby['flight_duration'],
608 'players' => $players,
609 'all_ready' => $allReady,
610 'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2,
611 'rankings' => $rankings,
612 'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null,
613 'podium_seconds' => METEORS_PODIUM_SECONDS,
614 ];
615 }
616 }
@@ -0,0 +1,616 @@
1<?php
2declare(strict_types=1);
3
4final class Store
5{
6 private PDO $pdo;
7 private int $txDepth = 0;
8
9 public function __construct(PDO $pdo)
10 {
11 $this->pdo = $pdo;
12 $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
13 $this->migrate();
14 }
15
16 public static function open(?string $dir = null): self
17 {
18 $dir = $dir ?? dataDir();
19 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
20 throw new RuntimeException('De datamap moet schrijfbaar zijn.');
21 }
22 $path = $dir . '/meteors.sqlite';
23 $pdo = new PDO('sqlite:' . $path, null, null, [
24 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
25 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
26 ]);
27 $pdo->exec('PRAGMA journal_mode = WAL');
28 $pdo->exec('PRAGMA foreign_keys = ON');
29 $pdo->exec('PRAGMA busy_timeout = 4000');
30 return new self($pdo);
31 }
32
33 private function migrate(): void
34 {
35 $this->pdo->exec(<<<'SQL'
36CREATE TABLE IF NOT EXISTS lobbies (
37 id TEXT PRIMARY KEY,
38 code TEXT UNIQUE NOT NULL,
39 host_id TEXT NOT NULL,
40 status TEXT NOT NULL DEFAULT 'waiting',
41 miss_chance REAL NOT NULL DEFAULT 0.30,
42 flight_duration REAL NOT NULL DEFAULT 1.2,
43 created INTEGER NOT NULL,
44 started INTEGER,
45 finished INTEGER
46);
47CREATE TABLE IF NOT EXISTS members (
48 lobby_id TEXT NOT NULL,
49 user_id TEXT NOT NULL,
50 name TEXT NOT NULL,
51 ready INTEGER NOT NULL DEFAULT 0,
52 eliminated INTEGER NOT NULL DEFAULT 0,
53 place INTEGER,
54 left_at INTEGER,
55 joined INTEGER NOT NULL,
56 last_seen INTEGER NOT NULL,
57 score INTEGER NOT NULL DEFAULT 0,
58 snapshot TEXT,
59 PRIMARY KEY (lobby_id, user_id)
60);
61CREATE TABLE IF NOT EXISTS shots (
62 id INTEGER PRIMARY KEY AUTOINCREMENT,
63 lobby_id TEXT NOT NULL,
64 from_user TEXT NOT NULL,
65 to_user TEXT,
66 color INTEGER NOT NULL,
67 client_id TEXT,
68 created REAL NOT NULL,
69 deliver_at REAL NOT NULL,
70 delivered INTEGER NOT NULL DEFAULT 0
71);
72CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
73SQL);
74 }
75
76 public function transaction(callable $fn): mixed
77 {
78 if ($this->txDepth > 0) {
79 return $fn();
80 }
81 $this->pdo->beginTransaction();
82 $this->txDepth++;
83 try {
84 $result = $fn();
85 $this->pdo->commit();
86 $this->txDepth--;
87 return $result;
88 } catch (Throwable $e) {
89 $this->txDepth--;
90 if ($this->pdo->inTransaction()) {
91 $this->pdo->rollBack();
92 }
93 throw $e;
94 }
95 }
96
97 private function now(): int
98 {
99 return time();
100 }
101
102 private function nowf(): float
103 {
104 return microtime(true);
105 }
106
107 private function newId(): string
108 {
109 return bin2hex(random_bytes(12));
110 }
111
112 private function newCode(): string
113 {
114 $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
115 $len = strlen($alphabet);
116 for ($attempt = 0; $attempt < 16; $attempt++) {
117 $code = '';
118 for ($i = 0; $i < 4; $i++) {
119 $code .= $alphabet[random_int(0, $len - 1)];
120 }
121 $exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?');
122 $exists->execute([$code]);
123 if (!$exists->fetch()) {
124 return $code;
125 }
126 }
127 throw new RuntimeException('Kon geen unieke lobbycode maken.');
128 }
129
130 public function lobbyForUser(string $userId): ?array
131 {
132 $stmt = $this->pdo->prepare(
133 'SELECT l.* FROM lobbies l
134 JOIN members m ON m.lobby_id = l.id
135 WHERE m.user_id = ? AND m.left_at IS NULL
136 ORDER BY l.created DESC LIMIT 1'
137 );
138 $stmt->execute([$userId]);
139 $row = $stmt->fetch();
140 return $row ?: null;
141 }
142
143 public function getLobby(string $id): ?array
144 {
145 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?');
146 $stmt->execute([$id]);
147 $row = $stmt->fetch();
148 return $row ?: null;
149 }
150
151 public function getLobbyByCode(string $code): ?array
152 {
153 $code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? '');
154 $stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?');
155 $stmt->execute([$code]);
156 $row = $stmt->fetch();
157 return $row ?: null;
158 }
159
160 /** @return list<array> */
161 public function members(string $lobbyId, bool $includeLeft = false): array
162 {
163 $sql = 'SELECT * FROM members WHERE lobby_id = ?';
164 if (!$includeLeft) {
165 $sql .= ' AND left_at IS NULL';
166 }
167 $sql .= ' ORDER BY joined ASC';
168 $stmt = $this->pdo->prepare($sql);
169 $stmt->execute([$lobbyId]);
170 return $stmt->fetchAll();
171 }
172
173 public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS): array
174 {
175 return $this->transaction(function () use ($userId, $name, $missChance) {
176 $existing = $this->lobbyForUser($userId);
177 if ($existing && $existing['status'] !== 'finished') {
178 throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
179 }
180 if ($existing && $existing['status'] === 'finished') {
181 $this->leaveMember($existing['id'], $userId);
182 }
183 $id = $this->newId();
184 $code = $this->newCode();
185 $now = $this->now();
186 $miss = max(0.0, min(1.0, $missChance));
187 $this->pdo->prepare(
188 'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
189 VALUES (?,?,?,?,?,?,?)'
190 )->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
191 $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]);
195 return $this->getLobby($id);
196 });
197 }
198
199 public function joinLobby(string $userId, string $name, string $code): array
200 {
201 return $this->transaction(function () use ($userId, $name, $code) {
202 $existing = $this->lobbyForUser($userId);
203 if ($existing && $existing['status'] !== 'finished') {
204 if (strcasecmp($existing['code'], $code) === 0) {
205 return $existing;
206 }
207 throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.');
208 }
209 $lobby = $this->getLobbyByCode($code);
210 if (!$lobby) {
211 throw new RuntimeException('Onbekende lobbycode.');
212 }
213 if ($lobby['status'] !== 'waiting') {
214 throw new RuntimeException('Deze lobby is al begonnen.');
215 }
216 $members = $this->members($lobby['id']);
217 if (count($members) >= METEORS_MAX_PLAYERS) {
218 throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
219 }
220 $now = $this->now();
221 $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)
224 ON CONFLICT(lobby_id, user_id) DO UPDATE SET
225 name = excluded.name,
226 ready = 0,
227 eliminated = 0,
228 place = NULL,
229 left_at = NULL,
230 joined = excluded.joined,
231 last_seen = excluded.last_seen,
232 score = 0,
233 snapshot = NULL'
234 )->execute([$lobby['id'], $userId, $name, $now, $now]);
235 return $this->getLobby($lobby['id']);
236 });
237 }
238
239 private function leaveMember(string $lobbyId, string $userId): void
240 {
241 $this->pdo->prepare(
242 'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
243 )->execute([$this->now(), $lobbyId, $userId]);
244 $lobby = $this->getLobby($lobbyId);
245 if (!$lobby) {
246 return;
247 }
248 $remaining = $this->members($lobbyId);
249 if ($lobby['host_id'] === $userId) {
250 if ($remaining) {
251 $this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?')
252 ->execute([$remaining[0]['user_id'], $lobbyId]);
253 } elseif ($lobby['status'] === 'waiting') {
254 // Empty waiting lobby can stay; a later join by code still works until we want to close it.
255 }
256 }
257 if ($lobby['status'] === 'playing') {
258 $this->assignPlaceIfNeeded($lobbyId, $userId, true);
259 $this->maybeFinish($lobbyId);
260 }
261 }
262
263 public function leaveLobby(string $userId): void
264 {
265 $this->transaction(function () use ($userId) {
266 $lobby = $this->lobbyForUser($userId);
267 if (!$lobby) {
268 return;
269 }
270 $this->leaveMember($lobby['id'], $userId);
271 });
272 }
273
274 public function setReady(string $userId, bool $ready): array
275 {
276 return $this->transaction(function () use ($userId, $ready) {
277 $lobby = $this->lobbyForUser($userId);
278 if (!$lobby) {
279 throw new RuntimeException('Je zit niet in een lobby.');
280 }
281 if ($lobby['status'] !== 'waiting') {
282 throw new RuntimeException('Het spel is al begonnen.');
283 }
284 $this->pdo->prepare(
285 'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
286 )->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]);
287 return $this->getLobby($lobby['id']);
288 });
289 }
290
291 public function startGame(string $userId): array
292 {
293 return $this->transaction(function () use ($userId) {
294 $lobby = $this->lobbyForUser($userId);
295 if (!$lobby) {
296 throw new RuntimeException('Je zit niet in een lobby.');
297 }
298 if ($lobby['host_id'] !== $userId) {
299 throw new RuntimeException('Alleen de host kan het spel starten.');
300 }
301 if ($lobby['status'] !== 'waiting') {
302 throw new RuntimeException('Het spel is al begonnen.');
303 }
304 $members = $this->members($lobby['id']);
305 if (count($members) < 2) {
306 throw new RuntimeException('Er zijn minstens twee spelers nodig.');
307 }
308 foreach ($members as $m) {
309 if (!(int) $m['ready']) {
310 throw new RuntimeException('Niet iedereen is gereed.');
311 }
312 }
313 $this->pdo->prepare(
314 'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?'
315 )->execute(['playing', $this->now(), $lobby['id']]);
316 $this->pdo->prepare(
317 'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL
318 WHERE lobby_id = ? AND left_at IS NULL'
319 )->execute([$lobby['id']]);
320 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]);
321 return $this->getLobby($lobby['id']);
322 });
323 }
324
325 /** @param list<array{client_id?:string,color?:int}> $shots */
326 public function recordShots(string $userId, array $shots): array
327 {
328 return $this->transaction(function () use ($userId, $shots) {
329 $lobby = $this->lobbyForUser($userId);
330 if (!$lobby || $lobby['status'] !== 'playing') {
331 return [];
332 }
333 $me = $this->member($lobby['id'], $userId);
334 if (!$me || (int) $me['eliminated']) {
335 return [];
336 }
337 $targets = [];
338 foreach ($this->members($lobby['id']) as $m) {
339 if ($m['user_id'] !== $userId && !(int) $m['eliminated']) {
340 $targets[] = $m;
341 }
342 }
343 $results = [];
344 $missChance = (float) $lobby['miss_chance'];
345 $flight = (float) $lobby['flight_duration'];
346 $now = $this->nowf();
347 $ins = $this->pdo->prepare(
348 'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered)
349 VALUES (?,?,?,?,?,?,?,0)'
350 );
351 foreach ($shots as $shot) {
352 $color = isset($shot['color']) ? (int) $shot['color'] : -1;
353 $clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');
354 $miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;
355 $to = null;
356 $toName = null;
357 if (!$miss) {
358 $pick = $targets[random_int(0, count($targets) - 1)];
359 $to = $pick['user_id'];
360 $toName = $pick['name'];
361 }
362 $deliver = $now + $flight;
363 $ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver]);
364 $results[] = [
365 'id' => (int) $this->pdo->lastInsertId(),
366 'client_id' => $clientId,
367 'miss' => $miss,
368 'target_id' => $to,
369 'target_name' => $toName,
370 'deliver_at' => $deliver,
371 'color' => $color,
372 'flight_duration' => $flight,
373 ];
374 }
375 return $results;
376 });
377 }
378
379 /** @return list<array> undelivered shots whose time has come, marked delivered. */
380 public function takeIncoming(string $lobbyId, string $userId): array
381 {
382 $now = $this->nowf();
383 $stmt = $this->pdo->prepare(
384 'SELECT * FROM shots
385 WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ?
386 ORDER BY deliver_at ASC, id ASC'
387 );
388 $stmt->execute([$lobbyId, $userId, $now]);
389 $rows = $stmt->fetchAll();
390 if (!$rows) {
391 return [];
392 }
393 $ids = array_column($rows, 'id');
394 $in = implode(',', array_fill(0, count($ids), '?'));
395 $this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids);
396 $incoming = [];
397 foreach ($rows as $r) {
398 $incoming[] = [
399 'id' => (int) $r['id'],
400 'color' => (int) $r['color'],
401 'from_user' => $r['from_user'],
402 'client_id' => $r['client_id'],
403 ];
404 }
405 return $incoming;
406 }
407
408 public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void
409 {
410 $lobby = $this->lobbyForUser($userId);
411 if (!$lobby || $lobby['status'] !== 'playing') {
412 return;
413 }
414 $json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null;
415 $fields = 'last_seen = ?';
416 $args = [$this->now()];
417 if ($json !== null) {
418 $fields .= ', snapshot = ?';
419 $args[] = $json;
420 }
421 if ($score !== null) {
422 $fields .= ', score = ?';
423 $args[] = $score;
424 }
425 $args[] = $lobby['id'];
426 $args[] = $userId;
427 $this->pdo->prepare(
428 "UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL"
429 )->execute($args);
430 if ($eliminated) {
431 $this->assignPlaceIfNeeded($lobby['id'], $userId, false);
432 $this->maybeFinish($lobby['id']);
433 }
434 }
435
436 public function member(string $lobbyId, string $userId): ?array
437 {
438 $stmt = $this->pdo->prepare(
439 'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?'
440 );
441 $stmt->execute([$lobbyId, $userId]);
442 $row = $stmt->fetch();
443 return $row ?: null;
444 }
445
446 private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void
447 {
448 $m = $this->member($lobbyId, $userId);
449 if (!$m || $m['place'] !== null) {
450 return;
451 }
452 $active = 0;
453 foreach ($this->members($lobbyId) as $row) {
454 if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) {
455 $active++;
456 }
457 }
458 // First out gets last place = number of current (incl. this) non-left players.
459 $total = count($this->members($lobbyId));
460 $alreadyPlaced = 0;
461 foreach ($this->members($lobbyId, true) as $row) {
462 if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) {
463 if ($row['place'] !== null) {
464 $alreadyPlaced++;
465 }
466 }
467 }
468 $place = $active + 1; // remaining others + self → this player's place
469 $this->pdo->prepare(
470 'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?'
471 )->execute([$place, $lobbyId, $userId]);
472 }
473
474 public function maybeFinish(string $lobbyId): void
475 {
476 $lobby = $this->getLobby($lobbyId);
477 if (!$lobby || $lobby['status'] !== 'playing') {
478 return;
479 }
480 $alive = [];
481 foreach ($this->members($lobbyId) as $m) {
482 if (!(int) $m['eliminated']) {
483 $alive[] = $m;
484 }
485 }
486 if (count($alive) > 1) {
487 return;
488 }
489 if (count($alive) === 1) {
490 $winner = $alive[0];
491 if ($winner['place'] === null) {
492 $this->pdo->prepare(
493 'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?'
494 )->execute([$lobbyId, $winner['user_id']]);
495 }
496 }
497 $this->pdo->prepare(
498 'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?'
499 )->execute(['finished', $this->now(), $lobbyId]);
500 }
501
502 public function maybeResetLobby(string $lobbyId): void
503 {
504 $lobby = $this->getLobby($lobbyId);
505 if (!$lobby || $lobby['status'] !== 'finished') {
506 return;
507 }
508 $finished = (int) ($lobby['finished'] ?? 0);
509 if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {
510 return;
511 }
512 $this->pdo->prepare(
513 'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?'
514 )->execute(['waiting', $lobbyId]);
515 $this->pdo->prepare(
516 'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0
517 WHERE lobby_id = ? AND left_at IS NULL'
518 )->execute([$lobbyId]);
519 $this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]);
520 }
521
522 /** Public view of a lobby for the given user, including incoming shots. */
523 public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array
524 {
525 return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) {
526 $touch = $this->lobbyForUser($userId);
527 if ($touch && $touch['status'] === 'finished') {
528 $this->maybeResetLobby($touch['id']);
529 }
530 if ($touch && $touch['status'] === 'playing') {
531 if ($snapshot !== null || $score !== null || $eliminated) {
532 $this->updateSnapshot($userId, $snapshot, $score, $eliminated);
533 } else {
534 $this->pdo->prepare(
535 'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
536 )->execute([$this->now(), $touch['id'], $userId]);
537 }
538 }
539 $shotResults = [];
540 if ($outgoing && $touch && $touch['status'] === 'playing') {
541 $shotResults = $this->recordShots($userId, $outgoing);
542 }
543 $lobby = $this->lobbyForUser($userId);
544 if (!$lobby) {
545 return [
546 'lobby' => null,
547 'incoming' => [],
548 'shot_results' => $shotResults,
549 ];
550 }
551 $incoming = [];
552 if ($lobby['status'] === 'playing') {
553 $incoming = $this->takeIncoming($lobby['id'], $userId);
554 }
555 return [
556 'lobby' => $this->presentLobby($lobby, $userId),
557 'incoming' => $incoming,
558 'shot_results' => $shotResults,
559 ];
560 });
561 }
562
563 public function presentLobby(array $lobby, string $userId): array
564 {
565 $members = $this->members($lobby['id']);
566 $players = [];
567 foreach ($members as $m) {
568 $snap = null;
569 if (is_string($m['snapshot']) && $m['snapshot'] !== '') {
570 $decoded = json_decode($m['snapshot'], true);
571 $snap = is_array($decoded) ? $decoded : null;
572 }
573 $players[] = [
574 'id' => $m['user_id'],
575 'name' => $m['name'],
576 'ready' => (bool) (int) $m['ready'],
577 'eliminated' => (bool) (int) $m['eliminated'],
578 'place' => $m['place'] !== null ? (int) $m['place'] : null,
579 'is_host' => $m['user_id'] === $lobby['host_id'],
580 'is_me' => $m['user_id'] === $userId,
581 'score' => (int) $m['score'],
582 'snapshot' => $m['user_id'] === $userId ? null : $snap,
583 ];
584 }
585 $rankings = [];
586 if ($lobby['status'] === 'finished' || $lobby['finished']) {
587 $all = $this->members($lobby['id'], true);
588 foreach ($all as $m) {
589 if ($m['place'] !== null) {
590 $rankings[] = [
591 'place' => (int) $m['place'],
592 'id' => $m['user_id'],
593 'name' => $m['name'],
594 'score' => (int) $m['score'],
595 ];
596 }
597 }
598 usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']);
599 }
600 $allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true);
601 return [
602 'id' => $lobby['id'],
603 'code' => $lobby['code'],
604 'status' => $lobby['status'],
605 'host_id' => $lobby['host_id'],
606 'miss_chance' => (float) $lobby['miss_chance'],
607 'flight_duration' => (float) $lobby['flight_duration'],
608 'players' => $players,
609 'all_ready' => $allReady,
610 'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2,
611 'rankings' => $rankings,
612 'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null,
613 'podium_seconds' => METEORS_PODIUM_SECONDS,
614 ];
615 }
616}
server/lib/bootstrap.php added +321 −0
@@ -0,0 +1,321 @@
1 <?php
2 declare(strict_types=1);
3
4 const METEORS_SESSION_TTL = 86400;
5 const METEORS_DEFAULT_AUTH = 'https://auth.timfalken.com';
6 const METEORS_DEFAULT_CLIENT_ID = 'projects.timfalken.com';
7 const METEORS_DEFAULT_BASE = 'https://projects.timfalken.com/meteors';
8 const METEORS_DEFAULT_MISS = 0.30;
9 const METEORS_FLIGHT_DURATION = 1.2;
10 const METEORS_MAX_PLAYERS = 32;
11 const METEORS_PODIUM_SECONDS = 5;
12
13 function dataDir(): string
14 {
15 $override = getenv('METEORS_DATA_DIR');
16 if (is_string($override) && $override !== '') {
17 return rtrim($override, '/');
18 }
19 return dirname(__DIR__) . '/data';
20 }
21
22 function ensureDataDir(): string
23 {
24 $dir = dataDir();
25 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
26 throw new RuntimeException('De datamap moet schrijfbaar zijn.');
27 }
28 $deny = $dir . '/.htaccess';
29 if (!is_file($deny)) {
30 @file_put_contents($deny, "Require all denied\n");
31 }
32 $sessions = $dir . '/sessions';
33 if (!is_dir($sessions)) {
34 @mkdir($sessions, 0775, true);
35 }
36 return $dir;
37 }
38
39 function localDev(): bool
40 {
41 $host = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
42 return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
43 && in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
44 }
45
46 function config(): array
47 {
48 $dir = ensureDataDir();
49 $path = $dir . '/config.php';
50 $lock = fopen($dir . '/config.lock', 'c');
51 if ($lock === false) {
52 throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
53 }
54 try {
55 if (!flock($lock, LOCK_EX)) {
56 throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
57 }
58 if (!is_file($path)) {
59 $template = <<<'PHP'
60 <?php
61 // Vul deze waarden op de server in. Lege velden gebruiken omgevingsvariabelen.
62 // Productie-URL: https://projects.timfalken.com/meteors
63 // client_id is het geregistreerde domein: projects.timfalken.com.
64 // Het geheim komt uit https://auth.timfalken.com/admin (het BESTAANDE geheim
65 // van dit domein; NIET opnieuw genereren, dat breekt de andere sites).
66 // Voeg daar ook het callback-pad /meteors/callback.php toe.
67 // Dit bestand wordt niet gedeployed en staat niet in git.
68 return [
69 'auth_url' => 'https://auth.timfalken.com',
70 'base_url' => 'https://projects.timfalken.com/meteors',
71 'client_id' => 'projects.timfalken.com',
72 'client_secret' => '',
73 ];
74 PHP;
75 if (file_put_contents($path, $template) !== strlen($template)) {
76 throw new RuntimeException('data/config.php kon niet worden gemaakt.');
77 }
78 }
79 $values = require $path;
80 if (!is_array($values)) {
81 throw new RuntimeException('data/config.php moet een array teruggeven.');
82 }
83 } finally {
84 flock($lock, LOCK_UN);
85 fclose($lock);
86 }
87 foreach ([
88 'auth_url' => 'METEORS_AUTH_URL',
89 'base_url' => 'METEORS_BASE_URL',
90 'client_id' => 'METEORS_CLIENT_ID',
91 'client_secret' => 'METEORS_CLIENT_SECRET',
92 ] as $key => $env) {
93 if (($values[$key] ?? '') === '') {
94 $values[$key] = getenv($env) ?: '';
95 }
96 }
97 if (($values['auth_url'] ?? '') === '') {
98 $values['auth_url'] = METEORS_DEFAULT_AUTH;
99 }
100 if (($values['client_id'] ?? '') === '') {
101 $values['client_id'] = METEORS_DEFAULT_CLIENT_ID;
102 }
103 return $values;
104 }
105
106 function authConfigured(): bool
107 {
108 $c = config();
109 return ($c['client_secret'] ?? '') !== ''
110 && ($c['client_id'] ?? '') !== ''
111 && ($c['base_url'] ?? '') !== '';
112 }
113
114 function baseUrl(): string
115 {
116 if (localDev()) {
117 $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
118 if ($dir === '/' || $dir === '.') {
119 $dir = '';
120 }
121 return 'http://' . $_SERVER['HTTP_HOST'] . $dir;
122 }
123 $base = rtrim((string) (config()['base_url'] ?? ''), '/');
124 if (!str_starts_with($base, 'https://')) {
125 throw new RuntimeException(
126 "Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie "
127 . '(https://projects.timfalken.com/meteors), of zet METEORS_BASE_URL.'
128 );
129 }
130 return $base;
131 }
132
133 function authUrl(): string
134 {
135 $url = rtrim((string) (config()['auth_url'] ?? METEORS_DEFAULT_AUTH), '/');
136 return $url !== '' ? $url : METEORS_DEFAULT_AUTH;
137 }
138
139 function authRequest(string $path, ?array $form = null, ?string $token = null): array
140 {
141 $ch = curl_init(authUrl() . $path);
142 $headers = ['Accept: application/json', 'User-Agent: Meteors/1.0'];
143 if ($token) {
144 $headers[] = 'Authorization: Bearer ' . $token;
145 }
146 curl_setopt_array($ch, [
147 CURLOPT_RETURNTRANSFER => true,
148 CURLOPT_TIMEOUT => 15,
149 CURLOPT_HTTPHEADER => $headers,
150 ]);
151 if ($form !== null) {
152 curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
153 }
154 $body = curl_exec($ch);
155 $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
156 $err = curl_error($ch);
157 curl_close($ch);
158 $data = is_string($body) ? json_decode($body, true) : null;
159 if ($status !== 200 || !is_array($data)) {
160 $hint = $err !== '' ? ' (' . $err . ')' : '';
161 throw new RuntimeException(
162 'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint
163 );
164 }
165 return $data;
166 }
167
168 /** @return array{0:string,1:string} */
169 function authIdentity(array $profile): array
170 {
171 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
172 throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');
173 }
174 $raw = $profile['id'];
175 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
176 if (!$numeric || (int) $raw < 1) {
177 throw new RuntimeException('Ongeldig account-id.');
178 }
179 return ['auth:' . (int) $raw, $profile['username']];
180 }
181
182 function loginUser(string $id, string $name): void
183 {
184 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) {
185 throw new RuntimeException('Ongeldig account.');
186 }
187 $name = trim($name);
188 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {
189 throw new RuntimeException('Ongeldige gebruikersnaam.');
190 }
191 session_regenerate_id(true);
192 $_SESSION['user'] = $id;
193 $_SESSION['name'] = $name;
194 $_SESSION['csrf'] = bin2hex(random_bytes(24));
195 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
196 }
197
198 function logoutUser(): void
199 {
200 $_SESSION = [];
201 if (ini_get('session.use_cookies')) {
202 $p = session_get_cookie_params();
203 setcookie(session_name(), '', [
204 'expires' => time() - 3600,
205 'path' => $p['path'] ?? '/',
206 'secure' => (bool) ($p['secure'] ?? false),
207 'httponly' => true,
208 'samesite' => 'Lax',
209 ]);
210 }
211 session_destroy();
212 }
213
214 function currentUser(): ?array
215 {
216 $id = $_SESSION['user'] ?? null;
217 $name = $_SESSION['name'] ?? null;
218 if (!is_string($id) || $id === '' || !is_string($name)) {
219 return null;
220 }
221 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
222 return null;
223 }
224 return ['id' => $id, 'name' => $name];
225 }
226
227 function requireUser(): array
228 {
229 $u = currentUser();
230 if (!$u) {
231 jsonFail('Log in om verder te gaan.', 401);
232 }
233 return $u;
234 }
235
236 function csrfToken(): string
237 {
238 if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
239 $_SESSION['csrf'] = bin2hex(random_bytes(24));
240 }
241 return $_SESSION['csrf'];
242 }
243
244 function requireCsrf(): void
245 {
246 if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
247 return;
248 }
249 $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
250 if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
251 jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);
252 }
253 }
254
255 function jsonOut(array $data, int $status = 200): never
256 {
257 http_response_code($status);
258 header('Content-Type: application/json; charset=utf-8');
259 header('Cache-Control: no-store');
260 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
261 exit;
262 }
263
264 function jsonFail(string $message, int $status = 400): never
265 {
266 jsonOut(['ok' => false, 'error' => $message], $status);
267 }
268
269 function readJsonBody(): array
270 {
271 $raw = file_get_contents('php://input');
272 if (!is_string($raw) || $raw === '') {
273 return $_POST;
274 }
275 $data = json_decode($raw, true);
276 return is_array($data) ? $data : [];
277 }
278
279 function startMeteorsSession(): void
280 {
281 if (session_status() === PHP_SESSION_ACTIVE) {
282 return;
283 }
284 $dir = ensureDataDir() . '/sessions';
285 if (!is_dir($dir)) {
286 @mkdir($dir, 0775, true);
287 }
288 session_name('meteors_session');
289 ini_set('session.use_strict_mode', '1');
290 ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);
291 session_save_path($dir);
292 $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
293 if ($path === '//') {
294 $path = '/';
295 }
296 $secure = !localDev();
297 session_set_cookie_params([
298 'lifetime' => METEORS_SESSION_TTL,
299 'path' => $path,
300 'secure' => $secure,
301 'httponly' => true,
302 'samesite' => 'Lax',
303 ]);
304 session_start();
305 if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
306 setcookie(session_name(), session_id(), [
307 'expires' => time() + METEORS_SESSION_TTL,
308 'path' => $path,
309 'secure' => $secure,
310 'httponly' => true,
311 'samesite' => 'Lax',
312 ]);
313 }
314 if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
315 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
316 }
317 }
318
319 if (!defined('METEORS_NO_SESSION')) {
320 startMeteorsSession();
321 }
@@ -0,0 +1,321 @@
1<?php
2declare(strict_types=1);
3
4const METEORS_SESSION_TTL = 86400;
5const METEORS_DEFAULT_AUTH = 'https://auth.timfalken.com';
6const METEORS_DEFAULT_CLIENT_ID = 'projects.timfalken.com';
7const METEORS_DEFAULT_BASE = 'https://projects.timfalken.com/meteors';
8const METEORS_DEFAULT_MISS = 0.30;
9const METEORS_FLIGHT_DURATION = 1.2;
10const METEORS_MAX_PLAYERS = 32;
11const METEORS_PODIUM_SECONDS = 5;
12
13function dataDir(): string
14{
15 $override = getenv('METEORS_DATA_DIR');
16 if (is_string($override) && $override !== '') {
17 return rtrim($override, '/');
18 }
19 return dirname(__DIR__) . '/data';
20}
21
22function ensureDataDir(): string
23{
24 $dir = dataDir();
25 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
26 throw new RuntimeException('De datamap moet schrijfbaar zijn.');
27 }
28 $deny = $dir . '/.htaccess';
29 if (!is_file($deny)) {
30 @file_put_contents($deny, "Require all denied\n");
31 }
32 $sessions = $dir . '/sessions';
33 if (!is_dir($sessions)) {
34 @mkdir($sessions, 0775, true);
35 }
36 return $dir;
37}
38
39function localDev(): bool
40{
41 $host = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
42 return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
43 && in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
44}
45
46function config(): array
47{
48 $dir = ensureDataDir();
49 $path = $dir . '/config.php';
50 $lock = fopen($dir . '/config.lock', 'c');
51 if ($lock === false) {
52 throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
53 }
54 try {
55 if (!flock($lock, LOCK_EX)) {
56 throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
57 }
58 if (!is_file($path)) {
59 $template = <<<'PHP'
60<?php
61// Vul deze waarden op de server in. Lege velden gebruiken omgevingsvariabelen.
62// Productie-URL: https://projects.timfalken.com/meteors
63// client_id is het geregistreerde domein: projects.timfalken.com.
64// Het geheim komt uit https://auth.timfalken.com/admin (het BESTAANDE geheim
65// van dit domein; NIET opnieuw genereren, dat breekt de andere sites).
66// Voeg daar ook het callback-pad /meteors/callback.php toe.
67// Dit bestand wordt niet gedeployed en staat niet in git.
68return [
69 'auth_url' => 'https://auth.timfalken.com',
70 'base_url' => 'https://projects.timfalken.com/meteors',
71 'client_id' => 'projects.timfalken.com',
72 'client_secret' => '',
73];
74PHP;
75 if (file_put_contents($path, $template) !== strlen($template)) {
76 throw new RuntimeException('data/config.php kon niet worden gemaakt.');
77 }
78 }
79 $values = require $path;
80 if (!is_array($values)) {
81 throw new RuntimeException('data/config.php moet een array teruggeven.');
82 }
83 } finally {
84 flock($lock, LOCK_UN);
85 fclose($lock);
86 }
87 foreach ([
88 'auth_url' => 'METEORS_AUTH_URL',
89 'base_url' => 'METEORS_BASE_URL',
90 'client_id' => 'METEORS_CLIENT_ID',
91 'client_secret' => 'METEORS_CLIENT_SECRET',
92 ] as $key => $env) {
93 if (($values[$key] ?? '') === '') {
94 $values[$key] = getenv($env) ?: '';
95 }
96 }
97 if (($values['auth_url'] ?? '') === '') {
98 $values['auth_url'] = METEORS_DEFAULT_AUTH;
99 }
100 if (($values['client_id'] ?? '') === '') {
101 $values['client_id'] = METEORS_DEFAULT_CLIENT_ID;
102 }
103 return $values;
104}
105
106function authConfigured(): bool
107{
108 $c = config();
109 return ($c['client_secret'] ?? '') !== ''
110 && ($c['client_id'] ?? '') !== ''
111 && ($c['base_url'] ?? '') !== '';
112}
113
114function baseUrl(): string
115{
116 if (localDev()) {
117 $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
118 if ($dir === '/' || $dir === '.') {
119 $dir = '';
120 }
121 return 'http://' . $_SERVER['HTTP_HOST'] . $dir;
122 }
123 $base = rtrim((string) (config()['base_url'] ?? ''), '/');
124 if (!str_starts_with($base, 'https://')) {
125 throw new RuntimeException(
126 "Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie "
127 . '(https://projects.timfalken.com/meteors), of zet METEORS_BASE_URL.'
128 );
129 }
130 return $base;
131}
132
133function authUrl(): string
134{
135 $url = rtrim((string) (config()['auth_url'] ?? METEORS_DEFAULT_AUTH), '/');
136 return $url !== '' ? $url : METEORS_DEFAULT_AUTH;
137}
138
139function authRequest(string $path, ?array $form = null, ?string $token = null): array
140{
141 $ch = curl_init(authUrl() . $path);
142 $headers = ['Accept: application/json', 'User-Agent: Meteors/1.0'];
143 if ($token) {
144 $headers[] = 'Authorization: Bearer ' . $token;
145 }
146 curl_setopt_array($ch, [
147 CURLOPT_RETURNTRANSFER => true,
148 CURLOPT_TIMEOUT => 15,
149 CURLOPT_HTTPHEADER => $headers,
150 ]);
151 if ($form !== null) {
152 curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
153 }
154 $body = curl_exec($ch);
155 $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
156 $err = curl_error($ch);
157 curl_close($ch);
158 $data = is_string($body) ? json_decode($body, true) : null;
159 if ($status !== 200 || !is_array($data)) {
160 $hint = $err !== '' ? ' (' . $err . ')' : '';
161 throw new RuntimeException(
162 'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint
163 );
164 }
165 return $data;
166}
167
168/** @return array{0:string,1:string} */
169function authIdentity(array $profile): array
170{
171 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
172 throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');
173 }
174 $raw = $profile['id'];
175 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
176 if (!$numeric || (int) $raw < 1) {
177 throw new RuntimeException('Ongeldig account-id.');
178 }
179 return ['auth:' . (int) $raw, $profile['username']];
180}
181
182function loginUser(string $id, string $name): void
183{
184 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) {
185 throw new RuntimeException('Ongeldig account.');
186 }
187 $name = trim($name);
188 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {
189 throw new RuntimeException('Ongeldige gebruikersnaam.');
190 }
191 session_regenerate_id(true);
192 $_SESSION['user'] = $id;
193 $_SESSION['name'] = $name;
194 $_SESSION['csrf'] = bin2hex(random_bytes(24));
195 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
196}
197
198function logoutUser(): void
199{
200 $_SESSION = [];
201 if (ini_get('session.use_cookies')) {
202 $p = session_get_cookie_params();
203 setcookie(session_name(), '', [
204 'expires' => time() - 3600,
205 'path' => $p['path'] ?? '/',
206 'secure' => (bool) ($p['secure'] ?? false),
207 'httponly' => true,
208 'samesite' => 'Lax',
209 ]);
210 }
211 session_destroy();
212}
213
214function currentUser(): ?array
215{
216 $id = $_SESSION['user'] ?? null;
217 $name = $_SESSION['name'] ?? null;
218 if (!is_string($id) || $id === '' || !is_string($name)) {
219 return null;
220 }
221 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
222 return null;
223 }
224 return ['id' => $id, 'name' => $name];
225}
226
227function requireUser(): array
228{
229 $u = currentUser();
230 if (!$u) {
231 jsonFail('Log in om verder te gaan.', 401);
232 }
233 return $u;
234}
235
236function csrfToken(): string
237{
238 if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
239 $_SESSION['csrf'] = bin2hex(random_bytes(24));
240 }
241 return $_SESSION['csrf'];
242}
243
244function requireCsrf(): void
245{
246 if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
247 return;
248 }
249 $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
250 if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
251 jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);
252 }
253}
254
255function jsonOut(array $data, int $status = 200): never
256{
257 http_response_code($status);
258 header('Content-Type: application/json; charset=utf-8');
259 header('Cache-Control: no-store');
260 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
261 exit;
262}
263
264function jsonFail(string $message, int $status = 400): never
265{
266 jsonOut(['ok' => false, 'error' => $message], $status);
267}
268
269function readJsonBody(): array
270{
271 $raw = file_get_contents('php://input');
272 if (!is_string($raw) || $raw === '') {
273 return $_POST;
274 }
275 $data = json_decode($raw, true);
276 return is_array($data) ? $data : [];
277}
278
279function startMeteorsSession(): void
280{
281 if (session_status() === PHP_SESSION_ACTIVE) {
282 return;
283 }
284 $dir = ensureDataDir() . '/sessions';
285 if (!is_dir($dir)) {
286 @mkdir($dir, 0775, true);
287 }
288 session_name('meteors_session');
289 ini_set('session.use_strict_mode', '1');
290 ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);
291 session_save_path($dir);
292 $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
293 if ($path === '//') {
294 $path = '/';
295 }
296 $secure = !localDev();
297 session_set_cookie_params([
298 'lifetime' => METEORS_SESSION_TTL,
299 'path' => $path,
300 'secure' => $secure,
301 'httponly' => true,
302 'samesite' => 'Lax',
303 ]);
304 session_start();
305 if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
306 setcookie(session_name(), session_id(), [
307 'expires' => time() + METEORS_SESSION_TTL,
308 'path' => $path,
309 'secure' => $secure,
310 'httponly' => true,
311 'samesite' => 'Lax',
312 ]);
313 }
314 if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
315 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
316 }
317}
318
319if (!defined('METEORS_NO_SESSION')) {
320 startMeteorsSession();
321}
server/logout.php added +11 −0
@@ -0,0 +1,11 @@
1 <?php
2 declare(strict_types=1);
3 require __DIR__ . '/lib/bootstrap.php';
4 logoutUser();
5 if (isset($_GET['json'])) {
6 // Session is destroyed; a new empty one may start on next request.
7 header('Content-Type: application/json; charset=utf-8');
8 echo json_encode(['ok' => true]);
9 exit;
10 }
11 header('Location: index.html');
@@ -0,0 +1,11 @@
1<?php
2declare(strict_types=1);
3require __DIR__ . '/lib/bootstrap.php';
4logoutUser();
5if (isset($_GET['json'])) {
6 // Session is destroyed; a new empty one may start on next request.
7 header('Content-Type: application/json; charset=utf-8');
8 echo json_encode(['ok' => true]);
9 exit;
10}
11header('Location: index.html');
server/router.php added +20 −0
@@ -0,0 +1,20 @@
1 <?php
2 declare(strict_types=1);
3 // Router for PHP's built-in server: php -S 127.0.0.1:8080 -t build server/router.php
4 // (copied to build/router.php; the -t directory is the docroot).
5 $uri = urldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/');
6 $file = __DIR__ . $uri;
7 if ($uri !== '/' && is_file($file)) {
8 return false;
9 }
10 if (str_ends_with($uri, '.php') && is_file($file)) {
11 require $file;
12 return true;
13 }
14 // Fall through to index.html for the game UI.
15 if (is_file(__DIR__ . '/index.html')) {
16 header('Content-Type: text/html; charset=utf-8');
17 readfile(__DIR__ . '/index.html');
18 return true;
19 }
20 return false;
@@ -0,0 +1,20 @@
1<?php
2declare(strict_types=1);
3// Router for PHP's built-in server: php -S 127.0.0.1:8080 -t build server/router.php
4// (copied to build/router.php; the -t directory is the docroot).
5$uri = urldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/');
6$file = __DIR__ . $uri;
7if ($uri !== '/' && is_file($file)) {
8 return false;
9}
10if (str_ends_with($uri, '.php') && is_file($file)) {
11 require $file;
12 return true;
13}
14// Fall through to index.html for the game UI.
15if (is_file(__DIR__ . '/index.html')) {
16 header('Content-Type: text/html; charset=utf-8');
17 readfile(__DIR__ . '/index.html');
18 return true;
19}
20return false;
server/tests/run.php added +201 −0
@@ -0,0 +1,201 @@
1 <?php
2 declare(strict_types=1);
3 // php server/tests/run.php
4 define('METEORS_NO_SESSION', true);
5 require dirname(__DIR__) . '/lib/bootstrap.php';
6 require dirname(__DIR__) . '/lib/Store.php';
7
8 $failed = 0;
9 $passed = 0;
10
11 function expect(bool $cond, string $msg): void
12 {
13 global $failed, $passed;
14 if ($cond) {
15 $passed++;
16 echo " ok $msg\n";
17 } else {
18 $failed++;
19 echo " FAIL $msg\n";
20 }
21 }
22
23 function almostEqual(float $a, float $b, float $eps = 1e-6): bool
24 {
25 return abs($a - $b) <= $eps;
26 }
27
28 $tmp = sys_get_temp_dir() . '/meteors-test-' . bin2hex(random_bytes(6));
29 mkdir($tmp, 0775, true);
30 putenv('METEORS_DATA_DIR=' . $tmp);
31
32 echo "Store: lobby and game\n";
33 $store = Store::open($tmp);
34
35 $a = $store->createLobby('local:test_user_1', 'test_user_1', 0.30);
36 expect(isset($a['id'], $a['code']), 'create lobby returns id and code');
37 expect($a['status'] === 'waiting', 'new lobby is waiting');
38 expect(strlen($a['code']) === 4, 'code is 4 characters');
39 expect(almostEqual((float) $a['miss_chance'], 0.30), 'default miss chance 0.30');
40
41 $view = $store->viewFor('local:test_user_1');
42 expect($view['lobby']['players'][0]['is_host'] === true, 'creator is host');
43 expect($view['lobby']['can_start'] === false, 'cannot start alone');
44
45 try {
46 $store->startGame('local:test_user_1');
47 expect(false, 'start alone should throw');
48 } catch (RuntimeException $e) {
49 expect(str_contains($e->getMessage(), 'twee'), 'start alone is refused: ' . $e->getMessage());
50 }
51
52 $joined = $store->joinLobby('local:test_user_2', 'test_user_2', $a['code']);
53 expect($joined['id'] === $a['id'], 'second player joins by code');
54 $view = $store->viewFor('local:test_user_1');
55 expect(count($view['lobby']['players']) === 2, 'two players in lobby');
56 expect($view['lobby']['can_start'] === false, 'cannot start until both ready');
57
58 $store->setReady('local:test_user_1', true);
59 $store->setReady('local:test_user_2', true);
60 $view = $store->viewFor('local:test_user_1');
61 expect($view['lobby']['all_ready'] === true, 'all ready');
62 expect($view['lobby']['can_start'] === true, 'host can start when all ready and 2+');
63
64 $view2 = $store->viewFor('local:test_user_2');
65 expect($view2['lobby']['can_start'] === false, 'non-host cannot start');
66
67 try {
68 $store->startGame('local:test_user_2');
69 expect(false, 'non-host start should throw');
70 } catch (RuntimeException $e) {
71 expect(str_contains($e->getMessage(), 'host'), 'non-host start refused');
72 }
73
74 $started = $store->startGame('local:test_user_1');
75 expect($started['status'] === 'playing', 'game starts');
76
77 // Shots: force miss by using miss_chance 1.0 on a fresh lobby later.
78 // Here miss is 0.30 — fire many shots and check some hits and some misses, or set chance.
79 $results = $store->recordShots('local:test_user_1', [
80 ['client_id' => 'c1', 'color' => 2],
81 ['client_id' => 'c2', 'color' => -1],
82 ]);
83 expect(count($results) === 2, 'two shot results');
84 expect(isset($results[0]['miss'], $results[0]['flight_duration']), 'result has miss and duration');
85 expect(almostEqual($results[0]['flight_duration'], METEORS_FLIGHT_DURATION), 'flight duration 1.2');
86
87 // Incoming is delayed until deliver_at.
88 $inc = $store->viewFor('local:test_user_2');
89 $hits = array_filter($results, fn ($r) => !$r['miss']);
90 if ($hits) {
91 expect(count($inc['incoming']) === 0, 'incoming not delivered before flight duration');
92 } else {
93 expect(true, 'all missed — no incoming expected');
94 }
95
96 // Fast-forward: rewrite deliver_at in the sqlite file.
97 $pdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
98 $pdo->exec('UPDATE shots SET deliver_at = 0 WHERE to_user = "local:test_user_2"');
99 $inc = $store->viewFor('local:test_user_2');
100 $expectedHits = count($hits);
101 expect(count($inc['incoming']) === $expectedHits, 'incoming delivered after deliver_at (' . count($inc['incoming']) . " vs $expectedHits)");
102 $inc2 = $store->viewFor('local:test_user_2');
103 expect(count($inc2['incoming']) === 0, 'incoming is delivered only once');
104
105 // Elimination and podium.
106 $store->updateSnapshot('local:test_user_2', ['score' => 3, 'blocks' => []], 3, true);
107 $view = $store->viewFor('local:test_user_1');
108 expect($view['lobby']['status'] === 'finished', 'game finishes when one remains');
109 $ranks = $view['lobby']['rankings'];
110 expect(count($ranks) >= 2, 'rankings present');
111 $first = $ranks[0];
112 expect($first['place'] === 1 && $first['id'] === 'local:test_user_1', 'survivor is 1st');
113 $second = $ranks[1];
114 expect($second['place'] === 2 && $second['id'] === 'local:test_user_2', 'eliminated is 2nd');
115
116 // Podium wait: not yet reset.
117 $view = $store->viewFor('local:test_user_1');
118 expect($view['lobby']['status'] === 'finished', 'still finished during podium');
119
120 $pdo->exec('UPDATE lobbies SET finished = ' . (time() - 6));
121 $view = $store->viewFor('local:test_user_1');
122 expect($view['lobby']['status'] === 'waiting', 'back to lobby after podium seconds');
123 expect($view['lobby']['players'][0]['ready'] === false, 'ready flags reset');
124
125 // Host leave transfers host.
126 $store->leaveLobby('local:test_user_1');
127 $view = $store->viewFor('local:test_user_2');
128 expect($view['lobby']['host_id'] === 'local:test_user_2', 'host transfers to remaining player');
129
130 // Mid-game leave counts as elimination.
131 $store->leaveLobby('local:test_user_2');
132 $b = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
133 $store->joinLobby('local:test_user_2', 'test_user_2', $b['code']);
134 $store->setReady('local:test_user_1', true);
135 $store->setReady('local:test_user_2', true);
136 $store->startGame('local:test_user_1');
137 $store->leaveLobby('local:test_user_2');
138 $view = $store->viewFor('local:test_user_1');
139 expect($view['lobby']['status'] === 'finished', 'leave mid-game finishes if one remains');
140 expect($view['lobby']['rankings'][0]['id'] === 'local:test_user_1', 'stayer wins');
141
142 // Miss chance 1.0: all miss. Need a fresh game with 2 players.
143 // Leave leftover memberships.
144 $store->leaveLobby('local:test_user_1');
145 $c = $store->createLobby('local:test_user_1', 'test_user_1', 1.0);
146 $store->joinLobby('local:test_user_2', 'test_user_2', $c['code']);
147 $store->setReady('local:test_user_1', true);
148 $store->setReady('local:test_user_2', true);
149 $store->startGame('local:test_user_1');
150 $allMiss = $store->recordShots('local:test_user_1', [
151 ['client_id' => 'm1', 'color' => 0],
152 ['client_id' => 'm2', 'color' => 1],
153 ['client_id' => 'm3', 'color' => 2],
154 ]);
155 expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'miss_chance 1.0 → all miss');
156
157 $d = null;
158 $store->leaveLobby('local:test_user_1');
159 $store->leaveLobby('local:test_user_2');
160 $d = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
161 $store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);
162 $store->setReady('local:test_user_1', true);
163 $store->setReady('local:test_user_2', true);
164 $store->startGame('local:test_user_1');
165 $allHit = $store->recordShots('local:test_user_1', [
166 ['client_id' => 'h1', 'color' => 0],
167 ['client_id' => 'h2', 'color' => 1],
168 ]);
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');
170
171 // Eliminated player is not a target.
172 $store->updateSnapshot('local:test_user_2', null, 0, true);
173 $none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' => 0]]);
174 // Game may already be finished; recordShots on finished returns [].
175 expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');
176
177 echo "\nConfig helpers\n";
178 $cfg = config();
179 expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
180 expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
181 expect($cfg['client_secret'] === '', 'secret starts empty (Tim must fill it in)');
182 expect(authConfigured() === false, 'auth is unconfigured without a secret');
183 putenv('METEORS_CLIENT_SECRET=test-secret-value');
184 // config file empty secret falls back to env
185 $cfg2 = config();
186 expect($cfg2['client_secret'] === 'test-secret-value', 'empty file field falls back to env');
187 putenv('METEORS_CLIENT_SECRET');
188
189 echo "\n$passed passed, $failed failed\n";
190
191 // cleanup
192 $files = new RecursiveIteratorIterator(
193 new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS),
194 RecursiveIteratorIterator::CHILD_FIRST
195 );
196 foreach ($files as $f) {
197 $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());
198 }
199 @rmdir($tmp);
200
201 exit($failed === 0 ? 0 : 1);
@@ -0,0 +1,201 @@
1<?php
2declare(strict_types=1);
3// php server/tests/run.php
4define('METEORS_NO_SESSION', true);
5require dirname(__DIR__) . '/lib/bootstrap.php';
6require dirname(__DIR__) . '/lib/Store.php';
7
8$failed = 0;
9$passed = 0;
10
11function expect(bool $cond, string $msg): void
12{
13 global $failed, $passed;
14 if ($cond) {
15 $passed++;
16 echo " ok $msg\n";
17 } else {
18 $failed++;
19 echo " FAIL $msg\n";
20 }
21}
22
23function almostEqual(float $a, float $b, float $eps = 1e-6): bool
24{
25 return abs($a - $b) <= $eps;
26}
27
28$tmp = sys_get_temp_dir() . '/meteors-test-' . bin2hex(random_bytes(6));
29mkdir($tmp, 0775, true);
30putenv('METEORS_DATA_DIR=' . $tmp);
31
32echo "Store: lobby and game\n";
33$store = Store::open($tmp);
34
35$a = $store->createLobby('local:test_user_1', 'test_user_1', 0.30);
36expect(isset($a['id'], $a['code']), 'create lobby returns id and code');
37expect($a['status'] === 'waiting', 'new lobby is waiting');
38expect(strlen($a['code']) === 4, 'code is 4 characters');
39expect(almostEqual((float) $a['miss_chance'], 0.30), 'default miss chance 0.30');
40
41$view = $store->viewFor('local:test_user_1');
42expect($view['lobby']['players'][0]['is_host'] === true, 'creator is host');
43expect($view['lobby']['can_start'] === false, 'cannot start alone');
44
45try {
46 $store->startGame('local:test_user_1');
47 expect(false, 'start alone should throw');
48} catch (RuntimeException $e) {
49 expect(str_contains($e->getMessage(), 'twee'), 'start alone is refused: ' . $e->getMessage());
50}
51
52$joined = $store->joinLobby('local:test_user_2', 'test_user_2', $a['code']);
53expect($joined['id'] === $a['id'], 'second player joins by code');
54$view = $store->viewFor('local:test_user_1');
55expect(count($view['lobby']['players']) === 2, 'two players in lobby');
56expect($view['lobby']['can_start'] === false, 'cannot start until both ready');
57
58$store->setReady('local:test_user_1', true);
59$store->setReady('local:test_user_2', true);
60$view = $store->viewFor('local:test_user_1');
61expect($view['lobby']['all_ready'] === true, 'all ready');
62expect($view['lobby']['can_start'] === true, 'host can start when all ready and 2+');
63
64$view2 = $store->viewFor('local:test_user_2');
65expect($view2['lobby']['can_start'] === false, 'non-host cannot start');
66
67try {
68 $store->startGame('local:test_user_2');
69 expect(false, 'non-host start should throw');
70} catch (RuntimeException $e) {
71 expect(str_contains($e->getMessage(), 'host'), 'non-host start refused');
72}
73
74$started = $store->startGame('local:test_user_1');
75expect($started['status'] === 'playing', 'game starts');
76
77// Shots: force miss by using miss_chance 1.0 on a fresh lobby later.
78// Here miss is 0.30 — fire many shots and check some hits and some misses, or set chance.
79$results = $store->recordShots('local:test_user_1', [
80 ['client_id' => 'c1', 'color' => 2],
81 ['client_id' => 'c2', 'color' => -1],
82]);
83expect(count($results) === 2, 'two shot results');
84expect(isset($results[0]['miss'], $results[0]['flight_duration']), 'result has miss and duration');
85expect(almostEqual($results[0]['flight_duration'], METEORS_FLIGHT_DURATION), 'flight duration 1.2');
86
87// Incoming is delayed until deliver_at.
88$inc = $store->viewFor('local:test_user_2');
89$hits = array_filter($results, fn ($r) => !$r['miss']);
90if ($hits) {
91 expect(count($inc['incoming']) === 0, 'incoming not delivered before flight duration');
92} else {
93 expect(true, 'all missed — no incoming expected');
94}
95
96// Fast-forward: rewrite deliver_at in the sqlite file.
97$pdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
98$pdo->exec('UPDATE shots SET deliver_at = 0 WHERE to_user = "local:test_user_2"');
99$inc = $store->viewFor('local:test_user_2');
100$expectedHits = count($hits);
101expect(count($inc['incoming']) === $expectedHits, 'incoming delivered after deliver_at (' . count($inc['incoming']) . " vs $expectedHits)");
102$inc2 = $store->viewFor('local:test_user_2');
103expect(count($inc2['incoming']) === 0, 'incoming is delivered only once');
104
105// Elimination and podium.
106$store->updateSnapshot('local:test_user_2', ['score' => 3, 'blocks' => []], 3, true);
107$view = $store->viewFor('local:test_user_1');
108expect($view['lobby']['status'] === 'finished', 'game finishes when one remains');
109$ranks = $view['lobby']['rankings'];
110expect(count($ranks) >= 2, 'rankings present');
111$first = $ranks[0];
112expect($first['place'] === 1 && $first['id'] === 'local:test_user_1', 'survivor is 1st');
113$second = $ranks[1];
114expect($second['place'] === 2 && $second['id'] === 'local:test_user_2', 'eliminated is 2nd');
115
116// Podium wait: not yet reset.
117$view = $store->viewFor('local:test_user_1');
118expect($view['lobby']['status'] === 'finished', 'still finished during podium');
119
120$pdo->exec('UPDATE lobbies SET finished = ' . (time() - 6));
121$view = $store->viewFor('local:test_user_1');
122expect($view['lobby']['status'] === 'waiting', 'back to lobby after podium seconds');
123expect($view['lobby']['players'][0]['ready'] === false, 'ready flags reset');
124
125// Host leave transfers host.
126$store->leaveLobby('local:test_user_1');
127$view = $store->viewFor('local:test_user_2');
128expect($view['lobby']['host_id'] === 'local:test_user_2', 'host transfers to remaining player');
129
130// Mid-game leave counts as elimination.
131$store->leaveLobby('local:test_user_2');
132$b = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
133$store->joinLobby('local:test_user_2', 'test_user_2', $b['code']);
134$store->setReady('local:test_user_1', true);
135$store->setReady('local:test_user_2', true);
136$store->startGame('local:test_user_1');
137$store->leaveLobby('local:test_user_2');
138$view = $store->viewFor('local:test_user_1');
139expect($view['lobby']['status'] === 'finished', 'leave mid-game finishes if one remains');
140expect($view['lobby']['rankings'][0]['id'] === 'local:test_user_1', 'stayer wins');
141
142// Miss chance 1.0: all miss. Need a fresh game with 2 players.
143// Leave leftover memberships.
144$store->leaveLobby('local:test_user_1');
145$c = $store->createLobby('local:test_user_1', 'test_user_1', 1.0);
146$store->joinLobby('local:test_user_2', 'test_user_2', $c['code']);
147$store->setReady('local:test_user_1', true);
148$store->setReady('local:test_user_2', true);
149$store->startGame('local:test_user_1');
150$allMiss = $store->recordShots('local:test_user_1', [
151 ['client_id' => 'm1', 'color' => 0],
152 ['client_id' => 'm2', 'color' => 1],
153 ['client_id' => 'm3', 'color' => 2],
154]);
155expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'miss_chance 1.0 → all miss');
156
157$d = null;
158$store->leaveLobby('local:test_user_1');
159$store->leaveLobby('local:test_user_2');
160$d = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
161$store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);
162$store->setReady('local:test_user_1', true);
163$store->setReady('local:test_user_2', true);
164$store->startGame('local:test_user_1');
165$allHit = $store->recordShots('local:test_user_1', [
166 ['client_id' => 'h1', 'color' => 0],
167 ['client_id' => 'h2', 'color' => 1],
168]);
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');
170
171// Eliminated player is not a target.
172$store->updateSnapshot('local:test_user_2', null, 0, true);
173$none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' => 0]]);
174// Game may already be finished; recordShots on finished returns [].
175expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');
176
177echo "\nConfig helpers\n";
178$cfg = config();
179expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
180expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
181expect($cfg['client_secret'] === '', 'secret starts empty (Tim must fill it in)');
182expect(authConfigured() === false, 'auth is unconfigured without a secret');
183putenv('METEORS_CLIENT_SECRET=test-secret-value');
184// config file empty secret falls back to env
185$cfg2 = config();
186expect($cfg2['client_secret'] === 'test-secret-value', 'empty file field falls back to env');
187putenv('METEORS_CLIENT_SECRET');
188
189echo "\n$passed passed, $failed failed\n";
190
191// cleanup
192$files = new RecursiveIteratorIterator(
193 new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS),
194 RecursiveIteratorIterator::CHILD_FIRST
195);
196foreach ($files as $f) {
197 $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());
198}
199@rmdir($tmp);
200
201exit($failed === 0 ? 0 : 1);
src/build.sh +18 −0
@@ -1,5 +1,7 @@
1 1 #!/usr/bin/env bash
2 2 # Concatenate game sources into build/game.js, same pattern as raytracer / frameworkv3.
3 # Also copies the PHP API into build/ so a local `php -S` and the FTP deploy
4 # serve the same tree. data/config.php and any sqlite are NEVER copied.
3 5 set -euo pipefail
4 6 ROOT="$(cd "$(dirname "$0")/.." && pwd)"
5 7 BUILD_FILE="$ROOT/build/game.js"
@@ -15,6 +17,7 @@ FILES=(
15 17 "$SRC_DIR/planet.js"
16 18 "$SRC_DIR/easing.js"
17 19 "$SRC_DIR/gameCore.js"
20 "$SRC_DIR/online.js"
18 21 "$SRC_DIR/main.js"
19 22 )
20 23
@@ -38,4 +41,19 @@ do
38 41 printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
39 42 done
40 43
44 # PHP API lives next to the static game so api.php, auth.php and callback.php
45 # share a cookie path. Never copy secrets or the database.
46 SERVER="$ROOT/server"
47 cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
48 "$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
49 "$ROOT/build/"
50 mkdir -p "$ROOT/build/lib"
51 cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" "$ROOT/build/lib/"
52 mkdir -p "$ROOT/build/data"
53 cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
54 # Belt and braces: a leftover local config or db must never enter build/.
55 rm -f "$ROOT/build/data/config.php" "$ROOT/build/data/config.lock"
56 rm -f "$ROOT/build/data/"*.sqlite "$ROOT/build/data/"*.sqlite-journal
57 rm -rf "$ROOT/build/data/sessions"
58
41 59 printf "DONE\n"
@@ -1,5 +1,7 @@
1#!/usr/bin/env bash
1#!/usr/bin/env bash
2# Concatenate game sources into build/game.js, same pattern as raytracer / frameworkv3.
2# Concatenate game sources into build/game.js, same pattern as raytracer / frameworkv3.
3# Also copies the PHP API into build/ so a local `php -S` and the FTP deploy
4# serve the same tree. data/config.php and any sqlite are NEVER copied.
3set -euo pipefail
5set -euo pipefail
4ROOT="$(cd "$(dirname "$0")/.." && pwd)"
6ROOT="$(cd "$(dirname "$0")/.." && pwd)"
5BUILD_FILE="$ROOT/build/game.js"
7BUILD_FILE="$ROOT/build/game.js"
@@ -15,6 +17,7 @@ FILES=(
15 "$SRC_DIR/planet.js"
17 "$SRC_DIR/planet.js"
16 "$SRC_DIR/easing.js"
18 "$SRC_DIR/easing.js"
17 "$SRC_DIR/gameCore.js"
19 "$SRC_DIR/gameCore.js"
20 "$SRC_DIR/online.js"
18 "$SRC_DIR/main.js"
21 "$SRC_DIR/main.js"
19)
22)
20
23
@@ -38,4 +41,19 @@ do
38 printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
41 printf "\n/*\n * End File:\n * %s\n */ \n" "$file" >> "$BUILD_FILE"
39done
42done
40
43
44# PHP API lives next to the static game so api.php, auth.php and callback.php
45# share a cookie path. Never copy secrets or the database.
46SERVER="$ROOT/server"
47cp -f "$SERVER/api.php" "$SERVER/auth.php" "$SERVER/callback.php" \
48 "$SERVER/logout.php" "$SERVER/router.php" "$SERVER/.htaccess" \
49 "$ROOT/build/"
50mkdir -p "$ROOT/build/lib"
51cp -f "$SERVER/lib/bootstrap.php" "$SERVER/lib/Store.php" "$ROOT/build/lib/"
52mkdir -p "$ROOT/build/data"
53cp -f "$SERVER/data/.htaccess" "$ROOT/build/data/.htaccess"
54# Belt and braces: a leftover local config or db must never enter build/.
55rm -f "$ROOT/build/data/config.php" "$ROOT/build/data/config.lock"
56rm -f "$ROOT/build/data/"*.sqlite "$ROOT/build/data/"*.sqlite-journal
57rm -rf "$ROOT/build/data/sessions"
58
41printf "DONE\n"
59printf "DONE\n"
src/gameCore.js +92 −1
@@ -77,6 +77,17 @@ function GameCore (planet, rng)
77 77 this.state = 'playing';
78 78 this.drag = null;
79 79 this.gameOverTime = 0;
80 this.outgoingShots = [];
81 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
82 this.missChance = optsMissChance(arguments);
83 }
84
85 function optsMissChance (args)
86 {
87 // GameCore(planet, rng, missChance) — third arg is optional.
88 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
89 { return Math.max(0, Math.min(1, args[2])); }
90 return GameCore.DEFAULT_MISS_CHANCE;
80 91 }
81 92
82 93 GameCore.COLOR_GRAY = COLOR_GRAY;
@@ -84,6 +95,7 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
84 95 GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
85 96 GameCore.SNAP_Y = SNAP_Y;
86 97 GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
98 GameCore.DEFAULT_MISS_CHANCE = 0.30;
87 99 GameCore.STATE_STILL = STATE_STILL;
88 100 GameCore.STATE_FALLING = STATE_FALLING;
89 101 GameCore.STATE_FLYING = STATE_FLYING;
@@ -1142,9 +1154,88 @@ GameCore.prototype.cullOffTop = function ()
1142 1154 }
1143 1155 for (var i = 0; i < gone.length; i++)
1144 1156 {
1157 var block = gone[i];
1158 this.outgoingShots.push({
1159 id: block.id,
1160 color: block.color,
1161 col: block.col,
1162 y: block.y
1163 });
1145 1164 this.score += 1;
1146 this.removeBlock(gone[i]);
1165 this.removeBlock(block);
1166 }
1167 };
1168
1169 GameCore.prototype.consumeOutgoingShots = function ()
1170 {
1171 var shots = this.outgoingShots;
1172 this.outgoingShots = [];
1173 return shots;
1174 };
1175
1176 /**
1177 * A compact field picture for the multiplayer snapshot (miniatures).
1178 * Includes every block's col, y, color, state and flame.
1179 */
1180 GameCore.prototype.fieldSnapshot = function ()
1181 {
1182 var blocks = [];
1183 for (var i = 0; i < this.blocks.length; i++)
1184 {
1185 var b = this.blocks[i];
1186 blocks.push({
1187 id: b.id,
1188 col: b.col,
1189 y: Math.round(b.y * 1000) / 1000,
1190 color: b.color,
1191 state: b.state,
1192 flame: !!b.flame
1193 });
1147 1194 }
1195 return {
1196 score: this.score,
1197 state: this.state,
1198 width: this.width,
1199 height: this.height,
1200 locked: this.lockedColumnCount(),
1201 blocks: blocks
1202 };
1203 };
1204
1205 /**
1206 * Incoming garbage from another player: a dark-grey block that falls
1207 * normally from the top of an open column. After landing it uses the
1208 * usual 3s settle and then a random colour (landFallingBlock).
1209 * `col` is optional; a random eligible column is used otherwise.
1210 * Returns the new block, or null if every column is locked or full.
1211 */
1212 GameCore.prototype.ingestGarbage = function (col)
1213 {
1214 if (this.state !== 'playing')
1215 { return null; }
1216 var chosen = null;
1217 if (col != null && col >= 0 && col < this.width
1218 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
1219 { chosen = col | 0; }
1220 else
1221 {
1222 var eligible = [];
1223 for (var c = 0; c < this.width; c++)
1224 {
1225 if (this.isColumnLocked(c))
1226 { continue; }
1227 if (this.groundedCount(c) >= this.height)
1228 { continue; }
1229 eligible.push(c);
1230 }
1231 if (!eligible.length)
1232 { return null; }
1233 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1234 }
1235 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
1236 block.vy = -this.planet.fallSpeed;
1237 block.flame = false;
1238 return block;
1148 1239 };
1149 1240
1150 1241 GameCore.prototype.advanceSettle = function (dt)
@@ -77,6 +77,17 @@ function GameCore (planet, rng)
77 this.state = 'playing';
77 this.state = 'playing';
78 this.drag = null;
78 this.drag = null;
79 this.gameOverTime = 0;
79 this.gameOverTime = 0;
80 this.outgoingShots = [];
81 // Stage-2 default; stage 3 replaces this with Planet.missChance (Power).
82 this.missChance = optsMissChance(arguments);
83}
84
85function optsMissChance (args)
86{
87 // GameCore(planet, rng, missChance) — third arg is optional.
88 if (args.length >= 3 && typeof args[2] === 'number' && isFinite(args[2]))
89 { return Math.max(0, Math.min(1, args[2])); }
90 return GameCore.DEFAULT_MISS_CHANCE;
80}
91}
81
92
82GameCore.COLOR_GRAY = COLOR_GRAY;
93GameCore.COLOR_GRAY = COLOR_GRAY;
@@ -84,6 +95,7 @@ GameCore.LAUNCH_PULL = LAUNCH_PULL;
84GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
95GameCore.SWAP_DISTANCE = SWAP_DISTANCE;
85GameCore.SNAP_Y = SNAP_Y;
96GameCore.SNAP_Y = SNAP_Y;
86GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
97GameCore.HORIZONTAL_SLOP = HORIZONTAL_SLOP;
98GameCore.DEFAULT_MISS_CHANCE = 0.30;
87GameCore.STATE_STILL = STATE_STILL;
99GameCore.STATE_STILL = STATE_STILL;
88GameCore.STATE_FALLING = STATE_FALLING;
100GameCore.STATE_FALLING = STATE_FALLING;
89GameCore.STATE_FLYING = STATE_FLYING;
101GameCore.STATE_FLYING = STATE_FLYING;
@@ -1142,9 +1154,88 @@ GameCore.prototype.cullOffTop = function ()
1142 }
1154 }
1143 for (var i = 0; i < gone.length; i++)
1155 for (var i = 0; i < gone.length; i++)
1144 {
1156 {
1157 var block = gone[i];
1158 this.outgoingShots.push({
1159 id: block.id,
1160 color: block.color,
1161 col: block.col,
1162 y: block.y
1163 });
1145 this.score += 1;
1164 this.score += 1;
1146 this.removeBlock(gone[i]);
1165 this.removeBlock(block);
1166 }
1167};
1168
1169GameCore.prototype.consumeOutgoingShots = function ()
1170{
1171 var shots = this.outgoingShots;
1172 this.outgoingShots = [];
1173 return shots;
1174};
1175
1176/**
1177 * A compact field picture for the multiplayer snapshot (miniatures).
1178 * Includes every block's col, y, color, state and flame.
1179 */
1180GameCore.prototype.fieldSnapshot = function ()
1181{
1182 var blocks = [];
1183 for (var i = 0; i < this.blocks.length; i++)
1184 {
1185 var b = this.blocks[i];
1186 blocks.push({
1187 id: b.id,
1188 col: b.col,
1189 y: Math.round(b.y * 1000) / 1000,
1190 color: b.color,
1191 state: b.state,
1192 flame: !!b.flame
1193 });
1147 }
1194 }
1195 return {
1196 score: this.score,
1197 state: this.state,
1198 width: this.width,
1199 height: this.height,
1200 locked: this.lockedColumnCount(),
1201 blocks: blocks
1202 };
1203};
1204
1205/**
1206 * Incoming garbage from another player: a dark-grey block that falls
1207 * normally from the top of an open column. After landing it uses the
1208 * usual 3s settle and then a random colour (landFallingBlock).
1209 * `col` is optional; a random eligible column is used otherwise.
1210 * Returns the new block, or null if every column is locked or full.
1211 */
1212GameCore.prototype.ingestGarbage = function (col)
1213{
1214 if (this.state !== 'playing')
1215 { return null; }
1216 var chosen = null;
1217 if (col != null && col >= 0 && col < this.width
1218 && !this.isColumnLocked(col) && this.groundedCount(col) < this.height)
1219 { chosen = col | 0; }
1220 else
1221 {
1222 var eligible = [];
1223 for (var c = 0; c < this.width; c++)
1224 {
1225 if (this.isColumnLocked(c))
1226 { continue; }
1227 if (this.groundedCount(c) >= this.height)
1228 { continue; }
1229 eligible.push(c);
1230 }
1231 if (!eligible.length)
1232 { return null; }
1233 chosen = eligible[Math.floor(this.rng() * eligible.length) % eligible.length];
1234 }
1235 var block = this.createBlock(chosen, this.height, COLOR_GRAY, STATE_FALLING);
1236 block.vy = -this.planet.fallSpeed;
1237 block.flame = false;
1238 return block;
1148};
1239};
1149
1240
1150GameCore.prototype.advanceSettle = function (dt)
1241GameCore.prototype.advanceSettle = function (dt)
src/main.js +455 −15
@@ -3,8 +3,8 @@
3 3 /**
4 4 * View and input for Meteors. The simulation lives in GameCore; this file
5 5 * only draws it, scales it to the viewport, and translates pointer events
6 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
7 * that reuses the same core.
6 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
7 * through Online (src/online.js) and the same GameCore.
8 8 */
9 9
10 10 var IMAGES = [
@@ -42,7 +42,11 @@ var app = {
42 42 cells: [],
43 43 pointerId: null,
44 44 gameOverShown: false,
45 selectTween: null
45 selectTween: null,
46 online: false,
47 eliminatedReported: false,
48 spectating: false,
49 miniH: 0
46 50 };
47 51
48 52 window.onload = function ()
@@ -65,6 +69,8 @@ window.onload = function ()
65 69 if (game.images.flame && game.images.flame.addAnimationCycle)
66 70 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
67 71 });
72
73 bindOnlineUi();
68 74 };
69 75
70 76 function onPlay ()
@@ -74,16 +80,27 @@ function onPlay ()
74 80 startPlay();
75 81 }
76 82
77 function startPlay ()
83 function startPlay (opts)
78 84 {
85 opts = opts || {};
79 86 hideEl('menu');
80 87 hideEl('game-over');
88 hideEl('online-panel');
89 hideEl('spectator');
90 hideEl('podium');
81 91 showEl('hud');
82 92
83 93 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
84 app.core = new GameCore(app.planet, Math.random);
94 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); }
85 99 app.mode = 'playing';
100 app.online = !!opts.online;
86 101 app.gameOverShown = false;
102 app.eliminatedReported = false;
103 app.spectating = false;
87 104 app.sprites = Object.create(null);
88 105 app.flames = Object.create(null);
89 106 app.cells = [];
@@ -91,6 +108,11 @@ function startPlay ()
91 108 app.selectTween = null;
92 109
93 110 layout();
111 if (app.scene)
112 {
113 app.scene.destroy();
114 app.scene = null;
115 }
94 116 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
95 117 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
96 118 app.scene.renderBackground = true;
@@ -98,11 +120,16 @@ function startPlay ()
98 120
99 121 buildCells();
100 122 app.manager = app.scene.addObject(makeManager());
101 bindPointer(app.scene.canvas);
123 if (!app.spectating)
124 { bindPointer(app.scene.canvas); }
102 125 refreshHud();
126 if (app.online)
127 { showEl('minis'); }
128 else
129 { hideEl('minis'); }
103 130 }
104 131
105 function returnToMenu ()
132 function teardownPlay ()
106 133 {
107 134 unbindPointer();
108 135 if (app.scene)
@@ -112,14 +139,31 @@ function returnToMenu ()
112 139 }
113 140 app.manager = null;
114 141 app.core = null;
115 app.mode = 'menu';
116 142 app.sprites = Object.create(null);
117 143 app.flames = Object.create(null);
118 144 app.cells = [];
119 145 app.selectTween = null;
120
146 app.pointerId = null;
147 app.gameOverShown = false;
121 148 hideEl('hud');
122 149 hideEl('game-over');
150 hideEl('spectator');
151 hideEl('minis');
152 if (typeof Online !== 'undefined')
153 { Online.clearFlights(); }
154 }
155
156 function returnToMenu ()
157 {
158 if (app.online && typeof Online !== 'undefined')
159 {
160 // Online matches do not dump you back to the solo menu:
161 // elimination becomes spectating; a finished match shows the podium.
162 return;
163 }
164 teardownPlay();
165 app.mode = 'menu';
166 app.online = false;
123 167 showEl('menu');
124 168 var last = document.getElementById('last-score');
125 169 if (app.lastScore > 0)
@@ -167,16 +211,26 @@ function layout ()
167 211 }
168 212 catch (e) { /* ignore */ }
169 213 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
214 app.miniH = 0;
215 if (app.online)
216 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
170 217 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
171 218 var availW = Math.max(80, vw - margin * 2);
172 var availH = Math.max(80, vh - app.hudH - margin);
219 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
173 220 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
174 221 app.fieldW = app.tile * 10;
175 222 app.fieldH = app.tile * 13;
176 223 app.fieldX = Math.floor((vw - app.fieldW) / 2);
177 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
178 if (app.fieldY < app.hudH)
179 { app.fieldY = app.hudH; }
224 var topBand = app.hudH + app.miniH;
225 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
226 if (app.fieldY < topBand)
227 { app.fieldY = topBand; }
228 var minis = document.getElementById('minis');
229 if (minis)
230 {
231 minis.style.top = app.hudH + 'px';
232 minis.style.maxHeight = app.miniH + 'px';
233 }
180 234
181 235 if (app.scene)
182 236 {
@@ -388,15 +442,19 @@ function tickView (dt)
388 442 updateSelectTween(dt);
389 443 syncSprites();
390 444 refreshHud();
445 tickOnline(dt);
391 446
392 447 if (app.core.state === 'gameover' && !app.gameOverShown)
393 448 {
394 449 app.gameOverShown = true;
395 450 app.lastScore = app.core.score;
396 451 document.getElementById('go-score').textContent = String(app.lastScore);
397 showEl('game-over');
452 if (app.online)
453 { onOnlineEliminated(); }
454 else
455 { showEl('game-over'); }
398 456 }
399 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
457 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
400 458 { returnToMenu(); }
401 459 }
402 460
@@ -544,3 +602,385 @@ window.addEventListener('orientationchange', function ()
544 602 { layout(); }
545 603 }, 120);
546 604 });
605
606 /* ---------- online play (stage 2) ---------------------------------- */
607
608 function tickOnline (dt)
609 {
610 if (!app.online || typeof Online === 'undefined')
611 { return; }
612 if (app.core)
613 {
614 var shots = app.core.consumeOutgoingShots();
615 for (var i = 0; i < shots.length; i++)
616 {
617 var s = shots[i];
618 var start = fieldToViewport(s.col, s.y + 1);
619 Online.rememberFlightLocal(s, start.x, start.y);
620 }
621 Online.queueShots(shots);
622 }
623 Online.tickFlights();
624 Online.renderMinis(document.getElementById('minis'));
625 }
626
627 function fieldToViewport (col, fieldY)
628 {
629 var canvas = app.scene && app.scene.canvas;
630 if (!canvas)
631 { return { x: window.innerWidth / 2, y: 40 }; }
632 var rect = canvas.getBoundingClientRect();
633 var x = rect.left + ((col + 0.5) / 10) * rect.width;
634 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
635 return { x: x, y: y };
636 }
637
638 function onlinePayload ()
639 {
640 if (!app.online || !app.core)
641 { return {}; }
642 return {
643 snapshot: app.core.fieldSnapshot(),
644 score: app.core.score,
645 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
646 };
647 }
648
649 function onOnlineEliminated ()
650 {
651 app.eliminatedReported = true;
652 app.spectating = true;
653 unbindPointer();
654 hideEl('game-over');
655 var lobby = typeof Online !== 'undefined' && Online.lobby;
656 if (lobby && lobby.status === 'finished')
657 {
658 showPodium(lobby);
659 return;
660 }
661 showEl('spectator');
662 }
663
664 function showPodium (lobby)
665 {
666 hideEl('spectator');
667 hideEl('game-over');
668 hideEl('online-panel');
669 showEl('podium');
670 var list = document.getElementById('podium-list');
671 list.innerHTML = '';
672 var ranks = (lobby && lobby.rankings) || [];
673 for (var i = 0; i < ranks.length; i++)
674 {
675 var r = ranks[i];
676 var li = document.createElement('li');
677 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
678 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
679 list.appendChild(li);
680 }
681 var hint = document.getElementById('podium-hint');
682 var secs = (lobby && lobby.podium_seconds) || 5;
683 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
684 }
685
686 function startOnlineMatch ()
687 {
688 if (app.mode === 'playing' && app.online)
689 { 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 });
694 if (typeof Online !== 'undefined')
695 { Online.startPolling(onlinePayload); }
696 }
697
698 function leaveOnlineMatch (goMenu)
699 {
700 if (typeof Online !== 'undefined')
701 {
702 Online.stopPolling();
703 Online.leaveLobby();
704 Online.clearFlights();
705 }
706 teardownPlay();
707 app.online = false;
708 if (goMenu)
709 {
710 app.mode = 'menu';
711 showEl('menu');
712 }
713 else
714 {
715 app.mode = 'online';
716 openOnlinePanel();
717 }
718 }
719
720 function bindOnlineUi ()
721 {
722 var onlineBtn = document.getElementById('btn-online');
723 if (!onlineBtn)
724 { return; }
725 onlineBtn.addEventListener('click', function ()
726 { openOnlinePanel(); });
727
728 var backs = document.querySelectorAll('[data-back-menu]');
729 for (var i = 0; i < backs.length; i++)
730 {
731 backs[i].addEventListener('click', function ()
732 {
733 if (typeof Online !== 'undefined')
734 { Online.stopPolling(); }
735 hideEl('online-panel');
736 app.mode = 'menu';
737 app.online = false;
738 showEl('menu');
739 });
740 }
741
742 document.getElementById('btn-create').addEventListener('click', function ()
743 {
744 Online.createLobby().then(function (data)
745 {
746 if (data && data.ok)
747 {
748 renderOnline();
749 Online.startPolling(onlinePayload);
750 }
751 else
752 { renderOnline(); }
753 });
754 });
755
756 document.getElementById('join-form').addEventListener('submit', function (e)
757 {
758 e.preventDefault();
759 var code = (document.getElementById('join-code').value || '').trim();
760 if (!code)
761 { return; }
762 Online.joinLobby(code).then(function ()
763 {
764 renderOnline();
765 if (Online.lobby)
766 { Online.startPolling(onlinePayload); }
767 });
768 });
769
770 document.getElementById('btn-ready').addEventListener('click', function ()
771 {
772 var me = Online.mePlayer();
773 Online.setReady(!(me && me.ready)).then(renderOnline);
774 });
775
776 document.getElementById('btn-start').addEventListener('click', function ()
777 {
778 Online.startGame().then(function (data)
779 {
780 if (data && data.ok)
781 { startOnlineMatch(); }
782 else
783 { renderOnline(); }
784 });
785 });
786
787 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
788 {
789 Online.leaveLobby().then(function ()
790 {
791 Online.stopPolling();
792 renderOnline();
793 });
794 });
795
796 document.getElementById('btn-copy-code').addEventListener('click', function ()
797 {
798 var code = document.getElementById('lobby-code').textContent;
799 if (navigator.clipboard && navigator.clipboard.writeText)
800 { navigator.clipboard.writeText(code); }
801 });
802
803 document.getElementById('btn-spectate').addEventListener('click', function ()
804 {
805 hideEl('spectator');
806 app.spectating = true;
807 });
808
809 document.getElementById('btn-leave-game').addEventListener('click', function ()
810 { leaveOnlineMatch(false); });
811
812 if (typeof Online !== 'undefined')
813 {
814 Online.onChange = function ()
815 { renderOnline(); };
816 Online.onGameStart = function ()
817 { startOnlineMatch(); };
818 Online.onIncoming = function (incoming)
819 {
820 if (!app.core || app.core.state !== 'playing')
821 { return; }
822 for (var i = 0; i < incoming.length; i++)
823 { app.core.ingestGarbage(); }
824 };
825 Online.onFinished = function (lobby)
826 { showPodium(lobby); };
827 Online.onLobbyReturn = function (lobby)
828 {
829 teardownPlay();
830 app.online = false;
831 app.mode = 'online';
832 hideEl('podium');
833 showEl('online-panel');
834 renderOnline();
835 Online.startPolling(onlinePayload);
836 };
837 }
838
839 var params = new URLSearchParams(window.location.search);
840 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
841 { openOnlinePanel(); }
842 }
843
844 function openOnlinePanel ()
845 {
846 hideEl('menu');
847 hideEl('game-over');
848 hideEl('podium');
849 hideEl('spectator');
850 showEl('online-panel');
851 app.mode = 'online';
852 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
853 if (typeof Online === 'undefined')
854 {
855 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
856 showOnly('online-unconfigured');
857 return;
858 }
859 Online.refresh().then(function (data)
860 {
861 if (!data || data.ok === false)
862 {
863 var msg = (data && data.error) || 'Geen verbinding met de server.';
864 showOnlineError(msg + ' Je kunt wel alleen spelen.');
865 if (data && data.configured === false)
866 { showOnly('online-unconfigured'); }
867 else
868 { showOnly('online-login'); }
869 document.getElementById('btn-login').style.display = 'none';
870 return;
871 }
872 renderOnline();
873 if (Online.lobby)
874 { Online.startPolling(onlinePayload); }
875 });
876 }
877
878 function setOnlineStatus (text)
879 {
880 var el = document.getElementById('online-status');
881 if (el)
882 { el.textContent = text; }
883 }
884
885 function showOnlineError (text)
886 {
887 var el = document.getElementById('online-error');
888 if (!el)
889 { return; }
890 if (!text)
891 {
892 el.hidden = true;
893 el.textContent = '';
894 return;
895 }
896 el.hidden = false;
897 el.textContent = text;
898 }
899
900 function showOnly (id)
901 {
902 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
903 for (var i = 0; i < ids.length; i++)
904 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
905 }
906
907 function renderOnline ()
908 {
909 if (typeof Online === 'undefined')
910 { return; }
911 if (app.mode === 'playing' && app.online)
912 {
913 Online.renderMinis(document.getElementById('minis'));
914 if (Online.lobby && Online.lobby.status === 'finished')
915 { showPodium(Online.lobby); }
916 return;
917 }
918 showOnlineError(Online.error);
919 if (!Online.configured && !Online.me && !Online.local)
920 {
921 setOnlineStatus('Online spelen is nog niet ingesteld.');
922 showOnly('online-unconfigured');
923 return;
924 }
925 if (!Online.me)
926 {
927 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
928 showOnly('online-login');
929 document.getElementById('btn-login').style.display = '';
930 document.getElementById('btn-login').href = Online.loginUrl();
931 document.getElementById('local-login').hidden = !Online.local;
932 return;
933 }
934 if (Online.lobby)
935 {
936 setOnlineStatus('Lobby');
937 showOnly('online-lobby');
938 document.getElementById('lobby-me-name').textContent = Online.me.name;
939 document.getElementById('lobby-code').textContent = Online.lobby.code;
940 var list = document.getElementById('lobby-players');
941 list.innerHTML = '';
942 var players = Online.lobby.players || [];
943 for (var i = 0; i < players.length; i++)
944 {
945 var p = players[i];
946 var li = document.createElement('li');
947 if (p.is_me)
948 { li.classList.add('you'); }
949 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
950 var state = p.ready ? 'Gereed' : 'Wacht…';
951 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
952 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
953 list.appendChild(li);
954 }
955 var me = Online.mePlayer();
956 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
957 var start = document.getElementById('btn-start');
958 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
959 start.disabled = !Online.lobby.can_start;
960 var hint = document.getElementById('lobby-hint');
961 if (Online.lobby.status === 'playing')
962 { hint.textContent = 'Het spel start…'; }
963 else if (players.length < 2)
964 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
965 else if (!Online.lobby.all_ready)
966 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
967 else if (Online.lobby.can_start)
968 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
969 else
970 { hint.textContent = 'Wachten tot de host start.'; }
971 return;
972 }
973 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
974 showOnly('online-home');
975 document.getElementById('me-name').textContent = Online.me.name;
976 document.getElementById('local-login').hidden = !Online.local;
977 }
978
979 function escapeText (s)
980 {
981 return String(s)
982 .replace(/&/g, '&amp;')
983 .replace(/</g, '&lt;')
984 .replace(/>/g, '&gt;')
985 .replace(/"/g, '&quot;');
986 }
@@ -3,8 +3,8 @@
3/**
3/**
4 * View and input for Meteors. The simulation lives in GameCore; this file
4 * View and input for Meteors. The simulation lives in GameCore; this file
5 * only draws it, scales it to the viewport, and translates pointer events
5 * only draws it, scales it to the viewport, and translates pointer events
6 * into beginDrag / moveDrag / endDrag. Ready for a later multiplayer view
6 * into beginDrag / moveDrag / endDrag. Online play (stage 2) is wired
7 * that reuses the same core.
7 * through Online (src/online.js) and the same GameCore.
8 */
8 */
9
9
10var IMAGES = [
10var IMAGES = [
@@ -42,7 +42,11 @@ var app = {
42 cells: [],
42 cells: [],
43 pointerId: null,
43 pointerId: null,
44 gameOverShown: false,
44 gameOverShown: false,
45 selectTween: null
45 selectTween: null,
46 online: false,
47 eliminatedReported: false,
48 spectating: false,
49 miniH: 0
46};
50};
47
51
48window.onload = function ()
52window.onload = function ()
@@ -65,6 +69,8 @@ window.onload = function ()
65 if (game.images.flame && game.images.flame.addAnimationCycle)
69 if (game.images.flame && game.images.flame.addAnimationCycle)
66 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
70 { game.images.flame.addAnimationCycle('burn', [0, 1, 2, 3], true); }
67 });
71 });
72
73 bindOnlineUi();
68};
74};
69
75
70function onPlay ()
76function onPlay ()
@@ -74,16 +80,27 @@ function onPlay ()
74 startPlay();
80 startPlay();
75}
81}
76
82
77function startPlay ()
83function startPlay (opts)
78{
84{
85 opts = opts || {};
79 hideEl('menu');
86 hideEl('menu');
80 hideEl('game-over');
87 hideEl('game-over');
88 hideEl('online-panel');
89 hideEl('spectator');
90 hideEl('podium');
81 showEl('hud');
91 showEl('hud');
82
92
83 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
93 app.planet = (typeof Planet !== 'undefined' ? Planet.defaultPlanet() : PlanetMod.defaultPlanet());
84 app.core = new GameCore(app.planet, Math.random);
94 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); }
85 app.mode = 'playing';
99 app.mode = 'playing';
100 app.online = !!opts.online;
86 app.gameOverShown = false;
101 app.gameOverShown = false;
102 app.eliminatedReported = false;
103 app.spectating = false;
87 app.sprites = Object.create(null);
104 app.sprites = Object.create(null);
88 app.flames = Object.create(null);
105 app.flames = Object.create(null);
89 app.cells = [];
106 app.cells = [];
@@ -91,6 +108,11 @@ function startPlay ()
91 app.selectTween = null;
108 app.selectTween = null;
92
109
93 layout();
110 layout();
111 if (app.scene)
112 {
113 app.scene.destroy();
114 app.scene = null;
115 }
94 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
116 app.scene = new Scene(app.fieldX, app.fieldY, app.fieldW, app.fieldH);
95 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
117 app.scene.backgroundColor = { r: 12, g: 16, b: 32 };
96 app.scene.renderBackground = true;
118 app.scene.renderBackground = true;
@@ -98,11 +120,16 @@ function startPlay ()
98
120
99 buildCells();
121 buildCells();
100 app.manager = app.scene.addObject(makeManager());
122 app.manager = app.scene.addObject(makeManager());
101 bindPointer(app.scene.canvas);
123 if (!app.spectating)
124 { bindPointer(app.scene.canvas); }
102 refreshHud();
125 refreshHud();
126 if (app.online)
127 { showEl('minis'); }
128 else
129 { hideEl('minis'); }
103}
130}
104
131
105function returnToMenu ()
132function teardownPlay ()
106{
133{
107 unbindPointer();
134 unbindPointer();
108 if (app.scene)
135 if (app.scene)
@@ -112,14 +139,31 @@ function returnToMenu ()
112 }
139 }
113 app.manager = null;
140 app.manager = null;
114 app.core = null;
141 app.core = null;
115 app.mode = 'menu';
116 app.sprites = Object.create(null);
142 app.sprites = Object.create(null);
117 app.flames = Object.create(null);
143 app.flames = Object.create(null);
118 app.cells = [];
144 app.cells = [];
119 app.selectTween = null;
145 app.selectTween = null;
120
146 app.pointerId = null;
147 app.gameOverShown = false;
121 hideEl('hud');
148 hideEl('hud');
122 hideEl('game-over');
149 hideEl('game-over');
150 hideEl('spectator');
151 hideEl('minis');
152 if (typeof Online !== 'undefined')
153 { Online.clearFlights(); }
154}
155
156function returnToMenu ()
157{
158 if (app.online && typeof Online !== 'undefined')
159 {
160 // Online matches do not dump you back to the solo menu:
161 // elimination becomes spectating; a finished match shows the podium.
162 return;
163 }
164 teardownPlay();
165 app.mode = 'menu';
166 app.online = false;
123 showEl('menu');
167 showEl('menu');
124 var last = document.getElementById('last-score');
168 var last = document.getElementById('last-score');
125 if (app.lastScore > 0)
169 if (app.lastScore > 0)
@@ -167,16 +211,26 @@ function layout ()
167 }
211 }
168 catch (e) { /* ignore */ }
212 catch (e) { /* ignore */ }
169 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
213 app.hudH = Math.max(56, Math.round(vh * 0.09) + safeTop);
214 app.miniH = 0;
215 if (app.online)
216 { app.miniH = Math.min(150, Math.max(86, Math.round(vh * 0.20))); }
170 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
217 var margin = Math.max(6, Math.round(Math.min(vw, vh) * 0.015));
171 var availW = Math.max(80, vw - margin * 2);
218 var availW = Math.max(80, vw - margin * 2);
172 var availH = Math.max(80, vh - app.hudH - margin);
219 var availH = Math.max(80, vh - app.hudH - app.miniH - margin);
173 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
220 app.tile = Math.max(14, Math.floor(Math.min(availW / 10, availH / 13)));
174 app.fieldW = app.tile * 10;
221 app.fieldW = app.tile * 10;
175 app.fieldH = app.tile * 13;
222 app.fieldH = app.tile * 13;
176 app.fieldX = Math.floor((vw - app.fieldW) / 2);
223 app.fieldX = Math.floor((vw - app.fieldW) / 2);
177 app.fieldY = app.hudH + Math.floor((vh - app.hudH - app.fieldH - margin / 2) / 2);
224 var topBand = app.hudH + app.miniH;
178 if (app.fieldY < app.hudH)
225 app.fieldY = topBand + Math.floor((vh - topBand - app.fieldH - margin / 2) / 2);
179 { app.fieldY = app.hudH; }
226 if (app.fieldY < topBand)
227 { app.fieldY = topBand; }
228 var minis = document.getElementById('minis');
229 if (minis)
230 {
231 minis.style.top = app.hudH + 'px';
232 minis.style.maxHeight = app.miniH + 'px';
233 }
180
234
181 if (app.scene)
235 if (app.scene)
182 {
236 {
@@ -388,15 +442,19 @@ function tickView (dt)
388 updateSelectTween(dt);
442 updateSelectTween(dt);
389 syncSprites();
443 syncSprites();
390 refreshHud();
444 refreshHud();
445 tickOnline(dt);
391
446
392 if (app.core.state === 'gameover' && !app.gameOverShown)
447 if (app.core.state === 'gameover' && !app.gameOverShown)
393 {
448 {
394 app.gameOverShown = true;
449 app.gameOverShown = true;
395 app.lastScore = app.core.score;
450 app.lastScore = app.core.score;
396 document.getElementById('go-score').textContent = String(app.lastScore);
451 document.getElementById('go-score').textContent = String(app.lastScore);
397 showEl('game-over');
452 if (app.online)
453 { onOnlineEliminated(); }
454 else
455 { showEl('game-over'); }
398 }
456 }
399 if (app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
457 if (!app.online && app.core.state === 'gameover' && app.core.gameOverTime >= GAME_OVER_DELAY)
400 { returnToMenu(); }
458 { returnToMenu(); }
401}
459}
402
460
@@ -544,3 +602,385 @@ window.addEventListener('orientationchange', function ()
544 { layout(); }
602 { layout(); }
545 }, 120);
603 }, 120);
546});
604});
605
606/* ---------- online play (stage 2) ---------------------------------- */
607
608function tickOnline (dt)
609{
610 if (!app.online || typeof Online === 'undefined')
611 { return; }
612 if (app.core)
613 {
614 var shots = app.core.consumeOutgoingShots();
615 for (var i = 0; i < shots.length; i++)
616 {
617 var s = shots[i];
618 var start = fieldToViewport(s.col, s.y + 1);
619 Online.rememberFlightLocal(s, start.x, start.y);
620 }
621 Online.queueShots(shots);
622 }
623 Online.tickFlights();
624 Online.renderMinis(document.getElementById('minis'));
625}
626
627function fieldToViewport (col, fieldY)
628{
629 var canvas = app.scene && app.scene.canvas;
630 if (!canvas)
631 { return { x: window.innerWidth / 2, y: 40 }; }
632 var rect = canvas.getBoundingClientRect();
633 var x = rect.left + ((col + 0.5) / 10) * rect.width;
634 var y = rect.top + (1 - (fieldY / 13)) * rect.height;
635 return { x: x, y: y };
636}
637
638function onlinePayload ()
639{
640 if (!app.online || !app.core)
641 { return {}; }
642 return {
643 snapshot: app.core.fieldSnapshot(),
644 score: app.core.score,
645 eliminated: app.core.state === 'gameover' || app.spectating || app.eliminatedReported
646 };
647}
648
649function onOnlineEliminated ()
650{
651 app.eliminatedReported = true;
652 app.spectating = true;
653 unbindPointer();
654 hideEl('game-over');
655 var lobby = typeof Online !== 'undefined' && Online.lobby;
656 if (lobby && lobby.status === 'finished')
657 {
658 showPodium(lobby);
659 return;
660 }
661 showEl('spectator');
662}
663
664function showPodium (lobby)
665{
666 hideEl('spectator');
667 hideEl('game-over');
668 hideEl('online-panel');
669 showEl('podium');
670 var list = document.getElementById('podium-list');
671 list.innerHTML = '';
672 var ranks = (lobby && lobby.rankings) || [];
673 for (var i = 0; i < ranks.length; i++)
674 {
675 var r = ranks[i];
676 var li = document.createElement('li');
677 var medal = r.place === 1 ? '1e' : (r.place === 2 ? '2e' : (r.place === 3 ? '3e' : r.place + 'e'));
678 li.textContent = medal + ' ' + r.name + ' · ' + r.score + ' punten';
679 list.appendChild(li);
680 }
681 var hint = document.getElementById('podium-hint');
682 var secs = (lobby && lobby.podium_seconds) || 5;
683 hint.textContent = 'Over ' + secs + ' seconden teruggaan naar de lobby…';
684}
685
686function startOnlineMatch ()
687{
688 if (app.mode === 'playing' && app.online)
689 { 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 });
694 if (typeof Online !== 'undefined')
695 { Online.startPolling(onlinePayload); }
696}
697
698function leaveOnlineMatch (goMenu)
699{
700 if (typeof Online !== 'undefined')
701 {
702 Online.stopPolling();
703 Online.leaveLobby();
704 Online.clearFlights();
705 }
706 teardownPlay();
707 app.online = false;
708 if (goMenu)
709 {
710 app.mode = 'menu';
711 showEl('menu');
712 }
713 else
714 {
715 app.mode = 'online';
716 openOnlinePanel();
717 }
718}
719
720function bindOnlineUi ()
721{
722 var onlineBtn = document.getElementById('btn-online');
723 if (!onlineBtn)
724 { return; }
725 onlineBtn.addEventListener('click', function ()
726 { openOnlinePanel(); });
727
728 var backs = document.querySelectorAll('[data-back-menu]');
729 for (var i = 0; i < backs.length; i++)
730 {
731 backs[i].addEventListener('click', function ()
732 {
733 if (typeof Online !== 'undefined')
734 { Online.stopPolling(); }
735 hideEl('online-panel');
736 app.mode = 'menu';
737 app.online = false;
738 showEl('menu');
739 });
740 }
741
742 document.getElementById('btn-create').addEventListener('click', function ()
743 {
744 Online.createLobby().then(function (data)
745 {
746 if (data && data.ok)
747 {
748 renderOnline();
749 Online.startPolling(onlinePayload);
750 }
751 else
752 { renderOnline(); }
753 });
754 });
755
756 document.getElementById('join-form').addEventListener('submit', function (e)
757 {
758 e.preventDefault();
759 var code = (document.getElementById('join-code').value || '').trim();
760 if (!code)
761 { return; }
762 Online.joinLobby(code).then(function ()
763 {
764 renderOnline();
765 if (Online.lobby)
766 { Online.startPolling(onlinePayload); }
767 });
768 });
769
770 document.getElementById('btn-ready').addEventListener('click', function ()
771 {
772 var me = Online.mePlayer();
773 Online.setReady(!(me && me.ready)).then(renderOnline);
774 });
775
776 document.getElementById('btn-start').addEventListener('click', function ()
777 {
778 Online.startGame().then(function (data)
779 {
780 if (data && data.ok)
781 { startOnlineMatch(); }
782 else
783 { renderOnline(); }
784 });
785 });
786
787 document.getElementById('btn-leave-lobby').addEventListener('click', function ()
788 {
789 Online.leaveLobby().then(function ()
790 {
791 Online.stopPolling();
792 renderOnline();
793 });
794 });
795
796 document.getElementById('btn-copy-code').addEventListener('click', function ()
797 {
798 var code = document.getElementById('lobby-code').textContent;
799 if (navigator.clipboard && navigator.clipboard.writeText)
800 { navigator.clipboard.writeText(code); }
801 });
802
803 document.getElementById('btn-spectate').addEventListener('click', function ()
804 {
805 hideEl('spectator');
806 app.spectating = true;
807 });
808
809 document.getElementById('btn-leave-game').addEventListener('click', function ()
810 { leaveOnlineMatch(false); });
811
812 if (typeof Online !== 'undefined')
813 {
814 Online.onChange = function ()
815 { renderOnline(); };
816 Online.onGameStart = function ()
817 { startOnlineMatch(); };
818 Online.onIncoming = function (incoming)
819 {
820 if (!app.core || app.core.state !== 'playing')
821 { return; }
822 for (var i = 0; i < incoming.length; i++)
823 { app.core.ingestGarbage(); }
824 };
825 Online.onFinished = function (lobby)
826 { showPodium(lobby); };
827 Online.onLobbyReturn = function (lobby)
828 {
829 teardownPlay();
830 app.online = false;
831 app.mode = 'online';
832 hideEl('podium');
833 showEl('online-panel');
834 renderOnline();
835 Online.startPolling(onlinePayload);
836 };
837 }
838
839 var params = new URLSearchParams(window.location.search);
840 if (params.get('online') === '1' || params.get('auth') === 'unconfigured')
841 { openOnlinePanel(); }
842}
843
844function openOnlinePanel ()
845{
846 hideEl('menu');
847 hideEl('game-over');
848 hideEl('podium');
849 hideEl('spectator');
850 showEl('online-panel');
851 app.mode = 'online';
852 setOnlineStatus('Even kijken of online spelen beschikbaar is…');
853 if (typeof Online === 'undefined')
854 {
855 showOnlineError('Online spelen is in deze build niet geladen. Je kunt wel alleen spelen.');
856 showOnly('online-unconfigured');
857 return;
858 }
859 Online.refresh().then(function (data)
860 {
861 if (!data || data.ok === false)
862 {
863 var msg = (data && data.error) || 'Geen verbinding met de server.';
864 showOnlineError(msg + ' Je kunt wel alleen spelen.');
865 if (data && data.configured === false)
866 { showOnly('online-unconfigured'); }
867 else
868 { showOnly('online-login'); }
869 document.getElementById('btn-login').style.display = 'none';
870 return;
871 }
872 renderOnline();
873 if (Online.lobby)
874 { Online.startPolling(onlinePayload); }
875 });
876}
877
878function setOnlineStatus (text)
879{
880 var el = document.getElementById('online-status');
881 if (el)
882 { el.textContent = text; }
883}
884
885function showOnlineError (text)
886{
887 var el = document.getElementById('online-error');
888 if (!el)
889 { return; }
890 if (!text)
891 {
892 el.hidden = true;
893 el.textContent = '';
894 return;
895 }
896 el.hidden = false;
897 el.textContent = text;
898}
899
900function showOnly (id)
901{
902 var ids = ['online-unconfigured', 'online-login', 'online-home', 'online-lobby'];
903 for (var i = 0; i < ids.length; i++)
904 { document.getElementById(ids[i]).hidden = (ids[i] !== id); }
905}
906
907function renderOnline ()
908{
909 if (typeof Online === 'undefined')
910 { return; }
911 if (app.mode === 'playing' && app.online)
912 {
913 Online.renderMinis(document.getElementById('minis'));
914 if (Online.lobby && Online.lobby.status === 'finished')
915 { showPodium(Online.lobby); }
916 return;
917 }
918 showOnlineError(Online.error);
919 if (!Online.configured && !Online.me && !Online.local)
920 {
921 setOnlineStatus('Online spelen is nog niet ingesteld.');
922 showOnly('online-unconfigured');
923 return;
924 }
925 if (!Online.me)
926 {
927 setOnlineStatus('Log in om een lobby te maken of eraan deel te nemen.');
928 showOnly('online-login');
929 document.getElementById('btn-login').style.display = '';
930 document.getElementById('btn-login').href = Online.loginUrl();
931 document.getElementById('local-login').hidden = !Online.local;
932 return;
933 }
934 if (Online.lobby)
935 {
936 setOnlineStatus('Lobby');
937 showOnly('online-lobby');
938 document.getElementById('lobby-me-name').textContent = Online.me.name;
939 document.getElementById('lobby-code').textContent = Online.lobby.code;
940 var list = document.getElementById('lobby-players');
941 list.innerHTML = '';
942 var players = Online.lobby.players || [];
943 for (var i = 0; i < players.length; i++)
944 {
945 var p = players[i];
946 var li = document.createElement('li');
947 if (p.is_me)
948 { li.classList.add('you'); }
949 var label = p.name + (p.is_host ? ' (host)' : '') + (p.is_me ? ' (jij)' : '');
950 var state = p.ready ? 'Gereed' : 'Wacht…';
951 li.innerHTML = '<span>' + escapeText(label) + '</span><span class="'
952 + (p.ready ? 'ready' : 'waiting') + '">' + state + '</span>';
953 list.appendChild(li);
954 }
955 var me = Online.mePlayer();
956 document.getElementById('btn-ready').textContent = (me && me.ready) ? 'Niet gereed' : 'Gereed';
957 var start = document.getElementById('btn-start');
958 start.hidden = !(Online.lobby && Online.me && Online.lobby.host_id === Online.me.id);
959 start.disabled = !Online.lobby.can_start;
960 var hint = document.getElementById('lobby-hint');
961 if (Online.lobby.status === 'playing')
962 { hint.textContent = 'Het spel start…'; }
963 else if (players.length < 2)
964 { hint.textContent = 'Wacht op minstens één andere speler. Deel de code.'; }
965 else if (!Online.lobby.all_ready)
966 { hint.textContent = 'Iedereen moet op Gereed drukken. De host start daarna.'; }
967 else if (Online.lobby.can_start)
968 { hint.textContent = 'Iedereen is gereed. Druk op Starten.'; }
969 else
970 { hint.textContent = 'Wachten tot de host start.'; }
971 return;
972 }
973 setOnlineStatus('Hoi ' + Online.me.name + '. Maak een lobby of val in met een code.');
974 showOnly('online-home');
975 document.getElementById('me-name').textContent = Online.me.name;
976 document.getElementById('local-login').hidden = !Online.local;
977}
978
979function escapeText (s)
980{
981 return String(s)
982 .replace(/&/g, '&amp;')
983 .replace(/</g, '&lt;')
984 .replace(/>/g, '&gt;')
985 .replace(/"/g, '&quot;');
986}
src/online.js added +522 −0
@@ -0,0 +1,522 @@
1 'use strict';
2
3 /**
4 * Online play: talks to api.php (cookie session), polls lobby and game
5 * state, and draws opponent miniatures plus flying-block tweens.
6 * Real-time sync is not required; a 0.75 s poll is enough.
7 */
8
9 var Online = {
10 POLL_MS: 750,
11 DEFAULT_MISS_CHANCE: 0.30,
12 FLIGHT_DURATION: 1.2,
13 configured: false,
14 local: false,
15 csrf: '',
16 me: null,
17 lobby: null,
18 incoming: [],
19 shotResults: [],
20 error: '',
21 _timer: null,
22 _pendingShots: [],
23 _flights: [],
24 _lastStatus: null,
25 onChange: null,
26 onGameStart: null,
27 onIncoming: null,
28 onFinished: null,
29 onLobbyReturn: null
30 };
31
32 Online._headers = function (json)
33 {
34 var h = { 'Accept': 'application/json' };
35 if (json)
36 { h['Content-Type'] = 'application/json'; }
37 if (this.csrf)
38 { h['X-CSRF-Token'] = this.csrf; }
39 return h;
40 };
41
42 Online._apply = function (data)
43 {
44 if (!data)
45 { return; }
46 if (typeof data.configured === 'boolean')
47 { this.configured = data.configured; }
48 if (typeof data.local === 'boolean')
49 { this.local = data.local; }
50 if (data.csrf)
51 { this.csrf = data.csrf; }
52 if (data.me !== undefined)
53 { this.me = data.me; }
54 if (data.lobby !== undefined)
55 { this.lobby = data.lobby; }
56 if (data.incoming)
57 { this.incoming = data.incoming; }
58 if (data.shot_results)
59 { this.shotResults = data.shot_results; }
60 if (data.miss_chance_default != null)
61 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
62 if (data.flight_duration != null)
63 { this.FLIGHT_DURATION = data.flight_duration; }
64 if (data.error)
65 { this.error = data.error; }
66 else if (data.ok)
67 { this.error = ''; }
68 };
69
70 Online.request = function (action, body)
71 {
72 var self = this;
73 var isGet = action === 'me' || action === '';
74 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
75 var opts = {
76 method: isGet && !body ? 'GET' : 'POST',
77 credentials: 'same-origin',
78 headers: this._headers(!!body || !isGet)
79 };
80 if (opts.method === 'POST')
81 {
82 var payload = body ? Object.assign({ action: action }, body) : { action: action };
83 opts.body = JSON.stringify(payload);
84 }
85 return fetch(url, opts).then(function (res)
86 {
87 return res.json().then(function (data)
88 {
89 data = data || {};
90 if (!res.ok && !data.error)
91 { data.error = 'De server gaf ' + res.status; data.ok = false; }
92 self._apply(data);
93 return data;
94 }, function ()
95 {
96 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
97 self.error = fail.error;
98 return fail;
99 });
100 }).catch(function (err)
101 {
102 var fail = { ok: false, error: 'Geen verbinding met de server.' };
103 self.error = fail.error;
104 return fail;
105 });
106 };
107
108 Online.refresh = function ()
109 {
110 return this.request('me');
111 };
112
113 Online.testLogin = function (who)
114 {
115 return this.request('test_login', { user: who });
116 };
117
118 Online.createLobby = function ()
119 {
120 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
121 };
122
123 Online.joinLobby = function (code)
124 {
125 return this.request('lobby_join', { code: code });
126 };
127
128 Online.leaveLobby = function ()
129 {
130 return this.request('lobby_leave');
131 };
132
133 Online.setReady = function (ready)
134 {
135 return this.request('lobby_ready', { ready: !!ready });
136 };
137
138 Online.startGame = function ()
139 {
140 var self = this;
141 var prev = this.lobby && this.lobby.status;
142 return this.request('lobby_start').then(function (data)
143 {
144 self._handleTransitions(prev, data);
145 return data;
146 });
147 };
148
149 Online.queueShots = function (shots)
150 {
151 for (var i = 0; i < shots.length; i++)
152 {
153 this._pendingShots.push({
154 client_id: String(shots[i].id),
155 color: shots[i].color,
156 col: shots[i].col,
157 y: shots[i].y
158 });
159 }
160 };
161
162 Online.poll = function (opts)
163 {
164 opts = opts || {};
165 var body = {};
166 if (opts.snapshot)
167 { body.snapshot = opts.snapshot; }
168 if (opts.score != null)
169 { body.score = opts.score; }
170 if (opts.eliminated)
171 { body.eliminated = true; }
172 if (this._pendingShots.length)
173 {
174 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
175 }
176 var self = this;
177 var prevStatus = this.lobby && this.lobby.status;
178 return this.request('poll', body).then(function (data)
179 {
180 self._handleTransitions(prevStatus, data);
181 if (self.onChange)
182 { self.onChange(self); }
183 return data;
184 });
185 };
186
187 Online._handleTransitions = function (prevStatus, data)
188 {
189 var lobby = this.lobby;
190 var status = lobby && lobby.status;
191 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
192 { this.onGameStart(lobby); }
193 if (data && data.incoming && data.incoming.length && this.onIncoming)
194 { this.onIncoming(data.incoming); }
195 if (data && data.shot_results && data.shot_results.length)
196 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
197 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
198 { this.onFinished(lobby); }
199 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
200 { this.onLobbyReturn(lobby); }
201 };
202
203 Online.startPolling = function (getPayload)
204 {
205 this.stopPolling();
206 var self = this;
207 var tick = function ()
208 {
209 var payload = getPayload ? getPayload() : {};
210 self.poll(payload);
211 };
212 tick();
213 this._timer = setInterval(tick, this.POLL_MS);
214 };
215
216 Online.stopPolling = function ()
217 {
218 if (this._timer)
219 {
220 clearInterval(this._timer);
221 this._timer = null;
222 }
223 };
224
225 Online.loginUrl = function ()
226 {
227 return 'auth.php';
228 };
229
230 Online.logoutUrl = function ()
231 {
232 return 'logout.php';
233 };
234
235 Online.opponents = function ()
236 {
237 if (!this.lobby || !this.lobby.players)
238 { return []; }
239 return this.lobby.players.filter(function (p) { return !p.is_me; });
240 };
241
242 Online.aliveOpponents = function ()
243 {
244 return this.opponents().filter(function (p) { return !p.eliminated; });
245 };
246
247 Online.mePlayer = function ()
248 {
249 if (!this.lobby || !this.lobby.players)
250 { return null; }
251 for (var i = 0; i < this.lobby.players.length; i++)
252 {
253 if (this.lobby.players[i].is_me)
254 { return this.lobby.players[i]; }
255 }
256 return null;
257 };
258
259 /* ---------- miniatures --------------------------------------------- */
260
261 Online.renderMinis = function (container)
262 {
263 if (!container)
264 { return; }
265 var opponents = this.opponents();
266 var existing = {};
267 var kids = container.querySelectorAll('[data-player]');
268 for (var i = 0; i < kids.length; i++)
269 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
270
271 var seen = Object.create(null);
272 for (var i = 0; i < opponents.length; i++)
273 {
274 var p = opponents[i];
275 seen[p.id] = true;
276 var el = existing[p.id];
277 if (!el)
278 {
279 el = document.createElement('div');
280 el.className = 'mini';
281 el.setAttribute('data-player', p.id);
282 el.innerHTML = '<div class="mini-name"></div>'
283 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
284 + '<div class="mini-meta"></div>';
285 container.appendChild(el);
286 }
287 el.classList.toggle('eliminated', !!p.eliminated);
288 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
289 el.querySelector('.mini-meta').textContent = p.eliminated
290 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
291 : ('Punten ' + (p.score || 0));
292 this._drawMini(el.querySelector('canvas'), p.snapshot);
293 }
294 for (var id in existing)
295 {
296 if (!seen[id])
297 { existing[id].remove(); }
298 }
299 };
300
301 var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
302
303 Online._drawMini = function (canvas, snapshot)
304 {
305 if (!canvas)
306 { return; }
307 var ctx = canvas.getContext('2d');
308 var w = 10;
309 var h = 13;
310 var tw = canvas.width / w;
311 var th = canvas.height / h;
312 ctx.fillStyle = '#0c1020';
313 ctx.fillRect(0, 0, canvas.width, canvas.height);
314 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
315 ctx.lineWidth = 1;
316 for (var c = 0; c <= w; c++)
317 {
318 ctx.beginPath();
319 ctx.moveTo(c * tw + 0.5, 0);
320 ctx.lineTo(c * tw + 0.5, canvas.height);
321 ctx.stroke();
322 }
323 for (var r = 0; r <= h; r++)
324 {
325 ctx.beginPath();
326 ctx.moveTo(0, r * th + 0.5);
327 ctx.lineTo(canvas.width, r * th + 0.5);
328 ctx.stroke();
329 }
330 if (!snapshot || !snapshot.blocks)
331 { return; }
332 var blocks = snapshot.blocks;
333 for (var i = 0; i < blocks.length; i++)
334 {
335 var b = blocks[i];
336 var x = b.col * tw;
337 var y = canvas.height - (b.y + 1) * th;
338 if (b.state === 'locked')
339 { ctx.fillStyle = '#3a3d4a'; }
340 else if (b.color < 0)
341 { ctx.fillStyle = '#5a5d66'; }
342 else
343 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
344 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
345 }
346 };
347
348 Online.miniElement = function (playerId)
349 {
350 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
351 };
352
353 /* ---------- flight tweens ------------------------------------------ */
354
355 function colorSpriteUrl (color)
356 {
357 if (color < 0)
358 { return 'images/block-gray.png'; }
359 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
360 return 'images/block-' + (names[color] || 'gray') + '.png';
361 }
362
363 /**
364 * Animate shot results. `locals` is a map of client_id → {col, y, color,
365 * startX, startY} in viewport pixels, filled by the view just after
366 * consumeOutgoingShots.
367 */
368 Online.spawnFlights = function (results, locals)
369 {
370 locals = locals || this._flightLocals || {};
371 var layer = document.getElementById('flights');
372 if (!layer)
373 { return; }
374 for (var i = 0; i < results.length; i++)
375 {
376 var r = results[i];
377 var meta = locals[r.client_id] || {};
378 var start = this._flightStart(meta.col);
379 var end;
380 var miss = !!r.miss;
381 if (miss)
382 { end = this._missEnd(start); }
383 else
384 { end = this._targetEnd(r.target_id, start); }
385 var el = document.createElement('img');
386 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
387 el.alt = '';
388 el.className = 'flight';
389 layer.appendChild(el);
390 var spin = (Math.random() * 2 - 1) * 720;
391 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
392 this._flights.push({
393 el: el,
394 start: start,
395 end: end,
396 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
397 t0: performance.now(),
398 duration: duration,
399 spin: spin,
400 miss: miss,
401 angle: Math.random() * 360
402 });
403 }
404 this._flightLocals = {};
405 };
406
407 Online.rememberFlightLocal = function (shot, startX, startY)
408 {
409 if (!this._flightLocals)
410 { this._flightLocals = {}; }
411 this._flightLocals[String(shot.id)] = {
412 col: shot.col,
413 y: shot.y,
414 color: shot.color,
415 startX: startX,
416 startY: startY
417 };
418 };
419
420 Online._flightStart = function (col)
421 {
422 var field = document.querySelector('canvas');
423 var appRef = typeof app !== 'undefined' ? app : null;
424 if (appRef && appRef.scene && appRef.scene.canvas)
425 {
426 var canvas = appRef.scene.canvas;
427 var rect = canvas.getBoundingClientRect();
428 var c = col == null ? 4.5 : col;
429 return {
430 x: rect.left + (c + 0.5) * (rect.width / 10),
431 y: rect.top + 4
432 };
433 }
434 if (field)
435 {
436 var rect = field.getBoundingClientRect();
437 return { x: rect.left + rect.width / 2, y: rect.top };
438 }
439 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
440 };
441
442 Online._targetEnd = function (targetId, start)
443 {
444 var el = targetId && this.miniElement(targetId);
445 if (el)
446 {
447 var r = el.getBoundingClientRect();
448 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
449 }
450 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
451 };
452
453 Online._missEnd = function (start)
454 {
455 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
456 return {
457 x: start.x + dx,
458 y: start.y - (120 + Math.random() * 220)
459 };
460 };
461
462 Online._missCtrl = function (start, end)
463 {
464 return {
465 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
466 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
467 };
468 };
469
470 Online._hitCtrl = function (start, end)
471 {
472 return {
473 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
474 y: (start.y + end.y) / 2 - 30
475 };
476 };
477
478 Online.tickFlights = function (now)
479 {
480 now = now || performance.now();
481 var leftover = [];
482 for (var i = 0; i < this._flights.length; i++)
483 {
484 var f = this._flights[i];
485 var u = (now - f.t0) / f.duration;
486 if (u >= 1)
487 {
488 if (f.el && f.el.parentNode)
489 { f.el.parentNode.removeChild(f.el); }
490 continue;
491 }
492 // Quadratic bezier, ease-in so they feel like they recede.
493 var e = u * u;
494 var mt = 1 - e;
495 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
496 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
497 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
498 var angle = f.angle + f.spin * u;
499 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
500 + angle + 'deg) scale(' + scale + ')';
501 f.el.style.opacity = f.miss ? String(1 - e) : '1';
502 leftover.push(f);
503 }
504 this._flights = leftover;
505 };
506
507 Online.clearFlights = function ()
508 {
509 for (var i = 0; i < this._flights.length; i++)
510 {
511 var el = this._flights[i].el;
512 if (el && el.parentNode)
513 { el.parentNode.removeChild(el); }
514 }
515 this._flights = [];
516 this._flightLocals = {};
517 };
518
519 if (typeof globalThis !== 'undefined')
520 { globalThis.Online = Online; }
521 if (typeof module !== 'undefined' && module.exports)
522 { module.exports = Online; }
@@ -0,0 +1,522 @@
1'use strict';
2
3/**
4 * Online play: talks to api.php (cookie session), polls lobby and game
5 * state, and draws opponent miniatures plus flying-block tweens.
6 * Real-time sync is not required; a 0.75 s poll is enough.
7 */
8
9var Online = {
10 POLL_MS: 750,
11 DEFAULT_MISS_CHANCE: 0.30,
12 FLIGHT_DURATION: 1.2,
13 configured: false,
14 local: false,
15 csrf: '',
16 me: null,
17 lobby: null,
18 incoming: [],
19 shotResults: [],
20 error: '',
21 _timer: null,
22 _pendingShots: [],
23 _flights: [],
24 _lastStatus: null,
25 onChange: null,
26 onGameStart: null,
27 onIncoming: null,
28 onFinished: null,
29 onLobbyReturn: null
30};
31
32Online._headers = function (json)
33{
34 var h = { 'Accept': 'application/json' };
35 if (json)
36 { h['Content-Type'] = 'application/json'; }
37 if (this.csrf)
38 { h['X-CSRF-Token'] = this.csrf; }
39 return h;
40};
41
42Online._apply = function (data)
43{
44 if (!data)
45 { return; }
46 if (typeof data.configured === 'boolean')
47 { this.configured = data.configured; }
48 if (typeof data.local === 'boolean')
49 { this.local = data.local; }
50 if (data.csrf)
51 { this.csrf = data.csrf; }
52 if (data.me !== undefined)
53 { this.me = data.me; }
54 if (data.lobby !== undefined)
55 { this.lobby = data.lobby; }
56 if (data.incoming)
57 { this.incoming = data.incoming; }
58 if (data.shot_results)
59 { this.shotResults = data.shot_results; }
60 if (data.miss_chance_default != null)
61 { this.DEFAULT_MISS_CHANCE = data.miss_chance_default; }
62 if (data.flight_duration != null)
63 { this.FLIGHT_DURATION = data.flight_duration; }
64 if (data.error)
65 { this.error = data.error; }
66 else if (data.ok)
67 { this.error = ''; }
68};
69
70Online.request = function (action, body)
71{
72 var self = this;
73 var isGet = action === 'me' || action === '';
74 var url = 'api.php?action=' + encodeURIComponent(action || 'me');
75 var opts = {
76 method: isGet && !body ? 'GET' : 'POST',
77 credentials: 'same-origin',
78 headers: this._headers(!!body || !isGet)
79 };
80 if (opts.method === 'POST')
81 {
82 var payload = body ? Object.assign({ action: action }, body) : { action: action };
83 opts.body = JSON.stringify(payload);
84 }
85 return fetch(url, opts).then(function (res)
86 {
87 return res.json().then(function (data)
88 {
89 data = data || {};
90 if (!res.ok && !data.error)
91 { data.error = 'De server gaf ' + res.status; data.ok = false; }
92 self._apply(data);
93 return data;
94 }, function ()
95 {
96 var fail = { ok: false, error: 'Geen geldig antwoord van de server.' };
97 self.error = fail.error;
98 return fail;
99 });
100 }).catch(function (err)
101 {
102 var fail = { ok: false, error: 'Geen verbinding met de server.' };
103 self.error = fail.error;
104 return fail;
105 });
106};
107
108Online.refresh = function ()
109{
110 return this.request('me');
111};
112
113Online.testLogin = function (who)
114{
115 return this.request('test_login', { user: who });
116};
117
118Online.createLobby = function ()
119{
120 return this.request('lobby_create', { miss_chance: this.DEFAULT_MISS_CHANCE });
121};
122
123Online.joinLobby = function (code)
124{
125 return this.request('lobby_join', { code: code });
126};
127
128Online.leaveLobby = function ()
129{
130 return this.request('lobby_leave');
131};
132
133Online.setReady = function (ready)
134{
135 return this.request('lobby_ready', { ready: !!ready });
136};
137
138Online.startGame = function ()
139{
140 var self = this;
141 var prev = this.lobby && this.lobby.status;
142 return this.request('lobby_start').then(function (data)
143 {
144 self._handleTransitions(prev, data);
145 return data;
146 });
147};
148
149Online.queueShots = function (shots)
150{
151 for (var i = 0; i < shots.length; i++)
152 {
153 this._pendingShots.push({
154 client_id: String(shots[i].id),
155 color: shots[i].color,
156 col: shots[i].col,
157 y: shots[i].y
158 });
159 }
160};
161
162Online.poll = function (opts)
163{
164 opts = opts || {};
165 var body = {};
166 if (opts.snapshot)
167 { body.snapshot = opts.snapshot; }
168 if (opts.score != null)
169 { body.score = opts.score; }
170 if (opts.eliminated)
171 { body.eliminated = true; }
172 if (this._pendingShots.length)
173 {
174 body.outgoing_shots = this._pendingShots.splice(0, this._pendingShots.length);
175 }
176 var self = this;
177 var prevStatus = this.lobby && this.lobby.status;
178 return this.request('poll', body).then(function (data)
179 {
180 self._handleTransitions(prevStatus, data);
181 if (self.onChange)
182 { self.onChange(self); }
183 return data;
184 });
185};
186
187Online._handleTransitions = function (prevStatus, data)
188{
189 var lobby = this.lobby;
190 var status = lobby && lobby.status;
191 if (status === 'playing' && prevStatus !== 'playing' && this.onGameStart)
192 { this.onGameStart(lobby); }
193 if (data && data.incoming && data.incoming.length && this.onIncoming)
194 { this.onIncoming(data.incoming); }
195 if (data && data.shot_results && data.shot_results.length)
196 { this.spawnFlights(data.shot_results, this._lastQueuedMeta); }
197 if (status === 'finished' && prevStatus !== 'finished' && this.onFinished)
198 { this.onFinished(lobby); }
199 if (status === 'waiting' && prevStatus === 'finished' && this.onLobbyReturn)
200 { this.onLobbyReturn(lobby); }
201};
202
203Online.startPolling = function (getPayload)
204{
205 this.stopPolling();
206 var self = this;
207 var tick = function ()
208 {
209 var payload = getPayload ? getPayload() : {};
210 self.poll(payload);
211 };
212 tick();
213 this._timer = setInterval(tick, this.POLL_MS);
214};
215
216Online.stopPolling = function ()
217{
218 if (this._timer)
219 {
220 clearInterval(this._timer);
221 this._timer = null;
222 }
223};
224
225Online.loginUrl = function ()
226{
227 return 'auth.php';
228};
229
230Online.logoutUrl = function ()
231{
232 return 'logout.php';
233};
234
235Online.opponents = function ()
236{
237 if (!this.lobby || !this.lobby.players)
238 { return []; }
239 return this.lobby.players.filter(function (p) { return !p.is_me; });
240};
241
242Online.aliveOpponents = function ()
243{
244 return this.opponents().filter(function (p) { return !p.eliminated; });
245};
246
247Online.mePlayer = function ()
248{
249 if (!this.lobby || !this.lobby.players)
250 { return null; }
251 for (var i = 0; i < this.lobby.players.length; i++)
252 {
253 if (this.lobby.players[i].is_me)
254 { return this.lobby.players[i]; }
255 }
256 return null;
257};
258
259/* ---------- miniatures --------------------------------------------- */
260
261Online.renderMinis = function (container)
262{
263 if (!container)
264 { return; }
265 var opponents = this.opponents();
266 var existing = {};
267 var kids = container.querySelectorAll('[data-player]');
268 for (var i = 0; i < kids.length; i++)
269 { existing[kids[i].getAttribute('data-player')] = kids[i]; }
270
271 var seen = Object.create(null);
272 for (var i = 0; i < opponents.length; i++)
273 {
274 var p = opponents[i];
275 seen[p.id] = true;
276 var el = existing[p.id];
277 if (!el)
278 {
279 el = document.createElement('div');
280 el.className = 'mini';
281 el.setAttribute('data-player', p.id);
282 el.innerHTML = '<div class="mini-name"></div>'
283 + '<canvas class="mini-canvas" width="80" height="104"></canvas>'
284 + '<div class="mini-meta"></div>';
285 container.appendChild(el);
286 }
287 el.classList.toggle('eliminated', !!p.eliminated);
288 el.querySelector('.mini-name').textContent = p.name + (p.is_host ? ' (host)' : '');
289 el.querySelector('.mini-meta').textContent = p.eliminated
290 ? ('Uit' + (p.place ? ' · ' + p.place + 'e' : ''))
291 : ('Punten ' + (p.score || 0));
292 this._drawMini(el.querySelector('canvas'), p.snapshot);
293 }
294 for (var id in existing)
295 {
296 if (!seen[id])
297 { existing[id].remove(); }
298 }
299};
300
301var MINI_COLORS = ['#d4553a', '#3a9ad4', '#4caf6a', '#e6c04a', '#b86ad4'];
302
303Online._drawMini = function (canvas, snapshot)
304{
305 if (!canvas)
306 { return; }
307 var ctx = canvas.getContext('2d');
308 var w = 10;
309 var h = 13;
310 var tw = canvas.width / w;
311 var th = canvas.height / h;
312 ctx.fillStyle = '#0c1020';
313 ctx.fillRect(0, 0, canvas.width, canvas.height);
314 ctx.strokeStyle = 'rgba(255,255,255,0.06)';
315 ctx.lineWidth = 1;
316 for (var c = 0; c <= w; c++)
317 {
318 ctx.beginPath();
319 ctx.moveTo(c * tw + 0.5, 0);
320 ctx.lineTo(c * tw + 0.5, canvas.height);
321 ctx.stroke();
322 }
323 for (var r = 0; r <= h; r++)
324 {
325 ctx.beginPath();
326 ctx.moveTo(0, r * th + 0.5);
327 ctx.lineTo(canvas.width, r * th + 0.5);
328 ctx.stroke();
329 }
330 if (!snapshot || !snapshot.blocks)
331 { return; }
332 var blocks = snapshot.blocks;
333 for (var i = 0; i < blocks.length; i++)
334 {
335 var b = blocks[i];
336 var x = b.col * tw;
337 var y = canvas.height - (b.y + 1) * th;
338 if (b.state === 'locked')
339 { ctx.fillStyle = '#3a3d4a'; }
340 else if (b.color < 0)
341 { ctx.fillStyle = '#5a5d66'; }
342 else
343 { ctx.fillStyle = MINI_COLORS[b.color] || '#888'; }
344 ctx.fillRect(x + 0.5, y + 0.5, tw - 1, th - 1);
345 }
346};
347
348Online.miniElement = function (playerId)
349{
350 return document.querySelector('#minis .mini[data-player="' + CSS.escape(playerId) + '"]');
351};
352
353/* ---------- flight tweens ------------------------------------------ */
354
355function colorSpriteUrl (color)
356{
357 if (color < 0)
358 { return 'images/block-gray.png'; }
359 var names = ['ember', 'aqua', 'leaf', 'sun', 'orchid'];
360 return 'images/block-' + (names[color] || 'gray') + '.png';
361}
362
363/**
364 * Animate shot results. `locals` is a map of client_id → {col, y, color,
365 * startX, startY} in viewport pixels, filled by the view just after
366 * consumeOutgoingShots.
367 */
368Online.spawnFlights = function (results, locals)
369{
370 locals = locals || this._flightLocals || {};
371 var layer = document.getElementById('flights');
372 if (!layer)
373 { return; }
374 for (var i = 0; i < results.length; i++)
375 {
376 var r = results[i];
377 var meta = locals[r.client_id] || {};
378 var start = this._flightStart(meta.col);
379 var end;
380 var miss = !!r.miss;
381 if (miss)
382 { end = this._missEnd(start); }
383 else
384 { end = this._targetEnd(r.target_id, start); }
385 var el = document.createElement('img');
386 el.src = colorSpriteUrl(r.color != null ? r.color : meta.color);
387 el.alt = '';
388 el.className = 'flight';
389 layer.appendChild(el);
390 var spin = (Math.random() * 2 - 1) * 720;
391 var duration = (r.flight_duration || this.FLIGHT_DURATION) * 1000;
392 this._flights.push({
393 el: el,
394 start: start,
395 end: end,
396 ctrl: miss ? this._missCtrl(start, end) : this._hitCtrl(start, end),
397 t0: performance.now(),
398 duration: duration,
399 spin: spin,
400 miss: miss,
401 angle: Math.random() * 360
402 });
403 }
404 this._flightLocals = {};
405};
406
407Online.rememberFlightLocal = function (shot, startX, startY)
408{
409 if (!this._flightLocals)
410 { this._flightLocals = {}; }
411 this._flightLocals[String(shot.id)] = {
412 col: shot.col,
413 y: shot.y,
414 color: shot.color,
415 startX: startX,
416 startY: startY
417 };
418};
419
420Online._flightStart = function (col)
421{
422 var field = document.querySelector('canvas');
423 var appRef = typeof app !== 'undefined' ? app : null;
424 if (appRef && appRef.scene && appRef.scene.canvas)
425 {
426 var canvas = appRef.scene.canvas;
427 var rect = canvas.getBoundingClientRect();
428 var c = col == null ? 4.5 : col;
429 return {
430 x: rect.left + (c + 0.5) * (rect.width / 10),
431 y: rect.top + 4
432 };
433 }
434 if (field)
435 {
436 var rect = field.getBoundingClientRect();
437 return { x: rect.left + rect.width / 2, y: rect.top };
438 }
439 return { x: window.innerWidth / 2, y: window.innerHeight * 0.3 };
440};
441
442Online._targetEnd = function (targetId, start)
443{
444 var el = targetId && this.miniElement(targetId);
445 if (el)
446 {
447 var r = el.getBoundingClientRect();
448 return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
449 }
450 return { x: start.x + (Math.random() - 0.5) * 80, y: 40 };
451};
452
453Online._missEnd = function (start)
454{
455 var dx = (Math.random() * 2 - 1) * window.innerWidth * 0.35;
456 return {
457 x: start.x + dx,
458 y: start.y - (120 + Math.random() * 220)
459 };
460};
461
462Online._missCtrl = function (start, end)
463{
464 return {
465 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 160,
466 y: Math.min(start.y, end.y) - 40 - Math.random() * 80
467 };
468};
469
470Online._hitCtrl = function (start, end)
471{
472 return {
473 x: (start.x + end.x) / 2 + (Math.random() - 0.5) * 40,
474 y: (start.y + end.y) / 2 - 30
475 };
476};
477
478Online.tickFlights = function (now)
479{
480 now = now || performance.now();
481 var leftover = [];
482 for (var i = 0; i < this._flights.length; i++)
483 {
484 var f = this._flights[i];
485 var u = (now - f.t0) / f.duration;
486 if (u >= 1)
487 {
488 if (f.el && f.el.parentNode)
489 { f.el.parentNode.removeChild(f.el); }
490 continue;
491 }
492 // Quadratic bezier, ease-in so they feel like they recede.
493 var e = u * u;
494 var mt = 1 - e;
495 var x = mt * mt * f.start.x + 2 * mt * e * f.ctrl.x + e * e * f.end.x;
496 var y = mt * mt * f.start.y + 2 * mt * e * f.ctrl.y + e * e * f.end.y;
497 var scale = f.miss ? (1 - e) : (1 - 0.85 * e);
498 var angle = f.angle + f.spin * u;
499 f.el.style.transform = 'translate(' + x + 'px,' + y + 'px) translate(-50%,-50%) rotate('
500 + angle + 'deg) scale(' + scale + ')';
501 f.el.style.opacity = f.miss ? String(1 - e) : '1';
502 leftover.push(f);
503 }
504 this._flights = leftover;
505};
506
507Online.clearFlights = function ()
508{
509 for (var i = 0; i < this._flights.length; i++)
510 {
511 var el = this._flights[i].el;
512 if (el && el.parentNode)
513 { el.parentNode.removeChild(el); }
514 }
515 this._flights = [];
516 this._flightLocals = {};
517};
518
519if (typeof globalThis !== 'undefined')
520{ globalThis.Online = Online; }
521if (typeof module !== 'undefined' && module.exports)
522{ module.exports = Online; }
test/deploy_guard.test.js +5 −1
@@ -96,7 +96,7 @@ describe('assert_safe_target', () =>
96 96 assert.doesNotMatch(r.stdout + r.stderr, /GEBLOKKEERD/);
97 97 });
98 98
99 it('the FTP mirror never deletes and never uploads favicon.ico', () =>
99 it('the FTP mirror never deletes, never uploads favicon.ico, and leaves data/ alone', () =>
100 100 {
101 101 const py = [
102 102 'import sys',
@@ -107,6 +107,10 @@ describe('assert_safe_target', () =>
107 107 'cmds = "\\n".join(deploy_commands(env, "/var/www/meteors", Path("build")))',
108 108 'assert "--delete" not in cmds, cmds',
109 109 'assert "--exclude-glob \\"favicon.ico\\"" in cmds, cmds',
110 'assert "--exclude-glob \\"data/**\\"" in cmds, cmds',
111 'assert "--exclude-glob \\"**/config.php\\"" in cmds, cmds',
112 'assert "data/.htaccess" in cmds, cmds',
113 'assert "put " in cmds, cmds',
110 114 'print("mirror ok")'
111 115 ].join('\n');
112 116 const r = spawnSync('python3', ['-c', py], {
@@ -96,7 +96,7 @@ describe('assert_safe_target', () =>
96 assert.doesNotMatch(r.stdout + r.stderr, /GEBLOKKEERD/);
96 assert.doesNotMatch(r.stdout + r.stderr, /GEBLOKKEERD/);
97 });
97 });
98
98
99 it('the FTP mirror never deletes and never uploads favicon.ico', () =>
99 it('the FTP mirror never deletes, never uploads favicon.ico, and leaves data/ alone', () =>
100 {
100 {
101 const py = [
101 const py = [
102 'import sys',
102 'import sys',
@@ -107,6 +107,10 @@ describe('assert_safe_target', () =>
107 'cmds = "\\n".join(deploy_commands(env, "/var/www/meteors", Path("build")))',
107 'cmds = "\\n".join(deploy_commands(env, "/var/www/meteors", Path("build")))',
108 'assert "--delete" not in cmds, cmds',
108 'assert "--delete" not in cmds, cmds',
109 'assert "--exclude-glob \\"favicon.ico\\"" in cmds, cmds',
109 'assert "--exclude-glob \\"favicon.ico\\"" in cmds, cmds',
110 'assert "--exclude-glob \\"data/**\\"" in cmds, cmds',
111 'assert "--exclude-glob \\"**/config.php\\"" in cmds, cmds',
112 'assert "data/.htaccess" in cmds, cmds',
113 'assert "put " in cmds, cmds',
110 'print("mirror ok")'
114 'print("mirror ok")'
111 ].join('\n');
115 ].join('\n');
112 const r = spawnSync('python3', ['-c', py], {
116 const r = spawnSync('python3', ['-c', py], {
test/multiplayer-core.test.js added +97 −0
@@ -0,0 +1,97 @@
1 'use strict';
2
3 const { describe, it } = require('node:test');
4 const assert = require('node:assert/strict');
5 const { makeGame, placeRow, almost, GameCore, Planet } = require('./helpers.js');
6
7 describe('Outgoing shots and incoming garbage', () =>
8 {
9 it('blocks that leave the top are recorded as outgoing shots and can be consumed', () =>
10 {
11 const g = makeGame({
12 noSpawn: true,
13 planetOpts: { jumpsToClear: 1, fallTime: 5, riseTime: 0.5 }
14 });
15 placeRow(g, 0, [0, 1, 2], 0);
16 g.place(1, 1, 4);
17 g.resolveMatches();
18 assert.equal(g.consumeOutgoingShots().length, 0);
19 g.step(2, 1 / 120);
20 const shots = g.consumeOutgoingShots();
21 assert.equal(shots.length, 4, '3 rockets + 1 cargo, got ' + shots.length);
22 assert.ok(shots.every((s) => 'id' in s && 'color' in s && 'col' in s));
23 assert.equal(g.consumeOutgoingShots().length, 0, 'consume clears the list');
24 assert.equal(g.score, 4);
25 });
26
27 it('ingestGarbage drops a falling grey that settles 3s then recolors', () =>
28 {
29 const g = makeGame({ noSpawn: true, seed: 4 });
30 const block = g.ingestGarbage(3);
31 assert.ok(block);
32 assert.equal(block.col, 3);
33 assert.equal(block.color, GameCore.COLOR_GRAY);
34 assert.equal(block.state, 'falling');
35 assert.ok(almost(block.y, g.height, 0.05));
36 let landed = false;
37 for (let i = 0; i < 3000; i++)
38 {
39 g.tick(1 / 120);
40 if (block.state === 'settling')
41 {
42 landed = true;
43 break;
44 }
45 }
46 assert.ok(landed, 'should settle after landing, state=' + block.state + ' y=' + block.y + ' color=' + block.color);
47 assert.ok(almost(block.y, 0, 0.08), 'landed on the floor, y=' + block.y);
48 assert.equal(block.color, GameCore.COLOR_GRAY);
49 assert.ok(block.settleTime < 0.05, 'timer starts at landing');
50 g.step(2.9, 1 / 120);
51 assert.equal(block.state, 'settling', 'still settling at 2.9s, t=' + block.settleTime);
52 g.step(0.2, 1 / 120);
53 assert.equal(block.state, 'still');
54 assert.ok(block.color >= 0 && block.color < 5, 'recolored, color=' + block.color);
55 });
56
57 it('ingestGarbage skips locked and full columns, and returns null when none are open', () =>
58 {
59 const g = makeGame({ noSpawn: true });
60 for (let c = 0; c < 10; c++)
61 {
62 for (let r = 0; r < 13; r++)
63 { g.place(c, r, r % 5); }
64 }
65 g.checkLocks();
66 assert.equal(g.lockedColumnCount(), 10);
67 assert.equal(g.ingestGarbage(), null);
68 });
69
70 it('missChance is a parameter defaulting to 0.30, independent of planet Power', () =>
71 {
72 const g = makeGame({ noSpawn: true });
73 assert.equal(g.missChance, 0.30);
74 assert.equal(GameCore.DEFAULT_MISS_CHANCE, 0.30);
75 const custom = new GameCore(Planet.defaultPlanet(), Math.random, 0.05);
76 assert.equal(custom.missChance, 0.05);
77 const clamped = new GameCore(Planet.defaultPlanet(), Math.random, 2);
78 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%');
82 });
83
84 it('fieldSnapshot lists every block for opponent miniatures', () =>
85 {
86 const g = makeGame({ noSpawn: true });
87 g.place(0, 0, 1);
88 g.place(1, 2, 3);
89 const snap = g.fieldSnapshot();
90 assert.equal(snap.score, 0);
91 assert.equal(snap.state, 'playing');
92 assert.equal(snap.blocks.length, 2);
93 assert.equal(snap.blocks[0].col, 0);
94 assert.equal(snap.blocks[1].y, 2);
95 assert.equal(snap.locked, 0);
96 });
97 });
@@ -0,0 +1,97 @@
1'use strict';
2
3const { describe, it } = require('node:test');
4const assert = require('node:assert/strict');
5const { makeGame, placeRow, almost, GameCore, Planet } = require('./helpers.js');
6
7describe('Outgoing shots and incoming garbage', () =>
8{
9 it('blocks that leave the top are recorded as outgoing shots and can be consumed', () =>
10 {
11 const g = makeGame({
12 noSpawn: true,
13 planetOpts: { jumpsToClear: 1, fallTime: 5, riseTime: 0.5 }
14 });
15 placeRow(g, 0, [0, 1, 2], 0);
16 g.place(1, 1, 4);
17 g.resolveMatches();
18 assert.equal(g.consumeOutgoingShots().length, 0);
19 g.step(2, 1 / 120);
20 const shots = g.consumeOutgoingShots();
21 assert.equal(shots.length, 4, '3 rockets + 1 cargo, got ' + shots.length);
22 assert.ok(shots.every((s) => 'id' in s && 'color' in s && 'col' in s));
23 assert.equal(g.consumeOutgoingShots().length, 0, 'consume clears the list');
24 assert.equal(g.score, 4);
25 });
26
27 it('ingestGarbage drops a falling grey that settles 3s then recolors', () =>
28 {
29 const g = makeGame({ noSpawn: true, seed: 4 });
30 const block = g.ingestGarbage(3);
31 assert.ok(block);
32 assert.equal(block.col, 3);
33 assert.equal(block.color, GameCore.COLOR_GRAY);
34 assert.equal(block.state, 'falling');
35 assert.ok(almost(block.y, g.height, 0.05));
36 let landed = false;
37 for (let i = 0; i < 3000; i++)
38 {
39 g.tick(1 / 120);
40 if (block.state === 'settling')
41 {
42 landed = true;
43 break;
44 }
45 }
46 assert.ok(landed, 'should settle after landing, state=' + block.state + ' y=' + block.y + ' color=' + block.color);
47 assert.ok(almost(block.y, 0, 0.08), 'landed on the floor, y=' + block.y);
48 assert.equal(block.color, GameCore.COLOR_GRAY);
49 assert.ok(block.settleTime < 0.05, 'timer starts at landing');
50 g.step(2.9, 1 / 120);
51 assert.equal(block.state, 'settling', 'still settling at 2.9s, t=' + block.settleTime);
52 g.step(0.2, 1 / 120);
53 assert.equal(block.state, 'still');
54 assert.ok(block.color >= 0 && block.color < 5, 'recolored, color=' + block.color);
55 });
56
57 it('ingestGarbage skips locked and full columns, and returns null when none are open', () =>
58 {
59 const g = makeGame({ noSpawn: true });
60 for (let c = 0; c < 10; c++)
61 {
62 for (let r = 0; r < 13; r++)
63 { g.place(c, r, r % 5); }
64 }
65 g.checkLocks();
66 assert.equal(g.lockedColumnCount(), 10);
67 assert.equal(g.ingestGarbage(), null);
68 });
69
70 it('missChance is a parameter defaulting to 0.30, independent of planet Power', () =>
71 {
72 const g = makeGame({ noSpawn: true });
73 assert.equal(g.missChance, 0.30);
74 assert.equal(GameCore.DEFAULT_MISS_CHANCE, 0.30);
75 const custom = new GameCore(Planet.defaultPlanet(), Math.random, 0.05);
76 assert.equal(custom.missChance, 0.05);
77 const clamped = new GameCore(Planet.defaultPlanet(), Math.random, 2);
78 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%');
82 });
83
84 it('fieldSnapshot lists every block for opponent miniatures', () =>
85 {
86 const g = makeGame({ noSpawn: true });
87 g.place(0, 0, 1);
88 g.place(1, 2, 3);
89 const snap = g.fieldSnapshot();
90 assert.equal(snap.score, 0);
91 assert.equal(snap.state, 'playing');
92 assert.equal(snap.blocks.length, 2);
93 assert.equal(snap.blocks[0].col, 0);
94 assert.equal(snap.blocks[1].y, 2);
95 assert.equal(snap.locked, 0);
96 });
97});
test/online-playwright.py added +261 −0
@@ -0,0 +1,261 @@
1 #!/usr/bin/env python3
2 """Stage-2 online flow: two Playwright contexts against a local PHP server.
3 Also a live solo/online-panel check where the public site is reachable.
4 """
5 from __future__ import annotations
6
7 import json
8 import os
9 import shutil
10 import socket
11 import subprocess
12 import sys
13 import tempfile
14 import time
15 from pathlib import Path
16
17 from playwright.sync_api import sync_playwright
18
19 ROOT = Path("/workspace/meteors")
20 OUT = Path("/workspace/meteors-shots")
21 OUT.mkdir(parents=True, exist_ok=True)
22 CHROME = "/usr/bin/google-chrome"
23 CHROME_ARGS = [
24 "--use-gl=angle",
25 "--use-angle=swiftshader",
26 "--no-sandbox",
27 "--disable-dev-shm-usage",
28 ]
29 LIVE = "https://projects.timfalken.com/meteors/"
30 PHP = shutil.which("php") or str(Path.home() / ".local/bin/php")
31 FAILURES = []
32
33
34 def free_port():
35 s = socket.socket()
36 s.bind(("127.0.0.1", 0))
37 port = s.getsockname()[1]
38 s.close()
39 return port
40
41
42 def check(cond, msg):
43 if not cond:
44 FAILURES.append(msg)
45 print("FAIL", msg)
46 else:
47 print("OK ", msg)
48 return cond
49
50
51 def shot(page, name):
52 path = OUT / name
53 page.screenshot(path=str(path), full_page=False)
54 print(f"wrote {path} ({path.stat().st_size} bytes)")
55 return path
56
57
58 def start_php(port, data_dir):
59 env = os.environ.copy()
60 env["METEORS_DATA_DIR"] = str(data_dir)
61 proc = subprocess.Popen(
62 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
63 cwd=str(ROOT / "build"),
64 stdout=subprocess.DEVNULL,
65 stderr=subprocess.PIPE,
66 env=env,
67 )
68 time.sleep(0.4)
69 if proc.poll() is not None:
70 err = proc.stderr.read().decode("utf-8", "replace") if proc.stderr else ""
71 raise RuntimeError("php -S failed: " + err)
72 return proc
73
74
75 def login(page, n, next_path="index.html?online=1"):
76 # Log in first (test= is only honoured on loopback), then open the online panel.
77 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=15000)
78 page.wait_for_timeout(300)
79 page.goto(f"{URL}{next_path}", wait_until="domcontentloaded", timeout=15000)
80 page.wait_for_timeout(400)
81
82
83 def wait_visible(page, sel, timeout=8000):
84 page.locator(sel).wait_for(state="visible", timeout=timeout)
85
86
87 def run_two_contexts(browser):
88 print("\n======== two local contexts ========")
89 c1 = browser.new_context(viewport={"width": 1280, "height": 800})
90 c2 = browser.new_context(viewport={"width": 1100, "height": 760})
91 p1 = c1.new_page()
92 p2 = c2.new_page()
93 bag = []
94 for p, tag in ((p1, "p1"), (p2, "p2")):
95 p.on("pageerror", lambda e, tag=tag: bag.append(f"{tag} pageerror: {e}"))
96 p.on("console", lambda m, tag=tag: bag.append(f"{tag} {m.type}: {m.text}") if m.type == "error" else None)
97
98 login(p1, 1)
99 login(p2, 2)
100 wait_visible(p1, "#online-panel")
101 wait_visible(p2, "#online-panel")
102 check(p1.locator("#online-home").is_visible() or p1.locator("#online-lobby").is_visible(),
103 "user 1 landed in the online panel")
104 check(p2.locator("#online-home").is_visible() or p2.locator("#online-lobby").is_visible(),
105 "user 2 landed in the online panel")
106 # If we landed in a leftover lobby, leave first.
107 for p in (p1, p2):
108 if p.locator("#online-lobby").is_visible() and p.locator("#btn-leave-lobby").is_visible():
109 p.locator("#btn-leave-lobby").click()
110 p.wait_for_timeout(400)
111
112 wait_visible(p1, "#btn-create")
113 shot(p1, "stage2-online-home.png")
114 p1.locator("#btn-create").click()
115 wait_visible(p1, "#online-lobby")
116 p1.wait_for_function("() => document.getElementById('lobby-code') && document.getElementById('lobby-code').textContent.trim().length >= 4", timeout=8000)
117 code = p1.locator("#lobby-code").inner_text().strip()
118 check(len(code) >= 4, f"lobby code visible ({code!r})")
119 shot(p1, "stage2-lobby-host.png")
120
121 wait_visible(p2, "#join-code")
122 p2.locator("#join-code").fill(code)
123 p2.locator("#btn-join").click()
124 wait_visible(p2, "#online-lobby")
125 p2.wait_for_timeout(500)
126 players2 = p2.locator("#lobby-players li").count()
127 players1 = p1.locator("#lobby-players li").count()
128 # Host poll should pick up the joiner shortly.
129 for _ in range(12):
130 if p1.locator("#lobby-players li").count() >= 2:
131 break
132 p1.wait_for_timeout(400)
133 players1 = p1.locator("#lobby-players li").count()
134 check(players2 >= 2, f"guest sees two players ({players2})")
135 check(players1 >= 2, f"host sees two players ({players1})")
136 shot(p2, "stage2-lobby-guest.png")
137
138 p1.locator("#btn-ready").click()
139 p2.locator("#btn-ready").click()
140 # Host start becomes enabled once both ready (poll).
141 start = p1.locator("#btn-start")
142 enabled = False
143 for _ in range(16):
144 if start.is_visible() and start.is_enabled():
145 enabled = True
146 break
147 p1.wait_for_timeout(400)
148 check(enabled, "host Starten is enabled when both are ready")
149 shot(p1, "stage2-lobby-ready.png")
150 start.click()
151
152 # Both should enter the game: HUD + canvas + opponent minis.
153 for p, name in ((p1, "host"), (p2, "guest")):
154 p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
155 p.wait_for_selector("canvas", state="visible", timeout=8000)
156 p.wait_for_timeout(600)
157 nminis = p.locator("#minis .mini").count()
158 check(nminis >= 1, f"{name} sees at least one opponent miniature ({nminis})")
159 hud = p.locator("#hud").is_visible()
160 check(hud, f"{name} HUD visible")
161 shot(p1, "stage2-game-host.png")
162 shot(p2, "stage2-game-guest.png")
163
164 # Inject a shot so we can screenshot the flight tween.
165 p1.evaluate(
166 """() => {
167 if (!app.core) return;
168 const shots = [{id: 9001, color: 0, col: 4, y: 12}];
169 Online.rememberFlightLocal(shots[0], window.innerWidth/2, 200);
170 Online.queueShots(shots);
171 // Force a poll-like result locally so the tween plays even before the server answers.
172 Online.spawnFlights([{client_id: '9001', miss: false, target_id: Online.aliveOpponents()[0] && Online.aliveOpponents()[0].id, color: 0, flight_duration: 1.2}], {'9001': {col: 4, y: 12, color: 0}});
173 }"""
174 )
175 p1.wait_for_timeout(350)
176 flights = p1.evaluate("() => document.querySelectorAll('#flights .flight').length")
177 check(flights >= 1, f"flight tween appears ({flights})")
178 shot(p1, "stage2-flight.png")
179
180 # Incoming garbage path: ingest a grey on the guest and wait a frame.
181 p2.evaluate("() => { const b = app.core.ingestGarbage(); return b && {col: b.col, color: b.color, state: b.state}; }")
182 p2.wait_for_timeout(200)
183 grey = p2.evaluate("() => app.core.blocks.some(b => b.color === -1 && b.state === 'falling')")
184 check(grey, "ingestGarbage drops a falling grey on the guest")
185 shot(p2, "stage2-garbage.png")
186
187 if bag:
188 print("console:", bag[:12])
189 c1.close()
190 c2.close()
191
192
193 def run_live(browser):
194 print("\n======== live site ========")
195 try:
196 ctx = browser.new_context(viewport={"width": 1280, "height": 800})
197 page = ctx.new_page()
198 page.goto(LIVE, wait_until="networkidle", timeout=20000)
199 page.wait_for_timeout(600)
200 title = page.locator("h1")
201 check(title.is_visible() and "Meteors" in title.inner_text(), "live menu title")
202 shot(page, "stage2-live-menu.png")
203 # Solo still works.
204 page.locator("#btn-play").click()
205 page.wait_for_timeout(800)
206 playing = page.evaluate("() => app && app.mode === 'playing'")
207 check(playing, "live solo Play still starts a game")
208 shot(page, "stage2-live-solo.png")
209 # Back via evaluating return — game-over takes 2s+ after a full lock, so just reload.
210 page.goto(LIVE, wait_until="networkidle", timeout=20000)
211 page.wait_for_timeout(400)
212 if page.locator("#btn-online").is_visible():
213 page.locator("#btn-online").click()
214 page.wait_for_timeout(1200)
215 shot(page, "stage2-live-online-panel.png")
216 # Either unconfigured notice, login, or a live API error — solo is already confirmed.
217 panel = page.locator("#online-panel").is_visible()
218 check(panel, "live Online spelen opens the panel")
219 body = page.locator("#online-panel").inner_text()
220 print("live online panel text:", body[:400].replace("\n", " / "))
221 ctx.close()
222 except Exception as e:
223 check(False, f"live site check: {e}")
224
225
226 def main():
227 global URL
228 if not Path(PHP).is_file():
229 print("php not found at", PHP)
230 return 1
231 port = free_port()
232 URL = f"http://127.0.0.1:{port}/"
233 data = Path(tempfile.mkdtemp(prefix="meteors-pw-"))
234 print("PHP", PHP, "URL", URL, "data", data)
235 proc = start_php(port, data)
236 try:
237 with sync_playwright() as p:
238 browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
239 run_two_contexts(browser)
240 run_live(browser)
241 browser.close()
242 finally:
243 proc.terminate()
244 try:
245 proc.wait(timeout=3)
246 except Exception:
247 proc.kill()
248 shutil.rmtree(data, ignore_errors=True)
249
250 print("\n======== summary ========")
251 if FAILURES:
252 print(f"{len(FAILURES)} failure(s):")
253 for f in FAILURES:
254 print(" -", f)
255 return 1
256 print("all stage-2 playwright checks passed")
257 return 0
258
259
260 if __name__ == "__main__":
261 sys.exit(main())
@@ -0,0 +1,261 @@
1#!/usr/bin/env python3
2"""Stage-2 online flow: two Playwright contexts against a local PHP server.
3Also a live solo/online-panel check where the public site is reachable.
4"""
5from __future__ import annotations
6
7import json
8import os
9import shutil
10import socket
11import subprocess
12import sys
13import tempfile
14import time
15from pathlib import Path
16
17from playwright.sync_api import sync_playwright
18
19ROOT = Path("/workspace/meteors")
20OUT = Path("/workspace/meteors-shots")
21OUT.mkdir(parents=True, exist_ok=True)
22CHROME = "/usr/bin/google-chrome"
23CHROME_ARGS = [
24 "--use-gl=angle",
25 "--use-angle=swiftshader",
26 "--no-sandbox",
27 "--disable-dev-shm-usage",
28]
29LIVE = "https://projects.timfalken.com/meteors/"
30PHP = shutil.which("php") or str(Path.home() / ".local/bin/php")
31FAILURES = []
32
33
34def free_port():
35 s = socket.socket()
36 s.bind(("127.0.0.1", 0))
37 port = s.getsockname()[1]
38 s.close()
39 return port
40
41
42def check(cond, msg):
43 if not cond:
44 FAILURES.append(msg)
45 print("FAIL", msg)
46 else:
47 print("OK ", msg)
48 return cond
49
50
51def shot(page, name):
52 path = OUT / name
53 page.screenshot(path=str(path), full_page=False)
54 print(f"wrote {path} ({path.stat().st_size} bytes)")
55 return path
56
57
58def start_php(port, data_dir):
59 env = os.environ.copy()
60 env["METEORS_DATA_DIR"] = str(data_dir)
61 proc = subprocess.Popen(
62 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
63 cwd=str(ROOT / "build"),
64 stdout=subprocess.DEVNULL,
65 stderr=subprocess.PIPE,
66 env=env,
67 )
68 time.sleep(0.4)
69 if proc.poll() is not None:
70 err = proc.stderr.read().decode("utf-8", "replace") if proc.stderr else ""
71 raise RuntimeError("php -S failed: " + err)
72 return proc
73
74
75def login(page, n, next_path="index.html?online=1"):
76 # Log in first (test= is only honoured on loopback), then open the online panel.
77 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=15000)
78 page.wait_for_timeout(300)
79 page.goto(f"{URL}{next_path}", wait_until="domcontentloaded", timeout=15000)
80 page.wait_for_timeout(400)
81
82
83def wait_visible(page, sel, timeout=8000):
84 page.locator(sel).wait_for(state="visible", timeout=timeout)
85
86
87def run_two_contexts(browser):
88 print("\n======== two local contexts ========")
89 c1 = browser.new_context(viewport={"width": 1280, "height": 800})
90 c2 = browser.new_context(viewport={"width": 1100, "height": 760})
91 p1 = c1.new_page()
92 p2 = c2.new_page()
93 bag = []
94 for p, tag in ((p1, "p1"), (p2, "p2")):
95 p.on("pageerror", lambda e, tag=tag: bag.append(f"{tag} pageerror: {e}"))
96 p.on("console", lambda m, tag=tag: bag.append(f"{tag} {m.type}: {m.text}") if m.type == "error" else None)
97
98 login(p1, 1)
99 login(p2, 2)
100 wait_visible(p1, "#online-panel")
101 wait_visible(p2, "#online-panel")
102 check(p1.locator("#online-home").is_visible() or p1.locator("#online-lobby").is_visible(),
103 "user 1 landed in the online panel")
104 check(p2.locator("#online-home").is_visible() or p2.locator("#online-lobby").is_visible(),
105 "user 2 landed in the online panel")
106 # If we landed in a leftover lobby, leave first.
107 for p in (p1, p2):
108 if p.locator("#online-lobby").is_visible() and p.locator("#btn-leave-lobby").is_visible():
109 p.locator("#btn-leave-lobby").click()
110 p.wait_for_timeout(400)
111
112 wait_visible(p1, "#btn-create")
113 shot(p1, "stage2-online-home.png")
114 p1.locator("#btn-create").click()
115 wait_visible(p1, "#online-lobby")
116 p1.wait_for_function("() => document.getElementById('lobby-code') && document.getElementById('lobby-code').textContent.trim().length >= 4", timeout=8000)
117 code = p1.locator("#lobby-code").inner_text().strip()
118 check(len(code) >= 4, f"lobby code visible ({code!r})")
119 shot(p1, "stage2-lobby-host.png")
120
121 wait_visible(p2, "#join-code")
122 p2.locator("#join-code").fill(code)
123 p2.locator("#btn-join").click()
124 wait_visible(p2, "#online-lobby")
125 p2.wait_for_timeout(500)
126 players2 = p2.locator("#lobby-players li").count()
127 players1 = p1.locator("#lobby-players li").count()
128 # Host poll should pick up the joiner shortly.
129 for _ in range(12):
130 if p1.locator("#lobby-players li").count() >= 2:
131 break
132 p1.wait_for_timeout(400)
133 players1 = p1.locator("#lobby-players li").count()
134 check(players2 >= 2, f"guest sees two players ({players2})")
135 check(players1 >= 2, f"host sees two players ({players1})")
136 shot(p2, "stage2-lobby-guest.png")
137
138 p1.locator("#btn-ready").click()
139 p2.locator("#btn-ready").click()
140 # Host start becomes enabled once both ready (poll).
141 start = p1.locator("#btn-start")
142 enabled = False
143 for _ in range(16):
144 if start.is_visible() and start.is_enabled():
145 enabled = True
146 break
147 p1.wait_for_timeout(400)
148 check(enabled, "host Starten is enabled when both are ready")
149 shot(p1, "stage2-lobby-ready.png")
150 start.click()
151
152 # Both should enter the game: HUD + canvas + opponent minis.
153 for p, name in ((p1, "host"), (p2, "guest")):
154 p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
155 p.wait_for_selector("canvas", state="visible", timeout=8000)
156 p.wait_for_timeout(600)
157 nminis = p.locator("#minis .mini").count()
158 check(nminis >= 1, f"{name} sees at least one opponent miniature ({nminis})")
159 hud = p.locator("#hud").is_visible()
160 check(hud, f"{name} HUD visible")
161 shot(p1, "stage2-game-host.png")
162 shot(p2, "stage2-game-guest.png")
163
164 # Inject a shot so we can screenshot the flight tween.
165 p1.evaluate(
166 """() => {
167 if (!app.core) return;
168 const shots = [{id: 9001, color: 0, col: 4, y: 12}];
169 Online.rememberFlightLocal(shots[0], window.innerWidth/2, 200);
170 Online.queueShots(shots);
171 // Force a poll-like result locally so the tween plays even before the server answers.
172 Online.spawnFlights([{client_id: '9001', miss: false, target_id: Online.aliveOpponents()[0] && Online.aliveOpponents()[0].id, color: 0, flight_duration: 1.2}], {'9001': {col: 4, y: 12, color: 0}});
173 }"""
174 )
175 p1.wait_for_timeout(350)
176 flights = p1.evaluate("() => document.querySelectorAll('#flights .flight').length")
177 check(flights >= 1, f"flight tween appears ({flights})")
178 shot(p1, "stage2-flight.png")
179
180 # Incoming garbage path: ingest a grey on the guest and wait a frame.
181 p2.evaluate("() => { const b = app.core.ingestGarbage(); return b && {col: b.col, color: b.color, state: b.state}; }")
182 p2.wait_for_timeout(200)
183 grey = p2.evaluate("() => app.core.blocks.some(b => b.color === -1 && b.state === 'falling')")
184 check(grey, "ingestGarbage drops a falling grey on the guest")
185 shot(p2, "stage2-garbage.png")
186
187 if bag:
188 print("console:", bag[:12])
189 c1.close()
190 c2.close()
191
192
193def run_live(browser):
194 print("\n======== live site ========")
195 try:
196 ctx = browser.new_context(viewport={"width": 1280, "height": 800})
197 page = ctx.new_page()
198 page.goto(LIVE, wait_until="networkidle", timeout=20000)
199 page.wait_for_timeout(600)
200 title = page.locator("h1")
201 check(title.is_visible() and "Meteors" in title.inner_text(), "live menu title")
202 shot(page, "stage2-live-menu.png")
203 # Solo still works.
204 page.locator("#btn-play").click()
205 page.wait_for_timeout(800)
206 playing = page.evaluate("() => app && app.mode === 'playing'")
207 check(playing, "live solo Play still starts a game")
208 shot(page, "stage2-live-solo.png")
209 # Back via evaluating return — game-over takes 2s+ after a full lock, so just reload.
210 page.goto(LIVE, wait_until="networkidle", timeout=20000)
211 page.wait_for_timeout(400)
212 if page.locator("#btn-online").is_visible():
213 page.locator("#btn-online").click()
214 page.wait_for_timeout(1200)
215 shot(page, "stage2-live-online-panel.png")
216 # Either unconfigured notice, login, or a live API error — solo is already confirmed.
217 panel = page.locator("#online-panel").is_visible()
218 check(panel, "live Online spelen opens the panel")
219 body = page.locator("#online-panel").inner_text()
220 print("live online panel text:", body[:400].replace("\n", " / "))
221 ctx.close()
222 except Exception as e:
223 check(False, f"live site check: {e}")
224
225
226def main():
227 global URL
228 if not Path(PHP).is_file():
229 print("php not found at", PHP)
230 return 1
231 port = free_port()
232 URL = f"http://127.0.0.1:{port}/"
233 data = Path(tempfile.mkdtemp(prefix="meteors-pw-"))
234 print("PHP", PHP, "URL", URL, "data", data)
235 proc = start_php(port, data)
236 try:
237 with sync_playwright() as p:
238 browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
239 run_two_contexts(browser)
240 run_live(browser)
241 browser.close()
242 finally:
243 proc.terminate()
244 try:
245 proc.wait(timeout=3)
246 except Exception:
247 proc.kill()
248 shutil.rmtree(data, ignore_errors=True)
249
250 print("\n======== summary ========")
251 if FAILURES:
252 print(f"{len(FAILURES)} failure(s):")
253 for f in FAILURES:
254 print(" -", f)
255 return 1
256 print("all stage-2 playwright checks passed")
257 return 0
258
259
260if __name__ == "__main__":
261 sys.exit(main())