Compare commits
24 Commits
4a14b1de76
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| a494290548 | |||
|
|
2bf5a40ebc | ||
|
|
90f1c9c37e | ||
|
|
c99881e63a | ||
|
|
695cf77afc | ||
|
|
a8d6158384 | ||
|
|
593d69714b | ||
|
|
3dc770e34a | ||
|
|
0ffa221e82 | ||
|
|
4535ac7d8a | ||
|
|
fade816169 | ||
|
|
dd120f47f8 | ||
|
|
0ee589c91e | ||
|
|
a73d33a821 | ||
|
|
ce7cb798ec | ||
|
|
101dd7c44b | ||
|
|
b587d12f37 | ||
|
|
0202a08b8d | ||
|
|
85a19ba242 | ||
|
|
4bd85f68bf | ||
|
|
dca1032ac4 | ||
|
|
46499e354b | ||
|
|
9012bee29f | ||
|
|
bbe206004a |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -7,7 +7,7 @@ node_modules/
|
|||||||
*.log
|
*.log
|
||||||
tools/shots/
|
tools/shots/
|
||||||
.claude/
|
.claude/
|
||||||
# Firebase admin service-account keys - SECRET, never commit
|
# service-account keys (legacy) - SECRET, never commit
|
||||||
serviceAccount*.json
|
serviceAccount*.json
|
||||||
admin/*.json
|
admin/*.json
|
||||||
**/*serviceaccount*.json
|
**/*serviceaccount*.json
|
||||||
@@ -16,3 +16,5 @@ server/node_modules/
|
|||||||
server/.env
|
server/.env
|
||||||
server/data.sqlite*
|
server/data.sqlite*
|
||||||
server/*.sqlite*
|
server/*.sqlite*
|
||||||
|
test-results/
|
||||||
|
playwright-report/
|
||||||
|
|||||||
68
CLAUDE.md
68
CLAUDE.md
@@ -16,7 +16,7 @@ keine Namen, Figuren, Arenen, Hausroboter, Grafiken, Sounds oder Code aus dem Or
|
|||||||
Knopf auf **Kampagne** um (`gameMode` in game.js, `setMode`/`switchMode`). Getrennt wird über den
|
Knopf auf **Kampagne** um (`gameMode` in game.js, `setMode`/`switchMode`). Getrennt wird über den
|
||||||
Speicher-Schlüssel: die Kampagne behält den bisherigen Schlüssel (alte Spielstände laufen als Kampagne weiter),
|
Speicher-Schlüssel: die Kampagne behält den bisherigen Schlüssel (alte Spielstände laufen als Kampagne weiter),
|
||||||
Online hängt `.online` an. **Geld, Teile, Roboter und Ruhm wandern nie hinüber.** Kampagne = Liga, Saisons,
|
Online hängt `.online` an. **Geld, Teile, Roboter und Ruhm wandern nie hinüber.** Kampagne = Liga, Saisons,
|
||||||
Schaukampf; Online = Werkstatt, PvP über die Lobby, Training gegen die KI (keine Liga). Ohne Firebase-Schlüssel
|
Schaukampf; Online = Werkstatt, PvP über die Lobby, Training gegen die KI (keine Liga). Ohne Server (`file://`)
|
||||||
fällt alles auf die Kampagne zurück. Dev: `&gmode=campaign|online`.
|
fällt alles auf die Kampagne zurück. Dev: `&gmode=campaign|online`.
|
||||||
|
|
||||||
|
|
||||||
@@ -82,20 +82,24 @@ Stilblock für ComfyGen: *isometric 3/4 view game sprite, chunky handmade combat
|
|||||||
bolts and hazard stripes, bold clean shapes, soft studio lighting, high detail, plain solid black background*
|
bolts and hazard stripes, bold clean shapes, soft studio lighting, high detail, plain solid black background*
|
||||||
|
|
||||||
**Erste Version (drin):** Werkstatt mit 25 Teilen in 7 Slots, 1 Arena, 8 Liga-Gegner + Training, Saisons,
|
**Erste Version (drin):** Werkstatt mit 25 Teilen in 7 Slots, 1 Arena, 8 Liga-Gegner + Training, Saisons,
|
||||||
Speichern, en/de, Synth-Sounds. **Später:** Firebase-Rangliste (URL von Michael), asynchrones PvP (hochgeladene
|
Speichern, en/de, Synth-Sounds. **Später:** asynchrones PvP (hochgeladene Roboter, KI-gesteuert),
|
||||||
Roboter, KI-gesteuert), echtes PvP (WebRTC), Replays/Zuschauer, weitere Arenen + Gewichtsklassen, Icon/Musik/SFX
|
Online-Turnier server-seitig (Plan P2-6), Replays/Zuschauer, weitere Arenen + Gewichtsklassen, Icon/Musik/SFX
|
||||||
über ComfyGen. Titel-Logo `assets/Sprites/logo.png` (Prompt `logo` in `sprite-generator/prompts.py`,
|
über ComfyGen. Titel-Logo `assets/Sprites/logo.png` (Prompt `logo` in `sprite-generator/prompts.py`,
|
||||||
`gen adopt --wide --size 1024 logo`) – fehlt es, zeigt der Titel den Schriftzug; ComfyUI muss dafür laufen.
|
`gen adopt --wide --size 1024 logo`) – fehlt es, zeigt der Titel den Schriftzug; ComfyUI muss dafür laufen.
|
||||||
|
|
||||||
**Online-Technik – VERALTET (Phase 1 ersetzt das Host-Modell durch Server-Rechnung über WebSocket):** Der Host rechnet und sendet Snapshots – er schreibt **nur einen** Request gleichzeitig
|
**Online-Technik (server-autoritativ):** Der **Server rechnet jeden Live-Kampf** (`server/match/room.js`,
|
||||||
(`sending`-Sperre in netfight.js) und drosselt bei langsamer Leitung, sonst stapeln sich die Uploads und *beim
|
`RC.Combat.step` mit 60 Hz) und schickt Snapshots (20 Hz) über **einen WebSocket** pro Spieler (`/ws`); die Clients
|
||||||
Host* ruckelt es, während der Gast flüssig bleibt. Zahlen werden auf 3 Nachkommastellen gerundet (Paketgröße).
|
senden nur Eingaben und zeigen an (`game/netfight.js`). Ergebnis, Preisgeld, Reparatur und Erfolge bucht der Server
|
||||||
Rangliste: `Kit.scores.top()` zeigt **jeden Spieler nur einmal** (bester Lauf) – jeder Eintrag ist eine eigene
|
(`match.end`). Seat ↔ lokaler Index wird **nur** in `RC.Proto.toLocal` (`game/protocol.js`) gespiegelt. Lobby =
|
||||||
Zeile in der DB, die Entdopplung passiert beim Lesen (Fix liegt in `_Tools\Library\web\kit\kit-scores.js`).
|
offene Verbindungen (kein Heartbeat, keine Client-Uhren). Verbindungsabbruch: 10 s Gnadenfrist, dann KI, Reconnect
|
||||||
|
holt den laufenden Kampf zurück. Ein Hintergrund-Tab stoppt nichts mehr – der Server läuft weiter.
|
||||||
|
**Wirtschaft online:** jede Werkstatt-Änderung läuft über `act()` → `RC.Eco` (`game/eco.js`, dieselben Regeln auf
|
||||||
|
Client und Server); der Client wendet sie sofort an, der Server prüft dieselbe Aktion und ist maßgeblich.
|
||||||
|
Kosmetik (Namen, Lack, Flagge) gehört dem Client. Starter-Teile verkaufen sich für 0 (sonst Geld-Exploit).
|
||||||
|
|
||||||
**Online (Firebase, optional) – VERALTET, wird in Plan-Task P1-8 ersetzt (eigener Server, WebSocket):** Titel → „Online spielen" (nur wenn `NET_CFG.apiKey` gesetzt), Login per
|
**Online-Ablauf:** Titel → „Online spielen" → Login (Name oder E-Mail) / Registrieren (Name, E-Mail optional) / Gast →
|
||||||
E-Mail/Passwort, globale Lobby (alle Online-Spieler + Länderflagge), Klick auf Spieler = Herausfordern → Live-Kampf.
|
globale Lobby (alle Online-Spieler + Länderflagge), Klick auf Spieler = Herausfordern → Live-Kampf. Rangliste
|
||||||
Rangliste läuft schon mit `DB_URL` allein. Einrichtung + Grenzen: `docs/firebase/README.md`.
|
`GET /api/ranks` (Ruhm aus den Server-Spielständen). Details: `server/README.md`.
|
||||||
|
|
||||||
**Performance:** Render ist auf ~60 fps gedeckelt (Menüs ~16 fps), Pixel-Ratio-Deckel hoch 1,5 / mittel 1,25 /
|
**Performance:** Render ist auf ~60 fps gedeckelt (Menüs ~16 fps), Pixel-Ratio-Deckel hoch 1,5 / mittel 1,25 /
|
||||||
niedrig 1,0, Schatten-Map 1024 (soft nur bei Hoch), `powerPreference high-performance`. Standard-Grafik „Mittel“.
|
niedrig 1,0, Schatten-Map 1024 (soft nur bei Hoch), `powerPreference high-performance`. Standard-Grafik „Mittel“.
|
||||||
@@ -115,16 +119,36 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
|
|||||||
Siegregeln · `game/ai.js` KI + Liga-Kader – alle ohne DOM, laufen in Node.
|
Siegregeln · `game/ai.js` KI + Liga-Kader – alle ohne DOM, laufen in Node.
|
||||||
- `game/render3d.js` three.js-Szenen (Werkstatt, Arena), Roboter-Modelle aus Teilen, Partikel.
|
- `game/render3d.js` three.js-Szenen (Werkstatt, Arena), Roboter-Modelle aus Teilen, Partikel.
|
||||||
- `game/shop.js` Werkstatt-Shop (Kategorien, Teile-Karten mit Sprites, Detail mit Vergleich, Mechaniker-Tipps)
|
- `game/shop.js` Werkstatt-Shop (Kategorien, Teile-Karten mit Sprites, Detail mit Vergleich, Mechaniker-Tipps)
|
||||||
· `game/net.js` Backend über REST (Auth + DB-Fassade + Server-Sent-Events) — zeigt jetzt auf den **eigenen Node-Server** (`server/`, `NET_CFG.serverUrl` leer = gleiche Domain), Firebase abgelöst; Deploy auf Hetzner unter `roboclash.michael-media.de` via `server/deploy/` (Caddy+systemd+ufw, kein Ansible). Server bildet die alte Firebase-Oberfläche nach, darum Client-Änderung klein. Anti-Cheat (server-autoritäres Geld) per `ANTICHEAT=1` scharf, sobald der Geldfluss umgestellt ist · `game/cloudsave.js` Spielstand registrierter E-Mail-Konten nach `saves/<uid>` spiegeln (localStorage bleibt Cache, neuerer `ts` gewinnt; Gäste nur lokal; kein harter Schutz) · `game/lobby.js` globale Lobby (Präsenz/Heartbeat, Herausfordern, Match) · `game/netfight.js` Live-PvP-Sync (Host rechnet + sendet Snapshots ~15/s, Gast interpoliert, KI-Übernahme bei Lag)
|
· `game/net.js` REST + ein WebSocket zum eigenen Server (`server/`, `NET_CFG.serverUrl` leer = gleiche Domain),
|
||||||
|
Refresh single-flight und tab-übergreifend, `?slot=N` = zweite Sitzung im selben Browser · `game/protocol.js`
|
||||||
|
Nachrichten, Validierung, Snapshots, Seat-Spiegelung · `game/eco.js` Werkstatt-Wirtschaft (Client + Server)
|
||||||
|
· `game/cloudsave.js` Cloud-Kopie der **Kampagne** für registrierte Konten (`/api/campaign`) · `game/lobby.js`
|
||||||
|
Lobby über den WebSocket · `game/netfight.js` zeigt den vom Server gerechneten Kampf · Server: `server/README.md`,
|
||||||
|
Deploy auf Hetzner (`roboclash.michael-media.de`) via `server/deploy/`
|
||||||
· `game/painter.js` Lackiererei: selbst auf den Roboter malen (Ebene 512×256: links Draufsicht, rechts Seite,
|
· `game/painter.js` Lackiererei: selbst auf den Roboter malen (Ebene 512×256: links Draufsicht, rechts Seite,
|
||||||
Front jeweils rechts), 3D-Vorschau live; gespeichert als PNG-Data-URL in `save.paint.decal`
|
Front jeweils rechts), 3D-Vorschau live; gespeichert als PNG-Data-URL in `save.paint.decal`
|
||||||
· `game/looks.js` Aussehen der Liga-Gegner passend zu ihren Porträts (Skin-Muster + Augen, Kabine, Höcker, Ketten-Optik)
|
· `game/looks.js` Aussehen der Liga-Gegner passend zu ihren Porträts (Skin-Muster + Augen, Kabine, Höcker, Ketten-Optik)
|
||||||
· `game/profiles.js` Konten (v1 lokal: Name + Passwort-Hash, je Konto eigener Spielstand; später Firebase)
|
· `game/profiles.js` lokale Konten für die Offline-Kampagne (Name + Passwort-Hash, je Konto eigener Spielstand)
|
||||||
· `game/game.js` Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Registrieren/Gast → Shop → Liga/VS → Kampf → Ergebnis, Einstellungen.
|
· `game/game.js` Kern + Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Gast → Shop → Liga/VS → Kampf → Ergebnis.
|
||||||
|
Aufgeteilt (klassische Skripte, kein Build): `game/sfx.js` Sound · `game/pages.js` Menüseiten (Einstellungen,
|
||||||
|
Hilfe, Tutorial, Land, Erfolge, Missionen, Rechtliches, Rangliste) · `game/online.js` Online (act(), Abgleich mit
|
||||||
|
dem Server, Login-Karte, Lobby, Online-Kampfende) · `game/workshop.js` Waffen-Editor, Lack, Hangar. Jedes Modul
|
||||||
|
ist eine Fabrik `RC.Game<Teil>(G)`; `G` (Ende von game.js) liefert per Getter den **aktuellen** Zustand (`G.save`,
|
||||||
|
`G.mode`, `G.F` …) und per Setter das Zurückschreiben. Neue gemeinsame Variable → in `G` eintragen. Aufrufe aus
|
||||||
|
game.js laufen über kurze Weiterleitungen (`function x(...a) { return GM.<teil>.x(...a); }`).
|
||||||
- `game/vendor/three.min.js` three.js r149 (MIT, letzte Version mit klassischem Build – nicht auf ES-Module updaten).
|
- `game/vendor/three.min.js` three.js r149 (MIT, letzte Version mit klassischem Build – nicht auf ES-Module updaten).
|
||||||
- Kommandos (Repo-Root): `npm run setup` (einmal), `npm test` (alle Tests: `tests/*.test.js` Regeln/Kämpfe ohne NaN/
|
- Kommandos (Repo-Root): `npm run setup` (einmal), `npm test` (alle Tests: `tests/*.test.js` Regeln/Kämpfe ohne NaN/
|
||||||
Grube + `server/test/*.test.js` echter Server mit In-Memory-DB), `npm run lint` (ESLint), `npm run balance`
|
Grube + `server/test/*.test.js` echter Server mit In-Memory-DB), `npm run lint` (ESLint), `npm run balance`
|
||||||
(Zahlen), `npm run dev` (Server lokal auf :8080, braucht `server/.env` aus `.env.example`).
|
(Zahlen), `npm run dev` (Server lokal auf :8080, braucht `server/.env` aus `.env.example`),
|
||||||
|
`npm --prefix server run db:reset` (DB frisch + Testkonten), `npm run deploy` (= `bash server/deploy/deploy.sh`,
|
||||||
|
`-- --reset-db` setzt die DB zurück), `npm run smoke -- https://roboclash.michael-media.de` (nach jedem Deploy).
|
||||||
|
Zwei Spieler lokal: `?online&slot=1` und `?online&slot=2` in zwei Tabs.
|
||||||
|
`npm run bot -- --url <server> --pattern circle|zigzag|spin|charge|idle [--challenge <name>]` = dummer Testgegner
|
||||||
|
(nimmt Herausforderungen an, fährt ein Muster, löscht sich bei Strg+C). **F3** im Spiel (oder `?net`) = Netz-Overlay:
|
||||||
|
Ping-Verlauf, Gegner-Ping (vom Server gemessen), Snapshot-Abstand, Tasten-Verzögerung, Server-Last + Klartext-Urteil
|
||||||
|
(`game/netstats.js` rechnet, `game/netoverlay.js` zeigt). Bot **auf dem Server** starten = Gegner mit ~0 ms Ping.
|
||||||
|
`npm run e2e` = Playwright-Browsertests (`tests/e2e/`, nutzt das installierte Chrome, startet eigenen Server auf
|
||||||
|
:8099 mit frischer DB): zwei Browser spielen online gegeneinander, Shop gegen Server, Kampagne über `file://`.
|
||||||
- Grafik/Sound: `sprite-generator/prompts.py` + `audio.py` → `gen generate`, `gen adopt --all` (Sprites), `gen adopt_scene bg_*` (Hintergründe als JPG),
|
- Grafik/Sound: `sprite-generator/prompts.py` + `audio.py` → `gen generate`, `gen adopt --all` (Sprites), `gen adopt_scene bg_*` (Hintergründe als JPG),
|
||||||
`gen make_tileable tex_floor`, `gen adopt_audio --all`. Fehlende Bilder → Ersatz-Symbol (`RC.pic`), fehlende Sounds → Synth.
|
`gen make_tileable tex_floor`, `gen adopt_audio --all`. Fehlende Bilder → Ersatz-Symbol (`RC.pic`), fehlende Sounds → Synth.
|
||||||
- `game/uicheck.js` Layout-Selbsttest: `&uicheck` misst Scrollen, Überläufe, Überlappungen, zu kleine Tap-Ziele,
|
- `game/uicheck.js` Layout-Selbsttest: `&uicheck` misst Scrollen, Überläufe, Überlappungen, zu kleine Tap-Ziele,
|
||||||
@@ -135,7 +159,7 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
|
|||||||
|
|
||||||
## Qualitätsregeln (verbindlich, gelten für jede Änderung)
|
## Qualitätsregeln (verbindlich, gelten für jede Änderung)
|
||||||
|
|
||||||
Laufender Umbau (Multiplayer server-autoritativ, Firebase raus, Dev-Server + Deploy): **`docs/MULTIPLAYER-PLAN.md`**
|
Laufender Umbau (Multiplayer server-autoritativ, Dev-Server + Deploy): **`docs/MULTIPLAYER-PLAN.md`**
|
||||||
ist die Aufgabenliste – Tasks der Reihe nach, Task-ID im Commit, erledigte Tasks dort abhaken.
|
ist die Aufgabenliste – Tasks der Reihe nach, Task-ID im Commit, erledigte Tasks dort abhaken.
|
||||||
|
|
||||||
1. **Erst Test, dann Code.** Jeder Bugfix beginnt mit einem Test, der den Fehler zeigt (rot), dann der Fix (grün).
|
1. **Erst Test, dann Code.** Jeder Bugfix beginnt mit einem Test, der den Fehler zeigt (rot), dann der Fix (grün).
|
||||||
@@ -151,7 +175,8 @@ ist die Aufgabenliste – Tasks der Reihe nach, Task-ID im Commit, erledigte Tas
|
|||||||
REST-Endpunkte und WS-Nachrichten aus `game/protocol.js`. Protokolländerung = `PROTOCOL_VERSION` erhöhen.
|
REST-Endpunkte und WS-Nachrichten aus `game/protocol.js`. Protokolländerung = `PROTOCOL_VERSION` erhöhen.
|
||||||
6. **Seat/Index-Spiegelung** nur an einer Stelle (`protocol.js`), mit Test. Nie im Spielcode verstreut.
|
6. **Seat/Index-Spiegelung** nur an einer Stelle (`protocol.js`), mit Test. Nie im Spielcode verstreut.
|
||||||
7. **Kampagne bleibt offline:** nach jeder Änderung `game/index.html` per Doppelklick (`file://`) prüfen.
|
7. **Kampagne bleibt offline:** nach jeder Änderung `game/index.html` per Doppelklick (`file://`) prüfen.
|
||||||
UI-Änderung → `&uicheck` laufen lassen.
|
UI-Änderung → `&uicheck` laufen lassen. Änderung an UI, Netz, Lobby, Kampf oder Shop → zusätzlich `npm run e2e`
|
||||||
|
(deckt Online-Kampf und `file://`-Kampagne im echten Browser ab).
|
||||||
8. **Server-Änderungen** auf den Dev-Server (`roboclash.michael-media.de`, derzeit einziges Server-System, darf
|
8. **Server-Änderungen** auf den Dev-Server (`roboclash.michael-media.de`, derzeit einziges Server-System, darf
|
||||||
per `npm run db:reset` zurückgesetzt werden) deployen und dort prüfen. Nie direkt auf dem Server Dateien
|
per `npm run db:reset` zurückgesetzt werden) deployen und dort prüfen. Nie direkt auf dem Server Dateien
|
||||||
editieren – nur über das Deploy-Skript. Produktion kommt später als eigene Umgebung.
|
editieren – nur über das Deploy-Skript. Produktion kommt später als eigene Umgebung.
|
||||||
@@ -185,11 +210,10 @@ es ein Produktionssystem gibt**. Dann zuerst Plan-Task **T-4** (Refactoring + Se
|
|||||||
- Grafik und Sound nur über `sprite-generator/` (ComfyGen, Katalog `_Tools\README.md`), Stilblock aus dem
|
- Grafik und Sound nur über `sprite-generator/` (ComfyGen, Katalog `_Tools\README.md`), Stilblock aus dem
|
||||||
Spielkonzept für alle Prompts. App-Icon = `game/assets/Sprites/icon.png` (`gen adopt --size 512 icon`).
|
Spielkonzept für alle Prompts. App-Icon = `game/assets/Sprites/icon.png` (`gen adopt --size 512 icon`).
|
||||||
Fehlt ein Bild oder Sound, läuft das Spiel mit prozeduraler Grafik / Synth-Sound weiter – nie abstürzen.
|
Fehlt ein Bild oder Sound, läuft das Spiel mit prozeduraler Grafik / Synth-Sound weiter – nie abstürzen.
|
||||||
- `admin/` liegt außerhalb `game/` und kommt **nicht** in den Build (`admin/index.html` Live-Steuerung,
|
- `admin/` liegt außerhalb `game/` und kommt **nicht** in den Release-Build. `admin/index.html` (Live-Steuerung:
|
||||||
`admin/cleanup.js` Firebase-Aufräumen per Admin-SDK). Service-Account-Keys sind geheim (`.gitignore`
|
Events, Nachricht, Sperren) liefert der Server unter `/admin/` aus; Speichern nur mit Admin-Konto (Server prüft).
|
||||||
deckt `serviceAccount*.json`) – nie hochladen/committen. Aufruf siehe `docs/firebase/README.md`.
|
- Git-Remote: Gitea (`origin`, `ssh://git@gitea.oezcan.cloud:32772/malkano.michael/Robot-Clash.git`).
|
||||||
- Git-Remote: Gitea (`origin`, `ssh://git@gitea.oezcan.cloud:32772/malkano.michael/Robot-Clash.git`). Arbeit auf
|
**Direkt auf `main` committen** (`main` = Dev). Kein Branch-/PR-Workflow – Michi und Benni arbeiten im Pair
|
||||||
**direkt auf `main` committen** (`main` = Dev). Kein Branch-/PR-Workflow – Michi und Benni arbeiten im Pair
|
|
||||||
Programming. Branches nur für Experimente, die man evtl. komplett verwirft. Commit/Push nur, wenn Michael oder
|
Programming. Branches nur für Experimente, die man evtl. komplett verwirft. Commit/Push nur, wenn Michael oder
|
||||||
Benni es sagt.
|
Benni es sagt.
|
||||||
- **Commit-Messages nach [Conventional Commits](https://www.conventionalcommits.org/):** `<typ>(<bereich>): <was>`,
|
- **Commit-Messages nach [Conventional Commits](https://www.conventionalcommits.org/):** `<typ>(<bereich>): <was>`,
|
||||||
|
|||||||
17
README.md
17
README.md
@@ -33,7 +33,7 @@ npm run dev # Server + Spiel lokal auf http://localhost:8080 (vorher serv
|
|||||||
npm run balance # Balance-Zahlen
|
npm run balance # Balance-Zahlen
|
||||||
```
|
```
|
||||||
|
|
||||||
**Laufender Umbau** (Multiplayer server-autoritativ, Firebase raus, Deploy): [`docs/MULTIPLAYER-PLAN.md`](docs/MULTIPLAYER-PLAN.md).
|
**Laufender Umbau** (Multiplayer server-autoritativ, Deploy): [`docs/MULTIPLAYER-PLAN.md`](docs/MULTIPLAYER-PLAN.md).
|
||||||
Git: direkt auf `main` (= Dev), Conventional Commits, Regeln in `CLAUDE.md`.
|
Git: direkt auf `main` (= Dev), Conventional Commits, Regeln in `CLAUDE.md`.
|
||||||
|
|
||||||
## Aufbau
|
## Aufbau
|
||||||
@@ -45,10 +45,12 @@ game/
|
|||||||
shop.js Werkstatt-Shop (Teile kaufen/einbauen/verkaufen, Vergleich, Lack, Mechaniker)
|
shop.js Werkstatt-Shop (Teile kaufen/einbauen/verkaufen, Vergleich, Lack, Mechaniker)
|
||||||
looks.js Aussehen der Liga-Gegner (wie ihre Porträts)
|
looks.js Aussehen der Liga-Gegner (wie ihre Porträts)
|
||||||
painter.js Lackiererei: selbst auf den Roboter malen, live in 3D
|
painter.js Lackiererei: selbst auf den Roboter malen, live in 3D
|
||||||
net.js Firebase über REST (Login, Datenbank, Push) – für Online
|
net.js eigener Server: REST + ein WebSocket (Login, Online-Spielstand, Lobby, Kampf)
|
||||||
|
protocol.js Netz-Nachrichten, Validierung, Snapshots (Client + Server)
|
||||||
|
eco.js Werkstatt-Wirtschaft: Kaufen/Verkaufen/Einbauen (Client + Server, gleiche Regeln)
|
||||||
lobby.js globale Online-Lobby (wer ist da, herausfordern)
|
lobby.js globale Online-Lobby (wer ist da, herausfordern)
|
||||||
netfight.js Live-PvP-Synchronisation
|
netfight.js zeigt den vom Server gerechneten Live-Kampf
|
||||||
profiles.js Konten: registrieren, einloggen, Gast (lokal, später Firebase)
|
profiles.js lokale Konten für die Offline-Kampagne
|
||||||
parts.js Teilekatalog (Werte, Preise) ┐
|
parts.js Teilekatalog (Werte, Preise) ┐
|
||||||
robot.js Bauregeln + Kampfwerte aus Teilen │ ohne DOM,
|
robot.js Bauregeln + Kampfwerte aus Teilen │ ohne DOM,
|
||||||
combat.js Physik, Waffen, Fallen, Grube, Sieg │ laufen auch in Node
|
combat.js Physik, Waffen, Fallen, Grube, Sieg │ laufen auch in Node
|
||||||
@@ -61,7 +63,8 @@ game/
|
|||||||
tests/ sim.test.js, balance.js
|
tests/ sim.test.js, balance.js
|
||||||
launcher/ Windows-Fenster (WebView2) → RobotClash.exe
|
launcher/ Windows-Fenster (WebView2) → RobotClash.exe
|
||||||
sprite-generator/ ComfyGen-Projekt: gen generate <name>, gen adopt <name>, gen generate_audio <name>
|
sprite-generator/ ComfyGen-Projekt: gen generate <name>, gen adopt <name>, gen generate_audio <name>
|
||||||
docs/firebase/ Online-Rangliste einrichten (danach DB_URL in game.js eintragen)
|
server/ Node-Server: Konten, Online-Wirtschaft, Lobby, Live-Kämpfe (server/README.md)
|
||||||
|
admin/ Live-Steuerung, vom Server unter /admin/ ausgeliefert
|
||||||
docs/itchio/ itch.io-Seite
|
docs/itchio/ itch.io-Seite
|
||||||
build-web.mjs → release/robotclash.html (alles in einer Datei)
|
build-web.mjs → release/robotclash.html (alles in einer Datei)
|
||||||
build.ps1 → release/RobotClash.exe + robotclash.html + robotclash-web.zip
|
build.ps1 → release/RobotClash.exe + robotclash.html + robotclash-web.zip
|
||||||
@@ -69,8 +72,8 @@ build.ps1 → release/RobotClash.exe + robotclash.html + robotclash-web.z
|
|||||||
|
|
||||||
## Online (optional)
|
## Online (optional)
|
||||||
|
|
||||||
Online läuft über den eigenen Node-Server (`server/`, Deploy siehe `server/deploy/README.md`).
|
Online läuft über den eigenen Node-Server (`server/`, Details `server/README.md`, Deploy `server/deploy/README.md`).
|
||||||
> **Veraltet:** Firebase-Hinweise (`docs/firebase/`, `NET_CFG.apiKey`) gelten nicht mehr und werden mit Plan-Task P1-8 entfernt.
|
Der Server rechnet die Live-Kämpfe und verwaltet Geld, Teile und Ruhm; über `file://` läuft nur die Kampagne.
|
||||||
|
|
||||||
## Release
|
## Release
|
||||||
|
|
||||||
|
|||||||
@@ -1,90 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
/* Robot Clash - Firebase cleanup. DRY-RUN by default: it only lists what it WOULD delete.
|
|
||||||
*
|
|
||||||
* npm install firebase-admin (once, locally)
|
|
||||||
* node admin/cleanup.js --key serviceAccount.json # preview, deletes nothing
|
|
||||||
* node admin/cleanup.js --key serviceAccount.json --apply # actually delete
|
|
||||||
*
|
|
||||||
* Options: --db <rtdb-url> --stale-min <minutes, default 10>
|
|
||||||
* The service-account key is a SECRET: never commit or upload it (add it to .gitignore).
|
|
||||||
*
|
|
||||||
* Deletes (only with --apply): anonymous guest accounts (no e-mail), stale lobby/ presence,
|
|
||||||
* and orphan saves/ ranks/ users/ nodes whose uid no longer exists in Auth.
|
|
||||||
*/
|
|
||||||
'use strict';
|
|
||||||
const admin = require('firebase-admin');
|
|
||||||
const fs = require('fs');
|
|
||||||
|
|
||||||
function arg(name, def) {
|
|
||||||
const i = process.argv.indexOf('--' + name);
|
|
||||||
if (i < 0) return def;
|
|
||||||
const next = process.argv[i + 1];
|
|
||||||
return next && !next.startsWith('--') ? next : true;
|
|
||||||
}
|
|
||||||
const keyPath = arg('key', process.env.GOOGLE_APPLICATION_CREDENTIALS);
|
|
||||||
const DB = arg('db', 'https://robot-clash-aa37b-default-rtdb.firebaseio.com');
|
|
||||||
const APPLY = arg('apply', false) === true;
|
|
||||||
const STALE_MIN = +arg('stale-min', 10);
|
|
||||||
|
|
||||||
if (!keyPath || keyPath === true) {
|
|
||||||
console.error('Need --key <serviceAccount.json> (or set GOOGLE_APPLICATION_CREDENTIALS).');
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
admin.initializeApp({
|
|
||||||
credential: admin.credential.cert(JSON.parse(fs.readFileSync(keyPath, 'utf8'))),
|
|
||||||
databaseURL: DB,
|
|
||||||
});
|
|
||||||
const auth = admin.auth();
|
|
||||||
const db = admin.database();
|
|
||||||
|
|
||||||
(async () => {
|
|
||||||
console.log(APPLY ? '=== APPLY: deleting ===' : '=== DRY-RUN: nothing is deleted ===');
|
|
||||||
|
|
||||||
// 1) all auth users; flag anonymous (no e-mail and no linked provider)
|
|
||||||
const uids = new Set();
|
|
||||||
const anon = [];
|
|
||||||
let pageToken;
|
|
||||||
do {
|
|
||||||
const res = await auth.listUsers(1000, pageToken);
|
|
||||||
for (const u of res.users) {
|
|
||||||
uids.add(u.uid);
|
|
||||||
const registered = !!u.email || (u.providerData && u.providerData.length > 0);
|
|
||||||
if (!registered) anon.push(u.uid);
|
|
||||||
}
|
|
||||||
pageToken = res.pageToken;
|
|
||||||
} while (pageToken);
|
|
||||||
console.log(`Auth users: ${uids.size} total, ${anon.length} anonymous/guest`);
|
|
||||||
|
|
||||||
// 2) stale lobby presence (no ts or older than the cutoff)
|
|
||||||
const cutoff = Date.now() - STALE_MIN * 60000;
|
|
||||||
const lobby = (await db.ref('lobby').get()).val() || {};
|
|
||||||
const staleLobby = Object.entries(lobby).filter(([, v]) => !v || !v.ts || v.ts < cutoff).map(([k]) => k);
|
|
||||||
console.log(`Lobby: ${Object.keys(lobby).length} entries, ${staleLobby.length} stale (> ${STALE_MIN} min)`);
|
|
||||||
|
|
||||||
// 3) orphan RTDB nodes (uid no longer exists in Auth)
|
|
||||||
const orphans = {};
|
|
||||||
for (const node of ['saves', 'ranks', 'users']) {
|
|
||||||
const data = (await db.ref(node).get()).val() || {};
|
|
||||||
orphans[node] = Object.keys(data).filter(uid => !uids.has(uid));
|
|
||||||
console.log(`${node}: ${Object.keys(data).length} entries, ${orphans[node].length} orphan`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!APPLY) {
|
|
||||||
console.log('\nWould delete:');
|
|
||||||
console.log(' anonymous accounts :', anon.length);
|
|
||||||
console.log(' stale lobby :', staleLobby.length);
|
|
||||||
for (const node of Object.keys(orphans)) console.log(` orphan ${node.padEnd(12)}:`, orphans[node].length);
|
|
||||||
console.log('\nRe-run with --apply to actually delete.');
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
let n = 0;
|
|
||||||
for (let i = 0; i < anon.length; i += 1000) { const r = await auth.deleteUsers(anon.slice(i, i + 1000)); n += r.successCount; }
|
|
||||||
console.log(`Deleted ${n} anonymous accounts.`);
|
|
||||||
for (const uid of staleLobby) await db.ref('lobby/' + uid).remove();
|
|
||||||
console.log(`Removed ${staleLobby.length} stale lobby entries.`);
|
|
||||||
for (const node of Object.keys(orphans)) { for (const uid of orphans[node]) await db.ref(node + '/' + uid).remove(); console.log(`Removed ${orphans[node].length} orphan ${node}.`); }
|
|
||||||
console.log('Done.');
|
|
||||||
process.exit(0);
|
|
||||||
})().catch(e => { console.error(e); process.exit(1); });
|
|
||||||
@@ -5,10 +5,9 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Robot Clash – Admin</title>
|
<title>Robot Clash – Admin</title>
|
||||||
<!--
|
<!--
|
||||||
Robot Clash backend admin. LOCAL TOOL ONLY - open by double-click, never upload.
|
Robot Clash backend admin, served by the game server at /admin/ (e.g. https://roboclash.michael-media.de/admin/).
|
||||||
It only works for the one Firebase account whose UID is in the database rules (node "live"),
|
Saving needs an account with role 'admin' (seed accounts michi / benni, see server/scripts/reset-db.js) -
|
||||||
so even if this file leaked it could not change anything without that account's password.
|
the server checks it, the page itself grants nothing. Writes the live settings every player reads (game/live.js).
|
||||||
Writes to /live, which every player reads (RC.Live in game/live.js).
|
|
||||||
-->
|
-->
|
||||||
<style>
|
<style>
|
||||||
:root { --bg:#0b0e13; --panel:#161b22; --panel2:#1d232d; --line:#2d3442; --text:#e8ebf2; --dim:#8d95a8;
|
:root { --bg:#0b0e13; --panel:#161b22; --panel2:#1d232d; --line:#2d3442; --text:#e8ebf2; --dim:#8d95a8;
|
||||||
@@ -62,9 +61,9 @@
|
|||||||
<!-- login -->
|
<!-- login -->
|
||||||
<div class="card" id="login">
|
<div class="card" id="login">
|
||||||
<h2>Anmelden</h2>
|
<h2>Anmelden</h2>
|
||||||
<p class="muted">Mit dem Admin-Konto (E-Mail + Master-Passwort), dessen UID in den Firebase-Regeln steht.</p>
|
<p class="muted">Mit einem Spielkonto, das auf dem Server Admin-Recht hat (z. B. michi oder benni).</p>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div><label>E-Mail</label><input type="email" id="mail" autocomplete="username"></div>
|
<div><label>Name oder E-Mail</label><input type="text" id="mail" autocomplete="username"></div>
|
||||||
<div><label>Passwort</label><input type="password" id="pass" autocomplete="current-password"></div>
|
<div><label>Passwort</label><input type="password" id="pass" autocomplete="current-password"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="bar"><button class="primary" id="bLogin">Anmelden</button></div>
|
<div class="bar"><button class="primary" id="bLogin">Anmelden</button></div>
|
||||||
@@ -140,17 +139,25 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script src="../game/kit/kit-core.js"></script>
|
<script src="/kit/kit-core.js"></script>
|
||||||
<script src="../game/parts.js"></script>
|
<script src="/kit/kit-scores.js"></script>
|
||||||
<script src="../game/robot.js"></script>
|
<script src="/parts.js"></script>
|
||||||
<script src="../game/combat.js"></script>
|
<script src="/robot.js"></script>
|
||||||
<script src="../game/net.js"></script>
|
<script src="/combat.js"></script>
|
||||||
|
<script src="/protocol.js"></script>
|
||||||
|
<script src="/net.js"></script>
|
||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
'use strict';
|
'use strict';
|
||||||
var RC = window.RC, Kit = window.Kit;
|
var RC = window.RC, Kit = window.Kit;
|
||||||
var net = RC.Net({ apiKey: 'AIzaSyCE29VQnubM_9ok46nnosg07MpvhZH3O5w',
|
var net = RC.Net({ serverUrl: '' }); // same origin: the page is served by the game server
|
||||||
dbUrl: 'https://robot-clash-aa37b-default-rtdb.firebaseio.com' });
|
// tiny adapter: the page's get/put/push/del calls -> the server's admin endpoints
|
||||||
|
var db = {
|
||||||
|
get: function (p) { return net.api('GET', p === 'live' ? '/api/live' : '/api/admin/events'); },
|
||||||
|
put: function (p, v) { return net.api('PUT', '/api/admin/live', v).then(function (r) { return !!(r && r.ok); }); },
|
||||||
|
push: function (p, v) { return net.api('POST', '/api/admin/events', v).then(function (r) { return r && r.name; }); },
|
||||||
|
del: function (p) { return net.api('DELETE', '/api/admin/events/' + encodeURIComponent(p.split('/').pop())); },
|
||||||
|
};
|
||||||
var $ = function (id) { return document.getElementById(id); };
|
var $ = function (id) { return document.getElementById(id); };
|
||||||
|
|
||||||
// ---- build the pick lists from the real game data ----
|
// ---- build the pick lists from the real game data ----
|
||||||
@@ -189,7 +196,7 @@
|
|||||||
$('panel').classList.remove('hide');
|
$('panel').classList.remove('hide');
|
||||||
$('who').textContent = acc.email || acc.name;
|
$('who').textContent = acc.email || acc.name;
|
||||||
$('uid').textContent = acc.uid;
|
$('uid').textContent = acc.uid;
|
||||||
$('uidHint').textContent = 'Diese UID muss in den Firebase-Regeln bei "live" (und "admin" für Vorlagen) stehen, sonst wird Speichern abgelehnt.';
|
$('uidHint').textContent = net.auth.current && net.auth.current.admin ? 'Admin-Recht: ja.' : 'Kein Admin-Recht - Speichern wird vom Server abgelehnt.';
|
||||||
loadLive();
|
loadLive();
|
||||||
loadPresets();
|
loadPresets();
|
||||||
}
|
}
|
||||||
@@ -228,7 +235,7 @@
|
|||||||
$('evOn').onchange = toggleEv;
|
$('evOn').onchange = toggleEv;
|
||||||
|
|
||||||
function loadLive() {
|
function loadLive() {
|
||||||
net.db.get('live').then(function (d) { fill(d || {}); });
|
db.get('live').then(function (d) { fill(d || {}); });
|
||||||
}
|
}
|
||||||
$('bReload').onclick = loadLive;
|
$('bReload').onclick = loadLive;
|
||||||
|
|
||||||
@@ -260,14 +267,14 @@
|
|||||||
$('bSave').onclick = function () {
|
$('bSave').onclick = function () {
|
||||||
var data = collect(), msg = $('saveMsg');
|
var data = collect(), msg = $('saveMsg');
|
||||||
msg.className = 'status'; msg.textContent = 'Speichern…';
|
msg.className = 'status'; msg.textContent = 'Speichern…';
|
||||||
net.db.put('live', data).then(function (ok) {
|
db.put('live', data).then(function (ok) {
|
||||||
if (ok) { msg.className = 'status ok'; msg.textContent = 'Gespeichert – alle Spieler sehen es sofort.'; $('dump').textContent = JSON.stringify(data, null, 2); }
|
if (ok) { msg.className = 'status ok'; msg.textContent = 'Gespeichert – alle Spieler sehen es sofort.'; $('dump').textContent = JSON.stringify(data, null, 2); }
|
||||||
else { msg.className = 'status err'; msg.textContent = 'Abgelehnt. Steht deine UID in den Firebase-Regeln bei "live"?'; }
|
else { msg.className = 'status err'; msg.textContent = 'Abgelehnt. Hat dein Konto Admin-Recht?'; }
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
$('bClear').onclick = function () {
|
$('bClear').onclick = function () {
|
||||||
if (!confirm('Wirklich alles zurücksetzen? Danach läuft kein Event, keine Nachricht, keine Sperre.')) return;
|
if (!confirm('Wirklich alles zurücksetzen? Danach läuft kein Event, keine Nachricht, keine Sperre.')) return;
|
||||||
net.db.put('live', {}).then(function (ok) {
|
db.put('live', {}).then(function (ok) {
|
||||||
var msg = $('saveMsg');
|
var msg = $('saveMsg');
|
||||||
msg.className = ok ? 'status ok' : 'status err';
|
msg.className = ok ? 'status ok' : 'status err';
|
||||||
msg.textContent = ok ? 'Zurückgesetzt.' : 'Abgelehnt.';
|
msg.textContent = ok ? 'Zurückgesetzt.' : 'Abgelehnt.';
|
||||||
@@ -296,7 +303,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function loadPresets() {
|
function loadPresets() {
|
||||||
net.db.get('admin/events').then(function (m) { renderPresets(m || {}); });
|
db.get('admin/events').then(function (m) { renderPresets(m || {}); });
|
||||||
}
|
}
|
||||||
function renderPresets(m) {
|
function renderPresets(m) {
|
||||||
var box = $('presetList'), keys = Object.keys(m);
|
var box = $('presetList'), keys = Object.keys(m);
|
||||||
@@ -317,7 +324,7 @@
|
|||||||
row.querySelector('[data-act="on"]').onclick = function () { activatePreset(p); };
|
row.querySelector('[data-act="on"]').onclick = function () { activatePreset(p); };
|
||||||
row.querySelector('[data-act="del"]').onclick = function () {
|
row.querySelector('[data-act="del"]').onclick = function () {
|
||||||
if (!confirm('Vorlage „' + (p.name || '') + '“ löschen?')) return;
|
if (!confirm('Vorlage „' + (p.name || '') + '“ löschen?')) return;
|
||||||
net.db.del('admin/events/' + k).then(loadPresets);
|
db.del('admin/events/' + k).then(loadPresets);
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -333,10 +340,10 @@
|
|||||||
var name = $('presetName').value.trim();
|
var name = $('presetName').value.trim();
|
||||||
if (!name) { alert('Bitte einen Vorlage-Namen eingeben.'); return; }
|
if (!name) { alert('Bitte einen Vorlage-Namen eingeben.'); return; }
|
||||||
var preset = { name: name, hours: parseInt($('presetHours').value, 10) || 48, event: eventFromForm() };
|
var preset = { name: name, hours: parseInt($('presetHours').value, 10) || 48, event: eventFromForm() };
|
||||||
net.db.push('admin/events', preset).then(function (key) {
|
db.push('admin/events', preset).then(function (key) {
|
||||||
$('presetName').value = '';
|
$('presetName').value = '';
|
||||||
var msg = $('saveMsg'); msg.className = key ? 'status ok' : 'status err';
|
var msg = $('saveMsg'); msg.className = key ? 'status ok' : 'status err';
|
||||||
msg.textContent = key ? 'Vorlage gespeichert.' : 'Vorlage abgelehnt – steht die UID in den Regeln bei "admin"?';
|
msg.textContent = key ? 'Vorlage gespeichert.' : 'Vorlage abgelehnt – hat dein Konto Admin-Recht?';
|
||||||
loadPresets();
|
loadPresets();
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,63 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
/* Robot Clash - set a player's coins (and optionally fame) in the cloud save. For testing.
|
|
||||||
*
|
|
||||||
* npm install firebase-admin
|
|
||||||
* node admin/setcoins.js --key serviceAccount.json --name SN09 --coins 2000000
|
|
||||||
* node admin/setcoins.js --key serviceAccount.json --email me@x.de --coins 2000000 --fame 50000
|
|
||||||
* node admin/setcoins.js --key serviceAccount.json --uid <uid> --coins 2000000
|
|
||||||
*
|
|
||||||
* It MERGES money/fame + a fresh ts into saves/<uid>, so the game takes it on next login (newer ts wins)
|
|
||||||
* and the rest of the save (robots, parts) stays intact. The account must have synced at least once
|
|
||||||
* (logged in after the cloud-save update) so a full save already exists.
|
|
||||||
*/
|
|
||||||
'use strict';
|
|
||||||
const admin = require('firebase-admin');
|
|
||||||
const fs = require('fs');
|
|
||||||
|
|
||||||
function arg(name, def) {
|
|
||||||
const i = process.argv.indexOf('--' + name);
|
|
||||||
if (i < 0) return def;
|
|
||||||
const next = process.argv[i + 1];
|
|
||||||
return next && !next.startsWith('--') ? next : true;
|
|
||||||
}
|
|
||||||
const keyPath = arg('key', process.env.GOOGLE_APPLICATION_CREDENTIALS);
|
|
||||||
const DB = arg('db', 'https://robot-clash-aa37b-default-rtdb.firebaseio.com');
|
|
||||||
const coins = arg('coins', undefined);
|
|
||||||
const fame = arg('fame', undefined);
|
|
||||||
let uid = arg('uid', undefined);
|
|
||||||
const email = arg('email', undefined);
|
|
||||||
const name = arg('name', undefined);
|
|
||||||
|
|
||||||
if (!keyPath || keyPath === true) { console.error('Need --key <serviceAccount.json>.'); process.exit(1); }
|
|
||||||
if (coins === undefined && fame === undefined) { console.error('Need --coins <n> and/or --fame <n>.'); process.exit(1); }
|
|
||||||
|
|
||||||
admin.initializeApp({
|
|
||||||
credential: admin.credential.cert(JSON.parse(fs.readFileSync(keyPath, 'utf8'))),
|
|
||||||
databaseURL: DB,
|
|
||||||
});
|
|
||||||
const auth = admin.auth();
|
|
||||||
const db = admin.database();
|
|
||||||
|
|
||||||
(async () => {
|
|
||||||
if (!uid && email) { uid = (await auth.getUserByEmail(email)).uid; }
|
|
||||||
if (!uid && name) {
|
|
||||||
// match the display name in users/<uid>/name (set on register/login)
|
|
||||||
const users = (await db.ref('users').get()).val() || {};
|
|
||||||
const hit = Object.entries(users).find(([, v]) => v && v.name === name);
|
|
||||||
if (hit) uid = hit[0];
|
|
||||||
if (!uid) { console.error(`No account found with name "${name}" in users/.`); process.exit(1); }
|
|
||||||
}
|
|
||||||
if (!uid) { console.error('Need one of --uid / --email / --name.'); process.exit(1); }
|
|
||||||
|
|
||||||
const snap = await db.ref('saves/' + uid).get();
|
|
||||||
if (!snap.exists()) {
|
|
||||||
console.error(`saves/${uid} does not exist yet. Let that account log in once (after the cloud-save update), then re-run.`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
const patch = { ts: Date.now() };
|
|
||||||
if (coins !== undefined) patch.money = +coins;
|
|
||||||
if (fame !== undefined) patch.fame = +fame;
|
|
||||||
await db.ref('saves/' + uid).update(patch);
|
|
||||||
console.log(`Updated saves/${uid}:`, patch, '\nThe player gets it on their next login/refresh.');
|
|
||||||
process.exit(0);
|
|
||||||
})().catch(e => { console.error(e); process.exit(1); });
|
|
||||||
@@ -8,6 +8,30 @@
|
|||||||
|
|
||||||
Stand der Analyse: 2026-11-19 (Commit `347701d`).
|
Stand der Analyse: 2026-11-19 (Commit `347701d`).
|
||||||
|
|
||||||
|
## Umsetzungsstand (2026-11-19)
|
||||||
|
|
||||||
|
**Erledigt:** Phase 0, Phase 1, Phase 2 (außer P2-6), aus Phase 3: P3-1b, P3-2, P3-3 (+ Teile von P3-1), aus Phase 4:
|
||||||
|
Smoke-Test (`npm run smoke -- <url>`, Vorstufe von P4-1), P4-2 Playwright (9 Browser-Tests, `npm run e2e`),
|
||||||
|
P4-5 `game.js` aufgeteilt (1996 → ~1380 Zeilen + `sfx.js`, `pages.js`, `online.js`, `workshop.js`). **Live** auf `https://roboclash.michael-media.de` (Dev).
|
||||||
|
Geprüft: 46 automatische Tests, Smoke-Test gegen den Dev-Server (WebSocket über Caddy/TLS, 20 Snapshots/s,
|
||||||
|
gespiegeltes Ergebnis), zwei Browser-Tabs michi gegen benni lokal (Kampf, Ergebnis, Belohnung, Hintergrund-Tab),
|
||||||
|
Shop-Kauf landet in der Server-DB, Kampagne offline über `file://` (headless + `&uicheck`).
|
||||||
|
|
||||||
|
**Abweichungen vom ursprünglichen Plan (bewusst):**
|
||||||
|
- Online-Spielstand = **ein JSON-Dokument pro Spieler** (`online_saves`) statt Tabellen `inventory`/`robots`.
|
||||||
|
Konsistenz kommt daher, dass nur `RC.Eco` (`game/eco.js`) und Kampfbelohnungen es ändern – dieselben Regeln wie
|
||||||
|
im Client. Einfacher und ohne doppelte Regeln; bei Bedarf später normalisieren.
|
||||||
|
- Erfolge (zahlen Credits) werden online **vom Server** vergeben (`server/economy.js` → `RC.Progress`).
|
||||||
|
- Starter-Teile verkaufen sich für 0 Credits (sonst Geld-Exploit über „neuer Roboter → Teile verkaufen“).
|
||||||
|
- Online-Turnier (`netourney.js`, P2P über die alte DB) entfernt → kommt mit **P2-6** server-seitig zurück.
|
||||||
|
- Admin-Seite läuft jetzt unter `/admin/` auf dem Server; `admin/cleanup.js`/`setcoins.js` (Firebase) gelöscht.
|
||||||
|
|
||||||
|
**Offen / nächste Schritte:** P2-6 (Online-Turnier), P3-1 Rest (SSH-Nutzer `deploy`, Passwort-Login aus), P3-5
|
||||||
|
(Logs/Monitoring), P3-6 (Gitea Actions + act_runner), P4-3 Lasttest (Bot ist da: mehrere `npm run bot` parallel),
|
||||||
|
P4-4 Vorhersage (erst nach Spieltest), `tests/sim.test.js:442` (halber Test).
|
||||||
|
Hinweis: Der Smoke-Test legt Gastkonten an (`SmokeA`/`SmokeB`), die in der Rangliste auftauchen können →
|
||||||
|
`--reset-db` beim Deploy räumt auf.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Warum der Umbau (Kurzfassung der Analyse)
|
## 1. Warum der Umbau (Kurzfassung der Analyse)
|
||||||
@@ -169,37 +193,46 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
|
|||||||
|
|
||||||
### Phase 1 – Server-autoritativer Kampf über WebSocket
|
### Phase 1 – Server-autoritativer Kampf über WebSocket
|
||||||
|
|
||||||
- [ ] **P1-1 `game/protocol.js`** (UMD, ohne DOM): Typkonstanten, `PROTOCOL_VERSION`, Validierer je Nachricht
|
- [x] **P1-1 `game/protocol.js`** (UMD, ohne DOM): Typkonstanten, `PROTOCOL_VERSION`, Validierer je Nachricht
|
||||||
(`validate(msg) → {ok, error}`), `packSnap(state)` / `unpackSnap`, `toLocal(seat, …)`.
|
(`validate(msg) → {ok, error}`), `packSnap(state)` / `unpackSnap`, `toLocal(seat, …)`.
|
||||||
*AK:* Unit-Tests für jeden Validierer (gültig/ungültig/Grenzwerte) und Seat-Mapping in beide Richtungen.
|
*AK:* Unit-Tests für jeden Validierer (gültig/ungültig/Grenzwerte) und Seat-Mapping in beide Richtungen.
|
||||||
- [ ] **P1-2 WS-Hub** `server/ws/hub.js`: `ws` an den HTTP-Server hängen (`/ws`), `hello` mit JWT innerhalb 5 s,
|
- [x] **P1-2 WS-Hub** `server/ws/hub.js`: `ws` an den HTTP-Server hängen (`/ws`), `hello` mit JWT innerhalb 5 s,
|
||||||
sonst schließen; Ping/Pong; Größenlimit pro Nachricht (8 KB), Rate-Limit (z. B. 60 Nachrichten/s).
|
sonst schließen; Ping/Pong; Größenlimit pro Nachricht (8 KB), Rate-Limit (z. B. 60 Nachrichten/s).
|
||||||
Eine Verbindung pro uid (neue ersetzt alte). *AK:* Integrationstest: ohne Token → zu; mit Token → `welcome`.
|
Eine Verbindung pro uid (neue ersetzt alte). *AK:* Integrationstest: ohne Token → zu; mit Token → `welcome`.
|
||||||
- [ ] **P1-3 Match-Raum** `server/match/room.js`: wie 4.2. Reine Klasse ohne Netzwerk (Eingaben rein, Snapshots raus),
|
- [x] **P1-3 Match-Raum** `server/match/room.js`: wie 4.2. Reine Klasse ohne Netzwerk (Eingaben rein, Snapshots raus),
|
||||||
damit sie ohne Sockets testbar ist. *AK:* Test lässt zwei KI-Eingabeströme einen ganzen Kampf spielen →
|
damit sie ohne Sockets testbar ist. *AK:* Test lässt zwei KI-Eingabeströme einen ganzen Kampf spielen →
|
||||||
genau ein Ergebnis, kein NaN, Ergebnis aus Sicht beider Seats konsistent (Gewinner A ⇔ Verlierer B).
|
genau ein Ergebnis, kein NaN, Ergebnis aus Sicht beider Seats konsistent (Gewinner A ⇔ Verlierer B).
|
||||||
- [ ] **P1-4 Lobby** `server/lobby.js`: Präsenz = authentifizierte Verbindung, Status idle/challenging/inmatch,
|
- [x] **P1-4 Lobby** `server/lobby.js`: Präsenz = authentifizierte Verbindung, Status idle/challenging/inmatch,
|
||||||
Räume nach Land, Challenges mit 15-s-Timeout (Serverzeit), keine Doppel-Challenges, Rematch.
|
Räume nach Land, Challenges mit 15-s-Timeout (Serverzeit), keine Doppel-Challenges, Rematch.
|
||||||
*AK:* Integrationstest mit 3 Clients: Liste, Challenge, Decline, Accept → `match.start` an beide.
|
*AK:* Integrationstest mit 3 Clients: Liste, Challenge, Decline, Accept → `match.start` an beide.
|
||||||
- [ ] **P1-5 Client `net.js` neu:** REST + WS, Reconnect mit Backoff, Single-Flight-Refresh, Ereignis-API
|
- [x] **P1-5 Client `net.js` neu:** REST + WS, Reconnect mit Backoff, Single-Flight-Refresh, Ereignis-API
|
||||||
(`net.on('lobby'|'challenge.in'|'match.start'|…)`). *AK:* Test in Node (mit `ws`-Client): Refresh unter
|
(`net.on('lobby'|'challenge.in'|'match.start'|…)`). *AK:* Test in Node (mit `ws`-Client): Refresh unter
|
||||||
Parallelität loggt nicht aus.
|
Parallelität loggt nicht aus.
|
||||||
- [ ] **P1-6 Client `netfight.js` neu:** Eingaben senden, Snapshots interpolieren, `match.end` anzeigen;
|
- [x] **P1-6 Client `netfight.js` neu:** Eingaben senden, Snapshots interpolieren, `match.end` anzeigen;
|
||||||
`game.js` nimmt das Ergebnis vom Server statt `s.result` selbst zu werten. *AK:* Zwei Browser-Fenster
|
`game.js` nimmt das Ergebnis vom Server statt `s.result` selbst zu werten. *AK:* Zwei Browser-Fenster
|
||||||
(oder Playwright, P4-2) spielen einen Kampf; beide sehen dasselbe Ergebnis aus ihrer Sicht.
|
(oder Playwright, P4-2) spielen einen Kampf; beide sehen dasselbe Ergebnis aus ihrer Sicht.
|
||||||
- [ ] **P1-7 Disconnect/Reconnect:** Gnadenfrist, KI-Übernahme, Wiederverbinden. *AK:* Test trennt einen Client
|
- **BEFUND 2026-11-19 (Michi laggt, Benni nicht):** `netfight.js` hat **keinen Jitter-Puffer** umgesetzt – es
|
||||||
|
zog den lokalen Zustand nur zum *neuesten* Snapshot (`k = dt*14`), nicht wie hier geplant „zwischen den zwei
|
||||||
|
letzten Snapshots (~100 ms Puffer)" (Zeile 151). Bei ungleichmäßiger Snapshot-Ankunft (Jitter/Bufferbloat,
|
||||||
|
auch über Kabel) bremst der Roboter und springt dann → F3 meldet `jitter`/`late`. Benni (gleichmäßige Leitung)
|
||||||
|
merkt nichts. **Fix (P4-x):** echte Entity-Interpolation mit ~100 ms Puffer; Render bei `now - INTERP_DELAY`
|
||||||
|
zwischen den zwei umgebenden Snapshots. **Reproduzierbar:** Dev-Param `?netlag=<basis>,<jitter>` verzögert
|
||||||
|
eingehende Snapshots geseedet; Node-Test `tests/netfight.test.js` (reine Interp-Mathe) + Playwright-Test misst
|
||||||
|
die Positions-Sprünge mit/ohne `netlag`. Erkenntnis für Benni: das Springen war ein Client-Interp-Problem,
|
||||||
|
kein Server-/Leitungsproblem.
|
||||||
|
- [x] **P1-7 Disconnect/Reconnect:** Gnadenfrist, KI-Übernahme, Wiederverbinden. *AK:* Test trennt einen Client
|
||||||
mitten im Kampf; Kampf endet trotzdem mit Ergebnis; Reconnect innerhalb 10 s übernimmt wieder.
|
mitten im Kampf; Kampf endet trotzdem mit Ergebnis; Reconnect innerhalb 10 s übernimmt wieder.
|
||||||
- [ ] **P1-8 Alt-Code entfernen:** `server/rtdb.js`, `server/rules.js`, `/db`-Routen, `game/lobby.js` (alt),
|
- [x] **P1-8 Alt-Code entfernen:** `server/rtdb.js`, `server/rules.js`, `/db`-Routen, `game/lobby.js` (alt),
|
||||||
SSE-Code in `net.js`, `docs/firebase/`, `admin/cleanup.js`, Firebase-Teile in `admin/`, `kit-scores`-Nutzung
|
SSE-Code in `net.js`, `docs/firebase/`, `admin/cleanup.js`, Firebase-Teile in `admin/`, `kit-scores`-Nutzung
|
||||||
(`Kit.scores` in `game.js`). *AK:* `grep -ri firebase` findet nur noch Historie in diesem Dokument; alle Tests grün.
|
(`Kit.scores` in `game.js`). *AK:* `grep -ri firebase` findet nur noch Historie in diesem Dokument; alle Tests grün.
|
||||||
|
|
||||||
### Phase 2 – Konten, Spielstand, Wirtschaft (Online)
|
### Phase 2 – Konten, Spielstand, Wirtschaft (Online)
|
||||||
|
|
||||||
- [ ] **P2-1 DB-Schema + Migrationen** (`server/db/migrations/NNN-*.sql`, Tabelle `schema_version`, beim Start
|
- [x] **P2-1 DB-Schema + Migrationen** (`server/db/migrations/NNN-*.sql`, Tabelle `schema_version`, beim Start
|
||||||
automatisch). Tabellen: `users`, `refresh_tokens`, `wallets`, `inventory (uid, part_id, count)`,
|
automatisch). Tabellen: `users`, `refresh_tokens`, `wallets`, `inventory (uid, part_id, count)`,
|
||||||
`robots (uid, build_json, paint_json, name)`, `saves (uid, json, ts)` für reine Komfortdaten,
|
`robots (uid, build_json, paint_json, name)`, `saves (uid, json, ts)` für reine Komfortdaten,
|
||||||
`matches`, `ranks`. *AK:* Leere DB → Migrationen laufen; zweimal starten ändert nichts.
|
`matches`, `ranks`. *AK:* Leere DB → Migrationen laufen; zweimal starten ändert nichts.
|
||||||
- [ ] **P2-1b Init-/Reset-Skript** `server/scripts/reset-db.js` (`npm run db:reset`): löscht die DB (vorher Kopie nach
|
- [x] **P2-1b Init-/Reset-Skript** `server/scripts/reset-db.js` (`npm run db:reset`): löscht die DB (vorher Kopie nach
|
||||||
`data.sqlite.bak-<zeit>`), legt das Schema neu an und erzeugt die **Seed-Konten** (Admin-Recht, Startgeld,
|
`data.sqlite.bak-<zeit>`), legt das Schema neu an und erzeugt die **Seed-Konten** (Admin-Recht, Startgeld,
|
||||||
Starter-Roboter). **Dev-Phase: feste Testzugänge, bewusst ohne E-Mail und ohne `.env`** – direkt im Skript als
|
Starter-Roboter). **Dev-Phase: feste Testzugänge, bewusst ohne E-Mail und ohne `.env`** – direkt im Skript als
|
||||||
Konstante `DEV_SEED_USERS`:
|
Konstante `DEV_SEED_USERS`:
|
||||||
@@ -216,15 +249,15 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
|
|||||||
von `ADMIN_UID` (Admin-Recht als Spalte `role` in `users`). → Härtung später: siehe **Abschnitt 10, T-1/T-2**.
|
von `ADMIN_UID` (Admin-Recht als Spalte `role` in `users`). → Härtung später: siehe **Abschnitt 10, T-1/T-2**.
|
||||||
*AK:* Zweimal ausführen → identischer Zustand; `michi`/`Michi2000!` und `benni`/`Benni2000!` können sich
|
*AK:* Zweimal ausführen → identischer Zustand; `michi`/`Michi2000!` und `benni`/`Benni2000!` können sich
|
||||||
einloggen und sehen das Dev-Menü.
|
einloggen und sehen das Dev-Menü.
|
||||||
- [ ] **P2-2 REST-Endpunkte** mit Schema-Prüfung (z. B. `zod` oder handgeschriebene Validierer aus `protocol.js`):
|
- [x] **P2-2 REST-Endpunkte** mit Schema-Prüfung (z. B. `zod` oder handgeschriebene Validierer aus `protocol.js`):
|
||||||
`GET /api/profile`, `PUT /api/robot`, `POST /api/shop/buy`, `POST /api/shop/sell`, `GET /api/wallet`,
|
`GET /api/profile`, `PUT /api/robot`, `POST /api/shop/buy`, `POST /api/shop/sell`, `GET /api/wallet`,
|
||||||
`GET /api/ranks`. Preise kommen aus `RC.PARTS` (Server), nie vom Client. *AK:* Tests: zu wenig Geld → 409,
|
`GET /api/ranks`. Preise kommen aus `RC.PARTS` (Server), nie vom Client. *AK:* Tests: zu wenig Geld → 409,
|
||||||
fremdes Teil einbauen → 400, Verkauf 50 %.
|
fremdes Teil einbauen → 400, Verkauf 50 %.
|
||||||
- [ ] **P2-3 Belohnungen** nach `match.end` serverseitig (Regeln aus `endOnlineFight` nach `server/economy.js`
|
- [x] **P2-3 Belohnungen** nach `match.end` serverseitig (Regeln aus `endOnlineFight` nach `server/economy.js`
|
||||||
verschieben, Client zeigt nur an). Rangliste = Ruhm aus der DB. *AK:* Test: Sieg bucht genau einmal, auch bei Reconnect.
|
verschieben, Client zeigt nur an). Rangliste = Ruhm aus der DB. *AK:* Test: Sieg bucht genau einmal, auch bei Reconnect.
|
||||||
- [ ] **P2-4 Client umstellen:** Shop/Werkstatt im Online-Modus ruft die Endpunkte auf; lokaler Stand ist nur Cache.
|
- [x] **P2-4 Client umstellen:** Shop/Werkstatt im Online-Modus ruft die Endpunkte auf; lokaler Stand ist nur Cache.
|
||||||
`cloudsave.js` entfällt im Online-Modus. Kampagne bleibt unverändert lokal.
|
`cloudsave.js` entfällt im Online-Modus. Kampagne bleibt unverändert lokal.
|
||||||
- [ ] **P2-5 Auth härten:** Rate-Limit auf Login/Register/Guest (z. B. 10/min pro IP), Gast-Konten ohne Aktivität
|
- [x] **P2-5 Auth härten:** Rate-Limit auf Login/Register/Guest (z. B. 10/min pro IP), Gast-Konten ohne Aktivität
|
||||||
nach 30 Tagen löschen (täglicher Job), Passwort-Mindestlänge 8.
|
nach 30 Tagen löschen (täglicher Job), Passwort-Mindestlänge 8.
|
||||||
- [ ] **P2-6 Online-Turnier** (`netourney.js`) auf Server-Logik umbauen: Turnierbaum und Ergebnisse führt der Server;
|
- [ ] **P2-6 Online-Turnier** (`netourney.js`) auf Server-Logik umbauen: Turnierbaum und Ergebnisse führt der Server;
|
||||||
Clients bekommen nur Ansichten. *(Kann nach dem ersten Release kommen.)*
|
Clients bekommen nur Ansichten. *(Kann nach dem ersten Release kommen.)*
|
||||||
@@ -235,13 +268,13 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
|
|||||||
und `deploy` (SSH-Key, darf nur Deploy-Skript + `systemctl restart robotclash*` per sudoers), Passwort-Login in
|
und `deploy` (SSH-Key, darf nur Deploy-Skript + `systemctl restart robotclash*` per sudoers), Passwort-Login in
|
||||||
SSH aus, `unattended-upgrades`, ufw (22/80/443), fail2ban. Root-Login erst abschalten, wenn `deploy` sicher geht.
|
SSH aus, `unattended-upgrades`, ufw (22/80/443), fail2ban. Root-Login erst abschalten, wenn `deploy` sicher geht.
|
||||||
*AK:* `ssh deploy@roboclash.michael-media.de` per Key geht, Dienst läuft nicht mehr als root.
|
*AK:* `ssh deploy@roboclash.michael-media.de` per Key geht, Dienst läuft nicht mehr als root.
|
||||||
- [ ] **P3-1b Node auf 24 LTS heben.** Auf dem Server läuft Node **20.20** – seit 30.04.2026 ohne Support (EOL).
|
- [x] **P3-1b Node auf 24 LTS heben.** Auf dem Server läuft Node **20.20** – seit 30.04.2026 ohne Support (EOL).
|
||||||
`setup.sh` auf NodeSource `setup_24.x` umstellen, auf der VM aktualisieren, `npm rebuild` (better-sqlite3 ist
|
`setup.sh` auf NodeSource `setup_24.x` umstellen, auf der VM aktualisieren, `npm rebuild` (better-sqlite3 ist
|
||||||
nativ). Lokal wird schon mit Node 24 entwickelt. *AK:* `node -v` auf der VM = v24.x, `/healthz` ok.
|
nativ). Lokal wird schon mit Node 24 entwickelt. *AK:* `node -v` auf der VM = v24.x, `/healthz` ok.
|
||||||
- [ ] **P3-2 Dienst + Caddy für die Umgebung `dev`** (Abschnitt 5): systemd-Unit mit `User=robotclash`,
|
- [x] **P3-2 Dienst + Caddy für die Umgebung `dev`** (Abschnitt 5): systemd-Unit mit `User=robotclash`,
|
||||||
`NoNewPrivileges`, `ProtectSystem=strict`, `ReadWritePaths` nur Datenordner. Caddyfile: **kein `encode` auf
|
`NoNewPrivileges`, `ProtectSystem=strict`, `ReadWritePaths` nur Datenordner. Caddyfile: **kein `encode` auf
|
||||||
`/ws`**. Produktion später = zweite Unit + zweiter Caddy-Block. *AK:* `/healthz` per HTTPS erreichbar.
|
`/ws`**. Produktion später = zweite Unit + zweiter Caddy-Block. *AK:* `/healthz` per HTTPS erreichbar.
|
||||||
- [ ] **P3-3 Release-basiertes Deploy-Skript** `server/deploy/deploy.sh <dev|prod> <git-ref>`:
|
- [x] **P3-3 Release-basiertes Deploy-Skript** `server/deploy/deploy.sh <dev|prod> <git-ref>`:
|
||||||
baut ein Release-Verzeichnis `/opt/robotclash[-<env>]/releases/<zeit>-<commit>`, `npm ci --omit=dev`,
|
baut ein Release-Verzeichnis `/opt/robotclash[-<env>]/releases/<zeit>-<commit>`, `npm ci --omit=dev`,
|
||||||
DB-Backup **vor** Migration, Symlink `current` umschalten, Dienst neu starten, `/healthz` prüfen,
|
DB-Backup **vor** Migration, Symlink `current` umschalten, Dienst neu starten, `/healthz` prüfen,
|
||||||
bei Fehler automatisch auf das vorige Release zurück. Die letzten 5 Releases behalten.
|
bei Fehler automatisch auf das vorige Release zurück. Die letzten 5 Releases behalten.
|
||||||
@@ -263,14 +296,14 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
|
|||||||
|
|
||||||
### Phase 4 – Absicherung und Feinschliff
|
### Phase 4 – Absicherung und Feinschliff
|
||||||
|
|
||||||
- [ ] **P4-1 Bot-Client** `tools/bot.js`: verbindet sich per WS, nimmt Challenges an, spielt mit `RC.AI`.
|
- [x] **P4-1 Bot-Client** `tools/bot.js`: verbindet sich per WS, nimmt Challenges an, spielt mit `RC.AI`.
|
||||||
Nutzbar für Smoke-Tests und als Gegner auf dem Dev-Server. *AK:* `node tools/bot.js --url … --count 20` spielt 10 Matches parallel.
|
Nutzbar für Smoke-Tests und als Gegner auf dem Dev-Server. *AK:* `node tools/bot.js --url … --count 20` spielt 10 Matches parallel.
|
||||||
- [ ] **P4-2 Browser-E2E** mit Playwright: zwei Browser-Kontexte, Gast-Login, Lobby, Challenge, Kampf mit `&auto`,
|
- [x] **P4-2 Browser-E2E** mit Playwright: zwei Browser-Kontexte, Gast-Login, Lobby, Challenge, Kampf mit `&auto`,
|
||||||
beide sehen spiegelbildliches Ergebnis. Läuft in CI gegen einen lokal gestarteten Server.
|
beide sehen spiegelbildliches Ergebnis. Läuft in CI gegen einen lokal gestarteten Server.
|
||||||
- [ ] **P4-3 Lasttest:** 100 Bots / 50 Matches auf dem Dev-Server; Tick-Dauer und CPU dokumentieren.
|
- [ ] **P4-3 Lasttest:** 100 Bots / 50 Matches auf dem Dev-Server; Tick-Dauer und CPU dokumentieren.
|
||||||
- [ ] **P4-4 Latenz-Komfort:** Vorhersage für den eigenen Roboter (Eingabe sofort lokal anwenden, mit Server-Snapshot
|
- [ ] **P4-4 Latenz-Komfort:** Vorhersage für den eigenen Roboter (Eingabe sofort lokal anwenden, mit Server-Snapshot
|
||||||
abgleichen), Ping-Anzeige im HUD. Nur wenn Spieltests Verzögerung bemängeln.
|
abgleichen), Ping-Anzeige im HUD. Nur wenn Spieltests Verzögerung bemängeln.
|
||||||
- [ ] **P4-5 `game.js` aufteilen** (> 1500 Zeilen, Regel aus CLAUDE.md): `online-ui.js` (Lobby, Login),
|
- [x] **P4-5 `game.js` aufteilen** (> 1500 Zeilen, Regel aus CLAUDE.md): `online-ui.js` (Lobby, Login),
|
||||||
`fight.js` (Kampfablauf), `results.js`. Ohne Verhaltensänderung, abgesichert durch `&uicheck` + E2E.
|
`fight.js` (Kampfablauf), `results.js`. Ohne Verhaltensänderung, abgesichert durch `&uicheck` + E2E.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,94 +0,0 @@
|
|||||||
# Firebase: Rangliste + Online-Lobby (ohne SDK, reines REST)
|
|
||||||
|
|
||||||
Das Spiel spricht Firebase komplett über REST an (`game/net.js`, `game/kit/kit-scores.js`) – kein SDK,
|
|
||||||
läuft per `file://` und als eine HTML-Datei.
|
|
||||||
|
|
||||||
- **Rangliste** braucht nur die DB-URL (`DB_URL` in `game/game.js`), **kein Login**.
|
|
||||||
- **Online-Lobby + Live-PvP** braucht zusätzlich den **Web-API-Key** (`NET_CFG.apiKey`) und aktivierte
|
|
||||||
Anmeldung. Ohne Key bleibt der „Online spielen"-Knopf aus; der Rest funktioniert.
|
|
||||||
|
|
||||||
## Einrichten
|
|
||||||
|
|
||||||
1. [Firebase-Konsole](https://console.firebase.google.com/) → Projekt `robot-clash-aa37b` (schon angelegt).
|
|
||||||
2. **Realtime Database** (Standort europe-west1 o. ä.): Tab **Regeln** → Inhalt von `database.rules.json`
|
|
||||||
einfügen → **Veröffentlichen**. Die DB-URL ist schon in `game/game.js` eingetragen
|
|
||||||
(`https://robot-clash-aa37b-default-rtdb.firebaseio.com`).
|
|
||||||
3. **Für die Lobby:** **Authentication → Anmeldemethode** → **E-Mail/Passwort** aktivieren
|
|
||||||
(optional **Anonym** für Gast-Login).
|
|
||||||
4. **Web-API-Key** holen: ⚙ **Projekteinstellungen → Allgemein → Web-API-Schlüssel** (beginnt mit `AIza…`).
|
|
||||||
In `game/game.js` bei `NET_CFG = { apiKey: '…' }` eintragen → `.\build.ps1 -Web -Obfuscate` neu bauen.
|
|
||||||
(Der Web-API-Key ist **nicht geheim**; er darf im Client stehen. Geschützt wird über die DB-Regeln.)
|
|
||||||
|
|
||||||
## Admin-Zugang (Events, Freischaltungen, Nachricht an alle)
|
|
||||||
|
|
||||||
**Das Passwort wird nirgends im Projekt hinterlegt.** Es gehört zu einem ganz normalen Firebase-Konto;
|
|
||||||
Firebase speichert es (gehasht) auf dem Server. Im Projekt steht nur die **Kennung (UID)** dieses Kontos –
|
|
||||||
und zwar in den Datenbankregeln. Ein Passwort, das der Client prüft, wäre wertlos: Jeder könnte es aus der
|
|
||||||
heruntergeladenen Datei lesen.
|
|
||||||
|
|
||||||
**Einmalig einrichten:**
|
|
||||||
|
|
||||||
1. [Firebase-Konsole](https://console.firebase.google.com/) → Projekt `robot-clash-aa37b`
|
|
||||||
→ **Authentication → Users → Nutzer hinzufügen**.
|
|
||||||
Dort E-Mail + Passwort eintragen – **das sind dein Benutzername und dein Master-Passwort.**
|
|
||||||
(Am besten ein eigenes Konto, nicht dein Spieler-Konto.)
|
|
||||||
2. In derselben Liste steht jetzt die Spalte **User UID** (z. B. `k3Jd9…`). Diese Kennung kopieren.
|
|
||||||
3. **Realtime Database → Regeln**: im Block `"live"` den Platzhalter `PUT-ADMIN-UID-HERE` durch die UID
|
|
||||||
ersetzen → **Veröffentlichen**.
|
|
||||||
Die Datei `database.rules.json` hier im Ordner ist nur die Vorlage – Firebase liest sie **nicht**
|
|
||||||
automatisch, der Inhalt muss in die Konsole eingefügt werden.
|
|
||||||
|
|
||||||
Ab dann gilt: Nur dieses eine Konto darf `/live` beschreiben. Lesen darf jeder (auch ohne Login), damit
|
|
||||||
Gäste Events und Nachrichten sehen.
|
|
||||||
|
|
||||||
**Oberfläche aufrufen:** Datei `admin/index.html` im Projektordner **per Doppelklick** öffnen (läuft lokal,
|
|
||||||
kein Webserver nötig), mit E-Mail + Master-Passwort anmelden, Werte setzen, speichern. Die Seite zeigt nach
|
|
||||||
dem Login auch die eigene UID an – praktisch, falls du Schritt 2 nachholen willst.
|
|
||||||
|
|
||||||
**Diese Datei nie hochladen.** Sie gehört nicht ins `game/`-Verzeichnis und landet deshalb auch nicht in
|
|
||||||
`release
|
|
||||||
obotclash.html`. Selbst wenn sie jemand hätte: Ohne dein Konto schreibt sie nichts – die Regel
|
|
||||||
oben lässt es nicht zu.
|
|
||||||
|
|
||||||
## Was die Regeln erlauben
|
|
||||||
|
|
||||||
- `highscores`: lesen offen, nur **neue** Einträge schreiben (Format/Bereich geprüft).
|
|
||||||
- `users/$uid`, `lobby/$uid`, `matches/$id`, `challenges`: nur eingeloggte Nutzer; jeder schreibt nur seinen
|
|
||||||
eigenen Lobby-Eintrag / seine Eingaben; den Kampf-Zustand schreibt nur der **Host** (kleinere uid).
|
|
||||||
- `live`: lesen offen (auch ohne Login), schreiben **nur** das Admin-Konto.
|
|
||||||
- `ranks/$uid`: lesen offen, schreiben nur das Konto selbst – eine Zeile je Spieler, dadurch keine Dubletten.
|
|
||||||
|
|
||||||
## Grenzen (ehrlich)
|
|
||||||
|
|
||||||
- Client-Code ist im Browser immer lesbar/ladbar. `-Obfuscate` erschwert das nur, verhindert es nicht.
|
|
||||||
Echter Schutz liegt serverseitig (Auth + Regeln).
|
|
||||||
- Punkte/Daten lassen sich per Hand-Request fälschen; die Regeln prüfen nur Format/Besitzer, keine Spiel-Logik.
|
|
||||||
Fälschungssicher nur mit Cloud Functions (nicht eingebaut).
|
|
||||||
- Live-PvP: der Host schreibt ~15 Snapshots/s (~1800 Writes pro 2-Minuten-Kampf). Für wenige gleichzeitige
|
|
||||||
Kämpfe im Spark-Gratis-Tarif ok; bei vielen Spielern RTDB-Nutzung im Blick behalten.
|
|
||||||
- Stockt der Gegner > 1,5 s, übernimmt die KI seinen Roboter, der Kampf läuft zu Ende.
|
|
||||||
|
|
||||||
## Spielstand in der Cloud (`saves/$uid`)
|
|
||||||
|
|
||||||
- Registrierte **E-Mail-Konten** spiegeln ihren Spielstand nach `saves/<uid>` (`game/cloudsave.js`).
|
|
||||||
Gäste + lokale Profile bleiben **nur lokal**. localStorage bleibt der schnelle Cache; die Cloud ist die
|
|
||||||
Kopie fürs Gerätewechseln.
|
|
||||||
- Regel: lesen/schreiben nur das Konto selbst; `money`/`fame` auf `0…1e9` geklemmt, `ts` muss eine Zahl sein.
|
|
||||||
- Konflikt: **neuerer `ts` gewinnt** (beim Login wird die Cloud geholt, ist sie neuer → übernommen, sonst der
|
|
||||||
lokale Stand hochgeladen). Firebase aus/offline → Spiel läuft wie bisher nur lokal weiter.
|
|
||||||
- **Ehrlich:** auch hier kann der Besitzer seinen eigenen Knoten schreiben – die Regeln kappen nur Wertebereiche.
|
|
||||||
Fälschungssicher wäre nur Server-Logik (Cloud Functions, nicht eingebaut). Fairness zählt über `ranks/`.
|
|
||||||
|
|
||||||
## Aufräumen (`admin/cleanup.js`)
|
|
||||||
|
|
||||||
Löscht Test-/Gast-Konten und verwaiste DB-Einträge. Läuft lokal mit dem **Service-Account-Key** (geheim,
|
|
||||||
`.gitignore` deckt `serviceAccount*.json` ab – **nie hochladen/committen**):
|
|
||||||
|
|
||||||
```
|
|
||||||
npm install firebase-admin
|
|
||||||
node admin/cleanup.js --key serviceAccount.json # Vorschau, löscht nichts
|
|
||||||
node admin/cleanup.js --key serviceAccount.json --apply # löscht wirklich
|
|
||||||
```
|
|
||||||
|
|
||||||
Zeigt/entfernt: anonyme Gast-Konten (ohne E-Mail), veraltete `lobby/`-Präsenz (> 10 min) und verwaiste
|
|
||||||
`saves/`, `ranks/`, `users/` (uid nicht mehr in Auth). Service-Account-Key: Firebase-Konsole →
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
{
|
|
||||||
"rules": {
|
|
||||||
".read": false,
|
|
||||||
".write": false,
|
|
||||||
"highscores": {
|
|
||||||
".read": true,
|
|
||||||
".indexOn": [
|
|
||||||
"score"
|
|
||||||
],
|
|
||||||
"$entry": {
|
|
||||||
".write": "!data.exists()",
|
|
||||||
".validate": "newData.hasChildren(['name', 'score', 'level', 'time'])",
|
|
||||||
"name": {
|
|
||||||
".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 20"
|
|
||||||
},
|
|
||||||
"score": {
|
|
||||||
".validate": "newData.isNumber() && newData.val() > 0 && newData.val() <= 10000000"
|
|
||||||
},
|
|
||||||
"level": {
|
|
||||||
".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 999"
|
|
||||||
},
|
|
||||||
"time": {
|
|
||||||
".validate": "newData.val() == now"
|
|
||||||
},
|
|
||||||
"$other": {
|
|
||||||
".validate": false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"users": {
|
|
||||||
"$uid": {
|
|
||||||
".read": "auth != null && auth.uid == $uid",
|
|
||||||
".write": "auth != null && auth.uid == $uid"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"saves": {
|
|
||||||
"$uid": {
|
|
||||||
".read": "auth != null && auth.uid == $uid",
|
|
||||||
".write": "auth != null && auth.uid == $uid",
|
|
||||||
"money": { ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 1000000000" },
|
|
||||||
"fame": { ".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 1000000000" },
|
|
||||||
"ts": { ".validate": "newData.isNumber()" }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"lobby": {
|
|
||||||
".read": "auth != null",
|
|
||||||
"$uid": {
|
|
||||||
".write": "auth != null && auth.uid == $uid",
|
|
||||||
".validate": "newData.hasChildren(['name', 'ts'])",
|
|
||||||
"name": {
|
|
||||||
".validate": "newData.isString() && newData.val().length <= 20"
|
|
||||||
},
|
|
||||||
"flag": {
|
|
||||||
".validate": "newData.isString() && newData.val().length <= 4"
|
|
||||||
},
|
|
||||||
"ts": {
|
|
||||||
".validate": "newData.isNumber()"
|
|
||||||
},
|
|
||||||
"$other": {
|
|
||||||
".validate": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"challenges": {
|
|
||||||
"$to": {
|
|
||||||
".read": "auth != null && auth.uid == $to",
|
|
||||||
"$from": {
|
|
||||||
".write": "auth != null && (auth.uid == $from || auth.uid == $to)",
|
|
||||||
".validate": "!newData.exists() || (newData.child('from').val() == $from)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"matches": {
|
|
||||||
"$id": {
|
|
||||||
".read": "auth != null && $id.contains(auth.uid)",
|
|
||||||
".write": "auth != null && $id.contains(auth.uid)",
|
|
||||||
"state": {
|
|
||||||
".validate": "$id.beginsWith(auth.uid + '_')"
|
|
||||||
},
|
|
||||||
"in": {
|
|
||||||
".validate": "$id.endsWith('_' + auth.uid)"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"live": {
|
|
||||||
".read": true,
|
|
||||||
".write": "auth != null && auth.uid === 'sQwhv1p7KvNHuRLHuyf2fbQI86F2'"
|
|
||||||
},
|
|
||||||
"ranks": {
|
|
||||||
".read": true,
|
|
||||||
".indexOn": [
|
|
||||||
"fame"
|
|
||||||
],
|
|
||||||
"$uid": {
|
|
||||||
".write": "auth != null && auth.uid == $uid",
|
|
||||||
".validate": "newData.hasChildren(['name','fame','ts'])",
|
|
||||||
"name": {
|
|
||||||
".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 20"
|
|
||||||
},
|
|
||||||
"fame": {
|
|
||||||
".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 10000000"
|
|
||||||
},
|
|
||||||
"cls": {
|
|
||||||
".validate": "newData.isString() && newData.val().length <= 10"
|
|
||||||
},
|
|
||||||
"season": {
|
|
||||||
".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 999"
|
|
||||||
},
|
|
||||||
"ts": {
|
|
||||||
".validate": "newData.val() == now"
|
|
||||||
},
|
|
||||||
"$other": {
|
|
||||||
".validate": false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"admin": {
|
|
||||||
".read": "auth != null && auth.uid === 'sQwhv1p7KvNHuRLHuyf2fbQI86F2'",
|
|
||||||
".write": "auth != null && auth.uid === 'sQwhv1p7KvNHuRLHuyf2fbQI86F2'"
|
|
||||||
},
|
|
||||||
"tourney": {
|
|
||||||
".read": "auth != null",
|
|
||||||
".write": "auth != null",
|
|
||||||
"reg": {
|
|
||||||
"$uid": {
|
|
||||||
".write": "auth != null && auth.uid == $uid"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -9,7 +9,7 @@ const gameGlobals = { RC: 'writable', Kit: 'writable', THREE: 'readonly', KIT_AS
|
|||||||
module.exports = [
|
module.exports = [
|
||||||
{
|
{
|
||||||
ignores: ['node_modules/**', 'server/node_modules/**', 'release/**', 'game/vendor/**', 'game/kit/**',
|
ignores: ['node_modules/**', 'server/node_modules/**', 'release/**', 'game/vendor/**', 'game/kit/**',
|
||||||
'launcher/**', 'sprite-generator/**', 'tools/shots/**', 'admin/**'],
|
'launcher/**', 'sprite-generator/**', 'tools/shots/**', 'admin/**', 'test-results/**', 'playwright-report/**'],
|
||||||
},
|
},
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
{
|
{
|
||||||
@@ -19,11 +19,11 @@ module.exports = [
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
files: ['game/**/*.js', 'tools/**/*.js'],
|
files: ['game/**/*.js'],
|
||||||
languageOptions: { sourceType: 'script', globals: { ...globals.browser, ...gameGlobals } },
|
languageOptions: { sourceType: 'script', globals: { ...globals.browser, ...gameGlobals } },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
files: ['server/**/*.js', 'tests/**/*.js', 'eslint.config.js'],
|
files: ['server/**/*.js', 'tests/**/*.js', 'tools/**/*.js', 'eslint.config.js', 'playwright.config.js'],
|
||||||
languageOptions: { sourceType: 'commonjs', globals: { ...globals.node } },
|
languageOptions: { sourceType: 'commonjs', globals: { ...globals.node } },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
/* Robot Clash - cloud save for registered accounts (no DOM). Needs net.js.
|
/* Robot Clash - cloud copy of the offline CAMPAIGN for registered accounts (no DOM). Needs net.js.
|
||||||
|
The online game does not use this: its save lives on the server (server/economy.js).
|
||||||
|
|
||||||
The whole save still lives in localStorage (fast cache); for a real e-mail account it is also mirrored to
|
The campaign still lives in localStorage (fast cache); with a real account it is mirrored to
|
||||||
Firebase RTDB at saves/<uid> so it survives a device change and is harder to fake than localStorage.
|
/api/campaign so it survives a device change. Client-trusted - it is the offline game.
|
||||||
Honest limit: the owner can still write their own node - rules only cap ranges. No hard copy protection.
|
|
||||||
|
|
||||||
const cloud = RC.CloudSave(net);
|
const cloud = RC.CloudSave(net);
|
||||||
cloud.pull(uid) -> the cloud save object, or null (best effort, never throws)
|
cloud.pull() -> the cloud save object, or null (best effort, never throws)
|
||||||
cloud.push(uid, save) -> debounced write (~2.5 s after the last change)
|
cloud.push(save) -> debounced write (~2.5 s after the last change)
|
||||||
cloud.flush(uid, save) -> write now (fight result, leaving garage, logout, unload)
|
cloud.flush(save) -> write now (fight result, leaving garage, logout, unload)
|
||||||
RC.CloudSave.newer(cloud, local) -> true if the cloud copy should win (by ts) */
|
RC.CloudSave.newer(cloud, local) -> true if the cloud copy should win (by ts) */
|
||||||
(function (root) {
|
(function (root) {
|
||||||
'use strict';
|
'use strict';
|
||||||
@@ -21,29 +21,29 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
RC.CloudSave = function (net) {
|
RC.CloudSave = function (net) {
|
||||||
let timer = null, sending = false, pending = null, pendingUid = null;
|
let timer = null, sending = false, pending = null;
|
||||||
const clone = s => { try { return JSON.parse(JSON.stringify(s)); } catch (e) { return null; } };
|
const clone = s => { try { return JSON.parse(JSON.stringify(s)); } catch (e) { return null; } };
|
||||||
|
|
||||||
async function write(uid, save) {
|
async function write(save) {
|
||||||
sending = true;
|
sending = true;
|
||||||
try { await net.db.put('saves/' + uid, save); } catch (e) { /* best effort */ }
|
try { await net.api('PUT', '/api/campaign', save); } catch (e) { /* best effort */ }
|
||||||
sending = false;
|
sending = false;
|
||||||
if (pending) { const s = pending, u = pendingUid; pending = null; pendingUid = null; write(u, s); }
|
if (pending) { const s = pending; pending = null; write(s); }
|
||||||
}
|
}
|
||||||
function doPush(uid, save) {
|
function doPush(save) {
|
||||||
if (!net || !net.enabled || !uid || !save) return;
|
if (!net || !net.enabled || !save) return;
|
||||||
if (sending) { pending = save; pendingUid = uid; return; } // one request at a time; keep only the latest
|
if (sending) { pending = save; return; } // one request at a time; keep only the latest
|
||||||
write(uid, save);
|
write(save);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
newer,
|
newer,
|
||||||
async pull(uid) {
|
async pull() {
|
||||||
if (!net || !net.enabled || !uid) return null;
|
if (!net || !net.enabled) return null;
|
||||||
try { return await net.db.get('saves/' + uid); } catch (e) { return null; }
|
try { return await net.api('GET', '/api/campaign'); } catch (e) { return null; }
|
||||||
},
|
},
|
||||||
push(uid, save) { clearTimeout(timer); const snap = clone(save); timer = setTimeout(() => doPush(uid, snap), 2500); },
|
push(save) { clearTimeout(timer); const snap = clone(save); timer = setTimeout(() => doPush(snap), 2500); },
|
||||||
flush(uid, save) { clearTimeout(timer); doPush(uid, clone(save)); },
|
flush(save) { clearTimeout(timer); doPush(clone(save)); },
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
RC.CloudSave.newer = newer;
|
RC.CloudSave.newer = newer;
|
||||||
|
|||||||
207
game/eco.js
Normal file
207
game/eco.js
Normal file
@@ -0,0 +1,207 @@
|
|||||||
|
/* Robot Clash - workshop economy rules, shared by client and server. No DOM.
|
||||||
|
The client applies an action at once (snappy UI); in online play the server applies the SAME action
|
||||||
|
to its own copy of the save and is the authority (its result replaces the client's economy fields).
|
||||||
|
|
||||||
|
RC.Eco.apply(save, action) -> { ok, error } mutates save only when ok
|
||||||
|
action.type: buy | sell | equip | weaponAdd | weaponRemove | weaponPlace | body |
|
||||||
|
robotNew | robotDelete | robotSwitch | rename | devCoins (server: admins only)
|
||||||
|
RC.Eco.sellValue(partId) -> credits back when selling (starter kit = 0, else 50 %)
|
||||||
|
RC.Eco.pvpReward(o) -> { money, fame, lines:[[key, amount]] } for a live PvP fight
|
||||||
|
RC.Eco.applyReward(save, r, o)
|
||||||
|
RC.Eco.newOnlineSave() -> the economy part of a fresh online save
|
||||||
|
RC.Eco.ECONOMY / COSMETIC which save fields belong to whom (server keeps economy, merges cosmetics)
|
||||||
|
|
||||||
|
save shape (same as game.js): { money, fame, owned:[partId], robots:[{ name, build, paint }], active,
|
||||||
|
build/paint/robotName mirror robots[active] (same objects) }. */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
|
||||||
|
const SELL = 0.5;
|
||||||
|
const MAX_ROBOTS = 6;
|
||||||
|
const BODY = { hx: [0.7, 1.6], wx: [0.8, 1.4], lx: [0.8, 1.3] };
|
||||||
|
const MAX_DECAL = 400 * 1024; // chars of the PNG data URL
|
||||||
|
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
||||||
|
const num = v => typeof v === 'number' && Number.isFinite(v);
|
||||||
|
const err = e => ({ ok: false, error: e });
|
||||||
|
const OK = { ok: true };
|
||||||
|
|
||||||
|
const starterIds = () => Object.values(RC.STARTER).filter(Boolean);
|
||||||
|
// the free starter kit sells for nothing - otherwise "new robot -> sell its starter parts" prints money
|
||||||
|
const sellValue = id => {
|
||||||
|
const p = RC.PARTS[id]; if (!p) return 0;
|
||||||
|
return starterIds().includes(id) ? 0 : Math.round(p.cost * SELL);
|
||||||
|
};
|
||||||
|
|
||||||
|
const starterBuild = () => {
|
||||||
|
const b = Object.assign({}, RC.STARTER);
|
||||||
|
b.weapons = RC.weaponsOf(b).map(w => ({ id: w.id, side: w.side || 'front', up: w.up || 0 }));
|
||||||
|
delete b.weapon; delete b.mount;
|
||||||
|
return b;
|
||||||
|
};
|
||||||
|
const newRobot = name => ({ name: name || 'Robot', build: starterBuild(), paint: { body: 0xff7a1a, accent: 0x15171b, decal: null, drawn: false } });
|
||||||
|
|
||||||
|
function newOnlineSave() {
|
||||||
|
const r = newRobot('Clank');
|
||||||
|
return { money: 800, fame: 0, best: 0, games: 0, wins: 0, losses: 0, owned: starterIds(), robots: [r], active: 0,
|
||||||
|
build: r.build, paint: r.paint, robotName: r.name };
|
||||||
|
}
|
||||||
|
|
||||||
|
// keep the live mirror fields pointing at the active robot
|
||||||
|
function mirror(save) {
|
||||||
|
const a = save.robots[save.active];
|
||||||
|
save.build = a.build; save.paint = a.paint; save.robotName = a.name;
|
||||||
|
}
|
||||||
|
const cur = save => save.robots[save.active].build;
|
||||||
|
const usedAnywhere = (save, id) => save.robots.some(r => RC.SLOTS.some(sl => sl !== 'weapon' && r.build[sl] === id));
|
||||||
|
const cleanName = n => Array.from(String(n || '')).filter(c => c.charCodeAt(0) >= 32 && c !== '<' && c !== '>').join('').trim().slice(0, 18);
|
||||||
|
|
||||||
|
const ACTIONS = {
|
||||||
|
buy(save, a) {
|
||||||
|
const p = RC.PARTS[a.part];
|
||||||
|
if (!p || p.slot === 'weapon') return err('BAD_PART');
|
||||||
|
if (save.owned.includes(a.part)) return err('OWNED');
|
||||||
|
if (save.money < p.cost) return err('NO_MONEY');
|
||||||
|
save.money -= p.cost; save.owned.push(a.part); cur(save)[p.slot] = a.part;
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
sell(save, a) {
|
||||||
|
const p = RC.PARTS[a.part];
|
||||||
|
if (!p || p.slot === 'weapon' || !save.owned.includes(a.part)) return err('NOT_OWNED');
|
||||||
|
if (usedAnywhere(save, a.part)) return err('IN_USE');
|
||||||
|
save.owned = save.owned.filter(x => x !== a.part); save.money += sellValue(a.part);
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
equip(save, a) {
|
||||||
|
if (!RC.SLOTS.includes(a.slot) || a.slot === 'weapon') return err('BAD_SLOT');
|
||||||
|
if (a.part == null) { if (RC.REQUIRED[a.slot]) return err('REQUIRED'); cur(save)[a.slot] = null; return OK; }
|
||||||
|
const p = RC.PARTS[a.part];
|
||||||
|
if (!p || p.slot !== a.slot) return err('BAD_PART');
|
||||||
|
if (!save.owned.includes(a.part)) return err('NOT_OWNED');
|
||||||
|
cur(save)[a.slot] = a.part;
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
weaponAdd(save, a) {
|
||||||
|
const p = RC.PARTS[a.part], b = cur(save);
|
||||||
|
if (!p || p.slot !== 'weapon') return err('BAD_PART');
|
||||||
|
b.weapons = b.weapons || [];
|
||||||
|
if (b.weapons.length >= RC.MAX_WEAPONS) return err('MAX_WEAPONS');
|
||||||
|
if (save.money < p.cost) return err('NO_MONEY');
|
||||||
|
save.money -= p.cost; b.weapons.push({ id: a.part, side: 'front', up: 0 });
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
weaponRemove(save, a) {
|
||||||
|
const b = cur(save), w = b.weapons && b.weapons[a.index];
|
||||||
|
if (!Number.isInteger(a.index) || !w) return err('BAD_INDEX');
|
||||||
|
b.weapons.splice(a.index, 1); save.money += sellValue(w.id);
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
weaponPlace(save, a) {
|
||||||
|
const w = cur(save).weapons && cur(save).weapons[a.index];
|
||||||
|
if (!Number.isInteger(a.index) || !w) return err('BAD_INDEX');
|
||||||
|
if (a.side !== undefined) { if (!RC.MOUNTS[a.side]) return err('BAD_SIDE'); w.side = a.side; }
|
||||||
|
if (a.up !== undefined) { if (!num(a.up)) return err('BAD_UP'); w.up = clamp(a.up, -0.3, 0.6); }
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
body(save, a) {
|
||||||
|
const keys = Object.keys(BODY).filter(k => a[k] !== undefined);
|
||||||
|
if (keys.some(k => !num(a[k]))) return err('BAD_BODY'); // validate everything before changing anything
|
||||||
|
const b = cur(save); b.body = Object.assign({ hx: 1, wx: 1, lx: 1 }, b.body);
|
||||||
|
for (const k of keys) b.body[k] = clamp(a[k], BODY[k][0], BODY[k][1]);
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
robotNew(save, a) {
|
||||||
|
if (save.robots.length >= MAX_ROBOTS) return err('HANGAR_FULL');
|
||||||
|
for (const id of starterIds()) if (!save.owned.includes(id)) save.owned.push(id); // the kit comes with the frame
|
||||||
|
save.robots.push(newRobot(cleanName(a.name) || 'Robot ' + (save.robots.length + 1)));
|
||||||
|
save.active = save.robots.length - 1; mirror(save);
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
robotDelete(save, a) {
|
||||||
|
if (save.robots.length <= 1) return err('LAST_ROBOT');
|
||||||
|
if (!Number.isInteger(a.index) || !save.robots[a.index]) return err('BAD_INDEX');
|
||||||
|
const i = a.index;
|
||||||
|
save.robots.splice(i, 1);
|
||||||
|
// robots after the deleted one move up; deleting the active one keeps the slot number (next robot)
|
||||||
|
save.active = clamp(save.active > i ? save.active - 1 : save.active, 0, save.robots.length - 1); mirror(save);
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
robotSwitch(save, a) {
|
||||||
|
if (!Number.isInteger(a.index) || !save.robots[a.index]) return err('BAD_INDEX');
|
||||||
|
save.active = a.index; mirror(save);
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
rename(save, a) {
|
||||||
|
const n = cleanName(a.name);
|
||||||
|
if (!n) return err('BAD_NAME');
|
||||||
|
save.robots[save.active].name = n; save.robotName = n;
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
devCoins(save, a) {
|
||||||
|
if (!num(a.money)) return err('BAD_MONEY');
|
||||||
|
save.money = clamp(Math.round(a.money), 0, 1e9);
|
||||||
|
return OK;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
function apply(save, action) {
|
||||||
|
if (!action || typeof action !== 'object' || !Object.prototype.hasOwnProperty.call(ACTIONS, action.type)) return err('BAD_ACTION');
|
||||||
|
if (!save || !Array.isArray(save.robots) || !save.robots[save.active]) return err('BAD_SAVE');
|
||||||
|
return ACTIONS[action.type](save, action);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- live PvP rewards: prize (win) / half (draw) / appearance fee (loss) + KO/pit bonus + damage bonus
|
||||||
|
// - repairs (can never take you below 0); fame on a win/draw. Lines carry i18n keys for the client.
|
||||||
|
const PVP = 600;
|
||||||
|
function pvpReward(o) {
|
||||||
|
const lines = [];
|
||||||
|
let money = 0, fame = 0;
|
||||||
|
const draw = o.winner === -1, won = o.won;
|
||||||
|
if (won) { money += PVP; lines.push(['r_prize', PVP]); fame = 150 + (o.reason === 'ko' ? 40 : o.reason === 'pit' ? 60 : 0); }
|
||||||
|
else if (draw) { money += PVP / 2; lines.push(['r_draw_prize', PVP / 2]); fame = 40; }
|
||||||
|
else { const ap = Math.round(PVP * 0.35); money += ap; lines.push(['r_appearance', ap]); }
|
||||||
|
if (won && o.reason !== 'time') { const b = Math.round(PVP * (o.reason === 'pit' ? 0.3 : 0.2)); money += b; lines.push(['r_bonus_' + o.reason, b]); }
|
||||||
|
const db = Math.round((o.dealt || 0) * 0.6);
|
||||||
|
if (db) { money += db; lines.push(['r_dmg_bonus', db]); }
|
||||||
|
const mul = num(o.prizeMul) && o.prizeMul > 0 ? o.prizeMul : 1;
|
||||||
|
if (mul !== 1 && money > 0) { const bonus = Math.round(money * mul) - money; if (bonus) { money += bonus; lines.push(['event_bonus', bonus]); } }
|
||||||
|
const repair = Math.round((1 - (o.hp || 0) / (o.maxHp || 1)) * (o.value || 0) * 0.06);
|
||||||
|
const paid = Math.max(0, Math.min(repair, (o.money || 0) + money));
|
||||||
|
if (paid) { money -= paid; lines.push(['r_repair', -paid]); }
|
||||||
|
return { money, fame, lines, won: !!won, draw };
|
||||||
|
}
|
||||||
|
function applyReward(save, r) {
|
||||||
|
save.money = clamp(Math.round(save.money + r.money), 0, 1e9);
|
||||||
|
save.fame = clamp(Math.round(save.fame + r.fame), 0, 1e9);
|
||||||
|
save.games = (save.games | 0) + 1;
|
||||||
|
if (r.won) save.wins = (save.wins | 0) + 1; else if (!r.draw) save.losses = (save.losses | 0) + 1;
|
||||||
|
if (save.fame > (save.best | 0)) save.best = save.fame;
|
||||||
|
}
|
||||||
|
|
||||||
|
// which fields of a save the server owns (economy) vs. takes from the client as they are (cosmetics)
|
||||||
|
const ECONOMY = ['money', 'fame', 'best', 'games', 'wins', 'losses', 'owned', 'robots', 'active', 'build', 'paint', 'robotName', 'ach'];
|
||||||
|
const COSMETIC = ['ts', 'flag', 'flagSet', 'tutorialSeen', 'paintSlots', 'paintSlot', 'unlockedPaints', 'unlockedSchemes', 'cls'];
|
||||||
|
const isColor = v => Number.isInteger(v) && v >= 0 && v <= 0xffffff;
|
||||||
|
// robot name / paint are cosmetic too, but live inside robots[] -> merged per robot, never adds or removes robots
|
||||||
|
function mergeCosmetics(save, incoming) {
|
||||||
|
if (!incoming || typeof incoming !== 'object') return;
|
||||||
|
for (const k of COSMETIC) if (incoming[k] !== undefined && JSON.stringify(incoming[k]).length < 64 * 1024) save[k] = incoming[k];
|
||||||
|
const rs = Array.isArray(incoming.robots) ? incoming.robots : [];
|
||||||
|
rs.forEach((r, i) => {
|
||||||
|
const mine = save.robots[i]; if (!mine || !r) return;
|
||||||
|
const n = cleanName(r.name); if (n) mine.name = n;
|
||||||
|
const p = r.paint;
|
||||||
|
if (p && typeof p === 'object') {
|
||||||
|
if (isColor(p.body)) mine.paint.body = p.body;
|
||||||
|
if (isColor(p.accent)) mine.paint.accent = p.accent;
|
||||||
|
if (p.decal === null || (typeof p.decal === 'string' && p.decal.startsWith('data:image/png;base64,') && p.decal.length <= MAX_DECAL)) mine.paint.decal = p.decal;
|
||||||
|
mine.paint.drawn = !!p.drawn;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
mirror(save);
|
||||||
|
}
|
||||||
|
|
||||||
|
RC.Eco = { apply, sellValue, pvpReward, applyReward, newOnlineSave, newRobot, starterBuild, mergeCosmetics, mirror,
|
||||||
|
ECONOMY, COSMETIC, MAX_ROBOTS, SELL, PVP };
|
||||||
|
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||||
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
908
game/game.js
908
game/game.js
File diff suppressed because it is too large
Load Diff
@@ -34,6 +34,18 @@
|
|||||||
/* fixed design size, scaled to the window by Kit.fit */
|
/* fixed design size, scaled to the window by Kit.fit */
|
||||||
#app { position: relative; width: 1280px; display: flex; flex-direction: column; }
|
#app { position: relative; width: 1280px; display: flex; flex-direction: column; }
|
||||||
/* HUD lives INSIDE the stage (full-screen game look), above the overlay so menus keep it reachable */
|
/* HUD lives INSIDE the stage (full-screen game look), above the overlay so menus keep it reachable */
|
||||||
|
/* network overlay (F3) */
|
||||||
|
#netov { position: absolute; left: 8px; bottom: 12px; z-index: 9; width: 316px; padding: 8px; border-radius: 6px;
|
||||||
|
background: rgba(10,12,16,.86); border: 1px solid var(--line); box-shadow: var(--hl); font: 12px/1.35 Consolas, monospace;
|
||||||
|
color: var(--text); pointer-events: none; }
|
||||||
|
#netov.hide { display: none; } /* #netov beats the generic .hide rule - hide it explicitly */
|
||||||
|
#netov .nvh { font-weight: bold; color: var(--accent); margin-bottom: 4px; }
|
||||||
|
#netov canvas { display: block; width: 300px; height: 84px; }
|
||||||
|
#netov .nvleg { display: flex; gap: 8px; flex-wrap: wrap; margin: 3px 0 5px; font-size: 11px; color: var(--dim, #8d95a8); }
|
||||||
|
#netov .nvleg i { display: inline-block; width: 10px; height: 3px; margin-right: 3px; vertical-align: middle; }
|
||||||
|
#netov .nvrows { display: grid; grid-template-columns: auto 1fr; gap: 1px 10px; }
|
||||||
|
#netov .nvrows b { text-align: right; font-weight: normal; }
|
||||||
|
#netov .nvv { margin-top: 5px; border-top: 1px solid var(--line); padding-top: 4px; }
|
||||||
#hud { position: absolute; left: 0; right: 0; top: 0; z-index: 7; display: flex; gap: 8px; align-items: center;
|
#hud { position: absolute; left: 0; right: 0; top: 0; z-index: 7; display: flex; gap: 8px; align-items: center;
|
||||||
height: 44px; padding: 0 12px; pointer-events: none;
|
height: 44px; padding: 0 12px; pointer-events: none;
|
||||||
background: linear-gradient(rgba(6,8,12,.9) 35%, rgba(6,8,12,0)); }
|
background: linear-gradient(rgba(6,8,12,.9) 35%, rgba(6,8,12,0)); }
|
||||||
@@ -817,6 +829,8 @@
|
|||||||
<script src="ltourney.js"></script>
|
<script src="ltourney.js"></script>
|
||||||
<script src="tourney.js"></script>
|
<script src="tourney.js"></script>
|
||||||
<script src="robot.js"></script>
|
<script src="robot.js"></script>
|
||||||
|
<script src="eco.js"></script>
|
||||||
|
<script src="protocol.js"></script>
|
||||||
<script src="combat.js"></script>
|
<script src="combat.js"></script>
|
||||||
<script src="ai.js"></script>
|
<script src="ai.js"></script>
|
||||||
<script src="profiles.js"></script>
|
<script src="profiles.js"></script>
|
||||||
@@ -828,10 +842,15 @@
|
|||||||
<script src="looks.js"></script>
|
<script src="looks.js"></script>
|
||||||
<script src="render3d.js"></script>
|
<script src="render3d.js"></script>
|
||||||
<script src="netfight.js"></script>
|
<script src="netfight.js"></script>
|
||||||
<script src="netourney.js"></script>
|
<script src="netstats.js"></script>
|
||||||
|
<script src="netoverlay.js"></script>
|
||||||
<script src="shop.js"></script>
|
<script src="shop.js"></script>
|
||||||
<script src="painter.js"></script>
|
<script src="painter.js"></script>
|
||||||
<script src="uicheck.js"></script>
|
<script src="uicheck.js"></script>
|
||||||
|
<script src="sfx.js"></script>
|
||||||
|
<script src="pages.js"></script>
|
||||||
|
<script src="online.js"></script>
|
||||||
|
<script src="workshop.js"></script>
|
||||||
<script src="game.js"></script>
|
<script src="game.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
42
game/lang.js
42
game/lang.js
@@ -209,7 +209,7 @@ window.LANG = {
|
|||||||
all_countries: 'All countries', filter_country: 'Show:',
|
all_countries: 'All countries', filter_country: 'Show:',
|
||||||
s_arena: 'Arena', arena_random: 'Random', arena_workshop: 'Workshop Pit', arena_foundry: 'The Foundry', arena_arena64: 'Mega Dome',
|
s_arena: 'Arena', arena_random: 'Random', arena_workshop: 'Workshop Pit', arena_foundry: 'The Foundry', arena_arena64: 'Mega Dome',
|
||||||
arena_scrapyard: 'Scrapyard', arena_crucible: 'The Crucible', arena_colosseum: 'Grand Colosseum',
|
arena_scrapyard: 'Scrapyard', arena_crucible: 'The Crucible', arena_colosseum: 'Grand Colosseum',
|
||||||
peer_back: 'Opponent is back', no_pause_online: 'No pause in live fights',
|
peer_back: 'Opponent is back', no_pause_online: 'No pause in live fights - the fight keeps running.',
|
||||||
r_draw_prize: 'Draw prize',
|
r_draw_prize: 'Draw prize',
|
||||||
online_guest: 'Join as guest (no e-mail)', online_short: '🌍 Online',
|
online_guest: 'Join as guest (no e-mail)', online_short: '🌍 Online',
|
||||||
room_title: '{room} lobby', room_count: '{n} in this room', other_rooms: 'Other countries', you: 'you',
|
room_title: '{room} lobby', room_count: '{n} in this room', other_rooms: 'Other countries', you: 'you',
|
||||||
@@ -236,12 +236,27 @@ window.LANG = {
|
|||||||
your_flag: 'Your flag:', challenge: 'Challenge', busy: 'in a fight', quick_match: 'Quick match',
|
your_flag: 'Your flag:', challenge: 'Challenge', busy: 'in a fight', quick_match: 'Quick match',
|
||||||
waiting_accept: 'Waiting for the other player...', challenge_in: 'Challenge!', wants_fight: 'wants to fight you!',
|
waiting_accept: 'Waiting for the other player...', challenge_in: 'Challenge!', wants_fight: 'wants to fight you!',
|
||||||
accept: 'Accept', decline: 'Decline', back_to_lobby: 'Back to lobby',
|
accept: 'Accept', decline: 'Decline', back_to_lobby: 'Back to lobby',
|
||||||
peer_lost: 'Connection to opponent lost - AI takes over', peer_left: '(left the fight)',
|
peer_lost: 'Opponent disconnected - the AI takes over in 10 s', peer_left: '(left the fight)',
|
||||||
e_EMAIL_EXISTS: 'That e-mail is already registered.', e_EMAIL_NOT_FOUND: 'No account with that e-mail.',
|
e_EMAIL_EXISTS: 'That e-mail is already registered.', e_EMAIL_NOT_FOUND: 'No account with that e-mail.',
|
||||||
e_INVALID_PASSWORD: 'Wrong password.', e_INVALID_LOGIN_CREDENTIALS: 'Wrong e-mail or password.',
|
e_INVALID_PASSWORD: 'Wrong password.', e_INVALID_LOGIN_CREDENTIALS: 'Wrong e-mail or password.',
|
||||||
e_WEAK_PASSWORD: 'Password needs at least 6 characters.', e_INVALID_EMAIL: 'That is not a valid e-mail.',
|
e_WEAK_PASSWORD: 'Password needs at least 8 characters.', e_INVALID_EMAIL: 'That is not a valid e-mail.',
|
||||||
e_MISSING_PASSWORD: 'Please enter a password.', e_OPERATION_NOT_ALLOWED: 'Guest login is off - use e-mail.',
|
e_MISSING_PASSWORD: 'Please enter a password.', e_OPERATION_NOT_ALLOWED: 'Guest login is off - use e-mail.',
|
||||||
e_OFFLINE: 'Online is not set up yet.', e_ERROR: 'Something went wrong. Try again.',
|
e_OFFLINE: 'Online is not set up yet.', e_ERROR: 'Something went wrong. Try again.',
|
||||||
|
f_login: 'Name or e-mail', f_email_opt: 'E-mail (optional)',
|
||||||
|
net_title: 'Network (F3 hides)', net_ping: 'Your ping', net_ping_srv: 'Server measures you', net_ping_opp: 'Opponent ping',
|
||||||
|
net_snaps: 'Snapshots', net_late: 'late', net_input: 'Key to server', net_server: 'Server step',
|
||||||
|
net_l_ping: 'your ping', net_l_opp: 'opponent', net_l_gap: 'snapshot gap', net_l_input: 'key delay',
|
||||||
|
nv_ok: 'Connection looks fine', nv_nofight: 'Not in a fight - only your ping is measured',
|
||||||
|
nv_me_slow: 'Your ping is high ({n} ms) - your connection or the route to the server',
|
||||||
|
nv_me_jitter: 'Your connection is unsteady (snapshots arrive irregularly, ±{n} ms)',
|
||||||
|
nv_opp_slow: 'Opponent has a high ping ({n} ms) - their connection',
|
||||||
|
nv_server: 'Server is slow ({n} ms per step)', nv_queue: 'Keys take {n} ms - data piles up on the way',
|
||||||
|
nv_lost: 'No snapshots for {n} s',
|
||||||
|
e_INVALID_LOGIN: 'Wrong name or password.', e_NAME_EXISTS: 'That name is already taken.', e_BAD_NAME: 'The name needs at least 3 letters or digits.',
|
||||||
|
e_RATE_LIMIT: 'Too many tries - please wait a minute.', e_INVALID_ROBOT: 'Your robot is not ready to fight - check weight and power in the workshop.',
|
||||||
|
e_OPPONENT_INVALID: 'The other robot is not ready to fight.', e_BUSY: 'That player is busy right now.', e_NOT_AVAILABLE: 'That player is not available.',
|
||||||
|
e_OUTDATED: 'A new version is out - please reload the page.', e_REPLACED: 'You are now playing in another window.', e_SESSION_EXPIRED: 'Your session has ended - please log in again.',
|
||||||
|
net_connecting: 'Connecting to the server...', net_lost: 'Connection lost', match_lost: 'No word from the server - the fight is counted there. Back to the lobby.',
|
||||||
pt_open: '🎨 Paint it yourself', pt_title: 'Paint booth', pt_top: 'TOP VIEW · front', pt_side: 'SIDE · front',
|
pt_open: '🎨 Paint it yourself', pt_title: 'Paint booth', pt_top: 'TOP VIEW · front', pt_side: 'SIDE · front',
|
||||||
pt_view_top: 'Top', pt_view_right: 'Right', pt_view_left: 'Left', pt_view_front: 'Front', pt_view_free: 'Turn',
|
pt_view_top: 'Top', pt_view_right: 'Right', pt_view_left: 'Left', pt_view_front: 'Front', pt_view_free: 'Turn',
|
||||||
pt_brush: 'Brush', pt_spray: 'Spray', pt_erase: 'Eraser', pt_stamp: 'Stamp', pt_text: 'Text', pt_fill: 'Fill',
|
pt_brush: 'Brush', pt_spray: 'Spray', pt_erase: 'Eraser', pt_stamp: 'Stamp', pt_text: 'Text', pt_fill: 'Fill',
|
||||||
@@ -483,7 +498,7 @@ window.LANG = {
|
|||||||
all_countries: 'Alle Länder', filter_country: 'Zeigen:',
|
all_countries: 'Alle Länder', filter_country: 'Zeigen:',
|
||||||
s_arena: 'Arena', arena_random: 'Zufällig', arena_workshop: 'Werkstatt-Grube', arena_foundry: 'Die Gießerei', arena_arena64: 'Mega-Dome',
|
s_arena: 'Arena', arena_random: 'Zufällig', arena_workshop: 'Werkstatt-Grube', arena_foundry: 'Die Gießerei', arena_arena64: 'Mega-Dome',
|
||||||
arena_scrapyard: 'Schrottplatz', arena_crucible: 'Der Schmelztiegel', arena_colosseum: 'Große Arena',
|
arena_scrapyard: 'Schrottplatz', arena_crucible: 'Der Schmelztiegel', arena_colosseum: 'Große Arena',
|
||||||
peer_back: 'Gegner ist wieder da', no_pause_online: 'Keine Pause im Live-Kampf',
|
peer_back: 'Gegner ist wieder da', no_pause_online: 'Keine Pause im Live-Kampf - der Kampf läuft weiter.',
|
||||||
r_draw_prize: 'Unentschieden-Preis',
|
r_draw_prize: 'Unentschieden-Preis',
|
||||||
online_guest: 'Als Gast beitreten (ohne E-Mail)', online_short: '🌍 Online',
|
online_guest: 'Als Gast beitreten (ohne E-Mail)', online_short: '🌍 Online',
|
||||||
room_title: 'Lobby {room}', room_count: '{n} in diesem Raum', other_rooms: 'Andere Länder', you: 'du',
|
room_title: 'Lobby {room}', room_count: '{n} in diesem Raum', other_rooms: 'Andere Länder', you: 'du',
|
||||||
@@ -510,12 +525,27 @@ window.LANG = {
|
|||||||
your_flag: 'Deine Flagge:', challenge: 'Herausfordern', busy: 'im Kampf', quick_match: 'Schnelles Match',
|
your_flag: 'Deine Flagge:', challenge: 'Herausfordern', busy: 'im Kampf', quick_match: 'Schnelles Match',
|
||||||
waiting_accept: 'Warte auf den anderen Spieler...', challenge_in: 'Herausforderung!', wants_fight: 'will gegen dich kämpfen!',
|
waiting_accept: 'Warte auf den anderen Spieler...', challenge_in: 'Herausforderung!', wants_fight: 'will gegen dich kämpfen!',
|
||||||
accept: 'Annehmen', decline: 'Ablehnen', back_to_lobby: 'Zurück zur Lobby',
|
accept: 'Annehmen', decline: 'Ablehnen', back_to_lobby: 'Zurück zur Lobby',
|
||||||
peer_lost: 'Verbindung zum Gegner weg - KI übernimmt', peer_left: '(hat den Kampf verlassen)',
|
peer_lost: 'Gegner getrennt - in 10 s übernimmt die KI', peer_left: '(hat den Kampf verlassen)',
|
||||||
e_EMAIL_EXISTS: 'Diese E-Mail ist schon registriert.', e_EMAIL_NOT_FOUND: 'Kein Konto mit dieser E-Mail.',
|
e_EMAIL_EXISTS: 'Diese E-Mail ist schon registriert.', e_EMAIL_NOT_FOUND: 'Kein Konto mit dieser E-Mail.',
|
||||||
e_INVALID_PASSWORD: 'Falsches Passwort.', e_INVALID_LOGIN_CREDENTIALS: 'E-Mail oder Passwort falsch.',
|
e_INVALID_PASSWORD: 'Falsches Passwort.', e_INVALID_LOGIN_CREDENTIALS: 'E-Mail oder Passwort falsch.',
|
||||||
e_WEAK_PASSWORD: 'Passwort braucht mindestens 6 Zeichen.', e_INVALID_EMAIL: 'Das ist keine gültige E-Mail.',
|
e_WEAK_PASSWORD: 'Passwort braucht mindestens 8 Zeichen.', e_INVALID_EMAIL: 'Das ist keine gültige E-Mail.',
|
||||||
e_MISSING_PASSWORD: 'Bitte ein Passwort eingeben.', e_OPERATION_NOT_ALLOWED: 'Gast-Login ist aus - nimm E-Mail.',
|
e_MISSING_PASSWORD: 'Bitte ein Passwort eingeben.', e_OPERATION_NOT_ALLOWED: 'Gast-Login ist aus - nimm E-Mail.',
|
||||||
e_OFFLINE: 'Online ist noch nicht eingerichtet.', e_ERROR: 'Etwas ist schiefgelaufen. Nochmal versuchen.',
|
e_OFFLINE: 'Online ist noch nicht eingerichtet.', e_ERROR: 'Etwas ist schiefgelaufen. Nochmal versuchen.',
|
||||||
|
f_login: 'Name oder E-Mail', f_email_opt: 'E-Mail (optional)',
|
||||||
|
net_title: 'Netzwerk (F3 blendet aus)', net_ping: 'Dein Ping', net_ping_srv: 'Server misst dich', net_ping_opp: 'Gegner-Ping',
|
||||||
|
net_snaps: 'Snapshots', net_late: 'zu spät', net_input: 'Taste bis Server', net_server: 'Server-Schritt',
|
||||||
|
net_l_ping: 'dein Ping', net_l_opp: 'Gegner', net_l_gap: 'Snapshot-Abstand', net_l_input: 'Tasten-Verzögerung',
|
||||||
|
nv_ok: 'Verbindung sieht gut aus', nv_nofight: 'Kein Kampf - nur dein Ping wird gemessen',
|
||||||
|
nv_me_slow: 'Dein Ping ist hoch ({n} ms) - deine Leitung oder der Weg zum Server',
|
||||||
|
nv_me_jitter: 'Deine Verbindung schwankt (Snapshots kommen unregelmäßig, ±{n} ms)',
|
||||||
|
nv_opp_slow: 'Der Gegner hat hohen Ping ({n} ms) - seine Leitung',
|
||||||
|
nv_server: 'Server ist langsam ({n} ms pro Schritt)', nv_queue: 'Tasten brauchen {n} ms - unterwegs staut es sich',
|
||||||
|
nv_lost: 'Seit {n} s keine Snapshots',
|
||||||
|
e_INVALID_LOGIN: 'Name oder Passwort falsch.', e_NAME_EXISTS: 'Dieser Name ist schon vergeben.', e_BAD_NAME: 'Der Name braucht mindestens 3 Buchstaben oder Ziffern.',
|
||||||
|
e_RATE_LIMIT: 'Zu viele Versuche - bitte eine Minute warten.', e_INVALID_ROBOT: 'Dein Roboter ist nicht kampfbereit - prüfe Gewicht und Strom in der Werkstatt.',
|
||||||
|
e_OPPONENT_INVALID: 'Der andere Roboter ist nicht kampfbereit.', e_BUSY: 'Dieser Spieler ist gerade beschäftigt.', e_NOT_AVAILABLE: 'Dieser Spieler ist nicht verfügbar.',
|
||||||
|
e_OUTDATED: 'Es gibt eine neue Version - bitte die Seite neu laden.', e_REPLACED: 'Du spielst jetzt in einem anderen Fenster.', e_SESSION_EXPIRED: 'Deine Sitzung ist abgelaufen - bitte neu anmelden.',
|
||||||
|
net_connecting: 'Verbinde mit dem Server...', net_lost: 'Verbindung verloren', match_lost: 'Keine Antwort vom Server - der Kampf wird dort gewertet. Zurück zur Lobby.',
|
||||||
pt_open: '🎨 Selbst bemalen', pt_title: 'Lackiererei', pt_top: 'OBEN · vorne', pt_side: 'SEITE · vorne',
|
pt_open: '🎨 Selbst bemalen', pt_title: 'Lackiererei', pt_top: 'OBEN · vorne', pt_side: 'SEITE · vorne',
|
||||||
pt_view_top: 'Oben', pt_view_right: 'Rechts', pt_view_left: 'Links', pt_view_front: 'Vorne', pt_view_free: 'Drehen',
|
pt_view_top: 'Oben', pt_view_right: 'Rechts', pt_view_left: 'Links', pt_view_front: 'Vorne', pt_view_free: 'Drehen',
|
||||||
pt_brush: 'Pinsel', pt_spray: 'Spray', pt_erase: 'Radierer', pt_stamp: 'Stempel', pt_text: 'Text', pt_fill: 'Füllen',
|
pt_brush: 'Pinsel', pt_spray: 'Spray', pt_erase: 'Radierer', pt_stamp: 'Stempel', pt_text: 'Text', pt_fill: 'Füllen',
|
||||||
|
|||||||
13
game/live.js
13
game/live.js
@@ -1,4 +1,4 @@
|
|||||||
/* Robot Clash - live settings from the backend (Firebase node /live).
|
/* Robot Clash - live settings from the own server (GET /api/live, admin writes PUT /api/admin/live).
|
||||||
The pure part has no DOM and no network, so the tests can run it in Node.
|
The pure part has no DOM and no network, so the tests can run it in Node.
|
||||||
|
|
||||||
RC.Live.parse(data, now, build) -> {
|
RC.Live.parse(data, now, build) -> {
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
needsReload, // this copy is older than build.min
|
needsReload, // this copy is older than build.min
|
||||||
locked(kind, id), // true when the admin has not released this part/arena/class yet
|
locked(kind, id), // true when the admin has not released this part/arena/class yet
|
||||||
}
|
}
|
||||||
RC.Live.load(net, onChange) reads /live once, then keeps listening, and remembers the last
|
RC.Live.load(net, onChange) reads /api/live, polls it every minute, and remembers the last
|
||||||
answer in localStorage so the game still works offline.
|
answer in localStorage so the game still works offline.
|
||||||
|
|
||||||
Everything is best effort: no config, broken JSON or no network simply means "nothing special
|
Everything is best effort: no config, broken JSON or no network simply means "nothing special
|
||||||
@@ -74,10 +74,11 @@
|
|||||||
const fire = data => { if (data) remember(data); onChange(parse(data, Date.now(), build)); };
|
const fire = data => { if (data) remember(data); onChange(parse(data, Date.now(), build)); };
|
||||||
fire(cached()); // show something immediately
|
fire(cached()); // show something immediately
|
||||||
if (!net || !net.enabled) return { close() {} };
|
if (!net || !net.enabled) return { close() {} };
|
||||||
net.db.get('live').then(d => { if (d) fire(d); }, () => {});
|
// the admin changes these rarely: read now, then poll every minute
|
||||||
let sub = null;
|
const pull = () => net.api('GET', '/api/live').then(d => { if (d) fire(d); }, () => {});
|
||||||
try { sub = net.db.stream('live', d => { if (d) fire(d); }); } catch (e) { sub = null; }
|
pull();
|
||||||
return { close() { if (sub) sub.close(); } };
|
const timer = setInterval(pull, 60000);
|
||||||
|
return { close() { clearInterval(timer); } };
|
||||||
}
|
}
|
||||||
|
|
||||||
RC.Live = { parse, load, KEY };
|
RC.Live = { parse, load, KEY };
|
||||||
|
|||||||
169
game/lobby.js
169
game/lobby.js
@@ -1,138 +1,65 @@
|
|||||||
/* Robot Clash - online lobby: presence, player list, challenges, match creation. No DOM.
|
/* Robot Clash - online lobby over the server WebSocket (net.socket). No DOM. The server owns presence,
|
||||||
Needs net.js (RC.Net). Transport is Firebase RTDB (net.db). All cosmetic/casual, see docs/firebase.
|
challenges and matches; this just mirrors its state and forwards clicks.
|
||||||
|
|
||||||
const lobby = RC.Lobby({ net, getProfile: () => ({ name, flag, build, paint, fame }) });
|
const lobby = RC.Lobby({ net })
|
||||||
lobby.enter() announce presence, start heartbeat, watch list + incoming challenges
|
lobby.enter() / leave()
|
||||||
lobby.leave() remove presence, stop everything
|
lobby.onList(fn) fn([{ uid, name, flag, fame, state, room }]) everyone online except me
|
||||||
lobby.onList(fn) fn([{ uid, name, flag, state, fame }]) - online players except me, newest first
|
lobby.onIncoming(fn) fn({ from, fromName, fromFlag }) someone challenges me
|
||||||
lobby.onIncoming(fn) fn({ from, fromName, fromFlag, build, paint, seed }) - someone challenges me
|
lobby.onCancel(fn) fn({ reason }) my challenge / an incoming one fell through
|
||||||
lobby.onMatch(fn) fn({ id, host (bool), opp: { uid, name, flag, build, paint }, seed }) - fight on
|
lobby.onMatch(fn) fn(matchStartMsg) fight on (also after a reconnect)
|
||||||
lobby.onCancel(fn) fn() - a pending challenge I sent/got fell through
|
lobby.onEnd(fn) fn(matchEndMsg) server result + rewards + new save
|
||||||
await lobby.challenge(uid) invite a player (writes to their inbox, waits for accept)
|
lobby.onError(fn) fn(code) BUSY | INVALID_ROBOT | ...
|
||||||
await lobby.accept(from) accept an incoming challenge -> creates the match
|
lobby.challenge(uid) / accept(from) / decline(from) / cancel() / setRoom(code|'all')
|
||||||
lobby.decline(from) reject an incoming challenge
|
lobby.pending uid I challenged (or null) */
|
||||||
lobby.cancel() withdraw the challenge I sent
|
|
||||||
|
|
||||||
Presence TTL: entries older than STALE ms count as offline (no SDK onDisconnect). */
|
|
||||||
(function (root) {
|
(function (root) {
|
||||||
'use strict';
|
'use strict';
|
||||||
const RC = (root.RC = root.RC || {});
|
const RC = (root.RC = root.RC || {});
|
||||||
const HEARTBEAT = 4000, STALE = 12000;
|
|
||||||
const now = () => Date.now();
|
|
||||||
// match id = both uids sorted + join -> same id on both sides; lower uid hosts (authority)
|
|
||||||
const matchId = (a, b) => [a, b].sort().join('_');
|
|
||||||
const isHost = (a, b) => a < b;
|
|
||||||
|
|
||||||
RC.Lobby = (opt) => {
|
RC.Lobby = (opt) => {
|
||||||
const net = opt.net, db = net.db;
|
const net = opt.net, sock = net.socket;
|
||||||
const cbs = { list: [], incoming: [], match: [], cancel: [] };
|
const cbs = { list: [], incoming: [], cancel: [], match: [], end: [], error: [] };
|
||||||
const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { /* ignore */ } });
|
const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { console.error(e); } });
|
||||||
let hb = null, subList = null, subIn = null, subMatch = null;
|
const players = new Map();
|
||||||
let outgoing = null; // uid I challenged
|
let me = null, pending = null, offs = [], incomingFrom = null;
|
||||||
let inMatch = null; // active match id
|
|
||||||
|
|
||||||
const me = () => net.uid;
|
const list = () => emit('list', [...players.values()].sort((a, b) => (b.fame | 0) - (a.fame | 0) || String(a.name).localeCompare(b.name)));
|
||||||
const prof = () => opt.getProfile();
|
|
||||||
|
|
||||||
async function beat(state) {
|
function wire() {
|
||||||
const p = prof();
|
offs = [
|
||||||
await db.put(`lobby/${me()}`, { name: p.name, flag: p.flag || 'XX', room: p.room || p.flag || 'XX', fame: p.fame | 0, ver: 2, state: state || 'idle', ts: { '.sv': 'timestamp' } });
|
sock.on('lobby', m => { players.clear(); for (const p of m.players) players.set(p.uid, p); me = m.you; list(); }),
|
||||||
}
|
sock.on('lobby.join', m => { players.set(m.player.uid, m.player); list(); }),
|
||||||
|
sock.on('lobby.state', m => { if (m.player.uid === net.uid) { me = m.player; return; } players.set(m.player.uid, m.player); list(); }),
|
||||||
function watchList() {
|
sock.on('lobby.leave', m => { players.delete(m.uid); list(); }),
|
||||||
subList = db.stream('lobby', data => {
|
sock.on('challenge.in', m => { incomingFrom = m.from; emit('incoming', { from: m.from, fromName: m.name, fromFlag: m.flag, fame: m.fame }); }),
|
||||||
const t = now(), mine = me();
|
sock.on('challenge.gone', m => {
|
||||||
const rows = Object.entries(data || {})
|
if (m.to && m.to === pending) { pending = null; emit('cancel', { reason: m.reason || 'gone', outgoing: true }); }
|
||||||
.map(([uid, v]) => Object.assign({ uid }, v))
|
if (m.from && m.from === incomingFrom) { incomingFrom = null; emit('cancel', { reason: m.reason || 'gone', outgoing: false }); }
|
||||||
.filter(v => v.uid !== mine && v.name && (t - (v.ts || 0)) < STALE)
|
}),
|
||||||
.sort((a, b) => (b.ts || 0) - (a.ts || 0));
|
sock.on('match.start', m => { pending = null; incomingFrom = null; emit('match', m); }),
|
||||||
emit('list', rows);
|
sock.on('match.end', m => emit('end', m)),
|
||||||
});
|
sock.on('error', m => { if (['BUSY', 'NOT_AVAILABLE', 'INVALID_ROBOT', 'OPPONENT_INVALID'].includes(m.code)) pending = null; emit('error', m.code); }),
|
||||||
}
|
sock.on('close', () => { players.clear(); pending = null; list(); }),
|
||||||
|
];
|
||||||
// incoming challenges land under challenges/<me>/<fromUid>
|
|
||||||
function watchIncoming() {
|
|
||||||
subIn = db.stream(`challenges/${me()}`, data => {
|
|
||||||
const entries = Object.entries(data || {}).filter(([, v]) => v && v.from && (now() - (v.ts || 0)) < STALE);
|
|
||||||
if (!entries.length) return;
|
|
||||||
const [, c] = entries[0];
|
|
||||||
emit('incoming', { from: c.from, fromName: c.fromName, fromFlag: c.fromFlag, build: c.build, paint: c.paint, seed: c.seed });
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// the match node appears for both players once created (host writes it on accept)
|
|
||||||
function watchMatch(id, oppUid, host) {
|
|
||||||
cleanupMatch();
|
|
||||||
inMatch = id;
|
|
||||||
subMatch = db.stream(`matches/${id}/meta`, meta => {
|
|
||||||
// wait until BOTH players have written their robot (each side patches its own entry)
|
|
||||||
if (!meta || inMatch !== id || meta.seed == null || !meta[oppUid] || !meta[me()]) return;
|
|
||||||
emit('match', { id, host, opp: { uid: oppUid, name: meta[oppUid] && meta[oppUid].name, flag: meta[oppUid] && meta[oppUid].flag, build: meta[oppUid] && meta[oppUid].build, paint: meta[oppUid] && meta[oppUid].paint }, seed: meta.seed });
|
|
||||||
if (subMatch) { subMatch.close(); subMatch = null; } // meta is fixed; stop watching
|
|
||||||
});
|
|
||||||
}
|
|
||||||
function cleanupMatch() { if (subMatch) { subMatch.close(); subMatch = null; } }
|
|
||||||
|
|
||||||
async function challenge(uid) {
|
|
||||||
if (outgoing) return;
|
|
||||||
outgoing = uid;
|
|
||||||
const p = prof();
|
|
||||||
// a rematch reuses the match id, so clear whatever a crashed fight left behind -
|
|
||||||
// otherwise the waiting side would pick up the old seed (and the old arena) at once
|
|
||||||
await db.del(`matches/${matchId(me(), uid)}`);
|
|
||||||
await beat('searching');
|
|
||||||
await db.put(`challenges/${uid}/${me()}`, { from: me(), fromName: p.name, fromFlag: p.flag || 'XX', build: p.build, paint: p.paint, seed: (Math.random() * 1e9) | 0, ts: { '.sv': 'timestamp' } });
|
|
||||||
// wait for the other side to create the match (they host if their uid < mine)
|
|
||||||
const id = matchId(me(), uid), host = isHost(me(), uid);
|
|
||||||
const give = setTimeout(() => { if (outgoing === uid) { emit('cancel'); cancel(); } }, STALE);
|
|
||||||
const watch = db.stream(`matches/${id}/meta/seed`, seed => {
|
|
||||||
if (seed == null) return;
|
|
||||||
clearTimeout(give); watch.close(); outgoing = null;
|
|
||||||
createMatch(uid, false); // add my own robot; the seed is already set by the other side
|
|
||||||
watchMatch(id, uid, host);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function accept(from) {
|
|
||||||
const id = matchId(me(), from), host = isHost(me(), from);
|
|
||||||
await db.del(`challenges/${me()}/${from}`);
|
|
||||||
await createMatch(from, true); // whoever accepts rolls the seed (and with it the arena)
|
|
||||||
watchMatch(id, from, host);
|
|
||||||
}
|
|
||||||
function decline(from) { db.del(`challenges/${me()}/${from}`); }
|
|
||||||
function cancel() { if (outgoing) { db.del(`challenges/${outgoing}/${me()}`); outgoing = null; beat('idle'); } }
|
|
||||||
|
|
||||||
// setSeed: only the side that accepts writes the seed, so both read the exact same value.
|
|
||||||
// It is rolled fresh for every match - a seed derived from the match id would hand the same
|
|
||||||
// pair of players the same arena for ever.
|
|
||||||
async function createMatch(oppUid, setSeed) {
|
|
||||||
const id = matchId(me(), oppUid), p = prof();
|
|
||||||
const meta = { [me()]: { name: p.name, flag: p.flag || 'XX', build: p.build, paint: p.paint } };
|
|
||||||
if (setSeed) meta.seed = ((Math.random() * 1e9) | 0) || 1;
|
|
||||||
await db.patch(`matches/${id}/meta`, meta);
|
|
||||||
await beat('inmatch');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
onList: fn => cbs.list.push(fn),
|
onList: fn => cbs.list.push(fn),
|
||||||
onIncoming: fn => cbs.incoming.push(fn),
|
onIncoming: fn => cbs.incoming.push(fn),
|
||||||
onMatch: fn => cbs.match.push(fn),
|
|
||||||
onCancel: fn => cbs.cancel.push(fn),
|
onCancel: fn => cbs.cancel.push(fn),
|
||||||
challenge, accept, decline, cancel,
|
onMatch: fn => cbs.match.push(fn),
|
||||||
async enter() {
|
onEnd: fn => cbs.end.push(fn),
|
||||||
if (!net.enabled || !me()) return;
|
onError: fn => cbs.error.push(fn),
|
||||||
await beat('idle');
|
get pending() { return pending; },
|
||||||
hb = setInterval(() => db.patch(`lobby/${me()}`, { ts: { '.sv': 'timestamp' }, state: outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle' }), HEARTBEAT);
|
get me() { return me; },
|
||||||
watchList(); watchIncoming();
|
get connected() { return sock.connected; },
|
||||||
},
|
enter() { if (!net.enabled || !net.uid) return; if (!offs.length) wire(); sock.connect(); },
|
||||||
refresh() { if (me()) beat(outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle'); },
|
leave() { offs.forEach(off => off()); offs = []; sock.close(); players.clear(); pending = null; },
|
||||||
endMatch() { const id = inMatch; inMatch = null; cleanupMatch(); if (id) db.del(`matches/${id}`); if (me()) beat('idle'); },
|
challenge(uid) { if (pending) return; pending = uid; if (!sock.send({ t: 'challenge', to: uid })) pending = null; },
|
||||||
leave() {
|
cancel() { if (!pending) return; sock.send({ t: 'challenge.cancel' }); pending = null; },
|
||||||
clearInterval(hb); hb = null;
|
accept(from) { incomingFrom = null; sock.send({ t: 'challenge.accept', from }); },
|
||||||
if (subList) subList.close(); if (subIn) subIn.close(); cleanupMatch();
|
decline(from) { incomingFrom = null; sock.send({ t: 'challenge.decline', from }); },
|
||||||
if (me()) db.del(`lobby/${me()}`);
|
setRoom(room) { sock.send({ t: 'room', room: room || 'all' }); },
|
||||||
},
|
leaveMatch() { sock.send({ t: 'match.leave' }); },
|
||||||
matchId, isHost,
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
})(typeof window !== 'undefined' ? window : globalThis);
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
drives this pure logic, so the hard-to-test bit here is small and fully covered by tests.
|
drives this pure logic, so the hard-to-test bit here is small and fully covered by tests.
|
||||||
|
|
||||||
Every client computes the SAME bracket from the same inputs (frozen player list + seed), so no
|
Every client computes the SAME bracket from the same inputs (frozen player list + seed), so no
|
||||||
server is needed to agree on who plays whom. Results come in over Firebase as a map
|
server is needed to agree on who plays whom. Results come in from the server as a map
|
||||||
results[round][pairIndex] = winnerUid; a bye (odd player out) advances on its own.
|
results[round][pairIndex] = winnerUid; a bye (odd player out) advances on its own.
|
||||||
|
|
||||||
RC.LTourney.order(uids, seed) -> seeded slot order, padded with null byes to a power of two
|
RC.LTourney.order(uids, seed) -> seeded slot order, padded with null byes to a power of two
|
||||||
|
|||||||
238
game/net.js
238
game/net.js
@@ -1,170 +1,156 @@
|
|||||||
/* Robot Clash - Firebase over plain REST (no SDK, classic script, runs from file://).
|
/* Robot Clash - client side of the own server (server/): REST + one WebSocket. Classic script, no SDK.
|
||||||
Auth = Identity Toolkit REST, database = Realtime Database REST + Server-Sent-Events for push.
|
Offline (file://, no server) everything is disabled and the game runs as the campaign only.
|
||||||
|
|
||||||
const net = RC.Net({ apiKey: '...', dbUrl: 'https://<proj>-default-rtdb.firebaseio.com' });
|
const net = RC.Net({ serverUrl: '' }) '' = same origin as the page
|
||||||
net.enabled false without a full config -> game stays offline
|
net.enabled false on file:// -> offline
|
||||||
await net.auth.register(email, pass, name) -> { ok, error } (error: 'EMAIL_EXISTS' | 'WEAK_PASSWORD' | ...)
|
await net.auth.register(name, pass, email?) -> { ok, error } error: NAME_EXISTS | WEAK_PASSWORD | BAD_NAME | ...
|
||||||
await net.auth.login(email, pass) -> { ok, error } ('EMAIL_NOT_FOUND' | 'INVALID_PASSWORD' | ...)
|
await net.auth.login(nameOrEmail, pass) -> { ok, error } INVALID_LOGIN | RATE_LIMIT | ...
|
||||||
await net.auth.guest(name) -> { ok, error } (anonymous sign-in, must be enabled in Firebase)
|
await net.auth.guest(name) -> { ok, error }
|
||||||
net.auth.resume() -> true if a saved session was restored (async refresh follows)
|
net.auth.resume() / logout() / current {uid,name,email,guest,admin} / onChange(fn)
|
||||||
net.auth.logout() / net.auth.current -> { uid, name, email, guest } | null
|
await net.api(method, path, body) -> parsed JSON or null (never throws); 401 -> one refresh + retry
|
||||||
net.auth.onChange(fn) called after login/logout/refresh
|
net.socket.connect() / close() / send(msg) / on(type, fn) / connected
|
||||||
|
events: every server message type ('lobby', 'snap', 'match.end', ...) + 'open' | 'close' | 'outdated'
|
||||||
|
|
||||||
await net.db.get(path) -> value | null
|
Session: refresh tokens rotate (each works once). Refresh is single-flight, and the session is shared
|
||||||
await net.db.put(path, value) -> ok (PUT, replaces)
|
through localStorage, so two tabs never burn the same refresh token and log each other out.
|
||||||
await net.db.patch(path, obj) -> ok (PATCH, merges)
|
Dev: ?slot=2 keeps a second session in the same browser (test PvP with two accounts in two tabs). */
|
||||||
await net.db.push(path, value) -> key | null (POST, new child)
|
|
||||||
await net.db.del(path) -> ok
|
|
||||||
const sub = net.db.stream(path, onValue) -> { close() } push updates via EventSource
|
|
||||||
onValue(value) fires with the whole subtree on connect and on every change.
|
|
||||||
|
|
||||||
All DB calls carry the id token (?auth=). Token auto-refreshes before it expires.
|
|
||||||
Every call is best effort: on error db.get -> null, writes -> false, never throws. */
|
|
||||||
(function (root) {
|
(function (root) {
|
||||||
'use strict';
|
'use strict';
|
||||||
const RC = (root.RC = root.RC || {});
|
const RC = (root.RC = root.RC || {});
|
||||||
|
|
||||||
RC.Net = (cfg = {}) => {
|
RC.Net = (cfg = {}) => {
|
||||||
const base = (cfg.serverUrl || '').replace(/\/+$/, ''); // '' = same origin as the page
|
const base = (cfg.serverUrl || '').replace(/\/+$/, '');
|
||||||
const API = base + '/api', DB = base + '/db';
|
|
||||||
// online when served over http(s) (own server) or given an explicit serverUrl; file:// stays offline
|
|
||||||
const enabled = cfg.enabled !== false && typeof fetch !== 'undefined' && (!!base || /^https?:$/.test(location.protocol));
|
const enabled = cfg.enabled !== false && typeof fetch !== 'undefined' && (!!base || /^https?:$/.test(location.protocol));
|
||||||
const store = Kit.store('robotclash.net');
|
const slot = (typeof location !== 'undefined' && new URLSearchParams(location.search).get('slot')) || '';
|
||||||
|
const store = Kit.store('robotclash.net' + (slot ? '.' + slot : ''));
|
||||||
|
|
||||||
let session = null; // { idToken, refreshToken, uid, name, email, guest, exp }
|
let session = null; // { idToken, exp, refreshToken, uid, name, email, guest, admin }
|
||||||
const listeners = [];
|
const listeners = [];
|
||||||
const fire = () => listeners.forEach(fn => { try { fn(cur()); } catch (e) { /* ignore */ } });
|
const cur = () => (session ? { uid: session.uid, name: session.name, email: session.email, guest: !!session.guest, admin: !!session.admin } : null);
|
||||||
function cur() { return session ? { uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null; }
|
const fire = () => listeners.forEach(fn => { try { fn(cur()); } catch (e) { /* listener bug */ } });
|
||||||
|
const persist = () => store.set('session', session);
|
||||||
|
const stored = () => store.get('session', null);
|
||||||
|
|
||||||
async function postJson(url, body) {
|
function setSession(d) {
|
||||||
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
session = {
|
||||||
|
idToken: d.idToken, refreshToken: d.refreshToken, exp: Date.now() + ((+d.expiresIn || 3600) - 60) * 1000,
|
||||||
|
uid: d.uid, name: d.name || '', email: d.email || '', guest: !!d.guest, admin: !!d.admin,
|
||||||
|
};
|
||||||
|
persist(); fire();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function post(path, body) {
|
||||||
|
const res = await fetch(base + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
||||||
const data = await res.json().catch(() => ({}));
|
const data = await res.json().catch(() => ({}));
|
||||||
if (!res.ok) { const msg = (data.error && (data.error.message || data.error)) || ('HTTP_' + res.status); const e = new Error(msg); e.code = String(msg).split(/[ :]/)[0]; throw e; }
|
if (!res.ok) { const e = new Error(data.error || 'HTTP_' + res.status); e.code = data.error || 'HTTP_' + res.status; throw e; }
|
||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
function save() { store.set('session', session ? { refreshToken: session.refreshToken, uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null); }
|
// another tab may already have refreshed: take its newer session instead of burning ours
|
||||||
|
function adoptStored() {
|
||||||
function setAuth(d, name, guest) {
|
const s = stored();
|
||||||
session = {
|
if (s && session && s.uid === session.uid && s.refreshToken !== session.refreshToken && s.exp > Date.now()) { session = s; return true; }
|
||||||
idToken: d.idToken || d.id_token, refreshToken: d.refreshToken || d.refresh_token,
|
return false;
|
||||||
uid: d.uid || d.localId || d.user_id, name: name || (session && session.name) || '', email: d.email || (session && session.email) || '', guest: !!guest,
|
|
||||||
exp: Date.now() + (+(d.expiresIn || d.expires_in || 3600) - 60) * 1000,
|
|
||||||
};
|
|
||||||
save(); fire();
|
|
||||||
}
|
}
|
||||||
|
let refreshing = null;
|
||||||
async function refresh() {
|
function refresh() {
|
||||||
if (!session || !session.refreshToken) return false;
|
if (!session || !session.refreshToken) return Promise.resolve(false);
|
||||||
try {
|
if (refreshing) return refreshing; // single flight
|
||||||
const d = await postJson(`${API}/auth/refresh`, { refreshToken: session.refreshToken });
|
refreshing = (async () => {
|
||||||
session.idToken = d.idToken; session.refreshToken = d.refreshToken; session.uid = d.uid;
|
if (adoptStored()) return true;
|
||||||
session.exp = Date.now() + (+(d.expiresIn || 3600) - 60) * 1000; save(); return true;
|
try { const d = await post('/api/auth/refresh', { refreshToken: session.refreshToken }); setSession(d); return true; } catch (e) {
|
||||||
} catch (e) { session = null; save(); fire(); return false; }
|
if (adoptStored()) return true; // lost the race against another tab
|
||||||
|
if (e.code === 'INVALID_REFRESH') { session = null; persist(); fire(); }
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
})().finally(() => { refreshing = null; });
|
||||||
|
return refreshing;
|
||||||
}
|
}
|
||||||
async function token() {
|
async function token() {
|
||||||
if (!session) return null;
|
if (!session) return null;
|
||||||
if (Date.now() >= session.exp) { if (!await refresh()) return null; }
|
if (Date.now() >= session.exp && !(await refresh())) return null;
|
||||||
return session.idToken;
|
return session ? session.idToken : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const authCall = async fn => {
|
||||||
|
if (!enabled) return { ok: false, error: 'OFFLINE' };
|
||||||
|
try { setSession(await fn()); return { ok: true }; } catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
|
||||||
|
};
|
||||||
const auth = {
|
const auth = {
|
||||||
get current() { return cur(); },
|
get current() { return cur(); },
|
||||||
onChange(fn) { listeners.push(fn); },
|
onChange(fn) { listeners.push(fn); },
|
||||||
async register(email, pass, name) {
|
register: (name, pass, email) => authCall(() => post('/api/auth/register', { name: Kit.cleanName(name), pass, email: String(email || '').trim() })),
|
||||||
if (!enabled) return { ok: false, error: 'OFFLINE' };
|
login: (login, pass) => authCall(() => post('/api/auth/login', { login: String(login || '').trim(), pass })),
|
||||||
email = String(email || '').trim().toLowerCase();
|
guest: name => authCall(() => post('/api/auth/guest', { name: Kit.cleanName(name) || 'Guest' })),
|
||||||
try {
|
|
||||||
const d = await postJson(`${API}/auth/register`, { email, pass, name: Kit.cleanName(name) || email.split('@')[0] });
|
|
||||||
setAuth(d, d.name || Kit.cleanName(name) || email.split('@')[0], false);
|
|
||||||
return { ok: true };
|
|
||||||
} catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
|
|
||||||
},
|
|
||||||
async login(email, pass) {
|
|
||||||
if (!enabled) return { ok: false, error: 'OFFLINE' };
|
|
||||||
email = String(email || '').trim().toLowerCase();
|
|
||||||
try {
|
|
||||||
const d = await postJson(`${API}/auth/login`, { email, pass });
|
|
||||||
setAuth(d, d.name || email.split('@')[0], false);
|
|
||||||
return { ok: true };
|
|
||||||
} catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
|
|
||||||
},
|
|
||||||
async guest(name) {
|
|
||||||
if (!enabled) return { ok: false, error: 'OFFLINE' };
|
|
||||||
try {
|
|
||||||
const d = await postJson(`${API}/auth/guest`, { name: Kit.cleanName(name) || 'Guest' });
|
|
||||||
setAuth(d, d.name || Kit.cleanName(name) || 'Guest', true);
|
|
||||||
return { ok: true };
|
|
||||||
} catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
|
|
||||||
},
|
|
||||||
resume() {
|
resume() {
|
||||||
const s = store.get('session', null);
|
const s = stored();
|
||||||
if (!s || !s.refreshToken) return false;
|
if (!s || !s.refreshToken) return false;
|
||||||
session = Object.assign({ idToken: '', exp: 0 }, s);
|
session = s;
|
||||||
refresh().then(ok => { if (ok) fire(); });
|
if (Date.now() >= (s.exp || 0)) refresh().then(ok => { if (ok) fire(); }); else fire();
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
logout() { const r = session && session.refreshToken; session = null; save(); fire(); if (r) fetch(`${API}/auth/logout`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken: r }) }).catch(() => {}); },
|
logout() {
|
||||||
|
const r = session && session.refreshToken;
|
||||||
|
socket.close(); session = null; persist(); fire();
|
||||||
|
if (r) fetch(base + '/api/auth/logout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken: r }) }).catch(() => {});
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
async function dbGet(path) {
|
async function api(method, path, body) {
|
||||||
if (!enabled) return null;
|
if (!enabled) return null;
|
||||||
|
for (let attempt = 0; attempt < 2; attempt++) {
|
||||||
const t = await token();
|
const t = await token();
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${DB}/${path}.json${t ? '?auth=' + t : ''}`, { cache: 'no-store' });
|
const res = await fetch(base + path, {
|
||||||
|
method, cache: 'no-store',
|
||||||
|
headers: Object.assign({ 'Content-Type': 'application/json' }, t ? { Authorization: 'Bearer ' + t } : {}),
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
});
|
||||||
|
if (res.status === 401 && attempt === 0 && session) { session.exp = 0; continue; } // token died early: refresh once
|
||||||
return res.ok ? await res.json() : null;
|
return res.ok ? await res.json() : null;
|
||||||
} catch (e) { return null; }
|
} catch (e) { return null; }
|
||||||
}
|
}
|
||||||
async function dbWrite(method, path, value) {
|
return null;
|
||||||
if (!enabled) return false;
|
|
||||||
const t = await token();
|
|
||||||
try {
|
|
||||||
const res = await fetch(`${DB}/${path}.json${t ? '?auth=' + t : ''}`, {
|
|
||||||
method, headers: { 'Content-Type': 'application/json' }, body: value === undefined ? undefined : JSON.stringify(value),
|
|
||||||
});
|
|
||||||
return res.ok ? (method === 'POST' ? (await res.json()).name : true) : false;
|
|
||||||
} catch (e) { return false; }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const db = {
|
// ---- one WebSocket with reconnect -------------------------------------------------------------
|
||||||
get: dbGet,
|
const handlers = {};
|
||||||
put: (p, v) => dbWrite('PUT', p, v),
|
const emit = (type, msg) => (handlers[type] || []).slice().forEach(fn => { try { fn(msg); } catch (e) { console.error(e); } });
|
||||||
patch: (p, v) => dbWrite('PATCH', p, v),
|
let ws = null, want = false, retry = null, backoff = 1000, isOpen = false;
|
||||||
push: (p, v) => dbWrite('POST', p, v),
|
const wsUrl = () => {
|
||||||
del: p => dbWrite('DELETE', p),
|
const b = base || location.origin;
|
||||||
// EventSource push stream. RTDB sends 'put' (whole subtree at /) and 'patch' (partial) events.
|
return b.replace(/^http/, 'ws') + '/ws';
|
||||||
stream(path, onValue) {
|
};
|
||||||
if (!enabled || typeof EventSource === 'undefined') return { close() {} };
|
async function open() {
|
||||||
let es = null, closed = false, value = null, retry = null;
|
if (!want || ws) return;
|
||||||
const open = async () => {
|
|
||||||
if (closed) return;
|
|
||||||
const t = await token();
|
const t = await token();
|
||||||
es = new EventSource(`${DB}/${path}.json${t ? '?auth=' + t : ''}`);
|
if (!t || !want || ws) { if (want) schedule(); return; }
|
||||||
// 'put' = replace the value at d.path; 'patch' = merge d.data's children into d.path
|
const s = ws = new WebSocket(wsUrl());
|
||||||
const setAt = (keys, data) => {
|
s.onopen = () => s.send(JSON.stringify({ t: 'hello', v: RC.Proto.VERSION, token: t }));
|
||||||
if (!keys.length) { value = data; return; }
|
s.onmessage = ev => {
|
||||||
if (value == null || typeof value !== 'object') value = {};
|
let msg; try { msg = JSON.parse(ev.data); } catch (e) { return; }
|
||||||
let o = value;
|
msg._bytes = ev.data.length; // for the network overlay (bandwidth)
|
||||||
for (let i = 0; i < keys.length - 1; i++) { if (o[keys[i]] == null || typeof o[keys[i]] !== 'object') o[keys[i]] = {}; o = o[keys[i]]; }
|
if (msg.t === 'welcome') { isOpen = true; backoff = 1000; emit('open', msg); }
|
||||||
if (data == null) delete o[keys[keys.length - 1]]; else o[keys[keys.length - 1]] = data;
|
if (msg.t === 'error' && (msg.code === 'OUTDATED' || msg.code === 'REPLACED')) { want = false; emit(msg.code === 'OUTDATED' ? 'outdated' : 'replaced', msg); }
|
||||||
|
if (msg.t === 'error' && msg.code === 'UNAUTH' && session) session.exp = 0; // refresh before the retry
|
||||||
|
emit(msg.t, msg);
|
||||||
};
|
};
|
||||||
const apply = ev => {
|
s.onclose = () => {
|
||||||
let d; try { d = JSON.parse(ev.data); } catch (e) { return; }
|
const was = isOpen; ws = null; isOpen = false;
|
||||||
if (!d || typeof d.path !== 'string') return;
|
if (was) emit('close', {});
|
||||||
const keys = d.path.split('/').filter(Boolean);
|
if (want) schedule();
|
||||||
if (ev.type === 'patch' && d.data && typeof d.data === 'object') {
|
|
||||||
for (const [k, v] of Object.entries(d.data)) setAt(keys.concat(k.split('/').filter(Boolean)), v);
|
|
||||||
} else setAt(keys, d.data);
|
|
||||||
try { onValue(value); } catch (e) { /* ignore */ }
|
|
||||||
};
|
};
|
||||||
es.addEventListener('put', apply);
|
s.onerror = () => {};
|
||||||
es.addEventListener('patch', apply);
|
}
|
||||||
es.onerror = () => { if (closed) return; es.close(); retry = setTimeout(open, 1500); };
|
function schedule() { clearTimeout(retry); retry = setTimeout(open, backoff); backoff = Math.min(10000, backoff * 2); }
|
||||||
};
|
const socket = {
|
||||||
open();
|
get connected() { return isOpen; },
|
||||||
return { close() { closed = true; clearTimeout(retry); if (es) es.close(); } };
|
connect() { if (!enabled) return; want = true; open(); },
|
||||||
},
|
close() { want = false; clearTimeout(retry); if (ws) { try { ws.close(); } catch (e) { /* closed */ } } ws = null; isOpen = false; },
|
||||||
|
send(msg) { if (ws && isOpen && ws.readyState === 1) { ws.send(JSON.stringify(msg)); return true; } return false; },
|
||||||
|
on(type, fn) { (handlers[type] = handlers[type] || []).push(fn); return () => { handlers[type] = handlers[type].filter(f => f !== fn); }; },
|
||||||
};
|
};
|
||||||
|
|
||||||
return { enabled, auth, db, get uid() { return session ? session.uid : null; }, token };
|
return { enabled, auth, api, socket, token, get uid() { return session ? session.uid : null; } };
|
||||||
};
|
};
|
||||||
})(typeof window !== 'undefined' ? window : globalThis);
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
|
|||||||
226
game/netfight.js
226
game/netfight.js
@@ -1,162 +1,102 @@
|
|||||||
/* Robot Clash - live PvP sync over an existing deterministic fight. Needs net.js, combat.js, ai.js.
|
/* Robot Clash - client side of a server-run live fight. No simulation here: the server steps RC.Combat;
|
||||||
Robot 0 is always the local player, robot 1 the opponent (both clients see it that way, so the host
|
this sends the local input and shows the server's snapshots (already mapped to "robot 0 = me").
|
||||||
mirrors indices when it publishes). The lower-uid player is the host (authority): it runs the real
|
|
||||||
RC.Combat.step and publishes snapshots; the guest renders them and only sends its input.
|
|
||||||
|
|
||||||
const nf = RC.NetFight({ net, id, host, mySeat, oppStyle, oppSkill, onPeerLost(wasHost) });
|
Entity interpolation: snapshots (20 Hz) are buffered and rendered ~INTERP_DELAY ms in the past, between the two
|
||||||
nf.start()
|
snapshots bracketing the render time. This absorbs jitter (uneven arrival) so the robot does not jump - the old
|
||||||
HOST each tick, instead of the normal step:
|
"ease to the newest snapshot" had no buffer and jumped whenever a snapshot arrived late.
|
||||||
nf.hostStep(s, localInput, dt) runs step with [local, remote|AI], publishes ~15 Hz, returns events
|
|
||||||
GUEST each frame, instead of step:
|
|
||||||
nf.guestFrame(s, localInput, dt) eases robots toward the last snapshot, returns events to play
|
|
||||||
nf.peerAlive false once the peer went silent > GRACE (AI takes over)
|
|
||||||
nf.stop()
|
|
||||||
|
|
||||||
mySeat: 0 if I am meta[myUid] rendered as robot 0 (always true locally). The host publishes with robots
|
const nf = RC.NetFight({ net, seat, stats, interp, lag })
|
||||||
ordered [host, guest]; each side maps so that *its* robot is index 0. */
|
interp interpolation delay in ms (default 100); lag = { base, jit, seed } delays incoming snapshots (dev only)
|
||||||
|
nf.frame(s, input, dt) send input, show the interpolated world, return not-yet-seen events
|
||||||
|
nf.oppAway / nf.silentFor / nf.stop()
|
||||||
|
Pure, Node-testable: RC.NetFight.pickFrames(buf, renderTime), RC.NetFight.lerpRobot(da, db, k) */
|
||||||
(function (root) {
|
(function (root) {
|
||||||
'use strict';
|
'use strict';
|
||||||
const RC = (root.RC = root.RC || {});
|
const RC = (root.RC = root.RC || {});
|
||||||
const PUB = 1 / 15, GRACE = 4000; // ms without news before the AI covers for the peer
|
const SEND_MIN = 1 / 30, SEND_KEEP = 0.25, INTERP_DEFAULT = 120, BUF_MAX = 30;
|
||||||
// robot fields the view / HUD / sound read - kept small for the wire
|
const EASE = ['x', 'z', 'y'], ANG = ['a', 'turretA'];
|
||||||
const RF = ['x', 'z', 'a', 'y', 'hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'turretA', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'lost', 'dead', 'out'];
|
|
||||||
const rnd = v => (typeof v === 'number' ? Math.round(v * 1000) / 1000 : v);
|
|
||||||
const packRobot = r => { const o = {}; for (const k of RF) o[k] = rnd(r[k]); return o; };
|
|
||||||
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
|
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
|
||||||
|
const mul = s => { let a = (s >>> 0) || 1; return () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };
|
||||||
|
|
||||||
|
// buf = [{ at, tick, snap }] sorted by at/tick ascending. Pick the snapshot reached by renderTime (a) and the
|
||||||
|
// next one (b), with the fraction between them. Past the newest -> hold the newest (a === b, frac 1).
|
||||||
|
function pickFrames(buf, renderTime) {
|
||||||
|
if (!buf.length) return null;
|
||||||
|
let a = buf[0], b = null;
|
||||||
|
for (let i = 0; i < buf.length; i++) { if (buf[i].at <= renderTime) a = buf[i]; else { b = buf[i]; break; } }
|
||||||
|
const span = b ? (b.at - a.at) : 0;
|
||||||
|
const frac = b && span > 0 ? Math.min(1, Math.max(0, (renderTime - a.at) / span)) : (b ? 0 : 1);
|
||||||
|
return { a, b: b || a, frac };
|
||||||
|
}
|
||||||
|
// blend two robot snapshots: positions/angles interpolate, discrete fields come from the reached snapshot (da)
|
||||||
|
function lerpRobot(da, db, k) {
|
||||||
|
const r = {};
|
||||||
|
for (const f of (RC.Proto ? RC.Proto.RF : Object.keys(da))) if (da[f] !== undefined && !EASE.includes(f) && !ANG.includes(f)) r[f] = da[f];
|
||||||
|
for (const f of EASE) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + (db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
|
||||||
|
for (const f of ANG) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + wrap(db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
|
||||||
|
r.lost = Object.assign({}, da.lost); r.lostW = (da.lostW || []).slice(); r.W = (da.W || []).map(w => Object.assign({}, w));
|
||||||
|
return r;
|
||||||
|
}
|
||||||
RC.NetFight = (opt) => {
|
RC.NetFight = (opt) => {
|
||||||
const net = opt.net, db = net.db, id = opt.id, host = opt.host;
|
const sock = opt.net.socket, seat = opt.seat;
|
||||||
const base = `matches/${id}`;
|
const DELAY = opt.interp > 0 ? opt.interp : INTERP_DEFAULT;
|
||||||
let pubT = 0, seq = 0, sendT = 0, beatT = 0, lastInSeq = -1, evBuf = [];
|
const lag = opt.lag && opt.lag.base >= 0 ? opt.lag : null, rng = lag ? mul(lag.seed || 1) : null;
|
||||||
let sending = false, slow = 0; // one write at a time; back off while the line is slow
|
const stats = opt.stats || null;
|
||||||
let remoteInput = { throttle: 0, turn: 0, fire: false, fire2: false, fire3: false };
|
const buf = []; // in-order snapshot buffer
|
||||||
let started = false, lastPeer = Date.now(), peerAlive = true, ai = null, subIn = null, subState = null, subPing = null, lastState = null, stateApplied = -1;
|
let newest = null, lastTick = -1, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
|
||||||
|
|
||||||
function start() {
|
function accept(m) { // a snapshot arrived (possibly delayed by the dev lag injector)
|
||||||
if (host) {
|
const snap = RC.Proto.toLocal(seat, m);
|
||||||
// host reads the guest's input stream
|
lastSnap = Date.now(); newest = snap;
|
||||||
subIn = db.stream(`${base}/in`, v => { if (v && typeof v.seq === 'number') { remoteInput = v; lastPeer = Date.now(); } });
|
if (stats) stats.snap(snap, m._bytes, performance.now());
|
||||||
} else {
|
if (m.tick <= lastTick) return; // out of order (rare) -> drop, keep the buffer monotonic
|
||||||
// guest reads the host's state stream
|
lastTick = m.tick;
|
||||||
subState = db.stream(`${base}/state`, v => { if (v && typeof v.seq === 'number') { lastState = v; lastPeer = Date.now(); } });
|
buf.push({ at: Date.now(), tick: m.tick, snap });
|
||||||
subPing = db.stream(`${base}/ping`, v => { if (v) lastPeer = Date.now(); }); // host alive during the countdown
|
while (buf.length > BUF_MAX) buf.shift();
|
||||||
}
|
}
|
||||||
|
const off = sock.on('snap', m => {
|
||||||
|
if (!lag) return accept(m);
|
||||||
|
setTimeout(() => accept(m), Math.max(0, lag.base + (rng() * 2 - 1) * lag.jit));
|
||||||
|
});
|
||||||
|
|
||||||
|
const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3;
|
||||||
|
function sendInput(inp, dt) {
|
||||||
|
sendT -= dt; keepT -= dt;
|
||||||
|
if (sendT > 0 || (!changed(inp) && keepT > 0)) return;
|
||||||
|
const i = RC.Proto.input(inp);
|
||||||
|
if (sock.send(Object.assign({ t: 'input', seq: ++seq }, i))) { prev = i; sendT = SEND_MIN; keepT = SEND_KEEP; if (stats) stats.inputSent(seq, performance.now()); }
|
||||||
}
|
}
|
||||||
|
|
||||||
function checkPeer() {
|
const applyRobot = (r, d) => { Object.assign(r, d); };
|
||||||
if (!started) { started = true; lastPeer = Math.max(lastPeer, Date.now()); } // countdown is over: start the clock
|
const syncList = (dst, src, def) => { dst.length = src.length; for (let i = 0; i < src.length; i++) dst[i] = Object.assign(dst[i] || Object.assign({}, def), src[i]); };
|
||||||
if (!peerAlive && Date.now() - lastPeer < GRACE) { peerAlive = true; if (opt.onPeerBack) opt.onPeerBack(host); }
|
|
||||||
if (peerAlive && Date.now() - lastPeer > GRACE) {
|
|
||||||
peerAlive = false;
|
|
||||||
if (host && !ai) ai = RC.AI.create({ style: opt.oppStyle || 'brawler', skill: opt.oppSkill != null ? opt.oppSkill : 0.5, seed: 7 });
|
|
||||||
if (opt.onPeerLost) opt.onPeerLost(host);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// HOST: step with [local, guest-or-AI], publish robots as [host, guest] but return a state where
|
function frame(s, inp, dt) {
|
||||||
// index 0 is the LOCAL player (so game.js renders identically on both sides).
|
sendInput(inp, dt);
|
||||||
function hostStep(s, localInput, dt) {
|
if (!buf.length) return [];
|
||||||
checkPeer();
|
const renderTime = Date.now() - DELAY;
|
||||||
const guestInput = peerAlive ? remoteInput : ai.think(s, s.robots[1], s.robots[0], dt);
|
const fr = pickFrames(buf, renderTime), na = fr.a.snap, nb = fr.b.snap, k = fr.frac;
|
||||||
RC.Combat.step(s, dt, [localInput, guestInput]);
|
s.t = na.time; s.left = na.left; s.pitOpen = na.pitOpen; s.pitAlarm = na.pitAlarm; s.endIn = na.endIn;
|
||||||
if (s.events.length) evBuf.push.apply(evBuf, s.events); // batch events between publishes for the guest
|
s.press.st = na.press.st; s.press.y = na.press.y;
|
||||||
pubT -= dt;
|
Object.assign(s.crane, na.crane);
|
||||||
// publish only when the previous write came back - otherwise slow uploads queue up and the host stutters
|
syncList(s.rockets, na.rockets, { sp: 6, t: 3 });
|
||||||
if (pubT <= 0 && !sending) {
|
syncList(s.mines, na.mines, { r: 0.85 });
|
||||||
pubT = PUB + slow;
|
applyRobot(s.robots[0], lerpRobot(na.robots[0], nb.robots[0], k));
|
||||||
sending = true;
|
applyRobot(s.robots[1], lerpRobot(na.robots[1], nb.robots[1], k));
|
||||||
const t0 = Date.now();
|
if (na.result) s.result = na.result;
|
||||||
const payload = {
|
while (buf.length > 2 && buf[1].at <= renderTime) buf.shift(); // keep one snapshot older than renderTime
|
||||||
seq: ++seq, t: rnd(s.t), left: rnd(s.left), pitOpen: rnd(s.pitOpen), pitAlarm: s.pitAlarm,
|
if (fr.a.tick === seenTick) return [];
|
||||||
press: { st: s.press.st, y: rnd(s.press.y) }, crane: { st: s.crane.st, x: rnd(s.crane.x), z: rnd(s.crane.z), who: s.crane.who },
|
seenTick = fr.a.tick;
|
||||||
rockets: s.rockets.map(k => ({ x: rnd(k.x), z: rnd(k.z), y: rnd(k.y), a: rnd(k.a) })),
|
return na.ev || [];
|
||||||
mines: s.mines.map(k => ({ x: rnd(k.x), z: rnd(k.z), arm: rnd(k.arm) })),
|
|
||||||
r: [packRobot(s.robots[0]), packRobot(s.robots[1])],
|
|
||||||
ev: evBuf.slice(-24), result: s.result, endIn: rnd(s.endIn),
|
|
||||||
};
|
|
||||||
evBuf.length = 0;
|
|
||||||
const done = () => {
|
|
||||||
sending = false;
|
|
||||||
const ms = Date.now() - t0; // slow line: send less often instead of piling up
|
|
||||||
slow = ms > 400 ? 0.2 : ms > 180 ? 0.08 : 0;
|
|
||||||
};
|
|
||||||
try { Promise.resolve(db.put(`${base}/state`, payload)).then(done, done); } catch (e) { done(); }
|
|
||||||
}
|
}
|
||||||
return s.events;
|
|
||||||
}
|
|
||||||
|
|
||||||
// GUEST: no simulation. Ease local robots toward the latest snapshot; snap flags/hp; play its events once.
|
|
||||||
function guestFrame(s, localInput, dt) {
|
|
||||||
checkPeer();
|
|
||||||
// send my input (I am robot 0 locally = guest = snapshot index 1)
|
|
||||||
sendT -= dt;
|
|
||||||
beatT -= dt;
|
|
||||||
// send on change, and at least every 0.5 s as a heartbeat (otherwise the host thinks I am gone)
|
|
||||||
if (sendT <= 0 && !sending && (changed(localInput) || beatT <= 0)) {
|
|
||||||
sendT = PUB; beatT = 0.5; lastInSeq++;
|
|
||||||
sending = true;
|
|
||||||
const fin = () => { sending = false; };
|
|
||||||
try {
|
|
||||||
Promise.resolve(db.put(`${base}/in`, { seq: lastInSeq, throttle: rnd(localInput.throttle || 0), turn: rnd(localInput.turn || 0),
|
|
||||||
fire: !!localInput.fire, fire2: !!localInput.fire2, fire3: !!localInput.fire3 })).then(fin, fin);
|
|
||||||
} catch (e) { fin(); }
|
|
||||||
prevInput = localInput;
|
|
||||||
}
|
|
||||||
const ev = [];
|
|
||||||
if (lastState) {
|
|
||||||
const snap = lastState;
|
|
||||||
s.t = snap.t; s.left = snap.left; s.pitOpen = snap.pitOpen; s.pitAlarm = snap.pitAlarm;
|
|
||||||
s.press.st = snap.press.st; s.press.y = snap.press.y;
|
|
||||||
s.crane.st = snap.crane.st; s.crane.x = snap.crane.x; s.crane.z = snap.crane.z; s.crane.who = snap.crane.who;
|
|
||||||
syncRockets(s, snap.rockets);
|
|
||||||
syncMines(s, snap.mines);
|
|
||||||
s.result = snap.result; s.endIn = snap.endIn;
|
|
||||||
// snapshot order [host, guest]; locally guest must be index 0 -> swap
|
|
||||||
applyRobot(s.robots[0], snap.r[1], dt); // me (guest)
|
|
||||||
applyRobot(s.robots[1], snap.r[0], dt); // host
|
|
||||||
if (snap.seq !== stateApplied) {
|
|
||||||
stateApplied = snap.seq;
|
|
||||||
for (const e of snap.ev || []) { const c = Object.assign({}, e); if (c.who === 0) c.who = 1; else if (c.who === 1) c.who = 0; ev.push(c); }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ev;
|
|
||||||
}
|
|
||||||
|
|
||||||
function applyRobot(r, d, dt) {
|
|
||||||
if (!d) return;
|
|
||||||
const k = Math.min(1, dt * 14); // ease position/angle, snap the rest
|
|
||||||
r.x += (d.x - r.x) * k; r.z += (d.z - r.z) * k; r.y += (d.y - r.y) * k;
|
|
||||||
r.a += wrap(d.a - r.a) * k;
|
|
||||||
r.turretA += wrap(d.turretA - r.turretA) * k;
|
|
||||||
for (const f of ['hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'lost', 'dead', 'out']) if (d[f] !== undefined) r[f] = d[f];
|
|
||||||
}
|
|
||||||
function syncRockets(s, list) {
|
|
||||||
list = list || [];
|
|
||||||
s.rockets.length = list.length;
|
|
||||||
for (let i = 0; i < list.length; i++) s.rockets[i] = Object.assign(s.rockets[i] || { owner: 1, sp: 6, t: 3 }, list[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
function syncMines(s, list) {
|
|
||||||
list = list || [];
|
|
||||||
s.mines.length = list.length;
|
|
||||||
for (let i = 0; i < list.length; i++) s.mines[i] = Object.assign(s.mines[i] || { owner: 0, r: 0.85 }, list[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
let prevInput = null;
|
|
||||||
function changed(inp) { return !prevInput || inp.throttle !== prevInput.throttle || inp.turn !== prevInput.turn || inp.fire !== prevInput.fire || inp.fire2 !== prevInput.fire2 || inp.fire3 !== prevInput.fire3; }
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
start, hostStep, guestFrame,
|
frame,
|
||||||
// during the countdown: keep the line alive (guest sends a neutral input, host an empty state ping)
|
get oppAway() { return !!(newest && newest.away && newest.away[1]); },
|
||||||
idle(dt) {
|
get silentFor() { return (Date.now() - lastSnap) / 1000; },
|
||||||
sendT -= dt;
|
stop() { off(); },
|
||||||
if (sendT > 0) return;
|
|
||||||
sendT = 0.5;
|
|
||||||
if (host) db.patch(`${base}/ping`, { h: Date.now() });
|
|
||||||
else { lastInSeq++; db.put(`${base}/in`, { seq: lastInSeq, throttle: 0, turn: 0, fire: false, fire2: false, fire3: false }); }
|
|
||||||
},
|
|
||||||
get peerAlive() { return peerAlive; },
|
|
||||||
stop() { if (subIn) subIn.close(); if (subState) subState.close(); if (subPing) subPing.close(); },
|
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
RC.NetFight.pickFrames = pickFrames;
|
||||||
|
RC.NetFight.lerpRobot = lerpRobot;
|
||||||
|
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||||
})(typeof window !== 'undefined' ? window : globalThis);
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
|
|||||||
@@ -1,121 +0,0 @@
|
|||||||
/* Robot Clash - live multiplayer tournament over Firebase (needs net.js + ltourney.js).
|
|
||||||
Players register, tick "ready", a 30 s countdown starts once >=2 are ready, then the bracket is
|
|
||||||
frozen and each pairing is played as a normal live PvP match (game.js supplies startMatch).
|
|
||||||
No server: the bracket is computed the same way on every client from the frozen list + seed
|
|
||||||
(RC.LTourney), results are shared through /tourney/results, a missing opponent is a walkover.
|
|
||||||
|
|
||||||
const T = RC.NetTourney(net, { uid, name, flag }, {
|
|
||||||
onView(v){} // v = { phase, players, readyCount, countdown, order, results, me:{match,champion,out} }
|
|
||||||
startMatch(info){} // info = { id, host, seed, opp:{uid,name,build,paint,flag} } -> game starts the fight
|
|
||||||
});
|
|
||||||
T.join(build, paint) / T.leave() / T.setReady(bool) / T.tick(dt) / T.reportWin(round, pair, uid)
|
|
||||||
T.close()
|
|
||||||
|
|
||||||
/tourney in Firebase:
|
|
||||||
reg/<uid> = { name, flag, build, paint, ready, ts } (each writes only their own)
|
|
||||||
meta = { phase:'open'|'countdown'|'running'|'done', startAt, seed, frozen:[uid...] }
|
|
||||||
results/<round>/<pair> = winnerUid */
|
|
||||||
(function (root) {
|
|
||||||
'use strict';
|
|
||||||
const RC = (root.RC = root.RC || {});
|
|
||||||
const COUNTDOWN = 30000, WALKOVER = 60000, STALE = 15000;
|
|
||||||
|
|
||||||
RC.NetTourney = function (net, me, opt) {
|
|
||||||
const db = net.db, cb = opt || {};
|
|
||||||
let reg = {}, meta = {}, results = {};
|
|
||||||
let inMatch = false, roundStart = 0, lastRound = -1, wroteRun = false, wroteCount = false;
|
|
||||||
const subs = [];
|
|
||||||
|
|
||||||
subs.push(db.stream('tourney/reg', v => { reg = v || {}; emit(); }));
|
|
||||||
subs.push(db.stream('tourney/meta', v => { meta = v || {}; emit(); }));
|
|
||||||
subs.push(db.stream('tourney/results', v => { results = v || {}; emit(); }));
|
|
||||||
|
|
||||||
const now = () => Date.now();
|
|
||||||
const readyUids = () => Object.keys(reg).filter(u => reg[u] && reg[u].ready && now() - (reg[u].ts || 0) < STALE * 3);
|
|
||||||
const frozen = () => (meta.frozen && meta.frozen.length ? meta.frozen : null);
|
|
||||||
|
|
||||||
function view() {
|
|
||||||
const phase = meta.phase || 'open';
|
|
||||||
const players = Object.keys(reg).map(u => ({ uid: u, name: reg[u].name, flag: reg[u].flag, ready: !!reg[u].ready, me: u === me.uid }));
|
|
||||||
const v = { phase, players, readyCount: readyUids().length, countdown: null, order: null, results: results, me: {} };
|
|
||||||
if (phase === 'countdown' && meta.startAt) v.countdown = Math.max(0, Math.ceil((meta.startAt - now()) / 1000));
|
|
||||||
const fr = frozen();
|
|
||||||
if (fr && (phase === 'running' || phase === 'done')) {
|
|
||||||
const ord = RC.LTourney.order(fr, meta.seed || 1);
|
|
||||||
v.order = ord;
|
|
||||||
const m = RC.LTourney.myMatch(ord, results, me.uid);
|
|
||||||
if (!m) v.me.out = true;
|
|
||||||
else if (m.done) v.me.champion = m.champion;
|
|
||||||
else v.me.match = m;
|
|
||||||
}
|
|
||||||
return v;
|
|
||||||
}
|
|
||||||
function emit() { if (cb.onView) cb.onView(view()); drive(); }
|
|
||||||
|
|
||||||
// my own registration row (heartbeat keeps it fresh)
|
|
||||||
let myRow = null;
|
|
||||||
function writeRow() {
|
|
||||||
if (!myRow) return;
|
|
||||||
db.put('tourney/reg/' + me.uid, Object.assign({ ts: now() }, myRow));
|
|
||||||
}
|
|
||||||
function join(build, paint) {
|
|
||||||
myRow = { name: me.name, flag: me.flag || 'XX', ready: false, build: build, paint: paint };
|
|
||||||
writeRow();
|
|
||||||
}
|
|
||||||
function leave() { myRow = null; db.del('tourney/reg/' + me.uid); }
|
|
||||||
function setReady(on) { if (myRow) { myRow.ready = !!on; writeRow(); } }
|
|
||||||
|
|
||||||
// state machine - every client runs it, writes are guarded so the first one wins
|
|
||||||
function drive() {
|
|
||||||
const phase = meta.phase || 'open';
|
|
||||||
if (phase === 'open' && readyUids().length >= 2 && !wroteCount) {
|
|
||||||
wroteCount = true;
|
|
||||||
db.patch('tourney/meta', { phase: 'countdown', startAt: now() + COUNTDOWN, seed: (Math.random() * 1e9) | 0 });
|
|
||||||
}
|
|
||||||
if (phase === 'countdown') {
|
|
||||||
wroteCount = true;
|
|
||||||
if (meta.startAt && now() >= meta.startAt && !wroteRun) {
|
|
||||||
wroteRun = true;
|
|
||||||
db.patch('tourney/meta', { phase: 'running', frozen: readyUids().sort() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (phase === 'running') {
|
|
||||||
const fr = frozen(); if (!fr) return;
|
|
||||||
const ord = RC.LTourney.order(fr, meta.seed || 1);
|
|
||||||
const m = RC.LTourney.myMatch(ord, results, me.uid);
|
|
||||||
if (!m || m.done) { if (m && m.done && !meta.doneWrote) db.patch('tourney/meta', { phase: 'done' }); return; }
|
|
||||||
if (m.round !== lastRound) { lastRound = m.round; roundStart = now(); }
|
|
||||||
if (m.opp == null) return; // bye: bracket advances by itself
|
|
||||||
if (inMatch) return;
|
|
||||||
// opponent gone / never there -> walkover after the timer
|
|
||||||
const oppReg = reg[m.opp];
|
|
||||||
const oppGone = !oppReg || now() - (oppReg.ts || 0) > STALE;
|
|
||||||
if (oppGone && now() - roundStart > WALKOVER) { reportWin(m.round, m.pairIndex, me.uid); return; }
|
|
||||||
// both present -> the host kicks the match off once (guest joins the same match id)
|
|
||||||
if (!oppReg) return;
|
|
||||||
inMatch = true;
|
|
||||||
const id = [me.uid, m.opp].sort().join('_');
|
|
||||||
if (cb.startMatch) cb.startMatch({ id: id, host: m.host, seed: (meta.seed || 1) + m.round * 7,
|
|
||||||
round: m.round, pairIndex: m.pairIndex, oppUid: m.opp,
|
|
||||||
opp: { uid: m.opp, name: oppReg.name, build: oppReg.build, paint: oppReg.paint, flag: oppReg.flag } });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function reportWin(round, pair, uid) {
|
|
||||||
inMatch = false;
|
|
||||||
db.patch('tourney/results/' + round, { [pair]: uid });
|
|
||||||
}
|
|
||||||
function matchDone() { inMatch = false; }
|
|
||||||
|
|
||||||
return {
|
|
||||||
join, leave, setReady, reportWin, matchDone,
|
|
||||||
tick() { /* heartbeat + state progress */ writeRow(); drive(); },
|
|
||||||
view,
|
|
||||||
// host-only admin reset (clears everything for a fresh tournament)
|
|
||||||
reset() { db.del('tourney'); },
|
|
||||||
close() { subs.forEach(s => s && s.close()); },
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
|
||||||
})(typeof window !== 'undefined' ? window : globalThis);
|
|
||||||
73
game/netoverlay.js
Normal file
73
game/netoverlay.js
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
/* Robot Clash - network overlay (F3 or ?net): ping graph of the last 10 s and a plain-language reading of
|
||||||
|
where lag comes from (your line, the opponent's line, the server). Measurements: netstats.js.
|
||||||
|
|
||||||
|
const ov = RC.NetOverlay({ stats, net, t, mount }) mount = #stage; pings the server once a second
|
||||||
|
ov.toggle() / ov.visible */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
const SECS = 10, MAX_MS = 300, W = 300, H = 84;
|
||||||
|
const COL = { ping: '#ff7a1a', opp: '#4aa8ff', gap: '#6dff9e', input: '#e8ebf2' };
|
||||||
|
const LEVEL = { ok: '#6dff9e', warn: '#ffc940', bad: '#ff5a4a' };
|
||||||
|
|
||||||
|
RC.NetOverlay = function (opt) {
|
||||||
|
const { stats, net, t } = opt;
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.id = 'netov';
|
||||||
|
el.className = 'hide';
|
||||||
|
el.innerHTML = `<div class="nvh"></div><canvas width="${W}" height="${H}"></canvas><div class="nvleg"></div><div class="nvrows"></div><div class="nvv"></div>`;
|
||||||
|
opt.mount.appendChild(el);
|
||||||
|
const cv = el.querySelector('canvas'), cx = cv.getContext('2d');
|
||||||
|
let visible = false, drawT = null;
|
||||||
|
|
||||||
|
// my ping: one tiny message per second while connected (also when hidden, so the history is there)
|
||||||
|
setInterval(() => { if (net.enabled && net.socket.connected) net.socket.send({ t: 'ping', t0: performance.now() }); }, 1000);
|
||||||
|
net.socket.on('pong', m => { if (typeof m.t0 === 'number') { const now = performance.now(); stats.pong(now - m.t0, now); } });
|
||||||
|
|
||||||
|
function graph(now) {
|
||||||
|
cx.clearRect(0, 0, W, H);
|
||||||
|
cx.fillStyle = 'rgba(0,0,0,.35)'; cx.fillRect(0, 0, W, H);
|
||||||
|
cx.strokeStyle = 'rgba(255,255,255,.12)'; cx.lineWidth = 1;
|
||||||
|
for (const ms of [50, 100, 200]) { const y = H - ms / MAX_MS * H; cx.beginPath(); cx.moveTo(0, y); cx.lineTo(W, y); cx.stroke(); }
|
||||||
|
cx.fillStyle = 'rgba(255,255,255,.35)'; cx.font = '9px monospace';
|
||||||
|
for (const ms of [50, 100, 200]) cx.fillText(ms + 'ms', 2, H - ms / MAX_MS * H - 2);
|
||||||
|
const pts = stats.series(now, SECS);
|
||||||
|
for (const k of ['gap', 'input', 'opp', 'ping']) {
|
||||||
|
cx.strokeStyle = COL[k]; cx.lineWidth = k === 'ping' ? 2 : 1.2; cx.beginPath();
|
||||||
|
let first = true;
|
||||||
|
for (const p of pts) {
|
||||||
|
if (p[k] === undefined) continue;
|
||||||
|
const x = W - (now - p.t) / (SECS * 1000) * W, y = H - Math.min(MAX_MS, p[k]) / MAX_MS * H;
|
||||||
|
if (first) { cx.moveTo(x, y); first = false; } else cx.lineTo(x, y);
|
||||||
|
}
|
||||||
|
cx.stroke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw() {
|
||||||
|
const now = performance.now(), s = stats.summary(now);
|
||||||
|
el.querySelector('.nvh').textContent = t('net_title');
|
||||||
|
el.querySelector('.nvleg').innerHTML = ['ping', 'opp', 'gap', 'input'].map(k => `<span><i style="background:${COL[k]}"></i>${t('net_l_' + k)}</span>`).join('');
|
||||||
|
const row = (label, val) => `<span>${label}</span><b>${val}</b>`;
|
||||||
|
el.querySelector('.nvrows').innerHTML =
|
||||||
|
row(t('net_ping'), s.ping ? `${s.ping} ms <small>(max ${s.pingMax})</small>` : '–')
|
||||||
|
+ (s.fight ? row(t('net_ping_srv'), `${s.serverPing} ms`)
|
||||||
|
+ row(t('net_ping_opp'), `${s.oppPing} ms`)
|
||||||
|
+ row(t('net_snaps'), `${s.gap} ms ±${s.jitter}${s.late ? ` · ${s.late} ${t('net_late')}` : ''}`)
|
||||||
|
+ row(t('net_input'), s.input ? `${s.input} ms` : '–')
|
||||||
|
+ row(t('net_server'), `${s.tickMs} ms · ${s.kbps} kbit/s`) : '');
|
||||||
|
el.querySelector('.nvv').innerHTML = RC.NetStats.verdict(s)
|
||||||
|
.map(v => `<div style="color:${LEVEL[v.level]}">${v.level === 'ok' ? '✔' : v.level === 'warn' ? '⚠' : '✖'} ${t(v.key, { n: v.n })}</div>`).join('');
|
||||||
|
graph(now);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggle(on) {
|
||||||
|
visible = on === undefined ? !visible : !!on;
|
||||||
|
el.classList.toggle('hide', !visible);
|
||||||
|
clearInterval(drawT);
|
||||||
|
if (visible) { draw(); drawT = setInterval(draw, 250); }
|
||||||
|
}
|
||||||
|
addEventListener('keydown', e => { if (e.key === 'F3') { e.preventDefault(); e.stopPropagation(); toggle(); } }, true);
|
||||||
|
return { toggle, get visible() { return visible; } };
|
||||||
|
};
|
||||||
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
78
game/netstats.js
Normal file
78
game/netstats.js
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
/* Robot Clash - network measurements for the F3 overlay. No DOM (Node-testable).
|
||||||
|
|
||||||
|
const st = RC.NetStats()
|
||||||
|
st.pong(rttMs, now) my ping, measured by the client (ping/pong over the WebSocket)
|
||||||
|
st.snap(localSnap, bytes, now) a snapshot arrived (already RC.Proto.toLocal'ed: rtt = [me, opponent])
|
||||||
|
st.inputSent(seq, now) input seq left the client
|
||||||
|
st.summary(now) -> { ping, pingMax, serverPing, oppPing, gap, jitter, late, input, tickMs, kbps, snapAge, fight }
|
||||||
|
st.series(now, seconds) -> samples for the graph [{ t, ping, opp, gap, input }]
|
||||||
|
RC.NetStats.verdict(summary) -> [{ key, level: 'ok'|'warn'|'bad', n }] (lang keys nv_*)
|
||||||
|
|
||||||
|
How to read it: ping = you <-> server. oppPing = the opponent <-> server (the server measures it).
|
||||||
|
gap/jitter = how evenly the 20 snapshots/s reach YOU (unsteady = your line). input = key press until the
|
||||||
|
server confirms it (~ping + up to one server step; much more = queueing somewhere). tickMs = server load. */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
const KEEP = 20000; // ms of history
|
||||||
|
|
||||||
|
RC.NetStats = function () {
|
||||||
|
const pings = [], snaps = [], inputs = new Map(), delays = [];
|
||||||
|
let lastSnapAt = 0;
|
||||||
|
const trim = (arr, now) => { while (arr.length && now - arr[0].t > KEEP) arr.shift(); };
|
||||||
|
const avg = a => (a.length ? a.reduce((s, x) => s + x, 0) / a.length : 0);
|
||||||
|
const recent = (arr, now, ms) => arr.filter(x => now - x.t <= ms);
|
||||||
|
|
||||||
|
return {
|
||||||
|
pong(rtt, now) { pings.push({ t: now, v: rtt }); trim(pings, now); },
|
||||||
|
inputSent(seq, now) { inputs.set(seq, now); if (inputs.size > 400) inputs.delete(inputs.keys().next().value); },
|
||||||
|
snap(s, bytes, now) {
|
||||||
|
const gap = lastSnapAt ? now - lastSnapAt : 0;
|
||||||
|
lastSnapAt = now;
|
||||||
|
snaps.push({ t: now, gap, bytes: bytes || 0, opp: s.rtt ? s.rtt[1] : 0, srv: s.rtt ? s.rtt[0] : 0, tickMs: s.tickMs || 0 });
|
||||||
|
trim(snaps, now);
|
||||||
|
// server confirmed every input up to s.ack: the oldest unconfirmed send time gives the delay
|
||||||
|
if (s.ack) for (const [seq, at] of inputs) { if (seq > s.ack) break; if (seq === s.ack) delays.push({ t: now, v: now - at }); inputs.delete(seq); }
|
||||||
|
trim(delays, now);
|
||||||
|
},
|
||||||
|
summary(now) {
|
||||||
|
const p = recent(pings, now, 5000).map(x => x.v), sn = recent(snaps, now, 5000), d = recent(delays, now, 5000).map(x => x.v);
|
||||||
|
const gaps = sn.map(x => x.gap).filter(g => g > 0), g = avg(gaps);
|
||||||
|
const jitter = gaps.length ? Math.sqrt(avg(gaps.map(x => (x - g) ** 2))) : 0;
|
||||||
|
const last = sn[sn.length - 1];
|
||||||
|
return {
|
||||||
|
ping: Math.round(avg(p)), pingMax: Math.round(p.length ? Math.max(...p) : 0),
|
||||||
|
serverPing: last ? last.srv : 0, oppPing: last ? last.opp : 0,
|
||||||
|
gap: Math.round(g), jitter: Math.round(jitter), late: gaps.filter(x => x > 110).length,
|
||||||
|
input: Math.round(avg(d)), tickMs: last ? last.tickMs : 0,
|
||||||
|
kbps: Math.round(sn.reduce((s, x) => s + x.bytes, 0) * 8 / 5 / 1000),
|
||||||
|
snapAge: lastSnapAt ? now - lastSnapAt : Infinity, fight: !!(lastSnapAt && now - lastSnapAt < 3000),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
series(now, seconds = 10) {
|
||||||
|
const from = now - seconds * 1000, out = [];
|
||||||
|
for (const x of snaps) if (x.t >= from) out.push({ t: x.t, gap: x.gap, opp: x.opp });
|
||||||
|
for (const x of pings) if (x.t >= from) out.push({ t: x.t, ping: x.v });
|
||||||
|
for (const x of delays) if (x.t >= from) out.push({ t: x.t, input: x.v });
|
||||||
|
return out.sort((a, b) => a.t - b.t);
|
||||||
|
},
|
||||||
|
reset() { snaps.length = 0; delays.length = 0; inputs.clear(); lastSnapAt = 0; },
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// plain-language reading of a summary; thresholds tuned for a 20 Hz action game
|
||||||
|
RC.NetStats.verdict = function (s) {
|
||||||
|
const out = [];
|
||||||
|
if (s.ping > 150) out.push({ key: 'nv_me_slow', level: s.ping > 250 ? 'bad' : 'warn', n: s.ping });
|
||||||
|
if (s.fight) {
|
||||||
|
if (s.jitter > 30 || s.late > 3) out.push({ key: 'nv_me_jitter', level: s.jitter > 60 || s.late > 10 ? 'bad' : 'warn', n: s.jitter });
|
||||||
|
if (s.oppPing > 150) out.push({ key: 'nv_opp_slow', level: s.oppPing > 250 ? 'bad' : 'warn', n: s.oppPing });
|
||||||
|
if (s.tickMs > 4) out.push({ key: 'nv_server', level: s.tickMs > 10 ? 'bad' : 'warn', n: s.tickMs });
|
||||||
|
if (s.input > s.ping + 150 && s.input > 200) out.push({ key: 'nv_queue', level: 'warn', n: s.input });
|
||||||
|
} else if (s.snapAge !== Infinity && s.snapAge > 3000 && s.snapAge < 30000) out.push({ key: 'nv_lost', level: 'bad', n: Math.round(s.snapAge / 1000) });
|
||||||
|
if (!out.length) out.push({ key: s.fight ? 'nv_ok' : 'nv_nofight', level: 'ok', n: 0 });
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||||
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
257
game/online.js
Normal file
257
game/online.js
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
/* Robot Clash - online play in the browser: server-checked workshop actions (act), online save sync, login card, lobby, live fight start/end.
|
||||||
|
Part of game.js (split for size): created once by game.js with the shared context G.
|
||||||
|
Live state (save, mode, F, ...) is read as G.<name>; services/helpers are taken from G at creation. */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
RC.GameOnline = function (G) {
|
||||||
|
const {
|
||||||
|
$, FLAGS, SFX, accounts, achHtml, card, ensureFlag, enterAccount, esc, fbAcc, flagHtml, hideOverlay, hud,
|
||||||
|
img, layer, loadSave, lobby, net, openGarage, overlay, paintObj, persist, playerName, prepOpp,
|
||||||
|
refreshDev, renderWeaponEditor, repairSave, setMode, setScreen, shop, showLegal, showTitle, startFight,
|
||||||
|
t
|
||||||
|
} = G;
|
||||||
|
|
||||||
|
// ---- online save: the server is the authority for money, fame, parts and robots -------------------
|
||||||
|
// act(): every workshop change goes through RC.Eco (game/eco.js). Applied locally at once; online the same
|
||||||
|
// action is sent to the server (one at a time, in order) and the server's answer replaces our economy fields.
|
||||||
|
let actQueue = Promise.resolve();
|
||||||
|
function act(a) {
|
||||||
|
const r = RC.Eco.apply(G.save, a);
|
||||||
|
if (!r.ok) return r;
|
||||||
|
if (G.gameMode === 'online' && net.enabled && net.uid) {
|
||||||
|
actQueue = actQueue.then(() => net.api('POST', '/api/online/action', a)).then(res => {
|
||||||
|
if (!res || !res.save) return;
|
||||||
|
if (!res.ok || econDiffers(res.save)) { adoptEconomy(res.save); afterEconomy(); }
|
||||||
|
}, () => {});
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
const econKey = s => JSON.stringify([s.money, s.fame, s.owned, s.active, (s.robots || []).map(r => r.build)]);
|
||||||
|
const econDiffers = srv => econKey(srv) !== econKey(G.save);
|
||||||
|
// keepLooks: robot names/paint are client-owned - keep ours (they may not be uploaded yet)
|
||||||
|
function adoptEconomy(srv, keepLooks = true) {
|
||||||
|
const looks = keepLooks && G.save.robots ? G.save.robots.map(r => ({ name: r.name, paint: r.paint })) : [];
|
||||||
|
for (const k of RC.Eco.ECONOMY) if (srv[k] !== undefined) G.save[k] = srv[k];
|
||||||
|
if (keepLooks && looks.length === G.save.robots.length) G.save.robots.forEach((r, i) => { r.name = looks[i].name; r.paint = looks[i].paint; });
|
||||||
|
RC.Eco.mirror(G.save);
|
||||||
|
G.slot.save(G.save);
|
||||||
|
}
|
||||||
|
function afterEconomy() {
|
||||||
|
hud();
|
||||||
|
if (G.mode === 'garage') { shop.render(); G.view.showGarage(G.save.build, paintObj()); if (G.editorOpen) renderWeaponEditor(); }
|
||||||
|
}
|
||||||
|
// cosmetics (names, paint, flag, ...) are client-owned: debounced upload, the server keeps only those fields
|
||||||
|
let pushTimer = null;
|
||||||
|
const cosmetics = () => {
|
||||||
|
const c = {};
|
||||||
|
for (const k of RC.Eco.COSMETIC) if (G.save[k] !== undefined) c[k] = G.save[k];
|
||||||
|
c.robots = G.save.robots.map(r => ({ name: r.name, paint: r.paint }));
|
||||||
|
return c;
|
||||||
|
};
|
||||||
|
function onlinePush() { clearTimeout(pushTimer); pushTimer = setTimeout(onlineFlush, 1500); }
|
||||||
|
function onlineFlush() {
|
||||||
|
clearTimeout(pushTimer);
|
||||||
|
if (G.gameMode === 'online' && G.save && net.uid) net.api('PUT', '/api/online/save', cosmetics());
|
||||||
|
}
|
||||||
|
// after login / page load: economy from the server; cosmetics from whichever copy is newer
|
||||||
|
function onlinePull() {
|
||||||
|
if (G.gameMode !== 'online' || !net.uid) return;
|
||||||
|
const uid = net.uid;
|
||||||
|
net.api('GET', '/api/online').then(srv => {
|
||||||
|
if (!srv || !G.save || G.gameMode !== 'online' || net.uid !== uid) return;
|
||||||
|
const serverNewer = (+srv.ts || 0) > (+G.save.ts || 0);
|
||||||
|
if (serverNewer) { for (const k of RC.Eco.COSMETIC) if (srv[k] !== undefined) G.save[k] = srv[k]; }
|
||||||
|
adoptEconomy(srv, !serverNewer);
|
||||||
|
repairSave();
|
||||||
|
RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); });
|
||||||
|
if (!serverNewer) onlinePush();
|
||||||
|
afterEconomy();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- online lobby
|
||||||
|
// The server owns presence, challenges and fights (server/lobby.js). This draws its state and forwards clicks.
|
||||||
|
|
||||||
|
const myRoom = () => G.joinedRoom || (FLAGS.includes(G.save.flag) ? G.save.flag : 'XX');
|
||||||
|
const pendingOut = () => (lobby ? lobby.pending : null);
|
||||||
|
function wireLobby() {
|
||||||
|
lobby.onList(rows => { G.lobbyRows = rows; if (G.mode === 'lobby') renderLobby(); });
|
||||||
|
lobby.onIncoming(c => { if (G.mode === 'lobby' || G.mode === 'garage') showIncoming(c); });
|
||||||
|
lobby.onMatch(m => startOnlineFight(m));
|
||||||
|
lobby.onEnd(m => onlineFightEnded(m));
|
||||||
|
lobby.onCancel(c => {
|
||||||
|
if (G.mode === 'lobby') { renderLobby(); if (c.outgoing) SFX.deny(); }
|
||||||
|
else if (!c.outgoing && $('cYes')) hideOverlay(); // the challenger gave up while I was asked
|
||||||
|
});
|
||||||
|
lobby.onError(code => {
|
||||||
|
SFX.deny();
|
||||||
|
if (G.mode === 'lobby') { renderLobby(); const el = $('lMsg'); if (el) el.textContent = errText(code); }
|
||||||
|
else if (G.mode === 'garage') $('mechTip').textContent = errText(code);
|
||||||
|
});
|
||||||
|
net.socket.on('outdated', () => {
|
||||||
|
card(`<h2>${t('reload_title')}</h2><p>${t('e_OUTDATED')}</p><div class="row"><button class="primary" id="rNow">${t('reload_now')}</button></div>`, { bg: 'bg_title.jpg' });
|
||||||
|
$('rNow').onclick = () => location.reload();
|
||||||
|
});
|
||||||
|
net.socket.on('replaced', () => { if (G.mode === 'lobby') { const el = $('lMsg'); if (el) el.textContent = t('e_REPLACED'); } });
|
||||||
|
}
|
||||||
|
async function startOnline(dest) { // dest 'lobby' -> player list, else the workshop (main page)
|
||||||
|
if (!net.enabled) return;
|
||||||
|
if (G.gameMode !== 'online') { setMode('online'); if (G.save) { loadSave(); hud(); } } // online uses its own save
|
||||||
|
if (!net.auth.current) {
|
||||||
|
if (G.save && !fbAcc()) return joinAnon(); // playing as guest -> straight in, anonymously
|
||||||
|
showOnlineLogin(false, null, 'online'); return;
|
||||||
|
}
|
||||||
|
if (!G.save || !G.slot) { if (!fbAcc()) accounts.guest(); loadSave(); }
|
||||||
|
if (!G.onlineReady) { wireLobby(); G.onlineReady = true; }
|
||||||
|
lobby.enter();
|
||||||
|
ensureFlag(() => { if (dest === 'lobby') showLobby(); else openGarage(); }); // country first, then main page / lobby
|
||||||
|
}
|
||||||
|
async function joinAnon() {
|
||||||
|
if (!G.save) { accounts.guest(); loadSave(); }
|
||||||
|
const r = await net.auth.guest(playerName() || t('guest'));
|
||||||
|
if (!r.ok) { SFX.deny(); showOnlineLogin(false, r.error, 'online'); return; }
|
||||||
|
hud(); refreshDev(); loadSave(); startOnline();
|
||||||
|
}
|
||||||
|
const errText = c => (window.LANG.en['e_' + c] ? t('e_' + c) : t('e_ERROR') + ' (' + esc(c) + ')');
|
||||||
|
function showOnlineLogin(reg, errKey, next) {
|
||||||
|
next = next || 'career';
|
||||||
|
setScreen('account');
|
||||||
|
const f = reg
|
||||||
|
? `<label>${t('f_name')}</label><input type="text" id="oName" maxlength="18" autocomplete="username">
|
||||||
|
<label>${t('f_email_opt')}</label><input type="email" id="oMail" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" inputmode="email">`
|
||||||
|
: `<label>${t('f_login')}</label><input type="text" id="oLogin" autocomplete="username" autocapitalize="off" autocorrect="off" spellcheck="false">`;
|
||||||
|
card(`<h2>${reg ? t('register') : t('login')}</h2><p>${t('online_login_text')}</p>
|
||||||
|
<div class="form">${f}
|
||||||
|
<label>${t('f_pass')}</label><input type="password" id="oPass" autocomplete="${reg ? 'new-password' : 'current-password'}"></div>
|
||||||
|
${reg ? `<label class="chk"><input type="checkbox" id="oConsent"> ${t('consent_pre')} <button type="button" class="link" id="oPriv">${t('legal_privacy')}</button></label>` : ''}
|
||||||
|
<div class="err" id="oErr">${errKey ? errText(errKey) : ''}</div>
|
||||||
|
<div class="row"><button id="oBack">${t('back')}</button><button class="primary" id="oGo">${reg ? t('register_go') : t('login')}</button></div>
|
||||||
|
<p class="muted">${reg ? '' : t('no_account') + ' '}<button class="link" id="oToggle">${reg ? t('login') : t('register')}</button></p>
|
||||||
|
${next === 'online' ? `<div class="row"><button id="oAnon">👤 ${t('online_guest')}</button></div>` : ''}`, { bg: 'bg_title.jpg' });
|
||||||
|
if ($('oAnon')) $('oAnon').onclick = () => { SFX.click(); joinAnon(); };
|
||||||
|
if ($('oPriv')) $('oPriv').onclick = () => { SFX.click(); showLegal(() => showOnlineLogin(true, null, next), 'privacy'); };
|
||||||
|
$('oBack').onclick = () => { SFX.click(); showTitle(); };
|
||||||
|
$('oToggle').onclick = () => { SFX.click(); showOnlineLogin(!reg, null, next); };
|
||||||
|
$('oGo').onclick = async () => {
|
||||||
|
if (reg && $('oConsent') && !$('oConsent').checked) { SFX.deny(); $('oErr').textContent = t('consent_required'); return; }
|
||||||
|
$('oGo').disabled = true;
|
||||||
|
const r = reg ? await net.auth.register($('oName').value, $('oPass').value, $('oMail').value)
|
||||||
|
: await net.auth.login($('oLogin').value, $('oPass').value);
|
||||||
|
if (!r.ok) { SFX.deny(); showOnlineLogin(reg, r.error, next); return; }
|
||||||
|
SFX.click(); hud(); refreshDev();
|
||||||
|
if (next === 'online') { loadSave(); startOnline(); } else enterAccount(reg);
|
||||||
|
};
|
||||||
|
overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Enter') $('oGo').click(); }));
|
||||||
|
setTimeout(() => { const el = $(reg ? 'oName' : 'oLogin'); if (el) el.focus(); }, 50);
|
||||||
|
}
|
||||||
|
function showLobby() {
|
||||||
|
if (!G.lobbyRoom) G.lobbyRoom = 'all'; // filter: 'all' or a country code
|
||||||
|
setScreen('lobby'); renderLobby();
|
||||||
|
}
|
||||||
|
// two-pane lobby: country rooms on the left, players of the chosen room on the right (own style, not copied art)
|
||||||
|
function renderLobby() {
|
||||||
|
const code = r => { const c = r.room || r.flag; return FLAGS.includes(c) ? c : 'XX'; }; // group by the room a player JOINED, not their flag
|
||||||
|
const all = G.lobbyRows;
|
||||||
|
const myFlag = FLAGS.includes(G.save.flag) ? G.save.flag : 'XX', mine = myRoom();
|
||||||
|
// I am in the lobby too: count myself in the room I joined (and in "all"), and only list me there
|
||||||
|
const total = all.length + 1;
|
||||||
|
const cnt = f => all.filter(r => code(r) === f).length + (f === mine ? 1 : 0);
|
||||||
|
const here = G.lobbyRoom === 'all' ? all : all.filter(r => code(r) === G.lobbyRoom);
|
||||||
|
const showMe = G.lobbyRoom === 'all' || G.lobbyRoom === mine;
|
||||||
|
const out = pendingOut();
|
||||||
|
const flagOpts = FLAGS.map(f => `<option value="${f}" ${f === myFlag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join('');
|
||||||
|
const room = (f, label, flag) => `<button class="rroom ${G.lobbyRoom === f ? 'on' : ''} ${f === mine ? 'joined' : ''}" data-f="${f}"><span class="rfl">${flag ? flagHtml(f) : ''}</span><span class="rn">${label}${f === mine ? ' <span class="rhere">📍</span>' : ''}</span><span class="cnt ${cnt(f) ? 'live' : ''}">${f === 'all' ? total : cnt(f)}</span></button>`;
|
||||||
|
const rooms = room('all', t('all_countries'), false) + FLAGS.map(f => room(f, t('cc_' + f), true)).join('');
|
||||||
|
const action = r => (r.state === 'idle' && !out ? `<button class="chal" data-uid="${esc(r.uid)}">${t('challenge')}</button>` : `<span class="pbusy">${r.state === 'idle' ? '' : t('busy')}</span>`);
|
||||||
|
const prow = (r, me) => `<div class="prow ${me ? 'me' : ''}" ${me ? '' : `data-uid="${esc(r.uid)}"`}><span class="pf">${flagHtml(me ? G.save.flag : r.flag)}</span><span class="pn">${esc(me ? playerName() : r.name)}${me ? ` <span class="muted">(${t('you')})</span>` : ''}</span><span class="pfame">⭐ ${Kit.fmt((me ? G.save.fame : r.fame) | 0)}</span>${me ? '<span class="pbusy"></span>' : action(r)}</div>`;
|
||||||
|
const list = here.map(r => prow(r, false)).join('');
|
||||||
|
const title = G.lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(G.lobbyRoom) + ' ' + t('cc_' + G.lobbyRoom);
|
||||||
|
const offline = lobby && !lobby.connected ? `<p class="muted" style="margin:6px 0 0">${t('net_connecting')}</p>` : '';
|
||||||
|
overlay.innerHTML = `<div class="lobbyfull">
|
||||||
|
<div class="lobbyL"><div class="lobbyLh">🌍 ${t('lobby')}</div><div class="roomlist">${rooms}</div></div>
|
||||||
|
<div class="lobbyR">
|
||||||
|
<div class="lobbyRh">${title} <span class="muted">(${here.length + (showMe ? 1 : 0)})</span><span class="grow"></span>
|
||||||
|
<label class="flagpick">${t('your_flag')} <select id="lFlag">${flagOpts}</select></label></div>
|
||||||
|
<div class="plist">${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `<div class="muted" style="padding:16px;text-align:center">${t('lobby_empty')}</div>`)}</div>
|
||||||
|
${out ? `<p class="muted" style="margin:6px 0 0">${t('waiting_accept')} <button class="link" id="lCancel">${t('cancel')}</button></p>` : ''}
|
||||||
|
${offline}<p class="err" id="lMsg" style="margin:4px 0 0"></p>
|
||||||
|
<div class="row" style="margin-top:8px"><button id="lBack">${t('back')}</button><button class="primary" id="lQuick">${t('quick_match')}</button></div>
|
||||||
|
</div></div>`;
|
||||||
|
overlay.classList.remove('hide'); overlay.classList.remove('clear');
|
||||||
|
overlay.style.backgroundImage = `linear-gradient(rgba(5,6,10,.6), rgba(5,6,10,.8)), url("${img('bg_title.jpg')}")`;
|
||||||
|
overlay.querySelectorAll('.rroom').forEach(b => { b.onclick = () => {
|
||||||
|
SFX.click(); G.lobbyRoom = b.dataset.f;
|
||||||
|
if (G.lobbyRoom !== 'all') { G.joinedRoom = G.lobbyRoom; if (lobby) lobby.setRoom(G.joinedRoom); } // joining a country = be present there
|
||||||
|
renderLobby();
|
||||||
|
}; });
|
||||||
|
$('lFlag').onchange = e => { G.save.flag = e.target.value; persist(); onlineFlush(); renderLobby(); };
|
||||||
|
overlay.querySelectorAll('.chal').forEach(b => { b.onclick = () => { SFX.click(); lobby.challenge(b.dataset.uid); renderLobby(); }; });
|
||||||
|
if ($('lCancel')) $('lCancel').onclick = () => { SFX.click(); lobby.cancel(); renderLobby(); };
|
||||||
|
$('lQuick').onclick = () => { const idle = here.find(r => r.state === 'idle') || all.find(r => r.state === 'idle'); if (idle && !pendingOut()) { SFX.click(); lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); };
|
||||||
|
$('lBack').onclick = () => { SFX.click(); if (G.save) openGarage(); else showTitle(); };
|
||||||
|
}
|
||||||
|
function showIncoming(c) {
|
||||||
|
card(`<h2>${t('challenge_in')}</h2><p>${flagHtml(c.fromFlag)} <b>${esc(c.fromName)}</b> ${t('wants_fight')}</p>
|
||||||
|
<div class="row"><button id="cNo">${t('decline')}</button><button class="primary" id="cYes">${t('accept')}</button></div>`);
|
||||||
|
$('cYes').onclick = () => { SFX.click(); lobby.accept(c.from); };
|
||||||
|
$('cNo').onclick = () => { SFX.click(); lobby.decline(c.from); if (G.mode === 'lobby') renderLobby(); else hideOverlay(); };
|
||||||
|
}
|
||||||
|
// server says: fight on (also after a reconnect into a running fight)
|
||||||
|
function startOnlineFight(m) {
|
||||||
|
const mine = m.robots[m.seat], other = m.robots[1 - m.seat];
|
||||||
|
const opp = { name: other.name, build: other.build, paint: other.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: other.flag };
|
||||||
|
prepOpp(opp, () => startFight(opp, false, false, { id: m.matchId, seat: m.seat, seed: m.seed, arena: m.arena, countdown: m.countdown, myBuild: mine.build }));
|
||||||
|
}
|
||||||
|
// server result + rewards (the fight on screen ends with it; if we missed the fight, just take the new save)
|
||||||
|
function onlineFightEnded(m) {
|
||||||
|
if (G.F && G.F.online && G.F.online.id === m.matchId && !G.F.ended) {
|
||||||
|
G.F.serverEnd = m;
|
||||||
|
G.F.s.result = RC.Proto.localResult(m.seat, m.result);
|
||||||
|
G.F.s.endIn = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (m.save && G.gameMode === 'online') { adoptEconomy(m.save); afterEconomy(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// live fight over: the server already booked prize, repairs and achievements - show them and take its save
|
||||||
|
function endOnlineFight(res, won, me) {
|
||||||
|
if (G.F.nf) G.F.nf.stop();
|
||||||
|
const m = G.F.serverEnd, rw = (m && m.reward) || { money: 0, fame: 0, lines: [], ach: [] };
|
||||||
|
if (m && m.save) { adoptEconomy(m.save); persist(); }
|
||||||
|
(won ? SFX.win : SFX.lose)();
|
||||||
|
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
|
||||||
|
const sm = (m && m.summary) || { dealt: me.dealt, taken: me.taken };
|
||||||
|
const rows = rw.lines.map(([k, v]) => `<span>${t(k)}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
|
||||||
|
const ach = (rw.ach || []).map(a => ({ id: a.id, reward: a.reward }));
|
||||||
|
hud();
|
||||||
|
setScreen('result');
|
||||||
|
card(`<h1>${title}</h1><p>${esc(G.F.opp.name)} ${G.F.oppAway ? t('peer_left') : ''}</p>
|
||||||
|
<div class="res"><span>${t('r_dealt')}</span><span>${Math.round(sm.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(sm.taken)}</span>${rows}
|
||||||
|
${rw.fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(rw.fame)}</span>` : ''}</div>
|
||||||
|
${achHtml(ach)}
|
||||||
|
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button><button id="bShopO">${t('to_garage')}</button></div>`,
|
||||||
|
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
|
||||||
|
$('bLobby').onclick = () => { SFX.click(); showLobby(); };
|
||||||
|
$('bShopO').onclick = () => { SFX.click(); openGarage(); };
|
||||||
|
}
|
||||||
|
// the server went silent mid-fight: leave the arena; the result (if any) is booked server-side anyway
|
||||||
|
function onlineFightLost() {
|
||||||
|
if (G.F && G.F.nf) G.F.nf.stop();
|
||||||
|
SFX.deny();
|
||||||
|
setScreen('result');
|
||||||
|
card(`<h2>${t('net_lost')}</h2><p>${t('match_lost')}</p>
|
||||||
|
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button></div>`, { bg: 'bg_lose.jpg' });
|
||||||
|
$('bLobby').onclick = () => { SFX.click(); onlinePull(); showLobby(); };
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return {
|
||||||
|
actQueue, act, econKey, econDiffers, adoptEconomy, afterEconomy, pushTimer, cosmetics, onlinePush,
|
||||||
|
onlineFlush, onlinePull, myRoom, pendingOut, wireLobby, startOnline, joinAnon, errText, showOnlineLogin,
|
||||||
|
showLobby, renderLobby, showIncoming, startOnlineFight, onlineFightEnded, endOnlineFight,
|
||||||
|
onlineFightLost
|
||||||
|
};
|
||||||
|
};
|
||||||
|
})(window);
|
||||||
271
game/pages.js
Normal file
271
game/pages.js
Normal file
@@ -0,0 +1,271 @@
|
|||||||
|
/* Robot Clash - menu pages: settings, help, tutorial, country, achievements, missions, legal, ranking board.
|
||||||
|
Part of game.js (split for size): created once by game.js with the shared context G.
|
||||||
|
Live state (save, mode, F, ...) is read as G.<name>; services/helpers are taken from G at creation. */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
RC.GamePages = function (G) {
|
||||||
|
const {
|
||||||
|
$, CAMS, FLAGS, L, SFX, accounts, act, audio, card, currentBack, ensureMissions, esc, fbAcc, flagHtml,
|
||||||
|
hud, layer, liveText, logout, net, newSave, openGarage, overlay, overlayEnter, persist, rank,
|
||||||
|
saveSettings, settings, shop, showLeague, showTournament, skipIntro, t, togglePause, tourState
|
||||||
|
} = G;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------- settings / help / ranking
|
||||||
|
function showSettings(back) {
|
||||||
|
overlayEnter();
|
||||||
|
const prev = G.mode;
|
||||||
|
const seg = (id, val, opts) => `<div class="seg" id="${id}">${opts.map(([v, label]) => `<button data-v="${v}" class="${v === val ? 'on' : ''}">${label}</button>`).join('')}</div>`;
|
||||||
|
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
|
||||||
|
const item = (label, ctl) => `<span class="sl">${label}</span>${ctl}`;
|
||||||
|
card(`<h2>${t('settings')}</h2><div class="set2">
|
||||||
|
${item(t('s_lang'), seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self])))}
|
||||||
|
${G.save ? item(t('s_country'), `<select id="sCountry" class="selset">${FLAGS.map(f => `<option value="${f}" ${f === G.save.flag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join('')}</select>`) : ''}
|
||||||
|
${item(t('s_music'), `<input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">`)}
|
||||||
|
${item(t('s_sfx'), `<input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">`)}
|
||||||
|
${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))}
|
||||||
|
${item(t('s_cam'), seg('sCam', settings.cam, CAMS.map(c => [c, t('cam_' + c)])))}
|
||||||
|
${item(t('s_comfort'), seg('sComfort', settings.comfort ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
|
||||||
|
${item(t('s_steer'), seg('sSteer', settings.steer, [['tank', t('steer_tank')], ['simple', t('steer_simple')]]))}
|
||||||
|
${item(t('s_autofire'), seg('sAuto', settings.autofire ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
|
||||||
|
${item(t('s_quiet'), seg('sQuiet', settings.quiet ? '1' : '0', [['0', t('off')], ['1', t('on')]]))}
|
||||||
|
${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))}
|
||||||
|
${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
|
||||||
|
</div>
|
||||||
|
${G.isDev && G.save ? `<div class="setdev"><span class="sl">🛠 Dev · Coins</span><div class="row">
|
||||||
|
<button data-coin="10000">+10k</button><button data-coin="100000">+100k</button>
|
||||||
|
<button data-coin="1000000">+1M</button><button data-coin="set800">Reset 800</button></div></div>` : ''}
|
||||||
|
<div class="setacc"><span class="sl">${t('s_account')}</span>
|
||||||
|
<span class="who">${who ? '👤 <b>' + esc(who.name) + '</b>' + (who.email ? ' <span class="muted">' + esc(who.email) + '</span>' : '') : '👤 ' + t('guest')}</span>
|
||||||
|
${G.save ? `<button id="sOut">${who ? t('logout') : t('to_title')}</button>` : ''}</div>
|
||||||
|
<div class="row"><button id="sFull">⛶ ${t('win_full')}</button><button id="sKeys">🎮 ${t('s_controls')}</button>
|
||||||
|
<button id="sLegal">§ ${t('legal')}</button>${G.save ? `<button id="sReset">${t('reset')}</button>` : ''}<button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, clear: prev === 'title' || prev === 'intro' });
|
||||||
|
const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; });
|
||||||
|
segOn('sLang', v => { L.set(v); showSettings(back); });
|
||||||
|
segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (G.view) G.view.setQuality(v); });
|
||||||
|
segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); });
|
||||||
|
segOn('sSteer', v => { settings.steer = v; saveSettings(); });
|
||||||
|
segOn('sCam', v => { settings.cam = v; saveSettings(); if (G.view) G.view.setCam(v); });
|
||||||
|
segOn('sComfort', v => { settings.comfort = v === '1'; saveSettings(); if (G.view && G.view.setComfort) G.view.setComfort(settings.comfort); });
|
||||||
|
segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); });
|
||||||
|
segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); });
|
||||||
|
segOn('sArena', v => { settings.arena = v; saveSettings(); });
|
||||||
|
if ($('sCountry')) $('sCountry').onchange = e => { G.save.flag = e.target.value; G.save.flagSet = true; persist(); hud(); };
|
||||||
|
$('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol);
|
||||||
|
$('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value);
|
||||||
|
$('sSfx').onchange = () => SFX.click();
|
||||||
|
$('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); };
|
||||||
|
if (G.isDev && G.save) overlay.querySelectorAll('[data-coin]').forEach(b => b.onclick = () => {
|
||||||
|
SFX.buy(); const v = b.dataset.coin;
|
||||||
|
act({ type: 'devCoins', money: v === 'set800' ? 800 : Math.min(1e9, (G.save.money | 0) + (+v || 0)) });
|
||||||
|
persist(); hud(); showSettings(back);
|
||||||
|
});
|
||||||
|
if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); };
|
||||||
|
if ($('sOut')) $('sOut').onclick = () => { SFX.click(); logout(); };
|
||||||
|
$('sKeys').onclick = () => { SFX.click(); showHelp(() => showSettings(back)); };
|
||||||
|
if ($('sLegal')) $('sLegal').onclick = () => { SFX.click(); showLegal(() => showSettings(back)); };
|
||||||
|
$('bBack').onclick = () => { SFX.click(); back(); };
|
||||||
|
}
|
||||||
|
function keysHtml() {
|
||||||
|
return `<div class="keys"><b>W A S D / ↑ ← ↓ →</b><span>${t('key_drive')}</span><b>${t('key_space')}</b><span>${t('key_weapon')}</span>
|
||||||
|
<b>Shift / E</b><span>${t('key_tower')}</span><b>C</b><span>${t('key_cam')}</span><b>P / Esc</b><span>${t('pause')}</span><b>M</b><span>${t('sound_on')} / ${t('sound_off')}</span>
|
||||||
|
<b>${t('key_pad')}</b><span>${t('key_pad_text')}</span></div>`;
|
||||||
|
}
|
||||||
|
// first start: four short cards instead of the full help page
|
||||||
|
const TUT = ['tut_1', 'tut_2', 'tut_3', 'tut_4'];
|
||||||
|
function startTutorial(done) {
|
||||||
|
let i = 0;
|
||||||
|
const step = () => {
|
||||||
|
if (i >= TUT.length) { done(); return; }
|
||||||
|
const n = i + 1;
|
||||||
|
overlayEnter();
|
||||||
|
card(`<h2>${t('tut_title')} <span class="muted">${n}/${TUT.length}</span></h2>
|
||||||
|
<p>${t(TUT[i])}</p>
|
||||||
|
<div class="row"><button id="tSkip">${t('tut_skip')}</button>
|
||||||
|
<button class="primary" id="tNext">${n === TUT.length ? t('tut_go') : t('tut_next')}</button></div>`,
|
||||||
|
{ bg: 'bg_workshop.jpg' });
|
||||||
|
$('tNext').onclick = () => { SFX.click(); i++; step(); };
|
||||||
|
$('tSkip').onclick = () => { SFX.click(); done(); };
|
||||||
|
};
|
||||||
|
step();
|
||||||
|
}
|
||||||
|
|
||||||
|
// first start: pick the country whose flag shows on the ranking / in the lobby (changeable later in settings)
|
||||||
|
function chooseFlag(done) {
|
||||||
|
overlayEnter();
|
||||||
|
let pick = (G.save && FLAGS.includes(G.save.flag)) ? G.save.flag : 'XX';
|
||||||
|
card(`<h2>🌍 ${t('country_title')}</h2><p>${t('country_text')}</p>
|
||||||
|
<div class="flaggrid">${FLAGS.map(f => `<button class="flagbtn ${f === pick ? 'on' : ''}" data-f="${f}">${flagHtml(f)}<span>${t('cc_' + f)}</span></button>`).join('')}</div>
|
||||||
|
<div class="row"><button class="primary" id="cfGo">${t('country_go')}</button></div>`, { bg: 'bg_title.jpg', wide: true });
|
||||||
|
overlay.querySelectorAll('.flagbtn').forEach(b => b.onclick = () => { pick = b.dataset.f; SFX.click(); overlay.querySelectorAll('.flagbtn').forEach(x => x.classList.toggle('on', x.dataset.f === pick)); });
|
||||||
|
$('cfGo').onclick = () => { if (G.save) { G.save.flag = pick; G.save.flagSet = true; persist(); } SFX.click(); done(); };
|
||||||
|
}
|
||||||
|
function ensureFlag(done) { if (G.save && !G.save.flagSet) chooseFlag(done); else done(); }
|
||||||
|
|
||||||
|
// one line for the running event and one for the admin's message
|
||||||
|
function liveBanner() {
|
||||||
|
const out = [];
|
||||||
|
if (G.LIVE.event) {
|
||||||
|
const n = liveText(G.LIVE.event.name) || t('event_running');
|
||||||
|
const extra = G.LIVE.event.prizeMul !== 1 ? ` · ${t('event_prize', { n: G.LIVE.event.prizeMul })}` : '';
|
||||||
|
out.push(`<div class="evbar"><b>${t('event')}</b><span>${esc(n)}${extra}</span></div>`);
|
||||||
|
}
|
||||||
|
const m = liveText(G.LIVE.motd);
|
||||||
|
if (m) out.push(`<p class="motd">${esc(m)}</p>`);
|
||||||
|
return out.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
function showAchievements(back) {
|
||||||
|
overlayEnter();
|
||||||
|
const P = RC.Progress, r = P.rankOf(G.save.fame);
|
||||||
|
const pct = Math.round(r.pct * 100);
|
||||||
|
const nextLine = r.next
|
||||||
|
? t('rank_next', { n: t('rank_' + r.next.key), f: Kit.fmt(r.next.at - G.save.fame) })
|
||||||
|
: t('rank_top');
|
||||||
|
const rows = P.ACHIEVEMENTS.map(a => {
|
||||||
|
const done = !!(G.save.ach && G.save.ach[a.id]);
|
||||||
|
return `<div class="achrow ${done ? 'done' : 'todo'}"><span class="am">${done ? '🏅' : '🔒'}</span>
|
||||||
|
<span><span class="an">${t('ach_' + a.id)}</span><br><span class="ad">${t('achd_' + a.id)}</span></span>
|
||||||
|
<span class="${done ? 'plus' : 'muted'}">${Kit.fmt(a.reward)}</span></div>`;
|
||||||
|
}).join('');
|
||||||
|
card(`<h2>🏅 ${t('achievements')}</h2>
|
||||||
|
<div class="rankbar"><div class="rt"><b>${t('rank_' + r.key)}</b><span class="muted">${nextLine}</span></div>
|
||||||
|
<div class="bar"><i style="width:${pct}%"></i></div></div>
|
||||||
|
<p class="muted">${t('ach_done', { n: P.earned(G.save), m: P.total })}</p>
|
||||||
|
<div class="achlist">${rows}</div>
|
||||||
|
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
|
||||||
|
$('bBack').onclick = () => { SFX.click(); back(); };
|
||||||
|
}
|
||||||
|
|
||||||
|
// campaign missions page: 3 daily + 1 weekly with progress bars + reset countdown
|
||||||
|
function showMissions(back) {
|
||||||
|
overlayEnter();
|
||||||
|
ensureMissions();
|
||||||
|
const daily = (G.save.missions && G.save.missions.daily) || [], weekly = (G.save.missions && G.save.missions.weekly) || [];
|
||||||
|
const hrs = ms => Math.max(1, Math.ceil(ms / 3600000));
|
||||||
|
const toDay = 86400000 - (Date.now() % 86400000), toWeek = 604800000 - (Date.now() % 604800000);
|
||||||
|
const row = m => {
|
||||||
|
const prog = Math.min(m.prog || 0, m.goal), pct = Math.round(prog / m.goal * 100);
|
||||||
|
const rew = `🪙 ${Kit.fmt(m.reward)}${m.fame ? ' · ⭐' + m.fame : ''}${typeof m.unlock === 'number' ? ' · 🎨' : ''}`;
|
||||||
|
return `<div class="missrow ${m.done ? 'done' : ''}"><span class="mm">${m.done ? '✅' : '🎯'}</span>
|
||||||
|
<div class="mi"><div class="mn">${t('mission_' + m.id)}</div><div class="md">${t('missd_' + m.id)}</div>
|
||||||
|
<div class="bar"><i style="width:${pct}%"></i></div></div>
|
||||||
|
<div class="mr"><span class="${m.done ? 'plus' : 'muted'}">${rew}</span><span class="mp">${prog}/${m.goal}</span></div></div>`;
|
||||||
|
};
|
||||||
|
card(`<h2>🎯 ${t('missions')}</h2>
|
||||||
|
<h3>${t('miss_daily')} <span class="muted">· ${t('miss_reset_in', { n: hrs(toDay) })}</span></h3>
|
||||||
|
<div class="misslist">${daily.map(row).join('')}</div>
|
||||||
|
<h3>${t('miss_weekly')} <span class="muted">· ${t('miss_reset_in', { n: hrs(toWeek) })}</span></h3>
|
||||||
|
<div class="misslist">${weekly.map(row).join('')}</div>
|
||||||
|
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
|
||||||
|
$('bBack').onclick = () => { SFX.click(); back(); };
|
||||||
|
}
|
||||||
|
|
||||||
|
function showHelp(back) {
|
||||||
|
overlayEnter();
|
||||||
|
card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>${keysHtml()}
|
||||||
|
<p style="margin-top:12px">${t('help_arena')}</p><button class="primary" id="bOk">${t('ok')}</button>`, { bg: 'bg_title.jpg' });
|
||||||
|
$('bOk').onclick = () => { SFX.click(); back(); };
|
||||||
|
}
|
||||||
|
// legal pages (Impressum / Datenschutz) — placeholders, Michael fills his data in lang.js
|
||||||
|
function showLegal(back, which) {
|
||||||
|
overlayEnter();
|
||||||
|
which = which === 'privacy' ? 'privacy' : 'impressum';
|
||||||
|
const seg = ['impressum', 'privacy'].map(k => `<button data-l="${k}" class="${k === which ? 'on' : ''}">${t('legal_' + k)}</button>`).join('');
|
||||||
|
card(`<h2>${t('legal')}</h2><div class="seg legalseg">${seg}</div>
|
||||||
|
<div class="legaltext">${t(which + '_text')}</div>
|
||||||
|
<div class="row"><button class="primary" id="bOk">${t('ok')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
|
||||||
|
overlay.querySelectorAll('.legalseg button').forEach(b => b.onclick = () => { SFX.click(); showLegal(back, b.dataset.l); });
|
||||||
|
$('bOk').onclick = () => { SFX.click(); back(); };
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeRank = () => { if (G.rankSub) { G.rankSub.close(); G.rankSub = null; } };
|
||||||
|
function showRanking(back) {
|
||||||
|
overlayEnter();
|
||||||
|
card(`<h2>🏆 ${t('ranking')} ${rank.enabled ? '<span class="livedot">● ' + t('rank_live') + '</span>' : ''}</h2>
|
||||||
|
<ol class="board live" id="board"><li class="muted">${t('loading')}</li></ol>
|
||||||
|
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { bg: 'bg_title.jpg' });
|
||||||
|
$('bBack').onclick = () => { SFX.click(); closeRank(); back(); };
|
||||||
|
G.boardFame = {}; G.boardIdx = {};
|
||||||
|
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
|
||||||
|
closeRank();
|
||||||
|
if (rank.enabled) G.rankSub = rank.watch(rows => drawBoard($('board'), rows, myUid));
|
||||||
|
else drawBoard($('board'), [], myUid);
|
||||||
|
}
|
||||||
|
// animated live board: FLIP row reordering, fame bars, count-up numbers, rank ▲/▼
|
||||||
|
function animNum(el, from, to) {
|
||||||
|
if (!el) return; const t0 = performance.now(), dur = 520;
|
||||||
|
(function step(now) {
|
||||||
|
const k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3);
|
||||||
|
el.textContent = Kit.fmt(Math.round(from + (to - from) * e));
|
||||||
|
if (k < 1 && el.isConnected) requestAnimationFrame(step);
|
||||||
|
})(t0);
|
||||||
|
}
|
||||||
|
function drawBoard(el, rows, myUid) {
|
||||||
|
if (!el) return;
|
||||||
|
if (!rows.length) { el.innerHTML = `<li class="muted">${t('no_scores')}</li>`; G.boardFame = {}; G.boardIdx = {}; return; }
|
||||||
|
const max = Math.max(1, rows[0].fame);
|
||||||
|
const prevTop = {};
|
||||||
|
el.querySelectorAll('.brow').forEach(li => { prevTop[li.dataset.key] = li.getBoundingClientRect().top; });
|
||||||
|
el.innerHTML = rows.map((r, i) => {
|
||||||
|
const me = r.key === myUid;
|
||||||
|
const was = G.boardIdx[r.key];
|
||||||
|
const arr = (was != null && was !== i) ? (i < was ? '<span class="arrow up">▲</span>' : '<span class="arrow dn">▼</span>') : '';
|
||||||
|
return `<li class="brow ${me ? 'me' : ''}" data-key="${r.key}" data-fame="${r.fame}">
|
||||||
|
<span class="rk">${i + 1}</span><span class="fl">${flagHtml(r.flag || 'XX')}</span>
|
||||||
|
<span class="nm">${esc(r.name)}${me ? ` <span class="muted">(${t('you')})</span>` : ''}${arr}</span>
|
||||||
|
<span class="val"><i class="fill" style="width:${(r.fame / max * 100).toFixed(1)}%"></i><b>0</b></span></li>`;
|
||||||
|
}).join('');
|
||||||
|
el.querySelectorAll('.brow').forEach(li => {
|
||||||
|
const key = li.dataset.key, to = +li.dataset.fame, from = G.boardFame[key] != null ? G.boardFame[key] : to;
|
||||||
|
animNum(li.querySelector('.val b'), from, to); G.boardFame[key] = to;
|
||||||
|
if (prevTop[key] != null) {
|
||||||
|
const d = prevTop[key] - li.getBoundingClientRect().top;
|
||||||
|
if (d) { li.style.transform = `translateY(${d}px)`; li.style.transition = 'none';
|
||||||
|
requestAnimationFrame(() => { li.style.transition = 'transform .45s cubic-bezier(.2,.8,.2,1)'; li.style.transform = ''; }); }
|
||||||
|
}
|
||||||
|
});
|
||||||
|
G.boardIdx = {}; rows.forEach((r, i) => G.boardIdx[r.key] = i);
|
||||||
|
}
|
||||||
|
function confirmReset(back) {
|
||||||
|
card(`<h2>${t('reset')}</h2><p>${t('reset_text')}</p><div class="row"><button id="bYes">${t('reset_yes')}</button><button class="primary" id="bNo">${t('cancel')}</button></div>`);
|
||||||
|
$('bNo').onclick = () => { SFX.click(); back(); };
|
||||||
|
$('bYes').onclick = () => { Object.assign(G.save, newSave()); RC.layerFromData(layer, null); G.save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); };
|
||||||
|
}
|
||||||
|
// the rank badge opens the achievements page
|
||||||
|
$('hTour').onclick = () => { SFX.click(); if (G.gameMode === 'campaign') { if (tourState()) showTournament(); else showLeague(); } }; // online tournament: server-side later (plan P2-6)
|
||||||
|
$('chipFame').onclick = () => {
|
||||||
|
if (!G.save || G.mode === 'intro' || G.mode === 'title') return;
|
||||||
|
if (G.mode === 'fight') togglePause();
|
||||||
|
SFX.click();
|
||||||
|
showAchievements(G.mode === 'pause' ? () => { G.mode = 'fight'; togglePause(); } : currentBack());
|
||||||
|
};
|
||||||
|
$('bSettings').onclick = () => {
|
||||||
|
if (G.mode === 'fight') togglePause();
|
||||||
|
if (G.mode === 'intro') skipIntro();
|
||||||
|
SFX.click();
|
||||||
|
const back = G.mode === 'pause' ? () => { G.mode = 'fight'; togglePause(); } : currentBack();
|
||||||
|
showSettings(back);
|
||||||
|
};
|
||||||
|
|
||||||
|
function boardHtml() { return (rank.enabled && G.gameMode === 'online') ? `<h3>${t('ranking')}</h3><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
|
||||||
|
async function fillBoard() {
|
||||||
|
const el = $('board');
|
||||||
|
if (!el) return;
|
||||||
|
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
|
||||||
|
try {
|
||||||
|
const rows = await rank.once(10);
|
||||||
|
el.innerHTML = rows.length
|
||||||
|
? rows.map((r, i) => `<li class="${r.key === myUid ? 'me' : ''}"><span>${i + 1}.</span><span class="nm">${esc(r.name)}</span><span>${Kit.fmt(r.fame)}</span></li>`).join('')
|
||||||
|
: `<li class="muted">${t('no_scores')}</li>`;
|
||||||
|
} catch (e) { el.innerHTML = `<li class="muted">${t('scores_offline')}</li>`; }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return {
|
||||||
|
showSettings, keysHtml, TUT, startTutorial, chooseFlag, ensureFlag, liveBanner, showAchievements,
|
||||||
|
showMissions, showHelp, showLegal, closeRank, showRanking, animNum, drawBoard, confirmReset, boardHtml,
|
||||||
|
fillBoard
|
||||||
|
};
|
||||||
|
};
|
||||||
|
})(window);
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
/* Robot Clash - player accounts. v1: local profiles on this device (name + password, stored as a
|
/* Robot Clash - player accounts. v1: local profiles on this device (name + password, stored as a
|
||||||
salted hash in localStorage - keeps siblings apart, no real security). Later the same interface
|
salted hash in localStorage - keeps siblings apart, no real security). Later the same interface
|
||||||
gets a Firebase Auth backend (docs/firebase) without changing game.js.
|
gets a server backend (server/auth.js) without changing game.js.
|
||||||
|
|
||||||
const acc = RC.Accounts('robotclash');
|
const acc = RC.Accounts('robotclash');
|
||||||
acc.list() -> [{ id, name }]
|
acc.list() -> [{ id, name }]
|
||||||
|
|||||||
113
game/protocol.js
Normal file
113
game/protocol.js
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
/* Robot Clash - wire protocol shared by client (classic script) and server (require). No DOM.
|
||||||
|
One WebSocket per player, JSON messages { t: '<type>', ... }.
|
||||||
|
|
||||||
|
RC.Proto.VERSION bump on every incompatible change (server rejects older clients)
|
||||||
|
RC.Proto.check(msg) -> { ok, error } validates a client->server message (type, ranges, sizes)
|
||||||
|
RC.Proto.input(raw) -> clean input { throttle, turn, fire, fire2, fire3 } (clamped)
|
||||||
|
RC.Proto.packSnap(s, tick, ack) -> compact snapshot of a fight state (server side, seat order)
|
||||||
|
RC.Proto.toLocal(seat, snap) -> copy of the snapshot as seen by `seat`: own robot at index 0,
|
||||||
|
every robot index inside (events, grabs, crane, owners, winner) mirrored.
|
||||||
|
THE ONLY PLACE where seat <-> local index mapping happens.
|
||||||
|
RC.Proto.localResult(seat, result) -> result with the winner as a local index (0 = me) */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
|
||||||
|
const VERSION = 1;
|
||||||
|
const MAX_MSG = 8 * 1024; // bytes per client message
|
||||||
|
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
|
||||||
|
|
||||||
|
const isStr = (v, max = 64) => typeof v === 'string' && v.length > 0 && v.length <= max;
|
||||||
|
const isNum = v => typeof v === 'number' && Number.isFinite(v);
|
||||||
|
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
||||||
|
|
||||||
|
// client -> server message schemas: field -> check
|
||||||
|
const C2S = {
|
||||||
|
hello: { v: v => Number.isInteger(v), token: v => isStr(v, 4096) },
|
||||||
|
ping: { t0: v => v === undefined || isNum(v) }, // (t is the message type itself)
|
||||||
|
room: { room: v => FLAGS.includes(v) || v === 'all' },
|
||||||
|
challenge: { to: v => isStr(v) },
|
||||||
|
'challenge.cancel': {},
|
||||||
|
'challenge.accept': { from: v => isStr(v) },
|
||||||
|
'challenge.decline': { from: v => isStr(v) },
|
||||||
|
input: {
|
||||||
|
seq: v => Number.isInteger(v) && v >= 0,
|
||||||
|
throttle: isNum, turn: isNum,
|
||||||
|
fire: v => typeof v === 'boolean', fire2: v => typeof v === 'boolean', fire3: v => typeof v === 'boolean',
|
||||||
|
},
|
||||||
|
'match.leave': {},
|
||||||
|
};
|
||||||
|
|
||||||
|
function check(msg) {
|
||||||
|
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return { ok: false, error: 'BAD_MESSAGE' };
|
||||||
|
const schema = C2S[msg.t];
|
||||||
|
if (!schema) return { ok: false, error: 'UNKNOWN_TYPE' };
|
||||||
|
for (const k of Object.keys(schema)) if (!schema[k](msg[k])) return { ok: false, error: 'BAD_FIELD:' + k };
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
const input = raw => ({
|
||||||
|
throttle: clamp(isNum(raw && raw.throttle) ? raw.throttle : 0, -1, 1),
|
||||||
|
turn: clamp(isNum(raw && raw.turn) ? raw.turn : 0, -1, 1),
|
||||||
|
fire: !!(raw && raw.fire), fire2: !!(raw && raw.fire2), fire3: !!(raw && raw.fire3),
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- snapshots ---------------------------------------------------------------------------------
|
||||||
|
// robot fields the view / HUD / sound / result screen read
|
||||||
|
const RF = ['x', 'z', 'a', 'y', 'hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'turretA', 'spin',
|
||||||
|
'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'dead', 'out', 'dealt', 'taken', 'onOil'];
|
||||||
|
const WF = ['cd', 'spin', 'swing', 'grab', 'sawOn', 'fire', 'flipAnim'];
|
||||||
|
const rnd = v => (typeof v === 'number' ? Math.round(v * 1000) / 1000 : v);
|
||||||
|
const pick = (o, keys) => { const r = {}; for (const k of keys) if (o[k] !== undefined) r[k] = rnd(o[k]); return r; };
|
||||||
|
const packRobot = r => Object.assign(pick(r, RF), {
|
||||||
|
lost: Object.assign({}, r.lost), lostW: (r.lostW || []).slice(), W: (r.W || []).map(w => pick(w, WF)),
|
||||||
|
});
|
||||||
|
|
||||||
|
function packSnap(s, tick, ack) {
|
||||||
|
return {
|
||||||
|
tick, ack: ack || [0, 0],
|
||||||
|
time: rnd(s.t), left: rnd(s.left), pitOpen: rnd(s.pitOpen), pitAlarm: !!s.pitAlarm, endIn: rnd(s.endIn),
|
||||||
|
result: s.result ? { winner: s.result.winner, reason: s.result.reason } : null,
|
||||||
|
press: { st: s.press.st, y: rnd(s.press.y) },
|
||||||
|
crane: { st: s.crane.st, x: rnd(s.crane.x), z: rnd(s.crane.z), who: s.crane.who },
|
||||||
|
rockets: s.rockets.map(k => ({ kind: k.kind, owner: k.owner, x: rnd(k.x), z: rnd(k.z), y: rnd(k.y), a: rnd(k.a) })),
|
||||||
|
mines: s.mines.map(k => ({ owner: k.owner, x: rnd(k.x), z: rnd(k.z), arm: rnd(k.arm) })),
|
||||||
|
robots: [packRobot(s.robots[0]), packRobot(s.robots[1])],
|
||||||
|
ev: s.events.map(e => Object.assign({}, e)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// seat index -> local index (0 = me). -1 / null stay as they are.
|
||||||
|
const mapper = seat => i => (i === 0 || i === 1) ? (seat === 0 ? i : 1 - i) : i;
|
||||||
|
|
||||||
|
function toLocal(seat, snap) {
|
||||||
|
if (!snap) return snap;
|
||||||
|
const m = mapper(seat);
|
||||||
|
const robots = (seat === 0 ? snap.robots : [snap.robots[1], snap.robots[0]])
|
||||||
|
.map(r => Object.assign({}, r, { grabbedBy: r.grabbedBy == null ? r.grabbedBy : m(r.grabbedBy) }));
|
||||||
|
return Object.assign({}, snap, {
|
||||||
|
robots,
|
||||||
|
ack: snap.ack ? snap.ack[seat] : 0,
|
||||||
|
away: snap.away ? (seat === 0 ? snap.away.slice() : [snap.away[1], snap.away[0]]) : undefined,
|
||||||
|
rtt: snap.rtt ? (seat === 0 ? snap.rtt.slice() : [snap.rtt[1], snap.rtt[0]]) : undefined, // ping of [me, opponent]
|
||||||
|
result: localResult(seat, snap.result),
|
||||||
|
crane: Object.assign({}, snap.crane, { who: m(snap.crane.who) }),
|
||||||
|
rockets: snap.rockets.map(k => Object.assign({}, k, { owner: m(k.owner) })),
|
||||||
|
mines: snap.mines.map(k => Object.assign({}, k, { owner: m(k.owner) })),
|
||||||
|
ev: (snap.ev || []).map(e => {
|
||||||
|
const c = Object.assign({}, e);
|
||||||
|
if ('who' in c) c.who = m(c.who);
|
||||||
|
if ('winner' in c) c.winner = m(c.winner);
|
||||||
|
return c;
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function localResult(seat, result) {
|
||||||
|
if (!result) return result;
|
||||||
|
return Object.assign({}, result, { winner: mapper(seat)(result.winner) });
|
||||||
|
}
|
||||||
|
|
||||||
|
RC.Proto = { VERSION, MAX_MSG, FLAGS, check, input, packSnap, toLocal, localResult, RF };
|
||||||
|
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||||
|
})(typeof window !== 'undefined' ? window : globalThis);
|
||||||
@@ -1,50 +1,41 @@
|
|||||||
/* Robot Clash - online ranking over the own server (ranks/<uid>, public read, owner write).
|
/* Robot Clash - online ranking. The server computes it from the online saves (fame only changes through
|
||||||
One row per account (dedupe by key is implicit); live push via net.db.stream (SSE).
|
server-booked fights), so the client only reads: GET /api/ranks, polled while a board is open.
|
||||||
Needs net.js + kit-core.js (Kit.badName). DOM-free; RC.Ranking.rank is a pure function (Node-testable).
|
DOM-free; RC.Ranking.rank is a pure function (Node-testable).
|
||||||
|
|
||||||
const rank = RC.Ranking(net);
|
const rank = RC.Ranking(net);
|
||||||
if (rank.enabled) {
|
if (rank.enabled) {
|
||||||
await rank.submit({ uid, name, fame, flag, cls, season }); // best effort, never throws
|
const sub = rank.watch(rows => draw(rows)); // { close() } rows best first, refreshed every 15 s
|
||||||
const sub = rank.watch(rows => draw(rows)); // { close() } live, rows best first
|
const rows = await rank.once(20);
|
||||||
const rows = await rank.once(20); // one-shot fallback (no stream)
|
|
||||||
}
|
}
|
||||||
RC.Ranking.rank(data, n) // { key: {name,fame,...} } -> sorted array, bad names out, capped */
|
RC.Ranking.rank(data, n) // [{uid,name,fame,flag}] or { key: {...} } -> sorted array, bad names out, capped */
|
||||||
(function (root) {
|
(function (root) {
|
||||||
'use strict';
|
'use strict';
|
||||||
const RC = (root.RC = root.RC || {});
|
const RC = (root.RC = root.RC || {});
|
||||||
const Kit = root.Kit || {};
|
const Kit = root.Kit || {};
|
||||||
const bad = s => (Kit.badName ? Kit.badName(s) : false);
|
const bad = s => (Kit.badName ? Kit.badName(s) : false);
|
||||||
|
const POLL = 15000;
|
||||||
|
|
||||||
// pure: raw ranks object -> clean, sorted (fame desc, newer first on tie), capped list
|
|
||||||
RC.Ranking = function (net) {
|
RC.Ranking = function (net) {
|
||||||
const api = {
|
const enabled = !!(net && net.enabled);
|
||||||
enabled: !!(net && net.enabled),
|
const fetchRows = async n => RC.Ranking.rank(await net.api('GET', '/api/ranks?n=' + (n || 20)), n);
|
||||||
async submit(row) {
|
return {
|
||||||
if (!api.enabled || !row || !row.uid) return false;
|
enabled,
|
||||||
const name = String(row.name || '').slice(0, 20);
|
|
||||||
if (!name || bad(name) || !(row.fame > 0)) return false;
|
|
||||||
const r = await net.db.put('ranks/' + row.uid, {
|
|
||||||
name, fame: Math.floor(row.fame) | 0, flag: row.flag || 'XX',
|
|
||||||
cls: row.cls || 'medium', season: row.season | 0, ts: { '.sv': 'timestamp' },
|
|
||||||
});
|
|
||||||
return !!r;
|
|
||||||
},
|
|
||||||
watch(cb, n) {
|
watch(cb, n) {
|
||||||
if (!api.enabled) { cb([]); return { close() {} }; }
|
if (!enabled) { cb([]); return { close() {} }; }
|
||||||
return net.db.stream('ranks', data => cb(RC.Ranking.rank(data, n)));
|
let alive = true;
|
||||||
},
|
const tick = () => fetchRows(n).then(rows => { if (alive) cb(rows); });
|
||||||
async once(n) {
|
tick();
|
||||||
if (!api.enabled) return [];
|
const timer = setInterval(tick, POLL);
|
||||||
return RC.Ranking.rank(await net.db.get('ranks'), n);
|
return { close() { alive = false; clearInterval(timer); } };
|
||||||
},
|
},
|
||||||
|
once: n => (enabled ? fetchRows(n) : Promise.resolve([])),
|
||||||
};
|
};
|
||||||
return api;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
RC.Ranking.rank = function (data, n = 20) {
|
RC.Ranking.rank = function (data, n = 20) {
|
||||||
const rows = Object.entries(data || {})
|
const list = Array.isArray(data) ? data.map(v => Object.assign({ key: v.uid }, v))
|
||||||
.map(([key, v]) => Object.assign({ key }, v))
|
: Object.entries(data || {}).map(([key, v]) => Object.assign({ key }, v));
|
||||||
.filter(v => v && typeof v.name === 'string' && typeof v.fame === 'number' && !bad(v.name));
|
const rows = list.filter(v => v && typeof v.name === 'string' && typeof v.fame === 'number' && !bad(v.name));
|
||||||
rows.sort((a, b) => b.fame - a.fame || (b.ts || 0) - (a.ts || 0));
|
rows.sort((a, b) => b.fame - a.fame || (b.ts || 0) - (a.ts || 0));
|
||||||
return rows.slice(0, n);
|
return rows.slice(0, n);
|
||||||
};
|
};
|
||||||
|
|||||||
60
game/sfx.js
Normal file
60
game/sfx.js
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
/* Robot Clash - sound effects: ComfyGen clips where they exist, synth tones as fallback (never silent, never crashes).
|
||||||
|
const SFX = RC.GameSfx(audio, settings) audio = Kit.createAudio(...), settings.quiet = softer weapon loops */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
RC.GameSfx = function (audio, settings) {
|
||||||
|
const last = {};
|
||||||
|
const every = (k, ms) => { const n = performance.now(); if (last[k] && n - last[k] < ms) return false; last[k] = n; return true; };
|
||||||
|
const SFX = {
|
||||||
|
click() { audio.sfx('sfx_click'); audio.tone(660, 0.04, 'square', 0.05); },
|
||||||
|
buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.08); },
|
||||||
|
deny() { audio.tone(160, 0.15, 'square', 0.12, -40); },
|
||||||
|
beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); },
|
||||||
|
clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); },
|
||||||
|
gate() { // metal garage door rolling open
|
||||||
|
audio.noise(1.0, 0.4, 1500); audio.noise(0.9, 0.3, 500, 0.05); // metal roll rumble
|
||||||
|
audio.tone(110, 0.9, 'sawtooth', 0.1, 70); // servo whir rising
|
||||||
|
for (let k = 0; k < 6; k++) audio.tone(170 + k * 28, 0.05, 'square', 0.07, 0, k * 0.11); // chain clanks
|
||||||
|
audio.noise(0.25, 0.55, 300, 0.9); audio.tone(58, 0.4, 'sine', 0.5, -22, 0.9); // heavy end clunk
|
||||||
|
},
|
||||||
|
win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); },
|
||||||
|
lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); },
|
||||||
|
event(e) {
|
||||||
|
switch (e.type) {
|
||||||
|
case 'bump': if (every('bump', 90)) audio.noise(0.12, Math.min(0.4, e.speed / 10), 700); break;
|
||||||
|
case 'wall': if (every('wall', 120)) { audio.sfx('sfx_hit'); audio.noise(0.2, 0.3, 1600); } break;
|
||||||
|
case 'flip': audio.tone(200, 0.2, 'square', 0.13, 500); audio.noise(0.12, 0.25, 3000); break;
|
||||||
|
case 'swing': audio.noise(0.15, 0.12, 900); break;
|
||||||
|
case 'smash': audio.sfx('sfx_hit'); audio.noise(0.25, 0.45, 650); audio.tone(95, 0.25, 'sine', 0.4, -45); break;
|
||||||
|
case 'spinhit': audio.sfx('sfx_hit'); audio.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); break;
|
||||||
|
case 'sparks': if (every('grind', 70)) audio.noise(0.06, 0.1, 5200); break;
|
||||||
|
case 'boom': audio.sfx('sfx_boom'); audio.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break;
|
||||||
|
case 'ko': audio.sfx('sfx_boom'); audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); break;
|
||||||
|
case 'launch': audio.noise(0.3, 0.18, 2200); audio.tone(300, 0.3, 'sawtooth', 0.07, 600); break;
|
||||||
|
case 'press_warn': for (let k = 0; k < 3; k++) audio.tone(880, 0.1, 'square', 0.1, 0, k * 0.2); break;
|
||||||
|
case 'press': audio.sfx('sfx_hit'); audio.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); break;
|
||||||
|
case 'crane': audio.tone(140, 0.6, 'sawtooth', 0.07, 140); break;
|
||||||
|
case 'drop': case 'land': audio.noise(0.22, 0.35, 500); break;
|
||||||
|
case 'broke': audio.sfx('sfx_hit'); audio.noise(0.45, 0.5, 900); audio.tone(240, 0.35, 'sawtooth', 0.22, -190); break;
|
||||||
|
case 'mine_drop': audio.tone(520, 0.08, 'square', 0.12, -160); audio.noise(0.06, 0.12, 2200); break;
|
||||||
|
case 'pit_open': for (let k = 0; k < 3; k++) audio.tone(700, 0.3, 'square', 0.12, -250, k * 0.4); break;
|
||||||
|
case 'pit': audio.tone(420, 1.2, 'sawtooth', 0.14, -360); break;
|
||||||
|
case 'grab': audio.tone(150, 0.25, 'square', 0.12, -60); break;
|
||||||
|
case 'boost': audio.noise(0.4, 0.25, 1800); break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
loops(s) { // continuous weapons as short repeated bursts
|
||||||
|
for (const r of s.robots) {
|
||||||
|
const q = settings.quiet ? 0.3 : 1, slow = settings.quiet ? 1.7 : 1; // quiet mode: softer + less often
|
||||||
|
if (r.sawOn && every('saw' + r.i, 200 * slow)) { if (!settings.quiet) audio.sfx('sfx_saw', 0.35); audio.tone(360 + Math.random() * 40, 0.12, 'triangle', 0.02 * q); }
|
||||||
|
if (r.flameOn && every('fl' + r.i, 120 * slow)) audio.noise(0.14, 0.12 * q, 900);
|
||||||
|
if (r.gunOn && every('gun' + r.i, 70 * slow)) audio.noise(0.04, 0.16 * q, 3500);
|
||||||
|
if (r.spin > 0.2 && every('spin' + r.i, 100 * slow)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin * q);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return SFX;
|
||||||
|
};
|
||||||
|
})(window);
|
||||||
20
game/shop.js
20
game/shop.js
@@ -15,7 +15,6 @@
|
|||||||
// ready-made [body, accent] combinations
|
// ready-made [body, accent] combinations
|
||||||
RC.SCHEMES = [[0xff7a1a, 0x15171b], [0x15171b, 0xff7a1a], [0x2a6fd8, 0xe6e6e6], [0xd8452b, 0xf2c230],
|
RC.SCHEMES = [[0xff7a1a, 0x15171b], [0x15171b, 0xff7a1a], [0x2a6fd8, 0xe6e6e6], [0xd8452b, 0xf2c230],
|
||||||
[0x5fae3b, 0x15171b], [0x6a3fb0, 0xf2c230], [0xe6e6e6, 0xd8452b], [0x3a3d44, 0x2e9c8f]];
|
[0x5fae3b, 0x15171b], [0x6a3fb0, 0xf2c230], [0xe6e6e6, 0xd8452b], [0x3a3d44, 0x2e9c8f]];
|
||||||
const SELL = 0.5;
|
|
||||||
const HOTKEY = { weapon: 'hk_weapon', tower: 'hk_tower', gadget: 'hk_gadget' };
|
const HOTKEY = { weapon: 'hk_weapon', tower: 'hk_tower', gadget: 'hk_gadget' };
|
||||||
const GLYPH = { chassis: '🧱', motor: '⚙️', wheels: '🛞', battery: '🔋', armour: '🛡️', weapon: '🪓', tower: '🔥', gadget: '🧰' };
|
const GLYPH = { chassis: '🧱', motor: '⚙️', wheels: '🛞', battery: '🔋', armour: '🛡️', weapon: '🪓', tower: '🔥', gadget: '🧰' };
|
||||||
const ICO = { hp: ['ico_hp', '❤️'], armour: ['ico_armour', '🛡️'], speed: ['ico_speed', '⏱️'], weight: ['ico_weight', '⚖️'],
|
const ICO = { hp: ['ico_hp', '❤️'], armour: ['ico_armour', '🛡️'], speed: ['ico_speed', '⏱️'], weight: ['ico_weight', '⚖️'],
|
||||||
@@ -98,7 +97,7 @@
|
|||||||
if (eq) act = `<button disabled>${t('equipped')}</button>`;
|
if (eq) act = `<button disabled>${t('equipped')}</button>`;
|
||||||
else if (own) act = `<button class="primary" data-act="eq">${t('equip')}</button>`;
|
else if (own) act = `<button class="primary" data-act="eq">${t('equip')}</button>`;
|
||||||
else act = `<button class="primary" data-act="buy" ${save.money < p.cost ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(p.cost) })}</button>`;
|
else act = `<button class="primary" data-act="buy" ${save.money < p.cost ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(p.cost) })}</button>`;
|
||||||
if (p && own && !eq) act += `<button data-act="sell">${t('sell', { n: Kit.fmt(Math.round(p.cost * SELL)) })}</button>`;
|
if (p && own && !eq) act += `<button data-act="sell">${t('sell', { n: Kit.fmt(RC.Eco.sellValue(sel)) })}</button>`;
|
||||||
if (p && !own && save.money < p.cost) act += `<span class="muted">${t('need_money', { n: Kit.fmt(p.cost - save.money) })}</span>`;
|
if (p && !own && save.money < p.cost) act += `<span class="muted">${t('need_money', { n: Kit.fmt(p.cost - save.money) })}</span>`;
|
||||||
$('detail').innerHTML = `${RC.pic(p ? 'part_' + sel : null, p ? GLYPH[slot] : '✖')}
|
$('detail').innerHTML = `${RC.pic(p ? 'part_' + sel : null, p ? GLYPH[slot] : '✖')}
|
||||||
<div><div class="nm">${p ? p.name : t('none')}</div><div class="ds">${p ? t('pd_' + sel) : t('none_' + slot)}</div>
|
<div><div class="nm">${p ? p.name : t('none')}</div><div class="ds">${p ? t('pd_' + sel) : t('none_' + slot)}</div>
|
||||||
@@ -183,21 +182,18 @@
|
|||||||
}).join('');
|
}).join('');
|
||||||
$('fitted').querySelectorAll('.frow').forEach(el => { el.onclick = e => {
|
$('fitted').querySelectorAll('.frow').forEach(el => { el.onclick = e => {
|
||||||
if (el.dataset.edit) { slot = 'weapon'; opt.sfx.click(); render(); return; }
|
if (el.dataset.edit) { slot = 'weapon'; opt.sfx.click(); render(); return; }
|
||||||
if (e.target.dataset.rm) { const s = e.target.dataset.rm; opt.getSave().build[s] = null; opt.sfx.click(); opt.onSave(); opt.onBuild(); render(); return; }
|
if (e.target.dataset.rm) { const s = e.target.dataset.rm; if (!opt.act({ type: 'equip', slot: s, part: null }).ok) { opt.sfx.deny(); return; } opt.sfx.click(); opt.onSave(); opt.onBuild(); render(); return; }
|
||||||
slot = el.dataset.goto; sel = opt.getSave().build[slot] || null; topTab = 'build'; opt.sfx.click(); render();
|
slot = el.dataset.goto; sel = opt.getSave().build[slot] || null; topTab = 'build'; opt.sfx.click(); render();
|
||||||
}; });
|
}; });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// every economy change goes through opt.act (RC.Eco rules; online the server checks the same action)
|
||||||
function act2(what) {
|
function act2(what) {
|
||||||
const save = opt.getSave(), p = sel ? RC.PARTS[sel] : null;
|
const p = sel ? RC.PARTS[sel] : null;
|
||||||
if (what === 'buy' && p && save.money >= p.cost && !save.owned.includes(sel)) {
|
const a = what === 'buy' ? { type: 'buy', part: sel } : what === 'eq' ? { type: 'equip', slot, part: sel || null } : what === 'sell' ? { type: 'sell', part: sel } : null;
|
||||||
save.money -= p.cost; save.owned.push(sel); save.build[slot] = sel; opt.sfx.buy();
|
if (!a || !opt.act(a).ok) { opt.sfx.deny(); return; }
|
||||||
say(t('tip_bought', { name: p.name }));
|
if (what === 'eq') opt.sfx.click(); else opt.sfx.buy();
|
||||||
} else if (what === 'eq') {
|
if (what === 'buy' && p) say(t('tip_bought', { name: p.name }));
|
||||||
save.build[slot] = sel; opt.sfx.click();
|
|
||||||
} else if (what === 'sell' && p && save.build[slot] !== sel) {
|
|
||||||
save.owned = save.owned.filter(x => x !== sel); save.money += Math.round(p.cost * SELL); opt.sfx.buy();
|
|
||||||
} else { opt.sfx.deny(); return; }
|
|
||||||
opt.onSave(); opt.onBuild(); render();
|
opt.onSave(); opt.onBuild(); render();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
196
game/workshop.js
Normal file
196
game/workshop.js
Normal file
@@ -0,0 +1,196 @@
|
|||||||
|
/* Robot Clash - workshop extras: weapon/shape editor, paint tab with paint slots, hangar (several robots).
|
||||||
|
Part of game.js (split for size): created once by game.js with the shared context G.
|
||||||
|
Live state (save, mode, F, ...) is read as G.<name>; services/helpers are taken from G at creation. */
|
||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
const RC = (root.RC = root.RC || {});
|
||||||
|
RC.GameWorkshop = function (G) {
|
||||||
|
const {
|
||||||
|
$, GLYPH_SLOT, MAX_ROBOTS, SFX, act, esc, hud, layer, paintObj, painter, persist, shop, syncActive, t,
|
||||||
|
weaponName
|
||||||
|
} = G;
|
||||||
|
|
||||||
|
// ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ----
|
||||||
|
function refreshEditorRobot() { G.view.showGarage(G.save.build, paintObj()); G.view.freeze(true); G.view.setEditWeapon(G.editSel); }
|
||||||
|
function reDrawEditor() { persist(); hud(); refreshEditorRobot(); shop.render(); } // after a change: 3D + tabs + meters + editor
|
||||||
|
|
||||||
|
// weapon detail chips (mirrors the shop's part chips, weapon stats only)
|
||||||
|
function wChips(p) {
|
||||||
|
const s = [];
|
||||||
|
if (p.dmg) s.push(`<span>${t('st_dmg', { n: p.dmg })}</span>`);
|
||||||
|
if (p.dps) s.push(`<span>${t('st_dps', { n: p.dps })}</span>`);
|
||||||
|
if (p.range) s.push(`<span>${t('st_range', { n: p.range })}</span>`);
|
||||||
|
s.push(`<span class="key">⌨ ${t('hk_weapon')}</span>`);
|
||||||
|
s.push(`<span>⚖️ ${p.weight} kg</span>`);
|
||||||
|
if (p.power) s.push(`<span>⚡ ${p.power}</span>`);
|
||||||
|
return s.join('');
|
||||||
|
}
|
||||||
|
// show the clicked weapon live on the robot (a mounted one, else a temporary front preview)
|
||||||
|
function previewWeapon(id) {
|
||||||
|
const weps = G.save.build.weapons || [];
|
||||||
|
const idx = weps.findIndex(w => w.id === id);
|
||||||
|
if (idx >= 0) { G.editSel = idx; refreshEditorRobot(); }
|
||||||
|
else {
|
||||||
|
const pv = Object.assign({}, G.save.build, { weapons: weps.concat([{ id, side: 'front', up: 0 }]) });
|
||||||
|
G.view.showGarage(pv, paintObj()); G.view.freeze(true); G.view.setEditWeapon(weps.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function renderWeaponEditor() {
|
||||||
|
const cards = $('cards'), wp = $('wplace'); if (!G.save || !cards) return;
|
||||||
|
const b = G.save.build, weps = b.weapons || [];
|
||||||
|
G.editSel = Math.min(G.editSel, Math.max(0, weps.length - 1));
|
||||||
|
const cat = RC.partsFor('weapon');
|
||||||
|
const canAdd = weps.length < RC.MAX_WEAPONS;
|
||||||
|
if (!G.wPrev || !RC.PARTS[G.wPrev]) G.wPrev = (weps[G.editSel] && weps[G.editSel].id) || cat[0].id;
|
||||||
|
// right (#cards): the weapon catalog, same card grid as the other slots — click = preview
|
||||||
|
cards.className = '';
|
||||||
|
cards.innerHTML = cat.map(p => {
|
||||||
|
const mounted = weps.filter(w => w.id === p.id).length;
|
||||||
|
const badge = mounted ? `<span class="badge own">×${mounted}</span>` : '';
|
||||||
|
const price = `<div class="pr ${G.save.money < p.cost ? 'no' : ''}">🪙 ${Kit.fmt(p.cost)}</div>`;
|
||||||
|
return `<div class="item ${p.id === G.wPrev ? 'sel' : ''}" data-prev="${p.id}">${badge}${RC.pic('part_' + p.id, GLYPH_SLOT.weapon)}<div class="nm">${p.name}</div>${price}</div>`;
|
||||||
|
}).join('');
|
||||||
|
cards.querySelectorAll('[data-prev]').forEach(x => x.onclick = () => { G.wPrev = x.dataset.prev; SFX.click(); previewWeapon(G.wPrev); renderWeaponEditor(); });
|
||||||
|
// detail panel: previewed weapon + Montieren / Entfernen (like the other slots)
|
||||||
|
const dp = $('detail'), pv = RC.PARTS[G.wPrev];
|
||||||
|
if (dp && pv) {
|
||||||
|
const mounted = weps.filter(w => w.id === G.wPrev).length, poor = G.save.money < pv.cost;
|
||||||
|
let act = `<button class="primary" data-wact="add" ${(!canAdd || poor) ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(pv.cost) })}</button>`;
|
||||||
|
if (mounted) act += `<button data-wact="rem">${t('sell', { n: Kit.fmt(RC.Eco.sellValue(G.wPrev)) })}</button>`;
|
||||||
|
if (!canAdd) act += `<span class="muted">${t('ed_max', { n: RC.MAX_WEAPONS })}</span>`;
|
||||||
|
dp.innerHTML = `${RC.pic('part_' + G.wPrev, GLYPH_SLOT.weapon)}
|
||||||
|
<div><div class="nm">${pv.name}${mounted ? ` <span class="badge own">×${mounted}</span>` : ''}</div>
|
||||||
|
<div class="ds">${t('pd_' + G.wPrev)}</div><div class="chips">${wChips(pv)}</div></div>
|
||||||
|
<div class="act">${act}</div>`;
|
||||||
|
dp.querySelectorAll('button[data-wact]').forEach(x => x.onclick = () => {
|
||||||
|
if (x.dataset.wact === 'add') addWeapon(G.wPrev);
|
||||||
|
else { const i = weps.map(w => w.id).lastIndexOf(G.wPrev); if (i >= 0) removeWeapon(i); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// left (#wplace): placement of the active mounted weapon + shape (no sell list)
|
||||||
|
if (wp) {
|
||||||
|
const sel = weps[G.editSel];
|
||||||
|
const sides = [['front', t('mt_front')], ['back', t('mt_back')], ['left', t('mt_left')], ['right', t('mt_right')]];
|
||||||
|
const srow = (key, label, lo, hi) => { const val = (b.body && b.body[key]) || 1; return `<div class="wprow"><span>${t('des_' + label)}</span><input type="range" data-body="${key}" min="${lo}" max="${hi}" step="0.05" value="${val}"><span class="dv">${Math.round(val * 100)}%</span></div>`; };
|
||||||
|
wp.classList.remove('hide');
|
||||||
|
wp.innerHTML =
|
||||||
|
`<div class="wphead">${t('ed_weapons')} ${weps.length}/${RC.MAX_WEAPONS}</div>`
|
||||||
|
+ (sel ? `<div class="wphead">${t('ed_place')} — ${RC.PARTS[sel.id].name}</div>`
|
||||||
|
+ `<div class="wpsides">${sides.map(([k, lb]) => `<button data-side="${k}" class="${sel.side === k ? 'on' : ''}">${lb}</button>`).join('')}</div>`
|
||||||
|
+ `<div class="wprow"><span>${t('des_height')}</span><input type="range" id="edUp" min="-0.3" max="0.6" step="0.05" value="${sel.up || 0}"><span class="dv">${Math.round(((sel.up || 0) + 0.3) / 0.9 * 100)}%</span></div>`
|
||||||
|
: `<span class="edhint">${t('ed_noweapons')}</span>`)
|
||||||
|
+ `<div class="wphead">${t('s_body')}</div>${srow('hx', 'height', 0.7, 1.6)}${srow('wx', 'width', 0.8, 1.4)}${srow('lx', 'length', 0.8, 1.3)}`;
|
||||||
|
wp.querySelectorAll('[data-side]').forEach(x => x.onclick = () => { if (!sel) return; act({ type: 'weaponPlace', index: G.editSel, side: x.dataset.side }); SFX.click(); reDrawEditor(); });
|
||||||
|
if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } }; // live preview while dragging
|
||||||
|
if ($('edUp')) $('edUp').onchange = e => { if (sel) act({ type: 'weaponPlace', index: G.editSel, up: +e.target.value }); reDrawEditor(); };
|
||||||
|
wp.querySelectorAll('[data-body]').forEach(x => {
|
||||||
|
x.oninput = e => { b.body = b.body || { hx: 1, wx: 1, lx: 1 }; b.body[e.target.dataset.body] = +e.target.value; refreshEditorRobot(); };
|
||||||
|
x.onchange = e => { act({ type: 'body', [e.target.dataset.body]: +e.target.value }); reDrawEditor(); };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (weps[G.editSel] && weps[G.editSel].id === G.wPrev) G.view.setEditWeapon(G.editSel);
|
||||||
|
}
|
||||||
|
function addWeapon(id) {
|
||||||
|
if (!act({ type: 'weaponAdd', part: id }).ok) { SFX.deny(); return; }
|
||||||
|
G.editSel = G.save.build.weapons.length - 1; G.wPrev = id; G.view.setEditWeapon(G.editSel);
|
||||||
|
SFX.buy(); reDrawEditor();
|
||||||
|
}
|
||||||
|
function removeWeapon(i) {
|
||||||
|
if (!act({ type: 'weaponRemove', index: i }).ok) { SFX.deny(); return; }
|
||||||
|
if (G.editSel >= G.save.build.weapons.length) G.editSel = Math.max(0, G.save.build.weapons.length - 1);
|
||||||
|
G.view.setEditWeapon(G.editSel);
|
||||||
|
SFX.buy(); reDrawEditor();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- paint tab: 3 save slots + quick colours + the inline painter (all inside #cards) ----
|
||||||
|
const phex = c => '#' + (c >>> 0).toString(16).padStart(6, '0');
|
||||||
|
function paintTab(el) {
|
||||||
|
let hdr = $('paintHdr');
|
||||||
|
if (!hdr) { el.innerHTML = ''; hdr = document.createElement('div'); hdr.id = 'paintHdr'; hdr.className = 'phdr'; el.appendChild(hdr); }
|
||||||
|
$('shop').classList.add('paintmode'); // hide category tabs / detail / fitted bar while painting
|
||||||
|
renderPaintHeader(hdr);
|
||||||
|
if (!painter.isOpen) painter.open(el); // mount the painter inline, below the header
|
||||||
|
}
|
||||||
|
function paintLeave() {
|
||||||
|
$('shop').classList.remove('paintmode');
|
||||||
|
if (!painter.isOpen) return;
|
||||||
|
const art = painter.hasArt();
|
||||||
|
G.save.paint.decal = art ? layer.toDataURL('image/png') : null; G.save.paint.drawn = art;
|
||||||
|
painter.close(); persist();
|
||||||
|
const hdr = $('paintHdr'); if (hdr) hdr.remove();
|
||||||
|
}
|
||||||
|
function renderPaintHeader(hdr) {
|
||||||
|
const slots = G.save.paintSlots || [];
|
||||||
|
hdr.innerHTML =
|
||||||
|
`<div class="pslots">${slots.map((s, i) => `<div class="pslot ${i === G.save.paintSlot ? 'on' : ''}" data-load="${i}" style="background:${phex(s.body)}"><i class="acc" style="background:${phex(s.accent)}"></i>${s.decal ? '<span class="dmark">🖌</span>' : ''}<button class="sv" data-save="${i}">💾</button></div>`).join('')}</div>`
|
||||||
|
+ `<div class="psec"><h4>${t('paint_body')}</h4><div class="pgrid" id="paintBody"></div></div>`
|
||||||
|
+ `<div class="psec"><h4>${t('paint_accent')}</h4><div class="pgrid" id="paintAccent"></div></div>`
|
||||||
|
+ `<div class="psec"><h4>${t('paint_schemes')}</h4><div class="pgrid wide" id="paintSchemes"></div></div>`;
|
||||||
|
const lockP = c => (RC.PAINT_REWARDS || []).includes(c) && !(G.save.unlockedPaints || []).includes(c); // reward colour, not earned yet
|
||||||
|
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
|
||||||
|
$(id).innerHTML = RC.PAINTS.map(c => `<span class="sw ${G.save.paint[key] === c ? 'on' : ''} ${lockP(c) ? 'locked' : ''}" data-c="${c}" style="background:${phex(c)}" title="${lockP(c) ? t('paint_locked') : ''}">${lockP(c) ? '<span class="lk">🔒</span>' : ''}</span>`).join('');
|
||||||
|
$(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { if (sw.classList.contains('locked')) { SFX.deny && SFX.deny(); return; } G.save.paint[key] = +sw.dataset.c; SFX.click(); persist(); G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
|
||||||
|
}
|
||||||
|
$('paintSchemes').innerHTML = RC.SCHEMES.map(([b2, a2]) => { const on = G.save.paint.body === b2 && G.save.paint.accent === a2; return `<span class="sw duo ${on ? 'on' : ''}" data-b="${b2}" data-a="${a2}"><i style="background:${phex(b2)}"></i><i style="background:${phex(a2)}"></i></span>`; }).join('');
|
||||||
|
$('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { G.save.paint.body = +sw.dataset.b; G.save.paint.accent = +sw.dataset.a; SFX.click(); persist(); G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
|
||||||
|
hdr.querySelectorAll('[data-load]').forEach(x => x.onclick = e => { if (e.target.dataset.save) return; loadPaintSlot(+x.dataset.load); });
|
||||||
|
hdr.querySelectorAll('[data-save]').forEach(x => x.onclick = e => { e.stopPropagation(); savePaintSlot(+x.dataset.save); });
|
||||||
|
}
|
||||||
|
function loadPaintSlot(i) {
|
||||||
|
const s = G.save.paintSlots[i]; if (!s) return;
|
||||||
|
G.save.paintSlot = i;
|
||||||
|
G.save.paint.body = s.body; G.save.paint.accent = s.accent; G.save.paint.decal = s.decal || null; G.save.paint.drawn = !!s.drawn;
|
||||||
|
SFX.click(); persist();
|
||||||
|
RC.layerFromData(layer, G.save.paint.decal, () => { G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); });
|
||||||
|
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
|
||||||
|
}
|
||||||
|
function savePaintSlot(i) {
|
||||||
|
const art = painter.hasArt();
|
||||||
|
G.save.paintSlots[i] = { body: G.save.paint.body, accent: G.save.paint.accent, decal: art ? layer.toDataURL('image/png') : (G.save.paint.decal || null), drawn: art || !!G.save.paint.drawn };
|
||||||
|
G.save.paintSlot = i; SFX.buy(); persist();
|
||||||
|
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// hangar: switch / add / delete robot slots (owned parts are shared)
|
||||||
|
function switchRobot(i) {
|
||||||
|
if (i === G.save.active || !G.save.robots[i]) return;
|
||||||
|
syncActive();
|
||||||
|
if (!act({ type: 'robotSwitch', index: i }).ok) return;
|
||||||
|
persist();
|
||||||
|
RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); });
|
||||||
|
shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar();
|
||||||
|
}
|
||||||
|
function addRobot() {
|
||||||
|
syncActive();
|
||||||
|
if (!act({ type: 'robotNew', name: t('robot_n', { n: G.save.robots.length + 1 }) }).ok) { SFX.deny(); return; }
|
||||||
|
persist();
|
||||||
|
RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); });
|
||||||
|
shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar();
|
||||||
|
SFX.buy();
|
||||||
|
}
|
||||||
|
function delRobot(i) {
|
||||||
|
syncActive();
|
||||||
|
if (!act({ type: 'robotDelete', index: i }).ok) { SFX.deny(); return; }
|
||||||
|
persist(); RC.layerFromData(layer, G.save.paint.decal, () => {}); shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar();
|
||||||
|
}
|
||||||
|
// hangar management (shop top-tab): list of robots with weapon, switch / delete + add button
|
||||||
|
function renderHangar(el) {
|
||||||
|
el = el || $('cards'); if (!el) return;
|
||||||
|
const rows = G.save.robots.map((r, i) => `<div class="hmrow ${i === G.save.active ? 'on' : ''}" data-i="${i}">
|
||||||
|
<div><div class="hmn">${esc(r.name)}</div><div class="hmw">${esc(weaponName(r.build))}</div></div>
|
||||||
|
${i === G.save.active ? `<span class="muted" style="font-size:12px">${t('active_robot')}</span>` : `<button data-use="${i}">${t('use')}</button>`}
|
||||||
|
${G.save.robots.length > 1 ? `<button data-del="${i}" title="${t('delete')}">✕</button>` : '<span></span>'}</div>`).join('');
|
||||||
|
el.innerHTML = `<div class="hmgr">${rows}</div>
|
||||||
|
${G.save.robots.length < MAX_ROBOTS ? `<button class="primary" id="hAdd" style="margin-top:8px">+ ${t('new_robot')}</button>` : `<p class="muted" style="margin-top:8px">${t('hangar_full')}</p>`}`;
|
||||||
|
el.querySelectorAll('[data-use]').forEach(b => { b.onclick = () => { SFX.click(); switchRobot(+b.dataset.use); shop.setTab('build'); } ; });
|
||||||
|
el.querySelectorAll('[data-del]').forEach(b => { b.onclick = () => { SFX.click(); delRobot(+b.dataset.del); renderHangar(); } ; });
|
||||||
|
if ($('hAdd')) $('hAdd').onclick = () => { addRobot(); shop.setTab('build'); };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
refreshEditorRobot, reDrawEditor, wChips, previewWeapon, renderWeaponEditor, addWeapon, removeWeapon,
|
||||||
|
phex, paintTab, paintLeave, renderPaintHeader, loadPaintSlot, savePaintSlot, switchRobot, addRobot,
|
||||||
|
delRobot, renderHangar
|
||||||
|
};
|
||||||
|
};
|
||||||
|
})(window);
|
||||||
46
package-lock.json
generated
46
package-lock.json
generated
@@ -9,6 +9,7 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.5",
|
"@eslint/js": "^9.39.5",
|
||||||
|
"@playwright/test": "^1.65.1",
|
||||||
"eslint": "^9.39.5",
|
"eslint": "^9.39.5",
|
||||||
"globals": "^16.5.0",
|
"globals": "^16.5.0",
|
||||||
"terser": "^5.46.1"
|
"terser": "^5.46.1"
|
||||||
@@ -290,6 +291,22 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@playwright/test": {
|
||||||
|
"version": "1.65.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz",
|
||||||
|
"integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright": "1.65.1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@types/estree": {
|
"node_modules/@types/estree": {
|
||||||
"version": "1.0.10",
|
"version": "1.0.10",
|
||||||
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",
|
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",
|
||||||
@@ -1037,6 +1054,35 @@
|
|||||||
"node": ">=8"
|
"node": ">=8"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/playwright": {
|
||||||
|
"version": "1.65.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
|
||||||
|
"integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"dependencies": {
|
||||||
|
"playwright-core": "1.65.1"
|
||||||
|
},
|
||||||
|
"bin": {
|
||||||
|
"playwright": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/playwright-core": {
|
||||||
|
"version": "1.65.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
|
||||||
|
"integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "Apache-2.0",
|
||||||
|
"bin": {
|
||||||
|
"playwright-core": "cli.js"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/prelude-ls": {
|
"node_modules/prelude-ls": {
|
||||||
"version": "1.2.1",
|
"version": "1.2.1",
|
||||||
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
|
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
|
||||||
|
|||||||
@@ -14,10 +14,13 @@
|
|||||||
"balance": "node tests/balance.js -v",
|
"balance": "node tests/balance.js -v",
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"dev": "npm --prefix server run dev",
|
"dev": "npm --prefix server run dev",
|
||||||
"build:web": "node build-web.mjs"
|
"build:web": "node build-web.mjs",
|
||||||
|
"e2e": "playwright test",
|
||||||
|
"bot": "node tools/bot.js"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^9.39.5",
|
"@eslint/js": "^9.39.5",
|
||||||
|
"@playwright/test": "^1.65.1",
|
||||||
"eslint": "^9.39.5",
|
"eslint": "^9.39.5",
|
||||||
"globals": "^16.5.0",
|
"globals": "^16.5.0",
|
||||||
"terser": "^5.46.1"
|
"terser": "^5.46.1"
|
||||||
|
|||||||
32
playwright.config.js
Normal file
32
playwright.config.js
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
// Browser end-to-end tests (npm run e2e). Uses the installed Google Chrome (no browser download) and starts its own
|
||||||
|
// server on port 8099 with a fresh throw-away database (tests/e2e/server.js).
|
||||||
|
'use strict';
|
||||||
|
const { defineConfig } = require('@playwright/test');
|
||||||
|
|
||||||
|
const PORT = 8099;
|
||||||
|
|
||||||
|
module.exports = defineConfig({
|
||||||
|
testDir: 'tests/e2e',
|
||||||
|
testMatch: '**/*.spec.js',
|
||||||
|
timeout: 90 * 1000,
|
||||||
|
expect: { timeout: 15 * 1000 },
|
||||||
|
fullyParallel: false,
|
||||||
|
workers: 1,
|
||||||
|
retries: 0,
|
||||||
|
reporter: [['list']],
|
||||||
|
use: {
|
||||||
|
baseURL: `http://127.0.0.1:${PORT}`,
|
||||||
|
channel: 'chrome',
|
||||||
|
headless: true,
|
||||||
|
viewport: { width: 1280, height: 720 },
|
||||||
|
launchOptions: { args: ['--enable-unsafe-swiftshader', '--use-angle=swiftshader', '--autoplay-policy=no-user-gesture-required'] },
|
||||||
|
trace: 'retain-on-failure',
|
||||||
|
},
|
||||||
|
webServer: {
|
||||||
|
command: 'node tests/e2e/server.js',
|
||||||
|
url: `http://127.0.0.1:${PORT}/healthz`,
|
||||||
|
env: { PORT: String(PORT) },
|
||||||
|
reuseExistingServer: false,
|
||||||
|
timeout: 30 * 1000,
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -1,36 +1,56 @@
|
|||||||
# Robot Clash – Server
|
# Robot Clash – Server
|
||||||
|
|
||||||
Node-Backend: Konten, Spielstände, Rangliste, Lobby, Live-PvP und **server-autoritäres Geld**. Spiegelt die
|
Node-Backend für den Online-Modus: Konten, server-autoritative Wirtschaft (Geld, Ruhm, Teile, Roboter),
|
||||||
alte Firebase-Oberfläche (Auth + `/db`-REST + SSE), damit der Client nur die Basis-URL tauscht. Serviert
|
Rangliste, Live-Einstellungen, Lobby und **vom Server gerechnete Live-Kämpfe** über WebSocket. Liefert zusätzlich
|
||||||
zusätzlich das Spiel aus `../game` (gleiche Domain → kein CORS, kein Mixed-Content).
|
das Spiel aus `../game` und die Admin-Seite unter `/admin/` aus – alles auf einer Domain (kein CORS).
|
||||||
|
|
||||||
## Lokal starten (Windows, WSL oder Linux, Node ≥ 20.6)
|
## Lokal starten (Windows, WSL oder Linux, Node ≥ 20.6, empfohlen 24)
|
||||||
|
|
||||||
```
|
```
|
||||||
npm run setup # einmal im Repo-Root: Abhängigkeiten für Root + server/
|
npm run setup # einmal im Repo-Root: Abhängigkeiten für Root + server/
|
||||||
cp server/.env.example server/.env # einmal
|
cp server/.env.example server/.env # einmal
|
||||||
|
npm --prefix server run db:reset # frische DB mit den Testkonten michi / benni
|
||||||
npm run dev # Server mit Auto-Neustart auf http://localhost:8080
|
npm run dev # Server mit Auto-Neustart auf http://localhost:8080
|
||||||
```
|
```
|
||||||
|
|
||||||
Spiel unter `http://localhost:8080/`, Status unter `/healthz`. SQLite-Datei: `server/data.sqlite` (ignoriert).
|
Spiel unter `http://localhost:8080/`, Status unter `/healthz`, Admin unter `/admin/`.
|
||||||
Unter Linux braucht `better-sqlite3` evtl. einen Compiler: `sudo apt install -y build-essential python3`.
|
**Zwei Spieler in einem Browser testen:** `?online&slot=1` und `?online&slot=2` in zwei Tabs (getrennte Sitzungen).
|
||||||
|
Testkonten (nur Test-System, siehe CLAUDE.md): `michi` / `Michi2000!`, `benni` / `Benni2000!` – beide Admin.
|
||||||
|
|
||||||
## Tests
|
## Tests
|
||||||
|
|
||||||
`npm test` im Repo-Root startet Spiel- und Server-Tests. Server-Tests (`server/test/*.test.js`) starten den echten
|
`npm test` im Repo-Root. Server-Tests (`server/test/*.test.js`) starten den echten Server auf einem Zufallsport mit
|
||||||
Server auf einem Zufallsport mit In-Memory-DB (`test/helpers.js`).
|
In-Memory-DB und verbinden echte WebSocket-Clients (`test/helpers.js`, `fastForward()` spult Kämpfe vor).
|
||||||
|
|
||||||
|
## Aufbau
|
||||||
|
|
||||||
|
| Datei | Aufgabe |
|
||||||
|
|---|---|
|
||||||
|
| `app.js` | Express (REST + statisch) + HTTP-Server, hängt den WebSocket-Hub an |
|
||||||
|
| `auth.js` | Registrieren (Name + Passwort, E-Mail optional), Login (Name oder E-Mail), Gast, Refresh-Rotation, JWT |
|
||||||
|
| `db/index.js` + `db/migrations/*.sql` | SQLite, Migrationen laufen beim Start automatisch (Tabelle `schema_version`) |
|
||||||
|
| `economy.js` | Online-Spielstand je Spieler; Änderungen **nur** über `RC.Eco` (`game/eco.js`) und Kampfbelohnungen |
|
||||||
|
| `lobby.js` | Präsenz (= offene Verbindung), Herausforderungen, Match-Start, Ergebnis + Belohnung |
|
||||||
|
| `match/room.js` | ein Kampf: `RC.Combat.step` mit 60 Hz, Snapshots 20 Hz, Gnadenfrist + KI bei Verbindungsabbruch |
|
||||||
|
| `match/runner.js` | ein Timer für alle Räume |
|
||||||
|
| `ws/hub.js` | `/ws`: `hello` mit Token in 5 s, Validierung (`game/protocol.js`), Rate-Limit, Ping |
|
||||||
|
| `ratelimit.js` | Login/Registrieren begrenzt (pro IP) |
|
||||||
|
| `scripts/reset-db.js` | DB sichern + neu aufsetzen + Testkonten (`npm run db:reset`) |
|
||||||
|
|
||||||
## API (Kurzüberblick)
|
## API (Kurzüberblick)
|
||||||
|
|
||||||
- `POST /api/auth/register|login|guest|refresh|logout` → `{ idToken, refreshToken, uid, name, email }`
|
REST (Token als `Authorization: Bearer <idToken>`):
|
||||||
- `GET /api/wallet` (mit `?auth=<idToken>`) → `{ money, fame }` (nur lesen)
|
|
||||||
- `GET|PUT|PATCH|POST|DELETE /db/<pfad>.json?auth=<idToken>` – RTDB-kompatibel; `GET` mit
|
|
||||||
`Accept: text/event-stream` liefert Live-Updates (SSE). Schreibzugriff per `rules.js`.
|
|
||||||
- **Saves:** beim Schreiben von `saves/<uid>` entfernt der Server `money`/`fame` (die kommen nur aus dem Wallet).
|
|
||||||
|
|
||||||
## Nächste Schritte (noch offen, Plan 13)
|
- `POST /api/auth/register {name, pass, email?}` · `login {login, pass}` · `guest {name}` · `refresh` · `logout`
|
||||||
|
- `GET /api/online` – eigener Online-Spielstand · `POST /api/online/action {type, ...}` – Werkstatt-Aktion
|
||||||
|
(`buy`, `sell`, `equip`, `weaponAdd`, `weaponRemove`, `weaponPlace`, `body`, `robotNew`, `robotDelete`,
|
||||||
|
`robotSwitch`, `rename`, `devCoins` nur Admin) → `{ ok, error?, save }` · `PUT /api/online/save` – nur Kosmetik
|
||||||
|
- `GET|PUT /api/campaign` – Cloud-Kopie der Offline-Kampagne (registrierte Konten)
|
||||||
|
- `GET /api/ranks` · `GET /api/live` · `PUT /api/admin/live` · `GET|POST|DELETE /api/admin/events` (Admin)
|
||||||
|
- `GET /healthz`
|
||||||
|
|
||||||
- Client (`game/net.js`, `game.js`) auf diesen Server umstellen (Basis-URL, Auth-Mapping).
|
WebSocket `/ws` – Nachrichten siehe `game/protocol.js` (Versionsnummer `RC.Proto.VERSION`).
|
||||||
- Anti-Cheat: `/api/shop/buy|sell` + `/api/fight/claim` (Server re-simuliert Seed-Kämpfe), Geld nur so änderbar.
|
|
||||||
- Deploy: **per Skript/PowerShell** (Ansible verschoben) – Caddy (TLS) + systemd + ufw auf den Hetzner-Server,
|
## Deploy
|
||||||
DNS `play.michael-media.de` → Server.
|
|
||||||
|
Siehe `deploy/README.md`.
|
||||||
|
|||||||
146
server/app.js
146
server/app.js
@@ -1,98 +1,104 @@
|
|||||||
/* Robot Clash backend. Serves the static game and an API/DB that mirrors the old Firebase surface,
|
/* Robot Clash server: REST (accounts, online save + shop actions, campaign cloud save, ranking, live settings),
|
||||||
so game/net.js only swaps its base URL. Money/fame are server-authoritative (stripped from saves). */
|
WebSocket /ws (lobby + server-run live fights) and the static game from ../game - all on one origin. */
|
||||||
'use strict';
|
'use strict';
|
||||||
const express = require('express');
|
const http = require('http');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
|
const express = require('express');
|
||||||
const auth = require('./auth');
|
const auth = require('./auth');
|
||||||
const rules = require('./rules');
|
const economy = require('./economy');
|
||||||
const rtdb = require('./rtdb');
|
const { Matches, KV, CampaignSaves } = require('./db');
|
||||||
const eco = require('./economy');
|
const { rateLimit } = require('./ratelimit');
|
||||||
const { getTree, putTree, patchTree, pushTree, delTreeAt, norm } = require('./db');
|
const { createRunner } = require('./match/runner');
|
||||||
|
const { createLobby } = require('./lobby');
|
||||||
|
const hub = require('./ws/hub');
|
||||||
const pkg = require('./package.json');
|
const pkg = require('./package.json');
|
||||||
|
|
||||||
const STARTED = Date.now();
|
const STARTED = Date.now();
|
||||||
|
const runner = createRunner();
|
||||||
|
const lobby = createLobby({ runner, economy, matches: Matches });
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
app.use(express.json({ limit: '2mb', strict: false })); // strict:false so scalar values (e.g. a name string) parse too
|
app.set('trust proxy', 'loopback'); // behind Caddy: real client IP for the rate limiter
|
||||||
app.use(auth.auth); // sets req.uid / req.user (null if not logged in)
|
app.use(express.json({ limit: '1mb' }));
|
||||||
|
app.use(auth.middleware);
|
||||||
|
|
||||||
// --- health (deploy checks, monitoring) --------------------------------------------------------------
|
const run = fn => (req, res) => {
|
||||||
|
try { res.json(fn(req)); } catch (e) { if (!e.status) console.error(e); res.status(e.status || 500).json({ error: e.code || 'ERROR' }); }
|
||||||
|
};
|
||||||
|
const need = (req, admin) => {
|
||||||
|
if (!req.user) { const e = new Error('UNAUTH'); e.status = 401; e.code = 'UNAUTH'; throw e; }
|
||||||
|
if (admin && !req.user.admin) { const e = new Error('DENIED'); e.status = 403; e.code = 'DENIED'; throw e; }
|
||||||
|
return req.user;
|
||||||
|
};
|
||||||
|
const body = req => (req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {});
|
||||||
|
|
||||||
|
// --- health ------------------------------------------------------------------------------------------
|
||||||
app.get('/healthz', (_req, res) => res.json({
|
app.get('/healthz', (_req, res) => res.json({
|
||||||
ok: true, version: pkg.version, commit: process.env.GIT_COMMIT || null, uptime: Math.round((Date.now() - STARTED) / 1000),
|
ok: true, version: pkg.version, commit: process.env.GIT_COMMIT || null,
|
||||||
|
uptime: Math.round((Date.now() - STARTED) / 1000), players: lobby.players.size, matches: runner.rooms.size,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
function run(res, fn) { try { res.json(fn()); } catch (e) { res.status(e.status || 500).json({ error: e.code || 'ERROR' }); } }
|
// --- accounts ----------------------------------------------------------------------------------------
|
||||||
|
const authLimit = rateLimit({ name: 'auth', windowMs: 60000, max: process.env.NODE_ENV === 'test' ? 1000 : 20 });
|
||||||
|
app.post('/api/auth/register', authLimit, run(req => auth.register(body(req).name, body(req).pass, body(req).email)));
|
||||||
|
app.post('/api/auth/login', authLimit, run(req => auth.login(body(req).login || body(req).email, body(req).pass)));
|
||||||
|
app.post('/api/auth/guest', authLimit, run(req => auth.guest(body(req).name)));
|
||||||
|
app.post('/api/auth/refresh', run(req => auth.refresh(body(req).refreshToken)));
|
||||||
|
app.post('/api/auth/logout', run(req => { auth.logout(body(req).refreshToken); return { ok: true }; }));
|
||||||
|
// delete your own account (and with it every save and token) - smoke tests clean up with this, players may too
|
||||||
|
app.delete('/api/me', run(req => { const u = need(req); lobby.leave(u.uid); require('./db').Users.del.run(u.uid); return { ok: true }; }));
|
||||||
|
app.get('/api/me', (req, res) => res.json(req.user ? { uid: req.uid, name: req.user.name, guest: req.user.guest, admin: req.user.admin } : { uid: null, admin: false }));
|
||||||
|
|
||||||
// --- accounts --------------------------------------------------------------------------------------
|
// --- online save: read, shop/workshop actions (server-authoritative), cosmetics ------------------------
|
||||||
app.post('/api/auth/register', (req, res) => run(res, () => auth.register(req.body.email, req.body.pass, req.body.name)));
|
app.get('/api/online', run(req => economy.load(need(req).uid)));
|
||||||
app.post('/api/auth/login', (req, res) => run(res, () => auth.login(req.body.email, req.body.pass)));
|
app.post('/api/online/action', run(req => {
|
||||||
app.post('/api/auth/guest', (req, res) => run(res, () => auth.guest(req.body.name)));
|
const u = need(req), r = economy.action(u, body(req));
|
||||||
app.post('/api/auth/refresh', (req, res) => run(res, () => auth.refresh(req.body.refreshToken)));
|
if (r.ok) lobby.refresh(u.uid);
|
||||||
app.post('/api/auth/logout', (req, res) => { auth.logout(req.body.refreshToken); res.json({ ok: true }); });
|
return r;
|
||||||
|
}));
|
||||||
|
app.put('/api/online/save', run(req => { const u = need(req), s = economy.putCosmetics(u.uid, body(req)); lobby.refresh(u.uid); return s; }));
|
||||||
|
|
||||||
// --- who am I (is this account an admin? drives the in-game dev menu) -------------------------------
|
// --- campaign cloud save (registered accounts; offline game, client-trusted) --------------------------
|
||||||
app.get('/api/me', (req, res) => res.json({ uid: req.uid || null, admin: !!(req.uid && rules.ADMIN.includes(req.uid)) }));
|
app.get('/api/campaign', run(req => { const u = need(req); return CampaignSaves.get(u.uid); }));
|
||||||
|
app.put('/api/campaign', run(req => { const u = need(req); if (u.guest) return { ok: false }; CampaignSaves.put(u.uid, body(req)); return { ok: true }; }));
|
||||||
|
|
||||||
// --- wallet (read-only; changes only via validated actions, added in step 3) -----------------------
|
// --- ranking + live settings (public read) -----------------------------------------------------------
|
||||||
app.get('/api/wallet', (req, res) => { if (!req.uid) return res.status(401).json({ error: 'UNAUTH' }); res.json(eco.wallet(req.uid)); });
|
app.get('/api/ranks', run(req => economy.ranks(+req.query.n || 20)));
|
||||||
|
app.get('/api/live', run(() => KV.get('live')));
|
||||||
|
app.put('/api/admin/live', run(req => { need(req, true); KV.put('live', body(req)); return { ok: true }; }));
|
||||||
|
// event presets for the admin page
|
||||||
|
app.get('/api/admin/events', run(req => { need(req, true); return KV.get('admin.events') || {}; }));
|
||||||
|
app.post('/api/admin/events', run(req => {
|
||||||
|
need(req, true);
|
||||||
|
const all = KV.get('admin.events') || {}, key = Date.now().toString(36);
|
||||||
|
all[key] = body(req); KV.put('admin.events', all);
|
||||||
|
return { name: key };
|
||||||
|
}));
|
||||||
|
app.delete('/api/admin/events/:key', run(req => {
|
||||||
|
need(req, true);
|
||||||
|
const all = KV.get('admin.events') || {}; delete all[req.params.key]; KV.put('admin.events', all);
|
||||||
|
return { ok: true };
|
||||||
|
}));
|
||||||
|
|
||||||
// --- dev: admins may set their own coins while testing (money is still in the save for now) ---------
|
// --- admin page (writes need an admin account, checked above) -----------------------------------------
|
||||||
app.post('/api/dev/coins', (req, res) => {
|
app.use('/admin', express.static(path.join(__dirname, '..', 'admin'), { index: 'index.html' }));
|
||||||
if (!req.uid || !rules.ADMIN.includes(req.uid)) return res.status(403).json({ error: 'DENIED' });
|
|
||||||
res.json({ ok: true, money: eco.clampMoney(req.body && req.body.money) });
|
|
||||||
});
|
|
||||||
|
|
||||||
// --- RTDB-compatible façade: /db/<path>.json (GET also serves SSE) ----------------------------------
|
// --- static game (same origin: no CORS, no mixed content) --------------------------------------------
|
||||||
// Anti-cheat: once ANTICHEAT=1 (step 3, wallet wired) the save may not carry money/fame; until then keep them
|
|
||||||
// so the game runs unchanged on the new server (transport swap first).
|
|
||||||
const ANTICHEAT = process.env.ANTICHEAT === '1';
|
|
||||||
const stripSave = (p, v) => {
|
|
||||||
if (ANTICHEAT && norm(p).split('/')[0] === 'saves' && v && typeof v === 'object' && !Array.isArray(v)) { const c = { ...v }; delete c.money; delete c.fame; return c; }
|
|
||||||
return v;
|
|
||||||
};
|
|
||||||
app.get(/^\/db\/(.*)\.json$/, (req, res) => {
|
|
||||||
const p = req.params[0];
|
|
||||||
if ((req.headers.accept || '').includes('text/event-stream')) {
|
|
||||||
if (!rules.canRead(req, p)) return res.status(403).end();
|
|
||||||
return rtdb.subscribe(p, res);
|
|
||||||
}
|
|
||||||
if (!rules.canRead(req, p)) return res.status(403).json({ error: 'DENIED' });
|
|
||||||
res.json(getTree(p));
|
|
||||||
});
|
|
||||||
function write(req, res, kind) {
|
|
||||||
const p = req.params[0];
|
|
||||||
if (!rules.canWrite(req, p)) return res.status(403).json({ error: 'DENIED' });
|
|
||||||
(kind === 'put' ? putTree : patchTree)(p, stripSave(p, req.body));
|
|
||||||
rtdb.notify(p);
|
|
||||||
res.json(req.body);
|
|
||||||
}
|
|
||||||
app.put(/^\/db\/(.*)\.json$/, (req, res) => write(req, res, 'put'));
|
|
||||||
app.patch(/^\/db\/(.*)\.json$/, (req, res) => write(req, res, 'patch'));
|
|
||||||
app.post(/^\/db\/(.*)\.json$/, (req, res) => {
|
|
||||||
const p = req.params[0];
|
|
||||||
if (!rules.canWrite(req, p)) return res.status(403).json({ error: 'DENIED' });
|
|
||||||
const id = pushTree(p, stripSave(p, req.body)); rtdb.notify(p + '/' + id); res.json({ name: id });
|
|
||||||
});
|
|
||||||
app.delete(/^\/db\/(.*)\.json$/, (req, res) => {
|
|
||||||
const p = req.params[0];
|
|
||||||
if (!rules.canWrite(req, p)) return res.status(403).json({ error: 'DENIED' });
|
|
||||||
delTreeAt(p); rtdb.notify(p); res.json(null);
|
|
||||||
});
|
|
||||||
|
|
||||||
// --- static game (same origin: no CORS, no mixed content) ------------------------------------------
|
|
||||||
app.use(express.static(path.join(__dirname, '..', 'game'), {
|
app.use(express.static(path.join(__dirname, '..', 'game'), {
|
||||||
etag: true,
|
etag: true,
|
||||||
setHeaders(res, p) {
|
setHeaders(res, p) {
|
||||||
// images / fonts / audio rarely change -> cache hard (fast re-renders, no re-fetch flicker)
|
|
||||||
if (/\.(png|jpe?g|webp|gif|svg|woff2?|ttf|otf|mp3|ogg|wav|m4a)$/i.test(p)) res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
|
if (/\.(png|jpe?g|webp|gif|svg|woff2?|ttf|otf|mp3|ogg|wav|m4a)$/i.test(p)) res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
|
||||||
else res.setHeader('Cache-Control', 'no-cache'); // code/html: revalidate so deploys show up
|
else res.setHeader('Cache-Control', 'no-cache'); // code/html: revalidate so deploys show up
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// started directly (node app.js) -> listen; required by tests -> they call listen() themselves
|
const server = http.createServer(app);
|
||||||
|
const wss = hub.attach(server, { lobby });
|
||||||
|
|
||||||
|
// started directly (node app.js) -> listen; tests call listen(0) themselves
|
||||||
function listen(port = process.env.PORT || 8080) {
|
function listen(port = process.env.PORT || 8080) {
|
||||||
return new Promise(resolve => { const srv = app.listen(port, () => resolve(srv)); });
|
return new Promise(resolve => server.listen(port, () => resolve(server)));
|
||||||
}
|
}
|
||||||
if (require.main === module) listen().then(srv => console.log('Robot Clash server on :' + srv.address().port));
|
if (require.main === module) listen().then(srv => console.log('Robot Clash server on :' + srv.address().port));
|
||||||
|
|
||||||
module.exports = { app, listen };
|
module.exports = { app, server, wss, listen, runner, lobby };
|
||||||
|
|||||||
@@ -1,10 +1,9 @@
|
|||||||
/* Accounts: register / login / guest / refresh, JWT access tokens + rotating refresh tokens.
|
/* Accounts: register / login (name or e-mail) / guest / refresh. JWT access tokens + rotating refresh tokens. */
|
||||||
Shaped like the old Firebase auth so game/net.js only swaps the base URL. */
|
|
||||||
'use strict';
|
'use strict';
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
const bcrypt = require('bcryptjs');
|
const bcrypt = require('bcryptjs');
|
||||||
const jwt = require('jsonwebtoken');
|
const jwt = require('jsonwebtoken');
|
||||||
const { Users, Wallet, Tokens } = require('./db');
|
const { Users, Tokens } = require('./db');
|
||||||
|
|
||||||
// No secret configured -> random per process (tokens die on restart). Never fall back to a known string.
|
// No secret configured -> random per process (tokens die on restart). Never fall back to a known string.
|
||||||
const SECRET = process.env.JWT_SECRET || (() => {
|
const SECRET = process.env.JWT_SECRET || (() => {
|
||||||
@@ -13,55 +12,70 @@ const SECRET = process.env.JWT_SECRET || (() => {
|
|||||||
})();
|
})();
|
||||||
const ACCESS_TTL = 3600; // seconds
|
const ACCESS_TTL = 3600; // seconds
|
||||||
const REFRESH_TTL = 30 * 864e5; // 30 days (ms)
|
const REFRESH_TTL = 30 * 864e5; // 30 days (ms)
|
||||||
const START_MONEY = 800;
|
const MIN_PASS = 8;
|
||||||
|
|
||||||
const newUid = () => crypto.randomBytes(16).toString('hex');
|
const newUid = () => crypto.randomBytes(16).toString('hex');
|
||||||
const newRefresh = () => crypto.randomBytes(32).toString('hex');
|
const cleanName = n => Array.from(String(n || '')).filter(c => /[\p{L}\p{N} _-]/u.test(c)).join('').trim().slice(0, 18);
|
||||||
const cleanName = n => String(n || '').replace(/[^\p{L}\p{N} _-]/gu, '').trim().slice(0, 18);
|
function err(status, code) { const e = new Error(code); e.code = code; e.status = status; return e; }
|
||||||
function err(code, msg) { const e = new Error(msg); e.code = msg; e.status = code; return e; }
|
|
||||||
|
|
||||||
function issue(u) {
|
function issue(u) {
|
||||||
const idToken = jwt.sign({ uid: u.uid, name: u.name, guest: !!u.guest }, SECRET, { expiresIn: ACCESS_TTL });
|
const idToken = jwt.sign({ uid: u.uid, name: u.name, guest: !!u.guest, role: u.role }, SECRET, { expiresIn: ACCESS_TTL });
|
||||||
const refreshToken = newRefresh();
|
const refreshToken = crypto.randomBytes(32).toString('hex');
|
||||||
Tokens.insert.run(refreshToken, u.uid, Date.now() + REFRESH_TTL);
|
Tokens.insert.run(refreshToken, u.uid, Date.now() + REFRESH_TTL);
|
||||||
return { idToken, refreshToken, uid: u.uid, name: u.name, email: u.email || '', expiresIn: ACCESS_TTL };
|
Users.seen.run(Date.now(), u.uid);
|
||||||
|
return { idToken, refreshToken, uid: u.uid, name: u.name, email: u.email || '', guest: !!u.guest, admin: u.role === 'admin', expiresIn: ACCESS_TTL };
|
||||||
}
|
}
|
||||||
|
|
||||||
function register(email, pass, name) {
|
function createUser({ name, pass, email, role = 'player', guest = false }) {
|
||||||
email = String(email || '').trim().toLowerCase();
|
const now = Date.now();
|
||||||
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) throw err(400, 'INVALID_EMAIL');
|
const u = {
|
||||||
if (String(pass || '').length < 6) throw err(400, 'WEAK_PASSWORD');
|
uid: newUid(), name, uname: guest ? null : name.toLowerCase(), email: email || null,
|
||||||
if (Users.byEmail.get(email)) throw err(409, 'EMAIL_EXISTS');
|
pass: pass ? bcrypt.hashSync(String(pass), 10) : null, role, guest: guest ? 1 : 0, created: now, seen: now,
|
||||||
const u = { uid: newUid(), email, pass: bcrypt.hashSync(String(pass), 10), name: cleanName(name) || email.split('@')[0], guest: 0, created: Date.now() };
|
};
|
||||||
Users.insert.run(u); Wallet.init.run(u.uid, START_MONEY);
|
Users.insert.run(u);
|
||||||
return issue(u);
|
return u;
|
||||||
}
|
}
|
||||||
function login(email, pass) {
|
|
||||||
email = String(email || '').trim().toLowerCase();
|
function register(name, pass, email) {
|
||||||
const u = Users.byEmail.get(email);
|
name = cleanName(name);
|
||||||
|
email = String(email || '').trim().toLowerCase() || null;
|
||||||
|
if (name.length < 3) throw err(400, 'BAD_NAME');
|
||||||
|
if (email && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) throw err(400, 'INVALID_EMAIL');
|
||||||
|
if (String(pass || '').length < MIN_PASS) throw err(400, 'WEAK_PASSWORD');
|
||||||
|
if (Users.byLogin.get(name, email || name)) throw err(409, 'NAME_EXISTS');
|
||||||
|
if (email && Users.byLogin.get(email, email)) throw err(409, 'EMAIL_EXISTS');
|
||||||
|
return issue(createUser({ name, pass, email }));
|
||||||
|
}
|
||||||
|
function login(loginName, pass) {
|
||||||
|
const l = String(loginName || '').trim().toLowerCase();
|
||||||
|
const u = l && Users.byLogin.get(l, l);
|
||||||
if (!u || !u.pass || !bcrypt.compareSync(String(pass || ''), u.pass)) throw err(400, 'INVALID_LOGIN');
|
if (!u || !u.pass || !bcrypt.compareSync(String(pass || ''), u.pass)) throw err(400, 'INVALID_LOGIN');
|
||||||
return issue(u);
|
return issue(u);
|
||||||
}
|
}
|
||||||
function guest(name) {
|
function guest(name) { return issue(createUser({ name: cleanName(name) || 'Guest', guest: true })); }
|
||||||
const u = { uid: newUid(), email: null, pass: null, name: cleanName(name) || 'Guest', guest: 1, created: Date.now() };
|
|
||||||
Users.insert.run(u); Wallet.init.run(u.uid, START_MONEY);
|
|
||||||
return issue(u);
|
|
||||||
}
|
|
||||||
function refresh(refreshToken) {
|
function refresh(refreshToken) {
|
||||||
const row = Tokens.get.get(refreshToken || '');
|
const row = Tokens.get.get(String(refreshToken || ''));
|
||||||
if (!row || row.exp < Date.now()) throw err(401, 'INVALID_REFRESH');
|
if (!row || row.exp < Date.now()) throw err(401, 'INVALID_REFRESH');
|
||||||
const u = Users.byId.get(row.uid);
|
const u = Users.byId.get(row.uid);
|
||||||
if (!u) throw err(401, 'INVALID_REFRESH');
|
if (!u) throw err(401, 'INVALID_REFRESH');
|
||||||
Tokens.del.run(refreshToken); // rotate
|
Tokens.del.run(row.token); // rotate: every refresh token works once
|
||||||
return issue(u);
|
return issue(u);
|
||||||
}
|
}
|
||||||
function logout(refreshToken) { if (refreshToken) Tokens.del.run(refreshToken); }
|
function logout(refreshToken) { if (refreshToken) Tokens.del.run(String(refreshToken)); }
|
||||||
|
|
||||||
// express middleware: reads ?auth=<idToken> or Authorization: Bearer, sets req.uid / req.user (or null)
|
// a token only counts while its account exists (deleted account / database reset -> the client must log in again)
|
||||||
function auth(req, _res, next) {
|
function verify(token) {
|
||||||
const tok = req.query.auth || (req.headers.authorization || '').replace(/^Bearer\s+/i, '');
|
let d;
|
||||||
try { const d = jwt.verify(tok, SECRET); req.uid = d.uid; req.user = d; } catch (e) { req.uid = null; req.user = null; }
|
try { d = jwt.verify(String(token || ''), SECRET); } catch (e) { return null; }
|
||||||
|
const u = Users.byId.get(d.uid);
|
||||||
|
return u ? { uid: u.uid, name: u.name, guest: !!u.guest, admin: u.role === 'admin' } : null;
|
||||||
|
}
|
||||||
|
// express middleware: Authorization: Bearer <idToken> (or ?auth= for old clients) -> req.user / req.uid
|
||||||
|
function middleware(req, _res, next) {
|
||||||
|
const tok = (req.headers.authorization || '').replace(/^Bearer\s+/i, '') || req.query.auth;
|
||||||
|
req.user = tok ? verify(tok) : null;
|
||||||
|
req.uid = req.user ? req.user.uid : null;
|
||||||
next();
|
next();
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { register, login, guest, refresh, logout, auth, cleanName };
|
module.exports = { register, login, guest, refresh, logout, verify, middleware, createUser, cleanName, MIN_PASS };
|
||||||
|
|||||||
109
server/db.js
109
server/db.js
@@ -1,109 +0,0 @@
|
|||||||
/* SQLite storage: real tables for accounts/wallet, plus a path-keyed "nodes" table that behaves
|
|
||||||
like a shallow Firebase-RTDB tree (so the client's db.get/put/patch/del/stream map 1:1). */
|
|
||||||
'use strict';
|
|
||||||
const path = require('path');
|
|
||||||
const Database = require('better-sqlite3');
|
|
||||||
|
|
||||||
const DB_FILE = process.env.DB_FILE || path.join(__dirname, 'data.sqlite');
|
|
||||||
const db = new Database(DB_FILE);
|
|
||||||
db.pragma('journal_mode = WAL');
|
|
||||||
db.exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS users (uid TEXT PRIMARY KEY, email TEXT UNIQUE, pass TEXT, name TEXT, guest INTEGER DEFAULT 0, created INTEGER);
|
|
||||||
CREATE TABLE IF NOT EXISTS tokens (token TEXT PRIMARY KEY, uid TEXT, exp INTEGER);
|
|
||||||
CREATE TABLE IF NOT EXISTS wallet (uid TEXT PRIMARY KEY, money INTEGER DEFAULT 800, fame INTEGER DEFAULT 0);
|
|
||||||
CREATE TABLE IF NOT EXISTS nodes (path TEXT PRIMARY KEY, data TEXT, ts INTEGER);
|
|
||||||
`);
|
|
||||||
|
|
||||||
const parse = s => { try { return JSON.parse(s); } catch (e) { return null; } };
|
|
||||||
const norm = p => String(p || '').replace(/^\/+|\/+$/g, '');
|
|
||||||
|
|
||||||
// Firebase server values: the client sends { ".sv": "timestamp" } for "server time" (lobby heartbeat etc).
|
|
||||||
// Resolve it to the real time on write, otherwise ts stays an object and presence filtering breaks.
|
|
||||||
function resolveSV(v) {
|
|
||||||
if (Array.isArray(v)) return v.map(resolveSV);
|
|
||||||
if (v && typeof v === 'object') {
|
|
||||||
if (v['.sv'] === 'timestamp') return Date.now();
|
|
||||||
const o = {}; for (const k in v) o[k] = resolveSV(v[k]); return o;
|
|
||||||
}
|
|
||||||
return v;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- RTDB-like tree over the nodes table ---------------------------------------------------------
|
|
||||||
// objects are stored as ONE json node, so a deep path (e.g. matches/<id>/meta/seed) has no own row -
|
|
||||||
// read it from the nearest ancestor blob by descending into its parsed json (Firebase-like deep reads)
|
|
||||||
function readInside(p) {
|
|
||||||
const seg = p.split('/');
|
|
||||||
for (let i = seg.length - 1; i >= 1; i--) {
|
|
||||||
const row = db.prepare('SELECT data FROM nodes WHERE path = ?').get(seg.slice(0, i).join('/'));
|
|
||||||
if (!row) continue;
|
|
||||||
let v = parse(row.data);
|
|
||||||
for (let j = i; j < seg.length; j++) { if (v && typeof v === 'object' && !Array.isArray(v)) v = v[seg[j]]; else { v = undefined; break; } }
|
|
||||||
return v === undefined ? null : v;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
function getTree(p) {
|
|
||||||
p = norm(p);
|
|
||||||
const like = p ? p + '/%' : '%';
|
|
||||||
const rows = p
|
|
||||||
? db.prepare('SELECT path, data FROM nodes WHERE path = ? OR path LIKE ?').all(p, like)
|
|
||||||
: db.prepare('SELECT path, data FROM nodes').all();
|
|
||||||
if (!rows.length) return p ? readInside(p) : null;
|
|
||||||
let result;
|
|
||||||
rows.sort((a, b) => a.path.length - b.path.length);
|
|
||||||
for (const row of rows) {
|
|
||||||
const val = parse(row.data);
|
|
||||||
if (row.path === p) { result = val; continue; }
|
|
||||||
const rel = (p ? row.path.slice(p.length + 1) : row.path).split('/');
|
|
||||||
if (result == null || typeof result !== 'object') result = {};
|
|
||||||
let o = result;
|
|
||||||
for (let i = 0; i < rel.length - 1; i++) { if (o[rel[i]] == null || typeof o[rel[i]] !== 'object') o[rel[i]] = {}; o = o[rel[i]]; }
|
|
||||||
o[rel[rel.length - 1]] = val;
|
|
||||||
}
|
|
||||||
return result === undefined ? null : result;
|
|
||||||
}
|
|
||||||
|
|
||||||
const setNode = db.prepare('INSERT INTO nodes (path, data, ts) VALUES (?, ?, ?) ON CONFLICT(path) DO UPDATE SET data = excluded.data, ts = excluded.ts');
|
|
||||||
const delTree = db.prepare('DELETE FROM nodes WHERE path = ? OR path LIKE ?');
|
|
||||||
|
|
||||||
function putTree(p, value) { // replace the whole subtree at p
|
|
||||||
p = norm(p);
|
|
||||||
value = resolveSV(value);
|
|
||||||
delTree.run(p, p + '/%');
|
|
||||||
if (value !== null && value !== undefined) setNode.run(p, JSON.stringify(value), Date.now());
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
function patchTree(p, value) { // merge object fields into p (shallow)
|
|
||||||
p = norm(p);
|
|
||||||
value = resolveSV(value);
|
|
||||||
if (value == null || typeof value !== 'object') return putTree(p, value);
|
|
||||||
const cur = getTree(p) || {};
|
|
||||||
for (const [k, v] of Object.entries(value)) { if (v === null) delete cur[k]; else cur[k] = v; }
|
|
||||||
return putTree(p, cur);
|
|
||||||
}
|
|
||||||
function pushTree(p, value) { // append with a time-sortable id (like Firebase push)
|
|
||||||
const id = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
|
|
||||||
putTree(norm(p) + '/' + id, value);
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
function delTreeAt(p) { p = norm(p); delTree.run(p, p + '/%'); }
|
|
||||||
|
|
||||||
// --- accounts / wallet ---------------------------------------------------------------------------
|
|
||||||
const Users = {
|
|
||||||
byEmail: db.prepare('SELECT * FROM users WHERE email = ?'),
|
|
||||||
byId: db.prepare('SELECT * FROM users WHERE uid = ?'),
|
|
||||||
insert: db.prepare('INSERT INTO users (uid, email, pass, name, guest, created) VALUES (@uid, @email, @pass, @name, @guest, @created)'),
|
|
||||||
setName: db.prepare('UPDATE users SET name = ? WHERE uid = ?'),
|
|
||||||
};
|
|
||||||
const Wallet = {
|
|
||||||
get: db.prepare('SELECT money, fame FROM wallet WHERE uid = ?'),
|
|
||||||
init: db.prepare('INSERT OR IGNORE INTO wallet (uid, money, fame) VALUES (?, ?, 0)'),
|
|
||||||
set: db.prepare('UPDATE wallet SET money = ?, fame = ? WHERE uid = ?'),
|
|
||||||
};
|
|
||||||
const Tokens = {
|
|
||||||
insert: db.prepare('INSERT OR REPLACE INTO tokens (token, uid, exp) VALUES (?, ?, ?)'),
|
|
||||||
get: db.prepare('SELECT * FROM tokens WHERE token = ?'),
|
|
||||||
del: db.prepare('DELETE FROM tokens WHERE token = ?'),
|
|
||||||
};
|
|
||||||
|
|
||||||
module.exports = { db, getTree, putTree, patchTree, pushTree, delTreeAt, norm, Users, Wallet, Tokens };
|
|
||||||
71
server/db/index.js
Normal file
71
server/db/index.js
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
/* SQLite access. Opens DB_FILE (':memory:' in tests), applies pending migrations from ./migrations
|
||||||
|
(NNN_name.sql, in order, each once - tracked in schema_version) and exposes small repositories. */
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
const Database = require('better-sqlite3');
|
||||||
|
|
||||||
|
const DB_FILE = process.env.DB_FILE || path.join(__dirname, '..', 'data.sqlite');
|
||||||
|
const db = new Database(DB_FILE);
|
||||||
|
db.pragma('journal_mode = WAL');
|
||||||
|
db.pragma('foreign_keys = ON');
|
||||||
|
|
||||||
|
function migrate() {
|
||||||
|
db.exec('CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY, name TEXT, applied INTEGER)');
|
||||||
|
const done = new Set(db.prepare('SELECT version FROM schema_version').all().map(r => r.version));
|
||||||
|
const dir = path.join(__dirname, 'migrations');
|
||||||
|
const files = fs.readdirSync(dir).filter(f => /^\d+_.+\.sql$/.test(f)).sort();
|
||||||
|
for (const f of files) {
|
||||||
|
const v = parseInt(f, 10);
|
||||||
|
if (done.has(v)) continue;
|
||||||
|
db.transaction(() => {
|
||||||
|
db.exec(fs.readFileSync(path.join(dir, f), 'utf8'));
|
||||||
|
db.prepare('INSERT INTO schema_version (version, name, applied) VALUES (?, ?, ?)').run(v, f, Date.now());
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
migrate();
|
||||||
|
|
||||||
|
const json = s => { try { return JSON.parse(s); } catch (e) { return null; } };
|
||||||
|
|
||||||
|
const Users = {
|
||||||
|
byId: db.prepare('SELECT * FROM users WHERE uid = ?'),
|
||||||
|
byLogin: db.prepare('SELECT * FROM users WHERE uname = lower(?) OR email = lower(?)'),
|
||||||
|
insert: db.prepare('INSERT INTO users (uid, name, uname, email, pass, role, guest, created, seen) VALUES (@uid, @name, @uname, @email, @pass, @role, @guest, @created, @seen)'),
|
||||||
|
seen: db.prepare('UPDATE users SET seen = ? WHERE uid = ?'),
|
||||||
|
del: db.prepare('DELETE FROM users WHERE uid = ?'), // cascades to tokens + saves
|
||||||
|
staleGuests: db.prepare('DELETE FROM users WHERE guest = 1 AND seen < ?'),
|
||||||
|
};
|
||||||
|
const Tokens = {
|
||||||
|
insert: db.prepare('INSERT INTO refresh_tokens (token, uid, exp) VALUES (?, ?, ?)'),
|
||||||
|
get: db.prepare('SELECT * FROM refresh_tokens WHERE token = ?'),
|
||||||
|
del: db.prepare('DELETE FROM refresh_tokens WHERE token = ?'),
|
||||||
|
purge: db.prepare('DELETE FROM refresh_tokens WHERE exp < ?'),
|
||||||
|
};
|
||||||
|
const OnlineSaves = {
|
||||||
|
_get: db.prepare('SELECT data FROM online_saves WHERE uid = ?'),
|
||||||
|
_put: db.prepare('INSERT INTO online_saves (uid, data, fame, updated) VALUES (?, ?, ?, ?) ON CONFLICT(uid) DO UPDATE SET data = excluded.data, fame = excluded.fame, updated = excluded.updated'),
|
||||||
|
_top: db.prepare(`SELECT u.uid, u.name, o.fame, o.data FROM online_saves o JOIN users u ON u.uid = o.uid
|
||||||
|
WHERE o.fame > 0 ORDER BY o.fame DESC, o.updated ASC LIMIT ?`),
|
||||||
|
get(uid) { const r = this._get.get(uid); return r ? json(r.data) : null; },
|
||||||
|
put(uid, save) { this._put.run(uid, JSON.stringify(save), save.fame | 0, Date.now()); },
|
||||||
|
top(n) { return this._top.all(n).map(r => { const d = json(r.data) || {}; return { uid: r.uid, name: r.name, fame: r.fame, flag: d.flag || 'XX' }; }); },
|
||||||
|
};
|
||||||
|
const CampaignSaves = {
|
||||||
|
_get: db.prepare('SELECT data FROM campaign_saves WHERE uid = ?'),
|
||||||
|
_put: db.prepare('INSERT INTO campaign_saves (uid, data, updated) VALUES (?, ?, ?) ON CONFLICT(uid) DO UPDATE SET data = excluded.data, updated = excluded.updated'),
|
||||||
|
get(uid) { const r = this._get.get(uid); return r ? json(r.data) : null; },
|
||||||
|
put(uid, data) { this._put.run(uid, JSON.stringify(data), Date.now()); },
|
||||||
|
};
|
||||||
|
const Matches = {
|
||||||
|
start: db.prepare('INSERT INTO matches (id, seed, arena, uid0, uid1, started) VALUES (?, ?, ?, ?, ?, ?)'),
|
||||||
|
end: db.prepare('UPDATE matches SET winner = ?, reason = ?, ended = ? WHERE id = ?'),
|
||||||
|
};
|
||||||
|
const KV = {
|
||||||
|
_get: db.prepare('SELECT value FROM kv WHERE key = ?'),
|
||||||
|
_put: db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'),
|
||||||
|
get(k) { const r = this._get.get(k); return r ? json(r.value) : null; },
|
||||||
|
put(k, v) { this._put.run(k, JSON.stringify(v)); },
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = { db, DB_FILE, migrate, Users, Tokens, OnlineSaves, CampaignSaves, Matches, KV };
|
||||||
46
server/db/migrations/001_init.sql
Normal file
46
server/db/migrations/001_init.sql
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
-- Robot Clash schema v1. Online saves are one JSON document per player; the server changes their economy
|
||||||
|
-- fields only through game/eco.js (same rules as the client), so a document stays consistent.
|
||||||
|
CREATE TABLE users (
|
||||||
|
uid TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL, -- display name
|
||||||
|
uname TEXT UNIQUE, -- login name, lower case (NULL for guests)
|
||||||
|
email TEXT UNIQUE, -- optional
|
||||||
|
pass TEXT, -- bcrypt hash (NULL for guests)
|
||||||
|
role TEXT NOT NULL DEFAULT 'player',-- player | admin
|
||||||
|
guest INTEGER NOT NULL DEFAULT 0,
|
||||||
|
created INTEGER NOT NULL,
|
||||||
|
seen INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE refresh_tokens (
|
||||||
|
token TEXT PRIMARY KEY,
|
||||||
|
uid TEXT NOT NULL REFERENCES users(uid) ON DELETE CASCADE,
|
||||||
|
exp INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX refresh_tokens_uid ON refresh_tokens(uid);
|
||||||
|
CREATE TABLE online_saves (
|
||||||
|
uid TEXT PRIMARY KEY REFERENCES users(uid) ON DELETE CASCADE,
|
||||||
|
data TEXT NOT NULL,
|
||||||
|
fame INTEGER NOT NULL DEFAULT 0, -- copy of data.fame for the ranking
|
||||||
|
updated INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX online_saves_fame ON online_saves(fame DESC);
|
||||||
|
CREATE TABLE campaign_saves ( -- offline campaign mirrored for registered accounts (client-trusted)
|
||||||
|
uid TEXT PRIMARY KEY REFERENCES users(uid) ON DELETE CASCADE,
|
||||||
|
data TEXT NOT NULL,
|
||||||
|
updated INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE matches (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
seed INTEGER NOT NULL,
|
||||||
|
arena TEXT NOT NULL,
|
||||||
|
uid0 TEXT NOT NULL,
|
||||||
|
uid1 TEXT NOT NULL,
|
||||||
|
winner INTEGER, -- seat 0 / 1, -1 draw, NULL running
|
||||||
|
reason TEXT,
|
||||||
|
started INTEGER NOT NULL,
|
||||||
|
ended INTEGER
|
||||||
|
);
|
||||||
|
CREATE TABLE kv ( -- small settings, e.g. 'live' (admin live control)
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
@@ -1,53 +1,65 @@
|
|||||||
# Robot Clash – Deploy auf den Hetzner-Server
|
# Robot Clash – Deploy auf den Hetzner-Server (Dev/Test-System)
|
||||||
|
|
||||||
Spiel + API laufen auf **einem** Server unter `https://roboclash.michael-media.de/` (Caddy macht TLS automatisch,
|
Spiel + API laufen auf **einem** Server unter `https://roboclash.michael-media.de/` (Caddy macht TLS automatisch und
|
||||||
reverse-proxyt auf den Node-Dienst). Kein Ansible nötig – ein Setup-Skript + ein PowerShell-Push.
|
leitet an den Node-Dienst weiter, WebSocket `/ws` inklusive). Alle Befehle aus dem Repo-Root in **Git Bash**
|
||||||
|
(Windows) oder einer Linux-Shell; SSH-Zugang `root@roboclash.michael-media.de` per Schlüssel.
|
||||||
|
|
||||||
## 0) DNS (einmal)
|
## Aufbau auf dem Server
|
||||||
Beim DNS-Anbieter von `michael-media.de` einen **A-Record** anlegen:
|
|
||||||
`roboclash` → `91.99.166.238` (die Server-IP). Kurz warten, bis er aktiv ist.
|
|
||||||
|
|
||||||
## 1) Server einrichten (einmal, von Windows PowerShell)
|
|
||||||
```powershell
|
|
||||||
scp server\deploy\setup.sh root@91.99.166.238:/root/
|
|
||||||
ssh root@91.99.166.238 "bash /root/setup.sh roboclash.michael-media.de"
|
|
||||||
```
|
```
|
||||||
Das installiert Node + Caddy, legt den systemd-Dienst, die Firewall (ufw) und ein tägliches DB-Backup an und
|
/opt/robotclash/
|
||||||
schreibt `/opt/robotclash/server/.env` mit zufälligem `JWT_SECRET`.
|
releases/<zeit>-<commit>/ je Deploy ein vollständiges Release (game/, server/, admin/, tools/), die letzten 5 bleiben
|
||||||
|
current -> releases/... aktives Release (Symlink)
|
||||||
## 2) Code hochladen + starten
|
shared/.env PORT, JWT_SECRET, DB_FILE (bleibt über Deploys erhalten, nur root/Dienst lesbar)
|
||||||
```powershell
|
shared/data.sqlite Datenbank
|
||||||
.\server\deploy\push.ps1
|
backups/ pre-<release>.sqlite vor jedem Deploy, daily-<datum>.sqlite (cron, 14 Tage)
|
||||||
ssh root@91.99.166.238 "systemctl start robotclash"
|
|
||||||
```
|
|
||||||
Fertig → **https://roboclash.michael-media.de/** (TLS kommt beim ersten Aufruf automatisch; ein paar Sekunden).
|
|
||||||
|
|
||||||
## 3) Updates später
|
|
||||||
Einfach erneut:
|
|
||||||
```powershell
|
|
||||||
.\server\deploy\push.ps1
|
|
||||||
```
|
|
||||||
(lädt Spiel + Server neu hoch, `npm ci`, startet den Dienst neu). `.env` und die Datenbank bleiben erhalten.
|
|
||||||
|
|
||||||
## Admin werden (für die Live-Steuerung / `/db/live`)
|
|
||||||
Im Spiel registrieren, dann auf dem Server die uid holen und in die `.env` eintragen:
|
|
||||||
```
|
|
||||||
ssh root@91.99.166.238
|
|
||||||
sqlite3 /opt/robotclash/server/data.sqlite "select uid,email from users"
|
|
||||||
nano /opt/robotclash/server/.env # ADMIN_UID=<deine uid>
|
|
||||||
systemctl restart robotclash
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Anti-Cheat scharf schalten (nach Schritt 3 der Umsetzung)
|
Dienst `robotclash` (systemd) läuft als eigener Nutzer `robotclash`, darf nur nach `shared/` schreiben.
|
||||||
In `.env` `ANTICHEAT=1` setzen + `systemctl restart robotclash`. Dann entfernt der Server `money`/`fame` aus
|
|
||||||
`saves/` und Geld läuft nur noch über die Server-Endpunkte. **Vorher** muss der Client-Geldfluss umgestellt sein,
|
## 1) Server einrichten (einmal; erneut ausführen schadet nicht)
|
||||||
sonst steht das Geld auf 0.
|
|
||||||
|
```bash
|
||||||
|
scp server/deploy/setup.sh root@roboclash.michael-media.de:/root/
|
||||||
|
ssh root@roboclash.michael-media.de "bash /root/setup.sh roboclash.michael-media.de"
|
||||||
|
```
|
||||||
|
|
||||||
|
Installiert Node 24 + Caddy, legt Nutzer, Ordner, Dienst, Firewall und Backup an. Ein altes Layout
|
||||||
|
(`/opt/robotclash/server`, `/game`) wird nach `/opt/robotclash/legacy-<datum>/` verschoben, `JWT_SECRET` übernommen.
|
||||||
|
|
||||||
|
## 2) Deployen
|
||||||
|
|
||||||
|
```bash
|
||||||
|
bash server/deploy/deploy.sh # aktuellen Commit (HEAD) ausrollen
|
||||||
|
bash server/deploy/deploy.sh --reset-db # ... und DB frisch aufsetzen (Testkonten michi / benni)
|
||||||
|
bash server/deploy/deploy.sh --ref <commit> # einen bestimmten Stand (z. B. zurück auf einen alten)
|
||||||
|
```
|
||||||
|
|
||||||
|
Es wird **nur Committetes** ausgerollt (`git archive`). Ablauf: hochladen → `npm ci` → DB-Backup → Dienst stoppen →
|
||||||
|
(optional Reset) → `current` umschalten → starten → `/healthz` muss den neuen Commit melden, sonst **automatisch
|
||||||
|
zurück** auf das vorige Release.
|
||||||
|
|
||||||
|
## Testkonten (nur Test-System, siehe CLAUDE.md)
|
||||||
|
|
||||||
|
`michi` / `Michi2000!` und `benni` / `Benni2000!` – beide Admin (Dev-Münzen, `/admin/`). Kommen per `--reset-db`.
|
||||||
|
|
||||||
## Logs / Status
|
## Logs / Status
|
||||||
```
|
|
||||||
systemctl status robotclash
|
```bash
|
||||||
journalctl -u robotclash -f
|
ssh root@roboclash.michael-media.de "systemctl status robotclash; journalctl -u robotclash -n 50"
|
||||||
|
curl -s https://roboclash.michael-media.de/healthz
|
||||||
```
|
```
|
||||||
|
|
||||||
Schneller (optional, aus WSL statt PowerShell): `rsync -az --delete game server root@91.99.166.238:/opt/robotclash/`
|
## Später (Plan)
|
||||||
statt `scp` – nur Änderungen, kein erneutes Hochladen der ~13 MB Assets.
|
|
||||||
|
Eigener SSH-Nutzer `deploy` statt root (P3-1), Deploy aus Gitea Actions bei Push auf `main` (P3-6), Produktion als
|
||||||
|
zweite Umgebung erst nach T-4.
|
||||||
|
|
||||||
|
## Test-Bot auf dem Server (Gegner mit ~0 ms Ping)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh root@roboclash.michael-media.de "cd /opt/robotclash/current && node tools/bot.js --url http://127.0.0.1:8080 --pattern circle"
|
||||||
|
```
|
||||||
|
|
||||||
|
Dann im Browser herausfordern, F3 drücken. Ruckelt es trotzdem, liegt es an deiner Leitung oder am Server – nicht am
|
||||||
|
Gegner. Strg+C beendet den Bot und löscht sein Gastkonto.
|
||||||
|
|||||||
@@ -1,31 +0,0 @@
|
|||||||
# Komplett-Deploy in einem: Server einrichten, Code hochladen, starten, Status prüfen.
|
|
||||||
# Aus dem Projektordner in Windows PowerShell: .\server\deploy\deploy-all.ps1
|
|
||||||
# Beim ersten Mal fragt SSH nach dem Hetzner-Root-Passwort (mehrfach) und einmal nach dem Fingerprint (yes).
|
|
||||||
param(
|
|
||||||
[string]$Server = "root@91.99.166.238",
|
|
||||||
[string]$Domain = "roboclash.michael-media.de",
|
|
||||||
[string]$App = "/opt/robotclash"
|
|
||||||
)
|
|
||||||
$ErrorActionPreference = "Stop"
|
|
||||||
$repo = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
|
|
||||||
|
|
||||||
Write-Host "== 1/4 Server einrichten (Node, Caddy, Dienst, Firewall) ==" -ForegroundColor Cyan
|
|
||||||
scp "$repo\server\deploy\setup.sh" "${Server}:/root/setup.sh"
|
|
||||||
ssh $Server "bash /root/setup.sh $Domain"
|
|
||||||
|
|
||||||
Write-Host "== 2/4 Code hochladen (Spiel + Server) ==" -ForegroundColor Cyan
|
|
||||||
ssh $Server "mkdir -p $App/game $App/server"
|
|
||||||
scp -r -q "$repo\game" "${Server}:$App/"
|
|
||||||
Get-ChildItem "$repo\server" -File |
|
|
||||||
Where-Object { $_.Name -ne ".env" -and $_.Name -notlike "*.sqlite*" } |
|
|
||||||
ForEach-Object { scp -q $_.FullName "${Server}:$App/server/" }
|
|
||||||
|
|
||||||
Write-Host "== 3/4 Abhaengigkeiten installieren + Dienst starten ==" -ForegroundColor Cyan
|
|
||||||
ssh $Server "cd $App/server && (npm ci --omit=dev 2>/dev/null || npm install --omit=dev) && systemctl restart robotclash"
|
|
||||||
|
|
||||||
Write-Host "== 4/4 Status ==" -ForegroundColor Cyan
|
|
||||||
ssh $Server "sleep 1; systemctl --no-pager --lines=6 status robotclash; echo '--- lokal (Node) ---'; curl -s -o /dev/null -w 'node:8080 -> HTTP %{http_code}\n' http://localhost:8080/; echo -n '--- caddy: '; systemctl is-active caddy"
|
|
||||||
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host "Fertig. Oeffne: https://$Domain/ (Browser: Strg+F5 oder Inkognito)" -ForegroundColor Green
|
|
||||||
Write-Host "Beim ersten Aufruf holt Caddy automatisch das TLS-Zertifikat (ein paar Sekunden)." -ForegroundColor Green
|
|
||||||
31
server/deploy/deploy.sh
Normal file
31
server/deploy/deploy.sh
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Deploy a committed git ref to the server. Run from the repo root (Git Bash on Windows, or Linux/CI):
|
||||||
|
# bash server/deploy/deploy.sh deploy HEAD
|
||||||
|
# bash server/deploy/deploy.sh --reset-db ... and reset the DB (test system: seed accounts michi/benni)
|
||||||
|
# bash server/deploy/deploy.sh --ref <sha|tag> --host root@<server>
|
||||||
|
# Only committed code is deployed (git archive), never the working tree. The server side (remote-release.sh)
|
||||||
|
# installs the release, backs up the DB, switches the `current` link, checks /healthz and rolls back on failure.
|
||||||
|
set -euo pipefail
|
||||||
|
HOST="root@roboclash.michael-media.de"
|
||||||
|
REF="HEAD"
|
||||||
|
RESET=0
|
||||||
|
while [ $# -gt 0 ]; do
|
||||||
|
case "$1" in
|
||||||
|
--host) HOST="$2"; shift 2 ;;
|
||||||
|
--ref) REF="$2"; shift 2 ;;
|
||||||
|
--reset-db) RESET=1; shift ;;
|
||||||
|
*) echo "unknown option: $1"; exit 2 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
cd "$(git rev-parse --show-toplevel)"
|
||||||
|
git diff --quiet HEAD -- game server admin tools || echo "!! uncommitted changes in game/server/admin are NOT deployed (only $REF)"
|
||||||
|
SHA=$(git rev-parse --short "$REF")
|
||||||
|
REL="$(date -u +%Y%m%d-%H%M%S)-$SHA"
|
||||||
|
TAR="$(mktemp -t rc-XXXXXX).tgz"
|
||||||
|
trap 'rm -f "$TAR"' EXIT
|
||||||
|
|
||||||
|
echo ">> release $REL -> $HOST"
|
||||||
|
git archive --format=tar.gz -o "$TAR" "$REF" game server admin tools
|
||||||
|
scp -q "$TAR" "$HOST:/tmp/rc-$REL.tgz"
|
||||||
|
tr -d '\r' < server/deploy/remote-release.sh | ssh "$HOST" bash -s -- "$REL" "$SHA" "$RESET"
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
# Push the game + server to the Hetzner box and restart. Run from Windows PowerShell (needs OpenSSH: ssh/scp).
|
|
||||||
# .\server\deploy\push.ps1
|
|
||||||
# .\server\deploy\push.ps1 -Server root@91.99.166.238
|
|
||||||
param(
|
|
||||||
[string]$Server = "root@91.99.166.238",
|
|
||||||
[string]$App = "/opt/robotclash"
|
|
||||||
)
|
|
||||||
$ErrorActionPreference = "Stop"
|
|
||||||
$repo = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
|
|
||||||
Write-Host "Deploy from $repo -> ${Server}:$App"
|
|
||||||
|
|
||||||
# make sure target dirs exist
|
|
||||||
ssh $Server "mkdir -p $App/game $App/server"
|
|
||||||
|
|
||||||
# game/ (no node_modules inside) - full tree incl. assets
|
|
||||||
Write-Host "Uploading game/ ..."
|
|
||||||
scp -r -q "$repo\game" "${Server}:$App/"
|
|
||||||
|
|
||||||
# server source only: skip .env, node_modules and the live DB
|
|
||||||
Write-Host "Uploading server/ source ..."
|
|
||||||
Get-ChildItem "$repo\server" -File |
|
|
||||||
Where-Object { $_.Name -ne ".env" -and $_.Name -notlike "*.sqlite*" } |
|
|
||||||
ForEach-Object { scp -q $_.FullName "${Server}:$App/server/" }
|
|
||||||
|
|
||||||
# install deps + restart
|
|
||||||
Write-Host "Installing deps + restarting ..."
|
|
||||||
ssh $Server "cd $App/server && (npm ci --omit=dev 2>/dev/null || npm install --omit=dev) && systemctl restart robotclash && sleep 1 && systemctl --no-pager --lines=5 status robotclash"
|
|
||||||
|
|
||||||
Write-Host "Done. https://roboclash.michael-media.de/"
|
|
||||||
49
server/deploy/remote-release.sh
Normal file
49
server/deploy/remote-release.sh
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Runs ON the server (piped in by deploy.sh): install release $1 (commit $2), optional DB reset ($3 = 1).
|
||||||
|
set -euo pipefail
|
||||||
|
REL="$1"; SHA="$2"; RESET="${3:-0}"
|
||||||
|
APP=/opt/robotclash
|
||||||
|
SVC=robotclash
|
||||||
|
D="$APP/releases/$REL"
|
||||||
|
PORT=$(grep -E '^PORT=' "$APP/shared/.env" | cut -d= -f2); PORT=${PORT:-8080}
|
||||||
|
|
||||||
|
mkdir -p "$D"
|
||||||
|
tar -xzf "/tmp/rc-$REL.tgz" -C "$D"
|
||||||
|
rm -f "/tmp/rc-$REL.tgz"
|
||||||
|
echo "GIT_COMMIT=$SHA" > "$D/server/.release"
|
||||||
|
echo ">> npm ci"
|
||||||
|
(cd "$D/server" && npm ci --omit=dev --no-audit --no-fund --loglevel=error)
|
||||||
|
chown -R "$SVC:$SVC" "$D"
|
||||||
|
|
||||||
|
PREV=$(readlink -f "$APP/current" 2>/dev/null || true)
|
||||||
|
if [ -f "$APP/shared/data.sqlite" ]; then
|
||||||
|
sqlite3 "$APP/shared/data.sqlite" ".backup '$APP/backups/pre-$REL.sqlite'"
|
||||||
|
echo ">> db backup: backups/pre-$REL.sqlite"
|
||||||
|
fi
|
||||||
|
|
||||||
|
systemctl stop "$SVC" || true
|
||||||
|
if [ "$RESET" = "1" ]; then
|
||||||
|
echo ">> db reset (seed accounts)"
|
||||||
|
sudo -u "$SVC" bash -c "set -a; . '$APP/shared/.env'; set +a; cd '$D/server' && node scripts/reset-db.js"
|
||||||
|
fi
|
||||||
|
ln -sfn "$D" "$APP/current"
|
||||||
|
systemctl start "$SVC"
|
||||||
|
|
||||||
|
ok=0
|
||||||
|
for i in $(seq 1 20); do
|
||||||
|
if curl -fsS "http://127.0.0.1:$PORT/healthz" 2>/dev/null | grep -q "\"commit\":\"$SHA\""; then ok=1; break; fi
|
||||||
|
sleep 0.5
|
||||||
|
done
|
||||||
|
if [ "$ok" != "1" ]; then
|
||||||
|
echo "!! health check failed for $REL"
|
||||||
|
journalctl -u "$SVC" -n 20 --no-pager || true
|
||||||
|
if [ -n "$PREV" ] && [ -d "$PREV" ]; then
|
||||||
|
echo "!! rolling back to $(basename "$PREV")"
|
||||||
|
ln -sfn "$PREV" "$APP/current"; systemctl restart "$SVC"
|
||||||
|
fi
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo ">> live: $(curl -fsS "http://127.0.0.1:$PORT/healthz")"
|
||||||
|
|
||||||
|
# keep the last 5 releases
|
||||||
|
ls -1dt "$APP"/releases/* 2>/dev/null | tail -n +6 | xargs -r rm -rf
|
||||||
@@ -1,69 +1,90 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# One-time server setup for Robot Clash. Run ON the Hetzner box as root:
|
# One-time (and re-runnable) server setup for Robot Clash. Run ON the server as root:
|
||||||
# bash setup.sh # uses roboclash.michael-media.de
|
# bash setup.sh [domain] default: roboclash.michael-media.de
|
||||||
# bash setup.sh my.domain.tld # custom domain
|
# Installs Node 24 + Caddy (auto-TLS), creates the service user, the release layout, the hardened systemd
|
||||||
# Installs Node + Caddy (auto-TLS), creates the systemd service, firewall and a daily DB backup.
|
# service, the firewall and a daily DB backup. Migrates the old /opt/robotclash/{game,server} layout.
|
||||||
# Then push the code (deploy/push.ps1 from Windows) and: systemctl start robotclash
|
# Afterwards deploy from your machine: bash server/deploy/deploy.sh --reset-db
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
DOMAIN="${1:-roboclash.michael-media.de}"
|
DOMAIN="${1:-roboclash.michael-media.de}"
|
||||||
APP=/opt/robotclash
|
APP=/opt/robotclash
|
||||||
|
SVC=robotclash
|
||||||
|
|
||||||
echo ">> Robot Clash setup for $DOMAIN"
|
echo ">> Robot Clash setup for $DOMAIN"
|
||||||
|
|
||||||
# --- Node LTS -------------------------------------------------------------------------------------
|
# --- Node 24 LTS (Node 20 is end-of-life since 2026-04-30) ----------------------------------------
|
||||||
if ! command -v node >/dev/null 2>&1; then
|
if ! node -v 2>/dev/null | grep -q '^v24\.'; then
|
||||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
|
||||||
apt-get install -y nodejs
|
apt-get install -y nodejs
|
||||||
fi
|
fi
|
||||||
apt-get install -y build-essential python3 git ufw sqlite3 curl
|
apt-get install -y build-essential python3 ufw sqlite3 curl
|
||||||
|
|
||||||
# --- Caddy (reverse proxy + automatic HTTPS) ------------------------------------------------------
|
# --- Caddy (reverse proxy + automatic HTTPS) ------------------------------------------------------
|
||||||
if ! command -v caddy >/dev/null 2>&1; then
|
if ! command -v caddy >/dev/null 2>&1; then
|
||||||
apt-get install -y debian-keyring debian-archive-keyring apt-transport-https
|
apt-get install -y debian-keyring debian-archive-keyring apt-transport-https gpg
|
||||||
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
|
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
|
||||||
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list >/dev/null
|
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list >/dev/null
|
||||||
apt-get update
|
apt-get update
|
||||||
apt-get install -y caddy
|
apt-get install -y caddy
|
||||||
fi
|
fi
|
||||||
|
|
||||||
mkdir -p "$APP/game" "$APP/server" "$APP/backups"
|
# --- service user + layout: releases/<time>-<commit>, current -> active release, shared/ (.env + DB) --
|
||||||
|
id "$SVC" >/dev/null 2>&1 || useradd --system --home-dir "$APP" --shell /usr/sbin/nologin "$SVC"
|
||||||
|
mkdir -p "$APP/releases" "$APP/shared" "$APP/backups"
|
||||||
|
|
||||||
# --- .env (random JWT secret, kept across deploys) ------------------------------------------------
|
# old layout (code + .env + DB directly in /opt/robotclash/server): keep the secret, park the rest
|
||||||
if [ ! -f "$APP/server/.env" ]; then
|
if [ -f "$APP/server/.env" ] && [ ! -f "$APP/shared/.env" ]; then cp "$APP/server/.env" "$APP/shared/.env"; fi
|
||||||
cat > "$APP/server/.env" <<EOF
|
if [ -d "$APP/server" ] || [ -d "$APP/game" ]; then
|
||||||
PORT=8080
|
systemctl stop "$SVC" 2>/dev/null || true
|
||||||
JWT_SECRET=$(head -c 32 /dev/urandom | base64 | tr -d '\n')
|
LEG="$APP/legacy-$(date +%F-%H%M)"; mkdir -p "$LEG"
|
||||||
ADMIN_UID=
|
[ -d "$APP/server" ] && mv "$APP/server" "$LEG/"
|
||||||
DB_FILE=$APP/server/data.sqlite
|
[ -d "$APP/game" ] && mv "$APP/game" "$LEG/"
|
||||||
ANTICHEAT=0
|
echo ">> old layout moved to $LEG (delete it once the new setup runs)"
|
||||||
EOF
|
|
||||||
echo ">> wrote $APP/server/.env (random JWT_SECRET)"
|
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# --- systemd service ------------------------------------------------------------------------------
|
if [ ! -f "$APP/shared/.env" ]; then
|
||||||
cat > /etc/systemd/system/robotclash.service <<EOF
|
printf 'PORT=8080\nJWT_SECRET=%s\n' "$(head -c 32 /dev/urandom | base64 | tr -d '\n')" > "$APP/shared/.env"
|
||||||
|
echo ">> wrote $APP/shared/.env (random JWT_SECRET)"
|
||||||
|
fi
|
||||||
|
# keys the new server no longer uses; DB lives in shared/
|
||||||
|
sed -i '/^DB_FILE=/d;/^ADMIN_UID=/d;/^ANTICHEAT=/d' "$APP/shared/.env"
|
||||||
|
echo "DB_FILE=$APP/shared/data.sqlite" >> "$APP/shared/.env"
|
||||||
|
grep -q '^PORT=' "$APP/shared/.env" || echo 'PORT=8080' >> "$APP/shared/.env"
|
||||||
|
chown -R "$SVC:$SVC" "$APP/shared" "$APP/backups"
|
||||||
|
chmod 700 "$APP/shared"; chmod 600 "$APP/shared/.env"
|
||||||
|
|
||||||
|
# --- systemd service (no root, read-only system, writes only to shared/) --------------------------
|
||||||
|
cat > "/etc/systemd/system/$SVC.service" <<EOF
|
||||||
[Unit]
|
[Unit]
|
||||||
Description=Robot Clash server
|
Description=Robot Clash server
|
||||||
After=network.target
|
After=network.target
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
WorkingDirectory=$APP/server
|
User=$SVC
|
||||||
EnvironmentFile=$APP/server/.env
|
Group=$SVC
|
||||||
|
WorkingDirectory=$APP/current/server
|
||||||
|
EnvironmentFile=$APP/shared/.env
|
||||||
|
EnvironmentFile=-$APP/current/server/.release
|
||||||
|
Environment=NODE_ENV=development
|
||||||
ExecStart=/usr/bin/node app.js
|
ExecStart=/usr/bin/node app.js
|
||||||
Restart=always
|
Restart=always
|
||||||
RestartSec=2
|
RestartSec=2
|
||||||
User=root
|
NoNewPrivileges=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ReadWritePaths=$APP/shared
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
EOF
|
EOF
|
||||||
systemctl daemon-reload
|
systemctl daemon-reload
|
||||||
systemctl enable robotclash
|
systemctl enable "$SVC" >/dev/null
|
||||||
|
|
||||||
# --- Caddy site -----------------------------------------------------------------------------------
|
# --- Caddy site: TLS + proxy; WebSocket /ws is proxied as-is (no compression on the socket) --------
|
||||||
cat > /etc/caddy/Caddyfile <<EOF
|
cat > /etc/caddy/Caddyfile <<EOF
|
||||||
$DOMAIN {
|
$DOMAIN {
|
||||||
encode gzip
|
@compress not path /ws
|
||||||
|
encode @compress gzip
|
||||||
reverse_proxy localhost:8080
|
reverse_proxy localhost:8080
|
||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
@@ -77,11 +98,11 @@ ufw --force enable >/dev/null
|
|||||||
cat > /etc/cron.daily/robotclash-backup <<EOF
|
cat > /etc/cron.daily/robotclash-backup <<EOF
|
||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
D=$APP/backups
|
D=$APP/backups
|
||||||
sqlite3 $APP/server/data.sqlite ".backup '\$D/data-\$(date +%F).sqlite'" 2>/dev/null || cp $APP/server/data.sqlite "\$D/data-\$(date +%F).sqlite" 2>/dev/null || true
|
[ -f $APP/shared/data.sqlite ] && sqlite3 $APP/shared/data.sqlite ".backup '\$D/daily-\$(date +%F).sqlite'"
|
||||||
ls -1t "\$D"/data-*.sqlite 2>/dev/null | tail -n +15 | xargs -r rm
|
ls -1t "\$D"/daily-*.sqlite 2>/dev/null | tail -n +15 | xargs -r rm
|
||||||
|
ls -1t "\$D"/pre-*.sqlite 2>/dev/null | tail -n +11 | xargs -r rm
|
||||||
EOF
|
EOF
|
||||||
chmod +x /etc/cron.daily/robotclash-backup
|
chmod +x /etc/cron.daily/robotclash-backup
|
||||||
|
|
||||||
echo ">> Setup done."
|
echo ">> Setup done. node $(node -v), caddy $(caddy version | cut -d' ' -f1)"
|
||||||
echo ">> DNS: point $DOMAIN A-record to this server's IP."
|
echo ">> Next (from your machine): bash server/deploy/deploy.sh --reset-db"
|
||||||
echo ">> Next: push the code (deploy/push.ps1 from Windows), then: systemctl start robotclash"
|
|
||||||
|
|||||||
@@ -1,25 +1,64 @@
|
|||||||
/* Server-authoritative money/fame. The client can read its wallet but never set it directly;
|
/* Server-authoritative online economy. The online save of every player lives here; money, fame, parts and
|
||||||
it changes only through validated actions (buy/sell, fight result) added in step 3.
|
robots change ONLY through RC.Eco (game/eco.js - the same rules the client runs) or fight rewards. */
|
||||||
Loads the game's DOM-free logic (parts/robot/combat) so the server is the single source of truth. */
|
|
||||||
'use strict';
|
'use strict';
|
||||||
const RC = require('../game/robot.js'); // pulls in parts.js too, sets globalThis.RC
|
const RC = require('../game/robot.js'); // pulls in parts.js, sets globalThis.RC
|
||||||
require('../game/combat.js');
|
require('../game/eco.js');
|
||||||
require('../game/ai.js');
|
require('../game/progress.js');
|
||||||
const { Wallet } = require('./db');
|
const { OnlineSaves, KV } = require('./db');
|
||||||
|
|
||||||
const clampMoney = v => Math.max(0, Math.min(1e9, Math.round(+v || 0)));
|
const Eco = RC.Eco;
|
||||||
|
|
||||||
function wallet(uid) { Wallet.init.run(uid, 800); return Wallet.get.get(uid); }
|
function load(uid) {
|
||||||
function setWallet(uid, money, fame) {
|
let s = OnlineSaves.get(uid);
|
||||||
const w = wallet(uid);
|
if (!s || !Array.isArray(s.robots) || !s.robots.length) { s = Eco.newOnlineSave(); OnlineSaves.put(uid, s); }
|
||||||
const m = money == null ? w.money : clampMoney(money);
|
s.active = Math.max(0, Math.min(s.active | 0, s.robots.length - 1));
|
||||||
const f = fame == null ? w.fame : clampMoney(fame);
|
Eco.mirror(s); // build/paint/robotName point at robots[active] again after JSON
|
||||||
Wallet.set.run(m, f, uid);
|
return s;
|
||||||
return { money: m, fame: f };
|
|
||||||
}
|
}
|
||||||
function addWallet(uid, dMoney, dFame) {
|
const store = (uid, s) => OnlineSaves.put(uid, s);
|
||||||
const w = wallet(uid);
|
|
||||||
return setWallet(uid, w.money + (+dMoney || 0), w.fame + (+dFame || 0));
|
// what the client gets: the whole online save (it caches it locally)
|
||||||
|
const view = s => JSON.parse(JSON.stringify(s));
|
||||||
|
|
||||||
|
function action(user, a) {
|
||||||
|
if (a && a.type === 'devCoins' && !user.admin) return { ok: false, error: 'DENIED' };
|
||||||
|
const s = load(user.uid);
|
||||||
|
const r = Eco.apply(s, a);
|
||||||
|
if (r.ok) store(user.uid, s);
|
||||||
|
return Object.assign(r, { save: view(s) }); // on error the client resyncs to this
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { RC, wallet, setWallet, addWallet, clampMoney };
|
function putCosmetics(uid, incoming) {
|
||||||
|
const s = load(uid);
|
||||||
|
Eco.mergeCosmetics(s, incoming);
|
||||||
|
store(uid, s);
|
||||||
|
return view(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the robot a player fights with (validated) + what the lobby shows
|
||||||
|
function fighter(uid, name) {
|
||||||
|
const s = load(uid);
|
||||||
|
const v = RC.validate(s.build);
|
||||||
|
return {
|
||||||
|
ok: v.ok, errors: v.errors, uid, name, flag: s.flag || 'XX', fame: s.fame | 0,
|
||||||
|
build: JSON.parse(JSON.stringify(s.build)), paint: JSON.parse(JSON.stringify(s.paint)), robotName: s.robotName,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// book a finished live fight; returns { money, fame, lines, save }
|
||||||
|
function reward(uid, o) {
|
||||||
|
const s = load(uid);
|
||||||
|
const live = KV.get('live') || {};
|
||||||
|
const ev = live.event && live.event.prizeMul && Date.now() >= (live.event.from || 0) && Date.now() <= (live.event.to || Infinity) ? live.event.prizeMul : 1;
|
||||||
|
const r = Eco.pvpReward(Object.assign({}, o, { money: s.money, prizeMul: ev }));
|
||||||
|
Eco.applyReward(s, r);
|
||||||
|
// achievements pay credits -> decided here, never on the client (same rules: game/progress.js)
|
||||||
|
const ach = RC.Progress.check(s, { won: r.won, reason: o.reason, hpPct: (o.hp || 0) / (o.maxHp || 1), dealt: o.dealt || 0, lost: (o.lost || []).length });
|
||||||
|
for (const a of ach) s.money = Math.min(1e9, s.money + (a.reward | 0));
|
||||||
|
store(uid, s);
|
||||||
|
return Object.assign(r, { ach: ach.map(a => ({ id: a.id, reward: a.reward })), save: view(s) });
|
||||||
|
}
|
||||||
|
|
||||||
|
function ranks(n = 20) { return OnlineSaves.top(Math.max(1, Math.min(100, n | 0))); }
|
||||||
|
|
||||||
|
module.exports = { load, action, putCosmetics, fighter, reward, ranks };
|
||||||
|
|||||||
156
server/lobby.js
Normal file
156
server/lobby.js
Normal file
@@ -0,0 +1,156 @@
|
|||||||
|
/* Lobby: who is online (= has an open, authenticated socket), challenges, match creation and results.
|
||||||
|
All state is in memory and uses server time only - no heartbeats, no client clocks.
|
||||||
|
|
||||||
|
const lobby = createLobby({ runner, economy, matches })
|
||||||
|
lobby.join({ uid, name, admin, send }) socket authenticated (a second socket replaces the first)
|
||||||
|
lobby.leave(uid, send) socket closed (only if it is still the current one)
|
||||||
|
lobby.handle(uid, msg) validated client message */
|
||||||
|
'use strict';
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
const CHALLENGE_TTL = 15000;
|
||||||
|
|
||||||
|
function createLobby({ runner, economy, matches, now = () => Date.now() }) {
|
||||||
|
const players = new Map(); // uid -> { uid, name, room, state, send, match: {id, seat} | null }
|
||||||
|
const pending = new Map(); // challenger uid -> { to, timer }
|
||||||
|
const inMatch = new Map(); // uid -> { id, seat } (survives a disconnect)
|
||||||
|
|
||||||
|
const row = p => {
|
||||||
|
const f = economy.fighter(p.uid, p.name);
|
||||||
|
return { uid: p.uid, name: p.name, flag: f.flag, fame: f.fame, room: p.room || f.flag, state: p.state };
|
||||||
|
};
|
||||||
|
const tell = (uid, msg) => { const p = players.get(uid); if (p) p.send(msg); };
|
||||||
|
const broadcast = (msg, except) => { for (const p of players.values()) if (p.uid !== except) p.send(msg); };
|
||||||
|
const setState = (p, state) => { p.state = state; broadcast({ t: 'lobby.state', player: row(p) }); };
|
||||||
|
|
||||||
|
function join(c) {
|
||||||
|
const old = players.get(c.uid);
|
||||||
|
const p = { uid: c.uid, name: c.name, admin: !!c.admin, room: old ? old.room : null, state: 'idle', send: c.send };
|
||||||
|
if (old && old.send !== c.send) old.send({ t: 'error', code: 'REPLACED' });
|
||||||
|
players.set(c.uid, p);
|
||||||
|
const m = inMatch.get(c.uid);
|
||||||
|
const room = m && runner.get(m.id);
|
||||||
|
if (room) { p.state = 'inmatch'; room.reconnect(m.seat); }
|
||||||
|
p.send({ t: 'lobby', players: [...players.values()].filter(x => x.uid !== c.uid).map(row), you: row(p) });
|
||||||
|
if (!old) broadcast({ t: 'lobby.join', player: row(p) }, c.uid);
|
||||||
|
if (room) p.send(room.startMsg(m.seat)); // reconnect: rebuild the running fight
|
||||||
|
}
|
||||||
|
|
||||||
|
function leave(uid, send) {
|
||||||
|
const p = players.get(uid);
|
||||||
|
if (!p || (send && p.send !== send)) return; // an old, already replaced socket
|
||||||
|
players.delete(uid);
|
||||||
|
dropChallenges(uid);
|
||||||
|
const m = inMatch.get(uid), room = m && runner.get(m.id);
|
||||||
|
if (room) room.disconnect(m.seat);
|
||||||
|
broadcast({ t: 'lobby.leave', uid });
|
||||||
|
}
|
||||||
|
|
||||||
|
function dropChallenges(uid) {
|
||||||
|
const out = pending.get(uid);
|
||||||
|
if (out) { clearTimeout(out.timer); pending.delete(uid); tell(out.to, { t: 'challenge.gone', from: uid }); }
|
||||||
|
for (const [from, c] of pending) if (c.to === uid) { clearTimeout(c.timer); pending.delete(from); const f = players.get(from); if (f) { setState(f, 'idle'); f.send({ t: 'challenge.gone', to: uid }); } }
|
||||||
|
}
|
||||||
|
|
||||||
|
function challenge(p, to) {
|
||||||
|
const q = players.get(to);
|
||||||
|
if (!q || to === p.uid) return p.send({ t: 'error', code: 'NOT_AVAILABLE' });
|
||||||
|
if (p.state !== 'idle' || q.state !== 'idle') return p.send({ t: 'error', code: 'BUSY' });
|
||||||
|
const f = economy.fighter(p.uid, p.name);
|
||||||
|
if (!f.ok) return p.send({ t: 'error', code: 'INVALID_ROBOT', errors: f.errors });
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
if (!pending.has(p.uid)) return;
|
||||||
|
pending.delete(p.uid); setState(p, 'idle');
|
||||||
|
p.send({ t: 'challenge.gone', to, reason: 'timeout' }); tell(to, { t: 'challenge.gone', from: p.uid, reason: 'timeout' });
|
||||||
|
}, CHALLENGE_TTL);
|
||||||
|
if (timer.unref) timer.unref();
|
||||||
|
pending.set(p.uid, { to, timer });
|
||||||
|
setState(p, 'challenging');
|
||||||
|
q.send({ t: 'challenge.in', from: p.uid, name: p.name, flag: f.flag, fame: f.fame });
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancel(p) {
|
||||||
|
const c = pending.get(p.uid); if (!c) return;
|
||||||
|
clearTimeout(c.timer); pending.delete(p.uid); setState(p, 'idle');
|
||||||
|
tell(c.to, { t: 'challenge.gone', from: p.uid, reason: 'cancelled' });
|
||||||
|
}
|
||||||
|
|
||||||
|
function decline(p, from) {
|
||||||
|
const c = pending.get(from); if (!c || c.to !== p.uid) return;
|
||||||
|
clearTimeout(c.timer); pending.delete(from);
|
||||||
|
const f = players.get(from); if (f) { setState(f, 'idle'); f.send({ t: 'challenge.gone', to: p.uid, reason: 'declined' }); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function accept(p, from) {
|
||||||
|
const c = pending.get(from), q = players.get(from);
|
||||||
|
if (!c || c.to !== p.uid || !q) return p.send({ t: 'error', code: 'NOT_AVAILABLE' });
|
||||||
|
clearTimeout(c.timer); pending.delete(from);
|
||||||
|
const fa = economy.fighter(q.uid, q.name), fb = economy.fighter(p.uid, p.name);
|
||||||
|
if (!fa.ok || !fb.ok) {
|
||||||
|
setState(q, 'idle');
|
||||||
|
const code = 'INVALID_ROBOT';
|
||||||
|
if (!fa.ok) q.send({ t: 'error', code, errors: fa.errors }); else p.send({ t: 'error', code: 'OPPONENT_INVALID' });
|
||||||
|
if (!fb.ok) p.send({ t: 'error', code, errors: fb.errors }); else q.send({ t: 'error', code: 'OPPONENT_INVALID' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
startMatch(fa, fb);
|
||||||
|
}
|
||||||
|
|
||||||
|
function startMatch(fa, fb) {
|
||||||
|
const id = crypto.randomBytes(8).toString('hex');
|
||||||
|
const seed = crypto.randomInt(1, 1e9);
|
||||||
|
const seats = seed % 2 ? [fa, fb] : [fb, fa]; // fair: who gets which start position is random
|
||||||
|
const room = runner.create({
|
||||||
|
id, seed,
|
||||||
|
players: seats.map(f => ({ uid: f.uid, name: f.name, build: f.build, paint: f.paint, flag: f.flag })),
|
||||||
|
send: (seat, msg) => tell(seats[seat].uid, msg),
|
||||||
|
rttOf: seat => { const p = players.get(seats[seat].uid); return p ? p.rtt : 0; },
|
||||||
|
onEnd: finish,
|
||||||
|
});
|
||||||
|
if (matches) matches.start.run(id, seed, room.arena, seats[0].uid, seats[1].uid, now());
|
||||||
|
seats.forEach((f, seat) => {
|
||||||
|
inMatch.set(f.uid, { id, seat });
|
||||||
|
const pl = players.get(f.uid); if (pl) setState(pl, 'inmatch');
|
||||||
|
tell(f.uid, room.startMsg(seat));
|
||||||
|
});
|
||||||
|
return room;
|
||||||
|
}
|
||||||
|
|
||||||
|
function finish(room) {
|
||||||
|
const res = room.result;
|
||||||
|
if (matches) matches.end.run(res.winner, res.reason, now(), room.id);
|
||||||
|
room.players.forEach((pl, seat) => {
|
||||||
|
inMatch.delete(pl.uid);
|
||||||
|
const sm = room.summary(seat);
|
||||||
|
const won = res.winner === seat;
|
||||||
|
const r = economy.reward(pl.uid, Object.assign({ won, winner: res.winner === -1 ? -1 : won ? 0 : 1, reason: res.reason }, sm));
|
||||||
|
tell(pl.uid, { t: 'match.end', matchId: room.id, seat, result: res, summary: sm,
|
||||||
|
reward: { money: r.money, fame: r.fame, lines: r.lines, ach: r.ach }, save: r.save });
|
||||||
|
const p = players.get(pl.uid); if (p) setState(p, 'idle');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function handle(uid, msg) {
|
||||||
|
const p = players.get(uid); if (!p) return;
|
||||||
|
switch (msg.t) {
|
||||||
|
case 'ping': return p.send({ t: 'pong', t0: msg.t0, serverTime: now() });
|
||||||
|
case 'room': p.room = msg.room === 'all' ? null : msg.room; return setState(p, p.state);
|
||||||
|
case 'challenge': return challenge(p, msg.to);
|
||||||
|
case 'challenge.cancel': return cancel(p);
|
||||||
|
case 'challenge.accept': return accept(p, msg.from);
|
||||||
|
case 'challenge.decline': return decline(p, msg.from);
|
||||||
|
case 'input': { const m = inMatch.get(uid), room = m && runner.get(m.id); if (room) room.input(m.seat, msg); return; }
|
||||||
|
case 'match.leave': { const m = inMatch.get(uid), room = m && runner.get(m.id); if (room) room.forfeit(m.seat); return; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ping of a player, measured by the hub (WebSocket ping/pong)
|
||||||
|
function setRtt(uid, ms) { const p = players.get(uid); if (p) p.rtt = p.rtt ? p.rtt * 0.7 + ms * 0.3 : ms; }
|
||||||
|
|
||||||
|
// the profile changed (robot, flag, fame): show it to everyone
|
||||||
|
function refresh(uid) { const p = players.get(uid); if (p) setState(p, p.state); }
|
||||||
|
|
||||||
|
return { join, leave, handle, refresh, setRtt, startMatch, players, pending, inMatch };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createLobby, CHALLENGE_TTL };
|
||||||
123
server/match/room.js
Normal file
123
server/match/room.js
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
/* One live fight, run by the server. Pure: no sockets, no timers - the caller feeds inputs and calls tick()
|
||||||
|
at 60 Hz (see runner.js). The fight itself is the same RC.Combat the browser uses offline.
|
||||||
|
|
||||||
|
const room = new Room({ id, seed, players: [{ uid, name, build, paint }, ...], send(seat, msg), onEnd(room) })
|
||||||
|
room.input(seat, raw) latest input of that seat (validated + clamped)
|
||||||
|
room.disconnect(seat) robot idles; after GRACE ticks the AI drives it
|
||||||
|
room.reconnect(seat) player takes over again
|
||||||
|
room.tick() one 1/60 s step (countdown first), snapshots every SNAP_EVERY ticks
|
||||||
|
room.ended / room.result { winner (seat or -1), reason } once over */
|
||||||
|
'use strict';
|
||||||
|
const RC = require('../../game/robot.js');
|
||||||
|
require('../../game/combat.js');
|
||||||
|
require('../../game/ai.js');
|
||||||
|
require('../../game/protocol.js');
|
||||||
|
|
||||||
|
const DT = 1 / 60;
|
||||||
|
const COUNTDOWN = Math.round(3.5 * 60); // ticks before the fight starts (matches the client countdown)
|
||||||
|
const SNAP_EVERY = 3; // 20 snapshots per second
|
||||||
|
const GRACE = 10 * 60; // ticks a disconnected player keeps his robot before the AI takes over
|
||||||
|
const HARD_CAP = 60 * 60 * 4; // safety net: no room lives longer than 4 minutes of fight
|
||||||
|
|
||||||
|
class Room {
|
||||||
|
constructor(opt) {
|
||||||
|
this.id = opt.id;
|
||||||
|
this.seed = opt.seed || 1;
|
||||||
|
this.players = opt.players; // [{ uid, name, build, paint, flag }]
|
||||||
|
this.send = opt.send || (() => {});
|
||||||
|
this.rttOf = opt.rttOf || (() => 0); // seat -> ping in ms (measured by the WebSocket hub)
|
||||||
|
this.onEnd = opt.onEnd || (() => {});
|
||||||
|
const ids = RC.ARENAS.map(a => a.id);
|
||||||
|
this.arena = opt.arena || ids[this.seed % ids.length];
|
||||||
|
this.s = RC.Combat.create({
|
||||||
|
robots: this.players.map(p => RC.stats(p.build)), seed: this.seed,
|
||||||
|
names: this.players.map(p => p.name), arena: this.arena,
|
||||||
|
});
|
||||||
|
this.inputs = [RC.Proto.input(null), RC.Proto.input(null)];
|
||||||
|
this.acks = [0, 0];
|
||||||
|
this.away = [0, 0]; // ticks since disconnect (0 = connected)
|
||||||
|
this.ai = [null, null];
|
||||||
|
this.tickN = 0;
|
||||||
|
this.ended = false;
|
||||||
|
this.result = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
input(seat, raw) {
|
||||||
|
if (this.ended || (seat !== 0 && seat !== 1)) return;
|
||||||
|
this.inputs[seat] = RC.Proto.input(raw);
|
||||||
|
if (raw && Number.isInteger(raw.seq)) this.acks[seat] = raw.seq;
|
||||||
|
}
|
||||||
|
disconnect(seat) { if (!this.away[seat]) this.away[seat] = 1; }
|
||||||
|
// player gives up: his robot is knocked out at once
|
||||||
|
forfeit(seat) {
|
||||||
|
const s = this.s, r = s.robots[seat];
|
||||||
|
if (this.ended || !r || s.result) return;
|
||||||
|
r.hp = 0; r.dead = true;
|
||||||
|
s.result = { winner: 1 - seat, reason: 'ko' }; s.endIn = 0;
|
||||||
|
if (this.tickN <= COUNTDOWN) this.tickN = COUNTDOWN; // end now even during the countdown
|
||||||
|
}
|
||||||
|
reconnect(seat) { this.away[seat] = 0; this.ai[seat] = null; }
|
||||||
|
connected(seat) { return !this.away[seat]; }
|
||||||
|
|
||||||
|
// what a (re)joining player needs to build the fight locally
|
||||||
|
startMsg(seat) {
|
||||||
|
return {
|
||||||
|
t: 'match.start', matchId: this.id, seat, seed: this.seed, arena: this.arena,
|
||||||
|
countdown: Math.max(0, (COUNTDOWN - this.tickN) * DT),
|
||||||
|
robots: this.players.map(p => ({ uid: p.uid, name: p.name, build: p.build, paint: p.paint, flag: p.flag })),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
inputFor(seat) {
|
||||||
|
if (!this.away[seat]) return this.inputs[seat];
|
||||||
|
if (this.away[seat] < GRACE) return RC.Proto.input(null); // grace period: robot stands still
|
||||||
|
if (!this.ai[seat]) this.ai[seat] = RC.AI.create({ style: 'brawler', skill: 0.5, seed: this.seed + seat });
|
||||||
|
return this.ai[seat].think(this.s, this.s.robots[seat], this.s.robots[1 - seat], DT);
|
||||||
|
}
|
||||||
|
|
||||||
|
tick() {
|
||||||
|
if (this.ended) return;
|
||||||
|
this.tickN++;
|
||||||
|
for (const k of [0, 1]) if (this.away[k]) this.away[k]++;
|
||||||
|
if (this.tickN <= COUNTDOWN) return;
|
||||||
|
const s = this.s;
|
||||||
|
const t0 = process.hrtime.bigint();
|
||||||
|
RC.Combat.step(s, DT, [this.inputFor(0), this.inputFor(1)]);
|
||||||
|
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
|
||||||
|
this.tickMs = this.tickMs ? this.tickMs * 0.9 + ms * 0.1 : ms; // smoothed cost of one step (server load)
|
||||||
|
if (!this.evBuf) this.evBuf = [];
|
||||||
|
if (s.events.length) this.evBuf.push(...s.events);
|
||||||
|
s.events.length = 0;
|
||||||
|
const over = s.result && s.endIn <= 0;
|
||||||
|
if (over || this.tickN % SNAP_EVERY === 0) this.publish();
|
||||||
|
if (over || this.tickN > COUNTDOWN + HARD_CAP) this.finish(s.result || { winner: -1, reason: 'time' });
|
||||||
|
}
|
||||||
|
|
||||||
|
publish() {
|
||||||
|
const s = this.s;
|
||||||
|
s.events = this.evBuf.slice(-48); // events since the last snapshot
|
||||||
|
const snap = RC.Proto.packSnap(s, this.tickN, this.acks);
|
||||||
|
s.events = []; this.evBuf.length = 0;
|
||||||
|
const away = [!!this.away[0], !!this.away[1]];
|
||||||
|
// network diagnostics for the F3 overlay: each player's ping to the server (measured here) + server step cost
|
||||||
|
const rtt = [0, 1].map(k => Math.round(this.rttOf(k) || 0));
|
||||||
|
const tickMs = Math.round((this.tickMs || 0) * 100) / 100;
|
||||||
|
for (const seat of [0, 1]) this.send(seat, Object.assign({ t: 'snap', away, rtt, tickMs, sent: Date.now() }, snap));
|
||||||
|
}
|
||||||
|
|
||||||
|
finish(result) {
|
||||||
|
if (this.ended) return;
|
||||||
|
this.ended = true;
|
||||||
|
this.result = { winner: result.winner, reason: result.reason };
|
||||||
|
this.onEnd(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
// per-seat fight summary for rewards / the result screen
|
||||||
|
summary(seat) {
|
||||||
|
const r = this.s.robots[seat];
|
||||||
|
return { hp: r.hp, maxHp: r.maxHp, dealt: r.dealt, taken: r.taken, value: r.st.value || 0,
|
||||||
|
lost: Object.keys(r.lost || {}).filter(k => r.lost[k]) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { Room, DT, COUNTDOWN, SNAP_EVERY, GRACE };
|
||||||
44
server/match/runner.js
Normal file
44
server/match/runner.js
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
/* Drives all live rooms at a fixed 60 Hz. One timer for the whole server; catches up after a hitch
|
||||||
|
(max 10 ticks per wake-up), logs when a tick takes too long. */
|
||||||
|
'use strict';
|
||||||
|
const { Room, DT } = require('./room');
|
||||||
|
|
||||||
|
function createRunner(opt = {}) {
|
||||||
|
const rooms = new Map();
|
||||||
|
const STEP = DT * 1000;
|
||||||
|
let next = 0, timer = null, slowLogged = 0;
|
||||||
|
|
||||||
|
function loop() {
|
||||||
|
const now = performance.now();
|
||||||
|
if (!next) next = now;
|
||||||
|
let n = 0;
|
||||||
|
while (now >= next && n < 10) {
|
||||||
|
const t0 = performance.now();
|
||||||
|
for (const room of rooms.values()) {
|
||||||
|
// one broken fight must never stop the others (or the server): end it as a draw and log it
|
||||||
|
try { room.tick(); } catch (e) { console.error('[match] room', room.id, 'crashed', e); try { room.finish({ winner: -1, reason: 'time' }); } catch (e2) { rooms.delete(room.id); } }
|
||||||
|
}
|
||||||
|
const ms = performance.now() - t0;
|
||||||
|
if (ms > 8 && Date.now() - slowLogged > 10000) { slowLogged = Date.now(); console.warn(`[match] slow tick ${ms.toFixed(1)} ms for ${rooms.size} rooms`); }
|
||||||
|
next += STEP; n++;
|
||||||
|
}
|
||||||
|
if (now - next > 250) next = now; // fell far behind (sleeping laptop, debugger): don't replay it
|
||||||
|
timer = setTimeout(loop, Math.max(0, next - performance.now()));
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
rooms,
|
||||||
|
create(o) {
|
||||||
|
const room = new Room(Object.assign({}, o, {
|
||||||
|
onEnd: r => { rooms.delete(r.id); if (o.onEnd) o.onEnd(r); },
|
||||||
|
}));
|
||||||
|
rooms.set(room.id, room);
|
||||||
|
if (!timer && opt.autoStart !== false) loop();
|
||||||
|
return room;
|
||||||
|
},
|
||||||
|
get: id => rooms.get(id),
|
||||||
|
stop() { clearTimeout(timer); timer = null; next = 0; },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { createRunner };
|
||||||
24
server/package-lock.json
generated
24
server/package-lock.json
generated
@@ -11,7 +11,8 @@
|
|||||||
"bcryptjs": "2.4.3",
|
"bcryptjs": "2.4.3",
|
||||||
"better-sqlite3": "11.3.0",
|
"better-sqlite3": "11.3.0",
|
||||||
"express": "4.19.2",
|
"express": "4.19.2",
|
||||||
"jsonwebtoken": "9.0.2"
|
"jsonwebtoken": "9.0.2",
|
||||||
|
"ws": "8.23.0"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=20.6"
|
"node": ">=20.6"
|
||||||
@@ -1356,6 +1357,27 @@
|
|||||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||||
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
|
||||||
"license": "ISC"
|
"license": "ISC"
|
||||||
|
},
|
||||||
|
"node_modules/ws": {
|
||||||
|
"version": "8.23.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
|
||||||
|
"integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=10.0.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"bufferutil": "^4.0.1",
|
||||||
|
"utf-8-validate": ">=5.0.2"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"bufferutil": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"utf-8-validate": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,12 +10,14 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node app.js",
|
"start": "node app.js",
|
||||||
"dev": "node --env-file=.env --watch app.js",
|
"dev": "node --env-file=.env --watch app.js",
|
||||||
"test": "node --test \"test/**/*.test.js\""
|
"test": "node --test \"test/**/*.test.js\"",
|
||||||
|
"db:reset": "node scripts/reset-db.js"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"express": "4.19.2",
|
|
||||||
"better-sqlite3": "11.3.0",
|
|
||||||
"bcryptjs": "2.4.3",
|
"bcryptjs": "2.4.3",
|
||||||
"jsonwebtoken": "9.0.2"
|
"better-sqlite3": "11.3.0",
|
||||||
|
"express": "4.19.2",
|
||||||
|
"jsonwebtoken": "9.0.2",
|
||||||
|
"ws": "8.23.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
18
server/ratelimit.js
Normal file
18
server/ratelimit.js
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
/* Tiny in-memory rate limiter (per IP + route group). Enough for one server; resets on restart. */
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
function rateLimit({ windowMs = 60000, max = 10, name = 'rl' } = {}) {
|
||||||
|
const hits = new Map(); // key -> { n, reset }
|
||||||
|
const sweep = setInterval(() => { const now = Date.now(); for (const [k, v] of hits) if (v.reset < now) hits.delete(k); }, windowMs);
|
||||||
|
if (sweep.unref) sweep.unref();
|
||||||
|
return (req, res, next) => {
|
||||||
|
const key = name + ':' + (req.ip || req.socket.remoteAddress);
|
||||||
|
const now = Date.now();
|
||||||
|
let h = hits.get(key);
|
||||||
|
if (!h || h.reset < now) { h = { n: 0, reset: now + windowMs }; hits.set(key, h); }
|
||||||
|
if (++h.n > max) { res.set('Retry-After', String(Math.ceil((h.reset - now) / 1000))); return res.status(429).json({ error: 'RATE_LIMIT' }); }
|
||||||
|
next();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { rateLimit };
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
/* Server-Sent-Events pub/sub so the client's db.stream(path) works like Firebase:
|
|
||||||
on subscribe we send one 'put' with the whole value, then a 'put' for every later change.
|
|
||||||
(The client applies 'put' by replacing the value at the given relative path; null = delete.) */
|
|
||||||
'use strict';
|
|
||||||
const { getTree, norm } = require('./db');
|
|
||||||
|
|
||||||
const subs = new Map(); // subPath -> Set<res>
|
|
||||||
|
|
||||||
function send(res, event, p, data) {
|
|
||||||
try { res.write(`event: ${event}\n`); res.write(`data: ${JSON.stringify({ path: p, data })}\n\n`); } catch (e) { /* closed */ }
|
|
||||||
}
|
|
||||||
|
|
||||||
function subscribe(path, res) {
|
|
||||||
path = norm(path);
|
|
||||||
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
|
|
||||||
if (!subs.has(path)) subs.set(path, new Set());
|
|
||||||
subs.get(path).add(res);
|
|
||||||
send(res, 'put', '/', getTree(path)); // initial snapshot
|
|
||||||
res.on('close', () => { const set = subs.get(path); if (set) { set.delete(res); if (!set.size) subs.delete(path); } });
|
|
||||||
}
|
|
||||||
|
|
||||||
// call after any write at writePath; pushes the change to every affected subscription
|
|
||||||
function notify(writePath) {
|
|
||||||
writePath = norm(writePath);
|
|
||||||
for (const [subPath, set] of subs) {
|
|
||||||
let evPath, data;
|
|
||||||
if (writePath === subPath) { evPath = '/'; data = getTree(subPath); }
|
|
||||||
else if (subPath === '' || writePath.startsWith(subPath + '/')) { evPath = '/' + (subPath ? writePath.slice(subPath.length + 1) : writePath); data = getTree(writePath); }
|
|
||||||
else if (subPath.startsWith(writePath + '/')) { evPath = '/'; data = getTree(subPath); }
|
|
||||||
else continue;
|
|
||||||
for (const res of set) send(res, 'put', evPath, data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const hb = setInterval(() => { for (const set of subs.values()) for (const res of set) { try { res.write(': ping\n\n'); } catch (e) { /* closed */ } } }, 25000);
|
|
||||||
if (hb.unref) hb.unref();
|
|
||||||
|
|
||||||
module.exports = { subscribe, notify };
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
/* Who may read/write which path - server-side (replaces Firebase database.rules.json).
|
|
||||||
req.uid is set by the auth middleware (null if not logged in). */
|
|
||||||
'use strict';
|
|
||||||
const { norm } = require('./db');
|
|
||||||
|
|
||||||
const ADMIN = (process.env.ADMIN_UID || '').split(',').map(s => s.trim()).filter(Boolean);
|
|
||||||
const seg = p => norm(p).split('/');
|
|
||||||
|
|
||||||
function canRead(req, path) {
|
|
||||||
const s = seg(path), top = s[0];
|
|
||||||
switch (top) {
|
|
||||||
case 'ranks': case 'live': return true; // public (also without login)
|
|
||||||
case 'saves': case 'users': return !!req.uid && req.uid === s[1];
|
|
||||||
case 'lobby': case 'tourney': return !!req.uid;
|
|
||||||
case 'challenges': return !!req.uid && req.uid === s[1];
|
|
||||||
case 'matches': return !!req.uid && !!s[1] && s[1].includes(req.uid);
|
|
||||||
default: return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function canWrite(req, path) {
|
|
||||||
const s = seg(path), top = s[0];
|
|
||||||
if (!req.uid) return false;
|
|
||||||
switch (top) {
|
|
||||||
case 'saves': case 'ranks': case 'lobby': case 'users': return req.uid === s[1];
|
|
||||||
case 'challenges': return s[1] === req.uid || s[2] === req.uid; // write to someone, or clear your own
|
|
||||||
case 'matches': return !!s[1] && s[1].includes(req.uid);
|
|
||||||
case 'tourney': return true; // registration is keyed by uid in the data
|
|
||||||
case 'live': return ADMIN.includes(req.uid);
|
|
||||||
default: return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
module.exports = { canRead, canWrite, seg, ADMIN };
|
|
||||||
33
server/scripts/reset-db.js
Normal file
33
server/scripts/reset-db.js
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
/* Reset the database to a clean state: backup copy, fresh schema, seed accounts.
|
||||||
|
Test system only (see CLAUDE.md). Stop the server first (systemctl stop robotclash), then:
|
||||||
|
npm run db:reset (in server/)
|
||||||
|
DB_FILE from the environment, default server/data.sqlite. */
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
// Dev phase: fixed test accounts (plan T-1: move to .env before there is ever a production system).
|
||||||
|
const DEV_SEED_USERS = [
|
||||||
|
{ name: 'michi', pass: 'Michi2000!', role: 'admin' },
|
||||||
|
{ name: 'benni', pass: 'Benni2000!', role: 'admin' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const file = process.env.DB_FILE || path.join(__dirname, '..', 'data.sqlite');
|
||||||
|
if (file !== ':memory:' && fs.existsSync(file)) {
|
||||||
|
const bak = `${file}.bak-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
||||||
|
fs.copyFileSync(file, bak);
|
||||||
|
for (const ext of ['', '-wal', '-shm']) if (fs.existsSync(file + ext)) fs.rmSync(file + ext);
|
||||||
|
console.log('backup:', bak);
|
||||||
|
}
|
||||||
|
process.env.DB_FILE = file;
|
||||||
|
process.env.JWT_SECRET = process.env.JWT_SECRET || 'reset-script-signs-nothing';
|
||||||
|
|
||||||
|
const { createUser } = require('../auth'); // opens + migrates the fresh database
|
||||||
|
const economy = require('../economy');
|
||||||
|
|
||||||
|
for (const u of DEV_SEED_USERS) {
|
||||||
|
const row = createUser({ name: u.name, pass: u.pass, role: u.role });
|
||||||
|
economy.load(row.uid); // creates the starter online save
|
||||||
|
console.log(`seeded ${u.name} (${u.role})`);
|
||||||
|
}
|
||||||
|
console.log('database reset:', file);
|
||||||
40
server/test/bot.test.js
Normal file
40
server/test/bot.test.js
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
'use strict';
|
||||||
|
const { test, before, after } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { startServer, fastForward } = require('./helpers');
|
||||||
|
const { startBot, PATTERNS } = require('../../tools/bot');
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
let S;
|
||||||
|
before(async () => { S = await startServer(); });
|
||||||
|
after(() => S.close());
|
||||||
|
|
||||||
|
test('every bot pattern gives valid inputs', () => {
|
||||||
|
for (const [name, f] of Object.entries(PATTERNS)) for (const t of [0, 1.3, 7.9]) {
|
||||||
|
const i = RC.Proto.input(f(t));
|
||||||
|
assert.ok(RC.Proto.check(Object.assign({ t: 'input', seq: 1 }, i)).ok, name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the bot accepts a challenge, drives its pattern, and deletes itself on stop', async () => {
|
||||||
|
const bot = await startBot({ url: S.base, pattern: 'circle', quiet: true });
|
||||||
|
const me = await S.account();
|
||||||
|
const c = await S.client(me.idToken);
|
||||||
|
await c.next('lobby.join', m => m.player.uid === bot.uid).catch(() => {});
|
||||||
|
c.send({ t: 'challenge', to: bot.uid });
|
||||||
|
const st = await c.next('match.start', () => true, 5000);
|
||||||
|
assert.equal(st.robots[1 - st.seat].uid, bot.uid);
|
||||||
|
|
||||||
|
// let the real 60 Hz runner play a bit after the countdown: the bot's robot must move
|
||||||
|
const room = S.runner.get(st.matchId);
|
||||||
|
const botSeat = 1 - st.seat, x0 = room.s.robots[botSeat].x, a0 = room.s.robots[botSeat].a;
|
||||||
|
await new Promise(r => setTimeout(r, (st.countdown + 1.2) * 1000));
|
||||||
|
const moved = Math.abs(room.s.robots[botSeat].x - x0) + Math.abs(room.s.robots[botSeat].a - a0);
|
||||||
|
assert.ok(moved > 0.1, 'bot robot moves (circle pattern)');
|
||||||
|
|
||||||
|
fastForward(S.runner);
|
||||||
|
await c.next('match.end', () => true, 5000);
|
||||||
|
await bot.stop();
|
||||||
|
assert.ok(!(await S.json('GET', '/api/ranks')).body.some(r => r.uid === bot.uid), 'bot account is gone');
|
||||||
|
c.close();
|
||||||
|
});
|
||||||
82
server/test/economy.test.js
Normal file
82
server/test/economy.test.js
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
'use strict';
|
||||||
|
const { test, before, after } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { startServer } = require('./helpers');
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
let S;
|
||||||
|
before(async () => { S = await startServer(); });
|
||||||
|
after(() => S.close());
|
||||||
|
|
||||||
|
const part = slot => Object.values(RC.PARTS).find(p => p.slot === slot && !Object.values(RC.STARTER).includes(p.id));
|
||||||
|
|
||||||
|
test('online save needs a login', async () => {
|
||||||
|
assert.equal((await S.json('GET', '/api/online')).status, 401);
|
||||||
|
assert.equal((await S.json('POST', '/api/online/action', { type: 'buy', part: 'x' })).status, 401);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shop actions run on the server and persist', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
const p = part('armour');
|
||||||
|
const r = await S.json('POST', '/api/online/action', { type: 'buy', part: p.id }, a.idToken);
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.equal(r.body.ok, true);
|
||||||
|
assert.equal(r.body.save.money, 800 - p.cost);
|
||||||
|
const again = await S.json('GET', '/api/online', undefined, a.idToken);
|
||||||
|
assert.equal(again.body.money, 800 - p.cost, 'stored');
|
||||||
|
assert.equal(again.body.build.armour, p.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('refused actions return the authoritative save and change nothing', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
const expensive = Object.values(RC.PARTS).filter(p => p.slot !== 'weapon').sort((x, y) => y.cost - x.cost)[0];
|
||||||
|
const r = await S.json('POST', '/api/online/action', { type: 'buy', part: expensive.id }, a.idToken);
|
||||||
|
assert.equal(r.body.ok, false);
|
||||||
|
assert.equal(r.body.error, 'NO_MONEY');
|
||||||
|
assert.equal(r.body.save.money, 800);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dev coins only for admins', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
const r = await S.json('POST', '/api/online/action', { type: 'devCoins', money: 99999 }, a.idToken);
|
||||||
|
assert.equal(r.body.error, 'DENIED');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cosmetics merge but money in the upload is ignored', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
const r = await S.json('PUT', '/api/online/save', { money: 1e9, fame: 1e9, flag: 'AT', robots: [{ name: 'Rusty', paint: { body: 0x00ff00, accent: 0, decal: null } }] }, a.idToken);
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.equal(r.body.money, 800);
|
||||||
|
assert.equal(r.body.fame, 0);
|
||||||
|
assert.equal(r.body.flag, 'AT');
|
||||||
|
assert.equal(r.body.robotName, 'Rusty');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ranking is public and only lists players with fame', async () => {
|
||||||
|
const r = await S.json('GET', '/api/ranks');
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.ok(Array.isArray(r.body));
|
||||||
|
assert.ok(r.body.every(x => x.fame > 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('live settings: public read, admin-only write', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
assert.equal((await S.json('PUT', '/api/admin/live', { motd: { en: 'hi' } }, a.idToken)).status, 403);
|
||||||
|
assert.equal((await S.json('GET', '/api/live')).status, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('campaign cloud save round trip', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
await S.json('PUT', '/api/campaign', { money: 5, ts: 1 }, a.idToken);
|
||||||
|
const r = await S.json('GET', '/api/campaign', undefined, a.idToken);
|
||||||
|
assert.deepEqual(r.body, { money: 5, ts: 1 });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('admin event presets: admin only; admin page is served', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
assert.equal((await S.json('GET', '/api/admin/events', undefined, a.idToken)).status, 403);
|
||||||
|
assert.equal((await S.json('POST', '/api/admin/events', { name: 'x' }, a.idToken)).status, 403);
|
||||||
|
const page = await fetch(S.base + '/admin/');
|
||||||
|
assert.equal(page.status, 200);
|
||||||
|
assert.match(await page.text(), /Robot Clash – Admin/);
|
||||||
|
});
|
||||||
@@ -15,17 +15,19 @@ test('GET /healthz reports ok + version', async () => {
|
|||||||
assert.equal(typeof r.body.uptime, 'number');
|
assert.equal(typeof r.body.uptime, 'number');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('register -> login -> refresh rotates the refresh token', async () => {
|
test('register by name -> login by name (any case) -> refresh rotates the token', async () => {
|
||||||
const reg = await S.json('POST', '/api/auth/register', { email: 'a@test.dev', pass: 'secret123', name: 'Alice' });
|
const reg = await S.json('POST', '/api/auth/register', { name: 'Alice', pass: 'secret123' });
|
||||||
assert.equal(reg.status, 200);
|
assert.equal(reg.status, 200);
|
||||||
assert.ok(reg.body.idToken && reg.body.refreshToken && reg.body.uid);
|
assert.ok(reg.body.idToken && reg.body.refreshToken && reg.body.uid);
|
||||||
|
|
||||||
const login = await S.json('POST', '/api/auth/login', { email: 'A@test.dev ', pass: 'secret123' });
|
const login = await S.json('POST', '/api/auth/login', { login: ' ALICE ', pass: 'secret123' });
|
||||||
assert.equal(login.status, 200);
|
assert.equal(login.status, 200);
|
||||||
assert.equal(login.body.uid, reg.body.uid);
|
assert.equal(login.body.uid, reg.body.uid);
|
||||||
|
assert.equal(login.body.name, 'Alice');
|
||||||
|
|
||||||
const me = await S.json('GET', '/api/me', undefined, login.body.idToken);
|
const me = await S.json('GET', '/api/me', undefined, login.body.idToken);
|
||||||
assert.equal(me.body.uid, reg.body.uid);
|
assert.equal(me.body.uid, reg.body.uid);
|
||||||
|
assert.equal(me.body.admin, false);
|
||||||
|
|
||||||
const r1 = await S.json('POST', '/api/auth/refresh', { refreshToken: login.body.refreshToken });
|
const r1 = await S.json('POST', '/api/auth/refresh', { refreshToken: login.body.refreshToken });
|
||||||
assert.equal(r1.status, 200);
|
assert.equal(r1.status, 200);
|
||||||
@@ -33,7 +35,33 @@ test('register -> login -> refresh rotates the refresh token', async () => {
|
|||||||
assert.equal(r2.status, 401, 'an already used refresh token is rejected');
|
assert.equal(r2.status, 401, 'an already used refresh token is rejected');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('wrong password is rejected', async () => {
|
test('register: optional e-mail works as login too; duplicates and weak passwords are refused', async () => {
|
||||||
const r = await S.json('POST', '/api/auth/login', { email: 'a@test.dev', pass: 'nope-nope' });
|
const r = await S.json('POST', '/api/auth/register', { name: 'Bob', pass: 'secret123', email: 'Bob@Test.dev' });
|
||||||
assert.equal(r.status, 400);
|
assert.equal(r.status, 200);
|
||||||
|
assert.equal((await S.json('POST', '/api/auth/login', { login: 'bob@test.dev', pass: 'secret123' })).status, 200);
|
||||||
|
assert.equal((await S.json('POST', '/api/auth/register', { name: 'bob', pass: 'secret123' })).body.error, 'NAME_EXISTS');
|
||||||
|
assert.equal((await S.json('POST', '/api/auth/register', { name: 'Carl', pass: 'short' })).body.error, 'WEAK_PASSWORD');
|
||||||
|
assert.equal((await S.json('POST', '/api/auth/register', { name: 'x', pass: 'secret123' })).body.error, 'BAD_NAME');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('DELETE /api/me removes the account, its save and its tokens', async () => {
|
||||||
|
const r = await S.json('POST', '/api/auth/register', { name: 'Leaver', pass: 'secret123' });
|
||||||
|
await S.json('GET', '/api/online', undefined, r.body.idToken);
|
||||||
|
assert.equal((await S.json('DELETE', '/api/me', undefined, r.body.idToken)).body.ok, true);
|
||||||
|
assert.equal((await S.json('POST', '/api/auth/login', { login: 'leaver', pass: 'secret123' })).status, 400);
|
||||||
|
assert.equal((await S.json('POST', '/api/auth/refresh', { refreshToken: r.body.refreshToken })).status, 401);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('wrong password is rejected', async () => {
|
||||||
|
const r = await S.json('POST', '/api/auth/login', { login: 'alice', pass: 'nope-nope' });
|
||||||
|
assert.equal(r.status, 400);
|
||||||
|
assert.equal(r.body.error, 'INVALID_LOGIN');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('guest accounts get a token and an online save', async () => {
|
||||||
|
const g = await S.json('POST', '/api/auth/guest', { name: 'Gast' });
|
||||||
|
assert.equal(g.status, 200);
|
||||||
|
assert.equal(g.body.guest, true);
|
||||||
|
const s = await S.json('GET', '/api/online', undefined, g.body.idToken);
|
||||||
|
assert.equal(s.body.money, 800);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,14 +1,18 @@
|
|||||||
/* Test helpers: start the real server on a random port with an in-memory database. */
|
/* Test helpers: start the real server on a random port with an in-memory database; WebSocket test clients. */
|
||||||
'use strict';
|
'use strict';
|
||||||
process.env.NODE_ENV = 'test';
|
process.env.NODE_ENV = 'test';
|
||||||
process.env.DB_FILE = ':memory:';
|
process.env.DB_FILE = ':memory:';
|
||||||
delete process.env.JWT_SECRET;
|
delete process.env.JWT_SECRET;
|
||||||
|
|
||||||
const { listen } = require('../app');
|
const WebSocket = require('ws');
|
||||||
|
const srvMod = require('../app');
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
let n = 0;
|
||||||
async function startServer() {
|
async function startServer() {
|
||||||
const srv = await listen(0);
|
const srv = await srvMod.listen(0);
|
||||||
const base = 'http://127.0.0.1:' + srv.address().port;
|
const port = srv.address().port;
|
||||||
|
const base = 'http://127.0.0.1:' + port;
|
||||||
const json = async (method, path, body, token) => {
|
const json = async (method, path, body, token) => {
|
||||||
const res = await fetch(base + path, {
|
const res = await fetch(base + path, {
|
||||||
method,
|
method,
|
||||||
@@ -17,7 +21,56 @@ async function startServer() {
|
|||||||
});
|
});
|
||||||
return { status: res.status, body: await res.json().catch(() => null) };
|
return { status: res.status, body: await res.json().catch(() => null) };
|
||||||
};
|
};
|
||||||
return { base, json, close: () => new Promise(r => { srv.closeAllConnections(); srv.close(r); }) };
|
// a fresh registered account: { uid, idToken, ... }
|
||||||
|
const account = async (name) => {
|
||||||
|
const r = await json('POST', '/api/auth/register', { name: name || 'tester' + (++n), pass: 'secret123' });
|
||||||
|
if (r.status !== 200) throw new Error('register failed ' + JSON.stringify(r.body));
|
||||||
|
return r.body;
|
||||||
|
};
|
||||||
|
// connected, greeted WebSocket client with a message inbox
|
||||||
|
const client = (token, opt = {}) => new Promise((resolve, reject) => {
|
||||||
|
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
|
||||||
|
const inbox = [], waiters = [];
|
||||||
|
const c = {
|
||||||
|
ws, inbox,
|
||||||
|
send: m => ws.send(JSON.stringify(m)),
|
||||||
|
// resolves with the first (already received or future) message matching type + predicate
|
||||||
|
next(t, pred = () => true, ms = 3000) {
|
||||||
|
const i = inbox.findIndex(m => m.t === t && pred(m));
|
||||||
|
if (i >= 0) return Promise.resolve(inbox.splice(i, 1)[0]);
|
||||||
|
return new Promise((res, rej) => {
|
||||||
|
const w = { t, pred, res, timer: setTimeout(() => rej(new Error('timeout waiting for ' + t)), ms) };
|
||||||
|
waiters.push(w);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
closed: new Promise(r => ws.on('close', (code, reason) => r({ code, reason: String(reason) }))),
|
||||||
|
close: () => ws.close(),
|
||||||
|
};
|
||||||
|
ws.on('message', d => {
|
||||||
|
const m = JSON.parse(d.toString());
|
||||||
|
const wi = waiters.findIndex(w => w.t === m.t && w.pred(m));
|
||||||
|
if (wi >= 0) { const w = waiters.splice(wi, 1)[0]; clearTimeout(w.timer); w.res(m); } else inbox.push(m);
|
||||||
|
});
|
||||||
|
ws.on('open', () => {
|
||||||
|
if (opt.noHello) return resolve(c);
|
||||||
|
c.send({ t: 'hello', v: opt.v !== undefined ? opt.v : RC.Proto.VERSION, token });
|
||||||
|
if (opt.expectFail) return resolve(c);
|
||||||
|
c.next('welcome').then(() => resolve(c), reject);
|
||||||
|
});
|
||||||
|
ws.on('error', reject);
|
||||||
|
});
|
||||||
|
const close = () => new Promise(r => {
|
||||||
|
srvMod.runner.stop();
|
||||||
|
for (const ws of srvMod.wss.clients) ws.terminate();
|
||||||
|
srv.closeAllConnections(); srv.close(() => r());
|
||||||
|
});
|
||||||
|
return { base, port, json, account, client, close, runner: srvMod.runner, lobby: srvMod.lobby };
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { startServer };
|
// run every live room to its end without waiting for real time
|
||||||
|
function fastForward(runner, maxTicks = 60 * 300) {
|
||||||
|
runner.stop();
|
||||||
|
for (let i = 0; i < maxTicks && runner.rooms.size; i++) for (const r of [...runner.rooms.values()]) r.tick();
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { startServer, fastForward };
|
||||||
|
|||||||
177
server/test/lobby.test.js
Normal file
177
server/test/lobby.test.js
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
'use strict';
|
||||||
|
const { test, before, after } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { startServer, fastForward } = require('./helpers');
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
let S;
|
||||||
|
before(async () => { S = await startServer(); });
|
||||||
|
after(() => S.close());
|
||||||
|
|
||||||
|
test('socket must authenticate with hello first', async () => {
|
||||||
|
const c = await S.client(null, { noHello: true });
|
||||||
|
c.send({ t: 'room', room: 'DE' });
|
||||||
|
assert.equal((await c.closed).code, 4001);
|
||||||
|
const bad = await S.client('not-a-token', { expectFail: true });
|
||||||
|
assert.equal((await bad.next('error')).code, 'UNAUTH');
|
||||||
|
assert.equal((await bad.closed).code, 4003);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a token of a deleted account is refused - and the server keeps running', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
await S.json('DELETE', '/api/me', undefined, a.idToken);
|
||||||
|
const c = await S.client(a.idToken, { expectFail: true });
|
||||||
|
assert.equal((await c.next('error')).code, 'UNAUTH');
|
||||||
|
assert.equal((await S.json('GET', '/api/online', undefined, a.idToken)).status, 401);
|
||||||
|
assert.equal((await S.json('GET', '/healthz')).status, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failing message handler answers with an error instead of crashing', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
const c = await S.client(a.idToken);
|
||||||
|
const orig = S.lobby.handle;
|
||||||
|
S.lobby.handle = () => { throw new Error('boom'); };
|
||||||
|
try {
|
||||||
|
c.send({ t: 'room', room: 'DE' });
|
||||||
|
assert.equal((await c.next('error')).code, 'SERVER_ERROR');
|
||||||
|
} finally { S.lobby.handle = orig; }
|
||||||
|
assert.equal((await S.json('GET', '/healthz')).status, 200);
|
||||||
|
c.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('old protocol version is told to reload', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
const c = await S.client(a.idToken, { v: 0, expectFail: true });
|
||||||
|
assert.equal((await c.next('error')).code, 'OUTDATED');
|
||||||
|
assert.equal((await c.closed).code, 4002);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ping is answered with pong (for the latency overlay)', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
const c = await S.client(a.idToken);
|
||||||
|
c.send({ t: 'ping', t0: 42 });
|
||||||
|
const p = await c.next('pong');
|
||||||
|
assert.equal(p.t0, 42);
|
||||||
|
assert.equal(typeof p.serverTime, 'number');
|
||||||
|
c.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('invalid messages get an error, the socket stays open', async () => {
|
||||||
|
const a = await S.account();
|
||||||
|
const c = await S.client(a.idToken);
|
||||||
|
c.send({ t: 'input', seq: 1, throttle: 'fast' });
|
||||||
|
assert.match((await c.next('error')).code, /BAD_FIELD/);
|
||||||
|
c.ws.send('{not json');
|
||||||
|
assert.equal((await c.next('error')).code, 'BAD_JSON');
|
||||||
|
c.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('presence: join and leave are pushed to the others', async () => {
|
||||||
|
const a = await S.account('Anna'), b = await S.account('Bert');
|
||||||
|
const ca = await S.client(a.idToken);
|
||||||
|
await ca.next('lobby');
|
||||||
|
const cb = await S.client(b.idToken);
|
||||||
|
const list = await cb.next('lobby');
|
||||||
|
assert.ok(list.players.some(p => p.uid === a.uid && p.state === 'idle'));
|
||||||
|
assert.equal((await ca.next('lobby.join', m => m.player.uid === b.uid)).player.name, 'Bert');
|
||||||
|
cb.close();
|
||||||
|
assert.equal((await ca.next('lobby.leave', m => m.uid === b.uid)).uid, b.uid);
|
||||||
|
ca.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('challenge -> decline / cancel', async () => {
|
||||||
|
const a = await S.account(), b = await S.account();
|
||||||
|
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
|
||||||
|
ca.send({ t: 'challenge', to: b.uid });
|
||||||
|
assert.equal((await cb.next('challenge.in')).from, a.uid);
|
||||||
|
cb.send({ t: 'challenge.decline', from: a.uid });
|
||||||
|
assert.equal((await ca.next('challenge.gone')).reason, 'declined');
|
||||||
|
ca.send({ t: 'challenge', to: b.uid });
|
||||||
|
await cb.next('challenge.in');
|
||||||
|
ca.send({ t: 'challenge.cancel' });
|
||||||
|
assert.equal((await cb.next('challenge.gone')).reason, 'cancelled');
|
||||||
|
ca.send({ t: 'challenge', to: a.uid });
|
||||||
|
assert.equal((await ca.next('error')).code, 'NOT_AVAILABLE', 'cannot challenge yourself');
|
||||||
|
ca.close(); cb.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('full live match over WebSocket: both get start, snapshots, and mirrored results with rewards', async () => {
|
||||||
|
const a = await S.account(), b = await S.account();
|
||||||
|
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
|
||||||
|
ca.send({ t: 'challenge', to: b.uid });
|
||||||
|
await cb.next('challenge.in');
|
||||||
|
cb.send({ t: 'challenge.accept', from: a.uid });
|
||||||
|
const [sa, sb] = await Promise.all([ca.next('match.start'), cb.next('match.start')]);
|
||||||
|
assert.equal(sa.matchId, sb.matchId);
|
||||||
|
assert.deepEqual([sa.seat, sb.seat].sort(), [0, 1]);
|
||||||
|
assert.equal(sa.seed, sb.seed);
|
||||||
|
assert.equal(sa.arena, sb.arena);
|
||||||
|
assert.equal(sa.robots[sa.seat].uid, a.uid, 'my seat holds my robot');
|
||||||
|
|
||||||
|
// inputs flow in, then the server plays the rest at full speed
|
||||||
|
ca.send({ t: 'input', seq: 1, throttle: 1, turn: 0, fire: true, fire2: false, fire3: false });
|
||||||
|
await new Promise(r => setTimeout(r, 50));
|
||||||
|
fastForward(S.runner);
|
||||||
|
const [ea, eb] = await Promise.all([ca.next('match.end'), cb.next('match.end')]);
|
||||||
|
assert.deepEqual(ea.result, eb.result, 'same seat-based result for both');
|
||||||
|
const la = RC.Proto.localResult(ea.seat, ea.result).winner, lb = RC.Proto.localResult(eb.seat, eb.result).winner;
|
||||||
|
if (ea.result.winner === -1) assert.ok(la === -1 && lb === -1);
|
||||||
|
else assert.ok((la === 0) !== (lb === 0), 'exactly one player won');
|
||||||
|
assert.equal(ea.save.games, 1);
|
||||||
|
assert.ok(Array.isArray(ea.reward.ach), 'achievements decided on the server');
|
||||||
|
const winner = la === 0 ? ea : lb === 0 ? eb : null;
|
||||||
|
if (winner) assert.ok(winner.reward.ach.some(x => x.id === 'first_win'), 'first win pays out');
|
||||||
|
assert.equal(eb.save.games, 1);
|
||||||
|
const snap = ca.inbox.find(m => m.t === 'snap');
|
||||||
|
assert.ok(snap, 'snapshots arrived before the end');
|
||||||
|
assert.ok(Array.isArray(snap.rtt) && snap.rtt.length === 2, 'snapshot carries both pings');
|
||||||
|
assert.equal(typeof snap.tickMs, 'number', 'snapshot carries the server step cost');
|
||||||
|
assert.equal(typeof snap.sent, 'number');
|
||||||
|
|
||||||
|
// rewards were booked on the server
|
||||||
|
const sA = await S.json('GET', '/api/online', undefined, a.idToken);
|
||||||
|
assert.equal(sA.body.money, ea.save.money);
|
||||||
|
ca.close(); cb.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('forfeit ends the match at once; disconnect + reconnect gets the running match back', async () => {
|
||||||
|
const a = await S.account(), b = await S.account();
|
||||||
|
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
|
||||||
|
ca.send({ t: 'challenge', to: b.uid });
|
||||||
|
await cb.next('challenge.in');
|
||||||
|
cb.send({ t: 'challenge.accept', from: a.uid });
|
||||||
|
const st = await ca.next('match.start');
|
||||||
|
await cb.next('match.start');
|
||||||
|
S.runner.stop();
|
||||||
|
|
||||||
|
// b drops and comes back: gets match.start again for the same match and seat
|
||||||
|
cb.close(); await cb.closed;
|
||||||
|
await ca.next('lobby.leave', m => m.uid === b.uid);
|
||||||
|
const room = S.runner.get(st.matchId);
|
||||||
|
assert.ok(room && !room.connected(1 - st.seat), 'room marks the seat as away');
|
||||||
|
const cb2 = await S.client(b.idToken);
|
||||||
|
const again = await cb2.next('match.start');
|
||||||
|
assert.equal(again.matchId, st.matchId);
|
||||||
|
assert.equal(again.seat, 1 - st.seat);
|
||||||
|
assert.ok(room.connected(1 - st.seat));
|
||||||
|
|
||||||
|
ca.send({ t: 'match.leave' });
|
||||||
|
await new Promise(r => setTimeout(r, 30));
|
||||||
|
fastForward(S.runner);
|
||||||
|
const ea = await ca.next('match.end'), eb = await cb2.next('match.end');
|
||||||
|
assert.equal(RC.Proto.localResult(ea.seat, ea.result).winner, 1, 'the one who left lost');
|
||||||
|
assert.equal(RC.Proto.localResult(eb.seat, eb.result).winner, 0);
|
||||||
|
ca.close(); cb2.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an invalid robot cannot challenge', async () => {
|
||||||
|
const a = await S.account(), b = await S.account();
|
||||||
|
// strip the battery via the economy: equip refuses required slots, so break the save directly
|
||||||
|
const econ = require('../economy');
|
||||||
|
const s = econ.load(a.uid); s.robots[0].build.battery = null; require('../db').OnlineSaves.put(a.uid, s);
|
||||||
|
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
|
||||||
|
ca.send({ t: 'challenge', to: b.uid });
|
||||||
|
const e = await ca.next('error');
|
||||||
|
assert.equal(e.code, 'INVALID_ROBOT');
|
||||||
|
ca.close(); cb.close();
|
||||||
|
});
|
||||||
80
server/test/room.test.js
Normal file
80
server/test/room.test.js
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
'use strict';
|
||||||
|
const { test } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { Room, COUNTDOWN, GRACE } = require('../match/room');
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
const players = () => [
|
||||||
|
{ uid: 'a', name: 'A', build: RC.STARTER, paint: {} },
|
||||||
|
{ uid: 'b', name: 'B', build: RC.STARTER, paint: {} },
|
||||||
|
];
|
||||||
|
|
||||||
|
function play(room, drive, maxTicks = 60 * 200) {
|
||||||
|
let n = 0;
|
||||||
|
while (!room.ended && n++ < maxTicks) { if (drive) drive(room); room.tick(); }
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('two AI-driven seats play a whole fight to exactly one result', () => {
|
||||||
|
const snaps = [[], []];
|
||||||
|
let ends = 0;
|
||||||
|
const room = new Room({ id: 'm1', seed: 7, players: players(), send: (seat, m) => snaps[seat].push(m), onEnd: () => ends++ });
|
||||||
|
const ai = [RC.AI.create({ style: 'brawler', skill: 0.7, seed: 1 }), RC.AI.create({ style: 'rammer', skill: 0.5, seed: 2 })];
|
||||||
|
play(room, r => { if (r.tickN > COUNTDOWN) for (const k of [0, 1]) r.input(k, ai[k].think(r.s, r.s.robots[k], r.s.robots[1 - k], 1 / 60)); });
|
||||||
|
assert.ok(room.ended);
|
||||||
|
assert.equal(ends, 1, 'onEnd fires once');
|
||||||
|
assert.ok([0, 1, -1].includes(room.result.winner));
|
||||||
|
assert.ok(snaps[0].length > 50 && snaps[0].length === snaps[1].length, 'both seats get the same number of snapshots');
|
||||||
|
const last = snaps[0][snaps[0].length - 1];
|
||||||
|
assert.deepEqual(last.result, room.result, 'last snapshot carries the result');
|
||||||
|
for (const s of snaps[0]) for (const r of s.robots) assert.ok(Number.isFinite(r.x) && Number.isFinite(r.hp), 'no NaN');
|
||||||
|
// seen from each seat, exactly one of them is the winner (or both see a draw)
|
||||||
|
const a = RC.Proto.localResult(0, room.result).winner, b = RC.Proto.localResult(1, room.result).winner;
|
||||||
|
if (room.result.winner === -1) assert.ok(a === -1 && b === -1);
|
||||||
|
else assert.ok((a === 0) !== (b === 0));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('nothing moves during the countdown', () => {
|
||||||
|
const room = new Room({ id: 'm2', seed: 1, players: players() });
|
||||||
|
const x0 = room.s.robots[0].x;
|
||||||
|
room.input(0, { seq: 1, throttle: 1, turn: 0, fire: false, fire2: false, fire3: false });
|
||||||
|
for (let i = 0; i < COUNTDOWN; i++) room.tick();
|
||||||
|
assert.equal(room.s.robots[0].x, x0);
|
||||||
|
for (let i = 0; i < 30; i++) room.tick();
|
||||||
|
assert.notEqual(room.s.robots[0].x, x0, 'moves once the countdown is over');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('inputs are clamped and acked per seat', () => {
|
||||||
|
const room = new Room({ id: 'm3', seed: 1, players: players() });
|
||||||
|
room.input(1, { seq: 42, throttle: 9, turn: -9, fire: true, fire2: false, fire3: false });
|
||||||
|
assert.deepEqual(room.inputs[1], { throttle: 1, turn: -1, fire: true, fire2: false, fire3: false });
|
||||||
|
assert.deepEqual(room.acks, [0, 42]);
|
||||||
|
room.input(5, { seq: 1 }); // bogus seat is ignored
|
||||||
|
assert.deepEqual(room.acks, [0, 42]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a disconnected seat stands still, then the AI takes over; the fight still ends', () => {
|
||||||
|
const room = new Room({ id: 'm4', seed: 3, players: players() });
|
||||||
|
for (let i = 0; i < COUNTDOWN; i++) room.tick();
|
||||||
|
room.input(1, { seq: 1, throttle: 1, turn: 0.3, fire: true, fire2: false, fire3: false });
|
||||||
|
room.disconnect(1);
|
||||||
|
assert.deepEqual(room.inputFor(1), RC.Proto.input(null), 'grace: neutral input');
|
||||||
|
for (let i = 0; i < GRACE; i++) room.tick();
|
||||||
|
room.inputFor(1);
|
||||||
|
assert.ok(room.ai[1], 'AI drives after the grace period');
|
||||||
|
room.reconnect(1);
|
||||||
|
assert.equal(room.ai[1], null);
|
||||||
|
assert.deepEqual(room.inputFor(1), room.inputs[1], 'reconnected: own input again');
|
||||||
|
room.disconnect(1);
|
||||||
|
play(room);
|
||||||
|
assert.ok(room.ended, 'fight ends even with one player gone');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('summary reports damage for rewards', () => {
|
||||||
|
const room = new Room({ id: 'm5', seed: 2, players: players() });
|
||||||
|
room.s.robots[0].dealt = 12; room.s.robots[0].hp = 10;
|
||||||
|
const sm = room.summary(0);
|
||||||
|
assert.equal(sm.dealt, 12);
|
||||||
|
assert.equal(sm.hp, 10);
|
||||||
|
assert.ok(sm.maxHp > 0);
|
||||||
|
});
|
||||||
66
server/ws/hub.js
Normal file
66
server/ws/hub.js
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
/* WebSocket endpoint /ws. Every socket must say { t:'hello', v, token } within HELLO_MS, then its messages
|
||||||
|
are validated (RC.Proto.check), rate limited and handed to the lobby. Keepalive via ws ping/pong. */
|
||||||
|
'use strict';
|
||||||
|
const { WebSocketServer } = require('ws');
|
||||||
|
const RC = require('../../game/protocol.js');
|
||||||
|
const auth = require('../auth');
|
||||||
|
|
||||||
|
const HELLO_MS = 5000;
|
||||||
|
const RATE = 80; // messages per second per socket (inputs ~30/s + lobby)
|
||||||
|
const PING_MS = 2000; // ws ping every 2 s: keepalive + ping measurement
|
||||||
|
const DEAD_MS = 15000; // no pong for this long -> connection is dead
|
||||||
|
|
||||||
|
function attach(server, { lobby }) {
|
||||||
|
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: RC.Proto.MAX_MSG });
|
||||||
|
|
||||||
|
wss.on('connection', ws => {
|
||||||
|
let user = null, tokens = RATE, last = Date.now();
|
||||||
|
ws.lastPong = Date.now();
|
||||||
|
ws.on('pong', () => {
|
||||||
|
ws.lastPong = Date.now();
|
||||||
|
if (ws.pingSent && user) lobby.setRtt(user.uid, Number(process.hrtime.bigint() - ws.pingSent) / 1e6);
|
||||||
|
ws.pingSent = 0n;
|
||||||
|
});
|
||||||
|
const send = msg => { if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg)); };
|
||||||
|
const bye = (code, reason) => { try { ws.close(code, reason); } catch (e) { /* closed */ } };
|
||||||
|
const helloTimer = setTimeout(() => { if (!user) bye(4001, 'HELLO_TIMEOUT'); }, HELLO_MS);
|
||||||
|
|
||||||
|
ws.on('message', (data, isBinary) => {
|
||||||
|
// token bucket
|
||||||
|
const now = Date.now(); tokens = Math.min(RATE, tokens + (now - last) * RATE / 1000); last = now;
|
||||||
|
if (--tokens < 0) return bye(4008, 'RATE_LIMIT');
|
||||||
|
let msg;
|
||||||
|
try { msg = JSON.parse(isBinary ? data : data.toString()); } catch (e) { return send({ t: 'error', code: 'BAD_JSON' }); }
|
||||||
|
const c = RC.Proto.check(msg);
|
||||||
|
if (!c.ok) return send({ t: 'error', code: c.error });
|
||||||
|
if (!user) {
|
||||||
|
if (msg.t !== 'hello') return bye(4001, 'HELLO_FIRST');
|
||||||
|
if (msg.v !== RC.Proto.VERSION) { send({ t: 'error', code: 'OUTDATED', need: RC.Proto.VERSION }); return bye(4002, 'OUTDATED'); }
|
||||||
|
const u = auth.verify(msg.token);
|
||||||
|
if (!u) { send({ t: 'error', code: 'UNAUTH' }); return bye(4003, 'UNAUTH'); }
|
||||||
|
clearTimeout(helloTimer);
|
||||||
|
user = u;
|
||||||
|
send({ t: 'welcome', uid: u.uid, name: u.name, serverTime: Date.now(), v: RC.Proto.VERSION });
|
||||||
|
try { lobby.join({ uid: u.uid, name: u.name, admin: u.admin, send }); } catch (e) { console.error('[ws] join failed', e); bye(1011, 'SERVER_ERROR'); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (msg.t === 'hello') return;
|
||||||
|
try { lobby.handle(user.uid, msg); } catch (e) { console.error('[ws] handler failed for', msg.t, e); send({ t: 'error', code: 'SERVER_ERROR' }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
ws.on('close', () => { clearTimeout(helloTimer); if (user) { try { lobby.leave(user.uid, send); } catch (e) { console.error('[ws] leave failed', e); } } });
|
||||||
|
ws.on('error', () => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
const beat = setInterval(() => {
|
||||||
|
for (const ws of wss.clients) {
|
||||||
|
if (Date.now() - ws.lastPong > DEAD_MS) { ws.terminate(); continue; }
|
||||||
|
try { ws.pingSent = process.hrtime.bigint(); ws.ping(); } catch (e) { /* closed */ }
|
||||||
|
}
|
||||||
|
}, PING_MS);
|
||||||
|
if (beat.unref) beat.unref();
|
||||||
|
wss.on('close', () => clearInterval(beat));
|
||||||
|
return wss;
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { attach };
|
||||||
37
tests/e2e/helpers.js
Normal file
37
tests/e2e/helpers.js
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
/* Shared steps for the browser tests: log in through the real UI, get from the workshop into the lobby. */
|
||||||
|
'use strict';
|
||||||
|
const { expect } = require('@playwright/test');
|
||||||
|
|
||||||
|
const mode = page => page.locator('body').getAttribute('data-mode');
|
||||||
|
|
||||||
|
// open the game in online mode and log in with name + password through the login card
|
||||||
|
async function login(page, name, pass, query = '') {
|
||||||
|
await page.goto('/?online' + query);
|
||||||
|
await page.locator('#oLogin').fill(name);
|
||||||
|
await page.locator('#oPass').fill(pass);
|
||||||
|
await page.locator('#oGo').click();
|
||||||
|
await chooseCountry(page);
|
||||||
|
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
|
||||||
|
await expect(page.locator('#hUser')).toContainText(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
// first start asks for a country - take the default
|
||||||
|
async function chooseCountry(page) {
|
||||||
|
const go = page.locator('#cfGo');
|
||||||
|
try { await go.waitFor({ timeout: 4000 }); await go.click(); } catch (e) { /* already chosen */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toLobby(page) {
|
||||||
|
await page.locator('#bLeague').click();
|
||||||
|
await expect(page.locator('body')).toHaveAttribute('data-mode', 'lobby');
|
||||||
|
}
|
||||||
|
|
||||||
|
// the header shows big amounts short like Kit.fmt does ("10.8K", "1.20M", "3B")
|
||||||
|
const UNIT = { K: 1e3, M: 1e6, B: 1e9 };
|
||||||
|
const parseCredits = text => {
|
||||||
|
const m = String(text).replace(/[,\s]/g, '').match(/([\d.]+)([KMB]?)/i);
|
||||||
|
return m ? Math.round(parseFloat(m[1]) * (UNIT[(m[2] || '').toUpperCase()] || 1)) : NaN;
|
||||||
|
};
|
||||||
|
const credits = async page => parseCredits(await page.locator('#hMoney').textContent());
|
||||||
|
|
||||||
|
module.exports = { mode, login, chooseCountry, toLobby, credits, parseCredits };
|
||||||
48
tests/e2e/netlag.spec.js
Normal file
48
tests/e2e/netlag.spec.js
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
// Repeatable lag test: one client gets a seeded snapshot delay+jitter (?netlag). The opponent robot must still
|
||||||
|
// move SMOOTHLY on that client (entity interpolation), i.e. no large per-step jumps - the bug Michi reported.
|
||||||
|
'use strict';
|
||||||
|
const { test, expect } = require('@playwright/test');
|
||||||
|
const { login, toLobby } = require('./helpers');
|
||||||
|
|
||||||
|
test('a jittery client still sees the opponent move smoothly (interpolation buffer)', async ({ browser }) => {
|
||||||
|
const ctxA = await browser.newContext(), ctxB = await browser.newContext();
|
||||||
|
const a = await ctxA.newPage(), b = await ctxB.newPage();
|
||||||
|
const errors = [];
|
||||||
|
for (const p of [a, b]) p.on('pageerror', e => errors.push(e.message));
|
||||||
|
|
||||||
|
// michi gets a repeatable snapshot delay + jitter (80 ms +/- 40 ms, seeded) + the position probe
|
||||||
|
await login(a, 'michi', 'Michi2000!', '&netlag=80,40,7&netprobe');
|
||||||
|
await login(b, 'benni', 'Benni2000!');
|
||||||
|
await toLobby(a); await toLobby(b);
|
||||||
|
|
||||||
|
await a.locator('.prow', { hasText: 'benni' }).locator('.chal').click();
|
||||||
|
await expect(b.locator('#cYes')).toBeVisible();
|
||||||
|
await b.locator('#cYes').click();
|
||||||
|
await expect(a.locator('body')).toHaveAttribute('data-mode', 'fight');
|
||||||
|
await expect(b.locator('body')).toHaveAttribute('data-mode', 'fight');
|
||||||
|
|
||||||
|
await a.waitForTimeout(4200); // countdown
|
||||||
|
await a.evaluate(() => { globalThis.__probe.length = 0; });
|
||||||
|
await b.keyboard.down('w'); // benni drives so his robot moves across michi's screen
|
||||||
|
await a.keyboard.down('a'); // michi turns a bit (keeps both sides active)
|
||||||
|
await a.waitForTimeout(2600);
|
||||||
|
await b.keyboard.up('w'); await a.keyboard.up('a');
|
||||||
|
|
||||||
|
const probe = await a.evaluate(() => globalThis.__probe.slice());
|
||||||
|
// consider only samples while the opponent was actually moving
|
||||||
|
const deltas = [];
|
||||||
|
let moved = 0;
|
||||||
|
for (let i = 1; i < probe.length; i++) {
|
||||||
|
const dx = probe[i].x - probe[i - 1].x, dz = probe[i].z - probe[i - 1].z;
|
||||||
|
const d = Math.hypot(dx, dz);
|
||||||
|
deltas.push(d); moved += d;
|
||||||
|
}
|
||||||
|
expect(probe.length, 'probe collected samples').toBeGreaterThan(30);
|
||||||
|
expect(moved, 'the opponent actually moved (test is meaningful)').toBeGreaterThan(0.8);
|
||||||
|
const maxJump = Math.max(...deltas);
|
||||||
|
// at ~5 m/s over a 60 Hz step a smooth move is ~0.08/step; a snapshot-jump would be several times that.
|
||||||
|
expect(maxJump, 'no large per-step jump despite jitter (smooth interpolation)').toBeLessThan(0.35);
|
||||||
|
|
||||||
|
expect(errors, 'no JavaScript errors').toEqual([]);
|
||||||
|
await ctxA.close(); await ctxB.close();
|
||||||
|
});
|
||||||
29
tests/e2e/offline.spec.js
Normal file
29
tests/e2e/offline.spec.js
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
// The offline campaign must keep working without any server (double-click on game/index.html = file://).
|
||||||
|
'use strict';
|
||||||
|
const { test, expect } = require('@playwright/test');
|
||||||
|
const path = require('path');
|
||||||
|
const { pathToFileURL } = require('url');
|
||||||
|
const { credits } = require('./helpers');
|
||||||
|
|
||||||
|
const file = pathToFileURL(path.join(__dirname, '..', '..', 'game', 'index.html')).href;
|
||||||
|
|
||||||
|
test('campaign runs from file:// : training fight with the AI pilot, layout check passes', async ({ page }) => {
|
||||||
|
const errors = [];
|
||||||
|
page.on('pageerror', e => errors.push(e.message));
|
||||||
|
await page.goto(file + '?play&fight=2&auto&ff=20&uicheck');
|
||||||
|
await expect(page.locator('body')).toHaveAttribute('data-gmode', 'campaign');
|
||||||
|
await expect(page.locator('body')).toHaveAttribute('data-mode', /fight|result/);
|
||||||
|
await expect(page.locator('#uicheck')).toContainText('UI ok');
|
||||||
|
expect(errors).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('campaign workshop: buying a part works offline', async ({ page }) => {
|
||||||
|
await page.goto(file + '?play');
|
||||||
|
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
|
||||||
|
const money = () => credits(page);
|
||||||
|
const before = await money();
|
||||||
|
await page.locator('.tab[data-slot="armour"]').click();
|
||||||
|
await page.locator('#cards .item:not(:has(.badge)):not(:has(.pr.no))').first().click();
|
||||||
|
await page.locator('#detail button[data-act="buy"]').click();
|
||||||
|
expect(await money()).toBeLessThan(before);
|
||||||
|
});
|
||||||
103
tests/e2e/online.spec.js
Normal file
103
tests/e2e/online.spec.js
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
// Two real browsers play a live fight through the server: login, lobby, challenge, accept, fight, give up, result.
|
||||||
|
'use strict';
|
||||||
|
const { test, expect } = require('@playwright/test');
|
||||||
|
const { login, toLobby, credits, chooseCountry } = require('./helpers');
|
||||||
|
|
||||||
|
test('michi challenges benni, benni gives up: mirrored result and server-booked rewards', async ({ browser }) => {
|
||||||
|
const ctxA = await browser.newContext(), ctxB = await browser.newContext();
|
||||||
|
const a = await ctxA.newPage(), b = await ctxB.newPage();
|
||||||
|
const errors = [];
|
||||||
|
for (const p of [a, b]) p.on('pageerror', e => errors.push(e.message));
|
||||||
|
|
||||||
|
await login(a, 'michi', 'Michi2000!');
|
||||||
|
await login(b, 'benni', 'Benni2000!');
|
||||||
|
const moneyA = await credits(a), moneyB = await credits(b);
|
||||||
|
await toLobby(a);
|
||||||
|
await toLobby(b);
|
||||||
|
|
||||||
|
// each sees the other in the lobby
|
||||||
|
await expect(a.locator('.prow', { hasText: 'benni' })).toBeVisible();
|
||||||
|
await expect(b.locator('.prow', { hasText: 'michi' })).toBeVisible();
|
||||||
|
|
||||||
|
// challenge -> incoming card -> accept -> both are in the fight
|
||||||
|
await a.locator('.prow', { hasText: 'benni' }).locator('.chal').click();
|
||||||
|
await expect(a.locator('#lCancel')).toBeVisible();
|
||||||
|
await expect(b.locator('#cYes')).toBeVisible();
|
||||||
|
await b.locator('#cYes').click();
|
||||||
|
await expect(a.locator('body')).toHaveAttribute('data-mode', 'fight');
|
||||||
|
await expect(b.locator('body')).toHaveAttribute('data-mode', 'fight');
|
||||||
|
await expect(a.locator('#fN1')).toHaveText('benni');
|
||||||
|
await expect(b.locator('#fN1')).toHaveText('michi');
|
||||||
|
|
||||||
|
// the fight runs on the server: after the countdown michi drives - the clock must tick down
|
||||||
|
await a.waitForTimeout(4500);
|
||||||
|
await a.keyboard.down('w');
|
||||||
|
await a.waitForTimeout(1500);
|
||||||
|
await a.keyboard.up('w');
|
||||||
|
await expect(a.locator('#fightHud')).not.toContainText('2:00');
|
||||||
|
|
||||||
|
// benni gives up through the pause card (live: no pause, the fight keeps running)
|
||||||
|
await b.keyboard.press('p');
|
||||||
|
await expect(b.locator('#bGiveUp')).toBeVisible();
|
||||||
|
await b.locator('#bGiveUp').click();
|
||||||
|
|
||||||
|
// result: michi wins, benni loses - never both "victory" (the old mirrored-result bug)
|
||||||
|
await expect(a.locator('body')).toHaveAttribute('data-mode', 'result', { timeout: 20000 });
|
||||||
|
await expect(b.locator('body')).toHaveAttribute('data-mode', 'result', { timeout: 20000 });
|
||||||
|
await expect(a.locator('#overlay h1')).toHaveText(/victory/i);
|
||||||
|
await expect(b.locator('#overlay h1')).toHaveText(/defeat/i);
|
||||||
|
|
||||||
|
// rewards came from the server and survive a reload (server is the authority)
|
||||||
|
const afterA = await credits(a), afterB = await credits(b);
|
||||||
|
expect(afterA).toBeGreaterThan(moneyA);
|
||||||
|
expect(afterB).toBeGreaterThanOrEqual(moneyB);
|
||||||
|
await a.reload();
|
||||||
|
await chooseCountry(a);
|
||||||
|
await expect(a.locator('body')).toHaveAttribute('data-mode', 'garage');
|
||||||
|
await expect.poll(() => credits(a)).toBe(afterA);
|
||||||
|
|
||||||
|
expect(errors, 'no JavaScript errors in either browser').toEqual([]);
|
||||||
|
await ctxA.close(); await ctxB.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shop purchase is checked and stored by the server', async ({ browser }) => {
|
||||||
|
const ctx = await browser.newContext();
|
||||||
|
const page = await ctx.newPage();
|
||||||
|
await page.goto('/?online');
|
||||||
|
await page.locator('#oAnon').click(); // guest account on the server
|
||||||
|
await chooseCountry(page);
|
||||||
|
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
|
||||||
|
const before = await credits(page);
|
||||||
|
|
||||||
|
await page.locator('.tab[data-slot="armour"]').click();
|
||||||
|
const item = page.locator('#cards .item:not(:has(.badge)):not(:has(.pr.no))').first();
|
||||||
|
await item.click();
|
||||||
|
await page.locator('#detail button[data-act="buy"]').click();
|
||||||
|
await expect.poll(() => credits(page)).toBeLessThan(before);
|
||||||
|
const after = await credits(page);
|
||||||
|
|
||||||
|
// what the server stored
|
||||||
|
const token = await page.evaluate(() => JSON.parse(localStorage.getItem('robotclash.net.session')).idToken);
|
||||||
|
const res = await page.request.get('/api/online', { headers: { Authorization: 'Bearer ' + token } });
|
||||||
|
const srv = await res.json();
|
||||||
|
expect(srv.money).toBe(after);
|
||||||
|
expect(srv.build.armour).toBeTruthy();
|
||||||
|
|
||||||
|
// the client cannot simply give itself money
|
||||||
|
const cheat = await page.request.put('/api/online/save', { headers: { Authorization: 'Bearer ' + token }, data: { money: 999999 } });
|
||||||
|
expect((await cheat.json()).money).toBe(after);
|
||||||
|
await ctx.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('F3 network overlay: hidden at start, F3 shows it with content, F3 hides it again', async ({ page }) => {
|
||||||
|
await login(page, 'benni', 'Benni2000!');
|
||||||
|
const ov = page.locator('#netov');
|
||||||
|
await expect(ov).toBeHidden(); // regression: an empty box was always on screen
|
||||||
|
await page.keyboard.press('F3');
|
||||||
|
await expect(ov).toBeVisible();
|
||||||
|
await expect(ov).toContainText(/ping/i);
|
||||||
|
await page.keyboard.press('F3');
|
||||||
|
await expect(ov).toBeHidden(); // regression: it could not be closed again
|
||||||
|
await page.keyboard.press('F3');
|
||||||
|
await expect(ov).toBeVisible();
|
||||||
|
});
|
||||||
89
tests/e2e/screens.spec.js
Normal file
89
tests/e2e/screens.spec.js
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
// Every menu page and workshop tool once, in the real browser, offline (file://) - guards the game.js split:
|
||||||
|
// a missing reference between the modules shows up here as a JavaScript error.
|
||||||
|
'use strict';
|
||||||
|
const { test, expect } = require('@playwright/test');
|
||||||
|
const path = require('path');
|
||||||
|
const { pathToFileURL } = require('url');
|
||||||
|
|
||||||
|
const file = pathToFileURL(path.join(__dirname, '..', '..', 'game', 'index.html')).href;
|
||||||
|
const { credits: money } = require('./helpers');
|
||||||
|
|
||||||
|
test.beforeEach(async ({ page }) => {
|
||||||
|
page.errors = [];
|
||||||
|
page.on('pageerror', e => page.errors.push(e.message));
|
||||||
|
await page.goto(file + '?play');
|
||||||
|
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
|
||||||
|
});
|
||||||
|
test.afterEach(async ({ page }) => { expect(page.errors, 'no JavaScript errors').toEqual([]); });
|
||||||
|
|
||||||
|
test('menu pages: settings, controls, legal, achievements, missions', async ({ page }) => {
|
||||||
|
await page.locator('#bSettings').click();
|
||||||
|
await expect(page.locator('#sKeys')).toBeVisible();
|
||||||
|
await page.locator('#sKeys').click(); // controls page from settings
|
||||||
|
await page.locator('#bOk').click();
|
||||||
|
await expect(page.locator('#sLegal')).toBeVisible(); // back in settings
|
||||||
|
await page.locator('#sLegal').click();
|
||||||
|
await page.locator('#bOk').click();
|
||||||
|
await page.locator('#bBack').click();
|
||||||
|
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
|
||||||
|
|
||||||
|
await page.locator('#chipFame').click(); // achievements
|
||||||
|
await expect(page.locator('.achlist')).toBeVisible();
|
||||||
|
await page.locator('#bBack').click();
|
||||||
|
|
||||||
|
await page.locator('#bMissions').click(); // campaign missions
|
||||||
|
await expect(page.locator('.misslist').first()).toBeVisible();
|
||||||
|
await page.locator('#bBack').click();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('guest via the title: country, tutorial, then dev coins go through the economy', async ({ page }) => {
|
||||||
|
await page.goto(file + '?title');
|
||||||
|
await page.locator('#bGuest').click();
|
||||||
|
await page.locator('#cfGo').click(); // country card
|
||||||
|
await page.locator('#tSkip').click(); // tutorial cards
|
||||||
|
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
|
||||||
|
await page.locator('#bSettings').click();
|
||||||
|
await page.locator('[data-coin="10000"]').click();
|
||||||
|
await page.locator('#bBack').click();
|
||||||
|
expect(await money(page)).toBeGreaterThanOrEqual(10800);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('weapon editor: buy, place, sell a weapon', async ({ page }) => {
|
||||||
|
const start = await money(page);
|
||||||
|
await page.locator('.tab[data-slot="weapon"]').click();
|
||||||
|
await expect(page.locator('#wplace')).toBeVisible();
|
||||||
|
const before = await page.locator('.wphead').first().textContent();
|
||||||
|
await page.locator('#cards .item:not(:has(.pr.no))').first().click();
|
||||||
|
await page.locator('#detail button[data-wact="add"]').click();
|
||||||
|
expect(await money(page)).toBeLessThan(start);
|
||||||
|
await expect(page.locator('.wphead').first()).not.toHaveText(before); // weapon count went up
|
||||||
|
await page.locator('[data-side="left"]').click();
|
||||||
|
await expect(page.locator('[data-side="left"]')).toHaveClass(/on/);
|
||||||
|
await page.locator('#detail button[data-wact="rem"]').click();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('paint tab: colour, scheme, paint slots', async ({ page }) => {
|
||||||
|
await page.locator('#shopTabs [data-tab="paint"]').click();
|
||||||
|
await expect(page.locator('#paintHdr')).toBeVisible();
|
||||||
|
await page.locator('#paintBody .sw:not(.locked)').nth(2).click();
|
||||||
|
await expect(page.locator('#paintBody .sw.on')).toHaveCount(1);
|
||||||
|
await page.locator('#paintSchemes .sw').nth(1).click();
|
||||||
|
await page.locator('[data-save="1"]').click(); // store into slot 2
|
||||||
|
await page.locator('[data-load="0"]').click(); // load slot 1
|
||||||
|
await expect(page.locator('.pslot.on')).toHaveCount(1);
|
||||||
|
await page.locator('#shopTabs [data-tab="build"]').click();
|
||||||
|
await expect(page.locator('#paintHdr')).toHaveCount(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hangar: new robot, switch, delete', async ({ page }) => {
|
||||||
|
await page.locator('#shopTabs [data-tab="hangar"]').click();
|
||||||
|
await expect(page.locator('.hmrow')).toHaveCount(1);
|
||||||
|
await page.locator('#hAdd').click();
|
||||||
|
await page.locator('#shopTabs [data-tab="hangar"]').click();
|
||||||
|
await expect(page.locator('.hmrow')).toHaveCount(2);
|
||||||
|
await page.locator('[data-use="0"]').click();
|
||||||
|
await page.locator('#shopTabs [data-tab="hangar"]').click();
|
||||||
|
await expect(page.locator('.hmrow.on')).toHaveAttribute('data-i', '0');
|
||||||
|
await page.locator('[data-del="1"]').click();
|
||||||
|
await expect(page.locator('.hmrow')).toHaveCount(1);
|
||||||
|
});
|
||||||
17
tests/e2e/server.js
Normal file
17
tests/e2e/server.js
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
/* Server for the browser tests: fresh database file every run, seed accounts michi / benni, then the real app. */
|
||||||
|
'use strict';
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const file = path.join(os.tmpdir(), 'robotclash-e2e.sqlite');
|
||||||
|
for (const ext of ['', '-wal', '-shm']) fs.rmSync(file + ext, { force: true });
|
||||||
|
process.env.DB_FILE = file;
|
||||||
|
process.env.NODE_ENV = 'test'; // high auth rate limit, no secret warning
|
||||||
|
process.env.PORT = process.env.PORT || '8099';
|
||||||
|
|
||||||
|
const { createUser } = require('../../server/auth');
|
||||||
|
const economy = require('../../server/economy');
|
||||||
|
for (const [name, pass] of [['michi', 'Michi2000!'], ['benni', 'Benni2000!']]) economy.load(createUser({ name, pass, role: 'admin' }).uid);
|
||||||
|
|
||||||
|
require('../../server/app').listen().then(srv => console.log('e2e server on :' + srv.address().port));
|
||||||
128
tests/eco.test.js
Normal file
128
tests/eco.test.js
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
'use strict';
|
||||||
|
const { test } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const path = require('path');
|
||||||
|
for (const f of ['parts.js', 'robot.js', 'eco.js']) require(path.join(__dirname, '..', 'game', f));
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
const E = RC.Eco;
|
||||||
|
|
||||||
|
const fresh = () => E.newOnlineSave();
|
||||||
|
const anyPart = (slot, notIn = []) => Object.values(RC.PARTS).find(p => p.slot === slot && !notIn.includes(p.id) && !Object.values(RC.STARTER).includes(p.id));
|
||||||
|
|
||||||
|
test('fresh online save is a valid starter robot with 800 credits', () => {
|
||||||
|
const s = fresh();
|
||||||
|
assert.equal(s.money, 800);
|
||||||
|
assert.ok(RC.validate(s.build).ok);
|
||||||
|
assert.equal(s.build, s.robots[0].build, 'mirror points at the active robot');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buy: deducts, owns, equips; refuses without money or twice', () => {
|
||||||
|
const s = fresh(), p = anyPart('armour');
|
||||||
|
s.money = p.cost;
|
||||||
|
assert.ok(E.apply(s, { type: 'buy', part: p.id }).ok);
|
||||||
|
assert.equal(s.money, 0);
|
||||||
|
assert.ok(s.owned.includes(p.id));
|
||||||
|
assert.equal(s.build.armour, p.id);
|
||||||
|
assert.equal(E.apply(s, { type: 'buy', part: p.id }).error, 'OWNED');
|
||||||
|
const q = anyPart('armour', [p.id]);
|
||||||
|
assert.equal(E.apply(s, { type: 'buy', part: q.id }).error, 'NO_MONEY');
|
||||||
|
assert.equal(E.apply(s, { type: 'buy', part: 'nope' }).error, 'BAD_PART');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('sell: 50 %, never while fitted on any robot, starter kit sells for 0', () => {
|
||||||
|
const s = fresh(), p = anyPart('armour');
|
||||||
|
s.money = 10000;
|
||||||
|
E.apply(s, { type: 'buy', part: p.id });
|
||||||
|
assert.equal(E.apply(s, { type: 'sell', part: p.id }).error, 'IN_USE');
|
||||||
|
E.apply(s, { type: 'equip', slot: 'armour', part: null });
|
||||||
|
const before = s.money;
|
||||||
|
assert.ok(E.apply(s, { type: 'sell', part: p.id }).ok);
|
||||||
|
assert.equal(s.money - before, Math.round(p.cost * 0.5));
|
||||||
|
// fitted on a second robot only -> still in use
|
||||||
|
E.apply(s, { type: 'buy', part: p.id });
|
||||||
|
E.apply(s, { type: 'robotNew' });
|
||||||
|
assert.equal(E.apply(s, { type: 'sell', part: p.id }).error, 'IN_USE', 'used by robot 0');
|
||||||
|
assert.equal(E.sellValue(RC.STARTER.chassis), 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('exploit closed: new robot -> sell its starter weapon -> delete robot gains nothing', () => {
|
||||||
|
const s = fresh();
|
||||||
|
const start = s.money;
|
||||||
|
for (let i = 0; i < 3; i++) {
|
||||||
|
E.apply(s, { type: 'robotNew' });
|
||||||
|
while (s.build.weapons.length) E.apply(s, { type: 'weaponRemove', index: 0 });
|
||||||
|
E.apply(s, { type: 'robotDelete', index: s.active });
|
||||||
|
}
|
||||||
|
assert.equal(s.money, start);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('equip: only owned parts of the right slot; required slots cannot be emptied', () => {
|
||||||
|
const s = fresh(), p = anyPart('motor');
|
||||||
|
assert.equal(E.apply(s, { type: 'equip', slot: 'motor', part: p.id }).error, 'NOT_OWNED');
|
||||||
|
assert.equal(E.apply(s, { type: 'equip', slot: 'motor', part: null }).error, 'REQUIRED');
|
||||||
|
assert.equal(E.apply(s, { type: 'equip', slot: 'armour', part: RC.STARTER.motor }).error, 'BAD_PART');
|
||||||
|
assert.equal(E.apply(s, { type: 'equip', slot: 'weapon', part: null }).error, 'BAD_SLOT');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('weapons: add costs money, max 3, remove refunds, placement is clamped', () => {
|
||||||
|
const s = fresh(), w = anyPart('weapon');
|
||||||
|
s.money = 1e6;
|
||||||
|
while (s.build.weapons.length < RC.MAX_WEAPONS) assert.ok(E.apply(s, { type: 'weaponAdd', part: w.id }).ok);
|
||||||
|
assert.equal(E.apply(s, { type: 'weaponAdd', part: w.id }).error, 'MAX_WEAPONS');
|
||||||
|
assert.ok(E.apply(s, { type: 'weaponPlace', index: 1, side: 'left', up: 5 }).ok);
|
||||||
|
assert.equal(s.build.weapons[1].side, 'left');
|
||||||
|
assert.equal(s.build.weapons[1].up, 0.6);
|
||||||
|
assert.equal(E.apply(s, { type: 'weaponPlace', index: 1, side: 'top' }).error, 'BAD_SIDE');
|
||||||
|
const m = s.money;
|
||||||
|
assert.ok(E.apply(s, { type: 'weaponRemove', index: 1 }).ok);
|
||||||
|
assert.equal(s.money - m, Math.round(w.cost * 0.5));
|
||||||
|
assert.equal(E.apply(s, { type: 'weaponRemove', index: 9 }).error, 'BAD_INDEX');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('hangar: max 6 robots, keep at least one, active index follows deletes', () => {
|
||||||
|
const s = fresh();
|
||||||
|
for (let i = 1; i < E.MAX_ROBOTS; i++) assert.ok(E.apply(s, { type: 'robotNew', name: 'R' + i }).ok);
|
||||||
|
assert.equal(E.apply(s, { type: 'robotNew' }).error, 'HANGAR_FULL');
|
||||||
|
E.apply(s, { type: 'robotSwitch', index: 4 });
|
||||||
|
E.apply(s, { type: 'robotDelete', index: 1 });
|
||||||
|
assert.equal(s.active, 3);
|
||||||
|
assert.equal(s.robotName, 'R4');
|
||||||
|
assert.equal(s.build, s.robots[s.active].build);
|
||||||
|
while (s.robots.length > 1) E.apply(s, { type: 'robotDelete', index: 0 });
|
||||||
|
assert.equal(E.apply(s, { type: 'robotDelete', index: 0 }).error, 'LAST_ROBOT');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unknown / malformed actions are refused without changes', () => {
|
||||||
|
const s = fresh(), snap = JSON.stringify(s);
|
||||||
|
assert.equal(E.apply(s, { type: 'toString' }).error, 'BAD_ACTION');
|
||||||
|
assert.equal(E.apply(s, { type: '__proto__' }).error, 'BAD_ACTION');
|
||||||
|
assert.equal(E.apply(s, null).error, 'BAD_ACTION');
|
||||||
|
assert.equal(E.apply(s, { type: 'body', hx: 'x' }).error, 'BAD_BODY');
|
||||||
|
assert.equal(JSON.stringify(s), snap);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pvpReward: win/draw/loss, bonus, repair never below zero', () => {
|
||||||
|
const win = E.pvpReward({ won: true, winner: 0, reason: 'ko', dealt: 100, hp: 50, maxHp: 100, value: 1000, money: 0 });
|
||||||
|
assert.equal(win.fame, 190);
|
||||||
|
assert.equal(win.money, 600 + 120 + 60 - 30);
|
||||||
|
const loss = E.pvpReward({ won: false, winner: 1, reason: 'ko', dealt: 0, hp: 0, maxHp: 100, value: 1e6, money: 0 });
|
||||||
|
assert.equal(loss.money, 0, 'repair capped at what you have');
|
||||||
|
const draw = E.pvpReward({ won: false, winner: -1, reason: 'time', dealt: 0, hp: 100, maxHp: 100, value: 0 });
|
||||||
|
assert.equal(draw.money, 300);
|
||||||
|
assert.ok(draw.draw);
|
||||||
|
const s = fresh(); E.applyReward(s, win);
|
||||||
|
assert.equal(s.wins, 1); assert.equal(s.games, 1); assert.equal(s.best, 190);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mergeCosmetics takes names/paint/flags but never economy or robot count', () => {
|
||||||
|
const s = fresh();
|
||||||
|
E.mergeCosmetics(s, { money: 1e9, owned: ['x'], flag: 'DE', robots: [{ name: 'Zed', paint: { body: 0x123456, accent: -5, decal: 'javascript:1' }, build: { chassis: 'x' } }, { name: 'ghost' }] });
|
||||||
|
assert.equal(s.money, 800);
|
||||||
|
assert.equal(s.flag, 'DE');
|
||||||
|
assert.equal(s.robots.length, 1);
|
||||||
|
assert.equal(s.robotName, 'Zed');
|
||||||
|
assert.equal(s.paint.body, 0x123456);
|
||||||
|
assert.equal(s.paint.accent, 0x15171b, 'bad colour ignored');
|
||||||
|
assert.equal(s.paint.decal, null, 'non-PNG decal ignored');
|
||||||
|
assert.equal(s.build.chassis, RC.STARTER.chassis);
|
||||||
|
});
|
||||||
49
tests/netfight.test.js
Normal file
49
tests/netfight.test.js
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
'use strict';
|
||||||
|
// Entity-interpolation math for the live fight (the jitter buffer that stops the robot from jumping).
|
||||||
|
const { test } = require('node:test');
|
||||||
|
const assert = require('node:assert');
|
||||||
|
const path = require('path');
|
||||||
|
require(path.join(__dirname, '..', 'game', 'protocol.js'));
|
||||||
|
require(path.join(__dirname, '..', 'game', 'netfight.js'));
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
const { pickFrames, lerpRobot } = RC.NetFight;
|
||||||
|
|
||||||
|
test('pickFrames: brackets the render time and gives the fraction between the two snapshots', () => {
|
||||||
|
const buf = [{ at: 0, tick: 1 }, { at: 100, tick: 2 }];
|
||||||
|
const fr = pickFrames(buf, 50);
|
||||||
|
assert.strictEqual(fr.a.tick, 1);
|
||||||
|
assert.strictEqual(fr.b.tick, 2);
|
||||||
|
assert.ok(Math.abs(fr.frac - 0.5) < 1e-9);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pickFrames: past the newest snapshot holds it (no extrapolation jump)', () => {
|
||||||
|
const buf = [{ at: 0, tick: 1 }, { at: 100, tick: 2 }];
|
||||||
|
const fr = pickFrames(buf, 500);
|
||||||
|
assert.strictEqual(fr.a.tick, 2);
|
||||||
|
assert.strictEqual(fr.b.tick, 2);
|
||||||
|
assert.strictEqual(fr.frac, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pickFrames: empty buffer -> null', () => {
|
||||||
|
assert.strictEqual(pickFrames([], 0), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('lerpRobot: positions interpolate linearly', () => {
|
||||||
|
const r = lerpRobot({ x: 0, z: 0, y: 0, hp: 100 }, { x: 10, z: -4, y: 2, hp: 50 }, 0.5);
|
||||||
|
assert.ok(Math.abs(r.x - 5) < 1e-9);
|
||||||
|
assert.ok(Math.abs(r.z + 2) < 1e-9);
|
||||||
|
assert.ok(Math.abs(r.y - 1) < 1e-9);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('lerpRobot: angles take the shortest path across the +/-PI seam', () => {
|
||||||
|
const r = lerpRobot({ a: 3.0 }, { a: -3.0 }, 0.5);
|
||||||
|
// short way is +0.28 rad across PI, not -6 rad the long way
|
||||||
|
assert.ok(r.a > 3.0 || r.a < -3.0, 'wrapped past PI, not back toward 0');
|
||||||
|
assert.ok(Math.abs(Math.abs(r.a) - Math.PI) < 0.2, 'lands near the seam');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('lerpRobot: discrete fields come from the reached (older) snapshot, not the newer one', () => {
|
||||||
|
const r = lerpRobot({ x: 0, hp: 100, dead: false }, { x: 10, hp: 0, dead: true }, 0.5);
|
||||||
|
assert.strictEqual(r.hp, 100);
|
||||||
|
assert.strictEqual(r.dead, false);
|
||||||
|
});
|
||||||
56
tests/netstats.test.js
Normal file
56
tests/netstats.test.js
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
'use strict';
|
||||||
|
const { test } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const path = require('path');
|
||||||
|
require(path.join(__dirname, '..', 'game', 'netstats.js'));
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
// feed a steady fight: snapshots every `gap` ms (+ jitter), pings, inputs acked after `inDelay`
|
||||||
|
function feed({ ping = 30, gap = 50, jit = 0, opp = 40, tickMs = 0.5, inDelay = 60, secs = 6 } = {}) {
|
||||||
|
const st = RC.NetStats();
|
||||||
|
let t = 1000, seq = 0;
|
||||||
|
const sent = [];
|
||||||
|
for (let i = 0; i < secs * 20; i++) {
|
||||||
|
t += gap + (i % 2 ? jit : -jit);
|
||||||
|
if (i % 20 === 0) st.pong(ping, t);
|
||||||
|
st.inputSent(++seq, t); sent.push({ seq, at: t });
|
||||||
|
const acked = sent.filter(x => t - x.at >= inDelay).pop();
|
||||||
|
st.snap({ rtt: [ping, opp], tickMs, ack: acked ? acked.seq : 0 }, 900, t);
|
||||||
|
}
|
||||||
|
return { st, now: t };
|
||||||
|
}
|
||||||
|
|
||||||
|
test('a good connection reads as ok', () => {
|
||||||
|
const { st, now } = feed();
|
||||||
|
const s = st.summary(now);
|
||||||
|
assert.equal(s.ping, 30);
|
||||||
|
assert.equal(s.gap, 50);
|
||||||
|
assert.equal(s.oppPing, 40);
|
||||||
|
assert.ok(s.input >= 50 && s.input <= 120, 'input delay measured: ' + s.input);
|
||||||
|
assert.ok(s.kbps > 100 && s.kbps < 200, 'bandwidth ~ 900 B x 20/s = 144 kbit/s: ' + s.kbps);
|
||||||
|
assert.deepEqual(RC.NetStats.verdict(s).map(v => v.key), ['nv_ok']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('each cause is told apart: my ping, my jitter, opponent, server', () => {
|
||||||
|
const keys = o => { const { st, now } = feed(o); return RC.NetStats.verdict(st.summary(now)).map(v => v.key); };
|
||||||
|
assert.deepEqual(keys({ ping: 220 }), ['nv_me_slow']);
|
||||||
|
assert.deepEqual(keys({ jit: 45 }), ['nv_me_jitter']);
|
||||||
|
assert.deepEqual(keys({ opp: 300 }), ['nv_opp_slow']);
|
||||||
|
assert.deepEqual(keys({ tickMs: 12 }), ['nv_server']);
|
||||||
|
assert.ok(keys({ inDelay: 500 }).includes('nv_queue'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('outside a fight only the ping counts; a silent server is reported', () => {
|
||||||
|
const st = RC.NetStats();
|
||||||
|
st.pong(25, 1000);
|
||||||
|
assert.deepEqual(RC.NetStats.verdict(st.summary(1500)).map(v => v.key), ['nv_nofight']);
|
||||||
|
st.snap({ rtt: [25, 25], tickMs: 0.4 }, 500, 2000);
|
||||||
|
assert.deepEqual(RC.NetStats.verdict(st.summary(9000)).map(v => v.key), ['nv_lost']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('series gives graph points of the last seconds only', () => {
|
||||||
|
const { st, now } = feed({ secs: 15 });
|
||||||
|
const pts = st.series(now, 10);
|
||||||
|
assert.ok(pts.length > 100);
|
||||||
|
assert.ok(pts.every(p => now - p.t <= 10000));
|
||||||
|
});
|
||||||
100
tests/protocol.test.js
Normal file
100
tests/protocol.test.js
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
'use strict';
|
||||||
|
const { test } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const path = require('path');
|
||||||
|
for (const f of ['parts.js', 'robot.js', 'combat.js', 'ai.js', 'protocol.js']) require(path.join(__dirname, '..', 'game', f));
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
const P = RC.Proto;
|
||||||
|
|
||||||
|
test('check accepts valid client messages', () => {
|
||||||
|
assert.ok(P.check({ t: 'hello', v: 1, token: 'abc' }).ok);
|
||||||
|
assert.ok(P.check({ t: 'challenge', to: 'u1' }).ok);
|
||||||
|
assert.ok(P.check({ t: 'challenge.cancel' }).ok);
|
||||||
|
assert.ok(P.check({ t: 'ping', t0: 123.4 }).ok, 'ping with a timestamp (regression: t was checked instead of t0)');
|
||||||
|
assert.ok(P.check({ t: 'ping' }).ok);
|
||||||
|
assert.ok(P.check({ t: 'room', room: 'DE' }).ok);
|
||||||
|
assert.ok(P.check({ t: 'input', seq: 3, throttle: 1, turn: -0.5, fire: true, fire2: false, fire3: false }).ok);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('check rejects bad messages', () => {
|
||||||
|
assert.equal(P.check(null).ok, false);
|
||||||
|
assert.equal(P.check([]).ok, false);
|
||||||
|
assert.equal(P.check({ t: 'nope' }).error, 'UNKNOWN_TYPE');
|
||||||
|
assert.equal(P.check({ t: 'hello', v: '1', token: 'x' }).error, 'BAD_FIELD:v');
|
||||||
|
assert.equal(P.check({ t: 'hello', v: 1, token: '' }).error, 'BAD_FIELD:token');
|
||||||
|
assert.equal(P.check({ t: 'challenge', to: 'x'.repeat(65) }).error, 'BAD_FIELD:to');
|
||||||
|
assert.equal(P.check({ t: 'room', room: 'ZZ' }).error, 'BAD_FIELD:room');
|
||||||
|
assert.equal(P.check({ t: 'input', seq: -1, throttle: 0, turn: 0, fire: false, fire2: false, fire3: false }).error, 'BAD_FIELD:seq');
|
||||||
|
assert.equal(P.check({ t: 'input', seq: 1, throttle: NaN, turn: 0, fire: false, fire2: false, fire3: false }).error, 'BAD_FIELD:throttle');
|
||||||
|
assert.equal(P.check({ t: 'input', seq: 1, throttle: 0, turn: 0, fire: 1, fire2: false, fire3: false }).error, 'BAD_FIELD:fire');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('input clamps ranges and coerces flags', () => {
|
||||||
|
assert.deepEqual(P.input({ throttle: 5, turn: -9, fire: 1 }), { throttle: 1, turn: -1, fire: true, fire2: false, fire3: false });
|
||||||
|
assert.deepEqual(P.input(null), { throttle: 0, turn: 0, fire: false, fire2: false, fire3: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
function fakeSnap() {
|
||||||
|
return {
|
||||||
|
tick: 10, ack: [4, 7], away: [false, true], rtt: [20, 140], time: 1, left: 100, pitOpen: 0, pitAlarm: false, endIn: 0,
|
||||||
|
result: { winner: 0, reason: 'ko' },
|
||||||
|
press: { st: 'idle', y: 1 }, crane: { st: 'grab', x: 0, z: 0, who: 1 },
|
||||||
|
rockets: [{ kind: 'rocket', owner: 0, x: 1, z: 2, y: 0.5, a: 0 }],
|
||||||
|
mines: [{ owner: 1, x: 0, z: 0, arm: 1 }],
|
||||||
|
robots: [{ x: 1, hp: 50, grabbedBy: null, dealt: 30 }, { x: 2, hp: 0, grabbedBy: 0, dealt: 5 }],
|
||||||
|
ev: [{ type: 'dmg', who: 1, amount: 3 }, { type: 'end', winner: 0, reason: 'ko' }, { type: 'pit_open' }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('toLocal for seat 0 keeps order and indices', () => {
|
||||||
|
const l = P.toLocal(0, fakeSnap());
|
||||||
|
assert.equal(l.robots[0].x, 1);
|
||||||
|
assert.equal(l.result.winner, 0);
|
||||||
|
assert.equal(l.ack, 4);
|
||||||
|
assert.equal(l.crane.who, 1);
|
||||||
|
assert.equal(l.ev[0].who, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('toLocal for seat 1 mirrors every robot index', () => {
|
||||||
|
const l = P.toLocal(1, fakeSnap());
|
||||||
|
assert.equal(l.robots[0].x, 2, 'own robot first');
|
||||||
|
assert.equal(l.robots[0].dealt, 5);
|
||||||
|
assert.equal(l.robots[0].grabbedBy, 1, 'grabbed by the other robot = local index 1');
|
||||||
|
assert.equal(l.robots[1].grabbedBy, null);
|
||||||
|
assert.equal(l.result.winner, 1, 'seat 0 won -> for seat 1 the winner is the opponent (local 1)');
|
||||||
|
assert.equal(l.ack, 7);
|
||||||
|
assert.deepEqual(l.away, [true, false], 'own connection first');
|
||||||
|
assert.deepEqual(l.rtt, [140, 20], 'own ping first');
|
||||||
|
assert.equal(l.crane.who, 0);
|
||||||
|
assert.equal(l.rockets[0].owner, 1);
|
||||||
|
assert.equal(l.mines[0].owner, 0);
|
||||||
|
assert.equal(l.ev[0].who, 0);
|
||||||
|
assert.equal(l.ev[1].winner, 1);
|
||||||
|
assert.ok(!('who' in l.ev[2]));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('draw stays a draw for both seats; mirrored results always disagree on the winner', () => {
|
||||||
|
assert.equal(P.localResult(0, { winner: -1, reason: 'time' }).winner, -1);
|
||||||
|
assert.equal(P.localResult(1, { winner: -1, reason: 'time' }).winner, -1);
|
||||||
|
for (const w of [0, 1]) {
|
||||||
|
const a = P.localResult(0, { winner: w }).winner, b = P.localResult(1, { winner: w }).winner;
|
||||||
|
assert.notEqual(a === 0, b === 0, 'exactly one seat sees itself as the winner');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('packSnap of a real fight carries what the result screen needs', () => {
|
||||||
|
const s = RC.Combat.create({ robots: [RC.stats(RC.STARTER), RC.stats(RC.STARTER)], seed: 3 });
|
||||||
|
RC.Combat.step(s, 1 / 60, [P.input({ throttle: 1 }), P.input({})]);
|
||||||
|
const snap = P.packSnap(s, 1, [0, 0]);
|
||||||
|
assert.equal(snap.robots.length, 2);
|
||||||
|
for (const k of ['x', 'z', 'a', 'hp', 'maxHp', 'dealt', 'taken']) assert.equal(typeof snap.robots[0][k], 'number', k);
|
||||||
|
assert.ok(Array.isArray(snap.robots[0].W));
|
||||||
|
assert.ok(JSON.stringify(snap).length < 6000, 'snapshot stays small');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a snapshot never carries a field named t (it is the message type on the wire)', () => {
|
||||||
|
const s = RC.Combat.create({ robots: [RC.stats(RC.STARTER), RC.stats(RC.STARTER)], seed: 1 });
|
||||||
|
const msg = Object.assign({ t: 'snap' }, P.packSnap(s, 1, [0, 0]));
|
||||||
|
assert.equal(msg.t, 'snap');
|
||||||
|
assert.equal(typeof msg.time, 'number');
|
||||||
|
});
|
||||||
136
tools/bot.js
Normal file
136
tools/bot.js
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/* Robot Clash test bot - a dumb fake player for testing online play alone. No AI: it drives a fixed pattern.
|
||||||
|
It logs in as a guest, waits in the lobby and ACCEPTS every challenge (or challenges a player by name),
|
||||||
|
fights, and goes back to the lobby. Ctrl+C deletes its guest account again.
|
||||||
|
|
||||||
|
npm run bot local server, circles
|
||||||
|
npm run bot -- --url https://roboclash.michael-media.de --pattern zigzag
|
||||||
|
npm run bot -- --url https://roboclash.michael-media.de --challenge benni
|
||||||
|
Options:
|
||||||
|
--url <server> default http://localhost:8080
|
||||||
|
--name <name> lobby name (default Bot-<pattern>)
|
||||||
|
--pattern <p> circle | zigzag | spin | charge | idle (default circle)
|
||||||
|
--challenge <name> challenge this player whenever both are idle (default: only accept)
|
||||||
|
--fights <n> stop after n fights (default: run until Ctrl+C)
|
||||||
|
Diagnosis tip: run the bot ON the server (ssh, then node tools/bot.js --url http://127.0.0.1:8080) - it then has
|
||||||
|
~0 ms ping, so any lag you see comes from your own connection or the server, not from the opponent.
|
||||||
|
|
||||||
|
Also usable as a module (tests): const bot = await startBot({ url, pattern }); ... await bot.stop(); */
|
||||||
|
'use strict';
|
||||||
|
const path = require('path');
|
||||||
|
const WebSocket = require(path.join(__dirname, '..', 'server', 'node_modules', 'ws'));
|
||||||
|
require(path.join(__dirname, '..', 'game', 'protocol.js'));
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
// input per pattern at time t (seconds since the fight started)
|
||||||
|
const PATTERNS = {
|
||||||
|
circle: () => ({ throttle: 0.75, turn: 0.55, fire: false }),
|
||||||
|
zigzag: t => ({ throttle: 1, turn: Math.sin(t * 1.6) > 0 ? 0.8 : -0.8, fire: false }),
|
||||||
|
spin: () => ({ throttle: 0, turn: 1, fire: false }),
|
||||||
|
charge: t => ({ throttle: (t % 4) < 2.5 ? 1 : -0.6, turn: (t % 4) < 2.5 ? 0 : 0.9, fire: (t % 4) < 2.5 }),
|
||||||
|
idle: () => ({ throttle: 0, turn: 0, fire: false }),
|
||||||
|
};
|
||||||
|
|
||||||
|
function args(argv) {
|
||||||
|
const o = { url: 'http://localhost:8080', pattern: 'circle', name: null, challenge: null, fights: 0 };
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const k = argv[i].replace(/^--/, ''), v = argv[i + 1];
|
||||||
|
if (k in o) { o[k] = k === 'fights' ? +v : v; i++; }
|
||||||
|
}
|
||||||
|
return o;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function startBot(opt) {
|
||||||
|
const url = (opt.url || 'http://localhost:8080').replace(/\/+$/, '');
|
||||||
|
const pattern = PATTERNS[opt.pattern] ? opt.pattern : 'circle';
|
||||||
|
const drive = PATTERNS[pattern];
|
||||||
|
const log = opt.quiet ? () => {} : (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
|
||||||
|
const api = async (method, p, body, token) => {
|
||||||
|
const r = await fetch(url + p, { method, headers: Object.assign({ 'Content-Type': 'application/json' }, token ? { Authorization: 'Bearer ' + token } : {}), body: body && JSON.stringify(body) });
|
||||||
|
return r.json().catch(() => null);
|
||||||
|
};
|
||||||
|
const acc = await api('POST', '/api/auth/guest', { name: opt.name || 'Bot-' + pattern });
|
||||||
|
if (!acc || !acc.idToken) throw new Error('guest login failed: ' + JSON.stringify(acc));
|
||||||
|
log(`logged in as ${acc.name} (${pattern}) at ${url}`);
|
||||||
|
|
||||||
|
const ws = new WebSocket(url.replace(/^http/, 'ws') + '/ws');
|
||||||
|
const send = m => { if (ws.readyState === 1) ws.send(JSON.stringify(m)); };
|
||||||
|
const players = new Map();
|
||||||
|
let match = null, timer = null, fights = 0, stopped = false, seq = 0, challengeT = null;
|
||||||
|
const stats = { snaps: 0, gaps: [], last: 0 };
|
||||||
|
const done = new Promise(res => { ws.on('close', res); });
|
||||||
|
|
||||||
|
function tryChallenge() {
|
||||||
|
if (!opt.challenge || match || stopped) return;
|
||||||
|
const target = [...players.values()].find(p => p.name.toLowerCase() === opt.challenge.toLowerCase() && p.state === 'idle');
|
||||||
|
if (target) { log(`challenging ${target.name}`); send({ t: 'challenge', to: target.uid }); }
|
||||||
|
}
|
||||||
|
|
||||||
|
ws.on('open', () => send({ t: 'hello', v: RC.Proto.VERSION, token: acc.idToken }));
|
||||||
|
ws.on('message', raw => {
|
||||||
|
const m = JSON.parse(raw);
|
||||||
|
switch (m.t) {
|
||||||
|
case 'welcome': log('connected - waiting in the lobby' + (opt.challenge ? ` for ${opt.challenge}` : ' (accepts every challenge)')); break;
|
||||||
|
case 'lobby': players.clear(); for (const p of m.players) players.set(p.uid, p); tryChallenge(); break;
|
||||||
|
case 'lobby.join': case 'lobby.state': players.set(m.player.uid, m.player); tryChallenge(); break;
|
||||||
|
case 'lobby.leave': players.delete(m.uid); break;
|
||||||
|
case 'challenge.in': log(`challenged by ${m.name} - accepting`); setTimeout(() => send({ t: 'challenge.accept', from: m.from }), 800); break;
|
||||||
|
case 'challenge.gone': log(`challenge gone (${m.reason || 'gone'})`); clearTimeout(challengeT); challengeT = setTimeout(tryChallenge, 3000); break;
|
||||||
|
case 'match.start': {
|
||||||
|
match = m; seq = 0; stats.snaps = 0; stats.gaps = []; stats.last = 0;
|
||||||
|
const opp = m.robots[1 - m.seat];
|
||||||
|
log(`fight vs ${opp.name} in ${m.arena} (seat ${m.seat}), countdown ${m.countdown.toFixed(1)} s`);
|
||||||
|
const start = Date.now() + m.countdown * 1000;
|
||||||
|
clearInterval(timer);
|
||||||
|
timer = setInterval(() => { // 20 inputs per second, like a player holding keys
|
||||||
|
const t = (Date.now() - start) / 1000;
|
||||||
|
if (t < 0) return;
|
||||||
|
const i = RC.Proto.input(drive(t));
|
||||||
|
send(Object.assign({ t: 'input', seq: ++seq }, i));
|
||||||
|
}, 50);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'snap': {
|
||||||
|
const now = Date.now();
|
||||||
|
if (stats.last) stats.gaps.push(now - stats.last);
|
||||||
|
stats.last = now; stats.snaps++;
|
||||||
|
if (stats.snaps % 200 === 0) {
|
||||||
|
const g = stats.gaps.slice(-200), avg = g.reduce((a, b) => a + b, 0) / g.length;
|
||||||
|
const jit = Math.sqrt(g.reduce((a, b) => a + (b - avg) ** 2, 0) / g.length);
|
||||||
|
const me = RC.Proto.toLocal(match.seat, m);
|
||||||
|
log(` snapshots every ${avg.toFixed(0)} ms (jitter ${jit.toFixed(0)} ms) · ping bot ${me.rtt[0]} ms, opponent ${me.rtt[1]} ms · server step ${m.tickMs} ms`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'match.end': {
|
||||||
|
clearInterval(timer); fights++;
|
||||||
|
const r = RC.Proto.localResult(m.seat, m.result);
|
||||||
|
log(`fight over: ${r.winner === -1 ? 'draw' : r.winner === 0 ? 'bot won' : 'bot lost'} (${m.result.reason})`);
|
||||||
|
match = null;
|
||||||
|
if (opt.fights && fights >= opt.fights) stop(); else { clearTimeout(challengeT); challengeT = setTimeout(tryChallenge, 4000); }
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'error': log('server says:', m.code); break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
async function stop() {
|
||||||
|
if (stopped) return;
|
||||||
|
stopped = true;
|
||||||
|
clearInterval(timer); clearTimeout(challengeT);
|
||||||
|
try { ws.close(); } catch (e) { /* closed */ }
|
||||||
|
await api('DELETE', '/api/me', undefined, acc.idToken).catch(() => {});
|
||||||
|
log('bot account deleted, bye');
|
||||||
|
}
|
||||||
|
return { uid: acc.uid, name: acc.name, stop, done, get fights() { return fights; }, get inMatch() { return !!match; } };
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { startBot, PATTERNS };
|
||||||
|
|
||||||
|
if (require.main === module) {
|
||||||
|
const o = args(process.argv.slice(2));
|
||||||
|
startBot(o).then(bot => {
|
||||||
|
process.on('SIGINT', () => bot.stop().then(() => process.exit(0)));
|
||||||
|
bot.done.then(() => { if (o.fights) process.exit(0); });
|
||||||
|
}).catch(e => { console.error(e.message); process.exit(1); });
|
||||||
|
}
|
||||||
68
tools/smoke.js
Normal file
68
tools/smoke.js
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/* Smoke test against a running server (after every deploy):
|
||||||
|
node tools/smoke.js https://roboclash.michael-media.de
|
||||||
|
node tools/smoke.js http://localhost:8080
|
||||||
|
Two throw-away guest accounts: health -> login -> WebSocket -> lobby -> challenge -> accept -> snapshots ->
|
||||||
|
one gives up -> both get the result + rewards. Exit code 0 = everything worked. */
|
||||||
|
'use strict';
|
||||||
|
const path = require('path');
|
||||||
|
const WebSocket = require(path.join(__dirname, '..', 'server', 'node_modules', 'ws'));
|
||||||
|
require(path.join(__dirname, '..', 'game', 'protocol.js'));
|
||||||
|
const RC = globalThis.RC;
|
||||||
|
|
||||||
|
const base = (process.argv[2] || 'http://localhost:8080').replace(/\/+$/, '');
|
||||||
|
const wsBase = base.replace(/^http/, 'ws');
|
||||||
|
let failed = 0;
|
||||||
|
const ok = (c, msg) => { console.log((c ? 'ok ' : 'FAIL ') + msg); if (!c) failed++; };
|
||||||
|
|
||||||
|
async function json(method, p, body, token) {
|
||||||
|
const r = await fetch(base + p, { method, headers: Object.assign({ 'Content-Type': 'application/json' }, token ? { Authorization: 'Bearer ' + token } : {}), body: body && JSON.stringify(body) });
|
||||||
|
return { status: r.status, body: await r.json().catch(() => null) };
|
||||||
|
}
|
||||||
|
function client(token) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const ws = new WebSocket(wsBase + '/ws'), inbox = [], waiters = [];
|
||||||
|
const c = {
|
||||||
|
send: m => ws.send(JSON.stringify(m)), close: () => ws.close(), inbox,
|
||||||
|
next(t, pred = () => true, ms = 8000) {
|
||||||
|
const i = inbox.findIndex(m => m.t === t && pred(m));
|
||||||
|
if (i >= 0) return Promise.resolve(inbox.splice(i, 1)[0]);
|
||||||
|
return new Promise((res, rej) => waiters.push({ t, pred, res, timer: setTimeout(() => rej(new Error('timeout: ' + t)), ms) }));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
ws.on('message', d => { const m = JSON.parse(d); const i = waiters.findIndex(w => w.t === m.t && w.pred(m)); if (i >= 0) { const w = waiters.splice(i, 1)[0]; clearTimeout(w.timer); w.res(m); } else inbox.push(m); });
|
||||||
|
ws.on('open', () => { c.send({ t: 'hello', v: RC.Proto.VERSION, token }); c.next('welcome').then(() => resolve(c), reject); });
|
||||||
|
ws.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
const h = await json('GET', '/healthz');
|
||||||
|
ok(h.status === 200 && h.body.ok, `health ${base} (version ${h.body && h.body.version}, commit ${h.body && h.body.commit})`);
|
||||||
|
const [a, b] = await Promise.all([json('POST', '/api/auth/guest', { name: 'SmokeA' }), json('POST', '/api/auth/guest', { name: 'SmokeB' })]);
|
||||||
|
ok(a.status === 200 && b.status === 200, 'two guest logins');
|
||||||
|
const ca = await client(a.body.idToken), cb = await client(b.body.idToken);
|
||||||
|
ok(true, 'WebSocket connected + authenticated (both)');
|
||||||
|
await cb.next('lobby');
|
||||||
|
ca.send({ t: 'challenge', to: b.body.uid });
|
||||||
|
await cb.next('challenge.in');
|
||||||
|
cb.send({ t: 'challenge.accept', from: a.body.uid });
|
||||||
|
const [sa, sb] = await Promise.all([ca.next('match.start'), cb.next('match.start')]);
|
||||||
|
ok(sa.matchId === sb.matchId && sa.seat !== sb.seat, `match ${sa.matchId} in arena ${sa.arena}`);
|
||||||
|
const t0 = Date.now();
|
||||||
|
await ca.next('snap', () => true, 10000);
|
||||||
|
ok(true, `first snapshot after ${Date.now() - t0} ms (countdown ${sa.countdown}s)`);
|
||||||
|
let n = 0; const t1 = Date.now();
|
||||||
|
while (Date.now() - t1 < 2000) { await ca.next('snap', () => true, 3000); n++; }
|
||||||
|
ok(n >= 25, `${n} snapshots in 2 s (expected ~40)`);
|
||||||
|
ca.send({ t: 'match.leave' });
|
||||||
|
const [ea, eb] = await Promise.all([ca.next('match.end'), cb.next('match.end')]);
|
||||||
|
const la = RC.Proto.localResult(ea.seat, ea.result).winner, lb = RC.Proto.localResult(eb.seat, eb.result).winner;
|
||||||
|
ok(la === 1 && lb === 0, `result mirrored: leaver lost, other won (+${eb.reward.money} credits, +${eb.reward.fame} fame)`);
|
||||||
|
ca.close(); cb.close();
|
||||||
|
// clean up: the throw-away accounts must not stay in the ranking
|
||||||
|
const del = await Promise.all([json('DELETE', '/api/me', undefined, a.body.idToken), json('DELETE', '/api/me', undefined, b.body.idToken)]);
|
||||||
|
ok(del.every(d => d.body && d.body.ok), 'test accounts deleted again');
|
||||||
|
console.log(failed ? `\n${failed} check(s) failed` : '\nsmoke test passed');
|
||||||
|
process.exit(failed ? 1 : 0);
|
||||||
|
})().catch(e => { console.error('FAIL', e.message); process.exit(1); });
|
||||||
Reference in New Issue
Block a user