Compare commits

..

12 Commits

Author SHA1 Message Date
Benjamin Oezcan
0ee589c91e docs: record progress of phases 1-3 in the plan, new commands in CLAUDE.md 2026-11-19 02:20:53 +01:00
Benjamin Oezcan
a73d33a821 fix(net): expired or stale session while online asks to log in again 2026-11-19 02:17:54 +01:00
Benjamin Oezcan
ce7cb798ec test: smoke test against a running server (npm run smoke -- <url>) 2026-11-19 02:17:54 +01:00
Benjamin Oezcan
101dd7c44b build(deploy): release-based deploy with health check and rollback, node 24, service user (P3-1b, P3-2, P3-3) 2026-11-19 02:12:53 +01:00
Benjamin Oezcan
b587d12f37 refactor!: remove firebase leftovers, admin page on the server (P1-8)
BREAKING CHANGE: admin/cleanup.js, admin/setcoins.js and docs/firebase are gone; the admin page now runs at /admin/.
2026-11-19 02:11:13 +01:00
Benjamin Oezcan
0202a08b8d feat(server): achievements pay out server-side, snapshots carry opponent connection state 2026-11-19 02:09:12 +01:00
Benjamin Oezcan
85a19ba242 feat(net)!: client on server-run fights, websocket lobby, server economy (P1-5, P1-6, P1-7, P2-3, P2-4)
- net.js: REST + one WebSocket with reconnect; single-flight refresh shared across tabs; ?slot=N
- lobby.js / netfight.js: server owns presence, challenges and the fight; client shows snapshots
- game.js: every workshop change goes through RC.Eco via act() (server-checked online);
  results, rewards and achievements come from the server (match.end)
- ranking/live/cloudsave on the new REST endpoints; online tournament removed until P2-6

BREAKING CHANGE: needs the new server (protocol v1); old online saves are not migrated.
2026-11-19 02:09:07 +01:00
Benjamin Oezcan
4bd85f68bf fix(net): snapshot fight time no longer overwrites the message type 2026-11-19 01:52:59 +01:00
Benjamin Oezcan
dca1032ac4 feat(server)!: websocket lobby, server-run matches, server economy, new schema (P1-2, P1-4, P2-1, P2-1b, P2-5)
Replaces the Firebase-style /db facade (rtdb, rules, nodes tree) with explicit REST endpoints and a
WebSocket hub. Login by name or optional e-mail, seed accounts via npm run db:reset.

BREAKING CHANGE: old clients (lobby/netfight over /db) no longer work against this server; database is new.
2026-11-19 01:52:30 +01:00
Benjamin Oezcan
46499e354b feat(shop): shared economy rules for client and server (P2-2) 2026-11-19 01:48:20 +01:00
Benjamin Oezcan
9012bee29f feat(server): server-side match room runs the fight (P1-3) 2026-11-19 01:46:17 +01:00
Benjamin Oezcan
bbe206004a feat(net): shared wire protocol with seat mapping (P1-1) 2026-11-19 01:45:26 +01:00
56 changed files with 2577 additions and 1725 deletions

2
.gitignore vendored
View File

@@ -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

View File

@@ -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,24 @@ 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` Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Registrieren/Gast → Shop → Liga/VS → Kampf → Ergebnis, Einstellungen.
- `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.
- 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 +147,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).
@@ -185,11 +197,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>`,

View File

@@ -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

View File

@@ -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); });

View File

@@ -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();
}); });
}; };

View File

@@ -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); });

View File

@@ -8,6 +8,29 @@
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). **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-1 voller Bot-Client, P4-2 Playwright, P4-3 Lasttest,
P4-4 Vorhersage (erst nach Spieltest), P4-5 `game.js` aufteilen (~2000 Zeilen), `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 +192,37 @@ 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 - [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 +239,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 +258,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.

View File

@@ -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 →

View File

@@ -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"
}
}
}
}
}

View File

@@ -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'],
languageOptions: { sourceType: 'commonjs', globals: { ...globals.node } }, languageOptions: { sourceType: 'commonjs', globals: { ...globals.node } },
}, },
{ {

View File

@@ -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
View 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);

View File

@@ -8,12 +8,12 @@
const W = 1280, H = 720; // design size of the stage (16:9, higher res = denser UI) const W = 1280, H = 720; // design size of the stage (16:9, higher res = denser UI)
const ID = 'robotclash'; // localStorage prefix const ID = 'robotclash'; // localStorage prefix
// Own backend (server/): auth + saves + ranks + lobby + live PvP. Empty serverUrl = same origin as the page, // Own backend (server/): accounts, online save + shop (server-authoritative), ranking, lobby + live fights over
// so when the game is served by the Node server it just works. file:// (double-click) stays offline. // WebSocket. Empty serverUrl = same origin as the page, so when the Node server serves the game it just works.
// file:// (double-click) stays offline = campaign only.
const NET_CFG = { serverUrl: '' }; const NET_CFG = { serverUrl: '' };
// dev/test: ?server=http://localhost:8080 points at a server on another origin; ?online jumps to login/lobby // dev/test: ?server=http://localhost:8080 points at a server on another origin; ?online jumps to login/lobby
{ const s = new URLSearchParams(location.search).get('server'); if (s) NET_CFG.serverUrl = s; } { const s = new URLSearchParams(location.search).get('server'); if (s) NET_CFG.serverUrl = s; }
const DB_URL = (NET_CFG.serverUrl || '') + '/db'; // ranking (Kit.scores) via the same server
// Credits (standard for every game): shown on the title screen, links open in the normal browser // Credits (standard for every game): shown on the title screen, links open in the normal browser
const DISCORD = 'https://discord.gg/Ej4JPmCZva'; const DISCORD = 'https://discord.gg/Ej4JPmCZva';
@@ -83,7 +83,12 @@
// the active class's league progress lives in save.beaten/season while you play, // the active class's league progress lives in save.beaten/season while you play,
// and is written back to its own slot on every save (same idea as the active robot) // and is written back to its own slot on every save (same idea as the active robot)
const syncClass = () => { if (save && save.leagues && save.cls) save.leagues[save.cls] = { beaten: save.beaten | 0, season: save.season || 1 }; }; const syncClass = () => { if (save && save.leagues && save.cls) save.leagues[save.cls] = { beaten: save.beaten | 0, season: save.season || 1 }; };
const persist = () => { if (slot && save) { syncActive(); syncClass(); save.ts = Date.now(); slot.save(save); if (fbAcc()) cloud.push(cloudId(), save); } }; // local cache always; online: cosmetics go to the server (economy only via act()); campaign: cloud copy for accounts
const persist = () => {
if (!slot || !save) return;
syncActive(); syncClass(); save.ts = Date.now(); slot.save(save);
if (gameMode === 'online') onlinePush(); else if (fbAcc()) cloud.push(save);
};
const audio = Kit.createAudio({ const audio = Kit.createAudio({
prefix: ID, prefix: ID,
files: ['sfx_click', 'sfx_buy', 'sfx_hit', 'sfx_saw', 'sfx_boom', 'sfx_win', 'sfx_lose', 'music_title', 'music_garage', 'music_fight'], files: ['sfx_click', 'sfx_buy', 'sfx_hit', 'sfx_saw', 'sfx_boom', 'sfx_win', 'sfx_lose', 'music_title', 'music_garage', 'music_fight'],
@@ -91,28 +96,76 @@
}); });
// first start (nothing saved yet): start very quiet; gain is squared, so these are low // first start (nothing saved yet): start very quiet; gain is squared, so these are low
if (Kit.store(ID).get('music', null) === null) audio.setVolume(0.1, 0.35); if (Kit.store(ID).get('music', null) === null) audio.setVolume(0.1, 0.35);
const scores = Kit.scores({ url: DB_URL }); // legacy (Firebase-only, disabled on the own server)
const DEV = new URLSearchParams(location.search); const DEV = new URLSearchParams(location.search);
if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop
const net = RC.Net(NET_CFG); const net = RC.Net(NET_CFG);
const rank = RC.Ranking(net); // live ranking over the own server (ranks/<uid> + SSE) const rank = RC.Ranking(net); // online ranking, computed by the server
const rankRow = () => ({ uid: (fbAcc() && fbAcc().uid) || net.uid, name: playerName(), fame: save.fame, flag: save.flag, cls: save.cls, season: save.season }); const cloud = RC.CloudSave(net); // campaign copy for registered accounts (online saves live on the server)
const cloud = RC.CloudSave(net); // mirrors a registered account's save to the server (best effort) const cloudFlush = () => { if (!save) return; if (gameMode === 'online') onlineFlush(); else if (fbAcc()) cloud.flush(save); };
// cloud path per mode: saves/<uid>/<campaign|online> - keeps the two games fully separate in the cloud too // dev menu (coins): local guests always; server accounts only if admin (the server checks again)
// (server rule canWrite('saves/$uid/...') still holds: segment[1] stays the uid)
const cloudId = () => { const a = fbAcc(); return a ? a.uid + '/' + (gameMode === 'online' ? 'online' : 'campaign') : null; };
const cloudFlush = () => { if (fbAcc() && save) cloud.flush(cloudId(), save); };
// dev menu (coins): guests get it too for now; registered accounts only if admin (server tells us via /api/me).
let isDev = false; let isDev = false;
function refreshDev() { function refreshDev() { isDev = !fbUser() ? true : !!fbUser().admin; }
if (!fbAcc()) { isDev = true; return; } // guest -> dev coins allowed (local money only)
isDev = false; // registered: wait for the admin check // ---- online save: the server is the authority for money, fame, parts and robots -------------------
if (!net.enabled) return; // act(): every workshop change goes through RC.Eco (game/eco.js). Applied locally at once; online the same
net.token().then(tk => { if (!tk) return; fetch((NET_CFG.serverUrl || '') + '/api/me?auth=' + tk).then(r => r.json()).then(d => { isDev = !!(d && d.admin); }).catch(() => {}); }); // 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(save, a);
if (!r.ok) return r;
if (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(save);
// keepLooks: robot names/paint are client-owned - keep ours (they may not be uploaded yet)
function adoptEconomy(srv, keepLooks = true) {
const looks = keepLooks && save.robots ? save.robots.map(r => ({ name: r.name, paint: r.paint })) : [];
for (const k of RC.Eco.ECONOMY) if (srv[k] !== undefined) save[k] = srv[k];
if (keepLooks && looks.length === save.robots.length) save.robots.forEach((r, i) => { r.name = looks[i].name; r.paint = looks[i].paint; });
RC.Eco.mirror(save);
slot.save(save);
}
function afterEconomy() {
hud();
if (mode === 'garage') { shop.render(); view.showGarage(save.build, paintObj()); if (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 (save[k] !== undefined) c[k] = save[k];
c.robots = 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 (gameMode === 'online' && 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 (gameMode !== 'online' || !net.uid) return;
const uid = net.uid;
net.api('GET', '/api/online').then(srv => {
if (!srv || !save || gameMode !== 'online' || net.uid !== uid) return;
const serverNewer = (+srv.ts || 0) > (+save.ts || 0);
if (serverNewer) { for (const k of RC.Eco.COSMETIC) if (srv[k] !== undefined) save[k] = srv[k]; }
adoptEconomy(srv, !serverNewer);
repairSave();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (!serverNewer) onlinePush();
afterEconomy();
});
} }
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX']; const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`; const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`;
const lobby = net.enabled ? RC.Lobby({ net, getProfile: () => ({ name: playerName(), flag: save.flag || 'XX', room: myRoom(), build: save.build, paint: { body: save.paint.body, accent: save.paint.accent, decal: save.paint.decal || null, drawn: !!save.paint.drawn }, fame: save.fame | 0 }) }) : null; const lobby = net.enabled ? RC.Lobby({ net }) : null;
const fx = Kit.fx(); const fx = Kit.fx();
const input = Kit.input({ const input = Kit.input({
@@ -198,6 +251,7 @@
const shop = RC.Shop({ const shop = RC.Shop({
t, getSave: () => save, onSave: () => { persist(); hud(); }, // buy/sell/rename -> header t, getSave: () => save, onSave: () => { persist(); hud(); }, // buy/sell/rename -> header
act: a => act(a), // economy changes (buy/sell/equip) - server-checked online
onBuild: () => view.showGarage(save.build, paintObj()), onBuild: () => view.showGarage(save.build, paintObj()),
onPaint: () => view.setPaint(paintObj()), onPaint: () => view.setPaint(paintObj()),
onPreview: b => { if (mode === 'garage') view.showGarage(b, paintObj()); }, // show the selected part on the robot onPreview: b => { if (mode === 'garage') view.showGarage(b, paintObj()); }, // show the selected part on the robot
@@ -249,7 +303,10 @@
} }
if (drag != null) { view.turn(e.clientX - drag); drag = e.clientX; } if (drag != null) { view.turn(e.clientX - drag); drag = e.clientX; }
}); });
$('gl').addEventListener('pointerup', () => { if (wdrag) { wdrag = false; persist(); refreshEditorRobot(); renderWeaponEditor(); } drag = null; }); $('gl').addEventListener('pointerup', () => {
if (wdrag) { wdrag = false; const w = save.build.weapons[editSel]; if (w) act({ type: 'weaponPlace', index: editSel, side: w.side, up: w.up }); persist(); refreshEditorRobot(); renderWeaponEditor(); }
drag = null;
});
addEventListener('beforeunload', () => { try { cloudFlush(); } catch (e) { /* closing anyway */ } }); addEventListener('beforeunload', () => { try { cloudFlush(); } catch (e) { /* closing anyway */ } });
// ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ---- // ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ----
@@ -298,7 +355,7 @@
if (dp && pv) { if (dp && pv) {
const mounted = weps.filter(w => w.id === wPrev).length, poor = save.money < pv.cost; const mounted = weps.filter(w => w.id === wPrev).length, poor = save.money < pv.cost;
let act = `<button class="primary" data-wact="add" ${(!canAdd || poor) ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(pv.cost) })}</button>`; 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(Math.round(pv.cost * 0.5)) })}</button>`; if (mounted) act += `<button data-wact="rem">${t('sell', { n: Kit.fmt(RC.Eco.sellValue(wPrev)) })}</button>`;
if (!canAdd) act += `<span class="muted">${t('ed_max', { n: RC.MAX_WEAPONS })}</span>`; if (!canAdd) act += `<span class="muted">${t('ed_max', { n: RC.MAX_WEAPONS })}</span>`;
dp.innerHTML = `${RC.pic('part_' + wPrev, GLYPH_SLOT.weapon)} dp.innerHTML = `${RC.pic('part_' + wPrev, GLYPH_SLOT.weapon)}
<div><div class="nm">${pv.name}${mounted ? ` <span class="badge own">×${mounted}</span>` : ''}</div> <div><div class="nm">${pv.name}${mounted ? ` <span class="badge own">×${mounted}</span>` : ''}</div>
@@ -322,27 +379,23 @@
+ `<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>` + `<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>`) : `<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)}`; + `<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; sel.side = x.dataset.side; SFX.click(); reDrawEditor(); }); wp.querySelectorAll('[data-side]').forEach(x => x.onclick = () => { if (!sel) return; act({ type: 'weaponPlace', index: editSel, side: x.dataset.side }); SFX.click(); reDrawEditor(); });
if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } }; if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } }; // live preview while dragging
if ($('edUp')) $('edUp').onchange = () => reDrawEditor(); if ($('edUp')) $('edUp').onchange = e => { if (sel) act({ type: 'weaponPlace', index: editSel, up: +e.target.value }); reDrawEditor(); };
wp.querySelectorAll('[data-body]').forEach(x => { 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.oninput = e => { b.body = b.body || { hx: 1, wx: 1, lx: 1 }; b.body[e.target.dataset.body] = +e.target.value; refreshEditorRobot(); };
x.onchange = () => reDrawEditor(); x.onchange = e => { act({ type: 'body', [e.target.dataset.body]: +e.target.value }); reDrawEditor(); };
}); });
} }
if (weps[editSel] && weps[editSel].id === wPrev) view.setEditWeapon(editSel); if (weps[editSel] && weps[editSel].id === wPrev) view.setEditWeapon(editSel);
} }
function addWeapon(id) { function addWeapon(id) {
const p = RC.PARTS[id]; if (!act({ type: 'weaponAdd', part: id }).ok) { SFX.deny(); return; }
if (!p || save.build.weapons.length >= RC.MAX_WEAPONS || save.money < p.cost) { SFX.deny(); return; }
save.money -= p.cost; save.build.weapons.push({ id, side: 'front', up: 0 });
editSel = save.build.weapons.length - 1; wPrev = id; view.setEditWeapon(editSel); editSel = save.build.weapons.length - 1; wPrev = id; view.setEditWeapon(editSel);
SFX.buy(); reDrawEditor(); SFX.buy(); reDrawEditor();
} }
function removeWeapon(i) { function removeWeapon(i) {
const w = save.build.weapons[i]; if (!w) return; if (!act({ type: 'weaponRemove', index: i }).ok) { SFX.deny(); return; }
const p = RC.PARTS[w.id]; if (p) save.money += Math.round(p.cost * 0.5);
save.build.weapons.splice(i, 1);
if (editSel >= save.build.weapons.length) editSel = Math.max(0, save.build.weapons.length - 1); if (editSel >= save.build.weapons.length) editSel = Math.max(0, save.build.weapons.length - 1);
view.setEditWeapon(editSel); view.setEditWeapon(editSel);
SFX.buy(); reDrawEditor(); SFX.buy(); reDrawEditor();
@@ -426,7 +479,7 @@
const fbUser = () => (net && net.enabled ? net.auth.current : null); const fbUser = () => (net && net.enabled ? net.auth.current : null);
const fbAcc = () => (fbUser() && !fbUser().guest ? fbUser() : null); // real (e-mail) account const fbAcc = () => (fbUser() && !fbUser().guest ? fbUser() : null); // real (e-mail) account
const playerName = () => (fbUser() ? fbUser().name : accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : ''); const playerName = () => (fbUser() ? fbUser().name : accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : '');
// save slot: Firebase account -> robotclash.save.fb_<uid>, else local profile / guest // save slot: server account -> robotclash.save.fb_<uid>, else local profile / guest
// Two completely separate games: the campaign (league, seasons) and online play (PvP). // Two completely separate games: the campaign (league, seasons) and online play (PvP).
// Money, parts and robots never cross over - they simply live in different saves. // Money, parts and robots never cross over - they simply live in different saves.
// Opening the page always starts in online mode; the campaign keeps the old save key, // Opening the page always starts in online mode; the campaign keeps the old save key,
@@ -436,7 +489,7 @@
+ (gameMode === 'online' ? '.online' : ''); + (gameMode === 'online' ? '.online' : '');
function setMode(m) { function setMode(m) {
const onlineOk = net && net.enabled && !LIVE.onlineOff; const onlineOk = net && net.enabled && !LIVE.onlineOff;
gameMode = onlineOk ? m : 'campaign'; // no Firebase or switched off: campaign only gameMode = onlineOk ? m : 'campaign'; // no server or switched off: campaign only
document.body.dataset.gmode = gameMode; document.body.dataset.gmode = gameMode;
} }
function switchMode(m) { function switchMode(m) {
@@ -584,10 +637,31 @@
} }
// ---------------------------------------------------------------- online lobby // ---------------------------------------------------------------- online lobby
let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker, = which room I view) // The server owns presence, challenges and fights (server/lobby.js). This draws its state and forwards clicks.
let onlineReady = false, lobbyRows = [], lobbyRoom = null; // lobbyRoom = country code or 'all' (which room I view)
let joinedRoom = null; // the country room I am present in (others see me there, with MY flag); default = my flag let joinedRoom = null; // the country room I am present in (others see me there, with MY flag); default = my flag
const myRoom = () => joinedRoom || (FLAGS.includes(save.flag) ? save.flag : 'XX'); const myRoom = () => joinedRoom || (FLAGS.includes(save.flag) ? save.flag : 'XX');
let ntour = null, inNetTour = false; // live multiplayer tournament const pendingOut = () => (lobby ? lobby.pending : null);
function wireLobby() {
lobby.onList(rows => { lobbyRows = rows; if (mode === 'lobby') renderLobby(); });
lobby.onIncoming(c => { if (mode === 'lobby' || mode === 'garage') showIncoming(c); });
lobby.onMatch(m => startOnlineFight(m));
lobby.onEnd(m => onlineFightEnded(m));
lobby.onCancel(c => {
if (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 (mode === 'lobby') { renderLobby(); const el = $('lMsg'); if (el) el.textContent = errText(code); }
else if (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 (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) async function startOnline(dest) { // dest 'lobby' -> player list, else the workshop (main page)
if (!net.enabled) return; if (!net.enabled) return;
if (gameMode !== 'online') { setMode('online'); if (save) { loadSave(); hud(); } } // online uses its own save if (gameMode !== 'online') { setMode('online'); if (save) { loadSave(); hud(); } } // online uses its own save
@@ -596,30 +670,26 @@
showOnlineLogin(false, null, 'online'); return; showOnlineLogin(false, null, 'online'); return;
} }
if (!save || !slot) { if (!fbAcc()) accounts.guest(); loadSave(); } if (!save || !slot) { if (!fbAcc()) accounts.guest(); loadSave(); }
if (!onlineReady) { if (!onlineReady) { wireLobby(); onlineReady = true; }
lobby.enter(); onlineReady = true; lobby.enter();
lobby.onList(rows => { lobbyRows = rows; if (mode === 'lobby') renderLobby(); });
lobby.onIncoming(c => { if (mode === 'lobby' || mode === 'garage') showIncoming(c); });
lobby.onMatch(m => { const opp = { name: m.opp.name, build: m.opp.build, paint: m.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: m.opp.flag }; prepOpp(opp, () => startFight(opp, false, false, { id: m.id, host: m.host, seed: m.seed })); });
lobby.onCancel(() => { pendingOut = null; if (mode === 'lobby') { renderLobby(); SFX.deny(); } });
}
ensureFlag(() => { if (dest === 'lobby') showLobby(); else openGarage(); }); // country first, then main page / lobby ensureFlag(() => { if (dest === 'lobby') showLobby(); else openGarage(); }); // country first, then main page / lobby
} }
async function joinAnon() { async function joinAnon() {
if (!save) { accounts.guest(); loadSave(); } if (!save) { accounts.guest(); loadSave(); }
const r = await net.auth.guest(playerName() || t('guest')); const r = await net.auth.guest(playerName() || t('guest'));
if (!r.ok) { SFX.deny(); showOnlineLogin(false, r.error, 'online'); return; } if (!r.ok) { SFX.deny(); showOnlineLogin(false, r.error, 'online'); return; }
hud(); startOnline(); hud(); refreshDev(); loadSave(); startOnline();
} }
const errText = c => (window.LANG.en['e_' + c] ? t('e_' + c) : t('e_ERROR') + ' (' + esc(c) + ')'); const errText = c => (window.LANG.en['e_' + c] ? t('e_' + c) : t('e_ERROR') + ' (' + esc(c) + ')');
function showOnlineLogin(reg, errKey, next) { function showOnlineLogin(reg, errKey, next) {
next = next || 'career'; next = next || 'career';
setScreen('account'); setScreen('account');
const f = reg const f = reg
? `<label>${t('f_name')}</label><input type="text" id="oName" maxlength="18" autocomplete="nickname">` ? `<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> card(`<h2>${reg ? t('register') : t('login')}</h2><p>${t('online_login_text')}</p>
<div class="form">${f}<label>${t('f_email')}</label><input type="email" id="oMail" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" inputmode="email"> <div class="form">${f}
<label>${t('f_pass')}</label><input type="password" id="oPass" autocomplete="${reg ? 'new-password' : 'current-password'}"></div> <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>` : ''} ${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="err" id="oErr">${errKey ? errText(errKey) : ''}</div>
@@ -633,19 +703,19 @@
$('oGo').onclick = async () => { $('oGo').onclick = async () => {
if (reg && $('oConsent') && !$('oConsent').checked) { SFX.deny(); $('oErr').textContent = t('consent_required'); return; } if (reg && $('oConsent') && !$('oConsent').checked) { SFX.deny(); $('oErr').textContent = t('consent_required'); return; }
$('oGo').disabled = true; $('oGo').disabled = true;
const r = reg ? await net.auth.register($('oMail').value.trim(), $('oPass').value, $('oName') ? $('oName').value : '') const r = reg ? await net.auth.register($('oName').value, $('oPass').value, $('oMail').value)
: await net.auth.login($('oMail').value.trim(), $('oPass').value); : await net.auth.login($('oLogin').value, $('oPass').value);
if (!r.ok) { SFX.deny(); showOnlineLogin(reg, r.error, next); return; } if (!r.ok) { SFX.deny(); showOnlineLogin(reg, r.error, next); return; }
SFX.click(); hud(); SFX.click(); hud(); refreshDev();
if (next === 'online') startOnline(); else enterAccount(reg); 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(); })); 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() { function showLobby() {
if (!lobbyRoom) lobbyRoom = 'all'; // filter: 'all' or a country code if (!lobbyRoom) lobbyRoom = 'all'; // filter: 'all' or a country code
setScreen('lobby'); renderLobby(); setScreen('lobby'); renderLobby();
} }
// compact one-view lobby: country filter + flag dropdowns, slim player list
// two-pane lobby: country rooms on the left, players of the chosen room on the right (own style, not copied art) // two-pane lobby: country rooms on the left, players of the chosen room on the right (own style, not copied art)
function renderLobby() { 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 code = r => { const c = r.room || r.flag; return FLAGS.includes(c) ? c : 'XX'; }; // group by the room a player JOINED, not their flag
@@ -656,107 +726,37 @@
const cnt = f => all.filter(r => code(r) === f).length + (f === mine ? 1 : 0); const cnt = f => all.filter(r => code(r) === f).length + (f === mine ? 1 : 0);
const here = lobbyRoom === 'all' ? all : all.filter(r => code(r) === lobbyRoom); const here = lobbyRoom === 'all' ? all : all.filter(r => code(r) === lobbyRoom);
const showMe = lobbyRoom === 'all' || lobbyRoom === mine; const showMe = lobbyRoom === 'all' || lobbyRoom === mine;
const out = pendingOut();
const flagOpts = FLAGS.map(f => `<option value="${f}" ${f === myFlag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join(''); const flagOpts = FLAGS.map(f => `<option value="${f}" ${f === myFlag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join('');
const room = (f, label, flag) => `<button class="rroom ${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 room = (f, label, flag) => `<button class="rroom ${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 rooms = room('all', t('all_countries'), false) + FLAGS.map(f => room(f, t('cc_' + f), true)).join('');
const prow = (r, me) => `<div class="prow ${me ? 'me' : ''}" ${me ? '' : `data-uid="${r.uid}"`}><span class="pf">${flagHtml(me ? save.flag : r.flag)}</span><span class="pn">${esc(me ? playerName() : r.name)}${me ? ` <span class="muted">(${t('you')})</span>` : ''}</span><span class="pfame">\u2B50 ${Kit.fmt((me ? save.fame : r.fame) | 0)}</span>${me ? '<span class="pbusy"></span>' : (r.state === 'idle' ? `<button class="chal" data-uid="${r.uid}">${t('challenge')}</button>` : `<span class="pbusy">${t('busy')}</span>`)}</div>`; 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 ? 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 ? save.fame : r.fame) | 0)}</span>${me ? '<span class="pbusy"></span>' : action(r)}</div>`;
const list = here.map(r => prow(r, false)).join(''); const list = here.map(r => prow(r, false)).join('');
const title = lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(lobbyRoom) + ' ' + t('cc_' + lobbyRoom); const title = lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(lobbyRoom) + ' ' + t('cc_' + lobbyRoom);
const offline = lobby && !lobby.connected ? `<p class="muted" style="margin:6px 0 0">${t('net_connecting')}</p>` : '';
overlay.innerHTML = `<div class="lobbyfull"> overlay.innerHTML = `<div class="lobbyfull">
<div class="lobbyL"><div class="lobbyLh">🌍 ${t('lobby')}</div><div class="roomlist">${rooms}</div></div> <div class="lobbyL"><div class="lobbyLh">🌍 ${t('lobby')}</div><div class="roomlist">${rooms}</div></div>
<div class="lobbyR"> <div class="lobbyR">
<div class="lobbyRh">${title} <span class="muted">(${here.length + (showMe ? 1 : 0)})</span><span class="grow"></span> <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> <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> <div class="plist">${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `<div class="muted" style="padding:16px;text-align:center">${t('lobby_empty')}</div>`)}</div>
${pendingOut ? `<p class="muted" style="margin:6px 0 0">${t('waiting_accept')} <button class="link" id="lCancel">${t('cancel')}</button></p>` : ''} ${out ? `<p class="muted" style="margin:6px 0 0">${t('waiting_accept')} <button class="link" id="lCancel">${t('cancel')}</button></p>` : ''}
<div class="row" style="margin-top:8px"><button id="lBack">${t('back')}</button><button id="lTour">🏆 ${t('ltour_title')}</button><button class="primary" id="lQuick">${t('quick_match')}</button></div> ${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>`; </div></div>`;
overlay.classList.remove('hide'); overlay.classList.remove('clear'); 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.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 = () => { overlay.querySelectorAll('.rroom').forEach(b => { b.onclick = () => {
SFX.click(); lobbyRoom = b.dataset.f; SFX.click(); lobbyRoom = b.dataset.f;
if (lobbyRoom !== 'all') { joinedRoom = lobbyRoom; if (lobby) lobby.refresh(); } // joining a country = be present there (with my own flag) if (lobbyRoom !== 'all') { joinedRoom = lobbyRoom; if (lobby) lobby.setRoom(joinedRoom); } // joining a country = be present there
renderLobby(); renderLobby();
}; }); }; });
$('lFlag').onchange = e => { save.flag = e.target.value; persist(); if (lobby) lobby.refresh(); renderLobby(); }; $('lFlag').onchange = e => { save.flag = e.target.value; persist(); onlineFlush(); renderLobby(); };
overlay.querySelectorAll('.chal').forEach(b => { b.onclick = () => { SFX.click(); pendingOut = b.dataset.uid; lobby.challenge(b.dataset.uid); renderLobby(); }; }); overlay.querySelectorAll('.chal').forEach(b => { b.onclick = () => { SFX.click(); lobby.challenge(b.dataset.uid); renderLobby(); }; });
if ($('lCancel')) $('lCancel').onclick = () => { SFX.click(); lobby.cancel(); pendingOut = null; 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) { SFX.click(); pendingOut = idle.uid; lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); }; $('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 (save) openGarage(); else showTitle(); }; $('lBack').onclick = () => { SFX.click(); if (save) openGarage(); else showTitle(); };
$('lTour').onclick = () => { SFX.click(); openNetTourney(); };
}
// ---------------------------------------------------------------- live multiplayer tournament
function openNetTourney() {
if (!(net && net.enabled && net.auth.current)) { showOnlineLogin(false, null, 'online'); return; }
const u = net.auth.current;
if (!ntour) ntour = RC.NetTourney(net, { uid: u.uid, name: u.name || playerName(), flag: save.flag || 'XX' }, {
onView: v => { if (inNetTour) renderNetTourney(v); },
startMatch: info => startNetTourMatch(info),
});
inNetTour = true;
ntour.join(save.build, paintObj());
renderNetTourney(ntour.view());
}
function leaveNetTourney() {
inNetTour = false;
if (ntour) { ntour.leave(); }
}
function renderNetTourney(v) {
if (!inNetTour) return;
const pls = v.players.map(p => `<div class="prow ${p.me ? 'me' : ''}"><span class="pf">${flagHtml(p.flag)}</span>`
+ `<span class="pn">${esc(p.name)}${p.me ? ` <span class="muted">(${t('you')})</span>` : ''}</span>`
+ `<span class="${p.ready ? 'plus' : 'muted'}">${p.ready ? '✔ ' + t('ltour_ready') : t('ltour_waiting')}</span></div>`).join('')
|| `<p class="muted" style="text-align:center;padding:12px">${t('ltour_empty')}</p>`;
let body, buttons = '';
if (v.phase === 'running' || v.phase === 'done') {
body = netBracketHtml(v);
if (v.me.match) buttons = `<button class="primary" id="ntFight">▶ ${t('tour_fight')} (${esc(v.me.match.opp || 'Bye')})</button>`;
else if (v.me.champion) body += `<p class="plus" style="text-align:center">🏆 ${t('tour_won')}</p>`;
else if (v.me.out) body += `<p class="muted" style="text-align:center">${t('tour_out')}</p>`;
else body += `<p class="muted" style="text-align:center">${t('ltour_wait_round')}</p>`;
} else {
const me = v.players.find(p => p.me);
body = `<p class="muted">${v.phase === 'countdown' ? t('ltour_countdown', { n: v.countdown }) : t('ltour_lobby', { n: v.readyCount })}</p>`
+ `<div class="plist" style="min-width:0;max-width:420px;margin:0 auto">${pls}</div>`;
buttons = me ? `<button class="${me.ready ? '' : 'primary'}" id="ntReady">${me.ready ? t('ltour_unready') : t('ltour_setready')}</button>` : '';
}
card(`<h1>🏆 ${t('ltour_title')}</h1>${body}
<div class="row">${buttons}<button id="ntBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
if ($('ntReady')) $('ntReady').onclick = () => { SFX.click(); const me = v.players.find(p => p.me); ntour.setReady(!(me && me.ready)); };
if ($('ntFight')) $('ntFight').onclick = () => { SFX.click(); if (v.me.match && v.me.match.opp == null) return; /* bye */ };
$('ntBack').onclick = () => { SFX.click(); leaveNetTourney(); showLobby(); };
}
function netBracketHtml(v) {
if (!v.order) return '';
const rounds = RC.LTourney.rounds(v.order, v.results);
const name = u => (u ? (v.players.find(p => p.uid === u) || {}).name || u.slice(0, 5) : '—');
let cols = '';
for (let r = 0; r < rounds.length; r++) {
const col = rounds[r]; if (col.length < 2 && r) continue;
let rows = '';
for (let i = 0; i < col.length; i += 2) {
rows += `<div class="tpair">${[col[i], col[i + 1]].map(u => {
const mine = u === net.auth.current.uid;
return `<div class="tslot ${mine ? 'you' : ''}">${esc(name(u))}</div>`; }).join('')}</div>`;
}
cols += `<div class="tcol"><div class="tch">${t('tour_round_' + (RC.Tourney.ROUND_KEY[r] || 'final'))}</div>${rows}</div>`;
}
return `<div class="bracket">${cols}</div>`;
}
function startNetTourMatch(info) {
const opp = { name: info.opp.name || 'Rival', build: info.opp.build, paint: info.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: info.opp.flag };
prepOpp(opp, () => startFight(opp, false, false, { id: info.id, host: info.host, seed: info.seed, tourney: { round: info.round, pair: info.pairIndex, oppUid: info.oppUid } }));
}
function endNetTourFight(res, won, me) {
if (ntour) ntour.reportWin(F.online.tourney.round, F.online.tourney.pair, won ? net.auth.current.uid : F.online.tourney.oppUid);
save.games++; if (won) save.wins++; else save.losses++;
save.fame += won ? 120 : 30; persist(); hud();
(won ? SFX.win : SFX.lose)();
setScreen('result');
card(`<h1>${won ? t('victory') : t('defeat')}</h1><p>${esc(F.opp.name)}</p>
<div class="row"><button class="primary" id="ntRes">🏆 ${t('ltour_title')}</button></div>`, { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('ntRes').onclick = () => { SFX.click(); inNetTour = true; renderNetTourney(ntour.view()); };
} }
function showIncoming(c) { function showIncoming(c) {
card(`<h2>${t('challenge_in')}</h2><p>${flagHtml(c.fromFlag)} <b>${esc(c.fromName)}</b> ${t('wants_fight')}</p> card(`<h2>${t('challenge_in')}</h2><p>${flagHtml(c.fromFlag)} <b>${esc(c.fromName)}</b> ${t('wants_fight')}</p>
@@ -764,6 +764,22 @@
$('cYes').onclick = () => { SFX.click(); lobby.accept(c.from); }; $('cYes').onclick = () => { SFX.click(); lobby.accept(c.from); };
$('cNo').onclick = () => { SFX.click(); lobby.decline(c.from); if (mode === 'lobby') renderLobby(); else hideOverlay(); }; $('cNo').onclick = () => { SFX.click(); lobby.decline(c.from); if (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 (F && F.online && F.online.id === m.matchId && !F.ended) {
F.serverEnd = m;
F.s.result = RC.Proto.localResult(m.seat, m.result);
F.s.endIn = 0;
return;
}
if (m.save && gameMode === 'online') { adoptEconomy(m.save); afterEconomy(); }
}
// ---------------------------------------------------------------- accounts // ---------------------------------------------------------------- accounts
function showLogin(errKey) { function showLogin(errKey) {
@@ -824,13 +840,13 @@
save = slot.load(); save = slot.load();
repairSave(); repairSave();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
cloudPull(); if (gameMode === 'online') onlinePull(); else cloudPull();
} }
// registered account: fetch the cloud save; take it if newer, else push the local copy up (first migration) // campaign + registered account: fetch the cloud copy; take it if newer, else push the local copy up
function cloudPull() { function cloudPull() {
const a = fbAcc(); if (!a) return; const a = fbAcc(); if (!a || gameMode !== 'campaign') return;
const id = cloudId(), m = gameMode; // this mode's cloud slot const m = gameMode;
cloud.pull(id).then(cl => { cloud.pull().then(cl => {
const cur = fbAcc(); const cur = fbAcc();
if (!save || !cur || cur.uid !== a.uid || gameMode !== m) return; // account or mode changed while we waited if (!save || !cur || cur.uid !== a.uid || gameMode !== m) return; // account or mode changed while we waited
if (cl && RC.CloudSave.newer(cl, save)) { if (cl && RC.CloudSave.newer(cl, save)) {
@@ -838,7 +854,7 @@
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (mode === 'garage') { shop.render(); view.showGarage(save.build, paintObj()); } if (mode === 'garage') { shop.render(); view.showGarage(save.build, paintObj()); }
} else { } else {
cloud.flush(id, save); cloud.flush(save);
} }
}); });
} }
@@ -908,25 +924,22 @@
function switchRobot(i) { function switchRobot(i) {
if (i === save.active || !save.robots[i]) return; if (i === save.active || !save.robots[i]) return;
syncActive(); syncActive();
save.active = i; if (!act({ type: 'robotSwitch', index: i }).ok) return;
const a = save.robots[i];
save.build = a.build; save.paint = a.paint; save.robotName = a.name;
persist(); persist();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar(); shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar();
} }
function addRobot() { function addRobot() {
if (save.robots.length >= MAX_ROBOTS) { SFX.deny(); return; }
syncActive(); syncActive();
save.robots.push(newRobotDef(t('robot_n', { n: save.robots.length + 1 }))); if (!act({ type: 'robotNew', name: t('robot_n', { n: save.robots.length + 1 }) }).ok) { SFX.deny(); return; }
switchRobot(save.robots.length - 1); persist();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar();
SFX.buy(); SFX.buy();
} }
function delRobot(i) { function delRobot(i) {
if (save.robots.length <= 1) { SFX.deny(); return; } syncActive();
save.robots.splice(i, 1); if (!act({ type: 'robotDelete', index: i }).ok) { SFX.deny(); return; }
save.active = Kit.clamp(save.active >= i ? save.active - (save.active === i ? 0 : 1) : save.active, 0, save.robots.length - 1);
const a = save.robots[save.active]; save.build = a.build; save.paint = a.paint; save.robotName = a.name;
persist(); RC.layerFromData(layer, save.paint.decal, () => {}); shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar(); persist(); RC.layerFromData(layer, save.paint.decal, () => {}); shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar();
} }
// hangar management (shop top-tab): list of robots with weapon, switch / delete + add button // hangar management (shop top-tab): list of robots with weapon, switch / delete + add button
@@ -945,8 +958,7 @@
function signOut() { function signOut() {
persist(); persist();
cloudFlush(); // push now, while we still have the auth token cloudFlush(); // push now, while we still have the auth token
if (lobby && onlineReady) { lobby.leave(); onlineReady = false; lobbyRows = []; pendingOut = null; } if (lobby) { lobby.leave(); lobbyRows = []; }
if (ntour) { ntour.leave(); inNetTour = false; }
if (net && net.enabled) net.auth.logout(); if (net && net.enabled) net.auth.logout();
accounts.logout(); save = null; slot = null; F = null; hud(); accounts.logout(); save = null; slot = null; F = null; hud();
} }
@@ -1002,14 +1014,14 @@
segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); }); segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); });
segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); }); segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); });
segOn('sArena', v => { settings.arena = v; saveSettings(); }); segOn('sArena', v => { settings.arena = v; saveSettings(); });
if ($('sCountry')) $('sCountry').onchange = e => { save.flag = e.target.value; save.flagSet = true; persist(); if (lobby) lobby.refresh(); hud(); }; if ($('sCountry')) $('sCountry').onchange = e => { save.flag = e.target.value; save.flagSet = true; persist(); hud(); };
$('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol); $('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol);
$('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value); $('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value);
$('sSfx').onchange = () => SFX.click(); $('sSfx').onchange = () => SFX.click();
$('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); }; $('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); };
if (isDev && save) overlay.querySelectorAll('[data-coin]').forEach(b => b.onclick = () => { if (isDev && save) overlay.querySelectorAll('[data-coin]').forEach(b => b.onclick = () => {
SFX.buy(); const v = b.dataset.coin; SFX.buy(); const v = b.dataset.coin;
save.money = v === 'set800' ? 800 : Math.min(1e9, (save.money | 0) + (+v || 0)); act({ type: 'devCoins', money: v === 'set800' ? 800 : Math.min(1e9, (save.money | 0) + (+v || 0)) });
persist(); hud(); showSettings(back); persist(); hud(); showSettings(back);
}); });
if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); }; if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); };
@@ -1050,7 +1062,7 @@
<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="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 }); <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)); }); 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 (save) { save.flag = pick; save.flagSet = true; persist(); } if (lobby) lobby.refresh(); SFX.click(); done(); }; $('cfGo').onclick = () => { if (save) { save.flag = pick; save.flagSet = true; persist(); } SFX.click(); done(); };
} }
const ensureFlag = done => { if (save && !save.flagSet) chooseFlag(done); else done(); }; const ensureFlag = done => { if (save && !save.flagSet) chooseFlag(done); else done(); };
@@ -1185,7 +1197,7 @@
$('bYes').onclick = () => { Object.assign(save, newSave()); RC.layerFromData(layer, null); save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); }; $('bYes').onclick = () => { Object.assign(save, newSave()); RC.layerFromData(layer, null); save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); };
} }
// the rank badge opens the achievements page // the rank badge opens the achievements page
$('hTour').onclick = () => { SFX.click(); openNetTourney(); }; $('hTour').onclick = () => { SFX.click(); if (gameMode === 'campaign') { if (tourState()) showTournament(); else showLeague(); } }; // online tournament: server-side later (plan P2-6)
$('chipFame').onclick = () => { $('chipFame').onclick = () => {
if (!save || mode === 'intro' || mode === 'title') return; if (!save || mode === 'intro' || mode === 'title') return;
if (mode === 'fight') togglePause(); if (mode === 'fight') togglePause();
@@ -1372,7 +1384,8 @@
function startFight(opp, training, exhibition, online, tour) { function startFight(opp, training, exhibition, online, tour) {
hideOverlay(); hideOverlay();
const D = BASE; const D = BASE;
const stA = RC.stats(save.build), stB = RC.stats(opp.build); const myBuild = online ? online.myBuild : save.build; // live: exactly the robot the server fights with
const stA = RC.stats(myBuild), stB = RC.stats(opp.build);
if (!online) stA.hp = Math.round(stA.hp * D.hp); // no handicap in live PvP if (!online) stA.hp = Math.round(stA.hp * D.hp); // no handicap in live PvP
const seed = online ? online.seed : (Date.now() & 0xffff) + save.games * 31; const seed = online ? online.seed : (Date.now() & 0xffff) + save.games * 31;
// arena: league scales with the opponent, online derives from the shared seed, training uses the setting // arena: league scales with the opponent, online derives from the shared seed, training uses the setting
@@ -1380,17 +1393,15 @@
const bySize = RC.ARENAS.slice().sort((a, b) => a.half - b.half).map(a => a.id); // small -> big for league progression const bySize = RC.ARENAS.slice().sort((a, b) => a.half - b.half).map(a => a.id); // small -> big for league progression
const arenaId = DEV.get('arena') ? DEV.get('arena') const arenaId = DEV.get('arena') ? DEV.get('arena')
: (LIVE.event && LIVE.event.arena && !online) ? LIVE.event.arena : (LIVE.event && LIVE.event.arena && !online) ? LIVE.event.arena
: online ? ids[seed % ids.length] : online ? online.arena
: idx >= 0 ? bySize[Math.min(bySize.length - 1, Math.floor(idx * bySize.length / RC.LEAGUE.length))] : idx >= 0 ? bySize[Math.min(bySize.length - 1, Math.floor(idx * bySize.length / RC.LEAGUE.length))]
: settings.arena === 'random' || !settings.arena ? ids[(Math.random() * ids.length) | 0] : settings.arena; : settings.arena === 'random' || !settings.arena ? ids[(Math.random() * ids.length) | 0] : settings.arena;
const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name], arena: arenaId }); const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name], arena: arenaId });
const skill = Kit.clamp(opp.skill + (save.season - 1) * 0.12 + D.skill, 0, 1); const skill = Kit.clamp(opp.skill + (save.season - 1) * 0.12 + D.skill, 0, 1);
F = { s, opp, training, exhibition: !!exhibition, online, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4, const count = online ? Math.max(0, +online.countdown || 0) : 3.5;
acc: [0, 0], accT: 0, banner: null, ended: false }; F = { s, opp, training, exhibition: !!exhibition, online, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count, beat: Math.ceil(count) + 1,
if (online) { acc: [0, 0], accT: 0, banner: null, ended: false, oppAway: false };
F.nf = RC.NetFight({ net, id: online.id, host: online.host, oppStyle: 'brawler', oppSkill: 0.6, onPeerLost: () => banner(t('peer_lost'), '#ff4a3a', 2.5), onPeerBack: () => banner(t('peer_back'), '#6dff9e', 1.6) }); if (online) F.nf = RC.NetFight({ net, seat: online.seat }); // the server runs the fight, we show it
F.nf.start();
}
// dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing) // dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing)
if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 }); if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 });
if (DEV.has('ff')) { if (DEV.has('ff')) {
@@ -1401,7 +1412,7 @@
s.events.length = 0; s.events.length = 0;
} }
} }
view.showArena(s, [save.build, opp.build], [paintObj(), oppPaint(opp)]); view.showArena(s, [myBuild, opp.build], [paintObj(), oppPaint(opp)]);
if (view.setComfort) view.setComfort(settings.comfort); if (view.setComfort) view.setComfort(settings.comfort);
view.setCam(DEV.get('cam') || settings.cam); // dev: &cam=chase|fpv view.setCam(DEV.get('cam') || settings.cam); // dev: &cam=chase|fpv
$('fN0').textContent = save.robotName; $('fN1').textContent = opp.name; $('fN0').textContent = save.robotName; $('fN1').textContent = opp.name;
@@ -1524,14 +1535,11 @@
function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; } function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; }
let ntourT = 0;
function update(dt) { function update(dt) {
if (ntour && inNetTour) { ntourT -= dt; if (ntourT <= 0) { ntourT = 2; ntour.tick(); } }
fx.update(dt); fx.update(dt);
introTick(); introTick();
if (mode !== 'fight' || !F) return; if (mode !== 'fight' || !F) return;
if (F.count > 0) { if (F.count > 0) {
if (F.nf) F.nf.idle(dt);
F.count -= dt; F.count -= dt;
const n = Math.ceil(F.count); const n = Math.ceil(F.count);
if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } } if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } }
@@ -1540,7 +1548,10 @@
const s = F.s, [me, en] = s.robots; const s = F.s, [me, en] = s.robots;
let events; let events;
if (F.online) { if (F.online) {
events = F.online.host ? F.nf.hostStep(s, playerInput(), dt) : F.nf.guestFrame(s, playerInput(), dt); events = F.nf.frame(s, playerInput(), dt);
if (F.nf.oppAway !== F.oppAway) { F.oppAway = F.nf.oppAway; banner(t(F.oppAway ? 'peer_lost' : 'peer_back'), F.oppAway ? '#ff4a3a' : '#6dff9e', 2.2); }
// no word from the server for 20 s (and no result yet - a hidden tab may simply have slept through the end)
if (!F.serverEnd && F.nf.silentFor > 20 && !F.ended) { F.ended = true; onlineFightLost(); return; }
} else { } else {
RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]); RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]);
events = s.events; events = s.events;
@@ -1567,7 +1578,8 @@
} }
} }
if (s.left <= 10 && !s.result && Math.ceil(s.left) !== F.tick) { F.tick = Math.ceil(s.left); audio.tone(1200, 0.05, 'square', 0.06); } if (s.left <= 10 && !s.result && Math.ceil(s.left) !== F.tick) { F.tick = Math.ceil(s.left); audio.tone(1200, 0.05, 'square', 0.06); }
if (s.result && s.endIn <= 0 && !F.ended) { F.ended = true; endFight(); } // live: the fight is over when the server says so (match.end carries the booked rewards)
if (s.result && s.endIn <= 0 && !F.ended && (!F.online || F.serverEnd)) { F.ended = true; endFight(); }
} }
// cooldown chips for the parts actually fitted (built once, only --p changes per frame) // cooldown chips for the parts actually fitted (built once, only --p changes per frame)
@@ -1682,7 +1694,6 @@
function endFight() { function endFight() {
const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp); const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp);
const won = res.winner === 0, me = s.robots[0]; const won = res.winner === 0, me = s.robots[0];
if (F.online && F.online.tourney) { endNetTourFight(res, won, me); return; }
if (F.online) { endOnlineFight(res, won, me); return; } if (F.online) { endOnlineFight(res, won, me); return; }
if (F.tour) { endTourFight(res, won, me); return; } if (F.tour) { endTourFight(res, won, me); return; }
const lines = []; const lines = [];
@@ -1724,7 +1735,7 @@
const fightCtx = { won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt, const fightCtx = { won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt,
lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length, lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length,
training: F.training, exhibition: F.exhibition, champion }; training: F.training, exhibition: F.exhibition, champion };
const gotAch = awardAch(fightCtx); const gotAch = gameMode === 'online' ? [] : awardAch(fightCtx); // online: achievements pay out on the server only
const gotMiss = updateMissions(fightCtx); // campaign missions: progress + pay const gotMiss = updateMissions(fightCtx); // campaign missions: progress + pay
hud(); hud();
(won ? SFX.win : SFX.lose)(); (won ? SFX.win : SFX.lose)();
@@ -1742,10 +1753,7 @@
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' }); { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bGarage').onclick = () => { SFX.click(); openGarage(); }; $('bGarage').onclick = () => { SFX.click(); openGarage(); };
if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false, F.exhibition); }; if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false, F.exhibition); };
if (!F.training && save.fame > save.best) { if (!F.training && save.fame > save.best) { save.best = save.fame; persist(); }
save.best = save.fame; persist();
if (gameMode === 'online') { rank.submit(rankRow()).then(fillBoard); return; } // global board = online fame only
}
fillBoard(); fillBoard();
} }
@@ -1783,43 +1791,36 @@
$('bTour').onclick = () => { SFX.click(); showTournament(); }; $('bTour').onclick = () => { SFX.click(); showTournament(); };
} }
// live fight over: the server already booked prize, repairs and achievements - show them and take its save
function endOnlineFight(res, won, me) { function endOnlineFight(res, won, me) {
if (F.nf) F.nf.stop(); if (F.nf) F.nf.stop();
if (lobby) lobby.endMatch(); const m = 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)(); (won ? SFX.win : SFX.lose)();
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat'); const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
// online rewards: prize (win) / half (draw) / appearance fee (loss) + damage bonus - repairs; fame on a win const sm = (m && m.summary) || { dealt: me.dealt, taken: me.taken };
const PVP = 600, lines = []; 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('');
let money = 0, fame = 0; const ach = (rw.ach || []).map(a => ({ id: a.id, reward: a.reward }));
const draw = res.winner === -1;
if (won) { money += PVP; lines.push([t('r_prize'), PVP]); fame = 150 + (res.reason === 'ko' ? 40 : res.reason === 'pit' ? 60 : 0); }
else if (draw) { money += PVP / 2; lines.push([t('r_draw_prize'), PVP / 2]); fame = 40; }
else { const ap = Math.round(PVP * 0.35); money += ap; lines.push([t('r_appearance'), ap]); }
if (won && res.reason !== 'time') { const b = Math.round(PVP * (res.reason === 'pit' ? 0.3 : 0.2)); money += b; lines.push([t('r_bonus_' + res.reason), b]); }
const db = Math.round(me.dealt * 0.6);
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06);
money = applyEvent(money, lines);
const paid = Math.min(repair, save.money + money);
if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); }
save.money += money; save.fame += fame; save.games++;
if (won) save.wins++; else if (!draw) save.losses++;
persist();
const gotAch = awardAch({ won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt,
lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length });
hud(); hud();
if (save.fame > save.best) { save.best = save.fame; persist(); rank.submit(rankRow()); }
const rows = lines.map(([k, v]) => `<span>${k}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
setScreen('result'); setScreen('result');
card(`<h1>${title}</h1><p>${esc(F.opp.name)} ${F.nf && !F.nf.peerAlive ? t('peer_left') : ''}</p> card(`<h1>${title}</h1><p>${esc(F.opp.name)} ${F.oppAway ? t('peer_left') : ''}</p>
<div class="res"><span>${t('r_dealt')}</span><span>${Math.round(me.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(me.taken)}</span>${rows} <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}
${fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div> ${rw.fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(rw.fame)}</span>` : ''}</div>
${achHtml(gotAch)} ${achHtml(ach)}
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button><button id="bShopO">${t('to_garage')}</button></div>`, <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' }); { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bLobby').onclick = () => { SFX.click(); showLobby(); }; $('bLobby').onclick = () => { SFX.click(); showLobby(); };
$('bShopO').onclick = () => { SFX.click(); openGarage(); }; $('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 (F && F.nf) 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(); };
}
// ---------------------------------------------------------------- loop // ---------------------------------------------------------------- loop
let lastNow = 0, fpsN = 0, fpsT = 0, fpsVal = 0; let lastNow = 0, fpsN = 0, fpsT = 0, fpsVal = 0;
@@ -1911,7 +1912,7 @@
if (LIVE.onlineOff && gameMode === 'online' && save) switchMode('campaign'); if (LIVE.onlineOff && gameMode === 'online' && save) switchMode('campaign');
if (mode === 'title') showTitle(); else if (mode === 'lobby') renderLobby(); if (mode === 'title') showTitle(); else if (mode === 'lobby') renderLobby();
}); });
if (DEV.get('live')) { // dev: &live=event|off|old|lock (no Firebase needed) if (DEV.get('live')) { // dev: &live=event|off|old|lock (no server needed)
const k = DEV.get('live'), now = Date.now(); const k = DEV.get('live'), now = Date.now();
const demo = { const demo = {
event: { event: { id: 'demo', name: { de: 'Schwergewichts-Wochenende', en: 'Heavyweight weekend' }, type: 'prize', prizeMul: 2, from: now - 1000, to: now + 36e5 } }, event: { event: { id: 'demo', name: { de: 'Schwergewichts-Wochenende', en: 'Heavyweight weekend' }, type: 'prize', prizeMul: 2, from: now - 1000, to: now + 36e5 } },
@@ -1925,7 +1926,19 @@
} }
setMode('online'); // every page load starts in online play setMode('online'); // every page load starts in online play
accounts.resume(); accounts.resume();
if (net && net.enabled) { net.auth.resume(); net.auth.onChange(() => { hud(); refreshDev(); if (mode === 'title') showTitle(); }); } if (net && net.enabled) {
let lastUid = null;
net.auth.onChange(cur => {
hud(); refreshDev();
// session gone while playing online (expired / server reset / logged out elsewhere): ask to log in again
if (lastUid && !cur && gameMode === 'online' && save && ['garage', 'lobby', 'result'].includes(mode)) {
if (lobby) lobby.leave();
showOnlineLogin(false, 'SESSION_EXPIRED', 'online');
} else if (mode === 'title') showTitle();
lastUid = cur ? cur.uid : null;
});
if (net.auth.resume()) lastUid = net.uid;
}
hud(); hud();
if (!hostOk()) { if (!hostOk()) {
card(`<h1>Robot Clash</h1><p>${t('wrong_host')}</p><p class="credits">${CREDITS}</p>`); card(`<h1>Robot Clash</h1><p>${t('wrong_host')}</p><p class="credits">${CREDITS}</p>`);

View File

@@ -817,6 +817,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,7 +830,6 @@
<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="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>

View File

@@ -236,12 +236,18 @@ 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)',
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',
@@ -510,12 +516,18 @@ 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)',
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',

View File

@@ -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 };

View File

@@ -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);

View File

@@ -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

View File

@@ -1,170 +1,155 @@
/* 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; if (msg.t === 'welcome') { isOpen = true; backoff = 1000; emit('open', msg); }
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 === 'error' && (msg.code === 'OUTDATED' || msg.code === 'REPLACED')) { want = false; emit(msg.code === 'OUTDATED' ? 'outdated' : 'replaced', msg); }
if (data == null) delete o[keys[keys.length - 1]]; else o[keys[keys.length - 1]] = data; 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);

View File

@@ -1,162 +1,64 @@
/* 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) }); const nf = RC.NetFight({ net, seat })
nf.start() nf.frame(s, input, dt) send input (on change, max 30/s, at least every 0.25 s), ease the local state toward
HOST each tick, instead of the normal step: the newest snapshot, return the events of snapshots not seen yet
nf.hostStep(s, localInput, dt) runs step with [local, remote|AI], publishes ~15 Hz, returns events nf.oppAway true while the opponent is disconnected (server tells us)
GUEST each frame, instead of step: nf.silentFor seconds since the last snapshot (connection trouble)
nf.guestFrame(s, localInput, dt) eases robots toward the last snapshot, returns events to play nf.stop() */
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
ordered [host, guest]; each side maps so that *its* robot is index 0. */
(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;
// 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; };
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}`; let latest = null, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
let pubT = 0, seq = 0, sendT = 0, beatT = 0, lastInSeq = -1, evBuf = []; const off = sock.on('snap', m => { latest = RC.Proto.toLocal(seat, m); lastSnap = Date.now(); });
let sending = false, slow = 0; // one write at a time; back off while the line is slow
let remoteInput = { throttle: 0, turn: 0, fire: false, fire2: false, fire3: false };
let started = false, lastPeer = Date.now(), peerAlive = true, ai = null, subIn = null, subState = null, subPing = null, lastState = null, stateApplied = -1;
function start() { const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3;
if (host) { function sendInput(inp, dt) {
// host reads the guest's input stream sendT -= dt; keepT -= dt;
subIn = db.stream(`${base}/in`, v => { if (v && typeof v.seq === 'number') { remoteInput = v; lastPeer = Date.now(); } }); if (sendT > 0 || (!changed(inp) && keepT > 0)) return;
} else { const i = RC.Proto.input(inp);
// guest reads the host's state stream if (sock.send(Object.assign({ t: 'input', seq: ++seq }, i))) { prev = i; sendT = SEND_MIN; keepT = SEND_KEEP; }
subState = db.stream(`${base}/state`, v => { if (v && typeof v.seq === 'number') { lastState = v; lastPeer = Date.now(); } });
subPing = db.stream(`${base}/ping`, v => { if (v) lastPeer = Date.now(); }); // host alive during the countdown
}
} }
function checkPeer() { function applyRobot(r, d, k) {
if (!started) { started = true; lastPeer = Math.max(lastPeer, Date.now()); } // countdown is over: start the clock for (const f of EASE) if (typeof d[f] === 'number') r[f] += (d[f] - r[f]) * k;
if (!peerAlive && Date.now() - lastPeer < GRACE) { peerAlive = true; if (opt.onPeerBack) opt.onPeerBack(host); } for (const f of ANG) if (typeof d[f] === 'number') r[f] += wrap(d[f] - r[f]) * k;
if (peerAlive && Date.now() - lastPeer > GRACE) { for (const f of RC.Proto.RF) if (!EASE.includes(f) && !ANG.includes(f) && d[f] !== undefined) r[f] = d[f];
peerAlive = false; if (d.lost) r.lost = Object.assign(r.lost || {}, d.lost);
if (host && !ai) ai = RC.AI.create({ style: opt.oppStyle || 'brawler', skill: opt.oppSkill != null ? opt.oppSkill : 0.5, seed: 7 }); if (d.lostW) r.lostW = d.lostW.slice();
if (opt.onPeerLost) opt.onPeerLost(host); if (d.W && r.W) d.W.forEach((w, i) => { if (r.W[i]) Object.assign(r.W[i], w); });
}
} }
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]); };
// 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 (!latest) return [];
checkPeer(); const n = latest, k = Math.min(1, dt * 14);
const guestInput = peerAlive ? remoteInput : ai.think(s, s.robots[1], s.robots[0], dt); s.t = n.time; s.left = n.left; s.pitOpen = n.pitOpen; s.pitAlarm = n.pitAlarm; s.endIn = n.endIn;
RC.Combat.step(s, dt, [localInput, guestInput]); s.press.st = n.press.st; s.press.y = n.press.y;
if (s.events.length) evBuf.push.apply(evBuf, s.events); // batch events between publishes for the guest Object.assign(s.crane, n.crane);
pubT -= dt; syncList(s.rockets, n.rockets, { sp: 6, t: 3 });
// publish only when the previous write came back - otherwise slow uploads queue up and the host stutters syncList(s.mines, n.mines, { r: 0.85 });
if (pubT <= 0 && !sending) { applyRobot(s.robots[0], n.robots[0], k);
pubT = PUB + slow; applyRobot(s.robots[1], n.robots[1], k);
sending = true; if (n.result) s.result = n.result;
const t0 = Date.now(); if (n.tick === seenTick) return [];
const payload = { seenTick = n.tick;
seq: ++seq, t: rnd(s.t), left: rnd(s.left), pitOpen: rnd(s.pitOpen), pitAlarm: s.pitAlarm, return n.ev || [];
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 => ({ x: rnd(k.x), z: rnd(k.z), y: rnd(k.y), a: rnd(k.a) })),
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 !!(latest && latest.away && latest.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(); },
}; };
}; };
})(typeof window !== 'undefined' ? window : globalThis); })(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -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);

View File

@@ -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 }]

112
game/protocol.js Normal file
View File

@@ -0,0 +1,112 @@
/* 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: { t: v => v === undefined || isNum(v) },
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,
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);

View File

@@ -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);
}; };

View File

@@ -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();
} }

View File

@@ -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`.

View File

@@ -1,98 +1,102 @@
/* 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 }; }));
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 };

View File

@@ -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,66 @@ 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) function verify(token) {
function auth(req, _res, next) { try { const d = jwt.verify(String(token || ''), SECRET); return { uid: d.uid, name: d.name, guest: !!d.guest, admin: d.role === 'admin' }; } catch (e) { return null; }
const tok = req.query.auth || (req.headers.authorization || '').replace(/^Bearer\s+/i, ''); }
try { const d = jwt.verify(tok, SECRET); req.uid = d.uid; req.user = d; } catch (e) { req.uid = null; req.user = 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 };

View File

@@ -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 };

70
server/db/index.js Normal file
View File

@@ -0,0 +1,70 @@
/* 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 = ?'),
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 };

View 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
);

View File

@@ -1,53 +1,56 @@
# 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/), 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.

View File

@@ -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
View 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 || 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
scp -q "$TAR" "$HOST:/tmp/rc-$REL.tgz"
tr -d '\r' < server/deploy/remote-release.sh | ssh "$HOST" bash -s -- "$REL" "$SHA" "$RESET"

View File

@@ -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/"

View 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

View File

@@ -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"

View File

@@ -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 };

152
server/lobby.js Normal file
View File

@@ -0,0 +1,152 @@
/* 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),
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; }
}
}
// 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, startMatch, players, pending, inMatch };
}
module.exports = { createLobby, CHALLENGE_TTL };

116
server/match/room.js Normal file
View File

@@ -0,0 +1,116 @@
/* 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.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;
RC.Combat.step(s, DT, [this.inputFor(0), this.inputFor(1)]);
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]];
for (const seat of [0, 1]) this.send(seat, Object.assign({ t: 'snap', away }, 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 };

41
server/match/runner.js Normal file
View File

@@ -0,0 +1,41 @@
/* 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()) room.tick();
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 };

View File

@@ -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
}
}
} }
} }
} }

View File

@@ -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
View 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 };

View File

@@ -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 };

View File

@@ -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 };

View 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);

View 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/);
});

View File

@@ -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,25 @@ 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('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);
}); });

View File

@@ -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 };

141
server/test/lobby.test.js Normal file
View File

@@ -0,0 +1,141 @@
'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('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('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);
assert.ok(ca.inbox.some(m => m.t === 'snap'), 'snapshots arrived before the end');
// 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
View 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);
});

58
server/ws/hub.js Normal file
View File

@@ -0,0 +1,58 @@
/* 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 = 15000;
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.alive = true;
ws.on('pong', () => { ws.alive = true; });
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 });
lobby.join({ uid: u.uid, name: u.name, admin: u.admin, send });
return;
}
if (msg.t === 'hello') return;
lobby.handle(user.uid, msg);
});
ws.on('close', () => { clearTimeout(helloTimer); if (user) lobby.leave(user.uid, send); });
ws.on('error', () => {});
});
const beat = setInterval(() => {
for (const ws of wss.clients) { if (!ws.alive) { ws.terminate(); continue; } ws.alive = false; try { ws.ping(); } catch (e) { /* closed */ } }
}, PING_MS);
if (beat.unref) beat.unref();
wss.on('close', () => clearInterval(beat));
return wss;
}
module.exports = { attach };

128
tests/eco.test.js Normal file
View 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);
});

97
tests/protocol.test.js Normal file
View File

@@ -0,0 +1,97 @@
'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: '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], 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.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');
});

65
tools/smoke.js Normal file
View File

@@ -0,0 +1,65 @@
#!/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();
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); });