Compare commits

...

37 Commits

Author SHA1 Message Date
a494290548 fix(net): interpolate between snapshots to absorb jitter (P1-6)
netfight eased to the newest snapshot with no buffer, so a jittery
client's robot stalled then jumped. Render ~120 ms in the past between
the two bracketing snapshots instead. Dev params ?netlag/?interp/
?netprobe reproduce it; unit test for the interp math + a Playwright
lag test (tests/e2e/netlag.spec.js).
2026-11-19 19:46:54 +01:00
Benjamin Oezcan
2bf5a40ebc fix(ui): F3 overlay was always shown as an empty box and could not be closed 2026-11-19 15:28:23 +01:00
Benjamin Oezcan
90f1c9c37e build(deploy): ship tools/ so the test bot can run on the server 2026-11-19 15:14:56 +01:00
Benjamin Oezcan
c99881e63a docs: test bot and F3 network overlay 2026-11-19 14:35:05 +01:00
Benjamin Oezcan
695cf77afc feat(net): F3 network overlay - ping graph and where lag comes from (you, opponent, server) 2026-11-19 14:30:40 +01:00
Benjamin Oezcan
a8d6158384 feat(tools): dumb test bot that accepts challenges and drives a pattern (npm run bot) (P4-1) 2026-11-19 14:26:50 +01:00
Benjamin Oezcan
593d69714b feat(net): server measures every player's ping and its own step cost, sent with each snapshot
Also fixes the ping message schema (it checked the field t, which is the message type).
2026-11-19 14:25:46 +01:00
Benjamin Oezcan
3dc770e34a fix(server): tokens of deleted accounts are refused; a failing message or fight can no longer crash the server
After a database reset an old (still signed) token made economy.load insert a save for a missing user;
the FOREIGN KEY error escaped the WebSocket handler and took the process down in a restart loop.
2026-11-19 10:02:51 +01:00
Benjamin Oezcan
0ffa221e82 feat(server): DELETE /api/me deletes your account; smoke test cleans up after itself 2026-11-19 09:59:19 +01:00
Benjamin Oezcan
4535ac7d8a refactor(game): split game.js into sfx, pages, online and workshop modules (P4-5)
Modules are classic-script factories RC.Game<Part>(G); G gives live access to the shared state.
Guarded by new browser tests for every moved page and workshop tool (tests/e2e/screens.spec.js).
2026-11-19 09:58:53 +01:00
Benjamin Oezcan
fade816169 test(e2e): playwright - two browsers play online, server shop, offline campaign (P4-2) 2026-11-19 09:47:22 +01:00
Benjamin Oezcan
dd120f47f8 feat(fight): give up a live fight from the pause card 2026-11-19 09:47:22 +01:00
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
Benjamin Oezcan
4a14b1de76 docs: mark host-based online notes outdated 2026-11-19 01:42:16 +01:00
Benjamin Oezcan
06b60a45d4 docs: update commands, mark firebase docs outdated, close phase 0 (P0-5, P0-6) 2026-11-19 01:42:08 +01:00
Benjamin Oezcan
1156bc68eb chore: add eslint, remove dead variables, pin line endings (P0-4) 2026-11-19 01:41:27 +01:00
Benjamin Oezcan
fa68ef620d feat(server): healthz, testable app, local dev script (P0-3) 2026-11-19 01:40:31 +01:00
Benjamin Oezcan
35348324d6 test: single npm test entry point, drop firebase live test (P0-2) 2026-11-19 01:40:30 +01:00
Benjamin Oezcan
dd85d488a8 docs: adopt conventional commits and semver 2026-11-19 01:36:03 +01:00
Benjamin Oezcan
89db76c9f7 docs: no co-author lines in commit messages 2026-11-19 01:35:01 +01:00
Benjamin Oezcan
d9b41fa1c8 docs: commit directly to main, no branch/PR workflow
Michi and Benni pair-program; main is the dev line. Branches only for
throwaway experiments. CI tests every push to main and deploys only green.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 01:33:31 +01:00
Benjamin Oezcan
267507f715 docs: multiplayer refactor plan + quality rules
- docs/MULTIPLAYER-PLAN.md: analysis of the current online mode, target
  architecture (server-authoritative fights over WebSocket, Firebase removed),
  phased tasks with acceptance criteria, test strategy, deploy plan,
  later TODOs (T-1..T-4)
- CLAUDE.md: binding quality rules (test first, lint/test before done,
  server decides online), test-system note (no prod yet), Gitea remote

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 01:31:47 +01:00
347701d66f onlinemodus fix failed 2026-11-19 00:55:39 +01:00
64c5b65543 big update 2026-11-18 15:18:38 +01:00
e0496fa089 view update 2026-11-17 14:17:50 +01:00
3e565cf8c7 map change 2026-11-15 20:05:02 +01:00
116 changed files with 10292 additions and 1312 deletions

10
.gitattributes vendored Normal file
View File

@@ -0,0 +1,10 @@
* text=auto
*.sh text eol=lf
*.ps1 text eol=crlf
*.png binary
*.jpg binary
*.ogg binary
*.wav binary
*.mp3 binary
*.ttf binary
*.sqlite binary

11
.gitignore vendored
View File

@@ -7,3 +7,14 @@ node_modules/
*.log
tools/shots/
.claude/
# service-account keys (legacy) - SECRET, never commit
serviceAccount*.json
admin/*.json
**/*serviceaccount*.json
# Server secrets + local DB
server/node_modules/
server/.env
server/data.sqlite*
server/*.sqlite*
test-results/
playwright-report/

125
CLAUDE.md
View File

@@ -12,6 +12,14 @@ keine Namen, Figuren, Arenen, Hausroboter, Grafiken, Sounds oder Code aus dem Or
## Spielkonzept
**Zwei getrennte Spiele.** Beim Seitenaufruf startet immer der **Online-Modus**; in der Werkstatt schaltet ein
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),
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 Server (`file://`)
fällt alles auf die Kampagne zurück. Dev: `&gmode=campaign|online`.
**Ablauf**
1. **Werkstatt:** Roboter aus Teilen bauen – je 1 Chassis, Motor, Räder, Batterie (Pflicht), dazu Panzerung,
Hauptwaffe, Turm und Gadget. Stand: 10 Chassis (Formen box/wedge/dome/frame/hex/barrel/arrow/plow/saucer),
@@ -20,7 +28,12 @@ keine Namen, Figuren, Arenen, Hausroboter, Grafiken, Sounds oder Code aus dem Or
Stacheln, Kacheln – `style` in parts.js, Zweig in render3d), 3 Türme, 5 Gadgets; jedes Teil zeigt im Detail seinen Hotkey und
führt seine Bewegung in der Werkstatt-Vorschau vor. Max. 100 kg,
Batterie muss den Strom liefern. Kaufen / einbauen / verkaufen (50 %), Lack + Akzentfarbe, Name.
2. **Liga:** 8 KI-Gegner nacheinander (Stile: Raufbold, Flankierer, Schieber, Schütze), steigende Preise.
2. **Liga, drei Gewichtsklassen:** Leicht ≤ 60 kg · Mittel ≤ 100 kg · Schwer ≤ 130 kg (`RC.CLASSES`),
je Klasse **eigene 8 Gegner** (`RC.LEAGUES`, Rosters in ai.js) und **eigener Fortschritt** (`save.leagues`,
aktive Werte stehen in `save.beaten`/`save.season`, `syncClass()` schreibt sie zurück). `RC.setClass(id)`
tauscht `RC.LEAGUE` **und** `RC.WEIGHT_LIMIT` – deshalb musste sonst nichts umgebaut werden. Klassenwahl über
Reiter auf der Liga-Seite. Eine Schwierigkeitseinstellung gibt es nicht mehr; die Klasse ist der Regler
(fester Balance-Sockel `BASE` in game.js = die frühere Voreinstellung „Leicht").
**Kampfschaden:** Teile reißen bei festen LP-Anteilen ab (Panzer 60 %, Rad 40 %, Hauptwaffe 25 %, Turm 18 % –
deterministisch, `BREAK_AT` in combat.js). Das Teil verlässt das 3D-Modell und poltert über den Boden
(`breakPart`/`dropPiece`), wirkt sich aus (Rad: langsamer; Panzer: weniger Schutz; Waffe/Turm: tot) und steht
@@ -69,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*
**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
Roboter, KI-gesteuert), echtes PvP (WebRTC), Replays/Zuschauer, weitere Arenen + Gewichtsklassen, Icon/Musik/SFX
Speichern, en/de, Synth-Sounds. **Später:** asynchrones PvP (hochgeladene Roboter, KI-gesteuert),
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`,
`gen adopt --wide --size 1024 logo`) – fehlt es, zeigt der Titel den Schriftzug; ComfyUI muss dafür laufen.
**Online-Technik:** Der Host rechnet und sendet Snapshots – er schreibt **nur einen** Request gleichzeitig
(`sending`-Sperre in netfight.js) und drosselt bei langsamer Leitung, sonst stapeln sich die Uploads und *beim
Host* ruckelt es, während der Gast flüssig bleibt. Zahlen werden auf 3 Nachkommastellen gerundet (Paketgröße).
Rangliste: `Kit.scores.top()` zeigt **jeden Spieler nur einmal** (bester Lauf) – jeder Eintrag ist eine eigene
Zeile in der DB, die Entdopplung passiert beim Lesen (Fix liegt in `_Tools\Library\web\kit\kit-scores.js`).
**Online-Technik (server-autoritativ):** Der **Server rechnet jeden Live-Kampf** (`server/match/room.js`,
`RC.Combat.step` mit 60 Hz) und schickt Snapshots (20 Hz) über **einen WebSocket** pro Spieler (`/ws`); die Clients
senden nur Eingaben und zeigen an (`game/netfight.js`). Ergebnis, Preisgeld, Reparatur und Erfolge bucht der Server
(`match.end`). Seat ↔ lokaler Index wird **nur** in `RC.Proto.toLocal` (`game/protocol.js`) gespiegelt. Lobby =
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):** Titel → „Online spielen" (nur wenn `NET_CFG.apiKey` gesetzt), Login per
E-Mail/Passwort, globale Lobby (alle Online-Spieler + Länderflagge), Klick auf Spieler = Herausfordern → Live-Kampf.
Rangliste läuft schon mit `DB_URL` allein. Einrichtung + Grenzen: `docs/firebase/README.md`.
**Online-Ablauf:** Titel → „Online spielen" → Login (Name oder E-Mail) / Registrieren (Name, E-Mail optional) / Gast →
globale Lobby (alle Online-Spieler + Länderflagge), Klick auf Spieler = Herausfordern → Live-Kampf. Rangliste
`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 /
niedrig 1,0, Schatten-Map 1024 (soft nur bei Hoch), `powerPreference high-performance`. Standard-Grafik „Mittel“.
@@ -95,18 +112,43 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
## Dateien
- `game/progress.js` Ränge (Ruhm-Schwellen) + Erfolge (DOM-frei, Node-testbar); je Modus eigener Stand in `save.ach`.
- `game/tourney.js` 8er-K.-o.-Turnier (DOM-frei): Feld aus dir + 7 Liga-Robotern, die anderen Partien werden
mit `RC.Combat`/`RC.AI` wirklich ausgefochten (~75 ms gesamt). Einstieg über die Liga-Seite, Stand in `save.tour`.
- `game/parts.js` Teilekatalog · `game/robot.js` Bauregeln + Werte · `game/combat.js` Physik, Waffen, Fallen,
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/shop.js` Werkstatt-Shop (Kategorien, Teile-Karten mit Sprites, Detail mit Vergleich, Mechaniker-Tipps)
· `game/net.js` Firebase über REST (Auth + RTDB + Server-Sent-Events, kein SDK) · `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,
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/profiles.js` Konten (v1 lokal: Name + Passwort-Hash, je Konto eigener Spielstand; später Firebase)
· `game/game.js` Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Registrieren/Gast → Shop → Liga/VS → Kampf → Ergebnis, Einstellungen.
· `game/profiles.js` lokale Konten für die Offline-Kampagne (Name + Passwort-Hash, je Konto eigener Spielstand)
· `game/game.js` Kern + Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Gast → Shop → Liga/VS → Kampf → Ergebnis.
Aufgeteilt (klassische Skripte, kein Build): `game/sfx.js` Sound · `game/pages.js` Menüseiten (Einstellungen,
Hilfe, Tutorial, Land, Erfolge, Missionen, Rechtliches, Rangliste) · `game/online.js` Online (act(), Abgleich mit
dem Server, Login-Karte, Lobby, Online-Kampfende) · `game/workshop.js` Waffen-Editor, Lack, Hangar. Jedes Modul
ist eine Fabrik `RC.Game<Teil>(G)`; `G` (Ende von game.js) liefert per Getter den **aktuellen** Zustand (`G.save`,
`G.mode`, `G.F` …) und per Setter das Zurückschreiben. Neue gemeinsame Variable → in `G` eintragen. Aufrufe aus
game.js laufen über kurze Weiterleitungen (`function x(...a) { return GM.<teil>.x(...a); }`).
- `game/vendor/three.min.js` three.js r149 (MIT, letzte Version mit klassischem Build – nicht auf ES-Module updaten).
- Tests: `node tests/sim.test.js` (Regeln, Kämpfe ohne NaN, Grube), `node tests/balance.js [-v]` (Zahlen).
- 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`
(Zahlen), `npm run dev` (Server lokal auf :8080, braucht `server/.env` aus `.env.example`),
`npm --prefix server run db:reset` (DB frisch + Testkonten), `npm run deploy` (= `bash server/deploy/deploy.sh`,
`-- --reset-db` setzt die DB zurück), `npm run smoke -- https://roboclash.michael-media.de` (nach jedem Deploy).
Zwei Spieler lokal: `?online&slot=1` und `?online&slot=2` in zwei Tabs.
`npm run bot -- --url <server> --pattern circle|zigzag|spin|charge|idle [--challenge <name>]` = dummer Testgegner
(nimmt Herausforderungen an, fährt ein Muster, löscht sich bei Strg+C). **F3** im Spiel (oder `?net`) = Netz-Overlay:
Ping-Verlauf, Gegner-Ping (vom Server gemessen), Snapshot-Abstand, Tasten-Verzögerung, Server-Last + Klartext-Urteil
(`game/netstats.js` rechnet, `game/netoverlay.js` zeigt). Bot **auf dem Server** starten = Gegner mit ~0 ms Ping.
`npm run e2e` = Playwright-Browsertests (`tests/e2e/`, nutzt das installierte Chrome, startet eigenen Server auf
:8099 mit frischer DB): zwei Browser spielen online gegeneinander, Shop gegen Server, Kampagne über `file://`.
- Grafik/Sound: `sprite-generator/prompts.py` + `audio.py` → `gen generate`, `gen adopt --all` (Sprites), `gen adopt_scene bg_*` (Hintergründe als JPG),
`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,
@@ -115,6 +157,42 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
- Dev-Parameter: `index.html?title` (Titel ohne Intro), `?play` (Shop als Gast), `?fight=N` (Training gegen Liga-Gegner N), `&auto` (KI fährt
für dich), `&ff=30` (30 s vorspulen), `&cam=chase|fpv` (Kamera), `&uicheck` (Layout-Prüfung), `&touch` (Touch-Pad am PC zeigen).
## Qualitätsregeln (verbindlich, gelten für jede Änderung)
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.
1. **Erst Test, dann Code.** Jeder Bugfix beginnt mit einem Test, der den Fehler zeigt (rot), dann der Fix (grün).
Neue Logik (Spielregeln, Protokoll, Server, Wirtschaft) kommt nie ohne Test.
2. **Vor jedem „fertig“:** `npm run lint` und `npm test` ausführen und das Ergebnis nennen. Rot = nicht fertig.
Tests nie abschwächen, auskommentieren oder überspringen, um grün zu werden – Ursache beheben oder Michael fragen.
3. **Logik ohne DOM** in eigenen Dateien (wie `combat.js`), damit Node-Tests und Server sie nutzen. Client und
Server teilen dieselben Dateien (`parts/robot/combat/ai/protocol.js`) – **keine Kopien**.
4. **Online gilt: der Server entscheidet.** Kampfergebnis, Geld, Ruhm, Teilebesitz, Rangliste rechnet/prüft nur der
Server. Client-Werte sind Wünsche, nie Wahrheit. Jede eingehende Nachricht/jeder Request wird validiert
(Typ, Bereich, Größe, Berechtigung).
5. **Keine generischen Datenbank-Pfade** vom Client (kein `/db/<pfad>`, kein Firebase-Muster). Nur explizite
REST-Endpunkte und WS-Nachrichten aus `game/protocol.js`. Protokolländerung = `PROTOCOL_VERSION` erhöhen.
6. **Seat/Index-Spiegelung** nur an einer Stelle (`protocol.js`), mit Test. Nie im Spielcode verstreut.
7. **Kampagne bleibt offline:** nach jeder Änderung `game/index.html` per Doppelklick (`file://`) prüfen.
UI-Änderung → `&uicheck` laufen lassen. Änderung an UI, Netz, Lobby, Kampf oder Shop → zusätzlich `npm run e2e`
(deckt Online-Kampf und `file://`-Kampagne im echten Browser ab).
8. **Server-Änderungen** auf den Dev-Server (`roboclash.michael-media.de`, derzeit einziges Server-System, darf
per `npm run db:reset` zurückgesetzt werden) deployen und dort prüfen. Nie direkt auf dem Server Dateien
editieren – nur über das Deploy-Skript. Produktion kommt später als eigene Umgebung.
9. **Secrets** (`.env`, Schlüssel, Tokens, Service-Accounts) nie committen, nie in Logs, nie in Client-Code.
Passwörter gehören grundsätzlich nicht in den Code. *Einzige Ausnahme:* die Testkonten `michi`/`Michi2000!` und
`benni`/`Benni2000!` im Reset-Skript – reine Test-User, werden später ausgebaut (Plan, Abschnitt 10, T-1/T-4).
Keine weiteren Ausnahmen hinzufügen.
## Umgebung: Test-System, kein Prod
`roboclash.michael-media.de` ist ein **Test-/Dev-Server**. Es gibt **kein Produktionssystem** und keine echten
Spielerdaten – die DB darf jederzeit zurückgesetzt werden, Testkonten mit festen Passwörtern sind ok, keine
Produktions-Sperren oder Prod-Absicherungen einbauen. Das gilt, **bis Michael oder Benni ausdrücklich sagen, dass
es ein Produktionssystem gibt**. Dann zuerst Plan-Task **T-4** (Refactoring + Security-Check), erst danach Prod.
10. **Kleine Schritte:** eine Task pro Commit, keine Nebenbaustellen. Unklar → fragen statt raten.
## Arbeitsweise
- Antworten auf Deutsch, knapp. Code und Kommentare auf Englisch, Dokumentation für Michael auf Deutsch.
@@ -132,5 +210,20 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
- 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`).
Fehlt ein Bild oder Sound, läuft das Spiel mit prozeduraler Grafik / Synth-Sound weiter – nie abstürzen.
- Git nur lokal (kein Remote). Commit nur, wenn Michael es sagt.
- `admin/` liegt außerhalb `game/` und kommt **nicht** in den Release-Build. `admin/index.html` (Live-Steuerung:
Events, Nachricht, Sperren) liefert der Server unter `/admin/` aus; Speichern nur mit Admin-Konto (Server prüft).
- Git-Remote: Gitea (`origin`, `ssh://git@gitea.oezcan.cloud:32772/malkano.michael/Robot-Clash.git`).
**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
Benni es sagt.
- **Commit-Messages nach [Conventional Commits](https://www.conventionalcommits.org/):** `<typ>(<bereich>): <was>`,
Englisch, Imperativ, klein. Typen: `feat`, `fix`, `refactor`, `test`, `docs`, `chore`, `build`, `ci`, `perf`,
`style`. Bereiche z. B. `server`, `net`, `lobby`, `fight`, `shop`, `ui`, `deploy`. Task-ID aus dem Plan in
Klammern am Ende, z. B. `feat(server): add websocket hub (P1-2)`. Inkompatible Änderung (z. B. Protokoll,
Spielstand-Format): `!` nach dem Typ + Fußzeile `BREAKING CHANGE: …`.
- **Ohne Co-Author-/Claude-Zeilen:** kein `Co-Authored-By:`, kein „Generated with Claude Code“ o. ä.
- **Versionen nach [SemVer](https://semver.org/)** (`MAJOR.MINOR.PATCH`), sobald released wird: Git-Tag `vX.Y.Z` auf
`main`, Version in `package.json` (Root + `server/`) gleich halten. Bis zum ersten Prod-Release bleibt es bei
`0.y.z` (0.x = instabil). Ab `1.0.0`: `fix` → PATCH, `feat` → MINOR, `BREAKING CHANGE` → MAJOR. Ein Release erst
taggen, wenn Michael oder Benni es sagen.
- Release prüfen: `.\build.ps1 -Web`, dann `release\robotclash.html` per Doppelklick testen.

View File

@@ -23,7 +23,18 @@ Angelegt am 2026-11-13 aus `_Tools\Library` (Vorlage `webgame`). Sprachen: Engli
Dev-Parameter: `index.html?title` (Titel ohne Intro), `?play` (direkt in den Shop, als Gast), `?play&paint` (Lackiererei mit Testbild), `?fight=N` (Training gegen Liga-Gegner N = 0…7),
`&auto` (KI fährt deinen Roboter), `&ff=30` (30 Sekunden vorspulen), `&cam=chase|fpv` (Kamera).
Tests (Node, ohne Browser): `node tests/sim.test.js` · Balance-Zahlen: `node tests/balance.js -v`
Entwickeln (Node ≥ 22, im Repo-Root):
```
npm run setup # einmal: Abhängigkeiten (Root + server/)
npm test # alle Tests (Spiel-Logik + Server)
npm run lint # ESLint
npm run dev # Server + Spiel lokal auf http://localhost:8080 (vorher server/.env aus .env.example)
npm run balance # Balance-Zahlen
```
**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`.
## Aufbau
@@ -34,10 +45,12 @@ game/
shop.js Werkstatt-Shop (Teile kaufen/einbauen/verkaufen, Vergleich, Lack, Mechaniker)
looks.js Aussehen der Liga-Gegner (wie ihre Porträts)
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)
netfight.js Live-PvP-Synchronisation
profiles.js Konten: registrieren, einloggen, Gast (lokal, später Firebase)
netfight.js zeigt den vom Server gerechneten Live-Kampf
profiles.js lokale Konten für die Offline-Kampagne
parts.js Teilekatalog (Werte, Preise) ┐
robot.js Bauregeln + Kampfwerte aus Teilen │ ohne DOM,
combat.js Physik, Waffen, Fallen, Grube, Sieg │ laufen auch in Node
@@ -50,7 +63,8 @@ game/
tests/ sim.test.js, balance.js
launcher/ Windows-Fenster (WebView2) → RobotClash.exe
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
build-web.mjs → release/robotclash.html (alles in einer Datei)
build.ps1 → release/RobotClash.exe + robotclash.html + robotclash-web.zip
@@ -58,8 +72,8 @@ build.ps1 → release/RobotClash.exe + robotclash.html + robotclash-web.z
## Online (optional)
Rangliste läuft mit der Firebase-DB-URL allein. Für die Lobby + Live-PvP den Web-API-Key in
`game/game.js` (`NET_CFG.apiKey`) eintragen – Anleitung `docs/firebase/README.md`.
Online läuft über den eigenen Node-Server (`server/`, Details `server/README.md`, Deploy `server/deploy/README.md`).
Der Server rechnet die Live-Kämpfe und verwaltet Geld, Teile und Ruhm; über `file://` läuft nur die Kampagne.
## Release

362
admin/index.html Normal file
View File

@@ -0,0 +1,362 @@
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Robot Clash – Admin</title>
<!--
Robot Clash backend admin, served by the game server at /admin/ (e.g. https://roboclash.michael-media.de/admin/).
Saving needs an account with role 'admin' (seed accounts michi / benni, see server/scripts/reset-db.js) -
the server checks it, the page itself grants nothing. Writes the live settings every player reads (game/live.js).
-->
<style>
:root { --bg:#0b0e13; --panel:#161b22; --panel2:#1d232d; --line:#2d3442; --text:#e8ebf2; --dim:#8d95a8;
--accent:#ff7a1a; --good:#6dff9e; --warn:#ff5a4a; }
* { box-sizing:border-box; }
body { margin:0; background:var(--bg); color:var(--text); font:15px/1.4 "Segoe UI",system-ui,sans-serif; }
.wrap { max-width:820px; margin:0 auto; padding:24px 18px 60px; }
h1 { font-size:24px; margin:0 0 2px; color:var(--accent); letter-spacing:.03em; }
h1 small { color:var(--dim); font-size:13px; font-weight:normal; letter-spacing:0; }
h2 { font-size:15px; margin:22px 0 8px; color:var(--accent); border-bottom:1px solid var(--line); padding-bottom:5px; }
label { display:block; font-size:13px; color:var(--dim); margin:8px 0 3px; }
input[type=text], input[type=email], input[type=password], input[type=number], textarea, select {
width:100%; padding:8px 10px; background:#0b0e14; color:var(--text); border:1px solid var(--line);
border-radius:7px; font:inherit; }
textarea { min-height:52px; resize:vertical; }
input:focus, textarea:focus, select:focus { outline:none; border-color:var(--accent); }
.row { display:flex; gap:10px; flex-wrap:wrap; }
.row > div { flex:1; min-width:140px; }
button { font:inherit; color:var(--text); background:var(--panel2); border:1px solid var(--line);
border-radius:8px; padding:9px 16px; cursor:pointer; }
button:hover { border-color:var(--accent); }
button.primary { background:linear-gradient(#ff8f3a,#e8650a); color:#1a0c02; border-color:#ffa25a; font-weight:700; }
button.danger { border-color:#5a2e2e; color:var(--warn); }
.card { background:var(--panel); border:1px solid var(--line); border-radius:12px; padding:16px 18px; margin-bottom:14px; }
.hide { display:none; }
.muted { color:var(--dim); font-size:13px; }
.pill { display:inline-block; background:var(--panel2); border:1px solid var(--line); border-radius:6px;
padding:2px 8px; font-size:12px; font-variant-numeric:tabular-nums; }
.checks { display:grid; grid-template-columns:repeat(auto-fill,minmax(150px,1fr)); gap:4px 12px; margin-top:4px; }
.checks label { display:flex; align-items:center; gap:6px; margin:0; color:var(--text); font-size:13px; }
.checks input { width:auto; }
.status { margin-top:10px; font-size:13px; min-height:18px; }
.status.ok { color:var(--good); } .status.err { color:var(--warn); }
.chk { display:flex; align-items:center; gap:8px; margin:6px 0; }
.chk input { width:auto; }
pre { background:#0b0e14; border:1px solid var(--line); border-radius:7px; padding:10px; overflow:auto;
font-size:12px; color:var(--dim); max-height:220px; }
.bar { position:sticky; bottom:0; background:var(--bg); padding:12px 0 0; border-top:1px solid var(--line);
display:flex; gap:10px; flex-wrap:wrap; margin-top:16px; }
.preset { display:flex; align-items:center; gap:10px; background:var(--panel2); border:1px solid var(--line);
border-radius:8px; padding:8px 12px; margin-bottom:6px; }
.preset .pn { flex:1; font-weight:600; }
.preset .psub { color:var(--dim); font-size:12px; }
.preset button { padding:5px 11px; font-size:13px; }
</style>
</head>
<body>
<div class="wrap">
<h1>Robot Clash – Admin <small>steuert, was alle Spieler sehen</small></h1>
<!-- login -->
<div class="card" id="login">
<h2>Anmelden</h2>
<p class="muted">Mit einem Spielkonto, das auf dem Server Admin-Recht hat (z. B. michi oder benni).</p>
<div class="row">
<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>
<div class="bar"><button class="primary" id="bLogin">Anmelden</button></div>
<div class="status" id="loginMsg"></div>
</div>
<!-- panel -->
<div class="card hide" id="panel">
<h2>Angemeldet</h2>
<p class="muted">Konto <b id="who"></b> · UID <span class="pill" id="uid"></span>
<button id="bOut" style="padding:3px 10px;font-size:12px">Abmelden</button></p>
<p class="muted" id="uidHint"></p>
<h2>📣 Nachricht an alle (Titel + Lobby)</h2>
<div class="row">
<div><label>Deutsch</label><input type="text" id="motdDe" maxlength="120" placeholder="z. B. Turnier am Samstag 20 Uhr"></div>
<div><label>English</label><input type="text" id="motdEn" maxlength="120" placeholder="e.g. Tournament Saturday 8pm"></div>
</div>
<h2>🏆 Event (läuft automatisch im Zeitfenster)</h2>
<div class="chk"><input type="checkbox" id="evOn"><label for="evOn" style="margin:0">Event aktiv</label></div>
<div id="evBody">
<div class="row">
<div><label>Name (DE)</label><input type="text" id="evDe" maxlength="60"></div>
<div><label>Name (EN)</label><input type="text" id="evEn" maxlength="60"></div>
</div>
<div class="row">
<div><label>Von</label><input type="datetime-local" id="evFrom"></div>
<div><label>Bis</label><input type="datetime-local" id="evTo"></div>
</div>
<div class="row">
<div><label>Preisgeld ×</label><input type="number" id="evMul" min="0.5" max="5" step="0.5" value="1"></div>
<div><label>Klasse erzwingen</label><select id="evCls"></select></div>
<div><label>Arena erzwingen</label><select id="evArena"></select></div>
</div>
<div class="chk"><input type="checkbox" id="evTour"><label for="evTour" style="margin:0">Turnier freischalten (ohne Startgeld)</label></div>
</div>
<h2>💾 Gespeicherte Events (Bibliothek)</h2>
<p class="muted">Vorlage aus dem Formular oben speichern, später mit einem Klick wieder aktivieren.
„Aktivieren“ setzt das Zeitfenster neu (ab jetzt + Dauer).</p>
<div class="row">
<div><label>Vorlage-Name</label><input type="text" id="presetName" maxlength="40" placeholder="z. B. Schwergewichts-Wochenende"></div>
<div><label>Dauer beim Aktivieren (Stunden)</label><input type="number" id="presetHours" min="1" max="720" value="48"></div>
</div>
<div class="bar" style="position:static;border:none;padding:0;margin:8px 0 0">
<button id="bPresetSave">Vorlage speichern</button>
<button id="bEvOff" class="danger">Laufendes Event stoppen</button>
</div>
<div id="presetList" style="margin-top:10px"></div>
<h2>🔓 Freischaltung (leer = alles frei)</h2>
<p class="muted">Nur Angehaktes ist im Shop verfügbar. Nichts angehakt = keine Sperre.</p>
<details><summary class="muted" style="cursor:pointer">Teile</summary><div class="checks" id="ckParts"></div></details>
<details><summary class="muted" style="cursor:pointer;margin-top:6px">Arenen</summary><div class="checks" id="ckArenas"></div></details>
<details><summary class="muted" style="cursor:pointer;margin-top:6px">Klassen</summary><div class="checks" id="ckClasses"></div></details>
<h2>🛠 Betrieb</h2>
<div class="chk"><input type="checkbox" id="tourOn"><label for="tourOn" style="margin:0"><b>Turnier für alle öffnen</b> (gratis Teilnahme; aus = Turnier ausgeblendet)</label></div>
<div class="chk"><input type="checkbox" id="offOn"><label for="offOn" style="margin:0">Online-Modus abschalten (alle in die Kampagne)</label></div>
<label>Mindest-Build (ältere Dateien bekommen „bitte neu laden“) – leer lassen, wenn egal</label>
<input type="text" id="buildMin" placeholder="z. B. 20261115.2223">
<div class="bar">
<button class="primary" id="bSave">Speichern (für alle sofort)</button>
<button id="bReload">Vom Server laden</button>
<button class="danger" id="bClear">Alles löschen</button>
</div>
<div class="status" id="saveMsg"></div>
<h2>Aktueller Serverstand</h2>
<pre id="dump">–</pre>
</div>
</div>
<script src="/kit/kit-core.js"></script>
<script src="/kit/kit-scores.js"></script>
<script src="/parts.js"></script>
<script src="/robot.js"></script>
<script src="/combat.js"></script>
<script src="/protocol.js"></script>
<script src="/net.js"></script>
<script>
(function () {
'use strict';
var RC = window.RC, Kit = window.Kit;
var net = RC.Net({ serverUrl: '' }); // same origin: the page is served by the game server
// 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); };
// ---- build the pick lists from the real game data ----
function opt(sel, items, label) {
sel.innerHTML = '<option value="">–</option>' + items.map(function (x) {
return '<option value="' + x.id + '">' + label(x) + '</option>'; }).join('');
}
opt($('evCls'), RC.CLASSES, function (c) { return c.id + ' (≤' + c.max + ' kg)'; });
opt($('evArena'), RC.ARENAS, function (a) { return a.name; });
function checks(box, items, label) {
box.innerHTML = items.map(function (x) {
return '<label><input type="checkbox" value="' + x.id + '"> ' + label(x) + '</label>'; }).join('');
}
checks($('ckParts'), RC.PART_LIST, function (p) { return p.name + ' (' + p.slot + ')'; });
checks($('ckArenas'), RC.ARENAS, function (a) { return a.name; });
checks($('ckClasses'), RC.CLASSES, function (c) { return c.id; });
function getChecks(box) {
return Array.prototype.slice.call(box.querySelectorAll('input:checked')).map(function (i) { return i.value; });
}
function setChecks(box, ids) {
ids = ids || [];
Array.prototype.forEach.call(box.querySelectorAll('input'), function (i) { i.checked = ids.indexOf(i.value) >= 0; });
}
// datetime-local <-> ms
function toLocal(ms) {
if (!ms) return '';
var d = new Date(ms - new Date().getTimezoneOffset() * 60000);
return d.toISOString().slice(0, 16);
}
function fromLocal(v) { return v ? new Date(v).getTime() : 0; }
// ---- login ----
function showPanel(acc) {
$('login').classList.add('hide');
$('panel').classList.remove('hide');
$('who').textContent = acc.email || acc.name;
$('uid').textContent = acc.uid;
$('uidHint').textContent = net.auth.current && net.auth.current.admin ? 'Admin-Recht: ja.' : 'Kein Admin-Recht - Speichern wird vom Server abgelehnt.';
loadLive();
loadPresets();
}
$('bLogin').onclick = function () {
var msg = $('loginMsg'); msg.className = 'status'; msg.textContent = 'Anmelden…';
net.auth.login($('mail').value.trim(), $('pass').value).then(function (r) {
if (r.ok) { showPanel(net.auth.current); }
else { msg.className = 'status err'; msg.textContent = 'Fehlgeschlagen: ' + (r.error || 'unbekannt'); }
});
};
$('pass').addEventListener('keydown', function (e) { if (e.key === 'Enter') $('bLogin').click(); });
$('bOut').onclick = function () { net.auth.logout(); location.reload(); };
// ---- read current /live into the form ----
function fill(d) {
d = d || {};
var m = d.motd || {}; $('motdDe').value = m.de || ''; $('motdEn').value = m.en || '';
var e = d.event || {};
$('evOn').checked = !!d.event;
var en = e.name || {};
$('evDe').value = en.de || ''; $('evEn').value = en.en || '';
$('evFrom').value = toLocal(e.from); $('evTo').value = toLocal(e.to);
$('evMul').value = e.prizeMul || 1;
$('evCls').value = e.cls || ''; $('evArena').value = e.arena || '';
$('evTour').checked = !!e.tournament;
var u = d.unlock || {};
setChecks($('ckParts'), u.parts); setChecks($('ckArenas'), u.arenas); setChecks($('ckClasses'), u.classes);
var f = d.flags || {};
$('offOn').checked = !!f.onlineOff;
$('tourOn').checked = !!f.tournament;
$('buildMin').value = (d.build && d.build.min) || '';
$('dump').textContent = JSON.stringify(d, null, 2);
toggleEv();
}
function toggleEv() { $('evBody').style.opacity = $('evOn').checked ? '1' : '.4'; }
$('evOn').onchange = toggleEv;
function loadLive() {
db.get('live').then(function (d) { fill(d || {}); });
}
$('bReload').onclick = loadLive;
// ---- collect the form into the /live object ----
function collect() {
var out = {};
var mde = $('motdDe').value.trim(), men = $('motdEn').value.trim();
if (mde || men) out.motd = { de: mde, en: men };
if ($('evOn').checked) {
var ev = { id: 'ev' + Date.now().toString(36), type: 'event',
name: { de: $('evDe').value.trim(), en: $('evEn').value.trim() },
from: fromLocal($('evFrom').value), to: fromLocal($('evTo').value),
prizeMul: parseFloat($('evMul').value) || 1, tournament: $('evTour').checked };
if ($('evCls').value) ev.cls = $('evCls').value;
if ($('evArena').value) ev.arena = $('evArena').value;
out.event = ev;
}
var parts = getChecks($('ckParts')), arenas = getChecks($('ckArenas')), classes = getChecks($('ckClasses'));
if (parts.length || arenas.length || classes.length) out.unlock = { parts: parts, arenas: arenas, classes: classes };
var flags = {};
if ($('offOn').checked) flags.onlineOff = true;
if ($('tourOn').checked) flags.tournament = true;
if (Object.keys(flags).length) out.flags = flags;
var bmin = $('buildMin').value.trim();
if (bmin) out.build = { min: bmin };
return out;
}
$('bSave').onclick = function () {
var data = collect(), msg = $('saveMsg');
msg.className = 'status'; msg.textContent = 'Speichern…';
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); }
else { msg.className = 'status err'; msg.textContent = 'Abgelehnt. Hat dein Konto Admin-Recht?'; }
});
};
$('bClear').onclick = function () {
if (!confirm('Wirklich alles zurücksetzen? Danach läuft kein Event, keine Nachricht, keine Sperre.')) return;
db.put('live', {}).then(function (ok) {
var msg = $('saveMsg');
msg.className = ok ? 'status ok' : 'status err';
msg.textContent = ok ? 'Zurückgesetzt.' : 'Abgelehnt.';
if (ok) fill({});
});
};
// ---- event library (/admin/events) ----
// read just the event part of the current form into a reusable preset
function eventFromForm() {
return {
name: { de: $('evDe').value.trim(), en: $('evEn').value.trim() },
prizeMul: parseFloat($('evMul').value) || 1,
cls: $('evCls').value || '', arena: $('evArena').value || '',
tournament: $('evTour').checked,
};
}
// put a preset back into the event form
function presetToForm(ev, hours) {
$('evOn').checked = true; toggleEv();
var n = ev.name || {}; $('evDe').value = n.de || ''; $('evEn').value = n.en || '';
$('evMul').value = ev.prizeMul || 1; $('evCls').value = ev.cls || ''; $('evArena').value = ev.arena || '';
$('evTour').checked = !!ev.tournament;
var from = Date.now(), to = from + (hours || 48) * 3600000;
$('evFrom').value = toLocal(from); $('evTo').value = toLocal(to);
}
function loadPresets() {
db.get('admin/events').then(function (m) { renderPresets(m || {}); });
}
function renderPresets(m) {
var box = $('presetList'), keys = Object.keys(m);
if (!keys.length) { box.innerHTML = '<p class="muted">Noch keine Vorlagen gespeichert.</p>'; return; }
box.innerHTML = keys.map(function (k) {
var p = m[k] || {}, ev = p.event || {}, nm = (ev.name && (ev.name.de || ev.name.en)) || p.name || '(ohne Name)';
var sub = 'Preisgeld x' + (ev.prizeMul || 1) + (ev.tournament ? ' · Turnier' : '') +
(ev.cls ? ' · ' + ev.cls : '') + (ev.arena ? ' · ' + ev.arena : '') + ' · ' + (p.hours || 48) + ' h';
return '<div class="preset" data-k="' + k + '"><div><div class="pn">' + esc(p.name || nm) +
'</div><div class="psub">' + esc(sub) + '</div></div>' +
'<button class="primary" data-act="on">Aktivieren</button>' +
'<button data-act="load">Laden</button>' +
'<button class="danger" data-act="del">Löschen</button></div>';
}).join('');
Array.prototype.forEach.call(box.querySelectorAll('.preset'), function (row) {
var k = row.dataset.k, p = m[k];
row.querySelector('[data-act="load"]').onclick = function () { presetToForm(p.event || {}, p.hours); };
row.querySelector('[data-act="on"]').onclick = function () { activatePreset(p); };
row.querySelector('[data-act="del"]').onclick = function () {
if (!confirm('Vorlage „' + (p.name || '') + '“ löschen?')) return;
db.del('admin/events/' + k).then(loadPresets);
};
});
}
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]; }); }
// activate: load the preset into the form, set a fresh window, then publish the whole /live
function activatePreset(p) {
presetToForm(p.event || {}, p.hours);
$('bSave').click();
}
$('bPresetSave').onclick = function () {
var name = $('presetName').value.trim();
if (!name) { alert('Bitte einen Vorlage-Namen eingeben.'); return; }
var preset = { name: name, hours: parseInt($('presetHours').value, 10) || 48, event: eventFromForm() };
db.push('admin/events', preset).then(function (key) {
$('presetName').value = '';
var msg = $('saveMsg'); msg.className = key ? 'status ok' : 'status err';
msg.textContent = key ? 'Vorlage gespeichert.' : 'Vorlage abgelehnt – hat dein Konto Admin-Recht?';
loadPresets();
});
};
// stop the running event without touching motd / unlocks / flags
$('bEvOff').onclick = function () {
$('evOn').checked = false; toggleEv();
$('bSave').click();
};
// already signed in from a previous visit?
if (net.auth.resume && net.auth.resume() && net.auth.current) showPanel(net.auth.current);
})();
</script>
</body>
</html>

View File

@@ -65,10 +65,13 @@ for (const [token, tag] of await Promise.all(scriptJobs)) html = html.replace(to
html = html.replace(/url\((['"]?)(assets\/[^'")]+)\1\)/g, (m, q, p) => (assets[p] ? `url('${assets[p]}')` : m));
html = html.replace(/(src|href)="(assets\/[^"]+)"/g, (m, a, p) => (assets[p] ? `${a}="${assets[p]}"` : m));
// everything the scripts load at runtime: must come before the first other <script>
html = html.replace('<script>', () => `<script>window.KIT_ASSETS = ${JSON.stringify(assets)};</script>\n<script>`);
// build stamp: identifies this exact release, so a leaked copy can be traced back
const BUILD = new Date().toISOString().slice(0, 16).replace('T', '.').replace(/[:-]/g, '');
html = html.replace('<script>', () => `<script>window.RC_BUILD = ${JSON.stringify(BUILD)};window.KIT_ASSETS = ${JSON.stringify(assets)};</script>\n<script>`);
html = html.replace('<head>', () => '<head><!-- Robot Clash (c) 2026 Michael Media | https://michael-media.de | build ' + BUILD + ' | Alle Rechte vorbehalten. Weitergabe oder Neuveroeffentlichung dieser Datei ist nicht gestattet. -->');
const out = path.join(root, 'release', 'robotclash.html');
fs.mkdirSync(path.dirname(out), { recursive: true });
fs.writeFileSync(out, html);
const mb = n => (n / 1024 / 1024).toFixed(1);
console.log(`Fertig: ${out} (${mb(fs.statSync(out).size)} MB, ${Object.keys(assets).length} Assets, ${mb(bytes)} MB roh)`);
console.log(`Fertig: ${out} (${mb(fs.statSync(out).size)} MB, ${Object.keys(assets).length} Assets, ${mb(bytes)} MB roh, Build ${BUILD})`);

368
docs/MULTIPLAYER-PLAN.md Normal file
View File

@@ -0,0 +1,368 @@
# Robot Clash – Plan: echter Multiplayer, Test-System, Deployment
> **Für Claude (Arbeitsauftrag):** Dieses Dokument ist die verbindliche Aufgabenliste für den Umbau.
> Arbeite die Phasen **der Reihe nach** ab, jede Task einzeln (Task-ID im Commit nennen, z. B. `P1-3`).
> Eine Task ist erst fertig, wenn ihre **Akzeptanzkriterien** erfüllt und `npm test` grün ist.
> Unklarheiten → Michael fragen, nicht raten. Die Regeln aus `CLAUDE.md` → „Qualitätsregeln“ gelten immer.
> Hake erledigte Tasks hier ab (`[x]`), damit der Stand im Repo sichtbar bleibt.
Stand der Analyse: 2026-11-19 (Commit `347701d`).
## Umsetzungsstand (2026-11-19)
**Erledigt:** Phase 0, Phase 1, Phase 2 (außer P2-6), aus Phase 3: P3-1b, P3-2, P3-3 (+ Teile von P3-1), aus Phase 4:
Smoke-Test (`npm run smoke -- <url>`, Vorstufe von P4-1), P4-2 Playwright (9 Browser-Tests, `npm run e2e`),
P4-5 `game.js` aufgeteilt (1996 → ~1380 Zeilen + `sfx.js`, `pages.js`, `online.js`, `workshop.js`). **Live** auf `https://roboclash.michael-media.de` (Dev).
Geprüft: 46 automatische Tests, Smoke-Test gegen den Dev-Server (WebSocket über Caddy/TLS, 20 Snapshots/s,
gespiegeltes Ergebnis), zwei Browser-Tabs michi gegen benni lokal (Kampf, Ergebnis, Belohnung, Hintergrund-Tab),
Shop-Kauf landet in der Server-DB, Kampagne offline über `file://` (headless + `&uicheck`).
**Abweichungen vom ursprünglichen Plan (bewusst):**
- Online-Spielstand = **ein JSON-Dokument pro Spieler** (`online_saves`) statt Tabellen `inventory`/`robots`.
Konsistenz kommt daher, dass nur `RC.Eco` (`game/eco.js`) und Kampfbelohnungen es ändern – dieselben Regeln wie
im Client. Einfacher und ohne doppelte Regeln; bei Bedarf später normalisieren.
- Erfolge (zahlen Credits) werden online **vom Server** vergeben (`server/economy.js` → `RC.Progress`).
- Starter-Teile verkaufen sich für 0 Credits (sonst Geld-Exploit über „neuer Roboter → Teile verkaufen“).
- Online-Turnier (`netourney.js`, P2P über die alte DB) entfernt → kommt mit **P2-6** server-seitig zurück.
- Admin-Seite läuft jetzt unter `/admin/` auf dem Server; `admin/cleanup.js`/`setcoins.js` (Firebase) gelöscht.
**Offen / nächste Schritte:** P2-6 (Online-Turnier), P3-1 Rest (SSH-Nutzer `deploy`, Passwort-Login aus), P3-5
(Logs/Monitoring), P3-6 (Gitea Actions + act_runner), P4-3 Lasttest (Bot ist da: mehrere `npm run bot` parallel),
P4-4 Vorhersage (erst nach Spieltest), `tests/sim.test.js:442` (halber Test).
Hinweis: Der Smoke-Test legt Gastkonten an (`SmokeA`/`SmokeB`), die in der Rangliste auftauchen können →
`--reset-db` beim Deploy räumt auf.
---
## 1. Warum der Umbau (Kurzfassung der Analyse)
Der jetzige Online-Modus ahmt Firebase nach: eine generische JSON-Datenbank (`/db/<pfad>.json`, SQLite) mit
SSE-Push. Live-PvP läuft darüber: **der Browser mit der kleineren uid ist Host**, rechnet den Kampf und schickt
15× pro Sekunde einen HTTP-PUT mit dem ganzen Zustand; der Server schreibt ihn in SQLite und streamt ihn an den Gast.
Daraus folgende, im Code bestätigte Fehler:
| # | Fehler | Stelle |
|---|---|---|
| 1 | Ergebnis beim Gast nicht gespiegelt (`winner` in Host-Reihenfolge) → beide sehen „Sieg“, beide kassieren, im Turnier melden beide sich als Sieger | `game/netfight.js:113`, `game/game.js:1684` |
| 2 | `dealt`/`taken` fehlen im Snapshot → Gast ohne Schadensbonus, Zeit-Entscheid falsch | `game/netfight.js:22` |
| 3 | Host-Tab im Hintergrund → `Kit.loop` pausiert → Kampf friert ein (zwei Tabs testen = geht nie) | `game/kit/kit-loop.js:28` |
| 4 | Host weg → Gast rechnet nichts, Kampf endet nie | `game/netfight.js:49` |
| 5 | Token-Refresh-Race: zwei parallele Refreshes mit rotierendem Token → zufälliges Ausloggen, Tabs loggen sich gegenseitig aus | `game/net.js:56-104`, `server/auth.js:51` |
| 6 | Lobby vergleicht Client-Uhr mit Server-Zeitstempel (12 s) → bei Uhrabweichung „alle offline“ | `game/lobby.js:47,56` |
| 7 | 4–7 SSE-Streams pro Spieler → HTTP/1.1-Limit (6) lokal erreicht, Requests hängen | lokal |
| 8 | Caddy `encode gzip` vor SSE kann Events puffern | `server/deploy/setup.sh:66` |
| 9 | Jeder Snapshot = SQLite-Write mit `LIKE`-Full-Scan | `server/db.js:68-74` |
| 10 | `.env` wird lokal nicht geladen, `npm test` zeigt ins Leere | `server/app.js`, `server/package.json` |
| S | `tourney` darf jeder komplett löschen; Geld/Ruhm/Rangliste rechnet der Client; Dienst läuft als root | `server/rules.js:28`, `game/game.js:1786ff` |
**Grundursache:** Datenbank als Echtzeit-Transport + Autorität im Browser. Einzelfixes lohnen nicht – der
Unterbau wird ersetzt.
---
## 2. Entscheidungen (verbindlich)
| Thema | Entscheidung | Begründung |
|---|---|---|
| Netz-Modell | **Server-autoritativ.** Der Server rechnet jeden Online-Kampf mit `RC.Combat.step`; Clients senden nur Eingaben und zeigen Snapshots. | `combat.js` läuft schon in Node. Löst Fehler 1–4, 9 und Cheating auf einmal. Ein 2-min-Kampf kostet wenige ms CPU. |
| Transport | **WebSocket** (Paket `ws`) auf demselben Node-Server, gleiche Domain, Pfad `/ws`. | Ein Kanal pro Spieler statt 7 Streams, niedrige Latenz, Caddy proxyt WS ohne Zusatzkonfig. |
| P2P / WebRTC | **Nein.** | Braucht TURN-Server, ein Peer wäre wieder Autorität, Validierung nur nachträglich. Kein Gewinn bei 1v1. |
| Firebase | **Komplett entfernen** (Code, Doku, Admin-Skripte, Tests, altes Firebase-Projekt abschalten). | Wird nicht mehr genutzt, verwirrt nur. |
| Generische `/db`-Fassade | **Entfernen.** Ersetzt durch explizite REST-Endpunkte mit Schema-Prüfung. | Pfad-Regeln sind unprüfbar und unsicher. |
| Wirtschaft (Online-Modus) | **Server-autoritativ:** Geld, Ruhm, Teilebesitz, Shop, Kampfbelohnungen, Rangliste rechnet/prüft der Server. *(bestätigt)* | Sonst ist die Rangliste wertlos. |
| Kampagne (offline) | Bleibt **rein lokal** und ohne Server spielbar: `game/index.html` direkt im Browser öffnen (`file://`, klassische Skripte, keine ES-Module, kein `fetch` auf lokale Dateien). *(bestätigt)* | Bestehende Regel aus CLAUDE.md; auch Grundlage für den exe-Launcher. |
| Bestandsdaten | **Keine Migration.** Die DB wird über ein Init-Skript frisch aufgesetzt (Schema + Seed-Konten Michi und Benni). *(bestätigt)* | Es gibt noch keine echten Spielerdaten. |
| Umgebungen | Vorerst **nur ein Server-System = Dev** (`roboclash.michael-media.de`). Produktion kommt später als zweite Umgebung. *(bestätigt)* | Noch keine echten Spieler. |
| Gemeinsame Logik | `parts.js`, `robot.js`, `combat.js`, `ai.js` + neu `protocol.js` bleiben in `game/` als UMD-Skripte und werden vom Server per `require` geladen. **Keine Kopien.** | Eine Wahrheit für Client und Server, kein Build-Schritt nötig. |
| Datenbank | SQLite (better-sqlite3) mit **richtigen Tabellen** (users, wallets, inventory, saves, matches, ranks). Keine Writes im Kampf-Takt. | Reicht für die Größenordnung, einfach zu sichern. |
---
## 3. Voraussetzungen
- [x] **SSH-Zugang** zur Hetzner-VM: `ssh root@roboclash.michael-media.de` (per Schlüssel). Später (P3-1) eigener
Nutzer `deploy` statt root.
- [x] **DNS:** `roboclash.michael-media.de` zeigt auf die VM (= Dev-System).
- [x] **Git-Remote:** Gitea `ssh://git@gitea.oezcan.cloud:32772/malkano.michael/Robot-Clash.git` (`origin`, Branch `main`).
CI später über **Gitea Actions** (braucht einen `act_runner`, siehe P3-6).
- [ ] **Secrets** (nie ins Repo): `JWT_SECRET` (wird beim Setup zufällig erzeugt), später im CI: `DEPLOY_SSH_KEY`,
`DEPLOY_HOST`. *Ausnahme in der Dev-Phase:* die festen Testpasswörter der Seed-Konten (P2-1b) stehen bewusst
im Code – wird nach dem Umbau ersetzt (Abschnitt 10).
- [ ] *Später, vor Produktion:* Hetzner-Backups/Snapshots aktivieren.
- [ ] *Optional:* altes Firebase-Projekt `robot-clash-aa37b` in der Firebase-Konsole löschen (Repo ist privat, daher
nicht dringend). Der **Code** wird in jedem Fall von Firebase befreit (P1-8).
---
## 4. Zielarchitektur
```
Browser (game/index.html, klassische Skripte)
├─ REST /api/* Auth, Profil, Spielstand, Shop, Wallet, Rangliste
└─ WS /ws Lobby/Präsenz, Herausforderungen, Live-Kampf
│
Caddy (TLS, HTTP/2) ──► Node-Dienst (je Umgebung eigener Port + eigene DB)
├─ http/express REST + statisches Spiel
├─ ws/hub Verbindungen, Auth, Routing
├─ lobby Präsenz = offene Verbindung, Challenges im Speicher
├─ match/room ein Raum pro Kampf, 60-Hz-Tick, RC.Combat.step
├─ economy Belohnungen, Shop, Wallet (Transaktionen)
└─ db (SQLite) Tabellen, Migrationen
```
### 4.1 Protokoll (`game/protocol.js`, gemeinsam für Client + Server)
JSON-Nachrichten `{ t: '<typ>', ... }`. `PROTOCOL_VERSION` als Zahl; der Server lehnt alte Clients mit
`{ t:'error', code:'OUTDATED' }` ab, der Client zeigt dann „Bitte neu laden“.
| Richtung | Typ | Inhalt |
|---|---|---|
| C→S | `hello` | `{ v, token }`; erste Nachricht, sonst Verbindung zu |
| S→C | `welcome` | `{ uid, name, serverTime }` |
| S→C | `lobby` | vollständige Liste beim Eintritt, danach `lobby.join` / `lobby.leave` / `lobby.state` |
| C→S | `challenge` / `challenge.cancel` | `{ to }` |
| S→C | `challenge.in` / `challenge.gone` | `{ from, name, flag }` |
| C→S | `challenge.accept` / `challenge.decline` | `{ from }` |
| S→C | `match.start` | `{ matchId, seat (0/1), seed, arena, robots:[{name,build,paint}], startsAt }` |
| C→S | `input` | `{ seq, throttle, turn, fire, fire2, fire3 }`, bei Änderung, mindestens alle 250 ms |
| S→C | `snap` | `{ tick, ack (letzte input-seq), state }` mit 20 Hz, Reihenfolge immer `[seat0, seat1]` |
| S→C | `match.end` | `{ result:{winner (seat), reason}, rewards:{money, fame, lines[]}, wallet }` |
| C↔S | `ping` / `pong` | Latenzanzeige, Keepalive alle 5 s |
**Regel:** Der Client mappt Seats selbst (`seat` aus `match.start`) – Index-Spiegelung passiert **an genau einer
Stelle** (`protocol.js`, `toLocal()`), mit Test.
### 4.2 Match-Raum (Server)
- Fester Takt 60 Hz (`setInterval` mit Drift-Ausgleich), Snapshot jede 3. Tick (20 Hz).
- Eingaben werden validiert (Zahlenbereiche, Typen) und gelten ab dem nächsten Tick; fehlt Input → letzter bekannter.
- **Verbindungsabbruch:** 10 s Gnadenfrist (Roboter steht), dann übernimmt die KI; nach Kampfende normal werten.
Reconnect mit gleichem Token → zurück in den Raum.
- Builds werden beim Start geprüft: `RC.validate(build)`, Gewichtsklasse, und **gehört dem Spieler jedes Teil?**
(Inventar aus der DB).
- Ergebnis + Belohnung berechnet ausschließlich der Server, Buchung in **einer** SQLite-Transaktion, dann `match.end`.
- Match-Protokoll (Seed, Builds, Ergebnis, Dauer) in Tabelle `matches` – für Support und Replays später.
### 4.3 Client
- `game/net.js` neu: REST-Helfer + **eine** WS-Verbindung mit Auto-Reconnect, Token-Refresh **single-flight**
(eine laufende Refresh-Promise, alle warten darauf).
- `game/netfight.js` neu: rechnet nichts. Interpoliert zwischen den zwei letzten Snapshots (~100 ms Puffer).
Optional später: Vorhersage für den eigenen Roboter.
- Online-Kampf läuft weiter, wenn der Tab im Hintergrund ist (Server rechnet; Client holt beim Zurückkommen auf).
---
## 5. Umgebungen
| Umgebung | URL | Dienst | Port | Daten | Zweck |
|---|---|---|---|---|---|
| lokal | `http://localhost:8080` | `npm run dev` | 8080 | `server/data.dev.sqlite` | Entwickeln, Tests |
| **Dev (jetzt)** | `https://roboclash.michael-media.de` | `robotclash` | 8080 | `/opt/robotclash/data.sqlite` | Gemeinsames Test-System für Michi + Benni; darf jederzeit zurückgesetzt werden |
| Produktion (später) | eigene Subdomain, z. B. `play.michael-media.de` | `robotclash-prod` | 8081 | eigener Ordner + DB | erst wenn echte Spieler kommen |
Deploy-Skript und Ordnerstruktur von Anfang an mit Umgebungsnamen (`dev`, später `prod`) bauen, damit Produktion nur
eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
---
## 6. Phasen und Tasks
### Phase 0 – Fundament (Repo, Tests, Regeln) ⟶ *zuerst*
- [x] **P0-1 Git-Ablauf.** Kein Branch-Workflow: Michi und Benni arbeiten im Pair Programming und committen **direkt
auf `main`** (= Dev). Branches nur für echte Experimente, die evtl. verworfen werden. Keine PRs, keine Merges.
*AK:* CLAUDE.md beschreibt den Ablauf.
- [x] **P0-2 Ein Test-Kommando.** `npm test` (Root) = `node --test` über `tests/**/*.test.js` + `server/test/**/*.test.js`;
`npm run balance` für die Balance-Zahlen (kein Test, nur Ausgabe). `tests/online.test.js` (Firebase) gelöscht.
Einmalig `npm run setup` (installiert Root + `server/`). Versionen auf `0.1.0` (SemVer, 0.x bis Prod).
- [x] **P0-3 Server lokal startbar.** `npm run dev` (Root oder `server/`) = `node --env-file=.env --watch app.js`.
Ohne `JWT_SECRET` nimmt der Server ein zufälliges Secret pro Start (kein bekannter Fallback-String mehr).
`GET /healthz` → `{ ok, version, commit, uptime }`; `app.js` exportiert `{ app, listen }` für Tests.
Erste Server-Tests: `server/test/health.test.js` (Health, Register/Login, Refresh-Rotation, falsches Passwort).
- [x] **P0-4 Lint.** ESLint 9 (flat config `eslint.config.js`, nur `recommended`, keine Stilregeln), `npm run lint`:
0 Fehler. **Bewusst kein Prettier** – ein Massen-Reformat würde den kompakten Stil zerstören und jede Zeile im
Diff ändern. Ignoriert: `game/vendor`, `game/kit` (Library-Kopie), `admin/` (fliegt in P1-8 raus).
Toten Code entfernt. Zwei Warnungen bleiben absichtlich: `scores` in `game.js` (Firebase-Rest → P1-8) und
`bye` in `tests/sim.test.js:442` – **halbfertiger Test** (Wert berechnet, nie geprüft) → beim nächsten Anfassen
der Turnier-Logik eine echte Prüfung ergänzen. `.gitattributes`: `*.sh` immer LF (sonst bricht `setup.sh` unter Linux).
- [x] **P0-5 Qualitätsregeln in `CLAUDE.md`** inkl. Conventional Commits, SemVer, Test-System-Hinweis.
- [x] **P0-6 Doku.** README verlinkt diesen Plan und die neuen Kommandos. Firebase-Texte in README/CLAUDE.md sind als
veraltet markiert und werden mit dem Code in P1-8 entfernt.
### Phase 1 – Server-autoritativer Kampf über WebSocket
- [x] **P1-1 `game/protocol.js`** (UMD, ohne DOM): Typkonstanten, `PROTOCOL_VERSION`, Validierer je Nachricht
(`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.
- [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).
Eine Verbindung pro uid (neue ersetzt alte). *AK:* Integrationstest: ohne Token → zu; mit Token → `welcome`.
- [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 →
genau ein Ergebnis, kein NaN, Ergebnis aus Sicht beider Seats konsistent (Gewinner A ⇔ Verlierer B).
- [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.
*AK:* Integrationstest mit 3 Clients: Liste, Challenge, Decline, Accept → `match.start` an beide.
- [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
Parallelität loggt nicht aus.
- [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
(oder Playwright, P4-2) spielen einen Kampf; beide sehen dasselbe Ergebnis aus ihrer Sicht.
- **BEFUND 2026-11-19 (Michi laggt, Benni nicht):** `netfight.js` hat **keinen Jitter-Puffer** umgesetzt – es
zog den lokalen Zustand nur zum *neuesten* Snapshot (`k = dt*14`), nicht wie hier geplant „zwischen den zwei
letzten Snapshots (~100 ms Puffer)" (Zeile 151). Bei ungleichmäßiger Snapshot-Ankunft (Jitter/Bufferbloat,
auch über Kabel) bremst der Roboter und springt dann → F3 meldet `jitter`/`late`. Benni (gleichmäßige Leitung)
merkt nichts. **Fix (P4-x):** echte Entity-Interpolation mit ~100 ms Puffer; Render bei `now - INTERP_DELAY`
zwischen den zwei umgebenden Snapshots. **Reproduzierbar:** Dev-Param `?netlag=<basis>,<jitter>` verzögert
eingehende Snapshots geseedet; Node-Test `tests/netfight.test.js` (reine Interp-Mathe) + Playwright-Test misst
die Positions-Sprünge mit/ohne `netlag`. Erkenntnis für Benni: das Springen war ein Client-Interp-Problem,
kein Server-/Leitungsproblem.
- [x] **P1-7 Disconnect/Reconnect:** Gnadenfrist, KI-Übernahme, Wiederverbinden. *AK:* Test trennt einen Client
mitten im Kampf; Kampf endet trotzdem mit Ergebnis; Reconnect innerhalb 10 s übernimmt wieder.
- [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
(`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)
- [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)`,
`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.
- [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,
Starter-Roboter). **Dev-Phase: feste Testzugänge, bewusst ohne E-Mail und ohne `.env`** – direkt im Skript als
Konstante `DEV_SEED_USERS`:
| Login-Name | Passwort | Rolle |
|---|---|---|
| `michi` | `Michi2000!` | Admin |
| `benni` | `Benni2000!` | Admin |
Dafür bekommt `users` eine eindeutige Spalte `username` (case-insensitive), **E-Mail wird optional**, und
`POST /api/auth/login` akzeptiert `{ login, pass }` mit Name **oder** E-Mail; das Login-Formular im Client fragt
entsprechend „Name oder E-Mail“. Registrierung neuer Konten per Name + Passwort (E-Mail-Feld optional).
Keine Produktions-Sperre nötig – es gibt nur das Test-System (siehe CLAUDE.md). Ersetzt das manuelle Eintragen
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
einloggen und sehen das Dev-Menü.
- [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/ranks`. Preise kommen aus `RC.PARTS` (Server), nie vom Client. *AK:* Tests: zu wenig Geld → 409,
fremdes Teil einbauen → 400, Verkauf 50 %.
- [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.
- [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.
- [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.
- [ ] **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.)*
### Phase 3 – Server und Deployment (Dev-System)
- [ ] **P3-1 Server härten (einmalig, per Skript `server/deploy/setup.sh` erweitern):** Nutzer `robotclash` (Dienst)
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.
*AK:* `ssh deploy@roboclash.michael-media.de` per Key geht, Dienst läuft nicht mehr als root.
- [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
nativ). Lokal wird schon mit Node 24 entwickelt. *AK:* `node -v` auf der VM = v24.x, `/healthz` ok.
- [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
`/ws`**. Produktion später = zweite Unit + zweiter Caddy-Block. *AK:* `/healthz` per HTTPS erreichbar.
- [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`,
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.
Ersetzt `push.ps1`/`deploy-all.ps1` (PowerShell-Wrapper darf das Skript per SSH aufrufen).
*AK:* Deploy auf Dev klappt; absichtlich kaputtes Release rollt sich selbst zurück.
Option `--reset-db` ruft nach dem Deploy `db:reset` auf (nur Umgebung `dev`).
- [ ] **P3-4 Backups** – *erst vor Produktion:* tägliches `sqlite3 .backup` (14 Tage) plus Kopie außerhalb der VM,
Wiederherstellung testen. Auf Dev reicht die Sicherungskopie aus dem Reset-Skript.
- [ ] **P3-5 Logs + Überwachung:** strukturierte Logs (JSON-Zeilen: Zeit, Ebene, Ereignis, uid, matchId) nach journald;
`/healthz` von außen überwachen (z. B. UptimeRobot, kostenlos) mit Mail an Michael.
Kennzahlen im Log: Verbindungen, laufende Matches, Tick-Dauer (Warnung > 8 ms).
- [ ] **P3-6 CI mit Gitea Actions** (`.gitea/workflows/`, braucht einen registrierten `act_runner` – auf der Gitea-
Maschine oder als Docker-Container auf der VM):
- bei jedem Push auf `main`: `npm ci`, `npm run lint`, `npm test`, Server-Integrationstests.
- nur wenn alles grün → automatisch Deploy auf **Dev** + Smoke-Test (`/healthz`, ein Bot-Kampf über WS).
- *Später:* Git-Tag `v*` → Deploy auf **Produktion** nach manueller Freigabe.
Secrets in Gitea: `DEPLOY_SSH_KEY`, `DEPLOY_HOST`. *AK:* Ein Push mit rotem Test wird **nicht** deployt
(der Dev-Server bleibt auf dem letzten grünen Stand).
### Phase 4 – Absicherung und Feinschliff
- [x] **P4-1 Bot-Client** `tools/bot.js`: verbindet sich per WS, nimmt Challenges an, spielt mit `RC.AI`.
Nutzbar für Smoke-Tests und als Gegner auf dem Dev-Server. *AK:* `node tools/bot.js --url … --count 20` spielt 10 Matches parallel.
- [x] **P4-2 Browser-E2E** mit Playwright: zwei Browser-Kontexte, Gast-Login, Lobby, Challenge, Kampf mit `&auto`,
beide sehen spiegelbildliches Ergebnis. Läuft in CI gegen einen lokal gestarteten Server.
- [ ] **P4-3 Lasttest:** 100 Bots / 50 Matches auf dem Dev-Server; Tick-Dauer und CPU dokumentieren.
- [ ] **P4-4 Latenz-Komfort:** Vorhersage für den eigenen Roboter (Eingabe sofort lokal anwenden, mit Server-Snapshot
abgleichen), Ping-Anzeige im HUD. Nur wenn Spieltests Verzögerung bemängeln.
- [x] **P4-5 `game.js` aufteilen** (> 1500 Zeilen, Regel aus CLAUDE.md): `online-ui.js` (Lobby, Login),
`fight.js` (Kampfablauf), `results.js`. Ohne Verhaltensänderung, abgesichert durch `&uicheck` + E2E.
---
## 7. Test-System (wer testet was)
| Ebene | Werkzeug | Was | Wann |
|---|---|---|---|
| Unit | `node --test` | Spiellogik, Protokoll-Validierer, Seat-Mapping, Wirtschaftsregeln | jede Änderung, < 10 s |
| Simulation | `tests/sim.test.js`, `tests/balance.js` | Kämpfe ohne NaN, Regeln, Balance | jede Änderung an Logik |
| Server-Integration | `node --test` + echter Server auf Zufallsport + `ws`-Clients + In-Memory-SQLite (`DB_FILE=:memory:`) | Auth, REST, Lobby, kompletter Match über WS, Disconnect | jede Änderung an Server/Netz |
| UI | `&uicheck` (headless Chrome) | Layout, Überläufe, Tap-Ziele | jede UI-Änderung |
| E2E | Playwright, 2 Browser | Login → Lobby → Kampf → Ergebnis | bei jedem Push auf `main` (CI) |
| Smoke | `tools/bot.js` gegen den Dev-Server | Deploy funktioniert wirklich | nach jedem Deploy |
| Last | Bots (P4-3) | Tick-Dauer, CPU | vor großen Releases |
| Manuell | Michi + Benni mit den Seed-Konten auf dem Dev-Server | Spielgefühl, Latenz | nach jeder Phase |
**Grundsatz:** Jeder gefundene Bug bekommt zuerst einen Test, der ihn zeigt (rot), dann den Fix (grün).
---
## 8. Definition of Done (für jede Task)
1. Akzeptanzkriterien erfüllt, `npm run lint` und `npm test` grün.
2. Neue Logik hat Tests; ein Bugfix hat einen Regressionstest.
3. Sichtbare Texte in `game/lang.js` (en + de).
4. Kampagne per Doppelklick auf `game/index.html` getestet (läuft weiter offline).
5. Bei UI-Änderung: `&uicheck` ohne neue Befunde.
6. Doku angepasst (`CLAUDE.md`, `README.md`, `server/README.md`), Task hier abgehakt.
7. Bei Server-Änderungen: auf den Dev-Server deployt und per Bot/Browser geprüft.
---
## 9. Risiken
| Risiko | Gegenmaßnahme |
|---|---|
| Latenz fühlt sich träge an (keine Vorhersage) | Erst messen (Ping-Anzeige), dann P4-4. Bei Hetzner Falkenstein/Nürnberg für DE meist < 40 ms. |
| `combat.js` hat versteckte Browser-Abhängigkeiten | `tests/sim.test.js` läuft schon in Node → gering. Raum-Test (P1-3) deckt es ab. |
| Bestehende Online-Spielstände | Entschieden: werden verworfen, `db:reset` setzt frisch auf (P2-1b). |
| Eine VM = Single Point of Failure | Für Dev egal; vor Produktion Backups außerhalb + dokumentierte Wiederherstellung (P3-4). |
| Schleichender Rückfall in Firebase-Muster | Regel in CLAUDE.md: keine generischen Pfad-Schreibzugriffe, nur explizite Endpunkte/Nachrichten. |
| Feste Testpasswörter landen in Produktion | Es gibt kein Prod. Bevor eins kommt: T-4 (Refactoring + Security-Check) inkl. T-1. |
---
## 10. TODO nach dem großen Umbau (bewusst verschoben)
Erst angehen, wenn Phase 1–3 durch sind. Pflicht erst, wenn Michael oder Benni ein Produktionssystem ansagen (dann T-4).
- [ ] **T-1 Seed-Passwörter aus dem Code.** `DEV_SEED_USERS` mit `Michi2000!`/`Benni2000!` aus `reset-db.js` entfernen;
Seed-Konten kommen aus der Server-`.env` (`SEED_USERS=michi:<mail>:<pass>,benni:<mail>:<pass>`) oder werden beim
Reset interaktiv abgefragt. Bestehende Dev-Konten: Passwort ändern. `.env.example` mit Platzhaltern ergänzen.
- [ ] **T-2 E-Mail für Konten.** E-Mail beim Registrieren (optional → später ggf. Pflicht), Bestätigungs-Mail,
„Passwort vergessen“ per Mail-Link. Braucht einen SMTP-Zugang oder Mail-Dienst (Zugangsdaten nur in `.env`).
Login per Name **oder** E-Mail bleibt.
- [ ] **T-3** Hetzner-Backups + Off-Site-Sicherung (P3-4) und Produktions-Umgebung (zweite systemd-Unit + Caddy-Block).
- [ ] **T-4 Prod-Readiness: Refactoring + Security-Check.** Startet erst, wenn Michael oder Benni ausdrücklich sagen,
dass es ein Produktionssystem geben soll. Umfang: Code-Review/Refactoring der Dev-Abkürzungen, Security-Review
(Auth, Rate-Limits, Eingabe-Validierung, Secrets, Server-Härtung P3-1, Abhängigkeiten `npm audit`),
T-1 bis T-3 erledigen, Testkonten entfernen oder durch echte Konten ersetzen, Produktions-Sperren in Reset-/
Admin-Skripten einbauen. Ergebnis als Bericht in `docs/`.

View File

@@ -1,36 +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.)
## 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).
## 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.

View File

@@ -1,62 +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"
}
},
"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)"
}
}
}
}
}

33
eslint.config.js Normal file
View File

@@ -0,0 +1,33 @@
// ESLint (flat config). `npm run lint`. Catches real bugs (undefined names, unused code, typos) - no style rules.
'use strict';
const js = require('@eslint/js');
const globals = require('globals');
// shared across the classic <script> files of the game (no modules, see CLAUDE.md)
const gameGlobals = { RC: 'writable', Kit: 'writable', THREE: 'readonly', KIT_ASSETS: 'readonly', module: 'readonly', require: 'readonly' };
module.exports = [
{
ignores: ['node_modules/**', 'server/node_modules/**', 'release/**', 'game/vendor/**', 'game/kit/**',
'launcher/**', 'sprite-generator/**', 'tools/shots/**', 'admin/**', 'test-results/**', 'playwright-report/**'],
},
js.configs.recommended,
{
rules: {
'no-unused-vars': ['warn', { args: 'none', caughtErrors: 'none' }],
'no-empty': ['error', { allowEmptyCatch: true }],
},
},
{
files: ['game/**/*.js'],
languageOptions: { sourceType: 'script', globals: { ...globals.browser, ...gameGlobals } },
},
{
files: ['server/**/*.js', 'tests/**/*.js', 'tools/**/*.js', 'eslint.config.js', 'playwright.config.js'],
languageOptions: { sourceType: 'commonjs', globals: { ...globals.node } },
},
{
files: ['**/*.mjs'],
languageOptions: { sourceType: 'module', globals: { ...globals.node } },
},
];

View File

@@ -19,6 +19,7 @@
// solid cover and slicks: drive round them, they are not deadly
for (const b of ar.blocks || []) if (Math.abs(x - b.x) < b.hw + me.st.rad && Math.abs(z - b.z) < b.hd + me.st.rad) return 1;
for (const o of ar.oil || []) if (Math.hypot(x - o.x, z - o.z) < o.r) return 1;
for (const mn of s.mines || []) if (mn.arm <= 0 && Math.hypot(x - mn.x, z - mn.z) < mn.r + me.st.rad) return 2;
return 0;
}
@@ -29,11 +30,14 @@
let hold = { throttle: 0, turn: 0, fire: false, fire2: false }, wait = 0, stuck = 0, unstick = 0, contact = 0, retreat = 0, wob = rand() * 6;
const react = 0.32 - skill * 0.26; // seconds between decisions
function steer(me, tx, tz, speed = 1) {
const want = Math.atan2(tz - me.z, tx - me.x), diff = wrap(want - me.a);
// aim=true: orient so the weapon (which may sit on the back/side) faces the target, else aim the front
function steer(me, tx, tz, speed = 1, aim = false) {
const mA = aim ? (me.st.mountA || 0) : 0;
const want = wrap(Math.atan2(tz - me.z, tx - me.x) - mA), diff = wrap(want - me.a);
const turn = clamp(diff * 2.2, -1, 1);
const ad = Math.abs(diff);
const throttle = ad < 0.5 ? speed : ad < 1.4 ? speed * 0.45 : ad > 2.6 && Math.hypot(tx - me.x, tz - me.z) < 2 ? -0.6 : 0.1;
const dir = Math.cos(mA) < -0.5 ? -1 : 1; // rear-mounted weapon: reverse to bring it onto the enemy
const throttle = (ad < 0.5 ? speed : ad < 1.4 ? speed * 0.45 : ad > 2.6 && Math.hypot(tx - me.x, tz - me.z) < 2 ? -0.6 : 0.1) * dir;
return { turn, throttle };
}
@@ -63,7 +67,7 @@
} else if (style === 'gunner' && t) { // face the enemy (fixed turret), hold the range
tx = e.x; tz = e.z;
}
let cmd = steer(me, tx, tz, 0.75 + skill * 0.25);
let cmd = steer(me, tx, tz, 0.75 + skill * 0.25, style !== 'pusher');
// gunner too close: back off but keep the nose (and the turret) on the enemy
if (style === 'gunner' && t && dist < ((t.type === 'flamer' || t.type === 'zapper') ? 1.4 : 2.8)) cmd = { turn: cmd.turn, throttle: -0.7 };
@@ -138,6 +142,58 @@
{ id: 'overlord', name: 'Overlord', style: 'flanker', skill: 0.95, prize: 1450,
build: { chassis: 'discus', motor: 'comet', wheels: 'rubber', battery: 'lipo', armour: 'steel', weapon: 'spinner', tower: null, gadget: 'righter' }, paint: pal(0x101418, 0xff3030) },
];
// --- lightweight league (max 60 kg): quick, fragile, cheap ---
RC.LEAGUE_LIGHT = [
{ id: 'tinflea', name: 'Tin Flea', style: 'brawler', skill: 0.1, prize: 200,
build: { chassis: 'cage', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'wedge', tower: null }, paint: pal(0x9aa3ad, 0xf2c230) },
{ id: 'sparrow', name: 'Sparrow', style: 'flanker', skill: 0.18, prize: 280,
build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'lance', tower: null }, paint: pal(0x2e9c8f, 0xffffff) },
{ id: 'needle', name: 'Needle', style: 'brawler', skill: 0.3, prize: 370,
build: { chassis: 'cage', motor: 'hornet', wheels: 'omni', battery: 'nicd', armour: 'mesh', weapon: 'saw', tower: null }, paint: pal(0xd8452b, 0x15171b) },
{ id: 'jackrabbit', name: 'Jackrabbit', style: 'pusher', skill: 0.4, prize: 470,
build: { chassis: 'doorstop', motor: 'sparky', wheels: 'bigtyre', battery: 'nicd', armour: null, weapon: 'lifter', tower: null }, paint: pal(0x5fae3b, 0xf2c230) },
{ id: 'switchblade', name: 'Switchblade', style: 'flanker', skill: 0.52, prize: 590,
build: { chassis: 'hexpod', motor: 'hornet', wheels: 'omni', battery: 'lipo', armour: 'titan', weapon: 'wedge', tower: null }, paint: pal(0x6a3fb0, 0xe6e6e6) },
{ id: 'wasp', name: 'Wasp', style: 'brawler', skill: 0.64, prize: 720,
build: { chassis: 'fang', motor: 'hornet', wheels: 'rubber', battery: 'lipo', armour: null, weapon: 'lance', tower: null, gadget: 'righter' }, paint: pal(0xf2c230, 0x15171b) },
{ id: 'firefly', name: 'Firefly', style: 'gunner', skill: 0.78, prize: 900,
build: { chassis: 'crate', motor: 'comet', wheels: 'omni', battery: 'lipo', armour: null, weapon: 'saw', tower: 'flamer' }, paint: pal(0xff7a1a, 0x3a3d44) },
{ id: 'pinpoint', name: 'Pinpoint', style: 'flanker', skill: 0.92, prize: 1150,
build: { chassis: 'fang', motor: 'comet', wheels: 'rubber', battery: 'lipo', armour: null, weapon: 'mace', tower: null }, paint: pal(0x101418, 0x4fa8ff) },
];
// --- heavyweight league (max 130 kg): slow, armoured, brutal ---
RC.LEAGUE_HEAVY = [
{ id: 'bulldozer', name: 'Bulldozer', style: 'pusher', skill: 0.14, prize: 420,
build: { chassis: 'bulwark', motor: 'bulldog', wheels: 'tracks', battery: 'lead', armour: 'steel', weapon: 'wedge', tower: null }, paint: pal(0xf2c230, 0x15171b) },
{ id: 'anvil', name: 'Anvil', style: 'brawler', skill: 0.26, prize: 540,
build: { chassis: 'plough', motor: 'bulldog', wheels: 'studs', battery: 'nicd', armour: 'steel', weapon: 'lance', tower: null }, paint: pal(0x8c8c8c, 0xd8452b) },
{ id: 'boilerplate', name: 'Boilerplate', style: 'brawler', skill: 0.38, prize: 680,
build: { chassis: 'boiler', motor: 'hornet', wheels: 'drumwh', battery: 'nicd', armour: 'spiked', weapon: 'hammer', tower: null }, paint: pal(0x5a5048, 0xff7a1a) },
{ id: 'grinder', name: 'Grinder', style: 'brawler', skill: 0.5, prize: 850,
build: { chassis: 'discus', motor: 'comet', wheels: 'tracks', battery: 'lipo', armour: 'ceramic', weapon: 'drum', tower: null }, paint: pal(0x3a3d44, 0x6dff9e) },
{ id: 'juggernaut', name: 'Juggernaut', style: 'pusher', skill: 0.62, prize: 1050,
build: { chassis: 'bulwark', motor: 'bulldog', wheels: 'tracks', battery: 'liion', armour: 'hardox', weapon: 'crusher', tower: null, gadget: 'repair' }, paint: pal(0xc0392b, 0xf2c230) },
{ id: 'warhound', name: 'Warhound', style: 'gunner', skill: 0.74, prize: 1300,
build: { chassis: 'plough', motor: 'hornet', wheels: 'studs', battery: 'liion', armour: 'ceramic', weapon: 'mace', tower: 'flamer', gadget: 'shield' }, paint: pal(0x6a3fb0, 0xffa020) },
{ id: 'colossus', name: 'Colossus', style: 'brawler', skill: 0.86, prize: 1600,
build: { chassis: 'scarab', motor: 'comet', wheels: 'tracks', battery: 'supercap', armour: 'hardox', weapon: 'spinner', tower: 'zapper' }, paint: pal(0x2b2f36, 0x4fa8ff) },
{ id: 'doomsday', name: 'Doomsday', style: 'flanker', skill: 0.97, prize: 2000,
build: { chassis: 'plough', motor: 'bulldog', wheels: 'tracks', battery: 'supercap', armour: 'hardox', weapon: 'vdisc', tower: 'swarm', gadget: 'mines' }, paint: pal(0x101418, 0xff3030) },
];
RC.LEAGUES = { light: RC.LEAGUE_LIGHT, medium: RC.LEAGUE, heavy: RC.LEAGUE_HEAVY };
// Swap the active class: RC.LEAGUE and the weight limit follow, like RC.setArena does for arenas.
RC.setClass = id => {
const c = RC.CLASSES.find(x => x.id === id) || RC.CLASSES[1];
RC.CLASS = c.id;
RC.WEIGHT_LIMIT = c.max;
RC.LEAGUE = RC.LEAGUES[c.id];
return c;
};
RC.CLASS = 'medium';
RC.DUMMY = { id: 'dummy', name: 'Dummy', style: 'dummy', skill: 0, prize: 0,
build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: 'steel', weapon: null, tower: null }, paint: pal(0x8c8c8c, 0xff7a1a) };

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 291 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 344 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 251 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 306 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 290 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 241 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 275 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 288 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 265 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 205 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

52
game/cloudsave.js Normal file
View File

@@ -0,0 +1,52 @@
/* 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 campaign still lives in localStorage (fast cache); with a real account it is mirrored to
/api/campaign so it survives a device change. Client-trusted - it is the offline game.
const cloud = RC.CloudSave(net);
cloud.pull() -> the cloud save object, or null (best effort, never throws)
cloud.push(save) -> debounced write (~2.5 s after the last change)
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) */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
// cloud wins when it is at least as new as local (shared copy is the source once it exists)
function newer(cloud, local) {
if (!cloud || typeof cloud !== 'object') return false;
const ct = +cloud.ts || 0, lt = (local && +local.ts) || 0;
return ct >= lt;
}
RC.CloudSave = function (net) {
let timer = null, sending = false, pending = null;
const clone = s => { try { return JSON.parse(JSON.stringify(s)); } catch (e) { return null; } };
async function write(save) {
sending = true;
try { await net.api('PUT', '/api/campaign', save); } catch (e) { /* best effort */ }
sending = false;
if (pending) { const s = pending; pending = null; write(s); }
}
function doPush(save) {
if (!net || !net.enabled || !save) return;
if (sending) { pending = save; return; } // one request at a time; keep only the latest
write(save);
}
return {
newer,
async pull() {
if (!net || !net.enabled) return null;
try { return await net.api('GET', '/api/campaign'); } catch (e) { return null; }
},
push(save) { clearTimeout(timer); const snap = clone(save); timer = setTimeout(() => doPush(snap), 2500); },
flush(save) { clearTimeout(timer); doPush(clone(save)); },
};
};
RC.CloudSave.newer = newer;
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -33,7 +33,6 @@
}
const saw = (x, z, phase) => ({ x, z, r: 0.95, period: 6, on: 2.2, phase });
const flame = (x, z, phase) => ({ x, z, hw: 0.9, hd: 0.9, period: 7, on: 1.8, phase });
const saw2 = saw, flame2 = flame;
const block = (kind, x, z, hw, hd, h2) => ({ kind, x, z, hw, hd, h: h2 || 0.8 });
const belt = (x, z, hw, hd, ax, az, force) => ({ x, z, hw, hd, ax, az, force });
const ram = (x, z, hw, hd, nx, nz, phase) => ({ x, z, hw, hd, nx, nz, period: 5, on: 1.3, phase });
@@ -138,8 +137,12 @@
shield: 0, gcd: 0, gUses: st.gadget && st.gadget.charges || 0,
lost: { armour: false, wheels: false, weapon: false, tower: false }, // parts torn off during the fight
onOil: false, // standing in a slick: less grip, lazy steering
g3: false, // last gadget button state (for one-shot gadgets)
cd: 0, cd2: 0, spin: 0, swing: 0, flipAnim: 0, boost: 0, sawOn: false, flameOn: false, gunOn: false,
turretA: p.a, dealt: 0, taken: 0, pressT: 0, craneT: 0, fx: 0,
// per-weapon runtime (one entry per mounted weapon) + per-weapon broken flag
W: (st.weapons || []).map(() => ({ cd: 0, spin: 0, swing: 0, grab: 0, fx: 0, flipAnim: 0, sawOn: false, fire: 0 })),
lostW: (st.weapons || []).map(() => false),
};
}
@@ -148,7 +151,7 @@
const s = {
arena: A, t: 0, left: A.duration, pitOpen: 0, rand: rng(opt.seed || 1),
robots: opt.robots.map((st, i) => makeRobot(st, i, (opt.names || [])[i] || 'Robot ' + (i + 1), A)),
rockets: [], events: [], result: null, endIn: 0,
rockets: [], mines: [], events: [], result: null, endIn: 0,
press: { st: 'idle', t: 0, y: 1 }, // idle | warn | slam | up ; y 1 = top, 0 = floor
crane: { st: 'idle', t: 0, who: -1, tx: 0, tz: 0, x: A.crane.x, z: A.crane.z },
pitAlarm: false,
@@ -157,38 +160,58 @@
}
// a part that broke off no longer works (and bare metal takes more damage)
const weaponOf = r => (r.lost.weapon ? null : r.st.weapon);
const weaponOf = r => (r.lostW && r.lostW[0] ? null : (r.st.weapons && r.st.weapons[0] && r.st.weapons[0].part) || null);
const towerOf = r => (r.lost.tower ? null : r.st.tower);
const reduceOf = r => (r.lost.armour ? r.st.reduce * 0.3 : r.st.reduce);
// battle damage: at these shares of health the next hit tears a part off (no randomness,
// so both sides of an online fight and the tests see exactly the same thing)
const BREAK_AT = [['armour', 0.6], ['wheels', 0.4], ['weapon', 0.25], ['tower', 0.18]];
const BREAK_AT = [['armour', 0.6], ['wheels', 0.4], ['tower', 0.18]];
const WEAPON_BREAK = [0.25, 0.17, 0.11]; // weapons tear off one by one as health drops
function breakCheck(s, r) {
if (r.dead || r.out) return;
const f = r.hp / r.maxHp;
for (const [part, at] of BREAK_AT) {
if (r.lost[part] || f >= at) continue;
if (part === 'armour' && !r.st.armour) continue;
if (part === 'weapon' && !r.st.weapon) continue;
if (part === 'tower' && !r.st.tower) continue;
r.lost[part] = true;
if (part === 'weapon') { r.spin = 0; r.swing = 0; if (r.grab > 0) release(s, r, s.robots[1 - r.i]); }
s.events.push({ type: 'broke', who: r.i, part, x: r.x, z: r.z });
}
const list = r.st.weapons || [];
for (let i = 0; i < list.length; i++) {
if (r.lostW[i] || f >= (WEAPON_BREAK[i] || 0.1)) continue;
r.lostW[i] = true;
const W = r.W[i]; W.spin = 0; W.swing = 0; if (W.grab > 0) release(s, r, s.robots[1 - r.i], i);
s.events.push({ type: 'broke', who: r.i, part: 'weapon' + i, x: r.x, z: r.z });
}
}
const fwd = r => [Math.cos(r.a), Math.sin(r.a)];
// enemy position in my frame: [forward, side]
function local(me, e) {
const dx = e.x - me.x, dz = e.z - me.z, c = Math.cos(me.a), sn = Math.sin(me.a);
// direction weapon i points: robot forward turned by that weapon's mount angle (front 0, back pi, sides +-pi/2)
const wdirI = (r, i) => { const m = r.st.weapons[i], a = r.a + (m ? m.mountA : 0); return [Math.cos(a), Math.sin(a)]; };
const alongI = (r, i) => { const m = r.st.weapons[i]; return ((m && m.mountAxis === 'wid') ? r.st.wid : r.st.len) / 2; }; // body half-extent toward weapon i
const wdir = r => wdirI(r, 0); // lead weapon (ram bonus, compat)
// enemy position in my frame about angle `a`: [along, side]
function localAt(me, e, a) {
const dx = e.x - me.x, dz = e.z - me.z, c = Math.cos(a), sn = Math.sin(a);
return [dx * c + dz * sn, -dx * sn + dz * c];
}
function inZone(s, me, e, extra = 0) {
function local(me, e) { return localAt(me, e, me.a); }
// is the enemy inside weapon i's reach (reach runs along that weapon's mounted axis)?
function inZoneI(s, me, e, i, extra = 0) {
if (e.out || me.out) return false;
const w = weaponOf(me); if (!w) return false;
const [lf, ls] = local(me, e);
return lf > 0 && lf < me.st.len / 2 + w.reach + e.st.rad * 0.75 + extra && Math.abs(ls) < me.st.wid / 2 + e.st.rad * 0.55;
const m = me.st.weapons[i]; if (!m || (me.lostW && me.lostW[i])) return false;
const [lf, ls] = localAt(me, e, me.a + m.mountA);
const along = (m.mountAxis === 'wid' ? me.st.wid : me.st.len) / 2;
const perp = (m.mountAxis === 'wid' ? me.st.len : me.st.wid) / 2;
return lf > 0 && lf < along + m.part.reach + e.st.rad * 0.75 + extra && Math.abs(ls) < perp + e.st.rad * 0.55;
}
// any weapon in range (AI fire decision, player weapon-assist)
function inZone(s, me, e, extra = 0) {
const list = me.st.weapons || [];
for (let i = 0; i < list.length; i++) if (inZoneI(s, me, e, i, extra)) return true;
return false;
}
// where on the target the hit lands: front 0.8 (+chassis front armour), side 1, rear 1.3
@@ -243,6 +266,7 @@
for (let k = 0; k < 2; k++) gadgets(s, R[k], R[1 - k], (s.result ? null : inputs[k]) || {}, dt);
for (let k = 0; k < 2; k++) weapons(s, R[k], R[1 - k], (s.result ? null : inputs[k]) || {}, dt);
rockets(s, dt);
mines(s, dt);
hazards(s, dt);
if (!s.result && s.left <= 0) {
@@ -254,8 +278,8 @@
}
function drive(s, r, e, inp, dt) {
r.cd = Math.max(0, r.cd - dt); r.cd2 = Math.max(0, r.cd2 - dt);
r.stun = Math.max(0, r.stun - dt); r.boost = Math.max(0, r.boost - dt); r.flipAnim = Math.max(0, r.flipAnim - dt);
r.cd2 = Math.max(0, r.cd2 - dt);
r.stun = Math.max(0, r.stun - dt); r.boost = Math.max(0, r.boost - dt);
if (r.out) { r.fall += dt; r.y -= dt * (1 + r.fall * 6); return; }
if (r.flipped > 0) {
r.flipped -= dt;
@@ -270,7 +294,7 @@
const thr = clamp(inp.throttle || 0, -1, 1), trn = clamp(inp.turn || 0, -1, 1);
const hurt = r.lost.wheels ? 0.75 : 1; // burst wheel: slower, clumsier
const oil = r.onOil ? 0.55 : 1; // oil slick: hardly any steering
let top = st.top * hurt * (r.boost > 0 ? 1.65 : 1) * (r.grab > 0 ? 0.6 : 1) * (thr < 0 ? 0.75 : 1);
let top = st.top * hurt * (r.boost > 0 ? 1.65 : 1) * (grabbing(r) ? 0.6 : 1) * (thr < 0 ? 0.75 : 1);
const target = thr * top, acc = st.accel * (r.lost.wheels ? 0.85 : 1) * (r.boost > 0 ? 2 : 1);
const braking = Math.abs(target) < Math.abs(vf) || target * vf < 0;
const rate = acc * (braking ? 1.6 : 1) * dt;
@@ -311,7 +335,7 @@
s.events.push({ type: 'wall', who: r.i, x: r.x, z: r.z, speed: vn });
damage(s, r, (vn - 1.8) * 4.5, null, { kind: 'spikes' });
// slammed into the spikes hard -> bounces up and can land on its back
if (vn > 3.5 && r.y < 0.05 && !r.st.invertible && !r.st.lowProfile && s.rand() < 0.3) { r.vy = Math.max(r.vy, 2); r.flipped = 2.2; r.av += (s.rand() - 0.5) * 6; }
if (vn > 3.5 && r.y < 0.05 && !r.st.invertible && !r.st.lowProfile && s.rand() < 0.3 * (r.st.topHeavy || 1)) { r.vy = Math.max(r.vy, 2); r.flipped = 2.2; r.av += (s.rand() - 0.5) * 6; }
}
r.vx += w.nx * vn * 1.45; r.vz += w.nz * vn * 1.45; // bounce (0.45 restitution)
}
@@ -350,9 +374,9 @@
const impact = -vrel;
if (impact < 1.2) return;
s.events.push({ type: 'bump', x: (a.x + b.x) / 2, z: (a.z + b.z) / 2, speed: impact });
// ramming: the robot whose front drives into the other does the damage
// ramming: the robot whose weapon side drives into the other does the damage
for (const [me, e, sx, sz] of [[a, b, nx, nz], [b, a, -nx, -nz]]) {
const [fx, fz] = fwd(me);
const [fx, fz] = wdir(me);
const facing = fx * sx + fz * sz;
const myV = me.vx * sx + me.vz * sz;
if (facing > 0.55 && myV > 1.2) {
@@ -363,78 +387,91 @@
if (w && w.type === 'wedge' && e.y < 0.05 && !e.st.lowProfile) {
const light = Math.sqrt(me.st.mass / e.st.mass);
e.vy = Math.max(e.vy, 2.3 * light); e.stun = Math.max(e.stun, 0.25);
if (!e.st.invertible && !e.st.lowProfile && s.rand() < 0.3 * light && impact > 3) { e.flipped = 2.2; e.av += (s.rand() - 0.5) * 6; }
if (!e.st.invertible && !e.st.lowProfile && s.rand() < 0.3 * light * (e.st.topHeavy || 1) && impact > 3) { e.flipped = 2.2; e.av += (s.rand() - 0.5) * 6; }
} else if (impact > 4.5 && e.y < 0.05 && !e.st.lowProfile && !e.st.invertible) {
const light = Math.sqrt(me.st.mass / e.st.mass);
if (s.rand() < 0.22 * light) { e.vy = Math.max(e.vy, 1.8 * light); e.flipped = 2.2; e.av += (s.rand() - 0.5) * 5; s.events.push({ type: 'flip', who: e.i, x: e.x, z: e.z }); }
if (s.rand() < 0.22 * light * (e.st.topHeavy || 1)) { e.vy = Math.max(e.vy, 1.8 * light); e.flipped = 2.2; e.av += (s.rand() - 0.5) * 5; s.events.push({ type: 'flip', who: e.i, x: e.x, z: e.z }); }
}
}
}
}
// each mounted weapon runs its own logic with its own state (r.W[i]) and mount direction
function weapons(s, r, e, inp, dt) {
r.sawOn = false; // aggregate for sound; per-weapon render flags on r.W[i]
const list = r.st.weapons || [];
for (let i = 0; i < list.length; i++) meleeWeapon(s, r, e, inp, dt, i);
towerFire(s, r, e, inp, dt);
}
function meleeWeapon(s, r, e, inp, dt, i) {
const W = r.W[i];
if (r.lostW[i]) { W.spin = 0; W.sawOn = false; return; }
const inst = r.st.weapons[i], w = inst.part;
const ok = !r.dead && !r.out && r.lifted <= 0 && r.grabbedBy === null && r.flipped <= 0;
const w = weaponOf(r), [fx, fz] = fwd(r);
r.sawOn = false; r.flameOn = false; r.gunOn = false;
if (r.swing > 0) { // hammer comes down
r.swing -= dt;
if (r.swing <= 0 && ok) {
s.events.push({ type: 'smash', who: r.i, x: r.x + fx * (r.st.len / 2 + 0.6), z: r.z + fz * (r.st.len / 2 + 0.6) });
if (inZone(s, r, e, 0.15)) { damage(s, e, w.dmg, r, { pierce: 0.5, noZone: true, kind: 'smash' }); e.stun = Math.max(e.stun, 0.35); }
const [fx, fz] = wdirI(r, i), reach0 = alongI(r, i);
const inZ = (ex = 0) => inZoneI(s, r, e, i, ex);
W.cd = Math.max(0, W.cd - dt); W.flipAnim = Math.max(0, W.flipAnim - dt); W.fire = Math.max(0, W.fire - dt);
W.sawOn = false;
if (W.swing > 0) { // hammer comes down
W.swing -= dt;
if (W.swing <= 0 && ok) {
s.events.push({ type: 'smash', who: r.i, x: r.x + fx * (reach0 + 0.6), z: r.z + fz * (reach0 + 0.6) });
if (inZ(0.15)) { damage(s, e, w.dmg, r, { pierce: 0.5, noZone: true, kind: 'smash' }); e.stun = Math.max(e.stun, 0.35); }
}
}
if (r.grab > 0) { // crusher holds the enemy
r.grab -= dt;
if (!ok || e.out || r.grab <= 0) release(s, r, e);
if (W.grab > 0) { // crusher holds the enemy
W.grab -= dt;
if (!ok || e.out || W.grab <= 0) release(s, r, e, i);
else {
const d = r.st.len / 2 + e.st.rad * 0.85;
const d = reach0 + e.st.rad * 0.85;
e.x = r.x + fx * d; e.z = r.z + fz * d; e.vx = r.vx; e.vz = r.vz; e.y = 0;
damage(s, e, w.dps * dt, r, { kind: 'crush', tick: true });
}
}
if (w && ok) {
if (ok) {
switch (w.type) {
case 'wedge':
if (inp.fire && r.cd <= 0) { r.boost = 0.8; r.cd = w.cd; s.events.push({ type: 'boost', who: r.i, x: r.x, z: r.z }); }
if (inp.fire && W.cd <= 0) { r.boost = 0.8; W.cd = w.cd; W.fire = 0.8; s.events.push({ type: 'boost', who: r.i, x: r.x, z: r.z }); }
break;
case 'flipper':
if (inp.fire && r.cd <= 0) {
r.cd = w.cd; r.flipAnim = 0.35;
if (inp.fire && W.cd <= 0) {
W.cd = w.cd; W.flipAnim = 0.35;
s.events.push({ type: 'flip', who: r.i, x: r.x + fx, z: r.z + fz });
if (inZone(s, r, e) && e.y < 0.2 && e.grabbedBy === null && e.lifted <= 0) {
if (inZ() && e.y < 0.2 && e.grabbedBy === null && e.lifted <= 0) {
const light = Math.sqrt(70 / e.st.mass);
e.vy = w.launch * light * (e.st.lowProfile ? 0.65 : 1);
e.vx += fx * 3 * light; e.vz += fz * 3 * light;
e.av += (s.rand() - 0.5) * 6;
damage(s, e, w.dmg, r, { kind: 'flip' });
if (!e.st.invertible && s.rand() < (e.st.lowProfile ? 0.25 : 0.45)) e.flipped = 2.2;
if (!e.st.invertible && s.rand() < (e.st.lowProfile ? 0.25 : 0.45) * (e.st.topHeavy || 1)) e.flipped = 2.2;
}
}
break;
case 'hammer':
if (inp.fire && r.cd <= 0 && r.swing <= 0) { r.swing = 0.28; r.cd = w.cd; s.events.push({ type: 'swing', who: r.i }); }
if (inp.fire && W.cd <= 0 && W.swing <= 0) { W.swing = 0.28; W.cd = w.cd; s.events.push({ type: 'swing', who: r.i }); }
break;
case 'saw':
if (inp.fire) {
r.sawOn = true;
if (inZone(s, r, e)) {
W.sawOn = true; r.sawOn = true;
if (inZ()) {
damage(s, e, w.dps * dt, r, { kind: 'saw', tick: true });
r.fx -= dt; if (r.fx <= 0) { r.fx = 0.06; s.events.push({ type: 'sparks', x: r.x + fx * (r.st.len / 2 + 0.3), z: r.z + fz * (r.st.len / 2 + 0.3), n: 6 }); }
W.fx -= dt; if (W.fx <= 0) { W.fx = 0.06; s.events.push({ type: 'sparks', x: r.x + fx * (reach0 + 0.3), z: r.z + fz * (reach0 + 0.3), n: 6 }); }
}
}
break;
case 'crusher':
if (inp.fire && r.cd <= 0 && r.grab <= 0 && inZone(s, r, e) && e.grabbedBy === null && e.y < 0.2 && e.lifted <= 0) {
r.grab = w.hold; r.cd = w.cd; e.grabbedBy = r.i;
if (inp.fire && W.cd <= 0 && W.grab <= 0 && inZ() && e.grabbedBy === null && e.y < 0.2 && e.lifted <= 0) {
W.grab = w.hold; W.cd = w.cd; e.grabbedBy = r.i;
s.events.push({ type: 'grab', who: r.i, x: e.x, z: e.z });
}
break;
case 'lifter':
// scoop: tips the enemy up again and again (short cooldown) - made for shoving into the pit
if (inp.fire && r.cd <= 0) {
r.cd = w.cd; r.flipAnim = 0.3;
if (inp.fire && W.cd <= 0) {
W.cd = w.cd; W.flipAnim = 0.3;
s.events.push({ type: 'flip', who: r.i, x: r.x + fx, z: r.z + fz });
if (inZone(s, r, e) && e.y < 0.2 && e.grabbedBy === null && e.lifted <= 0) {
if (inZ() && e.y < 0.2 && e.grabbedBy === null && e.lifted <= 0) {
const light = Math.sqrt(70 / e.st.mass);
e.vy = Math.max(e.vy, w.launch * light * 0.8);
e.vx += fx * 1.6 * light; e.vz += fz * 1.6 * light;
@@ -445,32 +482,36 @@
break;
case 'vspinner':
// vertical disc: throws the enemy into the air instead of sideways
r.spin = inp.fire ? Math.min(1, r.spin + dt / w.spinup) : Math.max(0, r.spin - dt * 0.35);
if (r.spin > 0.25 && r.cd <= 0 && inZone(s, r, e)) {
const k = r.spin, light = Math.sqrt(70 / e.st.mass);
W.spin = inp.fire ? Math.min(1, W.spin + dt / w.spinup) : Math.max(0, W.spin - dt * 0.35);
if (W.spin > 0.25 && W.cd <= 0 && inZ()) {
const k = W.spin, light = Math.sqrt(70 / e.st.mass);
damage(s, e, w.dmg * k, r, { kind: 'spin' });
e.vy = Math.max(e.vy, 6.5 * k * light);
e.vx += fx * 1.5 * k; e.vz += fz * 1.5 * k; e.av += 7 * k;
if (!e.st.invertible && s.rand() < 0.5 * k) e.flipped = 2.2;
r.spin *= 0.3; r.cd = 0.35;
if (!e.st.invertible && s.rand() < 0.5 * k * (e.st.topHeavy || 1)) e.flipped = 2.2;
W.spin *= 0.3; W.cd = 0.35;
s.events.push({ type: 'spinhit', who: r.i, x: (r.x + e.x) / 2, z: (r.z + e.z) / 2, k });
}
break;
case 'spinner':
r.spin = inp.fire ? Math.min(1, r.spin + dt / w.spinup) : Math.max(0, r.spin - dt * 0.35);
if (r.spin > 0.25 && r.cd <= 0 && inZone(s, r, e)) {
const k = r.spin, light = Math.sqrt(70 / e.st.mass);
W.spin = inp.fire ? Math.min(1, W.spin + dt / w.spinup) : Math.max(0, W.spin - dt * 0.35);
if (W.spin > 0.25 && W.cd <= 0 && inZ()) {
const k = W.spin, light = Math.sqrt(70 / e.st.mass);
damage(s, e, w.dmg * k, r, { kind: 'spin' });
e.vx += (fx * 5 + -fz * 2) * k * light; e.vz += (fz * 5 + fx * 2) * k * light;
e.vy = Math.max(e.vy, 2.5 * k * light); e.av += 5 * k;
r.vx -= fx * 2.5 * k; r.vz -= fz * 2.5 * k;
r.spin *= 0.35; r.cd = 0.3;
W.spin *= 0.35; W.cd = 0.3;
s.events.push({ type: 'spinhit', who: r.i, x: (r.x + e.x) / 2, z: (r.z + e.z) / 2, k });
}
break;
}
} else if (w && (w.type === 'spinner' || w.type === 'vspinner')) r.spin = Math.max(0, r.spin - dt * 0.5);
} else if (w.type === 'spinner' || w.type === 'vspinner') W.spin = Math.max(0, W.spin - dt * 0.5);
}
function towerFire(s, r, e, inp, dt) {
r.flameOn = false; r.gunOn = false;
const ok = !r.dead && !r.out && r.lifted <= 0 && r.grabbedBy === null && r.flipped <= 0;
// turret is bolted facing forward: you aim it by turning the robot, it does not track the enemy
const t = towerOf(r);
if (!t) return;
@@ -512,17 +553,21 @@
}
}
function release(s, r, e) {
r.grab = 0;
if (e.grabbedBy === r.i) { e.grabbedBy = null; }
function release(s, r, e, i) {
if (i == null) { for (const W of r.W) W.grab = 0; } else if (r.W[i]) r.W[i].grab = 0;
if (e.grabbedBy === r.i) e.grabbedBy = null;
}
const grabbing = r => r.W.some(W => W.grab > 0); // is any of my weapons holding the enemy?
// gadgets (input.fire3): one-shot abilities on a cooldown
function gadgets(s, r, e, inp, dt) {
r.gcd = Math.max(0, r.gcd - dt);
if (r.shield > 0) r.shield = Math.max(0, r.shield - dt);
const g = r.st.gadget;
const pressed = !!inp.fire3 && !r.g3; // rising edge: one action per press
r.g3 = !!inp.fire3;
if (!g || r.out || r.dead || !inp.fire3 || r.gcd > 0) return;
if (g.type === 'mines' && !pressed) return; // one mine per press, never a whole trail
const held = r.lifted > 0 || r.grabbedBy !== null;
switch (g.type) {
case 'righter': // flip back upright
@@ -541,6 +586,17 @@
if (r.gUses <= 0) return;
r.hp = Math.min(r.maxHp, r.hp + r.maxHp * g.heal); r.gUses--; r.gcd = g.cd;
break;
case 'mines': { // drop a mine behind you
if (r.gUses <= 0) return;
const [mx, mz] = fwd(r);
const d = r.st.len / 2 + 0.9; // well behind, not under your own tail
r.gUses--; r.gcd = g.cd;
// own: the layer is safe for a moment - drive back over it later and it still gets you
s.mines.push({ x: r.x - mx * d, z: r.z - mz * d, owner: r.i, arm: g.arm, own: 3,
r: g.r, dmg: g.dmg, launch: g.launch });
s.events.push({ type: 'mine_drop', who: r.i, x: r.x - mx * d, z: r.z - mz * d });
break;
}
case 'emp': // stun the enemy if close
r.gcd = g.cd;
if (!e.out && Math.hypot(e.x - r.x, e.z - r.z) < g.range + e.st.rad) {
@@ -563,10 +619,33 @@
case 'shield': return dist < 3 && me.flipped <= 0;
case 'repair': return me.gUses > 0 && me.hp < me.maxHp * 0.45;
case 'emp': return !e.out && dist < g.range * 0.9 && (e.boost > 0 || e.spin > 0.2 || dist < 2.5);
case 'mines': return me.gUses > 0 && dist > 1.4 && dist < 7; // drop one while they chase you
}
return false;
}
function mines(s, dt) {
for (let i = s.mines.length - 1; i >= 0; i--) {
const mn = s.mines[i];
if (mn.own > 0) mn.own -= dt;
if (mn.arm > 0) { mn.arm -= dt; continue; } // short delay so you can drive off it
for (const r of s.robots) {
if (r.out || r.dead || r.y > 0.35) continue;
if (mn.owner === r.i && mn.own > 0) continue; // grace period for whoever dropped it
if (Math.hypot(r.x - mn.x, r.z - mn.z) > mn.r + r.st.rad * 0.6) continue;
const light = Math.sqrt(70 / r.st.mass);
// your own mine pays the opponent, like any other hazard
damage(s, r, mn.dmg, mn.owner === r.i ? null : s.robots[mn.owner], { from: { x: mn.x, z: mn.z }, kind: 'mine' });
r.vy = Math.max(r.vy, mn.launch * light);
r.av += (s.rand() - 0.5) * 7;
if (!r.st.invertible && s.rand() < 0.5) r.flipped = 2.2;
s.events.push({ type: 'boom', x: mn.x, z: mn.z, y: 0.22, big: true });
s.mines.splice(i, 1);
break;
}
}
}
function rockets(s, dt) {
for (let i = s.rockets.length - 1; i >= 0; i--) {
const k = s.rockets[i], tgt = s.robots[1 - k.owner], own = s.robots[k.owner];
@@ -635,7 +714,7 @@
s.events.push({ type: 'pit', who: r.i, x: r.x, z: r.z });
const other = R[1 - r.i];
if (other.grabbedBy === r.i) other.grabbedBy = null;
if (r.grab > 0) release(s, r, other);
if (grabbing(r)) release(s, r, other);
finish(s, 1 - r.i, 'pit');
}
r.pressT = inRect(A.press, r.x, r.z) && ground ? r.pressT + dt : 0;
@@ -663,7 +742,7 @@
c.t -= dt;
if (c.st === 'idle') {
c.x += (A.crane.x - c.x) * Math.min(1, dt * 2); c.z += (A.crane.z - c.z) * Math.min(1, dt * 2);
const r = R.find(q => q.craneT > 0.8 && !q.out && !q.dead && q.grab <= 0);
const r = R.find(q => q.craneT > 0.8 && !q.out && !q.dead && !grabbing(q));
if (r && c.t <= 0) {
c.st = 'lift'; c.t = 0.6; c.who = r.i; r.lifted = 1; r.vx = r.vz = 0;
const toPit = s.pitOpen >= 1 && s.rand() < 0.35;
@@ -692,19 +771,20 @@
// p = share of the cooldown still running (1 = just used, 0 = ready), on = doing its thing right now,
// n = charges left where a part has them (repair kit).
function cooldowns(r) {
const out = [], w = r.st.weapon, t = r.st.tower, g = r.st.gadget;
const out = [], t = r.st.tower, g = r.st.gadget;
const broke = k => (r.lost && r.lost[k]) || false;
const frac = (left, full) => (full > 0 ? clamp(left / full, 0, 1) : 0);
if (w) {
const e = { slot: 'weapon', id: w.id, p: 0, on: false, broke: broke('weapon') };
if (w.type === 'saw') e.on = !!r.sawOn;
else if (w.type === 'spinner' || w.type === 'vspinner') { e.p = 1 - clamp(r.spin, 0, 1); e.on = r.spin > 0.25; }
(r.st.weapons || []).forEach((inst, i) => {
const w = inst.part, W = r.W[i];
const c = { slot: 'weapon', idx: i, id: w.id, p: 0, on: false, broke: !!(r.lostW && r.lostW[i]) };
if (w.type === 'saw') c.on = !!W.sawOn;
else if (w.type === 'spinner' || w.type === 'vspinner') { c.p = 1 - clamp(W.spin, 0, 1); c.on = W.spin > 0.25; }
else {
e.p = frac(r.cd, w.cd);
e.on = (w.type === 'hammer' && r.swing > 0) || (w.type === 'crusher' && r.grab > 0) || (w.type === 'wedge' && r.boost > 0);
c.p = frac(W.cd, w.cd);
c.on = (w.type === 'hammer' && W.swing > 0) || (w.type === 'crusher' && W.grab > 0) || (w.type === 'wedge' && W.fire > 0);
}
out.push(e);
}
out.push(c);
});
if (t) {
const e = { slot: 'tower', id: t.id, p: 0, on: false, broke: broke('tower') };
if (t.type === 'rockets' || t.type === 'mortar' || t.type === 'swarm') e.p = frac(r.cd2, t.cd);

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

File diff suppressed because it is too large Load Diff

View File

@@ -34,6 +34,18 @@
/* fixed design size, scaled to the window by Kit.fit */
#app { position: relative; width: 1280px; display: flex; flex-direction: column; }
/* HUD lives INSIDE the stage (full-screen game look), above the overlay so menus keep it reachable */
/* network overlay (F3) */
#netov { position: absolute; left: 8px; bottom: 12px; z-index: 9; width: 316px; padding: 8px; border-radius: 6px;
background: rgba(10,12,16,.86); border: 1px solid var(--line); box-shadow: var(--hl); font: 12px/1.35 Consolas, monospace;
color: var(--text); pointer-events: none; }
#netov.hide { display: none; } /* #netov beats the generic .hide rule - hide it explicitly */
#netov .nvh { font-weight: bold; color: var(--accent); margin-bottom: 4px; }
#netov canvas { display: block; width: 300px; height: 84px; }
#netov .nvleg { display: flex; gap: 8px; flex-wrap: wrap; margin: 3px 0 5px; font-size: 11px; color: var(--dim, #8d95a8); }
#netov .nvleg i { display: inline-block; width: 10px; height: 3px; margin-right: 3px; vertical-align: middle; }
#netov .nvrows { display: grid; grid-template-columns: auto 1fr; gap: 1px 10px; }
#netov .nvrows b { text-align: right; font-weight: normal; }
#netov .nvv { margin-top: 5px; border-top: 1px solid var(--line); padding-top: 4px; }
#hud { position: absolute; left: 0; right: 0; top: 0; z-index: 7; display: flex; gap: 8px; align-items: center;
height: 44px; padding: 0 12px; pointer-events: none;
background: linear-gradient(rgba(6,8,12,.9) 35%, rgba(6,8,12,0)); }
@@ -84,8 +96,8 @@
input:focus { outline: none; border-color: var(--accent); }
/* menus fade in once per screen (#overlay.enter is removed again, so live lists do not flicker) */
@keyframes cardIn { from { opacity: 0; transform: scale(.96); } to { opacity: 1; transform: none; } }
#overlay.enter > * { animation: cardIn .14s ease-out; }
@keyframes cardIn { from { opacity: 0; transform: translateY(10px) scale(.975); } to { opacity: 1; transform: none; } }
#overlay.enter > * { animation: cardIn .2s cubic-bezier(.2,.7,.2,1) both; will-change: transform, opacity; }
.tab, .item, .fitted .frow, .rroom, .prow { transition: border-color .1s, background-color .1s, transform .1s; }
@media (hover: hover) { .item:hover { transform: translateY(-2px); } }
@media (prefers-reduced-motion: reduce) {
@@ -105,7 +117,7 @@
#overlay.hide { display: none; }
#overlay.clear { background-color: transparent; }
.card { background: rgba(21, 25, 32, .94); border: 1px solid var(--line); border-radius: 14px; padding: 22px 30px;
min-width: 380px; max-width: 760px; max-height: 600px; overflow-y: auto; text-align: center; box-shadow: 0 20px 60px #000a; }
min-width: 380px; max-width: 760px; max-height: 624px; overflow-y: auto; text-align: center; box-shadow: 0 20px 60px #000a; }
.card h1 { margin: 0 0 6px; font: 44px var(--head); letter-spacing: .05em; color: var(--accent); text-shadow: 0 3px 0 #5a2600; }
.card h2 { margin: 0 0 10px; padding-bottom: 8px; font: 26px var(--head); letter-spacing: .04em; color: var(--accent);
position: relative; }
@@ -116,10 +128,30 @@
.board { list-style: none; padding: 0; margin: 14px 0 0; text-align: left; font-variant-numeric: tabular-nums; max-height: 150px; overflow: auto; }
.board li { display: flex; gap: 10px; padding: 2px 0; }
.board li .nm { flex: 1; } .board li.me { color: var(--good); }
/* live animated ranking board */
.livedot { font: 12px var(--head); color: var(--good); letter-spacing: .06em; vertical-align: middle; animation: pulse 1.6s ease-in-out infinite; }
@keyframes pulse { 50% { opacity: .35; } }
.board.live { max-height: 340px; margin-top: 10px; }
.board.live .brow { display: flex; align-items: center; gap: 9px; padding: 5px 8px; border-radius: 8px;
background: var(--panel2); border: 1px solid var(--line); margin-bottom: 5px; will-change: transform; }
.board.live .brow.me { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
.board.live .rk { width: 22px; text-align: center; font: 14px var(--head); color: var(--dim); }
.board.live .brow:nth-child(1) .rk { color: #f2c230; } .board.live .brow:nth-child(2) .rk { color: #cfd6e0; } .board.live .brow:nth-child(3) .rk { color: #d08a4a; }
.board.live .fl { width: 20px; flex: none; }
.board.live .nm { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.board.live .arrow { font-size: 10px; margin-left: 5px; animation: arrpop .9s ease-out; }
.board.live .arrow.up { color: var(--good); } .board.live .arrow.dn { color: #e5593b; }
@keyframes arrpop { 0% { transform: translateY(4px); opacity: 0; } 30% { opacity: 1; } 100% { opacity: .6; } }
.board.live .val { position: relative; width: 108px; flex: none; display: flex; align-items: center; justify-content: flex-end;
padding: 2px 8px; border-radius: 6px; overflow: hidden; background: #0d1016; }
.board.live .val .fill { position: absolute; left: 0; top: 0; bottom: 0; background: linear-gradient(90deg, var(--accent), #ffb060);
opacity: .3; transition: width .5s cubic-bezier(.2,.8,.2,1); }
.board.live .val b { position: relative; font-weight: 700; font-variant-numeric: tabular-nums; }
.muted { color: var(--dim); font-size: 13px; }
.row { display: flex; gap: 8px; justify-content: center; margin-top: 12px; flex-wrap: wrap; }
.credits { margin: 14px 0 0; font-size: 12px; color: var(--dim); }
.credits a { color: var(--accent); text-decoration: none; }
.credits .build { color: #5a6273; font-size: 10.5px; }
.credits a:hover { text-decoration: underline; }
.keys { display: grid; grid-template-columns: auto auto; gap: 3px 14px; text-align: left; margin: 10px auto 0; width: max-content; font-size: 13px; color: var(--dim); }
.keys b { color: var(--text); }
@@ -130,10 +162,17 @@
background: linear-gradient(90deg, rgba(4,5,8,.93) 0%, rgba(4,5,8,.8) 30%, rgba(4,5,8,0) 62%); }
.tpanel { width: 420px; padding: 0 20px 0 44px; display: flex; flex-direction: column; gap: 10px; text-align: left; }
.tlogoimg { width: 100%; max-height: 170px; object-fit: contain; object-position: left center;
filter: drop-shadow(0 6px 18px #000); animation: logoglow 3.6s ease-in-out infinite; }
@keyframes logoglow { 50% { filter: drop-shadow(0 6px 18px #000) drop-shadow(0 0 14px rgba(255,122,26,.45)); } }
transform-origin: left center; will-change: transform, filter;
filter: drop-shadow(0 6px 18px #000); animation: logoglow 3.6s ease-in-out infinite, logofloat 5s ease-in-out infinite, logoin .7s cubic-bezier(.2,1.3,.3,1) both; }
@keyframes logoglow { 50% { filter: drop-shadow(0 6px 18px #000) drop-shadow(0 0 16px rgba(255,122,26,.55)); } }
/* gentle idle motion: slow bob + slight tilt + breath (small amplitude, comfort-safe) */
@keyframes logofloat { 0%, 100% { transform: translateY(0) rotate(-0.6deg) scale(1); } 50% { transform: translateY(-7px) rotate(0.6deg) scale(1.02); } }
@keyframes logoin { 0% { opacity: 0; transform: translateY(18px) scale(.86); } 100% { opacity: 1; transform: translateY(0) scale(1); } }
.title .big { font: 62px var(--head); letter-spacing: .05em; color: var(--accent); line-height: .98;
text-shadow: 0 5px 0 #5a2600, 0 0 40px rgba(255,122,26,.5); }
transform-origin: left center; will-change: transform;
text-shadow: 0 5px 0 #5a2600, 0 0 40px rgba(255,122,26,.5);
animation: logofloat 5s ease-in-out infinite, bigglow 3.6s ease-in-out infinite, logoin .7s cubic-bezier(.2,1.3,.3,1) both; }
@keyframes bigglow { 50% { text-shadow: 0 5px 0 #5a2600, 0 0 64px rgba(255,122,26,.85); } }
.title .tag { color: #c9cfdc; margin: 0; text-shadow: 0 2px 4px #000; }
.hazbar { height: 5px; border-radius: 3px; background: var(--hazard); opacity: .9; }
.tmenu { display: flex; flex-direction: column; gap: 8px; margin-top: 4px; }
@@ -141,6 +180,21 @@
.trow2 { display: flex; gap: 6px; flex-wrap: wrap; }
.trow2 button { flex: 1 1 auto; font-size: 13px; min-height: 36px; padding: 4px 10px; }
.title .credits { margin-top: 10px; }
/* title: live ranking on the right, names fade in from the bottom up */
.trank { position: absolute; right: 40px; top: 50%; transform: translateY(-50%); width: 300px; max-width: 36vw;
background: rgba(12,14,19,.82); border: 1px solid var(--line); border-radius: 14px; padding: 13px 16px; box-shadow: var(--hl), 0 8px 30px #000a; }
.trank h3 { margin: 0 0 9px; font: 15px var(--head); letter-spacing: .05em; color: var(--accent); display: flex; align-items: center; gap: 8px; }
.trank ol { list-style: none; margin: 0; padding: 0; }
.trank .trow { display: grid; grid-template-columns: 18px 20px 1fr auto; gap: 8px; align-items: center; padding: 5px 2px; font-size: 13px;
font-variant-numeric: tabular-nums; border-bottom: 1px solid rgba(255,255,255,.06); opacity: 0; animation: trankin .5s ease-out both; }
.trank .trow:last-child { border-bottom: none; }
.trank .trow.me { color: var(--accent); font-weight: 700; }
.trank .trk { text-align: center; color: var(--dim); font-weight: 700; }
.trank .trow:nth-child(1) .trk { color: #f2c230; } .trank .trow:nth-child(2) .trk { color: #cfd6e0; } .trank .trow:nth-child(3) .trk { color: #d08a4a; }
.trank .trn { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.trank .trmuted { color: var(--dim); font-size: 13px; list-style: none; }
@keyframes trankin { from { opacity: 0; transform: translateY(18px); } to { opacity: 1; transform: translateY(0); } }
@media (max-width: 720px) { .trank { display: none; } } /* too narrow -> hide, title stays usable */
.skip { position: absolute; right: 16px; bottom: 12px; font-size: 12px; color: rgba(255,255,255,.55); }
.form { width: 320px; margin: 0 auto; text-align: left; display: flex; flex-direction: column; gap: 8px; }
.form label { font-size: 13px; color: var(--dim); }
@@ -155,18 +209,49 @@
.seg button { flex: 1 1 56px; padding: 5px 8px; font-size: 13px; }
.seg button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
/* compact settings: two columns of label + control */
.set2 { display: grid; grid-template-columns: 96px 1fr 96px 1fr; gap: 7px 12px; align-items: center; text-align: left; min-width: 680px; }
.set2 .sl, .setacc .sl { font-size: 13px; color: var(--dim); }
.set2 .seg button { padding: 6px 4px; font-size: 12px; min-height: 34px; }
.set2 input[type=range] { width: 100%; accent-color: var(--accent); height: 28px; }
.setacc { display: grid; grid-template-columns: 96px 1fr auto; gap: 12px; align-items: center; text-align: left; margin-top: 12px;
padding-top: 10px; border-top: 1px solid var(--line); }
.setacc .who { font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.set2 { display: grid; grid-template-columns: 88px 1fr 88px 1fr; gap: 5px 10px; align-items: center; text-align: left; min-width: 620px; }
.set2 .sl, .setacc .sl, .setdev .sl { font-size: 12px; color: var(--dim); }
.setdev { display: grid; grid-template-columns: 88px 1fr; gap: 8px; align-items: center; text-align: left; margin-top: 8px;
padding-top: 8px; border-top: 1px solid var(--line); }
.setdev .row { display: flex; gap: 6px; } .setdev .row button { flex: 1; min-height: 34px; font-size: 12px; }
.set2 .seg button { padding: 4px 4px; font-size: 11.5px; min-height: 34px; }
.set2 input[type=range] { width: 100%; accent-color: var(--accent); height: 24px; }
.setacc { display: grid; grid-template-columns: 88px 1fr auto; gap: 10px; align-items: center; text-align: left; margin-top: 8px;
padding-top: 8px; border-top: 1px solid var(--line); }
.setacc .who { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.selset { width: 100%; min-height: 34px; padding: 5px 8px; background: var(--panel2); color: var(--text); border: 1px solid var(--line); border-radius: 8px; font-size: 12.5px; }
/* first-start country picker */
.flaggrid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 12px 0 6px; }
.flagbtn { display: flex; flex-direction: column; align-items: center; gap: 5px; padding: 8px 4px; min-height: 48px;
background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; cursor: pointer; color: var(--text); font-size: 12px; }
.flagbtn .fl { width: 34px; height: 22px; }
.flagbtn.on { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; background: rgba(255,122,26,.14); }
@media (hover: hover) { .flagbtn:hover { border-color: var(--accent); } }
/* league */
/* tournament bracket */
.bracket { display: flex; gap: 10px; justify-content: center; align-items: center; margin: 10px 0; }
.tcol { display: flex; flex-direction: column; justify-content: space-around; gap: 6px; flex: 1; min-width: 0; }
.tch { font: 10px var(--head); letter-spacing: .08em; text-transform: uppercase; color: var(--dim); text-align: center; margin-bottom: 2px; }
.tpair { background: rgba(12,14,19,.7); border: 1px solid var(--line); border-radius: var(--r2); padding: 3px;
display: flex; flex-direction: column; gap: 3px; position: relative; }
.tpair.now { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,122,26,.3); }
.tslot { font-size: 11.5px; padding: 3px 7px; border-radius: var(--r1); background: var(--panel2);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--dim); }
.tslot.win { color: var(--text); font-weight: 700; }
.tslot .ki { font-size: 9px; background: #3c4556; color: #c9cfdc; border-radius: 3px; padding: 0 3px; vertical-align: middle; }
.tslot.you { background: #2a1c10; color: var(--accent); border: 1px solid var(--accent); }
.tslot.you.win { background: var(--accent); color: #1a0c02; }
.tgo { position: absolute; right: -9px; top: 50%; transform: translateY(-50%); background: var(--accent);
color: #1a0c02; font: 10px var(--head); padding: 2px 6px; border-radius: 5px; z-index: 1; white-space: nowrap; }
@media (hover: hover) { .tpair.now:hover { filter: brightness(1.1); } }
.clstabs { margin: 0 auto 10px; max-width: 520px; }
.clstabs button { flex: 1; padding: 6px 8px; font: 13px var(--head); letter-spacing: .03em; line-height: 1.25; }
.clstabs button small { display: block; font: 11px "Segoe UI", sans-serif; letter-spacing: 0; color: var(--dim); }
.clstabs button.on small { color: #4a2a08; }
.opps { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 10px 0; }
.opp { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 6px; text-align: center; position: relative; }
.opp > .pic { width: 100%; height: 92px; font-size: 56px; }
.opp > .pic { width: 100%; height: 78px; font-size: 48px; }
.opp .nm { font: 14px var(--head); letter-spacing: .03em; }
.opp .sm { font-size: 11px; color: var(--dim); min-height: 28px; }
.opp .pz { color: var(--gold); font-size: 13px; display: flex; gap: 4px; justify-content: center; align-items: center; }
@@ -183,11 +268,14 @@
.res .plus { color: var(--good); } .res .minus { color: var(--warn); }
/* shop */
#shop { position: absolute; inset: 44px 0 0; display: grid; grid-template-columns: 340px 1fr; z-index: 3; pointer-events: none; }
#shop { position: absolute; inset: 44px 0 0; display: grid; grid-template-columns: 1fr 560px; z-index: 3; pointer-events: none; }
#shop.hide, #fightHud.hide { display: none; }
#shop > * { pointer-events: auto; }
#sLeft { display: flex; flex-direction: column; padding: 12px; gap: 8px; pointer-events: none; }
/* left grid cell = the free area left of the shop panel; robot renders centered behind it */
#sLeft { position: relative; pointer-events: none; }
#sLeft > * { pointer-events: auto; }
.slTL { position: absolute; left: 14px; top: 12px; width: 230px; display: flex; flex-direction: column; gap: 8px; }
.slBottom { position: absolute; left: 50%; transform: translateX(-50%); bottom: 14px; width: min(96%, 660px); display: flex; flex-direction: column; align-items: center; gap: 6px; }
/* hangar: robot slots at the top of the shop */
.hangar { display: flex; gap: 5px; flex-wrap: wrap; margin-bottom: 4px; }
.hslot { display: inline-flex; align-items: center; gap: 5px; padding: 4px 9px; font-size: 12px; max-width: 120px; }
@@ -197,16 +285,17 @@
.hslot .hdel:hover { background: rgba(0,0,0,.25); opacity: 1; }
.hadd { padding: 4px 11px; font-size: 15px; font-weight: 700; color: var(--accent); }
/* name plate riveted to the robot, always readable (not only on hover) */
#rname { width: 100%; font: 24px var(--head); letter-spacing: .04em; background: rgba(11,14,20,.82);
#rname { width: 100%; font: 18px var(--head); letter-spacing: .04em; background: rgba(11,14,20,.82);
border: 1px solid var(--line); border-left: 3px solid var(--accent); border-radius: var(--r2);
color: var(--text); padding: 4px 10px; text-shadow: 0 2px 6px #000; box-shadow: var(--hl); }
#rname:hover, #rname:focus { border-color: var(--accent); outline: none; }
.mech { display: flex; gap: 8px; align-items: flex-end; }
.mech .pic { width: 50px; height: 60px; font-size: 34px; border-radius: 8px; overflow: hidden; background: rgba(0,0,0,.35); border: 1px solid var(--line); }
.mech .bubble { background: rgba(250,246,238,.95); color: #1b1d22; border-radius: 10px 10px 10px 2px; padding: 5px 8px; font-size: 12px; max-width: 262px; box-shadow: 0 4px 14px #0008; }
.mech .pic { width: 42px; height: 50px; font-size: 28px; border-radius: 8px; overflow: hidden; background: rgba(0,0,0,.35); border: 1px solid var(--line); }
.mech .bubble { background: rgba(250,246,238,.95); color: #1b1d22; border-radius: 10px 10px 10px 2px; padding: 6px 9px; font-size: 12px; line-height: 1.3; max-width: 240px; box-shadow: 0 4px 14px #0008; }
.spacer { flex: 1; pointer-events: none !important; }
.stats { background: rgba(12,14,19,.8); border: 1px solid var(--line); border-radius: 10px; padding: 6px 8px; display: grid; grid-template-columns: 1fr 1fr; gap: 3px 10px; font-size: 11px; font-variant-numeric: tabular-nums; }
.stats .st { display: grid; grid-template-columns: 18px 1fr 54px; gap: 5px; align-items: center; }
.stats { background: rgba(12,14,19,.88); border: 1px solid var(--line); border-radius: 12px; padding: 7px 12px; width: 100%;
display: flex; flex-wrap: wrap; justify-content: center; gap: 4px 16px; font-size: 12px; font-variant-numeric: tabular-nums; box-shadow: var(--hl); }
.stats .st { flex: 1 1 120px; display: grid; grid-template-columns: 18px 1fr 50px; gap: 6px; align-items: center; }
.stats .st > span:last-child { text-align: right; }
#shop.painting .mech, #shop.painting .stats { display: none; }
.stats .pic { width: 18px; height: 18px; font-size: 16px; }
@@ -214,11 +303,20 @@
.bar i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
.bar i.ghost { background: rgba(255,255,255,.35); }
.bar i.over { background: var(--warn); }
/* over-limit meter (weight / power) flashes so the problem is obvious at a glance */
.st.warn { animation: meterpulse 0.7s ease-in-out 4; border-radius: 6px; }
.st.warn .pic, .st.warn > span:last-child { color: var(--warn); font-weight: 700; }
.st.warn .bar i.over { animation: barpulse 0.7s ease-in-out infinite; }
@keyframes meterpulse { 0%, 100% { filter: none; } 50% { filter: brightness(1.9); } }
@keyframes barpulse { 0%, 100% { opacity: 1; } 50% { opacity: .45; } }
.gbar .err.alert { color: #fff; background: var(--warn); border-radius: 6px; padding: 3px 8px; font-size: 10.5px; font-weight: 700; line-height: 1.25;
box-shadow: 0 0 0 1px #000 inset, 0 2px 10px #0008; animation: errblink 0.46s steps(1, end) 6; }
@keyframes errblink { 0%, 100% { background: var(--warn); color: #fff; } 50% { background: #5a1410; color: #ffb9a6; } }
.paint { display: flex; gap: 3px; align-items: center; font-size: 11px; color: var(--dim); }
.paint span.sw { width: 15px; height: 15px; border-radius: 4px; border: 2px solid transparent; cursor: pointer; }
.paint span.sw.on { border-color: #fff; }
.paint .lb { width: 46px; }
#sRight { background: rgba(14,16,22,.9); border-left: 1px solid var(--line); display: flex; flex-direction: column; padding: 10px 12px; gap: 8px; min-height: 0; }
#sRight { background: rgba(14,16,22,.9); border-left: 1px solid var(--line); display: flex; flex-direction: column; padding: 10px 12px; gap: 8px; min-height: 0; width: 100%; max-width: 560px; margin-left: auto; }
#buildView { display: flex; flex-direction: column; gap: 8px; flex: 1; min-height: 0; }
#buildView.hide, #paintView.hide, #hangarView.hide { display: none; }
#paintView, #hangarView { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; }
@@ -229,15 +327,21 @@
/* zoom bar under the preview */
.zoombar { display: flex; align-items: center; justify-content: center; gap: 10px; font-size: 12px; color: var(--dim); margin-bottom: 2px; }
.zoombar button { width: 30px; height: 26px; padding: 0; font-size: 16px; font-weight: 700; }
.placebtn { width: 100%; min-height: 40px; font: 13px var(--head); letter-spacing: .03em; border-left: 3px solid var(--accent); }
.placebtn::before { content: '🔧 '; }
.placebtn.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); }
.placehint { font-size: 11.5px; color: var(--dim); background: rgba(8,10,14,.7); border: 1px solid var(--line);
border-radius: 8px; padding: 5px 8px; line-height: 1.3; }
.placehint.hide { display: none; }
/* fitted parts strip (bottom of the parts view): 7 compact chips, does not cover the robot preview */
.fittedwrap { border-top: 1px solid var(--line); padding-top: 5px; }
.flabel { font: 10.5px var(--head); letter-spacing: .12em; text-transform: uppercase; color: var(--dim); margin-bottom: 4px; }
.flabel { font: 10px var(--head); letter-spacing: .12em; text-transform: uppercase; color: var(--dim); margin-bottom: 3px; }
.fitted { display: grid; grid-template-columns: repeat(8, 1fr); gap: 4px; }
.fitted .frow { display: flex; flex-direction: column; align-items: center; gap: 1px; background: rgba(8,10,14,.75);
border: 1px solid #262c36; border-radius: var(--r1); padding: 3px 3px 2px; font-size: 11.5px; cursor: pointer;
border: 1px solid #262c36; border-radius: var(--r1); padding: 2px 3px; font-size: 11px; cursor: pointer;
position: relative; min-width: 0; box-shadow: none; }
@media (hover: hover) { .fitted .frow:hover { border-color: var(--accent); } }
.fitted .frow .pic { width: 18px; height: 18px; font-size: 14px; }
.fitted .frow .pic { width: 16px; height: 16px; font-size: 13px; }
.fitted .frow .fn { width: 100%; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fitted .frow .fn.empty { color: var(--dim); }
.fitted .frow .frm { position: absolute; top: -5px; right: -4px; font-size: 11px; color: #fff; background: var(--warn);
@@ -252,57 +356,126 @@
/* category tabs: a strip of folder tabs sitting ON the card panel - clearly navigation, not parts */
.tabs { display: grid; grid-template-columns: repeat(8, 1fr); gap: 3px; border-bottom: 2px solid var(--line); }
.tab { background: #141922; border: 1px solid var(--line); border-bottom: none;
border-radius: var(--r2) var(--r2) 0 0; margin-bottom: -2px; padding: 3px 2px 5px;
display: flex; flex-direction: column; align-items: center; gap: 1px; cursor: pointer;
font-size: 11.5px; letter-spacing: .02em; color: var(--dim); }
.tab .pic { width: 24px; height: 24px; font-size: 19px; }
border-radius: var(--r2) var(--r2) 0 0; margin-bottom: -2px; padding: 2px 2px 4px;
display: flex; flex-direction: column; align-items: center; gap: 0; cursor: pointer;
font-size: 10.5px; letter-spacing: .02em; color: var(--dim); }
.tab .pic { width: 20px; height: 20px; font-size: 16px; }
@media (hover: hover) { .tab:hover { border-color: var(--accent); } }
.tab.on { background: linear-gradient(#3a2414, #1d1410); border-color: var(--accent); color: var(--accent);
font-weight: 700; border-bottom: 2px solid #1d1410; } /* open tab merges into the panel below */
.tab.miss { border-color: var(--warn); }
#cards { flex: 1; min-height: 0; overflow-y: auto; display: grid; grid-template-columns: repeat(7, 1fr); gap: 6px;
align-content: start; padding: 9px; background: rgba(0,0,0,.26); border: 1px solid var(--line); border-top: none;
#designer { background: var(--panel2); background-image: var(--sheen); border: 1px solid var(--line);
border-left: 3px solid var(--accent); border-radius: var(--r2); box-shadow: var(--hl); padding: 5px 10px; }
#designer.hide { display: none; }
#designer.shut { padding: 3px 10px; }
#designer .dh { display: flex; align-items: center; gap: 8px; font: 11px var(--head); letter-spacing: .05em;
text-transform: uppercase; color: var(--accent); }
#designer.open .dh { margin-bottom: 3px; }
#designer .dh .dtitle { cursor: pointer; display: flex; align-items: center; gap: 6px; flex: 1; user-select: none; }
#designer .dh .dtitle .caret { font-size: 9px; opacity: .8; }
#designer .dh button { padding: 2px 9px; font-size: 11px; min-height: 0; }
#designer .drow { display: grid; grid-template-columns: 48px 1fr 34px; gap: 8px; align-items: center; font-size: 11px; margin: 2px 0; }
#designer .drow input[type=range] { width: 100%; accent-color: var(--accent); height: 20px; }
#designer .drow .dv { text-align: right; color: var(--dim); font-variant-numeric: tabular-nums; }
#cards { flex: 1; min-height: 0; overflow-y: auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(86px, 1fr)); gap: 6px;
align-content: start; padding: 8px; background: rgba(0,0,0,.26); border: 1px solid var(--line); border-top: none;
border-radius: 0 0 var(--r2) var(--r2); }
.item { background: linear-gradient(#252b37, #171b23); border: 1px solid #39414f; border-radius: var(--r2);
padding: 5px 5px 4px; cursor: pointer; text-align: center; position: relative;
box-shadow: var(--hl), 0 2px 0 rgba(0,0,0,.45); }
padding: 16px 4px 5px; cursor: pointer; text-align: center; position: relative; min-width: 0;
display: flex; flex-direction: column; gap: 2px; box-shadow: var(--hl), 0 2px 0 rgba(0,0,0,.45); }
@media (hover: hover) { .item:hover { border-color: #5a6478; } }
.item.sel { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,122,26,.3); }
.item > .pic { width: 100%; height: 52px; font-size: 38px; }
.item .nm { font-size: 12px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item .pr { font-size: 12px; color: var(--gold); display: flex; gap: 3px; justify-content: center; align-items: center;
.item > .pic { width: 100%; height: 42px; font-size: 30px; }
.item .nm { font-size: 11px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 100%; }
.item .pr { font-size: 11px; color: var(--gold); display: flex; gap: 3px; justify-content: center; align-items: center;
font-variant-numeric: tabular-nums; background: rgba(0,0,0,.3); border-radius: var(--r1); padding: 0 4px; margin: 2px auto 0; width: fit-content; }
.item .pr .pic { width: 14px; height: 14px; }
.item .pr.no { color: var(--warn); }
.item .badge { position: absolute; top: 5px; left: 5px; font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 6px; background: var(--accent); color: #1a0c02; }
/* badge as a thin ribbon across the top so it never overlaps the image */
.item .badge { position: absolute; top: 3px; left: 3px; right: 3px; text-align: center; font-size: 9px; font-weight: 700;
letter-spacing: .02em; padding: 1px 0; border-radius: 5px; background: var(--accent); color: #1a0c02; white-space: nowrap; overflow: hidden; }
.item .badge.own { background: #3c4556; color: var(--text); }
#detail { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; display: grid; grid-template-columns: 76px 1fr auto; gap: 10px; align-items: center; min-height: 86px; }
#detail > .pic { width: 76px; height: 76px; font-size: 52px; }
#detail .nm { font: 17px var(--head); letter-spacing: .03em; }
#detail .ds { font-size: 12.5px; color: var(--dim); margin: 2px 0 5px; }
.chips { display: flex; flex-wrap: wrap; gap: 4px; }
.chips span { background: #0f1218; border: 1px solid var(--line); border-radius: 6px; padding: 1px 6px; font-size: 11.5px; display: inline-flex; gap: 3px; align-items: center; font-variant-numeric: tabular-nums; }
.chips span .pic { width: 13px; height: 13px; font-size: 11px; }
#detail { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 6px 9px; display: grid; grid-template-columns: 46px 1fr auto; gap: 9px; align-items: center; min-height: 56px; }
#detail > .pic { width: 46px; height: 46px; font-size: 32px; }
#detail .nm { font: 15px var(--head); letter-spacing: .03em; }
#detail .ds { font-size: 11.5px; color: var(--dim); margin: 1px 0 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.chips { display: flex; flex-wrap: wrap; gap: 3px; }
.chips span { background: #0f1218; border: 1px solid var(--line); border-radius: 6px; padding: 1px 5px; font-size: 11px; display: inline-flex; gap: 3px; align-items: center; font-variant-numeric: tabular-nums; }
.chips span .pic { width: 12px; height: 12px; font-size: 10px; }
.chips span.up { color: var(--good); border-color: #2e5a3e; } .chips span.down { color: var(--warn); border-color: #5a2e2e; }
.chips span.key { color: var(--accent); border-color: #5a3a18; background: #1d1409; font-weight: 700; }
#detail .act { display: flex; flex-direction: column; gap: 6px; min-width: 120px; }
#detail .act button { padding: 8px 10px; min-height: 40px; }
#detail .act .primary { min-height: 44px; font-size: 15px; }
#detail .act { display: flex; flex-direction: column; gap: 5px; min-width: 116px; }
#detail .act button { padding: 7px 10px; min-height: 36px; }
#detail .act .primary { min-height: 42px; font-size: 14px; }
.gbar { display: flex; gap: 6px; align-items: center; }
.gbar .err { flex: 1; margin: 0; font-size: 12px; text-align: left; }
.gbar .primary { padding: 9px 26px; }
/* paint tab: proper colour chips instead of tiny dots */
#paintView { gap: 10px; }
.psec h4 { margin: 0 0 6px; font: 12px var(--head); letter-spacing: .1em; text-transform: uppercase; color: var(--dim); }
.pgrid { display: grid; grid-template-columns: repeat(12, 1fr); gap: 7px; }
.pgrid.wide { grid-template-columns: repeat(8, 1fr); }
.pgrid .sw { position: relative; height: 40px; border-radius: var(--r2); border: 2px solid #000a;
#hud .rank { font-size: 11.5px; color: var(--dim); letter-spacing: .02em; }
.htour { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700;
font-size: 13px; animation: tourpulse 1.6s ease-in-out infinite; }
@keyframes tourpulse { 50% { box-shadow: 0 0 0 3px rgba(255,122,26,.35); } }
.htour.hide { display: none; }
/* backend news + running event */
.motd { margin: 6px 0 0; font-size: 13px; color: #c9cfdc; text-shadow: 0 2px 4px #000; }
.evbar { display: inline-flex; align-items: center; gap: 8px; margin: 6px 0 0; padding: 5px 10px;
background: rgba(255,122,26,.16); border: 1px solid var(--accent); border-radius: var(--r2);
font-size: 13px; text-align: left; }
.evbar b { font: 13px var(--head); letter-spacing: .04em; color: var(--accent); }
.chip.clickable { cursor: pointer; }
@media (hover: hover) { .chip.clickable:hover { border-color: var(--accent); } }
/* achievements */
.achwon { margin: 10px auto 0; max-width: 340px; text-align: left; font-size: 13px;
background: rgba(255,122,26,.1); border: 1px solid var(--accent); border-radius: var(--r2); padding: 8px 10px; }
.achwon b { display: block; margin-bottom: 4px; color: var(--accent); font: 13px var(--head); letter-spacing: .04em; }
.achwon div { display: flex; justify-content: space-between; gap: 10px; }
.rankbar { margin: 4px 0 12px; }
.rankbar .rt { display: flex; justify-content: space-between; align-items: baseline; font-size: 13px; margin-bottom: 4px; }
.rankbar .rt b { font: 17px var(--head); color: var(--accent); letter-spacing: .03em; }
.achlist { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; text-align: left; }
.achrow { display: grid; grid-template-columns: 24px 1fr auto; gap: 8px; align-items: center; font-size: 12.5px;
background: var(--panel2); background-image: var(--sheen); border: 1px solid var(--line);
border-radius: var(--r2); padding: 6px 9px; box-shadow: var(--hl); }
.achrow.done { border-color: var(--good); }
.achrow.todo { opacity: .55; }
.achrow .an { font-weight: 700; }
.achrow .ad { font-size: 11.5px; color: var(--dim); font-weight: 400; }
.achrow .am { font-size: 16px; text-align: center; }
/* missions page */
.misslist { display: flex; flex-direction: column; gap: 6px; margin: 4px 0 12px; text-align: left; }
.missrow { display: grid; grid-template-columns: 24px 1fr auto; gap: 10px; align-items: center; background: var(--panel2);
border: 1px solid var(--line); border-radius: 10px; padding: 7px 10px; }
.missrow.done { border-color: var(--good); }
.missrow .mm { font-size: 18px; text-align: center; }
.missrow .mn { font-weight: 700; font-size: 13px; }
.missrow .md { font-size: 11.5px; color: var(--dim); margin: 1px 0 4px; }
.missrow .mi .bar { height: 7px; }
.missrow .mr { text-align: right; display: flex; flex-direction: column; gap: 2px; font-size: 12px; white-space: nowrap; }
.missrow .mp { font-variant-numeric: tabular-nums; color: var(--dim); font-size: 11px; }
#bMissions { position: relative; }
#bMissions.alert::after { content: ''; position: absolute; top: 3px; right: 5px; width: 7px; height: 7px; border-radius: 50%;
background: var(--accent); box-shadow: 0 0 6px var(--accent); }
/* legal pages (Impressum / Datenschutz) */
.legalseg { margin: 6px auto 10px; max-width: 360px; }
.legaltext { max-height: 48vh; overflow: auto; text-align: left; font-size: 13px; line-height: 1.5; color: var(--text);
background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 10px 14px; }
.legaltext p { margin: 0 0 9px; color: inherit; }
.legaltext b { color: var(--accent); }
.pgrid .sw.locked { cursor: not-allowed; opacity: .55; }
.pgrid .sw .lk { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; font-size: 10px; text-shadow: 0 1px 2px #000; }
/* paint tab: compact colour chips (must fit without scrolling) */
#shop.paintmode #tabs, #shop.paintmode #detail, #shop.paintmode #fittedwrap { display: none !important; }
.psec { margin: 0 0 2px; }
.psec h4 { margin: 0 0 2px; font: 8.5px var(--head); letter-spacing: .08em; text-transform: uppercase; color: var(--dim); }
.pgrid { display: grid; grid-template-columns: repeat(16, 1fr); gap: 3px; }
.pgrid.wide { grid-template-columns: repeat(10, 1fr); }
.pgrid .sw { position: relative; height: 16px; border-radius: var(--r1); border: 1.5px solid #000a;
cursor: pointer; box-shadow: var(--hl), 0 2px 0 rgba(0,0,0,.4); transition: transform .1s; }
@media (hover: hover) { .pgrid .sw:hover { transform: translateY(-2px); } }
.pgrid .sw.on { border-color: #fff; box-shadow: 0 0 0 2px var(--accent); }
.pgrid .sw.on::after { content: '✓'; position: absolute; inset: 0; display: flex; align-items: center;
justify-content: center; color: #fff; font-size: 19px; font-weight: 700; text-shadow: 0 1px 3px #000; }
justify-content: center; color: #fff; font-size: 10px; font-weight: 700; text-shadow: 0 1px 3px #000; }
.pgrid .duo { display: flex; overflow: hidden; }
.pgrid .duo i { flex: 1; }
.pcustom { display: grid; grid-template-columns: 1fr auto; gap: 12px; align-items: center;
@@ -376,6 +549,8 @@
.rroom .cnt.live { color: var(--good); font-weight: 700; }
.rroom.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
.rroom.on .cnt { color: #1a0c02; }
.rroom.joined:not(.on) { border-color: var(--accent); }
.rroom .rhere { font-size: 10px; }
.lobbyRh { display: flex; align-items: center; gap: 8px; font: 18px var(--head); letter-spacing: .03em; margin-bottom: 8px; }
.lobbyRh .grow { flex: 1; }
.lobbyRh .flagpick { font: 12px "Segoe UI", sans-serif; color: var(--dim); display: flex; gap: 6px; align-items: center; }
@@ -451,6 +626,87 @@
#dmgvig { position: absolute; inset: 0; z-index: 3; pointer-events: none; opacity: 0; transition: opacity .25s;
background: radial-gradient(ellipse at 50% 50%, transparent 45%, rgba(190,20,10,.75) 100%); }
/* spawn gate: two steel garage-door halves that split open when a fight starts */
#gate { position: absolute; inset: 0; z-index: 8; pointer-events: none; overflow: hidden; }
#gate.hide { display: none; }
#gate .gh { position: absolute; left: 0; right: 0; height: 50%;
background:
radial-gradient(circle at 14px 14px, rgba(255,255,255,.12) 0 2px, transparent 3px),
repeating-linear-gradient(180deg, rgba(0,0,0,.35) 0 2px, transparent 2px 26px),
linear-gradient(90deg, #22272f 0%, #3c4452 48%, #434b59 52%, #22272f 100%);
background-size: 28px 28px, auto, auto;
box-shadow: inset 0 0 70px rgba(0,0,0,.65);
transition: transform .85s cubic-bezier(.55,.03,.3,1); will-change: transform; }
#gate .gh-top { top: 0; } #gate .gh-bot { bottom: 0; }
#gate .gh::after { content: ''; position: absolute; left: 0; right: 0; height: 11px; background: var(--hazard); opacity: .95; }
#gate .gh-top::after { bottom: 0; } #gate .gh-bot::after { top: 0; }
#gate.open .gh-top { transform: translateY(-100%); }
#gate.open .gh-bot { transform: translateY(100%); }
/* build editor: fills the shop panel in place of the parts view (robot stays on the left) */
/* weapon placement + shape: small panel, top-right of the live-view area */
#wplace { position: absolute; right: 14px; top: 12px; width: 198px; background: rgba(12,14,19,.9); border: 1px solid var(--line);
border-radius: 10px; padding: 7px 9px; display: flex; flex-direction: column; gap: 4px; box-shadow: var(--hl); }
#wplace.hide { display: none; }
#wplace .wphead { font: 10px var(--head); letter-spacing: .06em; text-transform: uppercase; color: var(--accent); margin-top: 2px; }
#wplace .wpsides { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; }
#wplace .wpsides button { min-height: 30px; font-size: 11px; padding: 2px; }
#wplace .wpsides button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
#wplace .wprow { display: grid; grid-template-columns: 54px 1fr 36px; gap: 6px; align-items: center; font-size: 11px; }
#wplace .wprow input[type=range] { width: 100%; accent-color: var(--accent); height: 16px; }
#wplace .wprow .dv { text-align: right; color: var(--dim); font-variant-numeric: tabular-nums; }
#wplace .weplist { display: flex; flex-wrap: wrap; gap: 4px; }
#wplace .wepchip { display: flex; align-items: center; gap: 4px; padding: 2px 6px; min-height: 26px; border: 1px solid var(--line); border-radius: 7px; background: #141922; cursor: pointer; font-size: 11px; }
#wplace .wepchip.on { border-color: var(--accent); background: #2a1c10; }
#wplace .wepchip .pic { width: 16px; height: 16px; }
#wplace .wepchip .x { color: var(--warn); font-weight: 700; padding: 0 1px; font-size: 12px; }
#wplace .edhint { font-size: 10.5px; color: var(--dim); }
.item.dim { opacity: .5; }
.pbtn { width: 100%; min-height: 44px; font-size: 16px; }
/* paint / hangar / weapon editor all render inside #cards; override the parts grid */
#cards.wedit { display: flex; flex-direction: column; grid-template-columns: none; gap: 7px; padding: 9px; }
#cards.pcards { display: flex; flex-direction: column; grid-template-columns: none; gap: 6px; padding: 7px; overflow: hidden; }
#cards.hcards { display: flex; flex-direction: column; grid-template-columns: none; gap: 6px; padding: 10px; }
/* paint tab: 3 save slots + inline painter */
.phdr { display: flex; flex-direction: column; gap: 4px; }
.pslots { display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px; }
.pslot { position: relative; height: 22px; border-radius: 6px; border: 2px solid #000a; cursor: pointer; overflow: hidden; }
.pslot.on { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent); }
.pslot .acc { position: absolute; left: 0; right: 0; bottom: 0; height: 7px; }
.pslot .dmark { position: absolute; top: 1px; left: 4px; font-size: 11px; text-shadow: 0 1px 2px #000; }
.pslot .sv { position: absolute; top: 2px; right: 2px; min-height: 0; padding: 0 4px; font-size: 10px; line-height: 1.3; }
#painter.inline { position: static; grid-column: auto; grid-row: auto; background: none; border: none; padding: 0; gap: 6px; }
#painter.inline .pt-head { display: none; }
#painter.inline #ptCancel, #painter.inline #ptDone { display: none; }
#painter.inline .pt-canvas canvas { width: 100%; height: auto; max-height: 184px; aspect-ratio: 2 / 1; margin: 0 auto; }
#painter.inline .pt-tools button, #painter.inline .pt-colors .sw, #painter.inline .gbar button { padding: 3px 6px; font-size: 11px; }
#painter.inline .pt-row { margin: 2px 0; }
#painter.inline .gbar { border-top: none; padding-top: 0; }
.wedit .edsec { background: var(--panel2); border: 1px solid var(--line); border-radius: 9px; padding: 7px 9px; }
.wedit .edlabel { font: 10px var(--head); letter-spacing: .08em; text-transform: uppercase; color: var(--dim); margin-bottom: 5px; }
.wedit .weplist { display: flex; flex-wrap: wrap; gap: 5px; }
.wedit .wepchip { display: flex; align-items: center; gap: 5px; padding: 3px 7px; min-height: 30px; border: 1px solid var(--line);
border-radius: 8px; background: #141922; cursor: pointer; font-size: 12px; }
.wedit .wepchip.on { border-color: var(--accent); background: #2a1c10; }
.wedit .wepchip .pic { width: 18px; height: 18px; }
.wedit .wepchip .x { color: var(--warn); font-weight: 700; padding: 0 2px; font-size: 13px; }
.wedit .addrow { display: grid; grid-template-columns: repeat(6, 1fr); gap: 4px; margin-top: 6px; }
.wedit .addrow button { min-height: 36px; font-size: 9.5px; padding: 3px 2px; display: flex; flex-direction: column; align-items: center; gap: 1px; line-height: 1.1; }
.wedit .addrow button .pic { width: 18px; height: 18px; }
.wedit .addrow button .pr { color: var(--gold); font-size: 9px; }
.wedit .addrow button:disabled { opacity: .4; }
.wedit .sides { display: grid; grid-template-columns: repeat(4, 1fr); gap: 5px; }
.wedit .sides button { min-height: 34px; font-size: 11.5px; }
.wedit .sides button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
.wedit .erow { display: grid; grid-template-columns: 50px 1fr 38px; gap: 8px; align-items: center; font-size: 11px; margin: 3px 0; }
.wedit .erow input[type=range] { width: 100%; accent-color: var(--accent); height: 18px; }
.wedit .erow .dv { text-align: right; color: var(--dim); font-variant-numeric: tabular-nums; }
.wedit .edhint { font-size: 11px; color: var(--dim); line-height: 1.3; }
.wedit .edmeters { display: flex; flex-wrap: wrap; gap: 7px; font-size: 11.5px; }
.wedit .edmeters b { color: var(--text); }
.wedit .edmeters .over { color: var(--warn); }
/* touch pad: only on touch screens */
#pad { position: absolute; left: 14px; right: 14px; bottom: 14px; display: none; justify-content: space-between; pointer-events: none; z-index: 5; }
#pad > div { display: grid; grid-template-columns: repeat(3, 60px); gap: 6px; pointer-events: auto; }
@@ -491,11 +747,15 @@
<div id="shop" class="hide">
<div id="sLeft">
<input id="rname" maxlength="18" spellcheck="false">
<div class="zoombar"><button id="zOut" title="Zoom -">-</button><span data-i18n="zoom">Zoom</span><button id="zIn" title="Zoom +">+</button></div>
<div class="spacer"></div>
<div class="stats" id="meters"></div>
<div class="mech"><span class="pic" data-f="🧔" id="mechPic"></span><div class="bubble" id="mechTip"></div></div>
<div class="slTL">
<input id="rname" maxlength="18" spellcheck="false">
<div class="mech"><span class="pic" data-f="🧔" id="mechPic"></span><div class="bubble" id="mechTip"></div></div>
</div>
<div id="wplace" class="hide"></div>
<div class="slBottom">
<div class="zoombar"><button id="zOut" title="Zoom -">-</button><span data-i18n="zoom">Zoom</span><button id="zIn" title="Zoom +">+</button></div>
<div class="stats" id="meters"></div>
</div>
</div>
<div id="sRight">
<div class="shoptabs" id="shopTabs"></div>
@@ -503,25 +763,17 @@
<div class="tabs" id="tabs"></div>
<div id="cards"></div>
<div id="detail"></div>
<div class="fittedwrap"><div class="flabel" data-i18n="fitted_parts">Fitted</div><div id="fitted" class="fitted"></div></div>
<div id="designer" class="hide"></div>
<div id="fittedwrap" class="fittedwrap"><div class="flabel" data-i18n="fitted_parts">Fitted</div><div id="fitted" class="fitted"></div></div>
</div>
<div id="paintView" class="hide">
<div class="psec"><h4 data-i18n="paint_body">Body</h4><div class="pgrid" id="paintBody"></div></div>
<div class="psec"><h4 data-i18n="paint_accent">Accent</h4><div class="pgrid" id="paintAccent"></div></div>
<div class="psec"><h4 data-i18n="paint_schemes">Schemes</h4><div class="pgrid wide" id="paintSchemes"></div></div>
<div class="spacer"></div>
<div class="pcustom">
<div class="pct"><b data-i18n="pt_open">Paint it yourself</b><span class="muted" data-i18n="paint_hint">Pick quick colours above, or paint your own design.</span></div>
<button id="bPaint" class="primary">🎨</button>
</div>
</div>
<div id="hangarView" class="hide"></div>
<div class="gbar">
<div class="err" id="gErr"></div>
<button id="bGMenu" data-i18n="menu">Menu</button>
<button id="bGOnline" data-i18n="online_short">Online</button>
<button id="bGMode">Kampagne</button>
<button id="bRankG" style="display:none">🏆</button>
<button id="bMissions" style="display:none">🎯</button>
<button id="bTrain" data-i18n="training">Training</button>
<button class="primary" id="bLeague" data-i18n="to_league">League</button>
<button class="primary" id="bLeague">League</button>
</div>
</div>
</div>
@@ -547,14 +799,16 @@
<div id="hud">
<div class="logo">ROBOT CLASH</div>
<div class="chip" data-i18n-title="hud_money"><span class="pic" data-f="🪙" id="icoMoney"></span><b id="hMoney">0</b></div>
<div class="chip" data-i18n-title="hud_fame"><span class="pic" data-f="⭐" id="icoFame"></span><b id="hFame">0</b></div>
<div class="chip"><span data-i18n="hud_league">League</span> <b id="hLeague">-</b></div>
<div class="chip clickable" id="chipFame" data-i18n-title="achievements"><span class="pic" data-f="⭐" id="icoFame"></span><b id="hFame">0</b><span id="hRank" class="rank"></span></div>
<div class="chip"><span id="hModeLbl">League</span> <b id="hLeague">-</b></div>
<button id="hTour" class="chip clickable htour hide">🏆</button>
<div class="grow"></div>
<div class="chip" id="hUser" data-i18n-title="account"></div>
<button id="bSettings" class="icobtn" data-i18n-title="settings">⚙</button>
<button id="bMute" class="icobtn" title="M">🔊</button>
<button id="bPause" class="icobtn" title="P / Esc" data-i18n-title="pause">⏸</button>
</div>
<div id="gate" class="hide"><div class="gh gh-top"></div><div class="gh gh-bot"></div></div>
<div id="overlay" class="hide"></div>
</div>
</div>
@@ -570,18 +824,33 @@
<script src="kit/kit-i18n.js"></script>
<script src="lang.js"></script>
<script src="parts.js"></script>
<script src="progress.js"></script>
<script src="live.js"></script>
<script src="ltourney.js"></script>
<script src="tourney.js"></script>
<script src="robot.js"></script>
<script src="eco.js"></script>
<script src="protocol.js"></script>
<script src="combat.js"></script>
<script src="ai.js"></script>
<script src="profiles.js"></script>
<script src="net.js"></script>
<script src="cloudsave.js"></script>
<script src="ranking.js"></script>
<script src="missions.js"></script>
<script src="lobby.js"></script>
<script src="looks.js"></script>
<script src="render3d.js"></script>
<script src="netfight.js"></script>
<script src="netstats.js"></script>
<script src="netoverlay.js"></script>
<script src="shop.js"></script>
<script src="painter.js"></script>
<script src="uicheck.js"></script>
<script src="sfx.js"></script>
<script src="pages.js"></script>
<script src="online.js"></script>
<script src="workshop.js"></script>
<script src="game.js"></script>
</body>
</html>

View File

@@ -9,6 +9,43 @@ window.LANG = {
league_chip: 'S{s} · {n}/{m}',
sound_on: 'Sound on', sound_off: 'Sound off', pause: 'Pause',
win_min: 'Minimise', win_full: 'Fullscreen (F11)', win_close: 'Close',
event: 'Event', event_running: 'Event running', event_prize: 'prize money x{n}', event_bonus: 'Event bonus', tour_free: 'Tournament (free)', tour_join: 'Join tournament ({n})', tour_join_free: 'Join tournament (free)',
reload_now: 'Reload', reload_skip: 'Play anyway',
reload_title: 'New version', reload_text: 'A newer version of Robot Clash is online. Please reload the page (Ctrl+F5).',
cls_light: 'Lightweight', cls_medium: 'Middleweight', cls_heavy: 'Heavyweight',
tournament: 'Tournament', tour_enter: 'Tournament ({n})', tour_continue: 'Tournament', tour_fight: 'Fight',
tour_round_quarter: 'Quarter final', tour_round_semi: 'Semi final', tour_round_final: 'Final',
tour_left: '{n} robots left', tour_beat: 'beat', title_campaign: 'Campaign', title_online: 'Online', ltour_title: 'Live Tournament', ltour_ready: 'ready', ltour_waiting: 'not ready', ltour_setready: "I'm ready", ltour_unready: 'Not ready', ltour_empty: 'No one here yet - invite a friend!', ltour_lobby: '{n} ready (2 needed to start)', ltour_countdown: 'Starts in {n} s...', ltour_wait_round: 'Waiting for the other matches...', ai_tag: 'AI', tour_champion: 'Champion', tour_your_match: 'your match: {name}', tour_round_prize: 'Round prize', tour_trophy: 'Trophy',
tour_won: 'Tournament won!', tour_won_text: 'The whole bracket, beaten. Prize money: {n}.',
tour_out: 'Knocked out', tour_out_text: 'That is the end of the run. You take {n} with you.',
ach_tourney: 'Bracket Buster', achd_tourney: 'Win a tournament',
achievements: 'Achievements', ach_new: 'Unlocked', ach_done: '{n} of {m} done',
rank_next: 'to {n}: {f} fame', rank_top: 'top rank reached',
rank_scrap: 'Scrap Hauler', rank_rookie: 'Rookie', rank_contender: 'Contender', rank_pro: 'Pro',
rank_veteran: 'Veteran', rank_champion: 'Champion', rank_master: 'Master', rank_legend: 'Legend',
ach_first_win: 'First Blood', achd_first_win: 'Win a fight',
ach_ko: 'Lights Out', achd_ko: 'Win by knockout',
ach_pit: 'Down You Go', achd_pit: 'Push someone into the pit',
ach_tough: 'On The Ropes', achd_tough: 'Win with under 15% health left',
ach_flawless: 'Not A Scratch', achd_flawless: 'Win above 90% health, nothing broken off',
ach_demolition: 'Demolition', achd_demolition: 'Deal 600 damage in one fight',
ach_champion: 'Season Champion', achd_champion: 'Beat the whole league',
ach_veteran: 'Old Hand', achd_veteran: 'Fight 25 matches',
ach_rich: 'Loaded', achd_rich: 'Hold 5,000 credits',
ach_collector: 'Collector', achd_collector: 'Own 20 parts',
ach_garage: 'Full Garage', achd_garage: 'Keep 3 robots',
ach_artist: 'Own Colours', achd_artist: 'Paint your own design',
mode_online: 'Online', mode_campaign: 'Campaign', mode_pvp: 'vs. players', to_lobby: 'Lobby',
to_campaign: 'To campaign', to_online: 'To online', rank_live: 'LIVE',
mode_switched: 'Separate game - own money and parts',
click_start: 'Click or press any key to start',
tut_title: 'Quick start', tut_next: 'Next', tut_skip: 'Skip', tut_go: "Let's build",
tut_1: 'Every robot needs four parts: chassis, motor, wheels and a battery. You pick them under Parts.',
tut_2: 'A weapon is optional - without one you can only ram. A wedge is cheap, a flipper throws them over.',
tut_3: 'Watch the two bars on the left: 100 kg is the limit, and your battery has to power every part.',
tut_4: 'Then press LEAGUE. Even a defeat pays a little, and prize money buys better parts.',
tut_controls: 'W/S drive · A/D turn · Space weapon · Shift tower · G gadget · C camera',
wrong_host: 'This copy of Robot Clash may only be played on michael-media.de.',
no_webgl: 'This game needs WebGL (3D graphics). Please use a current browser or update the graphics driver.',
menu_text: 'Build your combat robot from parts, fight your way up the league<br>and send your opponents into the pit.',
name_placeholder: 'Your name',
@@ -33,7 +70,7 @@ window.LANG = {
st_supply: 'supplies {n} power', st_power: 'needs {n} power',
m_weight: 'Weight', m_power: 'Power', m_hp: 'Hit points', m_armour: 'Armour', m_speed: 'Speed', m_accel: 'Accel.', m_turn: 'Turning',
paint_body: 'Paint', paint_accent: 'Accent',
err_need: '{slot} missing', err_bad: '{slot} invalid', err_overweight: 'Too heavy (max 100 kg)', err_no_power: 'Battery too weak',
err_need: '{slot} missing', err_bad: '{slot} invalid', err_overweight: 'Too heavy (max {n} kg)', err_no_power: 'Battery too weak - stronger battery or less draw', err_too_many_weapons: 'Too many weapons (max 3)',
pd_crate: 'Simple steel box. Cheap and honest.',
pd_doorstop: 'Low wedge shape - hard to flip.',
pd_bulwark: 'Heavy frame with lots of hit points.',
@@ -42,6 +79,9 @@ window.LANG = {
pd_hornet: 'Faster all-rounder.',
pd_bulldog: 'Huge torque for pushing.',
pd_comet: 'Top speed for hit and run.',
pd_pico: 'Tiny cheap motor - weak but featherlight, good for a lightweight.',
pd_turbine: 'A solid all-round motor, decent push and speed.',
pd_titandrive: 'Monster torque to shove the heaviest builds, but slow and heavy.',
pd_rubber: 'Four small wheels, nimble.',
pd_cage: 'Open scrap frame: dirt cheap and light, but it dents fast.',
pd_hexpod: 'Six-sided shell, angled all round so hits glance off.',
@@ -49,6 +89,9 @@ window.LANG = {
pd_fang: 'Long pointed prow, low and quick - hard to flip.',
pd_plough: 'Heavy plough blade bolted to the nose, shrugs off front hits.',
pd_discus: 'Wide flat disc, sits low and takes a beating.',
pd_orb: 'Round armoured ball - hits glance off from every side.',
pd_tower: 'Tall upright build - towers over rivals, but tips easily.',
pd_slab: 'Very wide and flat - almost impossible to flip over.',
pd_omni: 'Caster wheels: spins on the spot, great steering.',
pd_bigtyre: 'Taller than the robot: keeps driving when flipped.',
pd_studs: 'Studded grip, drives upside down, strong shove.',
@@ -58,6 +101,8 @@ window.LANG = {
pd_lead: 'Heavy, but it works.',
pd_nicd: 'More power, less weight.',
pd_lipo: 'Light and powerful.',
pd_liion: 'Big cell block - runs a heavy weapon and a turret together.',
pd_supercap: 'Supercapacitor bank: the most power there is, and it weighs accordingly.',
pd_mesh: 'Thin wire grille - barely any weight, barely any protection.',
pd_buffer: 'Fat rubber buffers that soak up rams.',
pd_spiked: 'Plates with spikes, and they look the part.',
@@ -89,6 +134,7 @@ window.LANG = {
pd_shield: 'Field that cuts damage for a few seconds (G).',
pd_repair: 'Patches hull - two charges (G).',
pd_emp: 'Stuns a nearby enemy for a moment (G).',
pd_mines: 'Drops a mine behind you (G). It arms after a second - whoever drives over it gets thrown into the air. That includes you.',
// league
league_title: 'League - season {s}',
league_text: 'Beat the opponents one after another. Each season they get tougher and pay more.',
@@ -130,7 +176,27 @@ window.LANG = {
e_pass_short: 'Password needs at least 4 characters.', e_pass_match: 'Passwords do not match.',
e_unknown: 'No account with this name.', e_wrong_pass: 'Wrong password.',
// settings
s_lang: 'Language', s_music: 'Music', s_sfx: 'Effects', s_mute: 'Sound', s_gfx: 'Graphics', s_intro: 'Intro at start',
s_lang: 'Language', s_country: 'Country', s_music: 'Music', s_sfx: 'Effects', s_mute: 'Sound', s_gfx: 'Graphics', s_intro: 'Intro at start',
s_comfort: 'Comfort (less motion)',
missions: 'Missions', miss_daily: 'Daily', miss_weekly: 'Weekly', miss_reset_in: 'resets in {n}h', miss_complete: 'Mission complete!', paint_locked: 'Locked - earn it from a mission',
mission_d_win3: 'Win streak', missd_d_win3: 'Win 3 fights',
mission_d_play5: 'Warm-up', missd_d_play5: 'Fight 5 battles',
mission_d_dmg800: 'Heavy hitter', missd_d_dmg800: 'Deal 800 damage',
mission_d_ko2: 'Double K.O.', missd_d_ko2: 'K.O. 2 opponents',
mission_d_pit1: 'Into the pit', missd_d_pit1: 'Win 1 fight by pit',
mission_d_flaw1: 'Untouched', missd_d_flaw1: 'Win keeping every part (>=90% HP)',
mission_d_foundry: 'Foundry duel', missd_d_foundry: 'Win in the Foundry',
mission_d_colosseum: 'Colosseum', missd_d_colosseum: 'Win in the Colosseum',
mission_d_spin: 'Spin to win', missd_d_spin: 'Win with a spinner weapon',
mission_d_hammer: 'Hammer time', missd_d_hammer: 'Win with a hammer/axe',
mission_w_win15: 'Veteran week', missd_w_win15: 'Win 15 fights',
mission_w_dmg6000: 'Demolition week', missd_w_dmg6000: 'Deal 6000 damage',
mission_w_ko8: 'Knockout artist', missd_w_ko8: 'K.O. 8 opponents',
mission_w_flaw3: 'Flawless run', missd_w_flaw3: 'Win 3 flawless fights',
legal: 'Legal', legal_impressum: 'Imprint', legal_privacy: 'Privacy', consent_pre: 'I accept the', consent_required: 'Please accept the privacy policy.',
impressum_text: '<p><b>Information pursuant to § 5 DDG (German law)</b></p><p>[Name / provider]<br>[Address – e.g. c/o imprint service]<br>[Postcode, City]</p><p><b>Contact</b><br>Email: [contact@your-domain]</p><p class="muted">Note: fill in your real data. A deliverable address suffices (e.g. via an imprint / c-o service) — a private home address is not required.</p>',
privacy_text: '<p><b>Privacy policy</b></p><p>Controller: [Name], [contact email].</p><p><b>What data?</b> On registration: your email and an encrypted password hash; while playing: your save data, chosen country flag and — online — your lobby presence (name, status). The server keeps access data (IP address, time) in log files for technical reasons.</p><p><b>Why?</b> To run your account, store progress, the online lobby/ranking and to secure the server (Art. 6(1)(b) and (f) GDPR).</p><p><b>Hosting:</b> The server is hosted at Hetzner in Germany under a data-processing agreement.</p><p><b>Storage:</b> Account/save until you delete it; server logs only briefly.</p><p><b>Cookies/tracking:</b> Only technically necessary storage (localStorage, login token) — no tracking, no ads, no sharing with third parties.</p><p><b>Your rights:</b> access, rectification, erasure, objection and complaint to a supervisory authority. Contact: [contact email].</p><p class="muted">Template — please have it reviewed (lawyer / generator) and add your own data.</p>',
country_title: 'Choose your country', country_text: 'Your flag shows on the ranking and in the lobby. You can change it later in the settings.', country_go: 'Let\'s go',
s_screen: 'Display', s_controls: 'Controls', s_career: 'Career', on: 'On', off: 'Off',
gfx_low: 'Low', gfx_medium: 'Medium', gfx_high: 'High',
// paint booth
@@ -143,7 +209,7 @@ window.LANG = {
all_countries: 'All countries', filter_country: 'Show:',
s_arena: 'Arena', arena_random: 'Random', arena_workshop: 'Workshop Pit', arena_foundry: 'The Foundry', arena_arena64: 'Mega Dome',
arena_scrapyard: 'Scrapyard', arena_crucible: 'The Crucible', arena_colosseum: 'Grand Colosseum',
peer_back: 'Opponent is back', no_pause_online: 'No pause in live fights',
peer_back: 'Opponent is back', no_pause_online: 'No pause in live fights - the fight keeps running.',
r_draw_prize: 'Draw prize',
online_guest: 'Join as guest (no e-mail)', online_short: '🌍 Online',
room_title: '{room} lobby', room_count: '{n} in this room', other_rooms: 'Other countries', you: 'you',
@@ -170,21 +236,40 @@ window.LANG = {
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!',
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_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_OFFLINE: 'Online is not set up yet.', e_ERROR: 'Something went wrong. Try again.',
f_login: 'Name or e-mail', f_email_opt: 'E-mail (optional)',
net_title: 'Network (F3 hides)', net_ping: 'Your ping', net_ping_srv: 'Server measures you', net_ping_opp: 'Opponent ping',
net_snaps: 'Snapshots', net_late: 'late', net_input: 'Key to server', net_server: 'Server step',
net_l_ping: 'your ping', net_l_opp: 'opponent', net_l_gap: 'snapshot gap', net_l_input: 'key delay',
nv_ok: 'Connection looks fine', nv_nofight: 'Not in a fight - only your ping is measured',
nv_me_slow: 'Your ping is high ({n} ms) - your connection or the route to the server',
nv_me_jitter: 'Your connection is unsteady (snapshots arrive irregularly, ±{n} ms)',
nv_opp_slow: 'Opponent has a high ping ({n} ms) - their connection',
nv_server: 'Server is slow ({n} ms per step)', nv_queue: 'Keys take {n} ms - data piles up on the way',
nv_lost: 'No snapshots for {n} s',
e_INVALID_LOGIN: 'Wrong name or password.', e_NAME_EXISTS: 'That name is already taken.', e_BAD_NAME: 'The name needs at least 3 letters or digits.',
e_RATE_LIMIT: 'Too many tries - please wait a minute.', e_INVALID_ROBOT: 'Your robot is not ready to fight - check weight and power in the workshop.',
e_OPPONENT_INVALID: 'The other robot is not ready to fight.', e_BUSY: 'That player is busy right now.', e_NOT_AVAILABLE: 'That player is not available.',
e_OUTDATED: 'A new version is out - please reload the page.', e_REPLACED: 'You are now playing in another window.', e_SESSION_EXPIRED: 'Your session has ended - please log in again.',
net_connecting: 'Connecting to the server...', net_lost: 'Connection lost', match_lost: 'No word from the server - the fight is counted there. Back to the lobby.',
pt_open: '🎨 Paint it yourself', pt_title: 'Paint booth', pt_top: 'TOP VIEW · front', pt_side: 'SIDE · front',
pt_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_mirror: 'Mirror both sides', pt_size: 'Size', pt_undo: 'Undo', pt_clear: 'Clear all', pt_done: 'Done', pt_text_ph: 'Text or number',
s_cam: 'Camera', cam_iso: 'Arena', cam_chase: 'Chase', cam_fpv: 'Cockpit', key_cam: 'switch camera',
// easier play + income
s_diff: 'Difficulty', diff_easy: 'Easy', diff_normal: 'Normal', diff_hard: 'Hard',
s_steer: 'Steering', steer_simple: 'Simple', steer_tank: 'Tank',
s_autofire: 'Weapon helper',
s_autofire: 'Weapon helper', s_quiet: 'Quiet mode',
s_body: 'Shape', des_height: 'Height', des_width: 'Width', des_length: 'Length', des_reset: 'Reset',
place_weapon: 'Build / weapons', place_done: 'Done',
place_hint: 'Drag a weapon on the robot — front, back or a side; drag up/down for height. Turn the robot by dragging the floor.',
ed_title: 'Build your robot', ed_weapons: 'Weapons (up to 3, same allowed)', ed_place: 'Placement', ed_noweapons: 'No weapons yet — pick one and mount it.', ed_max: 'Max {n} weapons',
mt_front: 'Front', mt_back: 'Back', mt_left: 'Left', mt_right: 'Right',
fight_hint_simple: 'W A S D: drive in that direction · Space weapon · Shift / E tower · C camera · P pause',
exhibition_hint: 'Tip: click a beaten opponent for an exhibition fight - half the prize, as often as you like.',
exhibition_note: 'Exhibition fight: half prize money, no league progress.',
@@ -213,6 +298,43 @@ window.LANG = {
league_chip: 'S{s} · {n}/{m}',
sound_on: 'Sound an', sound_off: 'Sound aus', pause: 'Pause',
win_min: 'Minimieren', win_full: 'Vollbild (F11)', win_close: 'Schließen',
event: 'Event', event_running: 'Event läuft', event_prize: 'Preisgeld x{n}', event_bonus: 'Event-Bonus', tour_free: 'Turnier (gratis)', tour_join: 'Turnier beitreten ({n})', tour_join_free: 'Turnier beitreten (gratis)',
reload_now: 'Neu laden', reload_skip: 'Trotzdem spielen',
reload_title: 'Neue Version', reload_text: 'Es gibt eine neuere Fassung von Robot Clash. Bitte die Seite neu laden (Strg+F5).',
cls_light: 'Leichtgewicht', cls_medium: 'Mittelgewicht', cls_heavy: 'Schwergewicht',
tournament: 'Turnier', tour_enter: 'Turnier ({n})', tour_continue: 'Turnier', tour_fight: 'Kämpfen',
tour_round_quarter: 'Viertelfinale', tour_round_semi: 'Halbfinale', tour_round_final: 'Finale',
tour_left: 'noch {n} Roboter', tour_beat: 'schlägt', title_campaign: 'Kampagne', title_online: 'Online', ltour_title: 'Live-Turnier', ltour_ready: 'bereit', ltour_waiting: 'nicht bereit', ltour_setready: 'Ich bin bereit', ltour_unready: 'Doch nicht', ltour_empty: 'Noch niemand da - lad einen Freund ein!', ltour_lobby: '{n} bereit (2 zum Start noetig)', ltour_countdown: 'Start in {n} s...', ltour_wait_round: 'Warte auf die anderen Kaempfe...', ai_tag: 'KI', tour_champion: 'Sieger', tour_your_match: 'dein Kampf: {name}', tour_round_prize: 'Rundenpreis', tour_trophy: 'Pokal',
tour_won: 'Turnier gewonnen!', tour_won_text: 'Das ganze Feld besiegt. Preisgeld: {n}.',
tour_out: 'Ausgeschieden', tour_out_text: 'Hier ist Schluss. {n} nimmst du mit.',
ach_tourney: 'Turniersieger', achd_tourney: 'Gewinne ein Turnier',
achievements: 'Erfolge', ach_new: 'Freigeschaltet', ach_done: '{n} von {m} geschafft',
rank_next: 'bis {n}: {f} Ruhm', rank_top: 'höchster Rang erreicht',
rank_scrap: 'Schrottsammler', rank_rookie: 'Neuling', rank_contender: 'Herausforderer', rank_pro: 'Profi',
rank_veteran: 'Veteran', rank_champion: 'Champion', rank_master: 'Meister', rank_legend: 'Legende',
ach_first_win: 'Erster Sieg', achd_first_win: 'Gewinne einen Kampf',
ach_ko: 'Licht aus', achd_ko: 'Gewinne durch K.o.',
ach_pit: 'Ab in die Grube', achd_pit: 'Schieb jemanden in die Grube',
ach_tough: 'Zäher Hund', achd_tough: 'Gewinne mit unter 15% Leben',
ach_flawless: 'Kein Kratzer', achd_flawless: 'Gewinne über 90% Leben, nichts abgerissen',
ach_demolition: 'Abrissbirne', achd_demolition: 'Mach 600 Schaden in einem Kampf',
ach_champion: 'Saisonmeister', achd_champion: 'Besiege die ganze Liga',
ach_veteran: 'Alter Hase', achd_veteran: 'Bestreite 25 Kämpfe',
ach_rich: 'Gut betucht', achd_rich: 'Besitze 5.000 Credits',
ach_collector: 'Sammler', achd_collector: 'Besitze 20 Teile',
ach_garage: 'Volle Halle', achd_garage: 'Halte 3 Roboter',
ach_artist: 'Eigene Farben', achd_artist: 'Male ein eigenes Design',
mode_online: 'Online', mode_campaign: 'Kampagne', mode_pvp: 'gegen Spieler', to_lobby: 'Lobby',
to_campaign: 'Zur Kampagne', to_online: 'Zum Online', rank_live: 'LIVE',
mode_switched: 'Eigenes Spiel – eigenes Geld und eigene Teile',
click_start: 'Klicken oder Taste drücken zum Starten',
tut_title: 'Kurzanleitung', tut_next: 'Weiter', tut_skip: 'Überspringen', tut_go: 'Los bauen',
tut_1: 'Jeder Roboter braucht vier Teile: Chassis, Motor, Räder und Batterie. Die wählst du unter „Teile".',
tut_2: 'Eine Waffe ist freiwillig – ohne kannst du nur rammen. Ein Keil ist billig, ein Flipper wirft um.',
tut_3: 'Achte auf die zwei Balken links: 100 kg sind das Limit, und die Batterie muss alle Teile versorgen.',
tut_4: 'Dann auf LIGA drücken. Auch eine Niederlage bringt Geld, und vom Preisgeld kaufst du bessere Teile.',
tut_controls: 'W/S fahren · A/D drehen · Leertaste Waffe · Shift Turm · G Gadget · C Kamera',
wrong_host: 'Diese Ausgabe von Robot Clash darf nur auf michael-media.de gespielt werden.',
no_webgl: 'Dieses Spiel braucht WebGL (3D-Grafik). Bitte einen aktuellen Browser nutzen oder den Grafiktreiber aktualisieren.',
menu_text: 'Bau deinen Kampfroboter aus Teilen, kämpf dich durch die Liga<br>und schick deine Gegner in die Grube.',
name_placeholder: 'Dein Name',
@@ -237,7 +359,7 @@ window.LANG = {
st_supply: 'liefert {n} Strom', st_power: 'braucht {n} Strom',
m_weight: 'Gewicht', m_power: 'Strom', m_hp: 'Lebenspunkte', m_armour: 'Panzerung', m_speed: 'Tempo', m_accel: 'Beschl.', m_turn: 'Wendigkeit',
paint_body: 'Lack', paint_accent: 'Akzent',
err_need: '{slot} fehlt', err_bad: '{slot} ungültig', err_overweight: 'Zu schwer (max. 100 kg)', err_no_power: 'Batterie zu schwach',
err_need: '{slot} fehlt', err_bad: '{slot} ungültig', err_overweight: 'Zu schwer (max. {n} kg)', err_no_power: 'Batterie zu schwach – stärkere Batterie oder weniger Verbrauch', err_too_many_weapons: 'Zu viele Waffen (max. 3)',
pd_crate: 'Einfache Stahlkiste. Billig und ehrlich.',
pd_doorstop: 'Flacher Keil – schwer umzudrehen.',
pd_bulwark: 'Schwerer Rahmen mit vielen Lebenspunkten.',
@@ -246,6 +368,9 @@ window.LANG = {
pd_hornet: 'Schnellerer Allrounder.',
pd_bulldog: 'Riesiges Drehmoment zum Schieben.',
pd_comet: 'Höchsttempo für Angriff und Rückzug.',
pd_pico: 'Winziger Billigmotor – schwach, aber federleicht, gut fürs Leichtgewicht.',
pd_turbine: 'Solider Allround-Motor, ordentlich Schub und Tempo.',
pd_titandrive: 'Monster-Drehmoment für die schwersten Bauten, aber langsam und schwer.',
pd_rubber: 'Vier kleine Räder, wendig.',
pd_cage: 'Offener Schrottrahmen: spottbillig und leicht, aber schnell verbeult.',
pd_hexpod: 'Sechseckige Schale, rundum abgeschrägt – Treffer rutschen ab.',
@@ -253,6 +378,9 @@ window.LANG = {
pd_fang: 'Lange Spitze vorn, flach und flink – schwer umzuwerfen.',
pd_plough: 'Schweres Räumschild an der Nase, steckt Fronttreffer weg.',
pd_discus: 'Breite flache Scheibe, liegt tief und hält viel aus.',
pd_orb: 'Runde Panzerkugel – Treffer rutschen von allen Seiten ab.',
pd_tower: 'Hoher, aufrechter Bau – überragt alle, kippt aber leicht.',
pd_slab: 'Sehr breit und flach – kaum umzuwerfen.',
pd_omni: 'Lenkrollen: dreht auf der Stelle, top Lenkung.',
pd_bigtyre: 'Höher als der Roboter: fährt auch umgedreht weiter.',
pd_studs: 'Spike-Grip, fährt auch umgedreht, starkes Schieben.',
@@ -262,6 +390,8 @@ window.LANG = {
pd_lead: 'Schwer, aber sie tut es.',
pd_nicd: 'Mehr Strom, weniger Gewicht.',
pd_lipo: 'Leicht und stark.',
pd_liion: 'Großer Zellenblock – trägt schwere Waffe und Turm gleichzeitig.',
pd_supercap: 'Superkondensator-Bank: der meiste Strom, und entsprechend schwer.',
pd_mesh: 'Dünnes Drahtgitter – kaum Gewicht, kaum Schutz.',
pd_buffer: 'Dicke Gummipuffer, die Rammstöße schlucken.',
pd_spiked: 'Platten mit Stacheln, sehen auch so aus.',
@@ -293,6 +423,7 @@ window.LANG = {
pd_shield: 'Feld, das ein paar Sekunden Schaden abfängt (G).',
pd_repair: 'Flickt die Hülle – zwei Ladungen (G).',
pd_emp: 'Legt einen nahen Gegner kurz lahm (G).',
pd_mines: 'Legt eine Mine hinter dir ab (G). Nach einer Sekunde scharf – wer drüberfährt, fliegt hoch. Auch du.',
// league
league_title: 'Liga – Saison {s}',
league_text: 'Besiege die Gegner nacheinander. Jede Saison werden sie härter und zahlen mehr.',
@@ -334,7 +465,27 @@ window.LANG = {
e_pass_short: 'Das Passwort braucht mindestens 4 Zeichen.', e_pass_match: 'Die Passwörter stimmen nicht überein.',
e_unknown: 'Kein Konto mit diesem Namen.', e_wrong_pass: 'Falsches Passwort.',
// settings
s_lang: 'Sprache', s_music: 'Musik', s_sfx: 'Effekte', s_mute: 'Ton', s_gfx: 'Grafik', s_intro: 'Intro beim Start',
s_lang: 'Sprache', s_country: 'Land', s_music: 'Musik', s_sfx: 'Effekte', s_mute: 'Ton', s_gfx: 'Grafik', s_intro: 'Intro beim Start',
s_comfort: 'Komfort (weniger Bewegung)',
missions: 'Missionen', miss_daily: 'Täglich', miss_weekly: 'Wöchentlich', miss_reset_in: 'neu in {n} h', miss_complete: 'Mission geschafft!', paint_locked: 'Gesperrt – über eine Mission freischalten',
mission_d_win3: 'Siegesserie', missd_d_win3: 'Gewinne 3 Kämpfe',
mission_d_play5: 'Aufwärmen', missd_d_play5: 'Bestreite 5 Kämpfe',
mission_d_dmg800: 'Draufhauer', missd_d_dmg800: 'Mach 800 Schaden',
mission_d_ko2: 'Doppel-K.o.', missd_d_ko2: 'Schlage 2 Gegner K.o.',
mission_d_pit1: 'Ab in die Grube', missd_d_pit1: 'Gewinne 1 Kampf per Grube',
mission_d_flaw1: 'Unberührt', missd_d_flaw1: 'Sieg ohne Teileverlust (≥90% LP)',
mission_d_foundry: 'Gießerei-Duell', missd_d_foundry: 'Gewinne in der Gießerei',
mission_d_colosseum: 'Kolosseum', missd_d_colosseum: 'Gewinne im Kolosseum',
mission_d_spin: 'Dreh dich', missd_d_spin: 'Sieg mit einer Spinner-Waffe',
mission_d_hammer: 'Hammerzeit', missd_d_hammer: 'Sieg mit Hammer/Axt',
mission_w_win15: 'Veteranenwoche', missd_w_win15: 'Gewinne 15 Kämpfe',
mission_w_dmg6000: 'Abrisswoche', missd_w_dmg6000: 'Mach 6000 Schaden',
mission_w_ko8: 'K.o.-Künstler', missd_w_ko8: 'Schlage 8 Gegner K.o.',
mission_w_flaw3: 'Makellos', missd_w_flaw3: 'Gewinne 3 makellose Kämpfe',
legal: 'Rechtliches', legal_impressum: 'Impressum', legal_privacy: 'Datenschutz', consent_pre: 'Ich akzeptiere die', consent_required: 'Bitte die Datenschutzerklärung akzeptieren.',
impressum_text: '<p><b>Angaben gemäß § 5 DDG</b></p><p>[Name / Anbieter]<br>[Anschrift – z. B. c/o Impressums-Dienst]<br>[PLZ Ort]</p><p><b>Kontakt</b><br>E-Mail: [kontakt@deine-domain]</p><p class="muted">Hinweis: Bitte echte Daten eintragen. Es genügt eine ladungsfähige Anschrift (z. B. über einen Impressums-/c-o-Dienst) – keine Privatadresse nötig.</p>',
privacy_text: '<p><b>Datenschutzerklärung</b></p><p>Verantwortlich: [Name], [Kontakt-E-Mail].</p><p><b>Welche Daten?</b> Bei der Registrierung deine E-Mail-Adresse und ein verschlüsselter Passwort-Hash; beim Spielen dein Spielstand, die gewählte Länderflagge und – online – deine Lobby-Präsenz (Name, Status). Der Server speichert technisch bedingt Zugriffsdaten (IP-Adresse, Zeitpunkt) in Logdateien.</p><p><b>Wozu?</b> Zum Betrieb des Kontos, Speichern des Fortschritts, der Online-Lobby/Rangliste und zur Absicherung des Servers (Art. 6 Abs. 1 b und f DSGVO).</p><p><b>Hosting:</b> Der Server steht bei Hetzner in Deutschland; es besteht ein Auftragsverarbeitungsvertrag.</p><p><b>Speicherung:</b> Konto/Spielstand bis zur Löschung durch dich; Server-Logs nur kurzzeitig.</p><p><b>Cookies/Tracking:</b> Es werden nur technisch notwendige Speicher (localStorage, Login-Token) genutzt – kein Tracking, keine Werbung, keine Weitergabe an Dritte.</p><p><b>Deine Rechte:</b> Auskunft, Berichtigung, Löschung, Widerspruch und Beschwerde bei einer Aufsichtsbehörde. Kontakt: [Kontakt-E-Mail].</p><p class="muted">Vorlage – bitte anwaltlich/über einen Generator prüfen und eigene Daten eintragen.</p>',
country_title: 'Wähle dein Land', country_text: 'Deine Flagge erscheint in der Rangliste und in der Lobby. Du kannst sie später in den Einstellungen ändern.', country_go: 'Los geht\'s',
s_screen: 'Anzeige', s_controls: 'Steuerung', s_career: 'Karriere', on: 'An', off: 'Aus',
gfx_low: 'Niedrig', gfx_medium: 'Mittel', gfx_high: 'Hoch',
// paint booth
@@ -347,7 +498,7 @@ window.LANG = {
all_countries: 'Alle Länder', filter_country: 'Zeigen:',
s_arena: 'Arena', arena_random: 'Zufällig', arena_workshop: 'Werkstatt-Grube', arena_foundry: 'Die Gießerei', arena_arena64: 'Mega-Dome',
arena_scrapyard: 'Schrottplatz', arena_crucible: 'Der Schmelztiegel', arena_colosseum: 'Große Arena',
peer_back: 'Gegner ist wieder da', no_pause_online: 'Keine Pause im Live-Kampf',
peer_back: 'Gegner ist wieder da', no_pause_online: 'Keine Pause im Live-Kampf - der Kampf läuft weiter.',
r_draw_prize: 'Unentschieden-Preis',
online_guest: 'Als Gast beitreten (ohne E-Mail)', online_short: '🌍 Online',
room_title: 'Lobby {room}', room_count: '{n} in diesem Raum', other_rooms: 'Andere Länder', you: 'du',
@@ -374,21 +525,40 @@ window.LANG = {
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!',
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_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_OFFLINE: 'Online ist noch nicht eingerichtet.', e_ERROR: 'Etwas ist schiefgelaufen. Nochmal versuchen.',
f_login: 'Name oder E-Mail', f_email_opt: 'E-Mail (optional)',
net_title: 'Netzwerk (F3 blendet aus)', net_ping: 'Dein Ping', net_ping_srv: 'Server misst dich', net_ping_opp: 'Gegner-Ping',
net_snaps: 'Snapshots', net_late: 'zu spät', net_input: 'Taste bis Server', net_server: 'Server-Schritt',
net_l_ping: 'dein Ping', net_l_opp: 'Gegner', net_l_gap: 'Snapshot-Abstand', net_l_input: 'Tasten-Verzögerung',
nv_ok: 'Verbindung sieht gut aus', nv_nofight: 'Kein Kampf - nur dein Ping wird gemessen',
nv_me_slow: 'Dein Ping ist hoch ({n} ms) - deine Leitung oder der Weg zum Server',
nv_me_jitter: 'Deine Verbindung schwankt (Snapshots kommen unregelmäßig, ±{n} ms)',
nv_opp_slow: 'Der Gegner hat hohen Ping ({n} ms) - seine Leitung',
nv_server: 'Server ist langsam ({n} ms pro Schritt)', nv_queue: 'Tasten brauchen {n} ms - unterwegs staut es sich',
nv_lost: 'Seit {n} s keine Snapshots',
e_INVALID_LOGIN: 'Name oder Passwort falsch.', e_NAME_EXISTS: 'Dieser Name ist schon vergeben.', e_BAD_NAME: 'Der Name braucht mindestens 3 Buchstaben oder Ziffern.',
e_RATE_LIMIT: 'Zu viele Versuche - bitte eine Minute warten.', e_INVALID_ROBOT: 'Dein Roboter ist nicht kampfbereit - prüfe Gewicht und Strom in der Werkstatt.',
e_OPPONENT_INVALID: 'Der andere Roboter ist nicht kampfbereit.', e_BUSY: 'Dieser Spieler ist gerade beschäftigt.', e_NOT_AVAILABLE: 'Dieser Spieler ist nicht verfügbar.',
e_OUTDATED: 'Es gibt eine neue Version - bitte die Seite neu laden.', e_REPLACED: 'Du spielst jetzt in einem anderen Fenster.', e_SESSION_EXPIRED: 'Deine Sitzung ist abgelaufen - bitte neu anmelden.',
net_connecting: 'Verbinde mit dem Server...', net_lost: 'Verbindung verloren', match_lost: 'Keine Antwort vom Server - der Kampf wird dort gewertet. Zurück zur Lobby.',
pt_open: '🎨 Selbst bemalen', pt_title: 'Lackiererei', pt_top: 'OBEN · vorne', pt_side: 'SEITE · vorne',
pt_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_mirror: 'Beide Seiten spiegeln', pt_size: 'Größe', pt_undo: 'Zurück', pt_clear: 'Alles löschen', pt_done: 'Fertig', pt_text_ph: 'Text oder Nummer',
s_cam: 'Kamera', cam_iso: 'Arena', cam_chase: 'Verfolger', cam_fpv: 'Cockpit', key_cam: 'Kamera wechseln',
// easier play + income
s_diff: 'Schwierigkeit', diff_easy: 'Leicht', diff_normal: 'Normal', diff_hard: 'Schwer',
s_steer: 'Steuerung', steer_simple: 'Einfach', steer_tank: 'Panzer',
s_autofire: 'Waffen-Hilfe',
s_autofire: 'Waffen-Hilfe', s_quiet: 'Leiser Modus',
s_body: 'Form', des_height: 'Höhe', des_width: 'Breite', des_length: 'Länge', des_reset: 'Zurücksetzen',
place_weapon: 'Bauen / Waffen', place_done: 'Fertig',
place_hint: 'Zieh eine Waffe auf den Roboter — vorne, hinten oder an eine Seite; hoch/runter für die Höhe. Den Roboter drehst du, indem du den Boden ziehst.',
ed_title: 'Roboter bauen', ed_weapons: 'Waffen (bis 3, auch gleiche)', ed_place: 'Platzierung', ed_noweapons: 'Noch keine Waffe — eine wählen und montieren.', ed_max: 'Max. {n} Waffen',
mt_front: 'Vorne', mt_back: 'Hinten', mt_left: 'Links', mt_right: 'Rechts',
fight_hint_simple: 'W A S D: in diese Richtung fahren · Leertaste Waffe · Shift / E Turm · C Kamera · P Pause',
exhibition_hint: 'Tipp: Klick einen besiegten Gegner für einen Schaukampf – halbes Preisgeld, so oft du willst.',
exhibition_note: 'Schaukampf: halbes Preisgeld, kein Liga-Fortschritt.',

86
game/live.js Normal file
View File

@@ -0,0 +1,86 @@
/* 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.
RC.Live.parse(data, now, build) -> {
motd, // { de, en } or null
event, // the running event or null (outside its window it counts as none)
onlineOff, note, // kill switch + why
needsReload, // this copy is older than build.min
locked(kind, id), // true when the admin has not released this part/arena/class yet
}
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.
Everything is best effort: no config, broken JSON or no network simply means "nothing special
is running" - the game must never wait for or depend on this. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const KEY = 'robotclash.live';
const obj = v => (v && typeof v === 'object' && !Array.isArray(v) ? v : null);
const list = v => (Array.isArray(v) ? v.filter(x => typeof x === 'string') : null);
const num = (v, d) => (typeof v === 'number' && isFinite(v) ? v : d);
// An empty or missing list means "everything is free" - that is the behaviour without a backend,
// so a broken config can never lock players out of their own parts.
function makeLocked(unlock) {
const u = obj(unlock) || {};
const sets = { parts: list(u.parts), arenas: list(u.arenas), classes: list(u.classes) };
return (kind, id) => {
const only = sets[kind];
return !!(only && only.length && only.indexOf(id) < 0);
};
}
function parse(data, now, build) {
const d = obj(data) || {};
const t = num(now, Date.now());
const ev = obj(d.event);
const inWindow = ev && (!num(ev.from, 0) || t >= ev.from) && (!num(ev.to, 0) || t <= ev.to);
const flags = obj(d.flags) || {};
const b = obj(d.build) || {};
const min = typeof b.min === 'string' ? b.min : '';
return {
motd: obj(d.motd),
event: inWindow ? {
id: String(ev.id || 'event'),
name: obj(ev.name) || null,
from: num(ev.from, 0), to: num(ev.to, 0),
type: String(ev.type || 'plain'),
cls: typeof ev.cls === 'string' ? ev.cls : null,
arena: typeof ev.arena === 'string' ? ev.arena : null,
prizeMul: Math.max(0.1, Math.min(5, num(ev.prizeMul, 1))),
tournament: !!ev.tournament,
} : null,
onlineOff: !!flags.onlineOff,
note: obj(flags.note),
tournament: !!flags.tournament || !!(ev && ev.tournament && inWindow), // tournament open?
needsReload: !!(min && typeof build === 'string' && build && build < min),
locked: makeLocked(d.unlock),
};
}
// last known config, so a fresh page load already knows about an event before the network answers
function cached() {
try { return JSON.parse(root.localStorage.getItem(KEY) || 'null'); } catch (e) { return null; }
}
function remember(data) {
try { root.localStorage.setItem(KEY, JSON.stringify(data)); } catch (e) { /* private mode: ignore */ }
}
function load(net, onChange) {
const build = (root.RC_BUILD || root.window && root.window.RC_BUILD) || '';
const fire = data => { if (data) remember(data); onChange(parse(data, Date.now(), build)); };
fire(cached()); // show something immediately
if (!net || !net.enabled) return { close() {} };
// the admin changes these rarely: read now, then poll every minute
const pull = () => net.api('GET', '/api/live').then(d => { if (d) fire(d); }, () => {});
pull();
const timer = setInterval(pull, 60000);
return { close() { clearInterval(timer); } };
}
RC.Live = { parse, load, KEY };
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -1,132 +1,65 @@
/* Robot Clash - online lobby: presence, player list, challenges, match creation. No DOM.
Needs net.js (RC.Net). Transport is Firebase RTDB (net.db). All cosmetic/casual, see docs/firebase.
/* Robot Clash - online lobby over the server WebSocket (net.socket). No DOM. The server owns presence,
challenges and matches; this just mirrors its state and forwards clicks.
const lobby = RC.Lobby({ net, getProfile: () => ({ name, flag, build, paint, fame }) });
lobby.enter() announce presence, start heartbeat, watch list + incoming challenges
lobby.leave() remove presence, stop everything
lobby.onList(fn) fn([{ uid, name, flag, state, fame }]) - online players except me, newest first
lobby.onIncoming(fn) fn({ from, fromName, fromFlag, build, paint, seed }) - someone challenges me
lobby.onMatch(fn) fn({ id, host (bool), opp: { uid, name, flag, build, paint }, seed }) - fight on
lobby.onCancel(fn) fn() - a pending challenge I sent/got fell through
await lobby.challenge(uid) invite a player (writes to their inbox, waits for accept)
await lobby.accept(from) accept an incoming challenge -> creates the match
lobby.decline(from) reject an incoming challenge
lobby.cancel() withdraw the challenge I sent
Presence TTL: entries older than STALE ms count as offline (no SDK onDisconnect). */
const lobby = RC.Lobby({ net })
lobby.enter() / leave()
lobby.onList(fn) fn([{ uid, name, flag, fame, state, room }]) everyone online except me
lobby.onIncoming(fn) fn({ from, fromName, fromFlag }) someone challenges me
lobby.onCancel(fn) fn({ reason }) my challenge / an incoming one fell through
lobby.onMatch(fn) fn(matchStartMsg) fight on (also after a reconnect)
lobby.onEnd(fn) fn(matchEndMsg) server result + rewards + new save
lobby.onError(fn) fn(code) BUSY | INVALID_ROBOT | ...
lobby.challenge(uid) / accept(from) / decline(from) / cancel() / setRoom(code|'all')
lobby.pending uid I challenged (or null) */
(function (root) {
'use strict';
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) => {
const net = opt.net, db = net.db;
const cbs = { list: [], incoming: [], match: [], cancel: [] };
const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { /* ignore */ } });
let hb = null, subList = null, subIn = null, subMatch = null;
let outgoing = null; // uid I challenged
let inMatch = null; // active match id
const net = opt.net, sock = net.socket;
const cbs = { list: [], incoming: [], cancel: [], match: [], end: [], error: [] };
const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { console.error(e); } });
const players = new Map();
let me = null, pending = null, offs = [], incomingFrom = null;
const me = () => net.uid;
const prof = () => opt.getProfile();
const list = () => emit('list', [...players.values()].sort((a, b) => (b.fame | 0) - (a.fame | 0) || String(a.name).localeCompare(b.name)));
async function beat(state) {
const p = prof();
await db.put(`lobby/${me()}`, { name: p.name, flag: p.flag || 'XX', fame: p.fame | 0, ver: 2, state: state || 'idle', ts: { '.sv': 'timestamp' } });
}
function watchList() {
subList = db.stream('lobby', data => {
const t = now(), mine = me();
const rows = Object.entries(data || {})
.map(([uid, v]) => Object.assign({ uid }, v))
.filter(v => v.uid !== mine && v.name && (t - (v.ts || 0)) < STALE)
.sort((a, b) => (b.ts || 0) - (a.ts || 0));
emit('list', rows);
});
}
// 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();
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); // add my own robot to the match meta
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);
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'); } }
async function createMatch(oppUid) {
const id = matchId(me(), oppUid), p = prof();
const seed = (parseInt(id.slice(-6), 36) % 1e9) || 1; // same on both sides
// meta holds both players' robots; written once, guarded so the first writer wins
await db.patch(`matches/${id}/meta`, { seed, [me()]: { name: p.name, flag: p.flag || 'XX', build: p.build, paint: p.paint } });
await beat('inmatch');
function wire() {
offs = [
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(); }),
sock.on('lobby.leave', m => { players.delete(m.uid); list(); }),
sock.on('challenge.in', m => { incomingFrom = m.from; emit('incoming', { from: m.from, fromName: m.name, fromFlag: m.flag, fame: m.fame }); }),
sock.on('challenge.gone', m => {
if (m.to && m.to === pending) { pending = null; emit('cancel', { reason: m.reason || 'gone', outgoing: true }); }
if (m.from && m.from === incomingFrom) { incomingFrom = null; emit('cancel', { reason: m.reason || 'gone', outgoing: false }); }
}),
sock.on('match.start', m => { pending = null; incomingFrom = null; emit('match', m); }),
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(); }),
];
}
return {
onList: fn => cbs.list.push(fn),
onIncoming: fn => cbs.incoming.push(fn),
onMatch: fn => cbs.match.push(fn),
onCancel: fn => cbs.cancel.push(fn),
challenge, accept, decline, cancel,
async enter() {
if (!net.enabled || !me()) return;
await beat('idle');
hb = setInterval(() => db.patch(`lobby/${me()}`, { ts: { '.sv': 'timestamp' }, state: outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle' }), HEARTBEAT);
watchList(); watchIncoming();
},
refresh() { if (me()) beat(outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle'); },
endMatch() { const id = inMatch; inMatch = null; cleanupMatch(); if (id) db.del(`matches/${id}`); if (me()) beat('idle'); },
leave() {
clearInterval(hb); hb = null;
if (subList) subList.close(); if (subIn) subIn.close(); cleanupMatch();
if (me()) db.del(`lobby/${me()}`);
},
matchId, isHost,
onMatch: fn => cbs.match.push(fn),
onEnd: fn => cbs.end.push(fn),
onError: fn => cbs.error.push(fn),
get pending() { return pending; },
get me() { return me; },
get connected() { return sock.connected; },
enter() { if (!net.enabled || !net.uid) return; if (!offs.length) wire(); sock.connect(); },
leave() { offs.forEach(off => off()); offs = []; sock.close(); players.clear(); pending = null; },
challenge(uid) { if (pending) return; pending = uid; if (!sock.send({ t: 'challenge', to: uid })) pending = null; },
cancel() { if (!pending) return; sock.send({ t: 'challenge.cancel' }); pending = null; },
accept(from) { incomingFrom = null; sock.send({ t: 'challenge.accept', from }); },
decline(from) { incomingFrom = null; sock.send({ t: 'challenge.decline', from }); },
setRoom(room) { sock.send({ t: 'room', room: room || 'all' }); },
leaveMatch() { sock.send({ t: 'match.leave' }); },
};
};
})(typeof window !== 'undefined' ? window : globalThis);

93
game/ltourney.js Normal file
View File

@@ -0,0 +1,93 @@
/* Robot Clash - live multiplayer tournament bracket maths (no DOM, no network, runs in Node).
The networked part (registration, ready/countdown, match sync) lives in game.js/lobby.js and
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
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.
RC.LTourney.order(uids, seed) -> seeded slot order, padded with null byes to a power of two
RC.LTourney.rounds(order, results) -> [[slot,...] per round]; later rounds fill from results+byes
RC.LTourney.myMatch(order, results, me) -> for the player `me`:
{ done:true, champion } when the bracket is settled, or
{ round, pairIndex, opp (uid|null=bye), host (bool) } for the match to play now, or
null when `me` is out / not in it. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
function rng(seed) {
let s = (seed || 1) >>> 0;
return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}
const pow2 = n => { let p = 1; while (p < n) p *= 2; return Math.max(2, p); };
// deterministic seeded order, padded to a power of two with null (= bye)
function order(uids, seed) {
const a = (uids || []).filter(Boolean).slice();
const rand = rng(seed);
for (let i = a.length - 1; i > 0; i--) { const j = (rand() * (i + 1)) | 0; const t = a[i]; a[i] = a[j]; a[j] = t; }
const size = pow2(a.length);
while (a.length < size) a.push(null);
return a;
}
// winner of one pair: a reported result, or the only real player (bye), else undefined (not yet)
function pairWinner(a, b, res) {
if (a && !b) return a;
if (b && !a) return b;
if (!a && !b) return null; // empty pair stays empty
return res === a || res === b ? res : undefined;
}
function rounds(ord, results) {
results = results || {};
const out = [ord.slice()];
let cur = ord;
let r = 0;
while (cur.length > 1) {
const res = results[r] || {};
const next = [];
let complete = true;
for (let i = 0; i < cur.length; i += 2) {
const w = pairWinner(cur[i], cur[i + 1], res[i / 2]);
if (w === undefined) complete = false;
next.push(w === undefined ? null : w);
}
out.push(next);
if (!complete) break; // round not finished -> stop building further
cur = next; r++;
}
return out;
}
function myMatch(ord, results, me) {
if (!me || ord.indexOf(me) < 0) return null;
results = results || {};
let cur = ord, r = 0;
while (cur.length > 1) {
const i = cur.indexOf(me);
if (i < 0) return null; // knocked out in an earlier round
const other = i % 2 === 0 ? i + 1 : i - 1;
const opp = cur[other], res = (results[r] || {})[Math.floor(i / 2)];
const w = pairWinner(me, opp, res);
if (w === undefined) {
// my match this round is not decided yet -> this is the one to play
return { round: r, pairIndex: Math.floor(i / 2), opp: opp || null,
host: opp ? me < opp : true }; // lower uid hosts (matches netfight rule)
}
if (w !== me) return null; // I lost
// I advanced: rebuild next round and go on
const next = [];
for (let k = 0; k < cur.length; k += 2) {
const ww = pairWinner(cur[k], cur[k + 1], (results[r] || {})[k / 2]);
next.push(ww === undefined ? null : ww);
}
cur = next; r++;
}
return { done: true, champion: cur[0] || null };
}
RC.LTourney = { order, rounds, myMatch, pow2 };
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

96
game/missions.js Normal file
View File

@@ -0,0 +1,96 @@
/* Robot Clash - campaign missions (no DOM, runs in Node for the tests). Needs parts.js.
Rotating objectives: 3 daily + 1 weekly, stored in the save (per mode, so campaign keeps its own).
Reward = credits + fame, some weekly ones unlock a special paint / scheme.
RC.Missions.ensure(save, now, baseSeed) -> rolls/resets save.missions when the day/week changed
RC.Missions.apply(m, ctx) -> advance one mission from a fight ctx, true if newly done
RC.Missions.active(save) -> [ ...daily, weekly ] for UI / iteration
ctx (same as awardAch): { won, reason, hpPct, lost, dealt, arenaId, weaponType }
Texts: lang.js keys 'mission_<id>' (name) and 'missd_<id>' (what to do). */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || (typeof require === 'function' ? require('./parts.js') : {}));
const DAY = 86400000, WEEK = 7 * DAY;
const dayIndex = now => Math.floor((now || 0) / DAY);
const weekIndex = now => Math.floor((now || 0) / WEEK);
// deterministic RNG (mulberry32) so a given seed always rolls the same set
function rng(seed) {
let a = (seed >>> 0) || 1;
return () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}
const mix = (a, b) => (Math.imul((a >>> 0) ^ 0x9e3779b9, 0x85ebca6b) ^ ((b >>> 0) + 0x165667b1)) >>> 0;
// daily pool (small goals). type decides how a fight advances it.
const DAILY = [
{ id: 'd_win3', type: 'win', goal: 3, reward: 180, fame: 30 },
{ id: 'd_play5', type: 'play', goal: 5, reward: 120, fame: 15 },
{ id: 'd_dmg800', type: 'damage', goal: 800, reward: 160, fame: 20 },
{ id: 'd_ko2', type: 'ko', goal: 2, reward: 200, fame: 30 },
{ id: 'd_pit1', type: 'pit', goal: 1, reward: 180, fame: 30 },
{ id: 'd_flaw1', type: 'flawless', goal: 1, reward: 220, fame: 40 },
{ id: 'd_foundry', type: 'arena:foundry', goal: 1, reward: 200, fame: 30 },
{ id: 'd_colosseum', type: 'arena:colosseum', goal: 1, reward: 220, fame: 35 },
{ id: 'd_spin', type: 'weapon:spinner', goal: 1, reward: 200, fame: 30 },
{ id: 'd_hammer', type: 'weapon:hammer', goal: 1, reward: 200, fame: 30 },
];
// weekly pool (bigger goals, often an unlock). unlock: paint hex or 'scheme:<idx>'
const WEEKLY = [
{ id: 'w_win15', type: 'win', goal: 15, reward: 700, fame: 120, unlock: 0x39ff14 },
{ id: 'w_dmg6000', type: 'damage', goal: 6000, reward: 600, fame: 100, unlock: 0xc0c0c0 },
{ id: 'w_ko8', type: 'ko', goal: 8, reward: 800, fame: 140, unlock: 0xff1e8e },
{ id: 'w_flaw3', type: 'flawless', goal: 3, reward: 900, fame: 160, unlock: 0x7b2fff },
];
const inst = o => ({ id: o.id, type: o.type, goal: o.goal, reward: o.reward, fame: o.fame, unlock: o.unlock || null, prog: 0, done: false });
// pick n distinct objectives from a pool, deterministically from seed
function pick(pool, seed, n) {
const r = rng(seed), idx = pool.map((_, i) => i);
for (let i = idx.length - 1; i > 0; i--) { const j = (r() * (i + 1)) | 0; const t = idx[i]; idx[i] = idx[j]; idx[j] = t; }
return idx.slice(0, Math.min(n, pool.length)).map(i => inst(pool[i]));
}
const daily = (seed, n = 3) => pick(DAILY, seed, n);
const weekly = (seed, n = 1) => pick(WEEKLY, seed, n);
// roll or reset the mission set when the calendar day / week rolled over
function ensure(save, now, baseSeed) {
const d = dayIndex(now), w = weekIndex(now), base = (baseSeed >>> 0) || 1;
let m = save.missions;
if (!m || m.day !== d) m = Object.assign(m || {}, { day: d, daily: daily(mix(base, d)) });
if (m.week !== w) { m.week = w; m.weekly = weekly(mix(base, 1000003 + w)); }
save.missions = m;
return m;
}
// how much a single fight advances a mission of this type
function gain(type, ctx) {
const c = ctx || {};
if (type === 'play') return 1;
if (type === 'damage') return Math.max(0, Math.round(c.dealt || 0));
if (!c.won) return 0; // the rest only count on a win
if (type === 'win') return 1;
if (type === 'ko') return c.reason === 'ko' ? 1 : 0;
if (type === 'pit') return c.reason === 'pit' ? 1 : 0;
if (type === 'flawless') return (c.lost === 0 && (c.hpPct || 0) >= 0.9) ? 1 : 0;
if (type.startsWith('arena:')) return c.arenaId === type.slice(6) ? 1 : 0;
if (type.startsWith('weapon:')) return c.weaponType === type.slice(7) ? 1 : 0;
return 0;
}
// advance one mission; returns true the moment it is newly completed
function apply(m, ctx) {
if (!m || m.done) return false;
const add = gain(m.type, ctx);
if (add <= 0) return false;
m.prog = Math.min(m.goal, (m.prog || 0) + add);
if (m.prog >= m.goal) { m.done = true; return true; }
return false;
}
const active = save => (save && save.missions) ? [].concat(save.missions.daily || [], save.missions.weekly || []) : [];
RC.Missions = { DAILY, WEEKLY, dayIndex, weekIndex, daily, weekly, ensure, apply, gain, active };
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -1,175 +1,156 @@
/* Robot Clash - Firebase over plain REST (no SDK, classic script, runs from file://).
Auth = Identity Toolkit REST, database = Realtime Database REST + Server-Sent-Events for push.
/* Robot Clash - client side of the own server (server/): REST + one WebSocket. Classic script, no SDK.
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' });
net.enabled false without a full config -> game stays offline
await net.auth.register(email, pass, name) -> { ok, error } (error: 'EMAIL_EXISTS' | 'WEAK_PASSWORD' | ...)
await net.auth.login(email, pass) -> { ok, error } ('EMAIL_NOT_FOUND' | 'INVALID_PASSWORD' | ...)
await net.auth.guest(name) -> { ok, error } (anonymous sign-in, must be enabled in Firebase)
net.auth.resume() -> true if a saved session was restored (async refresh follows)
net.auth.logout() / net.auth.current -> { uid, name, email, guest } | null
net.auth.onChange(fn) called after login/logout/refresh
const net = RC.Net({ serverUrl: '' }) '' = same origin as the page
net.enabled false on file:// -> offline
await net.auth.register(name, pass, email?) -> { ok, error } error: NAME_EXISTS | WEAK_PASSWORD | BAD_NAME | ...
await net.auth.login(nameOrEmail, pass) -> { ok, error } INVALID_LOGIN | RATE_LIMIT | ...
await net.auth.guest(name) -> { ok, error }
net.auth.resume() / logout() / current {uid,name,email,guest,admin} / onChange(fn)
await net.api(method, path, body) -> parsed JSON or null (never throws); 401 -> one refresh + retry
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
await net.db.put(path, value) -> ok (PUT, replaces)
await net.db.patch(path, obj) -> ok (PATCH, merges)
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. */
Session: refresh tokens rotate (each works once). Refresh is single-flight, and the session is shared
through localStorage, so two tabs never burn the same refresh token and log each other out.
Dev: ?slot=2 keeps a second session in the same browser (test PvP with two accounts in two tabs). */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const AUTH = 'https://identitytoolkit.googleapis.com/v1/accounts:';
const TOKEN = 'https://securetoken.googleapis.com/v1/token';
RC.Net = (cfg = {}) => {
const apiKey = cfg.apiKey || '';
const dbUrl = (cfg.dbUrl || '').replace(/\/+$/, '');
const enabled = /^AIza[\w-]+$/.test(apiKey) && /^https:\/\/.+firebase(io|database)\.(com|app)$/.test(dbUrl);
const store = Kit.store('robotclash.net');
const base = (cfg.serverUrl || '').replace(/\/+$/, '');
const enabled = cfg.enabled !== false && typeof fetch !== 'undefined' && (!!base || /^https?:$/.test(location.protocol));
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 fire = () => listeners.forEach(fn => { try { fn(cur()); } catch (e) { /* ignore */ } });
function cur() { return session ? { uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null; }
const cur = () => (session ? { uid: session.uid, name: session.name, email: session.email, guest: !!session.guest, admin: !!session.admin } : 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) {
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
function setSession(d) {
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(() => ({}));
if (!res.ok) { const msg = (data.error && data.error.message) || ('HTTP_' + res.status); const e = new Error(msg); e.code = 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;
}
function save() { store.set('session', session ? { refreshToken: session.refreshToken, uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null); }
function setAuth(d, name, guest) {
session = {
idToken: d.idToken || d.id_token, refreshToken: d.refreshToken || d.refresh_token,
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();
// another tab may already have refreshed: take its newer session instead of burning ours
function adoptStored() {
const s = stored();
if (s && session && s.uid === session.uid && s.refreshToken !== session.refreshToken && s.exp > Date.now()) { session = s; return true; }
return false;
}
async function refresh() {
if (!session || !session.refreshToken) return false;
try {
const d = await postJson(`${TOKEN}?key=${apiKey}`, { grant_type: 'refresh_token', refresh_token: session.refreshToken });
session.idToken = d.id_token; session.refreshToken = d.refresh_token; session.uid = d.user_id;
session.exp = Date.now() + (+d.expires_in - 60) * 1000; save(); return true;
} catch (e) { session = null; save(); fire(); return false; }
let refreshing = null;
function refresh() {
if (!session || !session.refreshToken) return Promise.resolve(false);
if (refreshing) return refreshing; // single flight
refreshing = (async () => {
if (adoptStored()) return true;
try { const d = await post('/api/auth/refresh', { refreshToken: session.refreshToken }); setSession(d); return true; } catch (e) {
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() {
if (!session) return null;
if (Date.now() >= session.exp) { if (!await refresh()) return null; }
return session.idToken;
if (Date.now() >= session.exp && !(await refresh())) return null;
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 = {
get current() { return cur(); },
onChange(fn) { listeners.push(fn); },
async register(email, pass, name) {
if (!enabled) return { ok: false, error: 'OFFLINE' };
email = String(email || '').trim().toLowerCase();
try {
const d = await postJson(`${AUTH}signUp?key=${apiKey}`, { email, password: pass, returnSecureToken: true });
setAuth(d, Kit.cleanName(name) || email.split('@')[0], false);
await dbWrite('PUT', `users/${session.uid}/name`, session.name); // name for later logins
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(`${AUTH}signInWithPassword?key=${apiKey}`, { email, password: pass, returnSecureToken: true });
setAuth(d, email.split('@')[0], false);
const name = await dbGet(`users/${session.uid}/name`); // needs the token -> after setAuth
if (typeof name === 'string' && name) { session.name = name; save(); fire(); }
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(`${AUTH}signUp?key=${apiKey}`, { returnSecureToken: true });
setAuth(d, Kit.cleanName(name) || 'Guest', true);
return { ok: true };
} catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
},
register: (name, pass, email) => authCall(() => post('/api/auth/register', { name: Kit.cleanName(name), pass, email: String(email || '').trim() })),
login: (login, pass) => authCall(() => post('/api/auth/login', { login: String(login || '').trim(), pass })),
guest: name => authCall(() => post('/api/auth/guest', { name: Kit.cleanName(name) || 'Guest' })),
resume() {
const s = store.get('session', null);
const s = stored();
if (!s || !s.refreshToken) return false;
session = Object.assign({ idToken: '', exp: 0 }, s);
refresh().then(ok => { if (ok) fire(); });
session = s;
if (Date.now() >= (s.exp || 0)) refresh().then(ok => { if (ok) fire(); }); else fire();
return true;
},
logout() { session = null; save(); fire(); },
};
async function dbGet(path) {
if (!enabled) return null;
const t = await token();
try {
const res = await fetch(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`, { cache: 'no-store' });
return res.ok ? await res.json() : null;
} catch (e) { return null; }
}
async function dbWrite(method, path, value) {
if (!enabled) return false;
const t = await token();
try {
const res = await fetch(`${dbUrl}/${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 = {
get: dbGet,
put: (p, v) => dbWrite('PUT', p, v),
patch: (p, v) => dbWrite('PATCH', p, v),
push: (p, v) => dbWrite('POST', p, v),
del: p => dbWrite('DELETE', p),
// EventSource push stream. RTDB sends 'put' (whole subtree at /) and 'patch' (partial) events.
stream(path, onValue) {
if (!enabled || typeof EventSource === 'undefined') return { close() {} };
let es = null, closed = false, value = null, retry = null;
const open = async () => {
if (closed) return;
const t = await token();
es = new EventSource(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`);
// 'put' = replace the value at d.path; 'patch' = merge d.data's children into d.path
const setAt = (keys, data) => {
if (!keys.length) { value = data; return; }
if (value == null || typeof value !== 'object') value = {};
let o = value;
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 (data == null) delete o[keys[keys.length - 1]]; else o[keys[keys.length - 1]] = data;
};
const apply = ev => {
let d; try { d = JSON.parse(ev.data); } catch (e) { return; }
if (!d || typeof d.path !== 'string') return;
const keys = d.path.split('/').filter(Boolean);
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);
es.addEventListener('patch', apply);
es.onerror = () => { if (closed) return; es.close(); retry = setTimeout(open, 1500); };
};
open();
return { close() { closed = true; clearTimeout(retry); if (es) es.close(); } };
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(() => {});
},
};
return { enabled, auth, db, get uid() { return session ? session.uid : null; }, token };
async function api(method, path, body) {
if (!enabled) return null;
for (let attempt = 0; attempt < 2; attempt++) {
const t = await token();
try {
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;
} catch (e) { return null; }
}
return null;
}
// ---- one WebSocket with reconnect -------------------------------------------------------------
const handlers = {};
const emit = (type, msg) => (handlers[type] || []).slice().forEach(fn => { try { fn(msg); } catch (e) { console.error(e); } });
let ws = null, want = false, retry = null, backoff = 1000, isOpen = false;
const wsUrl = () => {
const b = base || location.origin;
return b.replace(/^http/, 'ws') + '/ws';
};
async function open() {
if (!want || ws) return;
const t = await token();
if (!t || !want || ws) { if (want) schedule(); return; }
const s = ws = new WebSocket(wsUrl());
s.onopen = () => s.send(JSON.stringify({ t: 'hello', v: RC.Proto.VERSION, token: t }));
s.onmessage = ev => {
let msg; try { msg = JSON.parse(ev.data); } catch (e) { return; }
msg._bytes = ev.data.length; // for the network overlay (bandwidth)
if (msg.t === 'welcome') { isOpen = true; backoff = 1000; emit('open', msg); }
if (msg.t === 'error' && (msg.code === 'OUTDATED' || msg.code === 'REPLACED')) { want = false; emit(msg.code === 'OUTDATED' ? 'outdated' : 'replaced', msg); }
if (msg.t === 'error' && msg.code === 'UNAUTH' && session) session.exp = 0; // refresh before the retry
emit(msg.t, msg);
};
s.onclose = () => {
const was = isOpen; ws = null; isOpen = false;
if (was) emit('close', {});
if (want) schedule();
};
s.onerror = () => {};
}
function schedule() { clearTimeout(retry); retry = setTimeout(open, backoff); backoff = Math.min(10000, backoff * 2); }
const socket = {
get connected() { return isOpen; },
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, api, socket, token, get uid() { return session ? session.uid : null; } };
};
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -1,154 +1,102 @@
/* Robot Clash - live PvP sync over an existing deterministic fight. Needs net.js, combat.js, ai.js.
Robot 0 is always the local player, robot 1 the opponent (both clients see it that way, so the host
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.
/* Robot Clash - client side of a server-run live fight. No simulation here: the server steps RC.Combat;
this sends the local input and shows the server's snapshots (already mapped to "robot 0 = me").
const nf = RC.NetFight({ net, id, host, mySeat, oppStyle, oppSkill, onPeerLost(wasHost) });
nf.start()
HOST each tick, instead of the normal step:
nf.hostStep(s, localInput, dt) runs step with [local, remote|AI], publishes ~15 Hz, returns events
GUEST each frame, instead of step:
nf.guestFrame(s, localInput, dt) eases robots toward the last snapshot, returns events to play
nf.peerAlive false once the peer went silent > GRACE (AI takes over)
nf.stop()
Entity interpolation: snapshots (20 Hz) are buffered and rendered ~INTERP_DELAY ms in the past, between the two
snapshots bracketing the render time. This absorbs jitter (uneven arrival) so the robot does not jump - the old
"ease to the newest snapshot" had no buffer and jumped whenever a snapshot arrived late.
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. */
const nf = RC.NetFight({ net, seat, stats, interp, lag })
interp interpolation delay in ms (default 100); lag = { base, jit, seed } delays incoming snapshots (dev only)
nf.frame(s, input, dt) send input, show the interpolated world, return not-yet-seen events
nf.oppAway / nf.silentFor / nf.stop()
Pure, Node-testable: RC.NetFight.pickFrames(buf, renderTime), RC.NetFight.lerpRobot(da, db, k) */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const PUB = 1 / 15, GRACE = 4000; // ms without news before the AI covers for the peer
// robot fields the view / HUD / sound read - kept small for the wire
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 SEND_MIN = 1 / 30, SEND_KEEP = 0.25, INTERP_DEFAULT = 120, BUF_MAX = 30;
const EASE = ['x', 'z', 'y'], ANG = ['a', 'turretA'];
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
const mul = s => { let a = (s >>> 0) || 1; return () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };
// buf = [{ at, tick, snap }] sorted by at/tick ascending. Pick the snapshot reached by renderTime (a) and the
// next one (b), with the fraction between them. Past the newest -> hold the newest (a === b, frac 1).
function pickFrames(buf, renderTime) {
if (!buf.length) return null;
let a = buf[0], b = null;
for (let i = 0; i < buf.length; i++) { if (buf[i].at <= renderTime) a = buf[i]; else { b = buf[i]; break; } }
const span = b ? (b.at - a.at) : 0;
const frac = b && span > 0 ? Math.min(1, Math.max(0, (renderTime - a.at) / span)) : (b ? 0 : 1);
return { a, b: b || a, frac };
}
// blend two robot snapshots: positions/angles interpolate, discrete fields come from the reached snapshot (da)
function lerpRobot(da, db, k) {
const r = {};
for (const f of (RC.Proto ? RC.Proto.RF : Object.keys(da))) if (da[f] !== undefined && !EASE.includes(f) && !ANG.includes(f)) r[f] = da[f];
for (const f of EASE) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + (db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
for (const f of ANG) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + wrap(db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
r.lost = Object.assign({}, da.lost); r.lostW = (da.lostW || []).slice(); r.W = (da.W || []).map(w => Object.assign({}, w));
return r;
}
RC.NetFight = (opt) => {
const net = opt.net, db = net.db, id = opt.id, host = opt.host;
const base = `matches/${id}`;
let pubT = 0, seq = 0, sendT = 0, beatT = 0, lastInSeq = -1, evBuf = [];
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;
const sock = opt.net.socket, seat = opt.seat;
const DELAY = opt.interp > 0 ? opt.interp : INTERP_DEFAULT;
const lag = opt.lag && opt.lag.base >= 0 ? opt.lag : null, rng = lag ? mul(lag.seed || 1) : null;
const stats = opt.stats || null;
const buf = []; // in-order snapshot buffer
let newest = null, lastTick = -1, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
function start() {
if (host) {
// host reads the guest's input stream
subIn = db.stream(`${base}/in`, v => { if (v && typeof v.seq === 'number') { remoteInput = v; lastPeer = Date.now(); } });
} else {
// guest reads the host's state stream
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 accept(m) { // a snapshot arrived (possibly delayed by the dev lag injector)
const snap = RC.Proto.toLocal(seat, m);
lastSnap = Date.now(); newest = snap;
if (stats) stats.snap(snap, m._bytes, performance.now());
if (m.tick <= lastTick) return; // out of order (rare) -> drop, keep the buffer monotonic
lastTick = m.tick;
buf.push({ at: Date.now(), tick: m.tick, snap });
while (buf.length > BUF_MAX) buf.shift();
}
const off = sock.on('snap', m => {
if (!lag) return accept(m);
setTimeout(() => accept(m), Math.max(0, lag.base + (rng() * 2 - 1) * lag.jit));
});
const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3;
function sendInput(inp, dt) {
sendT -= dt; keepT -= dt;
if (sendT > 0 || (!changed(inp) && keepT > 0)) return;
const i = RC.Proto.input(inp);
if (sock.send(Object.assign({ t: 'input', seq: ++seq }, i))) { prev = i; sendT = SEND_MIN; keepT = SEND_KEEP; if (stats) stats.inputSent(seq, performance.now()); }
}
function checkPeer() {
if (!started) { started = true; lastPeer = Math.max(lastPeer, Date.now()); } // countdown is over: start the clock
if (!peerAlive && Date.now() - lastPeer < GRACE) { peerAlive = true; if (opt.onPeerBack) opt.onPeerBack(host); }
if (peerAlive && Date.now() - lastPeer > GRACE) {
peerAlive = false;
if (host && !ai) ai = RC.AI.create({ style: opt.oppStyle || 'brawler', skill: opt.oppSkill != null ? opt.oppSkill : 0.5, seed: 7 });
if (opt.onPeerLost) opt.onPeerLost(host);
}
}
const applyRobot = (r, d) => { Object.assign(r, d); };
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
// index 0 is the LOCAL player (so game.js renders identically on both sides).
function hostStep(s, localInput, dt) {
checkPeer();
const guestInput = peerAlive ? remoteInput : ai.think(s, s.robots[1], s.robots[0], dt);
RC.Combat.step(s, dt, [localInput, guestInput]);
if (s.events.length) evBuf.push.apply(evBuf, s.events); // batch events between publishes for the guest
pubT -= dt;
// publish only when the previous write came back - otherwise slow uploads queue up and the host stutters
if (pubT <= 0 && !sending) {
pubT = PUB + slow;
sending = true;
const t0 = Date.now();
const payload = {
seq: ++seq, t: rnd(s.t), left: rnd(s.left), pitOpen: rnd(s.pitOpen), pitAlarm: s.pitAlarm,
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) })),
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;
function frame(s, inp, dt) {
sendInput(inp, dt);
if (!buf.length) return [];
const renderTime = Date.now() - DELAY;
const fr = pickFrames(buf, renderTime), na = fr.a.snap, nb = fr.b.snap, k = fr.frac;
s.t = na.time; s.left = na.left; s.pitOpen = na.pitOpen; s.pitAlarm = na.pitAlarm; s.endIn = na.endIn;
s.press.st = na.press.st; s.press.y = na.press.y;
Object.assign(s.crane, na.crane);
syncList(s.rockets, na.rockets, { sp: 6, t: 3 });
syncList(s.mines, na.mines, { r: 0.85 });
applyRobot(s.robots[0], lerpRobot(na.robots[0], nb.robots[0], k));
applyRobot(s.robots[1], lerpRobot(na.robots[1], nb.robots[1], k));
if (na.result) s.result = na.result;
while (buf.length > 2 && buf[1].at <= renderTime) buf.shift(); // keep one snapshot older than renderTime
if (fr.a.tick === seenTick) return [];
seenTick = fr.a.tick;
return na.ev || [];
}
// 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);
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]);
}
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 {
start, hostStep, guestFrame,
// during the countdown: keep the line alive (guest sends a neutral input, host an empty state ping)
idle(dt) {
sendT -= dt;
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(); },
frame,
get oppAway() { return !!(newest && newest.away && newest.away[1]); },
get silentFor() { return (Date.now() - lastSnap) / 1000; },
stop() { off(); },
};
};
RC.NetFight.pickFrames = pickFrames;
RC.NetFight.lerpRobot = lerpRobot;
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

73
game/netoverlay.js Normal file
View File

@@ -0,0 +1,73 @@
/* Robot Clash - network overlay (F3 or ?net): ping graph of the last 10 s and a plain-language reading of
where lag comes from (your line, the opponent's line, the server). Measurements: netstats.js.
const ov = RC.NetOverlay({ stats, net, t, mount }) mount = #stage; pings the server once a second
ov.toggle() / ov.visible */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const SECS = 10, MAX_MS = 300, W = 300, H = 84;
const COL = { ping: '#ff7a1a', opp: '#4aa8ff', gap: '#6dff9e', input: '#e8ebf2' };
const LEVEL = { ok: '#6dff9e', warn: '#ffc940', bad: '#ff5a4a' };
RC.NetOverlay = function (opt) {
const { stats, net, t } = opt;
const el = document.createElement('div');
el.id = 'netov';
el.className = 'hide';
el.innerHTML = `<div class="nvh"></div><canvas width="${W}" height="${H}"></canvas><div class="nvleg"></div><div class="nvrows"></div><div class="nvv"></div>`;
opt.mount.appendChild(el);
const cv = el.querySelector('canvas'), cx = cv.getContext('2d');
let visible = false, drawT = null;
// my ping: one tiny message per second while connected (also when hidden, so the history is there)
setInterval(() => { if (net.enabled && net.socket.connected) net.socket.send({ t: 'ping', t0: performance.now() }); }, 1000);
net.socket.on('pong', m => { if (typeof m.t0 === 'number') { const now = performance.now(); stats.pong(now - m.t0, now); } });
function graph(now) {
cx.clearRect(0, 0, W, H);
cx.fillStyle = 'rgba(0,0,0,.35)'; cx.fillRect(0, 0, W, H);
cx.strokeStyle = 'rgba(255,255,255,.12)'; cx.lineWidth = 1;
for (const ms of [50, 100, 200]) { const y = H - ms / MAX_MS * H; cx.beginPath(); cx.moveTo(0, y); cx.lineTo(W, y); cx.stroke(); }
cx.fillStyle = 'rgba(255,255,255,.35)'; cx.font = '9px monospace';
for (const ms of [50, 100, 200]) cx.fillText(ms + 'ms', 2, H - ms / MAX_MS * H - 2);
const pts = stats.series(now, SECS);
for (const k of ['gap', 'input', 'opp', 'ping']) {
cx.strokeStyle = COL[k]; cx.lineWidth = k === 'ping' ? 2 : 1.2; cx.beginPath();
let first = true;
for (const p of pts) {
if (p[k] === undefined) continue;
const x = W - (now - p.t) / (SECS * 1000) * W, y = H - Math.min(MAX_MS, p[k]) / MAX_MS * H;
if (first) { cx.moveTo(x, y); first = false; } else cx.lineTo(x, y);
}
cx.stroke();
}
}
function draw() {
const now = performance.now(), s = stats.summary(now);
el.querySelector('.nvh').textContent = t('net_title');
el.querySelector('.nvleg').innerHTML = ['ping', 'opp', 'gap', 'input'].map(k => `<span><i style="background:${COL[k]}"></i>${t('net_l_' + k)}</span>`).join('');
const row = (label, val) => `<span>${label}</span><b>${val}</b>`;
el.querySelector('.nvrows').innerHTML =
row(t('net_ping'), s.ping ? `${s.ping} ms <small>(max ${s.pingMax})</small>` : '–')
+ (s.fight ? row(t('net_ping_srv'), `${s.serverPing} ms`)
+ row(t('net_ping_opp'), `${s.oppPing} ms`)
+ row(t('net_snaps'), `${s.gap} ms ±${s.jitter}${s.late ? ` · ${s.late} ${t('net_late')}` : ''}`)
+ row(t('net_input'), s.input ? `${s.input} ms` : '–')
+ row(t('net_server'), `${s.tickMs} ms · ${s.kbps} kbit/s`) : '');
el.querySelector('.nvv').innerHTML = RC.NetStats.verdict(s)
.map(v => `<div style="color:${LEVEL[v.level]}">${v.level === 'ok' ? '✔' : v.level === 'warn' ? '⚠' : '✖'} ${t(v.key, { n: v.n })}</div>`).join('');
graph(now);
}
function toggle(on) {
visible = on === undefined ? !visible : !!on;
el.classList.toggle('hide', !visible);
clearInterval(drawT);
if (visible) { draw(); drawT = setInterval(draw, 250); }
}
addEventListener('keydown', e => { if (e.key === 'F3') { e.preventDefault(); e.stopPropagation(); toggle(); } }, true);
return { toggle, get visible() { return visible; } };
};
})(typeof window !== 'undefined' ? window : globalThis);

78
game/netstats.js Normal file
View File

@@ -0,0 +1,78 @@
/* Robot Clash - network measurements for the F3 overlay. No DOM (Node-testable).
const st = RC.NetStats()
st.pong(rttMs, now) my ping, measured by the client (ping/pong over the WebSocket)
st.snap(localSnap, bytes, now) a snapshot arrived (already RC.Proto.toLocal'ed: rtt = [me, opponent])
st.inputSent(seq, now) input seq left the client
st.summary(now) -> { ping, pingMax, serverPing, oppPing, gap, jitter, late, input, tickMs, kbps, snapAge, fight }
st.series(now, seconds) -> samples for the graph [{ t, ping, opp, gap, input }]
RC.NetStats.verdict(summary) -> [{ key, level: 'ok'|'warn'|'bad', n }] (lang keys nv_*)
How to read it: ping = you <-> server. oppPing = the opponent <-> server (the server measures it).
gap/jitter = how evenly the 20 snapshots/s reach YOU (unsteady = your line). input = key press until the
server confirms it (~ping + up to one server step; much more = queueing somewhere). tickMs = server load. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const KEEP = 20000; // ms of history
RC.NetStats = function () {
const pings = [], snaps = [], inputs = new Map(), delays = [];
let lastSnapAt = 0;
const trim = (arr, now) => { while (arr.length && now - arr[0].t > KEEP) arr.shift(); };
const avg = a => (a.length ? a.reduce((s, x) => s + x, 0) / a.length : 0);
const recent = (arr, now, ms) => arr.filter(x => now - x.t <= ms);
return {
pong(rtt, now) { pings.push({ t: now, v: rtt }); trim(pings, now); },
inputSent(seq, now) { inputs.set(seq, now); if (inputs.size > 400) inputs.delete(inputs.keys().next().value); },
snap(s, bytes, now) {
const gap = lastSnapAt ? now - lastSnapAt : 0;
lastSnapAt = now;
snaps.push({ t: now, gap, bytes: bytes || 0, opp: s.rtt ? s.rtt[1] : 0, srv: s.rtt ? s.rtt[0] : 0, tickMs: s.tickMs || 0 });
trim(snaps, now);
// server confirmed every input up to s.ack: the oldest unconfirmed send time gives the delay
if (s.ack) for (const [seq, at] of inputs) { if (seq > s.ack) break; if (seq === s.ack) delays.push({ t: now, v: now - at }); inputs.delete(seq); }
trim(delays, now);
},
summary(now) {
const p = recent(pings, now, 5000).map(x => x.v), sn = recent(snaps, now, 5000), d = recent(delays, now, 5000).map(x => x.v);
const gaps = sn.map(x => x.gap).filter(g => g > 0), g = avg(gaps);
const jitter = gaps.length ? Math.sqrt(avg(gaps.map(x => (x - g) ** 2))) : 0;
const last = sn[sn.length - 1];
return {
ping: Math.round(avg(p)), pingMax: Math.round(p.length ? Math.max(...p) : 0),
serverPing: last ? last.srv : 0, oppPing: last ? last.opp : 0,
gap: Math.round(g), jitter: Math.round(jitter), late: gaps.filter(x => x > 110).length,
input: Math.round(avg(d)), tickMs: last ? last.tickMs : 0,
kbps: Math.round(sn.reduce((s, x) => s + x.bytes, 0) * 8 / 5 / 1000),
snapAge: lastSnapAt ? now - lastSnapAt : Infinity, fight: !!(lastSnapAt && now - lastSnapAt < 3000),
};
},
series(now, seconds = 10) {
const from = now - seconds * 1000, out = [];
for (const x of snaps) if (x.t >= from) out.push({ t: x.t, gap: x.gap, opp: x.opp });
for (const x of pings) if (x.t >= from) out.push({ t: x.t, ping: x.v });
for (const x of delays) if (x.t >= from) out.push({ t: x.t, input: x.v });
return out.sort((a, b) => a.t - b.t);
},
reset() { snaps.length = 0; delays.length = 0; inputs.clear(); lastSnapAt = 0; },
};
};
// plain-language reading of a summary; thresholds tuned for a 20 Hz action game
RC.NetStats.verdict = function (s) {
const out = [];
if (s.ping > 150) out.push({ key: 'nv_me_slow', level: s.ping > 250 ? 'bad' : 'warn', n: s.ping });
if (s.fight) {
if (s.jitter > 30 || s.late > 3) out.push({ key: 'nv_me_jitter', level: s.jitter > 60 || s.late > 10 ? 'bad' : 'warn', n: s.jitter });
if (s.oppPing > 150) out.push({ key: 'nv_opp_slow', level: s.oppPing > 250 ? 'bad' : 'warn', n: s.oppPing });
if (s.tickMs > 4) out.push({ key: 'nv_server', level: s.tickMs > 10 ? 'bad' : 'warn', n: s.tickMs });
if (s.input > s.ping + 150 && s.input > 200) out.push({ key: 'nv_queue', level: 'warn', n: s.input });
} else if (s.snapAge !== Infinity && s.snapAge > 3000 && s.snapAge < 30000) out.push({ key: 'nv_lost', level: 'bad', n: Math.round(s.snapAge / 1000) });
if (!out.length) out.push({ key: s.fight ? 'nv_ok' : 'nv_nofight', level: 'ok', n: 0 });
return out;
};
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

257
game/online.js Normal file
View File

@@ -0,0 +1,257 @@
/* Robot Clash - online play in the browser: server-checked workshop actions (act), online save sync, login card, lobby, live fight start/end.
Part of game.js (split for size): created once by game.js with the shared context G.
Live state (save, mode, F, ...) is read as G.<name>; services/helpers are taken from G at creation. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
RC.GameOnline = function (G) {
const {
$, FLAGS, SFX, accounts, achHtml, card, ensureFlag, enterAccount, esc, fbAcc, flagHtml, hideOverlay, hud,
img, layer, loadSave, lobby, net, openGarage, overlay, paintObj, persist, playerName, prepOpp,
refreshDev, renderWeaponEditor, repairSave, setMode, setScreen, shop, showLegal, showTitle, startFight,
t
} = G;
// ---- online save: the server is the authority for money, fame, parts and robots -------------------
// act(): every workshop change goes through RC.Eco (game/eco.js). Applied locally at once; online the same
// action is sent to the server (one at a time, in order) and the server's answer replaces our economy fields.
let actQueue = Promise.resolve();
function act(a) {
const r = RC.Eco.apply(G.save, a);
if (!r.ok) return r;
if (G.gameMode === 'online' && net.enabled && net.uid) {
actQueue = actQueue.then(() => net.api('POST', '/api/online/action', a)).then(res => {
if (!res || !res.save) return;
if (!res.ok || econDiffers(res.save)) { adoptEconomy(res.save); afterEconomy(); }
}, () => {});
}
return r;
}
const econKey = s => JSON.stringify([s.money, s.fame, s.owned, s.active, (s.robots || []).map(r => r.build)]);
const econDiffers = srv => econKey(srv) !== econKey(G.save);
// keepLooks: robot names/paint are client-owned - keep ours (they may not be uploaded yet)
function adoptEconomy(srv, keepLooks = true) {
const looks = keepLooks && G.save.robots ? G.save.robots.map(r => ({ name: r.name, paint: r.paint })) : [];
for (const k of RC.Eco.ECONOMY) if (srv[k] !== undefined) G.save[k] = srv[k];
if (keepLooks && looks.length === G.save.robots.length) G.save.robots.forEach((r, i) => { r.name = looks[i].name; r.paint = looks[i].paint; });
RC.Eco.mirror(G.save);
G.slot.save(G.save);
}
function afterEconomy() {
hud();
if (G.mode === 'garage') { shop.render(); G.view.showGarage(G.save.build, paintObj()); if (G.editorOpen) renderWeaponEditor(); }
}
// cosmetics (names, paint, flag, ...) are client-owned: debounced upload, the server keeps only those fields
let pushTimer = null;
const cosmetics = () => {
const c = {};
for (const k of RC.Eco.COSMETIC) if (G.save[k] !== undefined) c[k] = G.save[k];
c.robots = G.save.robots.map(r => ({ name: r.name, paint: r.paint }));
return c;
};
function onlinePush() { clearTimeout(pushTimer); pushTimer = setTimeout(onlineFlush, 1500); }
function onlineFlush() {
clearTimeout(pushTimer);
if (G.gameMode === 'online' && G.save && net.uid) net.api('PUT', '/api/online/save', cosmetics());
}
// after login / page load: economy from the server; cosmetics from whichever copy is newer
function onlinePull() {
if (G.gameMode !== 'online' || !net.uid) return;
const uid = net.uid;
net.api('GET', '/api/online').then(srv => {
if (!srv || !G.save || G.gameMode !== 'online' || net.uid !== uid) return;
const serverNewer = (+srv.ts || 0) > (+G.save.ts || 0);
if (serverNewer) { for (const k of RC.Eco.COSMETIC) if (srv[k] !== undefined) G.save[k] = srv[k]; }
adoptEconomy(srv, !serverNewer);
repairSave();
RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); });
if (!serverNewer) onlinePush();
afterEconomy();
});
}
// ---------------------------------------------------------------- online lobby
// The server owns presence, challenges and fights (server/lobby.js). This draws its state and forwards clicks.
const myRoom = () => G.joinedRoom || (FLAGS.includes(G.save.flag) ? G.save.flag : 'XX');
const pendingOut = () => (lobby ? lobby.pending : null);
function wireLobby() {
lobby.onList(rows => { G.lobbyRows = rows; if (G.mode === 'lobby') renderLobby(); });
lobby.onIncoming(c => { if (G.mode === 'lobby' || G.mode === 'garage') showIncoming(c); });
lobby.onMatch(m => startOnlineFight(m));
lobby.onEnd(m => onlineFightEnded(m));
lobby.onCancel(c => {
if (G.mode === 'lobby') { renderLobby(); if (c.outgoing) SFX.deny(); }
else if (!c.outgoing && $('cYes')) hideOverlay(); // the challenger gave up while I was asked
});
lobby.onError(code => {
SFX.deny();
if (G.mode === 'lobby') { renderLobby(); const el = $('lMsg'); if (el) el.textContent = errText(code); }
else if (G.mode === 'garage') $('mechTip').textContent = errText(code);
});
net.socket.on('outdated', () => {
card(`<h2>${t('reload_title')}</h2><p>${t('e_OUTDATED')}</p><div class="row"><button class="primary" id="rNow">${t('reload_now')}</button></div>`, { bg: 'bg_title.jpg' });
$('rNow').onclick = () => location.reload();
});
net.socket.on('replaced', () => { if (G.mode === 'lobby') { const el = $('lMsg'); if (el) el.textContent = t('e_REPLACED'); } });
}
async function startOnline(dest) { // dest 'lobby' -> player list, else the workshop (main page)
if (!net.enabled) return;
if (G.gameMode !== 'online') { setMode('online'); if (G.save) { loadSave(); hud(); } } // online uses its own save
if (!net.auth.current) {
if (G.save && !fbAcc()) return joinAnon(); // playing as guest -> straight in, anonymously
showOnlineLogin(false, null, 'online'); return;
}
if (!G.save || !G.slot) { if (!fbAcc()) accounts.guest(); loadSave(); }
if (!G.onlineReady) { wireLobby(); G.onlineReady = true; }
lobby.enter();
ensureFlag(() => { if (dest === 'lobby') showLobby(); else openGarage(); }); // country first, then main page / lobby
}
async function joinAnon() {
if (!G.save) { accounts.guest(); loadSave(); }
const r = await net.auth.guest(playerName() || t('guest'));
if (!r.ok) { SFX.deny(); showOnlineLogin(false, r.error, 'online'); return; }
hud(); refreshDev(); loadSave(); startOnline();
}
const errText = c => (window.LANG.en['e_' + c] ? t('e_' + c) : t('e_ERROR') + ' (' + esc(c) + ')');
function showOnlineLogin(reg, errKey, next) {
next = next || 'career';
setScreen('account');
const f = reg
? `<label>${t('f_name')}</label><input type="text" id="oName" maxlength="18" autocomplete="username">
<label>${t('f_email_opt')}</label><input type="email" id="oMail" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" inputmode="email">`
: `<label>${t('f_login')}</label><input type="text" id="oLogin" autocomplete="username" autocapitalize="off" autocorrect="off" spellcheck="false">`;
card(`<h2>${reg ? t('register') : t('login')}</h2><p>${t('online_login_text')}</p>
<div class="form">${f}
<label>${t('f_pass')}</label><input type="password" id="oPass" autocomplete="${reg ? 'new-password' : 'current-password'}"></div>
${reg ? `<label class="chk"><input type="checkbox" id="oConsent"> ${t('consent_pre')} <button type="button" class="link" id="oPriv">${t('legal_privacy')}</button></label>` : ''}
<div class="err" id="oErr">${errKey ? errText(errKey) : ''}</div>
<div class="row"><button id="oBack">${t('back')}</button><button class="primary" id="oGo">${reg ? t('register_go') : t('login')}</button></div>
<p class="muted">${reg ? '' : t('no_account') + ' '}<button class="link" id="oToggle">${reg ? t('login') : t('register')}</button></p>
${next === 'online' ? `<div class="row"><button id="oAnon">👤 ${t('online_guest')}</button></div>` : ''}`, { bg: 'bg_title.jpg' });
if ($('oAnon')) $('oAnon').onclick = () => { SFX.click(); joinAnon(); };
if ($('oPriv')) $('oPriv').onclick = () => { SFX.click(); showLegal(() => showOnlineLogin(true, null, next), 'privacy'); };
$('oBack').onclick = () => { SFX.click(); showTitle(); };
$('oToggle').onclick = () => { SFX.click(); showOnlineLogin(!reg, null, next); };
$('oGo').onclick = async () => {
if (reg && $('oConsent') && !$('oConsent').checked) { SFX.deny(); $('oErr').textContent = t('consent_required'); return; }
$('oGo').disabled = true;
const r = reg ? await net.auth.register($('oName').value, $('oPass').value, $('oMail').value)
: await net.auth.login($('oLogin').value, $('oPass').value);
if (!r.ok) { SFX.deny(); showOnlineLogin(reg, r.error, next); return; }
SFX.click(); hud(); refreshDev();
if (next === 'online') { loadSave(); startOnline(); } else enterAccount(reg);
};
overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Enter') $('oGo').click(); }));
setTimeout(() => { const el = $(reg ? 'oName' : 'oLogin'); if (el) el.focus(); }, 50);
}
function showLobby() {
if (!G.lobbyRoom) G.lobbyRoom = 'all'; // filter: 'all' or a country code
setScreen('lobby'); renderLobby();
}
// two-pane lobby: country rooms on the left, players of the chosen room on the right (own style, not copied art)
function renderLobby() {
const code = r => { const c = r.room || r.flag; return FLAGS.includes(c) ? c : 'XX'; }; // group by the room a player JOINED, not their flag
const all = G.lobbyRows;
const myFlag = FLAGS.includes(G.save.flag) ? G.save.flag : 'XX', mine = myRoom();
// I am in the lobby too: count myself in the room I joined (and in "all"), and only list me there
const total = all.length + 1;
const cnt = f => all.filter(r => code(r) === f).length + (f === mine ? 1 : 0);
const here = G.lobbyRoom === 'all' ? all : all.filter(r => code(r) === G.lobbyRoom);
const showMe = G.lobbyRoom === 'all' || G.lobbyRoom === mine;
const out = pendingOut();
const flagOpts = FLAGS.map(f => `<option value="${f}" ${f === myFlag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join('');
const room = (f, label, flag) => `<button class="rroom ${G.lobbyRoom === f ? 'on' : ''} ${f === mine ? 'joined' : ''}" data-f="${f}"><span class="rfl">${flag ? flagHtml(f) : ''}</span><span class="rn">${label}${f === mine ? ' <span class="rhere">📍</span>' : ''}</span><span class="cnt ${cnt(f) ? 'live' : ''}">${f === 'all' ? total : cnt(f)}</span></button>`;
const rooms = room('all', t('all_countries'), false) + FLAGS.map(f => room(f, t('cc_' + f), true)).join('');
const action = r => (r.state === 'idle' && !out ? `<button class="chal" data-uid="${esc(r.uid)}">${t('challenge')}</button>` : `<span class="pbusy">${r.state === 'idle' ? '' : t('busy')}</span>`);
const prow = (r, me) => `<div class="prow ${me ? 'me' : ''}" ${me ? '' : `data-uid="${esc(r.uid)}"`}><span class="pf">${flagHtml(me ? G.save.flag : r.flag)}</span><span class="pn">${esc(me ? playerName() : r.name)}${me ? ` <span class="muted">(${t('you')})</span>` : ''}</span><span class="pfame">⭐ ${Kit.fmt((me ? G.save.fame : r.fame) | 0)}</span>${me ? '<span class="pbusy"></span>' : action(r)}</div>`;
const list = here.map(r => prow(r, false)).join('');
const title = G.lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(G.lobbyRoom) + ' ' + t('cc_' + G.lobbyRoom);
const offline = lobby && !lobby.connected ? `<p class="muted" style="margin:6px 0 0">${t('net_connecting')}</p>` : '';
overlay.innerHTML = `<div class="lobbyfull">
<div class="lobbyL"><div class="lobbyLh">🌍 ${t('lobby')}</div><div class="roomlist">${rooms}</div></div>
<div class="lobbyR">
<div class="lobbyRh">${title} <span class="muted">(${here.length + (showMe ? 1 : 0)})</span><span class="grow"></span>
<label class="flagpick">${t('your_flag')} <select id="lFlag">${flagOpts}</select></label></div>
<div class="plist">${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `<div class="muted" style="padding:16px;text-align:center">${t('lobby_empty')}</div>`)}</div>
${out ? `<p class="muted" style="margin:6px 0 0">${t('waiting_accept')} <button class="link" id="lCancel">${t('cancel')}</button></p>` : ''}
${offline}<p class="err" id="lMsg" style="margin:4px 0 0"></p>
<div class="row" style="margin-top:8px"><button id="lBack">${t('back')}</button><button class="primary" id="lQuick">${t('quick_match')}</button></div>
</div></div>`;
overlay.classList.remove('hide'); overlay.classList.remove('clear');
overlay.style.backgroundImage = `linear-gradient(rgba(5,6,10,.6), rgba(5,6,10,.8)), url("${img('bg_title.jpg')}")`;
overlay.querySelectorAll('.rroom').forEach(b => { b.onclick = () => {
SFX.click(); G.lobbyRoom = b.dataset.f;
if (G.lobbyRoom !== 'all') { G.joinedRoom = G.lobbyRoom; if (lobby) lobby.setRoom(G.joinedRoom); } // joining a country = be present there
renderLobby();
}; });
$('lFlag').onchange = e => { G.save.flag = e.target.value; persist(); onlineFlush(); renderLobby(); };
overlay.querySelectorAll('.chal').forEach(b => { b.onclick = () => { SFX.click(); lobby.challenge(b.dataset.uid); renderLobby(); }; });
if ($('lCancel')) $('lCancel').onclick = () => { SFX.click(); lobby.cancel(); renderLobby(); };
$('lQuick').onclick = () => { const idle = here.find(r => r.state === 'idle') || all.find(r => r.state === 'idle'); if (idle && !pendingOut()) { SFX.click(); lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); };
$('lBack').onclick = () => { SFX.click(); if (G.save) openGarage(); else showTitle(); };
}
function showIncoming(c) {
card(`<h2>${t('challenge_in')}</h2><p>${flagHtml(c.fromFlag)} <b>${esc(c.fromName)}</b> ${t('wants_fight')}</p>
<div class="row"><button id="cNo">${t('decline')}</button><button class="primary" id="cYes">${t('accept')}</button></div>`);
$('cYes').onclick = () => { SFX.click(); lobby.accept(c.from); };
$('cNo').onclick = () => { SFX.click(); lobby.decline(c.from); if (G.mode === 'lobby') renderLobby(); else hideOverlay(); };
}
// server says: fight on (also after a reconnect into a running fight)
function startOnlineFight(m) {
const mine = m.robots[m.seat], other = m.robots[1 - m.seat];
const opp = { name: other.name, build: other.build, paint: other.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: other.flag };
prepOpp(opp, () => startFight(opp, false, false, { id: m.matchId, seat: m.seat, seed: m.seed, arena: m.arena, countdown: m.countdown, myBuild: mine.build }));
}
// server result + rewards (the fight on screen ends with it; if we missed the fight, just take the new save)
function onlineFightEnded(m) {
if (G.F && G.F.online && G.F.online.id === m.matchId && !G.F.ended) {
G.F.serverEnd = m;
G.F.s.result = RC.Proto.localResult(m.seat, m.result);
G.F.s.endIn = 0;
return;
}
if (m.save && G.gameMode === 'online') { adoptEconomy(m.save); afterEconomy(); }
}
// live fight over: the server already booked prize, repairs and achievements - show them and take its save
function endOnlineFight(res, won, me) {
if (G.F.nf) G.F.nf.stop();
const m = G.F.serverEnd, rw = (m && m.reward) || { money: 0, fame: 0, lines: [], ach: [] };
if (m && m.save) { adoptEconomy(m.save); persist(); }
(won ? SFX.win : SFX.lose)();
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
const sm = (m && m.summary) || { dealt: me.dealt, taken: me.taken };
const rows = rw.lines.map(([k, v]) => `<span>${t(k)}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
const ach = (rw.ach || []).map(a => ({ id: a.id, reward: a.reward }));
hud();
setScreen('result');
card(`<h1>${title}</h1><p>${esc(G.F.opp.name)} ${G.F.oppAway ? t('peer_left') : ''}</p>
<div class="res"><span>${t('r_dealt')}</span><span>${Math.round(sm.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(sm.taken)}</span>${rows}
${rw.fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(rw.fame)}</span>` : ''}</div>
${achHtml(ach)}
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button><button id="bShopO">${t('to_garage')}</button></div>`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bLobby').onclick = () => { SFX.click(); showLobby(); };
$('bShopO').onclick = () => { SFX.click(); openGarage(); };
}
// the server went silent mid-fight: leave the arena; the result (if any) is booked server-side anyway
function onlineFightLost() {
if (G.F && G.F.nf) G.F.nf.stop();
SFX.deny();
setScreen('result');
card(`<h2>${t('net_lost')}</h2><p>${t('match_lost')}</p>
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button></div>`, { bg: 'bg_lose.jpg' });
$('bLobby').onclick = () => { SFX.click(); onlinePull(); showLobby(); };
}
return {
actQueue, act, econKey, econDiffers, adoptEconomy, afterEconomy, pushTimer, cosmetics, onlinePush,
onlineFlush, onlinePull, myRoom, pendingOut, wireLobby, startOnline, joinAnon, errText, showOnlineLogin,
showLobby, renderLobby, showIncoming, startOnlineFight, onlineFightEnded, endOnlineFight,
onlineFightLost
};
};
})(window);

271
game/pages.js Normal file
View File

@@ -0,0 +1,271 @@
/* Robot Clash - menu pages: settings, help, tutorial, country, achievements, missions, legal, ranking board.
Part of game.js (split for size): created once by game.js with the shared context G.
Live state (save, mode, F, ...) is read as G.<name>; services/helpers are taken from G at creation. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
RC.GamePages = function (G) {
const {
$, CAMS, FLAGS, L, SFX, accounts, act, audio, card, currentBack, ensureMissions, esc, fbAcc, flagHtml,
hud, layer, liveText, logout, net, newSave, openGarage, overlay, overlayEnter, persist, rank,
saveSettings, settings, shop, showLeague, showTournament, skipIntro, t, togglePause, tourState
} = G;
// ---------------------------------------------------------------- settings / help / ranking
function showSettings(back) {
overlayEnter();
const prev = G.mode;
const seg = (id, val, opts) => `<div class="seg" id="${id}">${opts.map(([v, label]) => `<button data-v="${v}" class="${v === val ? 'on' : ''}">${label}</button>`).join('')}</div>`;
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
const item = (label, ctl) => `<span class="sl">${label}</span>${ctl}`;
card(`<h2>${t('settings')}</h2><div class="set2">
${item(t('s_lang'), seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self])))}
${G.save ? item(t('s_country'), `<select id="sCountry" class="selset">${FLAGS.map(f => `<option value="${f}" ${f === G.save.flag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join('')}</select>`) : ''}
${item(t('s_music'), `<input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">`)}
${item(t('s_sfx'), `<input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">`)}
${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))}
${item(t('s_cam'), seg('sCam', settings.cam, CAMS.map(c => [c, t('cam_' + c)])))}
${item(t('s_comfort'), seg('sComfort', settings.comfort ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
${item(t('s_steer'), seg('sSteer', settings.steer, [['tank', t('steer_tank')], ['simple', t('steer_simple')]]))}
${item(t('s_autofire'), seg('sAuto', settings.autofire ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
${item(t('s_quiet'), seg('sQuiet', settings.quiet ? '1' : '0', [['0', t('off')], ['1', t('on')]]))}
${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))}
${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
</div>
${G.isDev && G.save ? `<div class="setdev"><span class="sl">🛠 Dev · Coins</span><div class="row">
<button data-coin="10000">+10k</button><button data-coin="100000">+100k</button>
<button data-coin="1000000">+1M</button><button data-coin="set800">Reset 800</button></div></div>` : ''}
<div class="setacc"><span class="sl">${t('s_account')}</span>
<span class="who">${who ? '👤 <b>' + esc(who.name) + '</b>' + (who.email ? ' <span class="muted">' + esc(who.email) + '</span>' : '') : '👤 ' + t('guest')}</span>
${G.save ? `<button id="sOut">${who ? t('logout') : t('to_title')}</button>` : ''}</div>
<div class="row"><button id="sFull">⛶ ${t('win_full')}</button><button id="sKeys">🎮 ${t('s_controls')}</button>
<button id="sLegal">§ ${t('legal')}</button>${G.save ? `<button id="sReset">${t('reset')}</button>` : ''}<button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, clear: prev === 'title' || prev === 'intro' });
const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; });
segOn('sLang', v => { L.set(v); showSettings(back); });
segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (G.view) G.view.setQuality(v); });
segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); });
segOn('sSteer', v => { settings.steer = v; saveSettings(); });
segOn('sCam', v => { settings.cam = v; saveSettings(); if (G.view) G.view.setCam(v); });
segOn('sComfort', v => { settings.comfort = v === '1'; saveSettings(); if (G.view && G.view.setComfort) G.view.setComfort(settings.comfort); });
segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); });
segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); });
segOn('sArena', v => { settings.arena = v; saveSettings(); });
if ($('sCountry')) $('sCountry').onchange = e => { G.save.flag = e.target.value; G.save.flagSet = true; persist(); hud(); };
$('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol);
$('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value);
$('sSfx').onchange = () => SFX.click();
$('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); };
if (G.isDev && G.save) overlay.querySelectorAll('[data-coin]').forEach(b => b.onclick = () => {
SFX.buy(); const v = b.dataset.coin;
act({ type: 'devCoins', money: v === 'set800' ? 800 : Math.min(1e9, (G.save.money | 0) + (+v || 0)) });
persist(); hud(); showSettings(back);
});
if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); };
if ($('sOut')) $('sOut').onclick = () => { SFX.click(); logout(); };
$('sKeys').onclick = () => { SFX.click(); showHelp(() => showSettings(back)); };
if ($('sLegal')) $('sLegal').onclick = () => { SFX.click(); showLegal(() => showSettings(back)); };
$('bBack').onclick = () => { SFX.click(); back(); };
}
function keysHtml() {
return `<div class="keys"><b>W A S D / ↑ ← ↓ →</b><span>${t('key_drive')}</span><b>${t('key_space')}</b><span>${t('key_weapon')}</span>
<b>Shift / E</b><span>${t('key_tower')}</span><b>C</b><span>${t('key_cam')}</span><b>P / Esc</b><span>${t('pause')}</span><b>M</b><span>${t('sound_on')} / ${t('sound_off')}</span>
<b>${t('key_pad')}</b><span>${t('key_pad_text')}</span></div>`;
}
// first start: four short cards instead of the full help page
const TUT = ['tut_1', 'tut_2', 'tut_3', 'tut_4'];
function startTutorial(done) {
let i = 0;
const step = () => {
if (i >= TUT.length) { done(); return; }
const n = i + 1;
overlayEnter();
card(`<h2>${t('tut_title')} <span class="muted">${n}/${TUT.length}</span></h2>
<p>${t(TUT[i])}</p>
<div class="row"><button id="tSkip">${t('tut_skip')}</button>
<button class="primary" id="tNext">${n === TUT.length ? t('tut_go') : t('tut_next')}</button></div>`,
{ bg: 'bg_workshop.jpg' });
$('tNext').onclick = () => { SFX.click(); i++; step(); };
$('tSkip').onclick = () => { SFX.click(); done(); };
};
step();
}
// first start: pick the country whose flag shows on the ranking / in the lobby (changeable later in settings)
function chooseFlag(done) {
overlayEnter();
let pick = (G.save && FLAGS.includes(G.save.flag)) ? G.save.flag : 'XX';
card(`<h2>🌍 ${t('country_title')}</h2><p>${t('country_text')}</p>
<div class="flaggrid">${FLAGS.map(f => `<button class="flagbtn ${f === pick ? 'on' : ''}" data-f="${f}">${flagHtml(f)}<span>${t('cc_' + f)}</span></button>`).join('')}</div>
<div class="row"><button class="primary" id="cfGo">${t('country_go')}</button></div>`, { bg: 'bg_title.jpg', wide: true });
overlay.querySelectorAll('.flagbtn').forEach(b => b.onclick = () => { pick = b.dataset.f; SFX.click(); overlay.querySelectorAll('.flagbtn').forEach(x => x.classList.toggle('on', x.dataset.f === pick)); });
$('cfGo').onclick = () => { if (G.save) { G.save.flag = pick; G.save.flagSet = true; persist(); } SFX.click(); done(); };
}
function ensureFlag(done) { if (G.save && !G.save.flagSet) chooseFlag(done); else done(); }
// one line for the running event and one for the admin's message
function liveBanner() {
const out = [];
if (G.LIVE.event) {
const n = liveText(G.LIVE.event.name) || t('event_running');
const extra = G.LIVE.event.prizeMul !== 1 ? ` · ${t('event_prize', { n: G.LIVE.event.prizeMul })}` : '';
out.push(`<div class="evbar"><b>${t('event')}</b><span>${esc(n)}${extra}</span></div>`);
}
const m = liveText(G.LIVE.motd);
if (m) out.push(`<p class="motd">${esc(m)}</p>`);
return out.join('');
}
function showAchievements(back) {
overlayEnter();
const P = RC.Progress, r = P.rankOf(G.save.fame);
const pct = Math.round(r.pct * 100);
const nextLine = r.next
? t('rank_next', { n: t('rank_' + r.next.key), f: Kit.fmt(r.next.at - G.save.fame) })
: t('rank_top');
const rows = P.ACHIEVEMENTS.map(a => {
const done = !!(G.save.ach && G.save.ach[a.id]);
return `<div class="achrow ${done ? 'done' : 'todo'}"><span class="am">${done ? '🏅' : '🔒'}</span>
<span><span class="an">${t('ach_' + a.id)}</span><br><span class="ad">${t('achd_' + a.id)}</span></span>
<span class="${done ? 'plus' : 'muted'}">${Kit.fmt(a.reward)}</span></div>`;
}).join('');
card(`<h2>🏅 ${t('achievements')}</h2>
<div class="rankbar"><div class="rt"><b>${t('rank_' + r.key)}</b><span class="muted">${nextLine}</span></div>
<div class="bar"><i style="width:${pct}%"></i></div></div>
<p class="muted">${t('ach_done', { n: P.earned(G.save), m: P.total })}</p>
<div class="achlist">${rows}</div>
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); back(); };
}
// campaign missions page: 3 daily + 1 weekly with progress bars + reset countdown
function showMissions(back) {
overlayEnter();
ensureMissions();
const daily = (G.save.missions && G.save.missions.daily) || [], weekly = (G.save.missions && G.save.missions.weekly) || [];
const hrs = ms => Math.max(1, Math.ceil(ms / 3600000));
const toDay = 86400000 - (Date.now() % 86400000), toWeek = 604800000 - (Date.now() % 604800000);
const row = m => {
const prog = Math.min(m.prog || 0, m.goal), pct = Math.round(prog / m.goal * 100);
const rew = `🪙 ${Kit.fmt(m.reward)}${m.fame ? ' · ⭐' + m.fame : ''}${typeof m.unlock === 'number' ? ' · 🎨' : ''}`;
return `<div class="missrow ${m.done ? 'done' : ''}"><span class="mm">${m.done ? '✅' : '🎯'}</span>
<div class="mi"><div class="mn">${t('mission_' + m.id)}</div><div class="md">${t('missd_' + m.id)}</div>
<div class="bar"><i style="width:${pct}%"></i></div></div>
<div class="mr"><span class="${m.done ? 'plus' : 'muted'}">${rew}</span><span class="mp">${prog}/${m.goal}</span></div></div>`;
};
card(`<h2>🎯 ${t('missions')}</h2>
<h3>${t('miss_daily')} <span class="muted">· ${t('miss_reset_in', { n: hrs(toDay) })}</span></h3>
<div class="misslist">${daily.map(row).join('')}</div>
<h3>${t('miss_weekly')} <span class="muted">· ${t('miss_reset_in', { n: hrs(toWeek) })}</span></h3>
<div class="misslist">${weekly.map(row).join('')}</div>
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); back(); };
}
function showHelp(back) {
overlayEnter();
card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>${keysHtml()}
<p style="margin-top:12px">${t('help_arena')}</p><button class="primary" id="bOk">${t('ok')}</button>`, { bg: 'bg_title.jpg' });
$('bOk').onclick = () => { SFX.click(); back(); };
}
// legal pages (Impressum / Datenschutz) — placeholders, Michael fills his data in lang.js
function showLegal(back, which) {
overlayEnter();
which = which === 'privacy' ? 'privacy' : 'impressum';
const seg = ['impressum', 'privacy'].map(k => `<button data-l="${k}" class="${k === which ? 'on' : ''}">${t('legal_' + k)}</button>`).join('');
card(`<h2>${t('legal')}</h2><div class="seg legalseg">${seg}</div>
<div class="legaltext">${t(which + '_text')}</div>
<div class="row"><button class="primary" id="bOk">${t('ok')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
overlay.querySelectorAll('.legalseg button').forEach(b => b.onclick = () => { SFX.click(); showLegal(back, b.dataset.l); });
$('bOk').onclick = () => { SFX.click(); back(); };
}
const closeRank = () => { if (G.rankSub) { G.rankSub.close(); G.rankSub = null; } };
function showRanking(back) {
overlayEnter();
card(`<h2>🏆 ${t('ranking')} ${rank.enabled ? '<span class="livedot">● ' + t('rank_live') + '</span>' : ''}</h2>
<ol class="board live" id="board"><li class="muted">${t('loading')}</li></ol>
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); closeRank(); back(); };
G.boardFame = {}; G.boardIdx = {};
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
closeRank();
if (rank.enabled) G.rankSub = rank.watch(rows => drawBoard($('board'), rows, myUid));
else drawBoard($('board'), [], myUid);
}
// animated live board: FLIP row reordering, fame bars, count-up numbers, rank ▲/▼
function animNum(el, from, to) {
if (!el) return; const t0 = performance.now(), dur = 520;
(function step(now) {
const k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3);
el.textContent = Kit.fmt(Math.round(from + (to - from) * e));
if (k < 1 && el.isConnected) requestAnimationFrame(step);
})(t0);
}
function drawBoard(el, rows, myUid) {
if (!el) return;
if (!rows.length) { el.innerHTML = `<li class="muted">${t('no_scores')}</li>`; G.boardFame = {}; G.boardIdx = {}; return; }
const max = Math.max(1, rows[0].fame);
const prevTop = {};
el.querySelectorAll('.brow').forEach(li => { prevTop[li.dataset.key] = li.getBoundingClientRect().top; });
el.innerHTML = rows.map((r, i) => {
const me = r.key === myUid;
const was = G.boardIdx[r.key];
const arr = (was != null && was !== i) ? (i < was ? '<span class="arrow up">▲</span>' : '<span class="arrow dn">▼</span>') : '';
return `<li class="brow ${me ? 'me' : ''}" data-key="${r.key}" data-fame="${r.fame}">
<span class="rk">${i + 1}</span><span class="fl">${flagHtml(r.flag || 'XX')}</span>
<span class="nm">${esc(r.name)}${me ? ` <span class="muted">(${t('you')})</span>` : ''}${arr}</span>
<span class="val"><i class="fill" style="width:${(r.fame / max * 100).toFixed(1)}%"></i><b>0</b></span></li>`;
}).join('');
el.querySelectorAll('.brow').forEach(li => {
const key = li.dataset.key, to = +li.dataset.fame, from = G.boardFame[key] != null ? G.boardFame[key] : to;
animNum(li.querySelector('.val b'), from, to); G.boardFame[key] = to;
if (prevTop[key] != null) {
const d = prevTop[key] - li.getBoundingClientRect().top;
if (d) { li.style.transform = `translateY(${d}px)`; li.style.transition = 'none';
requestAnimationFrame(() => { li.style.transition = 'transform .45s cubic-bezier(.2,.8,.2,1)'; li.style.transform = ''; }); }
}
});
G.boardIdx = {}; rows.forEach((r, i) => G.boardIdx[r.key] = i);
}
function confirmReset(back) {
card(`<h2>${t('reset')}</h2><p>${t('reset_text')}</p><div class="row"><button id="bYes">${t('reset_yes')}</button><button class="primary" id="bNo">${t('cancel')}</button></div>`);
$('bNo').onclick = () => { SFX.click(); back(); };
$('bYes').onclick = () => { Object.assign(G.save, newSave()); RC.layerFromData(layer, null); G.save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); };
}
// the rank badge opens the achievements page
$('hTour').onclick = () => { SFX.click(); if (G.gameMode === 'campaign') { if (tourState()) showTournament(); else showLeague(); } }; // online tournament: server-side later (plan P2-6)
$('chipFame').onclick = () => {
if (!G.save || G.mode === 'intro' || G.mode === 'title') return;
if (G.mode === 'fight') togglePause();
SFX.click();
showAchievements(G.mode === 'pause' ? () => { G.mode = 'fight'; togglePause(); } : currentBack());
};
$('bSettings').onclick = () => {
if (G.mode === 'fight') togglePause();
if (G.mode === 'intro') skipIntro();
SFX.click();
const back = G.mode === 'pause' ? () => { G.mode = 'fight'; togglePause(); } : currentBack();
showSettings(back);
};
function boardHtml() { return (rank.enabled && G.gameMode === 'online') ? `<h3>${t('ranking')}</h3><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
async function fillBoard() {
const el = $('board');
if (!el) return;
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
try {
const rows = await rank.once(10);
el.innerHTML = rows.length
? rows.map((r, i) => `<li class="${r.key === myUid ? 'me' : ''}"><span>${i + 1}.</span><span class="nm">${esc(r.name)}</span><span>${Kit.fmt(r.fame)}</span></li>`).join('')
: `<li class="muted">${t('no_scores')}</li>`;
} catch (e) { el.innerHTML = `<li class="muted">${t('scores_offline')}</li>`; }
}
return {
showSettings, keysHtml, TUT, startTutorial, chooseFlag, ensureFlag, liveBanner, showAchievements,
showMissions, showHelp, showLegal, closeRank, showRanking, animNum, drawBoard, confirmReset, boardHtml,
fillBoard
};
};
})(window);

View File

@@ -29,7 +29,7 @@
let tool = 'brush', color = '#ffffff', size = 14, stamp = '★', text = '', mirror = true;
let undo = [], drawing = null, panel = null, before = null, pending = false;
function build() {
function build(host) {
panel = document.createElement('div');
panel.id = 'painter';
panel.innerHTML = `
@@ -45,7 +45,7 @@
<div class="pt-colors" id="ptColors">${COLORS.map(c => `<span class="sw" data-c="${c}" style="background:${c}"></span>`).join('')}<input type="color" id="ptPick" value="${color}"></div>
<div class="gbar"><button id="ptUndo">↶ ${t('pt_undo')}</button><button id="ptClear">${t('pt_clear')}</button><div class="grow"></div>
<button id="ptCancel">${t('cancel')}</button><button class="primary" id="ptDone">✓ ${t('pt_done')}</button></div>`;
$('shop').appendChild(panel);
(host || $('shop')).appendChild(panel);
const cv = $('ptCv');
cv.addEventListener('pointerdown', down);
cv.addEventListener('pointermove', move);
@@ -157,19 +157,24 @@
});
}
function open() {
if (!panel) build();
function open(mountEl) {
const inline = !!mountEl;
if (!panel) build(mountEl || $('shop'));
else if (mountEl && panel.parentNode !== mountEl) mountEl.appendChild(panel);
panel.classList.toggle('inline', inline);
before = lc.getImageData(0, 0, LW, LH);
undo = [];
panel.style.display = '';
$('sRight').style.display = 'none'; $('shop').classList.add('painting');
if (!inline) { $('sRight').style.display = 'none'; $('shop').classList.add('painting'); }
opt.view.paintCam(true);
refresh(); live();
}
function close() {
if (!panel) return;
const inline = panel.classList.contains('inline');
panel.style.display = 'none';
$('sRight').style.display = ''; $('shop').classList.remove('painting');
if (!inline) $('sRight').style.display = '';
$('shop').classList.remove('painting');
opt.view.paintCam(false); opt.view.face(null);
}
// anything drawn at all? (decides stock stripes vs. own artwork on the model)
@@ -178,6 +183,6 @@
for (let i = 3; i < d.length; i += 16) if (d[i] > 8) return true;
return false;
}
return { open, close, hasArt, get isOpen() { return !!panel && panel.style.display !== 'none'; } };
return { open, close, hasArt, sync() { if (panel && panel.style.display !== 'none') { live(); refresh(); } }, get isOpen() { return !!panel && panel.style.display !== 'none'; } };
};
})(window);

View File

@@ -8,7 +8,10 @@
'use strict';
const RC = (root.RC = root.RC || {});
RC.WEIGHT_LIMIT = 100; // kg, single weight class in v1
// Weight classes. RC.WEIGHT_LIMIT follows the chosen class (see RC.setClass in ai.js);
// 'heavy' is as much as the catalogue can carry, so it is effectively "build what you like".
RC.CLASSES = [{ id: 'light', max: 60 }, { id: 'medium', max: 100 }, { id: 'heavy', max: 130 }];
RC.WEIGHT_LIMIT = 100; // medium is the default
RC.SLOTS = ['chassis', 'motor', 'wheels', 'battery', 'armour', 'weapon', 'tower', 'gadget'];
RC.REQUIRED = { chassis: true, motor: true, wheels: true, battery: true };
@@ -24,12 +27,18 @@
{ id: 'fang', slot: 'chassis', name: 'Fang', cost: 860, weight: 26, hp: 120, len: 1.55, wid: 1.0, h: 0.36, shape: 'arrow', lowProfile: true, frontArmour: 0.12 },
{ id: 'plough', slot: 'chassis', name: 'Snowplough', cost: 980, weight: 36, hp: 150, len: 1.45, wid: 1.2, h: 0.42, shape: 'plow', frontArmour: 0.22 },
{ id: 'discus', slot: 'chassis', name: 'Discus', cost: 1350, weight: 32, hp: 155, len: 1.5, wid: 1.35, h: 0.3, shape: 'saucer', lowProfile: true },
{ id: 'orb', slot: 'chassis', name: 'Orb', cost: 700, weight: 28, hp: 140, len: 1.2, wid: 1.2, h: 0.62, shape: 'ball', frontArmour: 0.1 },
{ id: 'tower', slot: 'chassis', name: 'Tower', cost: 640, weight: 27, hp: 125, len: 1.1, wid: 1.0, h: 0.82, shape: 'tower' },
{ id: 'slab', slot: 'chassis', name: 'Slab', cost: 820, weight: 33, hp: 150, len: 1.55, wid: 1.4, h: 0.26, shape: 'slab', lowProfile: true },
// motor: force (N), top speed (m/s)
{ id: 'sparky', slot: 'motor', name: 'Sparky 2kW', cost: 100, weight: 8, power: 3, force: 650, speed: 4.0 },
{ id: 'hornet', slot: 'motor', name: 'Hornet 3kW', cost: 420, weight: 10, power: 5, force: 850, speed: 5.0 },
{ id: 'bulldog', slot: 'motor', name: 'Bulldog Torque', cost: 680, weight: 14, power: 6, force: 1250, speed: 4.3 },
{ id: 'comet', slot: 'motor', name: 'Comet 5kW', cost: 1250, weight: 12, power: 8, force: 1150, speed: 6.2 },
{ id: 'pico', slot: 'motor', name: 'Pico 1kW', cost: 60, weight: 5, power: 2, force: 440, speed: 3.4 },
{ id: 'turbine', slot: 'motor', name: 'Turbine 4kW', cost: 560, weight: 11, power: 6, force: 980, speed: 5.4 },
{ id: 'titandrive', slot: 'motor', name: 'Titan Drive', cost: 1100, weight: 18, power: 9, force: 1500, speed: 3.8 },
// wheels: speed factor, lateral grip, turn rate (rad/s), push factor; invertible = drives upside down
{ id: 'rubber', slot: 'wheels', name: 'Rubber 4x', cost: 60, weight: 4, speedMul: 1.0, grip: 7, turn: 2.8, push: 1.0, kind: 'small' },
@@ -44,6 +53,8 @@
{ id: 'lead', slot: 'battery', name: 'Lead 12V', cost: 80, weight: 10, power: 9 },
{ id: 'nicd', slot: 'battery', name: 'NiCd Pack', cost: 320, weight: 7, power: 13 },
{ id: 'lipo', slot: 'battery', name: 'LiPo Stack', cost: 760, weight: 5, power: 19 },
{ id: 'liion', slot: 'battery', name: 'Li-Ion Brick', cost: 1150, weight: 8, power: 24 },
{ id: 'supercap', slot: 'battery', name: 'Supercap Bank', cost: 1700, weight: 11, power: 30 },
// armour: reduce = share of damage absorbed, hp bonus
{ id: 'mesh', slot: 'armour', name: 'Wire Mesh', cost: 120, weight: 5, reduce: 0.08, hp: 4, tint: 0x9aa3ad, style: 'mesh' },
@@ -83,6 +94,8 @@
{ id: 'shield', slot: 'gadget', name: 'Deflector Field', cost: 420, weight: 7, power: 4, type: 'shield', cd: 9, dur: 2.5, reduce: 0.6 },
{ id: 'repair', slot: 'gadget', name: 'Repair Kit', cost: 500, weight: 8, power: 3, type: 'repair', cd: 8, charges: 2, heal: 0.26 },
{ id: 'emp', slot: 'gadget', name: 'EMP Burst', cost: 640, weight: 7, power: 5, type: 'emp', cd: 8, range: 3.2, stun: 1.5 },
{ id: 'mines', slot: 'gadget', name: 'Mine Layer', cost: 560, weight: 9, power: 3, type: 'mines', cd: 2.2, charges: 3,
dmg: 26, launch: 7.5, r: 0.85, arm: 1.2 },
];
RC.PARTS = {};

View File

@@ -1,6 +1,6 @@
/* 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
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');
acc.list() -> [{ id, name }]

73
game/progress.js Normal file
View File

@@ -0,0 +1,73 @@
/* Robot Clash - ranks and achievements (no DOM, runs in Node for the tests).
Needs parts.js. Everything is read from / written to the save, so the campaign and the
online game keep their own ranks and their own achievements.
RC.Progress.rankOf(fame) -> { i, key, at, next, pct } next = null at the top rank
RC.Progress.check(save, ctx) -> [{ id, key, reward }] newly earned (marks them in save.ach)
RC.Progress.earned(save) -> number of achievements done
ctx after a fight: { won, reason, hpPct, lost, dealt, training, exhibition, champion }
Texts: lang.js keys 'rank_<key>', 'ach_<id>' (name) and 'achd_<id>' (what to do). */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || (typeof require === 'function' ? require('./parts.js') : {}));
// fame needed for each rank
const RANKS = [
{ at: 0, key: 'scrap' },
{ at: 150, key: 'rookie' },
{ at: 400, key: 'contender' },
{ at: 900, key: 'pro' },
{ at: 1800, key: 'veteran' },
{ at: 3200, key: 'champion' },
{ at: 5500, key: 'master' },
{ at: 9000, key: 'legend' },
];
function rankOf(fame) {
const f = Math.max(0, fame | 0);
let i = 0;
while (i + 1 < RANKS.length && f >= RANKS[i + 1].at) i++;
const cur = RANKS[i], next = RANKS[i + 1] || null;
const pct = next ? Math.min(1, (f - cur.at) / (next.at - cur.at)) : 1;
return { i, key: cur.key, at: cur.at, next, pct };
}
// test(save, ctx) - ctx is empty when we only re-check the save (e.g. after a purchase)
const ACHIEVEMENTS = [
{ id: 'first_win', reward: 100, test: (s, c) => c.won && !c.training },
{ id: 'ko', reward: 150, test: (s, c) => c.won && c.reason === 'ko' },
{ id: 'pit', reward: 150, test: (s, c) => c.won && c.reason === 'pit' },
{ id: 'tough', reward: 250, test: (s, c) => c.won && c.hpPct > 0 && c.hpPct < 0.15 },
{ id: 'flawless', reward: 250, test: (s, c) => c.won && !c.training && c.lost === 0 && c.hpPct >= 0.9 },
{ id: 'demolition', reward: 200, test: (s, c) => c.dealt >= 600 },
{ id: 'champion', reward: 1000, test: (s, c) => !!c.champion },
{ id: 'tourney', reward: 800, test: (s, c) => !!c.tourWon },
{ id: 'veteran', reward: 300, test: s => (s.games | 0) >= 25 },
{ id: 'rich', reward: 200, test: s => (s.money | 0) >= 5000 },
{ id: 'collector', reward: 300, test: s => (s.owned || []).length >= 20 },
{ id: 'garage', reward: 200, test: s => (s.robots || []).length >= 3 },
{ id: 'artist', reward: 150, test: s => !!(s.paint && s.paint.decal) },
];
function check(save, ctx) {
if (!save) return [];
const c = ctx || {};
if (!save.ach) save.ach = {};
const got = [];
for (const a of ACHIEVEMENTS) {
if (save.ach[a.id]) continue;
let ok = false;
try { ok = !!a.test(save, c); } catch (e) { ok = false; }
if (!ok) continue;
save.ach[a.id] = true;
got.push({ id: a.id, key: a.id, reward: a.reward });
}
return got;
}
const earned = save => ACHIEVEMENTS.filter(a => save && save.ach && save.ach[a.id]).length;
RC.Progress = { RANKS, rankOf, ACHIEVEMENTS, check, earned, total: ACHIEVEMENTS.length };
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

113
game/protocol.js Normal file
View File

@@ -0,0 +1,113 @@
/* Robot Clash - wire protocol shared by client (classic script) and server (require). No DOM.
One WebSocket per player, JSON messages { t: '<type>', ... }.
RC.Proto.VERSION bump on every incompatible change (server rejects older clients)
RC.Proto.check(msg) -> { ok, error } validates a client->server message (type, ranges, sizes)
RC.Proto.input(raw) -> clean input { throttle, turn, fire, fire2, fire3 } (clamped)
RC.Proto.packSnap(s, tick, ack) -> compact snapshot of a fight state (server side, seat order)
RC.Proto.toLocal(seat, snap) -> copy of the snapshot as seen by `seat`: own robot at index 0,
every robot index inside (events, grabs, crane, owners, winner) mirrored.
THE ONLY PLACE where seat <-> local index mapping happens.
RC.Proto.localResult(seat, result) -> result with the winner as a local index (0 = me) */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const VERSION = 1;
const MAX_MSG = 8 * 1024; // bytes per client message
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
const isStr = (v, max = 64) => typeof v === 'string' && v.length > 0 && v.length <= max;
const isNum = v => typeof v === 'number' && Number.isFinite(v);
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
// client -> server message schemas: field -> check
const C2S = {
hello: { v: v => Number.isInteger(v), token: v => isStr(v, 4096) },
ping: { t0: v => v === undefined || isNum(v) }, // (t is the message type itself)
room: { room: v => FLAGS.includes(v) || v === 'all' },
challenge: { to: v => isStr(v) },
'challenge.cancel': {},
'challenge.accept': { from: v => isStr(v) },
'challenge.decline': { from: v => isStr(v) },
input: {
seq: v => Number.isInteger(v) && v >= 0,
throttle: isNum, turn: isNum,
fire: v => typeof v === 'boolean', fire2: v => typeof v === 'boolean', fire3: v => typeof v === 'boolean',
},
'match.leave': {},
};
function check(msg) {
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) return { ok: false, error: 'BAD_MESSAGE' };
const schema = C2S[msg.t];
if (!schema) return { ok: false, error: 'UNKNOWN_TYPE' };
for (const k of Object.keys(schema)) if (!schema[k](msg[k])) return { ok: false, error: 'BAD_FIELD:' + k };
return { ok: true };
}
const input = raw => ({
throttle: clamp(isNum(raw && raw.throttle) ? raw.throttle : 0, -1, 1),
turn: clamp(isNum(raw && raw.turn) ? raw.turn : 0, -1, 1),
fire: !!(raw && raw.fire), fire2: !!(raw && raw.fire2), fire3: !!(raw && raw.fire3),
});
// ---- snapshots ---------------------------------------------------------------------------------
// robot fields the view / HUD / sound / result screen read
const RF = ['x', 'z', 'a', 'y', 'hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'turretA', 'spin',
'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'dead', 'out', 'dealt', 'taken', 'onOil'];
const WF = ['cd', 'spin', 'swing', 'grab', 'sawOn', 'fire', 'flipAnim'];
const rnd = v => (typeof v === 'number' ? Math.round(v * 1000) / 1000 : v);
const pick = (o, keys) => { const r = {}; for (const k of keys) if (o[k] !== undefined) r[k] = rnd(o[k]); return r; };
const packRobot = r => Object.assign(pick(r, RF), {
lost: Object.assign({}, r.lost), lostW: (r.lostW || []).slice(), W: (r.W || []).map(w => pick(w, WF)),
});
function packSnap(s, tick, ack) {
return {
tick, ack: ack || [0, 0],
time: rnd(s.t), left: rnd(s.left), pitOpen: rnd(s.pitOpen), pitAlarm: !!s.pitAlarm, endIn: rnd(s.endIn),
result: s.result ? { winner: s.result.winner, reason: s.result.reason } : null,
press: { st: s.press.st, y: rnd(s.press.y) },
crane: { st: s.crane.st, x: rnd(s.crane.x), z: rnd(s.crane.z), who: s.crane.who },
rockets: s.rockets.map(k => ({ kind: k.kind, owner: k.owner, x: rnd(k.x), z: rnd(k.z), y: rnd(k.y), a: rnd(k.a) })),
mines: s.mines.map(k => ({ owner: k.owner, x: rnd(k.x), z: rnd(k.z), arm: rnd(k.arm) })),
robots: [packRobot(s.robots[0]), packRobot(s.robots[1])],
ev: s.events.map(e => Object.assign({}, e)),
};
}
// seat index -> local index (0 = me). -1 / null stay as they are.
const mapper = seat => i => (i === 0 || i === 1) ? (seat === 0 ? i : 1 - i) : i;
function toLocal(seat, snap) {
if (!snap) return snap;
const m = mapper(seat);
const robots = (seat === 0 ? snap.robots : [snap.robots[1], snap.robots[0]])
.map(r => Object.assign({}, r, { grabbedBy: r.grabbedBy == null ? r.grabbedBy : m(r.grabbedBy) }));
return Object.assign({}, snap, {
robots,
ack: snap.ack ? snap.ack[seat] : 0,
away: snap.away ? (seat === 0 ? snap.away.slice() : [snap.away[1], snap.away[0]]) : undefined,
rtt: snap.rtt ? (seat === 0 ? snap.rtt.slice() : [snap.rtt[1], snap.rtt[0]]) : undefined, // ping of [me, opponent]
result: localResult(seat, snap.result),
crane: Object.assign({}, snap.crane, { who: m(snap.crane.who) }),
rockets: snap.rockets.map(k => Object.assign({}, k, { owner: m(k.owner) })),
mines: snap.mines.map(k => Object.assign({}, k, { owner: m(k.owner) })),
ev: (snap.ev || []).map(e => {
const c = Object.assign({}, e);
if ('who' in c) c.who = m(c.who);
if ('winner' in c) c.winner = m(c.winner);
return c;
}),
});
}
function localResult(seat, result) {
if (!result) return result;
return Object.assign({}, result, { winner: mapper(seat)(result.winner) });
}
RC.Proto = { VERSION, MAX_MSG, FLAGS, check, input, packSnap, toLocal, localResult, RF };
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

42
game/ranking.js Normal file
View File

@@ -0,0 +1,42 @@
/* Robot Clash - online ranking. The server computes it from the online saves (fame only changes through
server-booked fights), so the client only reads: GET /api/ranks, polled while a board is open.
DOM-free; RC.Ranking.rank is a pure function (Node-testable).
const rank = RC.Ranking(net);
if (rank.enabled) {
const sub = rank.watch(rows => draw(rows)); // { close() } rows best first, refreshed every 15 s
const rows = await rank.once(20);
}
RC.Ranking.rank(data, n) // [{uid,name,fame,flag}] or { key: {...} } -> sorted array, bad names out, capped */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const Kit = root.Kit || {};
const bad = s => (Kit.badName ? Kit.badName(s) : false);
const POLL = 15000;
RC.Ranking = function (net) {
const enabled = !!(net && net.enabled);
const fetchRows = async n => RC.Ranking.rank(await net.api('GET', '/api/ranks?n=' + (n || 20)), n);
return {
enabled,
watch(cb, n) {
if (!enabled) { cb([]); return { close() {} }; }
let alive = true;
const tick = () => fetchRows(n).then(rows => { if (alive) cb(rows); });
tick();
const timer = setInterval(tick, POLL);
return { close() { alive = false; clearInterval(timer); } };
},
once: n => (enabled ? fetchRows(n) : Promise.resolve([])),
};
};
RC.Ranking.rank = function (data, n = 20) {
const list = Array.isArray(data) ? data.map(v => Object.assign({ key: v.uid }, v))
: Object.entries(data || {}).map(([key, v]) => Object.assign({ key }, v));
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));
return rows.slice(0, n);
};
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -163,6 +163,18 @@
// ---------------------------------------------------------------- robot model
const M = {};
const sharedMat = new Set(); // the cached palette materials must never be disposed
// free a replaced robot's GPU resources (unique per build) so browsing parts / many fights does not leak
function disposeRobot(R) {
if (!R || !R.root) return;
const gs = new Set(), ms = new Set();
R.root.traverse(o => {
if (o.geometry && !gs.has(o.geometry)) { gs.add(o.geometry); o.geometry.dispose(); }
if (o.material) for (const m of [].concat(o.material)) {
if (m && !sharedMat.has(m) && !ms.has(m)) { ms.add(m); if (m.map && m.map.isTexture) m.map.dispose(); m.dispose(); }
}
});
}
function mats() {
if (M.dark) return M;
M.dark = new T.MeshStandardMaterial({ color: 0x2a2d33, metalness: 0.6, roughness: 0.5 });
@@ -179,12 +191,13 @@
M.track = new T.MeshStandardMaterial({ map: M.trackTex, roughness: 0.85, metalness: 0.2 });
M.wsteel = new T.MeshStandardMaterial({ color: 0xd2d7de, metalness: 0.95, roughness: 0.22 }); // bright weapon steel
M.wedge = new T.MeshStandardMaterial({ color: 0x9aa0a8, metalness: 0.85, roughness: 0.35 });
for (const k in M) if (M[k] && M[k].isMaterial) sharedMat.add(M[k]); // protect the shared palette from disposal
return M;
}
// shop: the robot is framed in the left column, not in the middle of the stage
const GARAGE_OFF_X = 455, GARAGE_OFF_Y = 16;
const GARAGE_OFF_X = 300, GARAGE_OFF_Y = 16; // robot centered in the free area left of the shop panel
// shop zoom: 0.6 = furthest out (the default, whole robot in frame), 1.9 = closest
const GZ_MIN = 0.6, GZ_MAX = 1.9, GZ_DEF = GZ_MIN;
const GZ_MIN = 0.6, GZ_MAX = 1.9, GZ_DEF = 0.72; // default framing of the robot in the shop
const box = (w, h, d, m) => { const o = new T.Mesh(new T.BoxGeometry(w, h, d), m); o.castShadow = true; o.receiveShadow = true; return o; };
const cyl = (r1, r2, h, m, seg = 20) => { const o = new T.Mesh(new T.CylinderGeometry(r1, r2, h, seg), m); o.castShadow = true; return o; };
@@ -237,6 +250,20 @@
return g;
}
// position the weapon-mount group from the robot's mount (front/back/left/right + height).
// weapons are built along +x; this turns that onto the chosen side and pulls side mounts in to the hull edge.
function placeMount(g, st, L, Wd) {
const th = -(st.mountA || 0), dx0 = ((st.mountAxis === 'wid' ? Wd : L) / 2) - L / 2;
g.rotation.y = th;
g.position.set(Math.cos(th) * dx0, st.mountUp || 0, -Math.sin(th) * dx0);
}
// pointer (client px) -> normalised device coords on the garage canvas
function ndcOf(canvas, cx, cy) {
const b = canvas.getBoundingClientRect();
return new T.Vector2(((cx - b.left) / b.width) * 2 - 1, -((cy - b.top) / b.height) * 2 + 1);
}
function buildRobot(build, paint) {
const m = mats(), st = RC.stats(build), P = RC.PARTS;
const ch = P[build.chassis], wh = P[build.wheels], ar = build.armour ? P[build.armour] : null;
@@ -245,7 +272,8 @@
const drawn = !!(paint.layer && paint.drawn); // own artwork: no stock stripes, painted armour
const accent = new T.MeshStandardMaterial({ color: paint.accent, metalness: 0.3, roughness: 0.45 });
const armour = ar ? (drawn ? body : new T.MeshStandardMaterial({ color: ar.tint, metalness: 0.9, roughness: 0.28 })) : null;
const root = new T.Group(), tilt = new T.Group();
const root = new T.Group();
let tilt = new T.Group(); // let: the weapon block points it at a mount group, then restores it
root.add(tilt);
const out = { root, tilt, body, skin, st, build, roll: 0, flash: 0, spinA: 0, sawA: 0, gunA: 0, smokeT: 0 };
const sk = (geo, w, h, d, y0) => { const o = new T.Mesh(skinUV(geo, w, d, h, y0), body); o.castShadow = o.receiveShadow = true; return o; };
@@ -313,6 +341,25 @@
const pan = sk(new T.BoxGeometry(L * 0.9, 0.09, Wd * 0.86), L * 0.9, 0.09, Wd * 0.86, -0.045);
pan.position.y = c + 0.07; tilt.add(pan);
top = c + H;
} else if (ch.shape === 'ball') {
const o = sk(new T.SphereGeometry(1, 24, 16), 2, 1, 2, 0);
o.scale.set(L / 2, H / 2 + 0.06, Wd / 2); o.position.y = c + H / 2; tilt.add(o);
const ring = new T.Mesh(new T.TorusGeometry(1, 0.045, 8, 28), accent);
ring.rotation.x = Math.PI / 2; ring.scale.set(L / 2 * 1.01, Wd / 2 * 1.01, 1); ring.position.y = c + H * 0.5; tilt.add(ring);
if (!drawn) { const st2 = box(0.05, H * 0.9, Wd * 0.5, m.stripe); st2.position.set(-L / 2 + 0.03, c + H * 0.5, 0); tilt.add(st2); }
top = c + H * 1.05;
} else if (ch.shape === 'tower') {
const o = sk(new T.BoxGeometry(L, H, Wd), L, H, Wd, -H / 2); o.position.y = c + H / 2; tilt.add(o);
const headH = H * 0.3, head = sk(new T.BoxGeometry(L * 0.7, headH, Wd * 0.7), L * 0.7, headH, Wd * 0.7, -headH / 2);
head.position.set(0, c + H + headH / 2, 0); tilt.add(head);
const vis = box(0.02, headH * 0.4, Wd * 0.5, m.glowW); vis.position.set(L * 0.35 + 0.005, c + H + headH * 0.6, 0); tilt.add(vis);
if (!drawn) for (const sy of [0.3, 0.7]) { const band = box(L * 1.004, 0.05, Wd * 1.004, m.stripe); band.position.set(0, c + H * sy, 0); tilt.add(band); }
top = c + H + headH;
} else if (ch.shape === 'slab') {
const o = sk(new T.BoxGeometry(L, H, Wd), L, H, Wd, -H / 2); o.position.y = c + H / 2; tilt.add(o);
const nose = box(0.4, H * 0.9, Wd * 1.02, m.steel); nose.position.set(L / 2 + 0.06, c + H * 0.4, 0); nose.rotation.z = -0.5; tilt.add(nose);
if (!drawn) { const edge = box(0.1, 0.07, Wd * 1.05, m.stripe); edge.position.set(L / 2 + 0.22, c * 0.5, 0); tilt.add(edge); }
top = c + H;
} else {
const o = sk(new T.BoxGeometry(L, H, Wd), L, H, Wd, -H / 2); o.position.y = c + H / 2; tilt.add(o);
if (!drawn) {
@@ -327,6 +374,11 @@
const win = box(0.02, chh * 0.25, cd * 0.8, m.dark); win.position.set(-L * 0.16 + cw / 2 + 0.005, top + chh * 0.62, 0); tilt.add(win);
top += chh;
}
if (look.hump) {
const hb = sk(new T.SphereGeometry(1, 18, 10, 0, Math.PI * 2, 0, Math.PI / 2), 2, 1, 2, 0);
hb.scale.set(L * 0.3, H * 0.9, Wd * 0.4); hb.position.set(-L * 0.22, top, 0); tilt.add(hb);
top += H * 0.6;
}
if (look.bumps) {
for (const sz of [-1, 1]) {
const b = sk(new T.SphereGeometry(1, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2), 2, 1, 2, 0);
@@ -435,15 +487,25 @@
mark('lights');
// main weapon (front = +x)
const w = st.weapon;
if (w) {
const WS = m.wsteel, ED = m.wedge, HZ = m.stripe; // weapon steel, edge, hazard stripe
// main weapons: each built facing +x, then rotated/moved to its mounted side + height
const WS = m.wsteel, ED = m.wedge, HZ = m.stripe; // weapon steel, edge, hazard stripe
out.weapons = []; out.st = st;
const _tilt = tilt;
for (let wi = 0; wi < (st.weapons || []).length; wi++) {
const inst = st.weapons[wi], w = inst.part, wo = {};
const wmount = new T.Group();
placeMount(wmount, { mountA: inst.mountA, mountAxis: inst.mountAxis, mountUp: inst.mountUp }, L, Wd);
_tilt.add(wmount); wo.wmount = wmount; out.weapons[wi] = wo;
tilt = wmount;
if (w.type === 'wedge') {
if (w.id === 'lance') {
// long spike lance
const shaft = cyl(0.05, 0.05, 0.85, m.dark, 8); shaft.rotation.z = Math.PI / 2; shaft.position.set(L / 2 + 0.42, c + H * 0.4, 0); tilt.add(shaft);
const tip = cyl(0.001, 0.13, 0.42, HZ, 12); tip.rotation.z = -Math.PI / 2; tip.position.set(L / 2 + 0.95, c + H * 0.4, 0); tilt.add(tip);
// long spike lance on a sleeve - retracted at rest, thrusts forward when fired (poseRobot drives out.lance.position.x)
const baseX = L / 2 - 0.45; // rest: tip sits just past the body, not poking far out
const g = new T.Group(); g.position.set(baseX, c + H * 0.4, 0); g.userData.baseX = baseX; tilt.add(g);
const sleeve = cyl(0.08, 0.1, 0.42, m.steel, 10); sleeve.rotation.z = Math.PI / 2; sleeve.position.set(L / 2 - 0.3, c + H * 0.4, 0); tilt.add(sleeve);
const shaft = cyl(0.05, 0.05, 0.85, m.dark, 8); shaft.rotation.z = Math.PI / 2; shaft.position.x = 0.42; g.add(shaft);
const tip = cyl(0.001, 0.13, 0.42, HZ, 12); tip.rotation.z = -Math.PI / 2; tip.position.x = 0.95; g.add(tip);
wo.lance = g;
} else {
// short ramp plate at the front (as before - stays close to the body so it does not poke through)
const p = box(0.5, 0.05, Wd * 1.05, ED); p.position.set(L / 2 + 0.18, c * 0.5 + 0.08, 0); p.rotation.z = -0.42; tilt.add(p);
@@ -456,7 +518,7 @@
const s = box(0.78 * lf, 0.03, Wd * 0.4, accent); s.position.set(0.39 * lf, 0.06, 0); piv.add(s);
const edge = box(0.12, 0.14, Wd * 0.98 * wf, HZ); edge.position.set(0.78 * lf, 0, 0); piv.add(edge);
const pist = cyl(0.05, 0.05, 0.4, m.hub, 8); pist.rotation.z = 1.0; pist.position.set(0.2, -0.16, 0); tilt.add(pist); // ram
out.flipper = piv;
wo.flipper = piv;
} else if (w.type === 'hammer') {
const post = box(0.16, 0.26, 0.24, m.dark); post.position.set(-L * 0.1, top + 0.11, 0); tilt.add(post);
const piv = new T.Group(); piv.position.set(-L * 0.1, top + 0.16, 0); tilt.add(piv);
@@ -469,7 +531,7 @@
const face = box(0.1, 0.44, 0.28, HZ); face.position.set(L * 0.82 + 0.17, -0.12, 0); piv.add(face);
const spike = box(0.18, 0.12, 0.12, accent); spike.position.set(L * 0.82, 0.12, 0); piv.add(spike);
}
out.hammer = piv;
wo.hammer = piv;
} else if (w.type === 'saw') {
const arm = box(0.4, 0.12, 0.12, m.dark); arm.position.set(L / 2 + 0.06, c + H * 0.5, 0); tilt.add(arm);
if (w.id === 'drill') {
@@ -477,7 +539,7 @@
const g = new T.Group(); g.position.set(L / 2 + 0.42, c + H * 0.5, 0); tilt.add(g);
const cone = cyl(0.001, 0.2, 0.72, WS, 14); cone.rotation.z = -Math.PI / 2; cone.castShadow = true; g.add(cone);
for (let k = 0; k < 3; k++) { const fl = box(0.6, 0.03, 0.06, HZ); fl.position.x = -0.1; fl.rotation.x = k / 3 * Math.PI * 2; g.add(fl); }
out.saw = g; out.sawAxis = 'x';
wo.saw = g; wo.sawAxis = 'x';
} else {
const guard = new T.Mesh(new T.TorusGeometry(0.42, 0.05, 8, 20, Math.PI), accent); // orange guard over the top
guard.position.set(L / 2 + 0.28, c + H * 0.5, 0); tilt.add(guard);
@@ -485,7 +547,7 @@
const d = cyl(0.38, 0.38, 0.04, WS, 32); d.rotation.x = Math.PI / 2; g.add(d);
for (let k = 0; k < 16; k++) { const t = box(0.11, 0.06, 0.05, WS); const a = k / 16 * Math.PI * 2; t.position.set(Math.cos(a) * 0.4, Math.sin(a) * 0.4, 0); t.rotation.z = a + 0.6; g.add(t); }
const hub = cyl(0.09, 0.09, 0.07, accent, 12); hub.rotation.x = Math.PI / 2; g.add(hub);
out.saw = g;
wo.saw = g;
}
} else if (w.type === 'spinner') {
if (w.id === 'drum') {
@@ -493,14 +555,14 @@
const g = new T.Group(); g.position.set(L / 2 + 0.12, c + H * 0.34, 0); tilt.add(g);
const drum = cyl(0.3, 0.3, 0.52, WS, 20); drum.castShadow = true; g.add(drum);
for (const sx of [-1, 1]) { const tb = box(0.14, 0.54, 0.12, HZ); tb.position.set(sx * 0.3, 0, 0); g.add(tb); }
out.spinner = g;
wo.spinner = g;
} else {
const post = cyl(0.1, 0.12, 0.3, m.dark, 12); post.position.set(L / 2 + 0.04, c + H * 0.32, 0); tilt.add(post);
const g = new T.Group(); g.position.set(L / 2 + 0.04, c + H * 0.3, 0); tilt.add(g);
const bar = box(1.5, 0.12, 0.22, WS); g.add(bar);
const stripe = box(1.5, 0.13, 0.08, HZ); g.add(stripe);
for (const sx of [-1, 1]) { const t = box(0.18, 0.16, 0.32, accent); t.position.x = sx * 0.72; g.add(t); }
out.spinner = g;
wo.spinner = g;
}
} else if (w.type === 'lifter') {
const piv = new T.Group(); piv.position.set(L / 2 - 0.08, c + H * 0.16, 0); tilt.add(piv);
@@ -509,7 +571,7 @@
const prong = box(0.85, 0.07, Wd * 0.26, WS); prong.position.set(0.46, 0, sz * Wd * 0.3); piv.add(prong);
const tip = box(0.16, 0.1, Wd * 0.28, HZ); tip.position.set(0.9, 0.015, sz * Wd * 0.3); piv.add(tip);
}
out.flipper = piv;
wo.flipper = piv;
} else if (w.type === 'vspinner') {
const arm = box(0.3, 0.14, 0.14, m.dark); arm.position.set(L / 2 + 0.02, c + H * 0.45, 0); tilt.add(arm);
const g = new T.Group(); g.position.set(L / 2 + 0.32, c + H * 0.42, 0); tilt.add(g);
@@ -519,19 +581,20 @@
tth.position.set(Math.cos(a) * 0.45, Math.sin(a) * 0.45, 0); tth.rotation.z = a; g.add(tth);
}
const hub = cyl(0.1, 0.1, 0.14, accent, 12); hub.rotation.x = Math.PI / 2; g.add(hub);
out.vspin = g;
wo.vspin = g;
} else if (w.type === 'crusher') {
out.jaws = [];
wo.jaws = [];
for (const sz of [-1, 1]) {
const piv = new T.Group(); piv.position.set(L / 2 - 0.02, c + H * 0.45, sz * Wd * 0.32); tilt.add(piv);
const j = box(0.68, 0.2, 0.14, WS); j.position.x = 0.34; piv.add(j);
for (let k = 0; k < 3; k++) { const tooth = box(0.1, 0.18, 0.14, accent); tooth.position.set(0.3 + k * 0.18, -sz * 0.02, -sz * 0.07); tooth.rotation.z = -sz * 0.25; piv.add(tooth); }
piv.userData.side = sz; out.jaws.push(piv);
piv.userData.side = sz; wo.jaws.push(piv);
}
}
tilt = _tilt; // restore before the next weapon / the tower
mark('weapon' + wi); // tag this weapon's mount group so breakPart can hide just it
}
mark('weapon');
out.wmount = out.weapons[0] && out.weapons[0].wmount; // editor drag targets a weapon (default the first)
// tower on top
const tw = st.tower;
@@ -591,12 +654,13 @@
}
mark('gadget');
root.traverse(o => { if (o.isMesh && !o.material.transparent) { o.castShadow = true; } });
// full height (incl. tower/antenna) so a flipped robot rests on its roof, never clips through the floor
const bb = new T.Box3().setFromObject(tilt); out.topY = Math.max(0.3, bb.max.y);
return out;
}
// per-frame robot animation from the combat state
function poseRobot(R, r, dt) {
const w = R.st.weapon;
R.root.position.set(r.x, r.y, r.z);
R.root.rotation.y = -r.a;
// upside down when flipped
@@ -605,22 +669,32 @@
if (r.y <= 0.05 && Math.abs(R.roll - want) < 0.02) R.roll = want;
R.roll %= Math.PI * 2;
R.tilt.rotation.x = R.roll;
const h = R.c + R.st.h;
const h = R.topY || (R.c + R.st.h); // lift by the real top so nothing sinks under the floor when flipped
R.tilt.position.y = (1 - Math.cos(R.roll)) / 2 * h;
const sp = Math.hypot(r.vx, r.vz) * (Math.cos(r.a) * r.vx + Math.sin(r.a) * r.vz >= 0 ? 1 : -1);
for (const wl of R.wheels) wl.rotation.z -= sp * dt / (R.wheelR || 0.16);
if (R.flipper) R.flipper.rotation.z = -0.32 + (r.flipAnim > 0 ? Math.sin((1 - r.flipAnim / 0.35) * Math.PI) * 1.5 : 0);
if (R.hammer) {
let ang = 1.9;
if (r.swing > 0) { const k = 1 - r.swing / 0.28; ang = lerp(1.9, -0.25, k * k); }
else if (w && r.cd > w.cd - 0.28 - 0.15) ang = -0.25;
else if (w && r.cd > 0) ang = lerp(-0.25, 1.9, clamp((w.cd - 0.43 - r.cd) / 0.5, 0, 1));
R.hammer.rotation.z = ang;
// animate each mounted weapon from its own state r.W[i]
const wlist = R.weapons || [];
for (let i = 0; i < wlist.length; i++) {
const wo = wlist[i], W = (r.W && r.W[i]) || {}, w = R.st.weapons[i] && R.st.weapons[i].part;
if (!wo || !w) continue;
if (wo.flipper) wo.flipper.rotation.z = -0.32 + ((W.flipAnim || 0) > 0 ? Math.sin((1 - W.flipAnim / 0.35) * Math.PI) * 1.5 : 0);
if (wo.lance) { // W.fire runs 0.8s on a thrust -> fast, deep stab out and back
const k = (W.fire || 0) > 0 ? W.fire / 0.8 : 0;
wo.lance.position.x = wo.lance.userData.baseX + Math.sin(Math.min(1, (1 - k) * 2.2) * Math.PI) * 0.95;
}
if (wo.hammer) {
let ang = 1.9;
if ((W.swing || 0) > 0) { const k = 1 - W.swing / 0.28; ang = lerp(1.9, -0.25, k * k); }
else if (W.cd > w.cd - 0.28 - 0.15) ang = -0.25;
else if (W.cd > 0) ang = lerp(-0.25, 1.9, clamp((w.cd - 0.43 - W.cd) / 0.5, 0, 1));
wo.hammer.rotation.z = ang;
}
if (wo.saw) { if (W.sawOn) wo.sawA = (wo.sawA || 0) + dt * 40; wo.saw.rotation[wo.sawAxis || 'z'] = -(wo.sawA || 0); }
if (wo.spinner) { wo.spinA = (wo.spinA || 0) + dt * (W.spin || 0) * 38; wo.spinner.rotation.y = wo.spinA; }
if (wo.vspin) { wo.spinA = (wo.spinA || 0) + dt * (W.spin || 0) * 40; wo.vspin.rotation.z = -wo.spinA; }
if (wo.jaws) for (const j of wo.jaws) j.rotation.y = j.userData.side * ((W.grab || 0) > 0 ? -0.18 : 0.45);
}
if (R.saw) { if (r.sawOn) R.sawA += dt * 40; R.saw.rotation[R.sawAxis || 'z'] = -R.sawA; }
if (R.spinner) { R.spinA += dt * r.spin * 38; R.spinner.rotation.y = R.spinA; }
if (R.vspin) { R.spinA += dt * r.spin * 40; R.vspin.rotation.z = -R.spinA; }
if (R.jaws) for (const j of R.jaws) j.rotation.y = j.userData.side * (r.grab > 0 ? -0.18 : 0.45);
if (R.turret) R.turret.rotation.y = -(r.turretA - r.a);
if (R.flame) {
const tw2 = R.st.tower, beam = r.flameOn || (tw2 && tw2.type === 'zapper' && r.gunOn);
@@ -661,8 +735,9 @@
out.flashLight = new T.PointLight(0xffaa55, 0, 9); scene.add(out.flashLight);
out.scene = scene; out.group = null; out.id = null;
out.rocketGeo = new T.CylinderGeometry(0.05, 0.05, 0.32, 8); out.rocketGeo.rotateZ(Math.PI / 2);
out.rocketMat = new T.MeshStandardMaterial({ color: 0xdddddd, emissive: 0x331100 });
out.rocketMat = new T.MeshStandardMaterial({ color: 0xe8e8e8, emissive: 0xff5a10, emissiveIntensity: 0.75 });
out.rocketMeshes = [];
out.mineMeshes = [];
buildArenaGeo(out, RC.ARENA);
return out;
}
@@ -683,7 +758,7 @@
const scene_add = o => group.add(o);
scene.background = new T.Color(th.bg);
scene.fog = new T.Fog(th.fog, half * 3, half * 5.5);
const { key, rimA, rimB, flashLight } = out.lights;
const { key, rimA, rimB } = out.lights;
const sc = Math.max(11, half + 3);
Object.assign(key.shadow.camera, { left: -sc, right: sc, top: sc, bottom: -sc }); key.shadow.camera.updateProjectionMatrix();
rimA.color.setHex(th.rimA); rimA.position.set(-half - 1, 5, half + 1); rimA.distance = half * 2.6;
@@ -758,10 +833,14 @@
}
for (const [px, pz] of [[-1, -1], [1, -1], [-1, 1]]) {
const post = box(0.22, 3.4, 0.22, wallMat); post.position.set(px * (half + 0.35), 1.7, pz * (half + 0.35)); scene.add(post);
const lamp = box(0.5, 0.3, 0.3, m.lamp); lamp.position.set(px * (half + 0.2), 3.5, pz * (half + 0.2)); scene.add(lamp);
const rig = new T.Group(); rig.position.set(px * (half + 0.2), 3.5, pz * (half + 0.2)); scene.add(rig);
const hous = box(0.46, 0.36, 0.34, new T.MeshStandardMaterial({ color: 0x23272e, metalness: 0.6, roughness: 0.5 }));
hous.castShadow = true; rig.add(hous);
const lens = box(0.3, 0.2, 0.3, m.lamp); lens.position.set(-px * 0.13, -0.12, -pz * 0.13); rig.add(lens);
const arm = cyl(0.035, 0.035, 0.36, m.dark, 6); arm.position.set(px * 0.12, 0.26, pz * 0.12); rig.add(arm);
}
// audience stands behind the back walls
const seats = new T.InstancedMesh(new T.BoxGeometry(0.32, 0.5, 0.32), new T.MeshStandardMaterial({ roughness: 0.9 }), 900);
const seats = new T.InstancedMesh(new T.BoxGeometry(0.32, 0.5, 0.32), new T.MeshStandardMaterial({ color: 0x1b1d24, roughness: 0.95 }), 900);
const col = new T.Color(); let ci = 0; let sd = 11;
const rnd = () => { sd = (sd * 16807) % 2147483647; return sd / 2147483647; };
for (const [nx, nz] of [[-1, 0], [0, -1]]) for (let row = 0; row < 5; row++) {
@@ -776,7 +855,10 @@
col.setHSL(rnd(), 0.3, 0.07 + rnd() * 0.08); seats.setColorAt(ci, col); ci++;
}
}
seats.count = ci; dm.scale.set(1, 1, 1); scene.add(seats);
seats.count = ci; dm.scale.set(1, 1, 1);
seats.instanceMatrix.needsUpdate = true;
if (seats.instanceColor) seats.instanceColor.needsUpdate = true;
scene.add(seats);
// floor saws
// --- cover and floor traps (static, built once per arena) ---
@@ -786,6 +868,9 @@
scrap: new T.MeshStandardMaterial({ color: 0x5a5048, metalness: 0.6, roughness: 0.8 }),
barrier: new T.MeshStandardMaterial({ color: 0x9aa0a8, metalness: 0.6, roughness: 0.5 }),
};
const RUST = new T.MeshStandardMaterial({ color: 0x6e3e22, metalness: 0.45, roughness: 0.92 });
const PAINT = new T.MeshStandardMaterial({ color: 0x7a5230, metalness: 0.3, roughness: 0.85 });
const scrapMats = [BMAT.scrap, RUST, PAINT, m.steel, m.dark];
let bseed = 7;
const brnd = () => { bseed = (bseed * 16807) % 2147483647; return bseed / 2147483647; };
for (const b of A.blocks) {
@@ -793,22 +878,43 @@
const mat = BMAT[b.kind] || BMAT.crate;
if (b.kind === 'pillar') {
const rr = Math.min(b.hw, b.hd);
const col = cyl(rr, rr * 1.12, b.h, mat, 14); col.position.y = b.h / 2; col.castShadow = true; g.add(col);
const cap = cyl(rr * 1.18, rr * 1.18, 0.12, m.dark, 14); cap.position.y = b.h; g.add(cap);
const band = cyl(rr * 1.06, rr * 1.06, 0.18, m.stripe, 14); band.position.y = b.h * 0.42; g.add(band);
const col = cyl(rr, rr * 1.12, b.h, mat, 16); col.position.y = b.h / 2; col.castShadow = true; g.add(col);
const cap = cyl(rr * 1.18, rr * 1.18, 0.12, m.dark, 16); cap.position.y = b.h; g.add(cap);
const foot = cyl(rr * 1.25, rr * 1.35, 0.14, m.dark, 16); foot.position.y = 0.07; g.add(foot);
for (const sy of [0.28, 0.64]) { const band = cyl(rr * 1.05, rr * 1.05, 0.14, m.stripe, 16); band.position.y = b.h * sy; g.add(band); }
// warning light on top
const wl = new T.Mesh(new T.SphereGeometry(0.07, 8, 6), new T.MeshStandardMaterial({ color: 0x401000, emissive: 0xff5a10, emissiveIntensity: 0.9 }));
wl.position.y = b.h + 0.1; g.add(wl);
} else if (b.kind === 'scrap') {
for (let k = 0; k < 5; k++) {
const w2 = b.hw * (0.5 + brnd() * 0.75), h2 = b.h * (0.35 + brnd() * 0.65), d2 = b.hd * (0.5 + brnd() * 0.75);
const p2 = box(w2, h2, d2, mat);
p2.position.set((brnd() - 0.5) * b.hw, h2 / 2, (brnd() - 0.5) * b.hd);
p2.rotation.y = brnd() * 3; p2.castShadow = true; g.add(p2);
// tumbled junk pile: mixed rusty/steel/painted plates, each tilted, with a dark edge lip
for (let k = 0; k < 6; k++) {
const w2 = b.hw * (0.45 + brnd() * 0.8), h2 = b.h * (0.22 + brnd() * 0.5), d2 = b.hd * (0.45 + brnd() * 0.8);
const pm = scrapMats[(brnd() * scrapMats.length) | 0];
const slab = new T.Group();
const p2 = box(w2, h2, d2, pm); p2.castShadow = true; slab.add(p2);
const lip = box(w2 + 0.04, 0.05, d2 + 0.04, m.dark); lip.position.y = h2 / 2; slab.add(lip); // crisp top edge
slab.position.set((brnd() - 0.5) * b.hw * 1.1, h2 / 2 + brnd() * b.h * 0.5, (brnd() - 0.5) * b.hd * 1.1);
slab.rotation.set((brnd() - 0.5) * 0.4, brnd() * 3, (brnd() - 0.5) * 0.4);
g.add(slab);
}
// a rusty barrel wedged in, with a warning ring
const br = Math.min(b.hw, b.hd) * 0.42;
const barrel = cyl(br, br, b.h * 0.95, RUST, 14); barrel.position.set((brnd() - 0.5) * b.hw * 0.5, b.h * 0.48, (brnd() - 0.5) * b.hd * 0.5);
barrel.rotation.z = 0.12; barrel.castShadow = true; g.add(barrel);
const ring = cyl(br * 1.04, br * 1.04, 0.1, m.stripe, 14); ring.position.copy(barrel.position); ring.rotation.z = 0.12; g.add(ring);
// a leaning hazard-striped plank
const plank = box(0.1, b.h * 1.5, b.hd * 0.8, m.stripe); plank.position.set(b.hw * 0.7, b.h * 0.6, 0); plank.rotation.z = 0.5; plank.castShadow = true; g.add(plank);
} else if (b.kind === 'barrier') {
const bar = box(b.hw * 2, b.h, b.hd * 2, mat); bar.position.y = b.h / 2; bar.castShadow = true; g.add(bar);
const top = box(b.hw * 2, 0.1, b.hd * 2.1, m.stripe); top.position.y = b.h; g.add(top);
} else {
const top = box(b.hw * 2 + 0.06, 0.12, b.hd * 2 + 0.06, m.stripe); top.position.y = b.h; g.add(top);
const base = box(b.hw * 2 + 0.1, 0.1, b.hd * 2 + 0.1, m.dark); base.position.y = 0.05; g.add(base);
} else { // crate: steel box with hazard bands, corner bolts and a plated top
const bx = box(b.hw * 2, b.h, b.hd * 2, mat); bx.position.y = b.h / 2; bx.castShadow = true; g.add(bx);
for (const sy of [0.28, 0.74]) { const band = box(b.hw * 2.05, 0.06, b.hd * 2.05, m.dark); band.position.y = b.h * sy; g.add(band); }
const lid = box(b.hw * 2 + 0.05, 0.08, b.hd * 2 + 0.05, m.dark); lid.position.y = b.h; g.add(lid);
for (const sy of [0.3, 0.72]) { const band = box(b.hw * 2.04, 0.08, b.hd * 2.04, m.stripe); band.position.y = b.h * sy; g.add(band); }
for (const sx of [-1, 1]) for (const sz of [-1, 1]) {
const bolt = cyl(0.03, 0.03, b.h * 0.9, m.dark, 6); bolt.position.set(sx * (b.hw - 0.05), b.h / 2, sz * (b.hd - 0.05)); g.add(bolt);
}
}
}
for (const b of A.belts) {
@@ -879,11 +985,30 @@
const mr = cyl(0.43, 0.43, 0.06, m.stripe, 20); mr.position.y = 0.08; mag.add(mr);
out.crane = { post: cpost, boom, cable, mag, px: C.x - 2.4, pz: C.z + 2.4 };
// pit doors + warning lights
// pit: a real shaft you fall into, a hazard-striped rim and a steel grate
const pit = A.pit;
const shaftMat = new T.MeshStandardMaterial({ color: 0x090a0d, metalness: 0.6, roughness: 0.9 });
const floorHole = box(pit.hw * 2, 0.02, pit.hd * 2, new T.MeshBasicMaterial({ color: 0x000000 }));
floorHole.position.set(pit.x, -0.01, pit.z); scene.add(floorHole);
for (const [nx, nz] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { // four shaft walls going down
const w = box(nz ? pit.hw * 2 : 0.08, 1.6, nz ? 0.08 : pit.hd * 2, shaftMat);
w.position.set(pit.x + nx * pit.hw, -0.8, pit.z + nz * pit.hd); scene.add(w);
}
for (const sx of [-1, 1]) for (const sz of [-1, 1]) { // striped rim around the edge
const bx = box(pit.hw * 2 + 0.2, 0.09, 0.14, m.stripe); bx.position.set(pit.x, 0.05, pit.z + sz * (pit.hd + 0.05)); scene.add(bx);
const bz = box(0.14, 0.09, pit.hd * 2 + 0.2, m.stripe); bz.position.set(pit.x + sx * (pit.hw + 0.05), 0.05, pit.z); scene.add(bz);
}
const grate = new T.Group(); out.pitGrate = grate; scene.add(grate); // retracts as the pit opens
const gbarMat = new T.MeshStandardMaterial({ color: 0x4a515c, metalness: 0.85, roughness: 0.35 });
const nb = Math.max(4, Math.round(pit.hw * 2 / 0.3));
for (let k = 0; k <= nb; k++) {
const t = -pit.hw + (k / nb) * pit.hw * 2;
const b1 = box(0.05, 0.08, pit.hd * 2, gbarMat); b1.position.set(pit.x + t, 0.06, pit.z); grate.add(b1);
const b2 = box(pit.hw * 2, 0.08, 0.05, gbarMat); b2.position.set(pit.x, 0.055, pit.z + t * (pit.hd / pit.hw)); grate.add(b2);
}
out.pitDoors = [-1, 1].map(sx => {
const d = box(pit.hw, 0.05, pit.hd * 2, new T.MeshStandardMaterial({ color: 0x3d4148, metalness: 0.8, roughness: 0.4 }));
d.position.set(pit.x + sx * pit.hw / 2, 0.025, pit.z); d.userData.sx = sx; scene.add(d); return d;
d.position.set(pit.x + sx * pit.hw / 2, 0.03, pit.z); d.userData.sx = sx; scene.add(d); return d;
});
out.pitLamps = [[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([sx, sz]) => {
const l = new T.Mesh(new T.SphereGeometry(0.09, 10, 6), new T.MeshStandardMaterial({ color: 0x400000, emissive: 0xff1a1a, emissiveIntensity: 0 }));
@@ -955,7 +1080,7 @@
// intro / title: perspective camera flying over the arena
const pcam = new T.PerspectiveCamera(40, asp, 0.1, 120);
let mode = 'garage', gRobot = null, robots = [], state = null, shake = 0, flashT = 0, introT = 0, scale = 1, hold = 0;
let mode = 'garage', gRobot = null, robots = [], state = null, shake = 0, flashT = 0, introT = 0, scale = 1, hold = 0, editSel = 0, introLightK = 0, comfort = true, titleT = 0, garageSig = null;
let quality = 'high', fxMul = 1, camMode = 'iso', chaseInit = false, gcamZoom = GZ_DEF;
placeGarageCam(); // after gcamZoom exists: start fully zoomed out
// workshop: show what the fitted weapon / turret actually does, on a short loop
@@ -964,17 +1089,19 @@
const R = gRobot; if (!R) return;
demoT += dt;
const c = demoT % 3; // one signature move every 3 s
if (R.saw) { R.sawA += dt * 26; R.saw.rotation[R.sawAxis || 'z'] = -R.sawA; }
if (R.spinner) { R.spinA += dt * 17; R.spinner.rotation.y = R.spinA; }
if (R.vspin) { R.spinA += dt * 19; R.vspin.rotation.z = -R.spinA; }
if (R.hammer) {
const k = c < 0.35 ? c / 0.35 : c < 1.2 ? 1 - (c - 0.35) / 0.85 : 0;
R.hammer.rotation.z = lerp(1.9, -0.25, k);
}
if (R.flipper) R.flipper.rotation.z = -0.32 + (c < 0.3 ? Math.sin(c / 0.3 * Math.PI) * 1.5 : 0);
if (R.jaws) {
const k = c < 1.2 ? Math.abs(Math.sin(c / 1.2 * Math.PI)) : 0;
for (const j of R.jaws) j.rotation.y = j.userData.side * (0.45 - k * 0.63);
for (const wo of R.weapons || []) {
if (wo.saw) { wo.sawA = (wo.sawA || 0) + dt * 26; wo.saw.rotation[wo.sawAxis || 'z'] = -wo.sawA; }
if (wo.spinner) { wo.spinA = (wo.spinA || 0) + dt * 17; wo.spinner.rotation.y = wo.spinA; }
if (wo.vspin) { wo.spinA = (wo.spinA || 0) + dt * 19; wo.vspin.rotation.z = -wo.spinA; }
if (wo.hammer) {
const k = c < 0.35 ? c / 0.35 : c < 1.2 ? 1 - (c - 0.35) / 0.85 : 0;
wo.hammer.rotation.z = lerp(1.9, -0.25, k);
}
if (wo.flipper) wo.flipper.rotation.z = -0.32 + (c < 0.3 ? Math.sin(c / 0.3 * Math.PI) * 1.5 : 0);
if (wo.jaws) {
const k = c < 1.2 ? Math.abs(Math.sin(c / 1.2 * Math.PI)) : 0;
for (const j of wo.jaws) j.rotation.y = j.userData.side * (0.45 - k * 0.63);
}
}
if (R.gun) { R.gunA += dt * 16; R.gun.rotation.x = R.gunA; }
const shooting = c > 1.5 && c < 2.3;
@@ -1013,16 +1140,54 @@
// intro fly-over, then a slow orbit behind the title screen; skip() jumps to the orbit
showIntro(builds, paints) {
api.showArena(RC.Combat.create({ robots: builds.map(b => RC.stats(b)), seed: 3, arena: 'workshop' }), builds, paints);
mode = 'intro'; introT = 0; pointMode(true);
mode = 'intro'; introT = 0; introLightK = 0; pointMode(true);
// compile every shader up front, otherwise the first seconds stutter while they are built
try { renderer.compile(arenaScene, pcam); } catch (e) { /* older three: just carry on */ }
},
skipIntro() { if (mode === 'intro' && introT < INTRO_END) introT = INTRO_END; },
showGarage(build, paint) {
mode = 'garage';
if (gRobot) garage.turntable.remove(gRobot.root);
const sig = JSON.stringify(build);
if (gRobot && sig === garageSig) { gRobot.skin.redraw(paint); return; } // same robot -> just repaint, no rebuild (smoother)
garageSig = sig;
if (gRobot) { garage.turntable.remove(gRobot.root); disposeRobot(gRobot); }
gRobot = buildRobot(build, paint);
gRobot.root.position.y = 0.12;
garage.turntable.add(gRobot.root);
},
// editor: stop / resume the turntable auto-spin so the robot holds still
freeze(on) { hold = on ? 1e9 : 0; },
setEditWeapon(i) { editSel = i | 0; },
// which weapon (index) is under the pointer, or -1
pickWeaponAt(cx, cy) {
if (!gRobot || !gRobot.weapons) return -1;
const r = new T.Raycaster(); r.setFromCamera(ndcOf(canvas, cx, cy), gcam);
for (let i = 0; i < gRobot.weapons.length; i++) {
const wo = gRobot.weapons[i];
if (wo && wo.wmount && r.intersectObject(wo.wmount, true).length) return i;
}
return -1;
},
// drag the selected weapon: snap to the nearest side + set height; returns { side, up } or null
dragWeapon(cx, cy) {
if (!gRobot || !gRobot.weapons || !gRobot.weapons[editSel]) return null;
const wo = gRobot.weapons[editSel], st = gRobot.st, inst = st.weapons[editSel];
const clamp = x => Math.max(-0.3, Math.min(0.6, x));
gRobot.root.updateWorldMatrix(true, false);
const center = new T.Vector3(); gRobot.root.getWorldPosition(center); center.y += st.h * 0.5;
const r = new T.Raycaster(); r.setFromCamera(ndcOf(canvas, cx, cy), gcam);
const hz = new T.Vector3();
if (!r.ray.intersectPlane(new T.Plane(new T.Vector3(0, 1, 0), -center.y), hz)) return null;
const loc = gRobot.root.worldToLocal(hz.clone()), ang = Math.atan2(loc.z, loc.x);
const side = Math.abs(ang) < Math.PI / 4 ? 'front' : Math.abs(ang) > 3 * Math.PI / 4 ? 'back' : ang > 0 ? 'right' : 'left';
let up = inst.mountUp || 0;
const n = new T.Vector3().subVectors(gcam.position, center); n.y = 0; n.normalize();
const vp = new T.Vector3();
if (r.ray.intersectPlane(new T.Plane(n, -n.dot(center)), vp)) up = clamp(vp.y - center.y);
inst.mountA = RC.MOUNTS[side].a; inst.mountAxis = RC.MOUNTS[side].axis; inst.mountUp = up;
placeMount(wo.wmount, inst, st.len, st.wid);
return { side, up };
},
// live update while painting (colour or drawing changed, no rebuild)
setPaint(paint) { if (gRobot) gRobot.skin.redraw(paint); },
// camera for the paint booth: closer, robot centred in the left part
@@ -1063,11 +1228,13 @@
showArena(s, builds, paints) {
api.setArena(s.arena);
mode = 'arena'; state = s; pointMode(camMode !== 'iso'); lightsOn(1); chaseInit = false;
for (const R of robots) arenaScene.remove(R.root);
for (const R of robots) { arenaScene.remove(R.root); disposeRobot(R); }
robots = builds.map((b, i) => { const R = buildRobot(b, paints[i]); arenaScene.add(R.root); return R; });
sparks.clear(); smoke.clear(); fire.clear(); clearDebris(); shake = 0;
for (const m of arena.rocketMeshes) arenaScene.remove(m);
arena.rocketMeshes = [];
for (const m of arena.mineMeshes) arenaScene.remove(m);
arena.mineMeshes = [];
},
events(list) {
for (const e of list) {
@@ -1088,6 +1255,7 @@
case 'press': puff(e.x, e.z, 14); burst(e.x, 0.1, e.z, 24, 5, [1, 0.8, 0.4]); shake = Math.max(shake, 0.45); break;
case 'drop': puff(e.x, e.z, 8); shake = Math.max(shake, 0.2); break;
case 'ko': explode(e.x, 0.5, e.z, 1.2); break;
case 'mine_drop': burst(e.x, 0.12, e.z, 6, 2, [1, 0.8, 0.3]); break;
case 'broke':
breakPart(robots[e.who], e.part);
burst(e.x, 0.45, e.z, 22, 5, [1, 0.8, 0.4]); puff(e.x, e.z, 6);
@@ -1101,12 +1269,14 @@
get camMode() { return camMode; },
setCam(m) {
camMode = m; chaseInit = false;
pcam.fov = m === 'fpv' ? 72 : 55; pcam.updateProjectionMatrix();
pcam.fov = m === 'fpv' ? (comfort ? 62 : 70) : 55; pcam.updateProjectionMatrix(); // narrower fpv fov = less vection
if (mode === 'arena') pointMode(m !== 'iso');
if (robots[0] && robots[0].turret) robots[0].turret.visible = m !== 'fpv';
},
// comfort mode: smoother cockpit follow, narrower fov, weaker shake (reduces motion sickness)
setComfort(on) { comfort = !!on; pcam.fov = camMode === 'fpv' ? (comfort ? 62 : 70) : 55; pcam.updateProjectionMatrix(); },
project(x, y, z) {
const v = new T.Vector3(x, y, z).project(mode === 'arena' && camMode !== 'iso' ? pcam : cam);
const v = _pv.set(x, y, z).project(mode === 'arena' && camMode !== 'iso' ? pcam : cam); // reuse one vector (no per-call GC)
// behind the camera (chase / cockpit): off screen
if (v.z > 1) return { x: -999, y: -999 };
return { x: (v.x + 1) / 2 * W, y: (1 - v.y) / 2 * H };
@@ -1126,10 +1296,12 @@
renderer.render(arenaScene, pcam);
return;
}
if (mode === 'title') titleIdle(dt); // gently animate the two robots behind the title menu
animateArena(dt, now);
sparks.update(dt, 9, 1.2); smoke.update(dt, -0.6, 1.4); fire.update(dt, -2.5, 2);
shake = Math.max(0, shake - dt * 1.2);
const sx = (Math.random() - 0.5) * shake, sz = (Math.random() - 0.5) * shake;
const sk = comfort ? 0.4 : 1; // comfort: soften camera shake
const sx = (Math.random() - 0.5) * shake * sk, sz = (Math.random() - 0.5) * shake * sk;
flashT = Math.max(0, flashT - dt * 3);
arena.flashLight.intensity = flashT * 4;
if (camMode !== 'iso' && state && robots[0]) {
@@ -1144,7 +1316,7 @@
};
// chase: smooth camera behind and above robot 0 · fpv: eyes at the front edge of its top
const cpos = new T.Vector3(), clook = new T.Vector3();
const cpos = new T.Vector3(), clook = new T.Vector3(), _ta = new T.Vector3(), _tb = new T.Vector3(), _pv = new T.Vector3();
function followCam(dt, sx, sz) {
const r = state.robots[0], R = robots[0], half = (state.arena || RC.ARENA).half;
const fx = Math.cos(r.a), fz = Math.sin(r.a);
@@ -1153,55 +1325,77 @@
const k = R.st.len * 0.08;
px = r.x + fx * k; pz = r.z + fz * k; py = Math.max(0.25, r.y) + R.top + 0.55;
lx = px + fx * 6; lz = pz + fz * 6; ly = py - 1.25;
cpos.set(px + sx * 0.3, py, pz + sz * 0.3); clook.set(lx, ly, lz);
// smooth the eye + aim instead of snapping 1:1 to the robot's yaw/bounce -> the main motion-sickness fix
const sm = chaseInit ? Math.min(1, dt * (comfort ? 9 : 16)) : 1;
chaseInit = true;
cpos.lerp(_ta.set(px + sx * 0.3, py, pz + sz * 0.3), sm);
clook.lerp(_tb.set(lx, ly, lz), sm);
} else {
px = Kit.clamp(r.x - fx * 3.6, -half - 1.2, half + 1.2); pz = Kit.clamp(r.z - fz * 3.6, -half - 1.2, half + 1.2); py = 2.2 + r.y * 0.5;
lx = r.x + fx * 1.6; lz = r.z + fz * 1.6; ly = 0.3 + r.y * 0.5;
const k = chaseInit ? Math.min(1, dt * 5) : 1;
chaseInit = true;
cpos.lerp(new T.Vector3(px + sx, py, pz + sz), k); clook.lerp(new T.Vector3(lx, ly, lz), k);
cpos.lerp(_ta.set(px + sx, py, pz + sz), k); clook.lerp(_tb.set(lx, ly, lz), k);
}
pcam.position.copy(cpos); pcam.lookAt(clook);
}
// ---- intro: dark arena -> floodlights flicker on -> camera sweeps up -> two robots are lowered in
const INTRO_END = RC.INTRO_END = 7.5;
const ease = u => (u < 0.5 ? 2 * u * u : 1 - Math.pow(-2 * u + 2, 2) / 2);
const INTRO_END = RC.INTRO_END = 5.2;
function lightsOn(k) {
const L = arena.lights;
L.key.intensity = 1.25 * k; L.rimA.intensity = 1.1 * k; L.rimB.intensity = 0.9 * k;
if (L.hemi) L.hemi.intensity = 0.55 * (0.12 + 0.88 * k);
M.lamp.emissiveIntensity = 1.5 * k;
}
const smoother = u => u * u * u * (u * (u * 6 - 15) + 10); // smootherstep: zero velocity at both ends
function introScript(dt) {
const t = introT, s = state;
// floodlights: off, flicker, on
lightsOn(t < 1.2 ? 0 : t < 1.32 ? 1 : t < 1.5 ? 0.08 : t < 1.62 ? 0.8 : t < 1.85 ? 0.25 : 1);
// camera path, then a slow orbit
// floodlights: dark -> two quick flickers -> full; softened by easing the intensity toward the target
const target = t < 0.25 ? 0.12 : t < 0.4 ? 1 : t < 0.52 ? 0.2 : t < 0.64 ? 1 : t < 0.78 ? 0.45 : 1;
introLightK += (target - introLightK) * Math.min(1, dt * 16);
lightsOn(introLightK);
// one continuous cinematic dolly: low & close -> rise and pull back to a hero 3/4, with a gentle orbit throughout
const orbit = t * 0.05;
let ang, r, h, lx, lz;
if (t < INTRO_END) {
const e = ease(Math.min(1, t / INTRO_END));
ang = lerp(-2.4, Math.PI / 4, e); r = lerp(5, 20.5, e); h = lerp(0.8, 13.5, Math.pow(e, 1.4));
lx = lerp(RC.ARENA.pit.x, -0.6, e); lz = lerp(RC.ARENA.pit.z, -0.6, e);
const u = smoother(Math.min(1, t / INTRO_END));
ang = lerp(-2.4, Math.PI / 4, u) + orbit;
r = lerp(8.2, 19.5, u);
h = lerp(1.7, 13, u);
lx = lerp(RC.ARENA.pit.x * 0.5, -0.3, u); lz = lerp(RC.ARENA.pit.z * 0.5, -0.3, u);
} else {
ang = Math.PI / 4 + (t - INTRO_END) * 0.05; r = 20.5; h = 13.5; lx = lz = 0;
ang = Math.PI / 4 + orbit; r = 19.5; h = 13; lx = -0.3; lz = -0.3; // seamless: matches the sweep's end
}
pcam.position.set(Math.cos(ang) * r, h, Math.sin(ang) * r);
pcam.lookAt(lx, 0.3, lz);
pcam.lookAt(lx, 0.45, lz);
// robots lowered in from above, landing with sparks
s.t = t + 2; // trap timing: flames ignite once the lights are on
s.robots.forEach((rb, i) => {
const k = clamp((t - 2.6 - i * 0.35) / 1.6, 0, 1);
const k = clamp((t - 0.9 - i * 0.3) / 1.3, 0, 1);
const was = rb.y;
rb.y = 7 * Math.pow(1 - k, 2); rb.vx = rb.vz = 0; rb.lifted = rb.y > 0 ? 1 : 0; // lifted: no tumbling
if (was > 0 && rb.y === 0) { burst(rb.x, 0.2, rb.z, Math.round(40 * fxMul), 5, [1, 0.8, 0.4]); puff(rb.x, rb.z, 10); }
rb.spin = t > 5.4 ? Math.min(1, (t - 5.4) * 0.8) : 0; // spinners rev up
rb.sawOn = t > 5.6;
rb.flameOn = t > 5.8 && t < 6.6 || (t > INTRO_END && Math.sin(t * 0.9 + i * 2) > 0.97);
rb.spin = t > 3.1 ? Math.min(1, (t - 3.1) * 1.1) : 0; // spinners rev up
rb.sawOn = t > 3.3;
rb.flameOn = t > 3.5 && t < 4.3 || (t > INTRO_END && Math.sin(t * 0.9 + i * 2) > 0.97);
rb.turretA = rb.a + Math.sin(t * 0.7 + i) * 0.4;
});
}
// title screen: keep the two intro robots alive — spinners turning, turrets swaying, a soft hover bob
function titleIdle(dt) {
const s = state; if (!s || !s.robots) return;
titleT += dt;
s.robots.forEach((rb, i) => {
rb.lifted = 1; // no tumbling physics
rb.spin = 1; rb.sawOn = false;
rb.turretA = rb.a + Math.sin(titleT * 0.55 + i * 2.1) * 0.35;
rb.y = 0.02 + Math.sin(titleT * 1.0 + i * 1.7) * 0.025; // gentle hover
rb.flameOn = Math.sin(titleT * 0.8 + i * 2) > 0.985; // rare flame flick
});
}
function burst(x, y, z, n, sp, c) {
n = Math.max(1, Math.round(n * fxMul));
for (let k = 0; k < n; k++) {
@@ -1226,21 +1420,37 @@
obj.getWorldPosition(wp); obj.getWorldQuaternion(wq);
arenaScene.add(obj);
obj.position.copy(wp); obj.quaternion.copy(wq);
debris.push({ o: obj, vx: (Math.random() - 0.5) * 3.5, vy: 2.2 + Math.random() * 1.8, vz: (Math.random() - 0.5) * 3.5,
rx: (Math.random() - 0.5) * 9, rz: (Math.random() - 0.5) * 9, t: 9 });
while (debris.length > 10) { const d = debris.shift(); arenaScene.remove(d.o); }
const bb = new T.Box3().setFromObject(obj);
const half = Math.max(0.05, (bb.max.y - bb.min.y) / 2); // rest height so the piece sits ON the floor, not through it
debris.push({ o: obj, half, vx: (Math.random() - 0.5) * 3.5, vy: 2.2 + Math.random() * 1.8, vz: (Math.random() - 0.5) * 3.5,
rx: (Math.random() - 0.5) * 9, rz: (Math.random() - 0.5) * 9, settle: 0 });
while (debris.length > 12) { freeDebris(debris.shift()); } // keep the last few lying around
}
function updateDebris(dt) {
const ah = (state && state.arena ? state.arena.half : (RC.ARENA ? RC.ARENA.half : 10));
for (let i = debris.length - 1; i >= 0; i--) {
const d = debris[i];
d.t -= dt; d.vy -= 22 * dt;
d.o.position.x += d.vx * dt; d.o.position.y += d.vy * dt; d.o.position.z += d.vz * dt;
if (d.o.position.y < 0.07) { d.o.position.y = 0.07; d.vy = -d.vy * 0.3; d.vx *= 0.6; d.vz *= 0.6; d.rx *= 0.5; d.rz *= 0.5; }
d.o.rotation.x += d.rx * dt; d.o.rotation.z += d.rz * dt;
if (d.t <= 0) { arenaScene.remove(d.o); debris.splice(i, 1); }
const d = debris[i], o = d.o, rest = d.half;
d.vy -= 22 * dt;
o.position.x += d.vx * dt; o.position.y += d.vy * dt; o.position.z += d.vz * dt;
if (o.position.y <= rest) { // on the ground: bounce a little, then settle flat
o.position.y = rest;
if (d.vy < 0) d.vy = -d.vy * 0.25;
d.vx *= 0.7; d.vz *= 0.7; d.rx *= 0.4; d.rz *= 0.4;
if (Math.abs(d.vy) < 0.3 && Math.hypot(d.vx, d.vz) < 0.2) { d.vy = 0; d.settle = Math.min(1, d.settle + dt * 2); }
} else d.settle = 0;
o.position.x = Math.max(-ah + rest, Math.min(ah - rest, o.position.x)); // stay inside the arena
o.position.z = Math.max(-ah + rest, Math.min(ah - rest, o.position.z));
if (state && state.robots) for (const rb of state.robots) { // robots shove fallen parts aside
if (rb.out) continue;
const dx = o.position.x - rb.x, dz = o.position.z - rb.z, dd = Math.hypot(dx, dz), reach = (rb.st.rad || 0.8) + rest + 0.1;
if (dd < reach && dd > 0.001) { const push = reach - dd, nx = dx / dd, nz = dz / dd; o.position.x += nx * push; o.position.z += nz * push; d.vx += nx * 7; d.vz += nz * 7; d.settle = 0; }
}
o.rotation.x += d.rx * dt; o.rotation.z += d.rz * dt;
if (d.settle >= 1) { const k = 1 - Math.min(1, dt * 3); d.rx *= k; d.rz *= k; }
}
}
function clearDebris() { for (const d of debris) arenaScene.remove(d.o); debris.length = 0; }
const freeDebris = d => { arenaScene.remove(d.o); d.o.traverse(o => { if (o.geometry) o.geometry.dispose(); }); };
function clearDebris() { for (const d of debris) freeDebris(d); debris.length = 0; }
// combat.js says a part broke off -> take it off the model (one piece tumbles away)
function breakPart(R, part) {
if (!R) return;
@@ -1254,7 +1464,7 @@
const main = kill[0];
for (const o of kill) if (o !== main) o.visible = false;
dropPiece(main);
if (part === 'weapon') { R.saw = null; R.spinner = null; R.hammer = null; R.flipper = null; R.jaws = null; }
if (/^weapon\d/.test(part)) { const wi = +part.slice(6); if (R.weapons && R.weapons[wi]) R.weapons[wi] = null; } // stop animating the torn-off weapon
if (part === 'tower') { R.turret = null; R.flame = null; R.gun = null; R.muzzle = null; }
}
@@ -1265,6 +1475,22 @@
robots.forEach((R, i) => {
const r = s.robots[i];
poseRobot(R, r, dt);
// each lance must stop at the enemy (in its own mount direction), not stab through it
const e = s.robots[1 - i];
for (let wi = 0; e && !e.out && wi < (R.weapons || []).length; wi++) {
const wo = R.weapons[wi]; if (!wo || !wo.lance) continue;
const inst = R.st.weapons[wi];
const dx = e.x - r.x, dz = e.z - r.z, d = Math.hypot(dx, dz) || 1;
const a = r.a + (inst ? inst.mountA : 0), fx = Math.cos(a), fz = Math.sin(a), facing = (dx * fx + dz * fz) / d;
if (facing <= 0.55) continue;
const reach = d - e.st.rad * 0.85, bx = wo.lance.userData.baseX;
const maxThrust = reach - (bx + 0.95); // may be negative -> pull the lance back into the sleeve
if (wo.lance.position.x - bx > maxThrust) {
const hit = wo.lance.position.x - bx - maxThrust > 0.04;
wo.lance.position.x = bx + Math.max(-0.45, maxThrust);
if (hit && Math.random() < 0.6) burst(e.x - fx * e.st.rad, 0.4, e.z - fz * e.st.rad, 10, 5, [1, 0.8, 0.4]);
}
}
// damaged robots smoke, dead ones burn
const hp = r.hp / r.maxHp;
R.smokeT -= dt;
@@ -1274,6 +1500,16 @@
smoke.spawn(r.x, y, r.z, (Math.random() - 0.5) * 0.3, 0.9, (Math.random() - 0.5) * 0.3, 1.6, r.dead ? 0.12 : 0.35, r.dead ? 0.12 : 0.34, r.dead ? 0.12 : 0.33);
if (r.dead || hp < 0.2) fire.spawn(r.x, y, r.z, (Math.random() - 0.5) * 0.4, 0.8, (Math.random() - 0.5) * 0.4, 0.4, 1, 0.5, 0.1);
}
// minigun: glowing tracers flying out of the barrel so you can see where it shoots
if (r.gunOn && R.st.tower && R.st.tower.type === 'minigun') {
const ca = Math.cos(r.turretA), sa = Math.sin(r.turretA), y0 = r.y + R.top + 0.2;
for (let q = 0; q < 2; q++) {
const sp = 46 + Math.random() * 14, sprd = (Math.random() - 0.5) * 0.06;
sparks.spawn(r.x + ca * 0.62, y0, r.z + sa * 0.62,
(ca - sa * sprd) * sp, (Math.random() - 0.5) * 0.6, (sa + ca * sprd) * sp, 0.2, 1, 0.92, 0.55);
}
if (Math.random() < 0.5) smoke.spawn(r.x + ca * 0.6, y0, r.z + sa * 0.6, ca * 0.6, 0.5, sa * 0.6, 0.5, 0.42, 0.42, 0.42);
}
if (r.flameOn && Math.random() < 0.7) {
const a = r.turretA + (Math.random() - 0.5) * 0.5, v = 5 + Math.random() * 2;
fire.spawn(r.x + Math.cos(r.turretA) * 0.6, r.y + R.top + 0.18, r.z + Math.sin(r.turretA) * 0.6, Math.cos(a) * v, 0.3, Math.sin(a) * v, 0.45, 1, 0.55, 0.15);
@@ -1312,8 +1548,31 @@
// pit
const o = s.pitOpen;
for (const d of arena.pitDoors) { d.position.x = A.pit.x + d.userData.sx * (A.pit.hw / 2 + o * A.pit.hw * 1.02); d.position.y = 0.025 + o * 0.01; }
if (arena.pitGrate) { arena.pitGrate.position.y = -o * 1.5; arena.pitGrate.visible = o < 0.98; }
for (const l of arena.pitLamps) l.material.emissiveIntensity = s.pitAlarm ? (Math.sin(now / 150) > 0 ? 2.5 : 0.4) : 0;
// rockets
// mines lying on the floor: dark puck, the lamp blinks fast once it is armed
const mines = s.mines || [];
while (arena.mineMeshes.length < mines.length) {
const g = new T.Group();
const puck = new T.Mesh(new T.CylinderGeometry(0.3, 0.34, 0.11, 14), new T.MeshStandardMaterial({ color: 0x23262c, metalness: 0.6, roughness: 0.6 }));
puck.position.y = 0.055; puck.castShadow = true; g.add(puck);
const ring = new T.Mesh(new T.TorusGeometry(0.3, 0.03, 6, 18), new T.MeshStandardMaterial({ color: 0xf2b51c, roughness: 0.6 }));
ring.rotation.x = Math.PI / 2; ring.position.y = 0.1; g.add(ring);
const lamp = new T.Mesh(new T.SphereGeometry(0.06, 8, 6), new T.MeshStandardMaterial({ color: 0x661111, emissive: 0xff2010, emissiveIntensity: 1 }));
lamp.position.y = 0.15; g.add(lamp);
g.userData.lamp = lamp;
arenaScene.add(g); arena.mineMeshes.push(g);
}
arena.mineMeshes.forEach((g, i) => {
const mn = mines[i];
g.visible = !!mn;
if (!mn) return;
g.position.set(mn.x, 0.01, mn.z);
const armed = mn.arm <= 0;
const blink = armed ? (Math.sin(now / 90) > 0 ? 2.4 : 0.15) : 0.5;
g.userData.lamp.material.emissiveIntensity = blink;
});
while (arena.rocketMeshes.length < s.rockets.length) {
const gr = new T.Group();
const body = new T.Mesh(arena.rocketGeo, arena.rocketMat); gr.add(body);

View File

@@ -9,6 +9,39 @@
const RC = (root.RC = root.RC || (typeof require === 'function' ? require('./parts.js') : {}));
const part = (b, slot) => (b && b[slot] ? RC.PARTS[b[slot]] || null : null);
const clamp = (v, a, c) => (v < a ? a : v > c ? c : v);
// per-robot proportions: height / width / length factor (default 1). Bigger = heavier + tougher + slower.
RC.bodyOf = b => {
const d = (b && b.body) || {};
return { hx: clamp(+d.hx || 1, 0.7, 1.6), wx: clamp(+d.wx || 1, 0.8, 1.4), lx: clamp(+d.lx || 1, 0.8, 1.3) };
};
// where the main weapon is bolted on: front (default), back, left or right.
// a = angle offset from the robot's forward (+x); axis = which body half-extent reaches that way.
RC.MOUNTS = { front: { a: 0, axis: 'len' }, back: { a: Math.PI, axis: 'len' }, left: { a: Math.PI / 2, axis: 'wid' }, right: { a: -Math.PI / 2, axis: 'wid' } };
RC.mountOf = b => {
const d = (b && b.mount && b.mount.weapon) || {};
const side = RC.MOUNTS[d.side] ? d.side : 'front';
return { side, a: RC.MOUNTS[side].a, axis: RC.MOUNTS[side].axis, up: clamp(+d.up || 0, -0.3, 0.6) };
};
RC.MAX_WEAPONS = 3;
// a robot carries up to 3 weapons (same id allowed), each with its own side + height.
// new builds use build.weapons = [{id,side,up}]; old builds (single build.weapon + build.mount) are read too.
RC.weaponsOf = b => {
let list = [];
if (b && Array.isArray(b.weapons)) list = b.weapons;
else if (b && b.weapon) { const m = b.mount && b.mount.weapon; list = [{ id: b.weapon, side: m && m.side, up: m && m.up }]; }
const out = [];
for (const w of list) {
const p = w && RC.PARTS[w.id];
if (!p || p.slot !== 'weapon') continue;
const side = RC.MOUNTS[w.side] ? w.side : 'front';
out.push({ id: w.id, part: p, side, up: clamp(+w.up || 0, -0.3, 0.6), a: RC.MOUNTS[side].a, axis: RC.MOUNTS[side].axis });
if (out.length >= RC.MAX_WEAPONS) break;
}
return out;
};
RC.weaponCount = b => (b && Array.isArray(b.weapons) ? b.weapons.filter(w => w && RC.PARTS[w.id] && RC.PARTS[w.id].slot === 'weapon').length : (b && b.weapon ? 1 : 0));
const sizeFactor = bo => bo.hx * bo.wx * bo.lx;
RC.HP_SCALE = 3; // catalogue hp x this = hit points in the arena
@@ -16,12 +49,15 @@
const errors = [];
let weight = 0, power = 0, supply = 0;
for (const slot of RC.SLOTS) {
if (slot === 'weapon') continue; // weapons are a list now, summed below
const p = part(build, slot);
if (!p) { if (RC.REQUIRED[slot]) errors.push('need_' + slot); continue; }
if (p.slot !== slot) { errors.push('bad_' + slot); continue; }
weight += p.weight;
weight += slot === 'chassis' ? Math.round(p.weight * (0.4 + 0.6 * sizeFactor(RC.bodyOf(build)))) : p.weight;
if (slot === 'battery') supply += p.power; else power += p.power || 0;
}
for (const inst of RC.weaponsOf(build)) { weight += inst.part.weight; power += inst.part.power || 0; }
if (RC.weaponCount(build) > RC.MAX_WEAPONS) errors.push('too_many_weapons');
if (weight > RC.WEIGHT_LIMIT) errors.push('overweight');
if (supply && power > supply) errors.push('no_power');
return { ok: errors.length === 0, errors, weight, power, supply };
@@ -29,14 +65,24 @@
RC.stats = build => {
const ch = part(build, 'chassis'), mo = part(build, 'motor'), wh = part(build, 'wheels');
const ar = part(build, 'armour'), we = part(build, 'weapon'), to = part(build, 'tower'), gd = part(build, 'gadget');
const ar = part(build, 'armour'), to = part(build, 'tower'), gd = part(build, 'gadget');
const v = RC.validate(build);
const mass = Math.max(30, v.weight);
let value = 0;
for (const slot of RC.SLOTS) { const p = part(build, slot); if (p) value += p.cost; }
const len = ch ? ch.len : 1.3, wid = ch ? ch.wid : 1.0;
for (const slot of RC.SLOTS) { if (slot === 'weapon') continue; const p = part(build, slot); if (p) value += p.cost; }
const weps = RC.weaponsOf(build);
for (const w of weps) value += w.part.cost;
// per-weapon mount info; combat/render iterate this list, lead weapon kept on st.weapon/mountA for compat
const weapons = weps.map(w => ({ id: w.id, part: w.part, side: w.side, mountA: w.a, mountAxis: w.axis, mountUp: w.up }));
const lead = weapons[0] || null;
const bo = RC.bodyOf(build), size = sizeFactor(bo);
const len = (ch ? ch.len : 1.3) * bo.lx, wid = (ch ? ch.wid : 1.0) * bo.wx;
return {
hp: ((ch ? ch.hp : 80) + (ar ? ar.hp : 0)) * RC.HP_SCALE,
body: bo,
weapons,
mountA: lead ? lead.mountA : 0, mountAxis: lead ? lead.mountAxis : 'len', mountUp: lead ? lead.mountUp : 0,
topHeavy: bo.hx / ((bo.wx + bo.lx) / 2), // tall + narrow = easier to tip over
hp: (Math.round((ch ? ch.hp : 80) * (0.6 + 0.4 * size)) + (ar ? ar.hp : 0)) * RC.HP_SCALE,
reduce: ar ? ar.reduce : 0,
mass,
accel: (mo ? mo.force : 500) / mass * (wh ? Math.min(1.2, wh.grip / 8) : 1),
@@ -44,9 +90,9 @@
turn: (wh ? wh.turn : 2.5) * (1.15 - mass / 650),
grip: wh ? wh.grip : 6,
push: wh ? wh.push : 1,
len, wid, h: ch ? ch.h : 0.42,
rad: Math.hypot(len, wid) / 2 * 0.9, // close to the body corners so robots do not clip through each other
weapon: we, tower: to, gadget: gd, armour: ar,
len, wid, h: (ch ? ch.h : 0.42) * bo.hx,
rad: Math.hypot(len, wid) / 2 * 0.95, // body corners - bigger = robots keep more distance, less clipping
weapon: lead ? lead.part : null, tower: to, gadget: gd, armour: ar,
invertible: !!(wh && wh.invertible),
lowProfile: !!(ch && ch.lowProfile),
frontArmour: ch && ch.frontArmour ? ch.frontArmour : 0,

60
game/sfx.js Normal file
View File

@@ -0,0 +1,60 @@
/* Robot Clash - sound effects: ComfyGen clips where they exist, synth tones as fallback (never silent, never crashes).
const SFX = RC.GameSfx(audio, settings) audio = Kit.createAudio(...), settings.quiet = softer weapon loops */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
RC.GameSfx = function (audio, settings) {
const last = {};
const every = (k, ms) => { const n = performance.now(); if (last[k] && n - last[k] < ms) return false; last[k] = n; return true; };
const SFX = {
click() { audio.sfx('sfx_click'); audio.tone(660, 0.04, 'square', 0.05); },
buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.08); },
deny() { audio.tone(160, 0.15, 'square', 0.12, -40); },
beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); },
clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); },
gate() { // metal garage door rolling open
audio.noise(1.0, 0.4, 1500); audio.noise(0.9, 0.3, 500, 0.05); // metal roll rumble
audio.tone(110, 0.9, 'sawtooth', 0.1, 70); // servo whir rising
for (let k = 0; k < 6; k++) audio.tone(170 + k * 28, 0.05, 'square', 0.07, 0, k * 0.11); // chain clanks
audio.noise(0.25, 0.55, 300, 0.9); audio.tone(58, 0.4, 'sine', 0.5, -22, 0.9); // heavy end clunk
},
win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); },
lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); },
event(e) {
switch (e.type) {
case 'bump': if (every('bump', 90)) audio.noise(0.12, Math.min(0.4, e.speed / 10), 700); break;
case 'wall': if (every('wall', 120)) { audio.sfx('sfx_hit'); audio.noise(0.2, 0.3, 1600); } break;
case 'flip': audio.tone(200, 0.2, 'square', 0.13, 500); audio.noise(0.12, 0.25, 3000); break;
case 'swing': audio.noise(0.15, 0.12, 900); break;
case 'smash': audio.sfx('sfx_hit'); audio.noise(0.25, 0.45, 650); audio.tone(95, 0.25, 'sine', 0.4, -45); break;
case 'spinhit': audio.sfx('sfx_hit'); audio.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); break;
case 'sparks': if (every('grind', 70)) audio.noise(0.06, 0.1, 5200); break;
case 'boom': audio.sfx('sfx_boom'); audio.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break;
case 'ko': audio.sfx('sfx_boom'); audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); break;
case 'launch': audio.noise(0.3, 0.18, 2200); audio.tone(300, 0.3, 'sawtooth', 0.07, 600); break;
case 'press_warn': for (let k = 0; k < 3; k++) audio.tone(880, 0.1, 'square', 0.1, 0, k * 0.2); break;
case 'press': audio.sfx('sfx_hit'); audio.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); break;
case 'crane': audio.tone(140, 0.6, 'sawtooth', 0.07, 140); break;
case 'drop': case 'land': audio.noise(0.22, 0.35, 500); break;
case 'broke': audio.sfx('sfx_hit'); audio.noise(0.45, 0.5, 900); audio.tone(240, 0.35, 'sawtooth', 0.22, -190); break;
case 'mine_drop': audio.tone(520, 0.08, 'square', 0.12, -160); audio.noise(0.06, 0.12, 2200); break;
case 'pit_open': for (let k = 0; k < 3; k++) audio.tone(700, 0.3, 'square', 0.12, -250, k * 0.4); break;
case 'pit': audio.tone(420, 1.2, 'sawtooth', 0.14, -360); break;
case 'grab': audio.tone(150, 0.25, 'square', 0.12, -60); break;
case 'boost': audio.noise(0.4, 0.25, 1800); break;
}
},
loops(s) { // continuous weapons as short repeated bursts
for (const r of s.robots) {
const q = settings.quiet ? 0.3 : 1, slow = settings.quiet ? 1.7 : 1; // quiet mode: softer + less often
if (r.sawOn && every('saw' + r.i, 200 * slow)) { if (!settings.quiet) audio.sfx('sfx_saw', 0.35); audio.tone(360 + Math.random() * 40, 0.12, 'triangle', 0.02 * q); }
if (r.flameOn && every('fl' + r.i, 120 * slow)) audio.noise(0.14, 0.12 * q, 900);
if (r.gunOn && every('gun' + r.i, 70 * slow)) audio.noise(0.04, 0.16 * q, 3500);
if (r.spin > 0.2 && every('spin' + r.i, 100 * slow)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin * q);
}
},
};
return SFX;
};
})(window);

View File

@@ -9,23 +9,23 @@
(function (root) {
'use strict';
const RC = root.RC, $ = Kit.$;
RC.PAINTS = [0xd8452b, 0xff7a1a, 0xf2c230, 0x5fae3b, 0x2e9c8f, 0x2a6fd8, 0x6a3fb0, 0xd94f9a, 0xe6e6e6, 0x8c8c8c, 0x3a3d44, 0x15171b];
RC.PAINTS = [0xd8452b, 0xff7a1a, 0xf2c230, 0x5fae3b, 0x2e9c8f, 0x2a6fd8, 0x6a3fb0, 0xd94f9a, 0xe6e6e6, 0x8c8c8c, 0x3a3d44, 0x15171b,
0x39ff14, 0xc0c0c0, 0xff1e8e, 0x7b2fff]; // last 4 are mission rewards (locked until earned)
RC.PAINT_REWARDS = [0x39ff14, 0xc0c0c0, 0xff1e8e, 0x7b2fff];
// ready-made [body, accent] combinations
RC.SCHEMES = [[0xff7a1a, 0x15171b], [0x15171b, 0xff7a1a], [0x2a6fd8, 0xe6e6e6], [0xd8452b, 0xf2c230],
[0x5fae3b, 0x15171b], [0x6a3fb0, 0xf2c230], [0xe6e6e6, 0xd8452b], [0x3a3d44, 0x2e9c8f]];
const hex = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
const SELL = 0.5;
const HOTKEY = { weapon: 'hk_weapon', tower: 'hk_tower', gadget: 'hk_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', '⚖️'],
power: ['ico_power', '⚡'], money: ['ico_credits', '🪙'], fame: ['ico_fame', '⭐'], accel: [null, '🚀'], turn: [null, '↻'] };
RC.pic = (name, glyph = '', cls = '') =>
`<span class="pic ${cls}" data-f="${glyph}">${name ? `<img src="${Kit.asset('assets/Sprites/' + name + '.png')}" alt="" draggable="false" onerror="this.classList.add('missing')">` : ''}</span>`;
`<span class="pic ${cls}" data-f="${glyph}">${name ? `<img src="${Kit.asset('assets/Sprites/' + name + '.png')}" alt="" draggable="false" decoding="async" onerror="this.classList.add('missing')">` : ''}</span>`;
const ico = k => RC.pic(ICO[k][0], ICO[k][1]);
RC.Shop = function (opt) {
const t = opt.t;
let slot = 'weapon', sel = undefined, tipN = 0, topTab = 'build';
let slot = 'chassis', sel = undefined, tipN = 0, topTab = 'build';
function chipsFor(p) {
const s = [];
@@ -63,110 +63,137 @@
const save = opt.getSave(), b = save.build, v = RC.validate(b);
if (sel === undefined || (sel && RC.PARTS[sel].slot !== slot)) sel = b[slot] || null;
// category tiles
$('tabs').innerHTML = RC.SLOTS.map(sl => `<div class="tab ${sl === slot ? 'on' : ''} ${RC.REQUIRED[sl] && !b[sl] ? 'miss' : ''}" data-slot="${sl}">${RC.pic('slot_' + sl, GLYPH[sl])}<span>${t('slot_' + sl)}</span></div>`).join('');
$('tabs').querySelectorAll('.tab').forEach(el => { el.onclick = () => { slot = el.dataset.slot; sel = b[slot] || null; opt.sfx.click(); render(); }; });
renderTopTabs(); // draw the 3 top tabs (Parts / Paint / Hangar)
if (topTab !== 'paint' && opt.onPaintLeave) opt.onPaintLeave(); // close the inline painter when leaving
const parts = topTab === 'build';
let editing = false;
// category tabs + detail + fitted belong to the Parts tab only
$('tabs').classList.toggle('hide', !parts);
$('fittedwrap').classList.toggle('hide', !parts);
{ const d = $('designer'); if (d) d.classList.add('hide'); }
// part cards
const items = (RC.REQUIRED[slot] ? [] : [null]).concat(RC.partsFor(slot).map(p => p.id));
$('cards').innerHTML = items.map(id => {
const p = id && RC.PARTS[id], eq = b[slot] === id, own = !id || save.owned.includes(id);
const badge = eq ? `<span class="badge">${t('equipped')}</span>` : own && id ? `<span class="badge own">${t('owned')}</span>` : '';
const price = !p || own ? `<div class="pr">&nbsp;</div>` : `<div class="pr ${save.money < p.cost ? 'no' : ''}">${ico('money')}${Kit.fmt(p.cost)}</div>`;
return `<div class="item ${id === sel ? 'sel' : ''}" data-id="${id || ''}">${badge}${RC.pic(p ? 'part_' + id : null, p ? GLYPH[slot] : '✖')}<div class="nm">${p ? p.name : t('none')}</div>${price}</div>`;
}).join('');
$('cards').querySelectorAll('.item').forEach(el => { el.onclick = () => { sel = el.dataset.id || null; opt.sfx.click(); render(); }; });
// detail of the selected card
const p = sel && RC.PARTS[sel], eq = b[slot] === sel, own = !sel || save.owned.includes(sel);
let act;
if (eq) act = `<button disabled>${t('equipped')}</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>`;
if (p && own && !eq) act += `<button data-act="sell">${t('sell', { n: Kit.fmt(Math.round(p.cost * SELL)) })}</button>`;
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] : '✖')}
<div><div class="nm">${p ? p.name : t('none')}</div><div class="ds">${p ? t('pd_' + sel) : t('none_' + slot)}</div>
<div class="chips">${p ? chipsFor(p) : ''}</div><div class="chips" style="margin-top:4px">${deltas(b, sel)}</div></div>
<div class="act">${act}</div>`;
$('detail').querySelectorAll('button[data-act]').forEach(el => { el.onclick = () => act2(el.dataset.act); });
if (parts) {
// category tiles; the weapon tab shows the build editor inside the cards area (tabs stay visible)
$('tabs').innerHTML = RC.SLOTS.map(sl => `<div class="tab ${sl === slot ? 'on' : ''} ${RC.REQUIRED[sl] && !b[sl] ? 'miss' : ''}" data-slot="${sl}">${RC.pic('slot_' + sl, GLYPH[sl])}<span>${t('slot_' + sl)}</span></div>`).join('');
$('tabs').querySelectorAll('.tab').forEach(el => { el.onclick = () => { slot = el.dataset.slot; sel = b[slot] || null; opt.sfx.click(); render(); }; });
editing = slot === 'weapon';
if (opt.onSlot) opt.onSlot(slot); // game.js: freeze the robot while on the weapon tab
$('cards').className = ''; // weapon catalog uses the same card grid as parts
$('detail').classList.remove('hide'); // weapon tab also shows the detail/preview panel
if (editing) {
if (opt.onWeaponTab) opt.onWeaponTab($('cards')); // game.js fills #cards + #detail with the weapon editor
} else {
const locked = opt.locked || (() => false); // event/unlock: hide parts not released yet
const items = (RC.REQUIRED[slot] ? [] : [null]).concat(RC.partsFor(slot).filter(p => !locked(p.id)).map(p => p.id));
$('cards').innerHTML = items.map(id => {
const p = id && RC.PARTS[id], eq = b[slot] === id, own = !id || save.owned.includes(id);
const badge = eq ? `<span class="badge">${t('equipped')}</span>` : own && id ? `<span class="badge own">${t('owned')}</span>` : '';
const price = !p || own ? `<div class="pr">&nbsp;</div>` : `<div class="pr ${save.money < p.cost ? 'no' : ''}">${ico('money')}${Kit.fmt(p.cost)}</div>`;
return `<div class="item ${id === sel ? 'sel' : ''}" data-id="${id || ''}">${badge}${RC.pic(p ? 'part_' + id : null, p ? GLYPH[slot] : '✖')}<div class="nm">${p ? p.name : t('none')}</div>${price}</div>`;
}).join('');
$('cards').querySelectorAll('.item').forEach(el => { el.onclick = () => { sel = el.dataset.id || null; opt.sfx.click(); render(); }; });
const p = sel && RC.PARTS[sel], eq = b[slot] === sel, own = !sel || save.owned.includes(sel);
let act;
if (eq) act = `<button disabled>${t('equipped')}</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>`;
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>`;
$('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 class="chips">${p ? chipsFor(p) : ''}</div><div class="chips" style="margin-top:4px">${deltas(b, sel)}</div></div>
<div class="act">${act}</div>`;
$('detail').querySelectorAll('button[data-act]').forEach(el => { el.onclick = () => act2(el.dataset.act); });
}
} else if (topTab === 'paint') {
if (opt.onSlot) opt.onSlot(''); // leave weapon mode / unfreeze
$('detail').classList.add('hide');
$('cards').className = 'pcards';
if (opt.onPaintTab) opt.onPaintTab($('cards')); // game.js: slots + colours + inline painter
} else { // hangar
if (opt.onSlot) opt.onSlot('');
$('detail').classList.add('hide');
$('cards').className = 'hcards';
if (opt.onHangarView) opt.onHangarView($('cards'));
}
// robot stats (white ghost bar = value with the selected part)
const st = RC.stats(b), alt = sel !== b[slot] ? RC.stats(Object.assign({}, b, { [slot]: sel })) : null;
const st = RC.stats(b), alt = (parts && !editing && sel !== b[slot]) ? RC.stats(Object.assign({}, b, { [slot]: sel })) : null;
const valt = alt ? RC.validate(Object.assign({}, b, { [slot]: sel })) : null;
const bar = (val, max, over, ghost) => `<div class="bar">${ghost != null ? `<i class="ghost" style="width:${Math.min(100, ghost / max * 100)}%"></i>` : ''}<i class="${over ? 'over' : ''}" style="width:${Math.min(100, val / max * 100)}%;${ghost != null && ghost < val ? 'opacity:.55' : ''}"></i></div>`;
// warn about the build you are PREVIEWING (selected part card / picked weapon) before you commit it, else the current build
let shownB = b;
if (parts && !editing && sel && sel !== b[slot]) shownB = Object.assign({}, b, { [slot]: sel });
else if (editing && opt.weaponPreview) { const pb = opt.weaponPreview(); if (pb) shownB = pb; }
const vWarn = shownB === b ? v : RC.validate(shownB);
const overW = vWarn.weight > RC.WEIGHT_LIMIT, overP = vWarn.power > vWarn.supply;
$('meters').innerHTML = [
['weight', t('m_weight'), bar(v.weight, RC.WEIGHT_LIMIT, v.weight > RC.WEIGHT_LIMIT, valt && valt.weight), `${v.weight}/${RC.WEIGHT_LIMIT} kg`],
['power', t('m_power'), bar(v.power, Math.max(1, v.supply), v.power > v.supply, valt && valt.power), `${v.power}/${v.supply}`],
['weight', t('m_weight'), bar(v.weight, RC.WEIGHT_LIMIT, overW, valt && valt.weight), `${v.weight}/${RC.WEIGHT_LIMIT} kg`, overW],
['power', t('m_power'), bar(v.power, Math.max(1, v.supply), overP, valt && valt.power), `${v.power}/${v.supply}`, overP],
['hp', t('m_hp'), bar(st.hp, 175 * RC.HP_SCALE, false, alt && alt.hp), Math.round(st.hp)],
['armour', t('m_armour'), bar(st.reduce, 0.4, false, alt && alt.reduce), Math.round(st.reduce * 100) + '%'],
['speed', t('m_speed'), bar(st.top, 7, false, alt && alt.top), st.top.toFixed(1) + ' m/s'],
['accel', t('m_accel'), bar(st.accel, 30, false, alt && alt.accel), st.accel.toFixed(1)],
['turn', t('m_turn'), bar(st.turn, 3.6, false, alt && alt.turn), st.turn.toFixed(1)],
].map(r => `<span class="st" title="${r[1]}">${ico(r[0])}${r[2]}<span>${r[3]}</span></span>`).join('');
].map(r => `<span class="st ${r[5] ? 'warn' : ''}" title="${r[1]}">${ico(r[0])}${r[2]}<span>${r[3]}</span></span>`).join('');
// paint
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
$(id).innerHTML = RC.PAINTS.map(c => `<span class="sw ${save.paint[key] === c ? 'on' : ''}" data-c="${c}" style="background:${hex(c)}"></span>`).join('');
$(id).querySelectorAll('.sw').forEach(el => { el.onclick = () => { save.paint[key] = +el.dataset.c; opt.sfx.click(); opt.onSave(); opt.onPaint(); render(); }; });
}
// ready-made two-colour schemes
const sc = $('paintSchemes');
if (sc) {
sc.innerHTML = RC.SCHEMES.map(([b2, a2]) => {
const on = save.paint.body === b2 && save.paint.accent === a2;
return `<span class="sw duo ${on ? 'on' : ''}" data-b="${b2}" data-a="${a2}"><i style="background:${hex(b2)}"></i><i style="background:${hex(a2)}"></i></span>`;
}).join('');
sc.querySelectorAll('.sw').forEach(el => {
el.onclick = () => { save.paint.body = +el.dataset.b; save.paint.accent = +el.dataset.a; opt.sfx.click(); opt.onSave(); opt.onPaint(); render(); };
});
}
$('gErr').textContent = v.errors.map(e => t('err_' + e.replace(/^(need|bad)_.*/, '$1'), { slot: t('slot_' + e.split('_')[1]) })).join(' · ');
// build problem -> a loud, blinking message naming exactly what is too weak (battery / weight / motor)
const gErr = $('gErr');
if (vWarn.errors.length) {
const msg = vWarn.errors.map(e => {
if (e === 'overweight') return t('err_overweight', { n: RC.WEIGHT_LIMIT });
if (e === 'no_power') return t('err_no_power');
if (e === 'too_many_weapons') return t('err_too_many_weapons');
return t('err_' + e.replace(/^(need|bad)_.*/, '$1'), { slot: t('slot_' + e.split('_')[1]) });
}).join(' · ');
gErr.innerHTML = '⚠ ' + msg;
gErr.classList.remove('alert'); void gErr.offsetWidth; gErr.classList.add('alert'); // restart the blink on every change/click
} else { gErr.textContent = ''; gErr.classList.remove('alert'); }
$('bLeague').disabled = !v.ok; $('bTrain').disabled = !v.ok;
const name = $('rname');
if (document.activeElement !== name) name.value = save.robotName;
if (!$('mechTip').textContent) tip();
renderTopTabs(); renderFitted();
renderFitted();
// live preview: show the selected part on the 3D robot (even parts you can't afford yet)
if (opt.onPreview) opt.onPreview(topTab === 'build' && sel !== b[slot] ? Object.assign({}, b, { [slot]: sel }) : b);
if (opt.onPreview) opt.onPreview(parts && !editing && sel !== b[slot] ? Object.assign({}, b, { [slot]: sel }) : b);
}
// top mode tabs: Parts / Paint / Hangar
// proportions (height/width/length) now live in the build editor (game.js), not here
// top mode tabs: Parts / Paint / Hangar - all render into #cards (render() routes the content)
function renderTopTabs() {
const tabs = [['build', '🔧 ' + t('tab_build')], ['paint', '🎨 ' + t('tab_paint')], ['hangar', '🚗 ' + t('tab_hangar')]];
$('shopTabs').innerHTML = tabs.map(([k, label]) => `<button class="${k === topTab ? 'on' : ''}" data-tab="${k}">${label}</button>`).join('');
$('shopTabs').querySelectorAll('button').forEach(bt => { bt.onclick = () => { setTab(bt.dataset.tab); opt.sfx.click(); }; });
$('buildView').classList.toggle('hide', topTab !== 'build');
$('paintView').classList.toggle('hide', topTab !== 'paint');
$('hangarView').classList.toggle('hide', topTab !== 'hangar');
if (topTab === 'hangar' && opt.onHangarView) opt.onHangarView($('hangarView'));
}
function setTab(k) { topTab = k; renderTopTabs(); }
function setTab(k) { topTab = k; render(); }
// fitted parts summary (left column): every slot with the equipped part + quick remove/jump
function renderFitted() {
const save = opt.getSave(), b = save.build;
$('fitted').innerHTML = RC.SLOTS.map(sl => {
if (sl === 'weapon') { // weapons are a list -> open the editor
const ws = RC.weaponsOf(b), label = ws.length ? ws[0].part.name + (ws.length > 1 ? ' ×' + ws.length : '') : t('none');
return `<div class="frow" data-edit="1">${RC.pic('slot_weapon', GLYPH.weapon)}<span class="fn ${ws.length ? '' : 'empty'}">${label}</span><span class="frm">🔧</span></div>`;
}
const id = b[sl], p = id && RC.PARTS[id];
const rm = p && !RC.REQUIRED[sl] ? `<span class="frm" data-rm="${sl}">✕</span>` : '<span></span>';
return `<div class="frow" data-goto="${sl}">${RC.pic('slot_' + sl, GLYPH[sl])}<span class="fn ${p ? '' : 'empty'}">${p ? p.name : t('none')}</span>${rm}</div>`;
}).join('');
$('fitted').querySelectorAll('.frow').forEach(el => { el.onclick = e => {
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 (el.dataset.edit) { slot = 'weapon'; opt.sfx.click(); 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();
}; });
}
// every economy change goes through opt.act (RC.Eco rules; online the server checks the same action)
function act2(what) {
const save = opt.getSave(), p = sel ? RC.PARTS[sel] : null;
if (what === 'buy' && p && save.money >= p.cost && !save.owned.includes(sel)) {
save.money -= p.cost; save.owned.push(sel); save.build[slot] = sel; opt.sfx.buy();
say(t('tip_bought', { name: p.name }));
} else if (what === 'eq') {
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; }
const p = sel ? RC.PARTS[sel] : null;
const a = what === 'buy' ? { type: 'buy', part: sel } : what === 'eq' ? { type: 'equip', slot, part: sel || null } : what === 'sell' ? { type: 'sell', part: sel } : null;
if (!a || !opt.act(a).ok) { opt.sfx.deny(); return; }
if (what === 'eq') opt.sfx.click(); else opt.sfx.buy();
if (what === 'buy' && p) say(t('tip_bought', { name: p.name }));
opt.onSave(); opt.onBuild(); render();
}
@@ -186,6 +213,6 @@
});
$('rname').addEventListener('keydown', e => { if (e.key === 'Enter') $('rname').blur(); e.stopPropagation(); });
$('mechPic').innerHTML = `<img src="${Kit.asset('assets/Sprites/npc_mechanic.png')}" alt="" onerror="this.classList.add('missing')">`;
return { render, tip, setTab, reset() { sel = undefined; topTab = 'build'; } };
return { render, tip, setTab, weaponTab() { slot = 'weapon'; render(); }, reset() { sel = undefined; topTab = 'build'; } };
};
})(window);

104
game/tourney.js Normal file
View File

@@ -0,0 +1,104 @@
/* Robot Clash - knockout tournament (no DOM, runs in Node for the tests).
Needs parts.js, robot.js, combat.js, ai.js.
An eight robot bracket: you plus seven league robots. Quarter final, semi final, final -
three fights if you keep winning. The other matches of each round are really fought out with
the normal simulation, so the field behaves like the league does.
const st = RC.Tourney.create({ me: { name, build, paint }, seed });
RC.Tourney.pair(st) -> [a, b] for your match this round (null once it is over)
RC.Tourney.simOthers(st) -> fights every other match of the round, fills st.log
RC.Tourney.advance(st, won) -> your result goes in, the round closes, next field is built
st.round 0..2, st.field (entries left), st.done, st.won, st.out (you were knocked out)
Entries: league robots as they are, your own has player: true. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || (typeof require === 'function' ? require('./parts.js') : {}));
const ROUND_PRIZE = [600, 1200, 2500]; // won the quarter / semi / final
const ENTRY_FEE = 400;
const ROUND_KEY = ['quarter', 'semi', 'final'];
function rng(seed) {
let s = (seed || 1) >>> 0;
return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 4294967296; };
}
// one AI against another, fought out properly; returns the winner (0 or 1)
function simFight(a, b, seed, arenaId) {
const s = RC.Combat.create({ robots: [RC.stats(a.build), RC.stats(b.build)], seed, names: [a.name, b.name], arena: arenaId });
const ba = RC.AI.create({ style: a.style || 'brawler', skill: a.skill == null ? 0.5 : a.skill, seed });
const bb = RC.AI.create({ style: b.style || 'brawler', skill: b.skill == null ? 0.5 : b.skill, seed: seed + 7 });
const dt = 1 / 60;
for (let i = 0; i < 60 * 125 && !s.result; i++) {
const [p, q] = s.robots;
RC.Combat.step(s, dt, [ba.think(s, p, q, dt), bb.think(s, q, p, dt)]);
s.events.length = 0;
}
if (s.result && s.result.winner >= 0) return s.result.winner;
// a draw is decided by damage, then by the stronger robot
const [p, q] = s.robots;
if (Math.abs(p.dealt - q.dealt) > 0.5) return p.dealt > q.dealt ? 0 : 1;
return (a.skill || 0) >= (b.skill || 0) ? 0 : 1;
}
function create(opt) {
const seed = (opt.seed || 1) >>> 0, rand = rng(seed);
const pool = RC.LEAGUE.slice();
// seven opponents, drawn at random
for (let i = pool.length - 1; i > 0; i--) { const j = (rand() * (i + 1)) | 0; const t = pool[i]; pool[i] = pool[j]; pool[j] = t; }
const field = pool.slice(0, 7);
const me = { id: 'you', player: true, name: opt.me.name, build: opt.me.build, paint: opt.me.paint, style: 'brawler', skill: 0.5 };
field.splice((rand() * 8) | 0, 0, me); // you can start anywhere in the bracket
return { seed, round: 0, field, rounds: [field.slice()], log: [], done: false, won: false, out: false, prize: 0 };
}
const myIndex = st => st.field.findIndex(e => e && e.player);
// your match of this round: pairs are (0,1), (2,3), ...
function pair(st) {
if (st.done) return null;
const i = myIndex(st);
if (i < 0) return null;
const other = i % 2 === 0 ? i + 1 : i - 1;
return [st.field[i], st.field[other]];
}
// fight every match of this round that you are not in
function simOthers(st) {
const rand = rng(st.seed + st.round * 101);
const mine = myIndex(st), ids = RC.ARENAS.map(a => a.id);
st.pending = [];
for (let i = 0; i < st.field.length; i += 2) {
const a = st.field[i], b = st.field[i + 1];
if (!b) { st.pending.push(a); continue; } // odd one out walks on
if (i === mine || i + 1 === mine) { st.pending.push(null); continue; } // yours is played for real
const seed = ((rand() * 1e9) | 0) || 1;
const w = simFight(a, b, seed, ids[seed % ids.length]);
const win = w === 0 ? a : b, lose = w === 0 ? b : a;
st.pending.push(win);
st.log.push({ round: st.round, a: a.name, b: b.name, winner: win.name, loser: lose.name });
}
return st.pending;
}
// your result closes the round and builds the next field
function advance(st, playerWon) {
if (st.done) return st;
if (!st.pending) simOthers(st);
const mine = myIndex(st), slot = (mine / 2) | 0;
const me = st.field[mine], other = st.field[mine % 2 === 0 ? mine + 1 : mine - 1];
st.pending[slot] = playerWon ? me : other;
st.log.push({ round: st.round, a: me.name, b: other.name, winner: (playerWon ? me : other).name, loser: (playerWon ? other : me).name, mine: true });
if (playerWon) st.prize += ROUND_PRIZE[st.round] || 0;
st.field = st.pending.filter(Boolean);
st.pending = null;
st.round++;
if (st.field.length) st.rounds[st.round] = st.field.slice(); // snapshot for the bracket view
if (!playerWon) { st.done = true; st.out = true; }
else if (st.field.length <= 1) { st.done = true; st.won = true; }
return st;
}
RC.Tourney = { create, pair, simOthers, advance, simFight, ROUND_PRIZE, ENTRY_FEE, ROUND_KEY, SIZE: 8 };
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

196
game/workshop.js Normal file
View File

@@ -0,0 +1,196 @@
/* Robot Clash - workshop extras: weapon/shape editor, paint tab with paint slots, hangar (several robots).
Part of game.js (split for size): created once by game.js with the shared context G.
Live state (save, mode, F, ...) is read as G.<name>; services/helpers are taken from G at creation. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
RC.GameWorkshop = function (G) {
const {
$, GLYPH_SLOT, MAX_ROBOTS, SFX, act, esc, hud, layer, paintObj, painter, persist, shop, syncActive, t,
weaponName
} = G;
// ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ----
function refreshEditorRobot() { G.view.showGarage(G.save.build, paintObj()); G.view.freeze(true); G.view.setEditWeapon(G.editSel); }
function reDrawEditor() { persist(); hud(); refreshEditorRobot(); shop.render(); } // after a change: 3D + tabs + meters + editor
// weapon detail chips (mirrors the shop's part chips, weapon stats only)
function wChips(p) {
const s = [];
if (p.dmg) s.push(`<span>${t('st_dmg', { n: p.dmg })}</span>`);
if (p.dps) s.push(`<span>${t('st_dps', { n: p.dps })}</span>`);
if (p.range) s.push(`<span>${t('st_range', { n: p.range })}</span>`);
s.push(`<span class="key">⌨ ${t('hk_weapon')}</span>`);
s.push(`<span>⚖️ ${p.weight} kg</span>`);
if (p.power) s.push(`<span>⚡ ${p.power}</span>`);
return s.join('');
}
// show the clicked weapon live on the robot (a mounted one, else a temporary front preview)
function previewWeapon(id) {
const weps = G.save.build.weapons || [];
const idx = weps.findIndex(w => w.id === id);
if (idx >= 0) { G.editSel = idx; refreshEditorRobot(); }
else {
const pv = Object.assign({}, G.save.build, { weapons: weps.concat([{ id, side: 'front', up: 0 }]) });
G.view.showGarage(pv, paintObj()); G.view.freeze(true); G.view.setEditWeapon(weps.length);
}
}
function renderWeaponEditor() {
const cards = $('cards'), wp = $('wplace'); if (!G.save || !cards) return;
const b = G.save.build, weps = b.weapons || [];
G.editSel = Math.min(G.editSel, Math.max(0, weps.length - 1));
const cat = RC.partsFor('weapon');
const canAdd = weps.length < RC.MAX_WEAPONS;
if (!G.wPrev || !RC.PARTS[G.wPrev]) G.wPrev = (weps[G.editSel] && weps[G.editSel].id) || cat[0].id;
// right (#cards): the weapon catalog, same card grid as the other slots — click = preview
cards.className = '';
cards.innerHTML = cat.map(p => {
const mounted = weps.filter(w => w.id === p.id).length;
const badge = mounted ? `<span class="badge own">×${mounted}</span>` : '';
const price = `<div class="pr ${G.save.money < p.cost ? 'no' : ''}">🪙 ${Kit.fmt(p.cost)}</div>`;
return `<div class="item ${p.id === G.wPrev ? 'sel' : ''}" data-prev="${p.id}">${badge}${RC.pic('part_' + p.id, GLYPH_SLOT.weapon)}<div class="nm">${p.name}</div>${price}</div>`;
}).join('');
cards.querySelectorAll('[data-prev]').forEach(x => x.onclick = () => { G.wPrev = x.dataset.prev; SFX.click(); previewWeapon(G.wPrev); renderWeaponEditor(); });
// detail panel: previewed weapon + Montieren / Entfernen (like the other slots)
const dp = $('detail'), pv = RC.PARTS[G.wPrev];
if (dp && pv) {
const mounted = weps.filter(w => w.id === G.wPrev).length, poor = G.save.money < pv.cost;
let act = `<button class="primary" data-wact="add" ${(!canAdd || poor) ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(pv.cost) })}</button>`;
if (mounted) act += `<button data-wact="rem">${t('sell', { n: Kit.fmt(RC.Eco.sellValue(G.wPrev)) })}</button>`;
if (!canAdd) act += `<span class="muted">${t('ed_max', { n: RC.MAX_WEAPONS })}</span>`;
dp.innerHTML = `${RC.pic('part_' + G.wPrev, GLYPH_SLOT.weapon)}
<div><div class="nm">${pv.name}${mounted ? ` <span class="badge own">×${mounted}</span>` : ''}</div>
<div class="ds">${t('pd_' + G.wPrev)}</div><div class="chips">${wChips(pv)}</div></div>
<div class="act">${act}</div>`;
dp.querySelectorAll('button[data-wact]').forEach(x => x.onclick = () => {
if (x.dataset.wact === 'add') addWeapon(G.wPrev);
else { const i = weps.map(w => w.id).lastIndexOf(G.wPrev); if (i >= 0) removeWeapon(i); }
});
}
// left (#wplace): placement of the active mounted weapon + shape (no sell list)
if (wp) {
const sel = weps[G.editSel];
const sides = [['front', t('mt_front')], ['back', t('mt_back')], ['left', t('mt_left')], ['right', t('mt_right')]];
const srow = (key, label, lo, hi) => { const val = (b.body && b.body[key]) || 1; return `<div class="wprow"><span>${t('des_' + label)}</span><input type="range" data-body="${key}" min="${lo}" max="${hi}" step="0.05" value="${val}"><span class="dv">${Math.round(val * 100)}%</span></div>`; };
wp.classList.remove('hide');
wp.innerHTML =
`<div class="wphead">${t('ed_weapons')} ${weps.length}/${RC.MAX_WEAPONS}</div>`
+ (sel ? `<div class="wphead">${t('ed_place')} — ${RC.PARTS[sel.id].name}</div>`
+ `<div class="wpsides">${sides.map(([k, lb]) => `<button data-side="${k}" class="${sel.side === k ? 'on' : ''}">${lb}</button>`).join('')}</div>`
+ `<div class="wprow"><span>${t('des_height')}</span><input type="range" id="edUp" min="-0.3" max="0.6" step="0.05" value="${sel.up || 0}"><span class="dv">${Math.round(((sel.up || 0) + 0.3) / 0.9 * 100)}%</span></div>`
: `<span class="edhint">${t('ed_noweapons')}</span>`)
+ `<div class="wphead">${t('s_body')}</div>${srow('hx', 'height', 0.7, 1.6)}${srow('wx', 'width', 0.8, 1.4)}${srow('lx', 'length', 0.8, 1.3)}`;
wp.querySelectorAll('[data-side]').forEach(x => x.onclick = () => { if (!sel) return; act({ type: 'weaponPlace', index: G.editSel, side: x.dataset.side }); SFX.click(); reDrawEditor(); });
if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } }; // live preview while dragging
if ($('edUp')) $('edUp').onchange = e => { if (sel) act({ type: 'weaponPlace', index: G.editSel, up: +e.target.value }); reDrawEditor(); };
wp.querySelectorAll('[data-body]').forEach(x => {
x.oninput = e => { b.body = b.body || { hx: 1, wx: 1, lx: 1 }; b.body[e.target.dataset.body] = +e.target.value; refreshEditorRobot(); };
x.onchange = e => { act({ type: 'body', [e.target.dataset.body]: +e.target.value }); reDrawEditor(); };
});
}
if (weps[G.editSel] && weps[G.editSel].id === G.wPrev) G.view.setEditWeapon(G.editSel);
}
function addWeapon(id) {
if (!act({ type: 'weaponAdd', part: id }).ok) { SFX.deny(); return; }
G.editSel = G.save.build.weapons.length - 1; G.wPrev = id; G.view.setEditWeapon(G.editSel);
SFX.buy(); reDrawEditor();
}
function removeWeapon(i) {
if (!act({ type: 'weaponRemove', index: i }).ok) { SFX.deny(); return; }
if (G.editSel >= G.save.build.weapons.length) G.editSel = Math.max(0, G.save.build.weapons.length - 1);
G.view.setEditWeapon(G.editSel);
SFX.buy(); reDrawEditor();
}
// ---- paint tab: 3 save slots + quick colours + the inline painter (all inside #cards) ----
const phex = c => '#' + (c >>> 0).toString(16).padStart(6, '0');
function paintTab(el) {
let hdr = $('paintHdr');
if (!hdr) { el.innerHTML = ''; hdr = document.createElement('div'); hdr.id = 'paintHdr'; hdr.className = 'phdr'; el.appendChild(hdr); }
$('shop').classList.add('paintmode'); // hide category tabs / detail / fitted bar while painting
renderPaintHeader(hdr);
if (!painter.isOpen) painter.open(el); // mount the painter inline, below the header
}
function paintLeave() {
$('shop').classList.remove('paintmode');
if (!painter.isOpen) return;
const art = painter.hasArt();
G.save.paint.decal = art ? layer.toDataURL('image/png') : null; G.save.paint.drawn = art;
painter.close(); persist();
const hdr = $('paintHdr'); if (hdr) hdr.remove();
}
function renderPaintHeader(hdr) {
const slots = G.save.paintSlots || [];
hdr.innerHTML =
`<div class="pslots">${slots.map((s, i) => `<div class="pslot ${i === G.save.paintSlot ? 'on' : ''}" data-load="${i}" style="background:${phex(s.body)}"><i class="acc" style="background:${phex(s.accent)}"></i>${s.decal ? '<span class="dmark">🖌</span>' : ''}<button class="sv" data-save="${i}">💾</button></div>`).join('')}</div>`
+ `<div class="psec"><h4>${t('paint_body')}</h4><div class="pgrid" id="paintBody"></div></div>`
+ `<div class="psec"><h4>${t('paint_accent')}</h4><div class="pgrid" id="paintAccent"></div></div>`
+ `<div class="psec"><h4>${t('paint_schemes')}</h4><div class="pgrid wide" id="paintSchemes"></div></div>`;
const lockP = c => (RC.PAINT_REWARDS || []).includes(c) && !(G.save.unlockedPaints || []).includes(c); // reward colour, not earned yet
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
$(id).innerHTML = RC.PAINTS.map(c => `<span class="sw ${G.save.paint[key] === c ? 'on' : ''} ${lockP(c) ? 'locked' : ''}" data-c="${c}" style="background:${phex(c)}" title="${lockP(c) ? t('paint_locked') : ''}">${lockP(c) ? '<span class="lk">🔒</span>' : ''}</span>`).join('');
$(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { if (sw.classList.contains('locked')) { SFX.deny && SFX.deny(); return; } G.save.paint[key] = +sw.dataset.c; SFX.click(); persist(); G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
}
$('paintSchemes').innerHTML = RC.SCHEMES.map(([b2, a2]) => { const on = G.save.paint.body === b2 && G.save.paint.accent === a2; return `<span class="sw duo ${on ? 'on' : ''}" data-b="${b2}" data-a="${a2}"><i style="background:${phex(b2)}"></i><i style="background:${phex(a2)}"></i></span>`; }).join('');
$('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { G.save.paint.body = +sw.dataset.b; G.save.paint.accent = +sw.dataset.a; SFX.click(); persist(); G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
hdr.querySelectorAll('[data-load]').forEach(x => x.onclick = e => { if (e.target.dataset.save) return; loadPaintSlot(+x.dataset.load); });
hdr.querySelectorAll('[data-save]').forEach(x => x.onclick = e => { e.stopPropagation(); savePaintSlot(+x.dataset.save); });
}
function loadPaintSlot(i) {
const s = G.save.paintSlots[i]; if (!s) return;
G.save.paintSlot = i;
G.save.paint.body = s.body; G.save.paint.accent = s.accent; G.save.paint.decal = s.decal || null; G.save.paint.drawn = !!s.drawn;
SFX.click(); persist();
RC.layerFromData(layer, G.save.paint.decal, () => { G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); });
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
}
function savePaintSlot(i) {
const art = painter.hasArt();
G.save.paintSlots[i] = { body: G.save.paint.body, accent: G.save.paint.accent, decal: art ? layer.toDataURL('image/png') : (G.save.paint.decal || null), drawn: art || !!G.save.paint.drawn };
G.save.paintSlot = i; SFX.buy(); persist();
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
}
// hangar: switch / add / delete robot slots (owned parts are shared)
function switchRobot(i) {
if (i === G.save.active || !G.save.robots[i]) return;
syncActive();
if (!act({ type: 'robotSwitch', index: i }).ok) return;
persist();
RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); });
shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar();
}
function addRobot() {
syncActive();
if (!act({ type: 'robotNew', name: t('robot_n', { n: G.save.robots.length + 1 }) }).ok) { SFX.deny(); return; }
persist();
RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); });
shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar();
SFX.buy();
}
function delRobot(i) {
syncActive();
if (!act({ type: 'robotDelete', index: i }).ok) { SFX.deny(); return; }
persist(); RC.layerFromData(layer, G.save.paint.decal, () => {}); shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar();
}
// hangar management (shop top-tab): list of robots with weapon, switch / delete + add button
function renderHangar(el) {
el = el || $('cards'); if (!el) return;
const rows = G.save.robots.map((r, i) => `<div class="hmrow ${i === G.save.active ? 'on' : ''}" data-i="${i}">
<div><div class="hmn">${esc(r.name)}</div><div class="hmw">${esc(weaponName(r.build))}</div></div>
${i === G.save.active ? `<span class="muted" style="font-size:12px">${t('active_robot')}</span>` : `<button data-use="${i}">${t('use')}</button>`}
${G.save.robots.length > 1 ? `<button data-del="${i}" title="${t('delete')}">✕</button>` : '<span></span>'}</div>`).join('');
el.innerHTML = `<div class="hmgr">${rows}</div>
${G.save.robots.length < MAX_ROBOTS ? `<button class="primary" id="hAdd" style="margin-top:8px">+ ${t('new_robot')}</button>` : `<p class="muted" style="margin-top:8px">${t('hangar_full')}</p>`}`;
el.querySelectorAll('[data-use]').forEach(b => { b.onclick = () => { SFX.click(); switchRobot(+b.dataset.use); shop.setTab('build'); } ; });
el.querySelectorAll('[data-del]').forEach(b => { b.onclick = () => { SFX.click(); delRobot(+b.dataset.del); renderHangar(); } ; });
if ($('hAdd')) $('hAdd').onclick = () => { addRobot(); shop.setTab('build'); };
}
return {
refreshEditorRobot, reDrawEditor, wChips, previewWeapon, renderWeaponEditor, addWeapon, removeWeapon,
phex, paintTab, paintLeave, renderPaintHeader, loadPaintSlot, savePaintSlot, switchRobot, addRobot,
delRobot, renderHangar
};
};
})(window);

1140
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,28 @@
{
"name": "robot-clash",
"version": "1.0.0",
"version": "0.1.0",
"private": true,
"description": "Robot Clash - build helpers only (the game itself needs no build step).",
"description": "Robot Clash - tests, lint and build helpers (the game itself needs no build step).",
"engines": {
"node": ">=22"
},
"scripts": {
"setup": "npm install && npm --prefix server install",
"test": "node --test \"tests/**/*.test.js\" \"server/test/**/*.test.js\"",
"test:game": "node --test \"tests/**/*.test.js\"",
"test:server": "npm --prefix server test",
"balance": "node tests/balance.js -v",
"lint": "eslint .",
"dev": "npm --prefix server run dev",
"build:web": "node build-web.mjs",
"e2e": "playwright test",
"bot": "node tools/bot.js"
},
"devDependencies": {
"@eslint/js": "^9.39.5",
"@playwright/test": "^1.65.1",
"eslint": "^9.39.5",
"globals": "^16.5.0",
"terser": "^5.46.1"
}
}

32
playwright.config.js Normal file
View File

@@ -0,0 +1,32 @@
// Browser end-to-end tests (npm run e2e). Uses the installed Google Chrome (no browser download) and starts its own
// server on port 8099 with a fresh throw-away database (tests/e2e/server.js).
'use strict';
const { defineConfig } = require('@playwright/test');
const PORT = 8099;
module.exports = defineConfig({
testDir: 'tests/e2e',
testMatch: '**/*.spec.js',
timeout: 90 * 1000,
expect: { timeout: 15 * 1000 },
fullyParallel: false,
workers: 1,
retries: 0,
reporter: [['list']],
use: {
baseURL: `http://127.0.0.1:${PORT}`,
channel: 'chrome',
headless: true,
viewport: { width: 1280, height: 720 },
launchOptions: { args: ['--enable-unsafe-swiftshader', '--use-angle=swiftshader', '--autoplay-policy=no-user-gesture-required'] },
trace: 'retain-on-failure',
},
webServer: {
command: 'node tests/e2e/server.js',
url: `http://127.0.0.1:${PORT}/healthz`,
env: { PORT: String(PORT) },
reuseExistingServer: false,
timeout: 30 * 1000,
},
});

7
server/.env.example Normal file
View File

@@ -0,0 +1,7 @@
# Copy to server/.env (local dev: npm run dev). Never commit the real .env.
PORT=8080
# Long random string. Empty = random per start (fine locally; sessions end on restart).
JWT_SECRET=
# comma-separated uids allowed to write /db/live (admin). Replaced by seed accounts later (plan P2-1b).
ADMIN_UID=
DB_FILE=./data.sqlite

56
server/README.md Normal file
View File

@@ -0,0 +1,56 @@
# Robot Clash – Server
Node-Backend für den Online-Modus: Konten, server-autoritative Wirtschaft (Geld, Ruhm, Teile, Roboter),
Rangliste, Live-Einstellungen, Lobby und **vom Server gerechnete Live-Kämpfe** über WebSocket. Liefert zusätzlich
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, empfohlen 24)
```
npm run setup # einmal im Repo-Root: Abhängigkeiten für Root + server/
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
```
Spiel unter `http://localhost:8080/`, Status unter `/healthz`, Admin unter `/admin/`.
**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
`npm test` im Repo-Root. Server-Tests (`server/test/*.test.js`) starten den echten Server auf einem Zufallsport mit
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)
REST (Token als `Authorization: Bearer <idToken>`):
- `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`
WebSocket `/ws` – Nachrichten siehe `game/protocol.js` (Versionsnummer `RC.Proto.VERSION`).
## Deploy
Siehe `deploy/README.md`.

104
server/app.js Normal file
View File

@@ -0,0 +1,104 @@
/* Robot Clash server: REST (accounts, online save + shop actions, campaign cloud save, ranking, live settings),
WebSocket /ws (lobby + server-run live fights) and the static game from ../game - all on one origin. */
'use strict';
const http = require('http');
const path = require('path');
const express = require('express');
const auth = require('./auth');
const economy = require('./economy');
const { Matches, KV, CampaignSaves } = require('./db');
const { rateLimit } = require('./ratelimit');
const { createRunner } = require('./match/runner');
const { createLobby } = require('./lobby');
const hub = require('./ws/hub');
const pkg = require('./package.json');
const STARTED = Date.now();
const runner = createRunner();
const lobby = createLobby({ runner, economy, matches: Matches });
const app = express();
app.set('trust proxy', 'loopback'); // behind Caddy: real client IP for the rate limiter
app.use(express.json({ limit: '1mb' }));
app.use(auth.middleware);
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({
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,
}));
// --- accounts ----------------------------------------------------------------------------------------
const authLimit = rateLimit({ name: 'auth', windowMs: 60000, max: process.env.NODE_ENV === 'test' ? 1000 : 20 });
app.post('/api/auth/register', authLimit, run(req => auth.register(body(req).name, body(req).pass, body(req).email)));
app.post('/api/auth/login', authLimit, run(req => auth.login(body(req).login || body(req).email, body(req).pass)));
app.post('/api/auth/guest', authLimit, run(req => auth.guest(body(req).name)));
app.post('/api/auth/refresh', run(req => auth.refresh(body(req).refreshToken)));
app.post('/api/auth/logout', run(req => { auth.logout(body(req).refreshToken); return { ok: true }; }));
// delete your own account (and with it every save and token) - smoke tests clean up with this, players may too
app.delete('/api/me', run(req => { const u = need(req); lobby.leave(u.uid); require('./db').Users.del.run(u.uid); return { ok: true }; }));
app.get('/api/me', (req, res) => res.json(req.user ? { uid: req.uid, name: req.user.name, guest: req.user.guest, admin: req.user.admin } : { uid: null, admin: false }));
// --- online save: read, shop/workshop actions (server-authoritative), cosmetics ------------------------
app.get('/api/online', run(req => economy.load(need(req).uid)));
app.post('/api/online/action', run(req => {
const u = need(req), r = economy.action(u, body(req));
if (r.ok) lobby.refresh(u.uid);
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; }));
// --- campaign cloud save (registered accounts; offline game, client-trusted) --------------------------
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 }; }));
// --- ranking + live settings (public read) -----------------------------------------------------------
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 };
}));
// --- admin page (writes need an admin account, checked above) -----------------------------------------
app.use('/admin', express.static(path.join(__dirname, '..', 'admin'), { index: 'index.html' }));
// --- static game (same origin: no CORS, no mixed content) --------------------------------------------
app.use(express.static(path.join(__dirname, '..', 'game'), {
etag: true,
setHeaders(res, p) {
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
},
}));
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) {
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));
module.exports = { app, server, wss, listen, runner, lobby };

81
server/auth.js Normal file
View File

@@ -0,0 +1,81 @@
/* Accounts: register / login (name or e-mail) / guest / refresh. JWT access tokens + rotating refresh tokens. */
'use strict';
const crypto = require('crypto');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { Users, Tokens } = require('./db');
// No secret configured -> random per process (tokens die on restart). Never fall back to a known string.
const SECRET = process.env.JWT_SECRET || (() => {
if (process.env.NODE_ENV !== 'test') console.warn('[auth] JWT_SECRET not set - using a random secret, sessions end on restart');
return crypto.randomBytes(32).toString('hex');
})();
const ACCESS_TTL = 3600; // seconds
const REFRESH_TTL = 30 * 864e5; // 30 days (ms)
const MIN_PASS = 8;
const newUid = () => crypto.randomBytes(16).toString('hex');
const cleanName = n => Array.from(String(n || '')).filter(c => /[\p{L}\p{N} _-]/u.test(c)).join('').trim().slice(0, 18);
function err(status, code) { const e = new Error(code); e.code = code; e.status = status; return e; }
function issue(u) {
const idToken = jwt.sign({ uid: u.uid, name: u.name, guest: !!u.guest, role: u.role }, SECRET, { expiresIn: ACCESS_TTL });
const refreshToken = crypto.randomBytes(32).toString('hex');
Tokens.insert.run(refreshToken, u.uid, Date.now() + REFRESH_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 createUser({ name, pass, email, role = 'player', guest = false }) {
const now = Date.now();
const u = {
uid: newUid(), name, uname: guest ? null : name.toLowerCase(), email: email || null,
pass: pass ? bcrypt.hashSync(String(pass), 10) : null, role, guest: guest ? 1 : 0, created: now, seen: now,
};
Users.insert.run(u);
return u;
}
function register(name, pass, 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');
return issue(u);
}
function guest(name) { return issue(createUser({ name: cleanName(name) || 'Guest', guest: true })); }
function refresh(refreshToken) {
const row = Tokens.get.get(String(refreshToken || ''));
if (!row || row.exp < Date.now()) throw err(401, 'INVALID_REFRESH');
const u = Users.byId.get(row.uid);
if (!u) throw err(401, 'INVALID_REFRESH');
Tokens.del.run(row.token); // rotate: every refresh token works once
return issue(u);
}
function logout(refreshToken) { if (refreshToken) Tokens.del.run(String(refreshToken)); }
// a token only counts while its account exists (deleted account / database reset -> the client must log in again)
function verify(token) {
let d;
try { d = jwt.verify(String(token || ''), SECRET); } catch (e) { return null; }
const u = Users.byId.get(d.uid);
return u ? { uid: u.uid, name: u.name, guest: !!u.guest, admin: u.role === 'admin' } : null;
}
// express middleware: Authorization: Bearer <idToken> (or ?auth= for old clients) -> req.user / req.uid
function middleware(req, _res, next) {
const tok = (req.headers.authorization || '').replace(/^Bearer\s+/i, '') || req.query.auth;
req.user = tok ? verify(tok) : null;
req.uid = req.user ? req.user.uid : null;
next();
}
module.exports = { register, login, guest, refresh, logout, verify, middleware, createUser, cleanName, MIN_PASS };

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

@@ -0,0 +1,71 @@
/* SQLite access. Opens DB_FILE (':memory:' in tests), applies pending migrations from ./migrations
(NNN_name.sql, in order, each once - tracked in schema_version) and exposes small repositories. */
'use strict';
const fs = require('fs');
const path = require('path');
const Database = require('better-sqlite3');
const DB_FILE = process.env.DB_FILE || path.join(__dirname, '..', 'data.sqlite');
const db = new Database(DB_FILE);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
function migrate() {
db.exec('CREATE TABLE IF NOT EXISTS schema_version (version INTEGER PRIMARY KEY, name TEXT, applied INTEGER)');
const done = new Set(db.prepare('SELECT version FROM schema_version').all().map(r => r.version));
const dir = path.join(__dirname, 'migrations');
const files = fs.readdirSync(dir).filter(f => /^\d+_.+\.sql$/.test(f)).sort();
for (const f of files) {
const v = parseInt(f, 10);
if (done.has(v)) continue;
db.transaction(() => {
db.exec(fs.readFileSync(path.join(dir, f), 'utf8'));
db.prepare('INSERT INTO schema_version (version, name, applied) VALUES (?, ?, ?)').run(v, f, Date.now());
})();
}
}
migrate();
const json = s => { try { return JSON.parse(s); } catch (e) { return null; } };
const Users = {
byId: db.prepare('SELECT * FROM users WHERE uid = ?'),
byLogin: db.prepare('SELECT * FROM users WHERE uname = lower(?) OR email = lower(?)'),
insert: db.prepare('INSERT INTO users (uid, name, uname, email, pass, role, guest, created, seen) VALUES (@uid, @name, @uname, @email, @pass, @role, @guest, @created, @seen)'),
seen: db.prepare('UPDATE users SET seen = ? WHERE uid = ?'),
del: db.prepare('DELETE FROM users WHERE uid = ?'), // cascades to tokens + saves
staleGuests: db.prepare('DELETE FROM users WHERE guest = 1 AND seen < ?'),
};
const Tokens = {
insert: db.prepare('INSERT INTO refresh_tokens (token, uid, exp) VALUES (?, ?, ?)'),
get: db.prepare('SELECT * FROM refresh_tokens WHERE token = ?'),
del: db.prepare('DELETE FROM refresh_tokens WHERE token = ?'),
purge: db.prepare('DELETE FROM refresh_tokens WHERE exp < ?'),
};
const OnlineSaves = {
_get: db.prepare('SELECT data FROM online_saves WHERE uid = ?'),
_put: db.prepare('INSERT INTO online_saves (uid, data, fame, updated) VALUES (?, ?, ?, ?) ON CONFLICT(uid) DO UPDATE SET data = excluded.data, fame = excluded.fame, updated = excluded.updated'),
_top: db.prepare(`SELECT u.uid, u.name, o.fame, o.data FROM online_saves o JOIN users u ON u.uid = o.uid
WHERE o.fame > 0 ORDER BY o.fame DESC, o.updated ASC LIMIT ?`),
get(uid) { const r = this._get.get(uid); return r ? json(r.data) : null; },
put(uid, save) { this._put.run(uid, JSON.stringify(save), save.fame | 0, Date.now()); },
top(n) { return this._top.all(n).map(r => { const d = json(r.data) || {}; return { uid: r.uid, name: r.name, fame: r.fame, flag: d.flag || 'XX' }; }); },
};
const CampaignSaves = {
_get: db.prepare('SELECT data FROM campaign_saves WHERE uid = ?'),
_put: db.prepare('INSERT INTO campaign_saves (uid, data, updated) VALUES (?, ?, ?) ON CONFLICT(uid) DO UPDATE SET data = excluded.data, updated = excluded.updated'),
get(uid) { const r = this._get.get(uid); return r ? json(r.data) : null; },
put(uid, data) { this._put.run(uid, JSON.stringify(data), Date.now()); },
};
const Matches = {
start: db.prepare('INSERT INTO matches (id, seed, arena, uid0, uid1, started) VALUES (?, ?, ?, ?, ?, ?)'),
end: db.prepare('UPDATE matches SET winner = ?, reason = ?, ended = ? WHERE id = ?'),
};
const KV = {
_get: db.prepare('SELECT value FROM kv WHERE key = ?'),
_put: db.prepare('INSERT INTO kv (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value'),
get(k) { const r = this._get.get(k); return r ? json(r.value) : null; },
put(k, v) { this._put.run(k, JSON.stringify(v)); },
};
module.exports = { db, DB_FILE, migrate, Users, Tokens, OnlineSaves, CampaignSaves, Matches, KV };

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

65
server/deploy/README.md Normal file
View File

@@ -0,0 +1,65 @@
# 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 und
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.
## Aufbau auf dem Server
```
/opt/robotclash/
releases/<zeit>-<commit>/ je Deploy ein vollständiges Release (game/, server/, admin/, tools/), die letzten 5 bleiben
current -> releases/... aktives Release (Symlink)
shared/.env PORT, JWT_SECRET, DB_FILE (bleibt über Deploys erhalten, nur root/Dienst lesbar)
shared/data.sqlite Datenbank
backups/ pre-<release>.sqlite vor jedem Deploy, daily-<datum>.sqlite (cron, 14 Tage)
```
Dienst `robotclash` (systemd) läuft als eigener Nutzer `robotclash`, darf nur nach `shared/` schreiben.
## 1) Server einrichten (einmal; erneut ausführen schadet nicht)
```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
```bash
ssh root@roboclash.michael-media.de "systemctl status robotclash; journalctl -u robotclash -n 50"
curl -s https://roboclash.michael-media.de/healthz
```
## Später (Plan)
Eigener SSH-Nutzer `deploy` statt root (P3-1), Deploy aus Gitea Actions bei Push auf `main` (P3-6), Produktion als
zweite Umgebung erst nach T-4.
## Test-Bot auf dem Server (Gegner mit ~0 ms Ping)
```bash
ssh root@roboclash.michael-media.de "cd /opt/robotclash/current && node tools/bot.js --url http://127.0.0.1:8080 --pattern circle"
```
Dann im Browser herausfordern, F3 drücken. Ruckelt es trotzdem, liegt es an deiner Leitung oder am Server – nicht am
Gegner. Strg+C beendet den Bot und löscht sein Gastkonto.

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 tools || echo "!! uncommitted changes in game/server/admin are NOT deployed (only $REF)"
SHA=$(git rev-parse --short "$REF")
REL="$(date -u +%Y%m%d-%H%M%S)-$SHA"
TAR="$(mktemp -t rc-XXXXXX).tgz"
trap 'rm -f "$TAR"' EXIT
echo ">> release $REL -> $HOST"
git archive --format=tar.gz -o "$TAR" "$REF" game server admin tools
scp -q "$TAR" "$HOST:/tmp/rc-$REL.tgz"
tr -d '\r' < server/deploy/remote-release.sh | ssh "$HOST" bash -s -- "$REL" "$SHA" "$RESET"

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

108
server/deploy/setup.sh Normal file
View File

@@ -0,0 +1,108 @@
#!/usr/bin/env bash
# One-time (and re-runnable) server setup for Robot Clash. Run ON the server as root:
# bash setup.sh [domain] default: roboclash.michael-media.de
# Installs Node 24 + Caddy (auto-TLS), creates the service user, the release layout, the hardened systemd
# service, the firewall and a daily DB backup. Migrates the old /opt/robotclash/{game,server} layout.
# Afterwards deploy from your machine: bash server/deploy/deploy.sh --reset-db
set -euo pipefail
DOMAIN="${1:-roboclash.michael-media.de}"
APP=/opt/robotclash
SVC=robotclash
echo ">> Robot Clash setup for $DOMAIN"
# --- Node 24 LTS (Node 20 is end-of-life since 2026-04-30) ----------------------------------------
if ! node -v 2>/dev/null | grep -q '^v24\.'; then
curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
apt-get install -y nodejs
fi
apt-get install -y build-essential python3 ufw sqlite3 curl
# --- Caddy (reverse proxy + automatic HTTPS) ------------------------------------------------------
if ! command -v caddy >/dev/null 2>&1; then
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/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list >/dev/null
apt-get update
apt-get install -y caddy
fi
# --- 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"
# old layout (code + .env + DB directly in /opt/robotclash/server): keep the secret, park the rest
if [ -f "$APP/server/.env" ] && [ ! -f "$APP/shared/.env" ]; then cp "$APP/server/.env" "$APP/shared/.env"; fi
if [ -d "$APP/server" ] || [ -d "$APP/game" ]; then
systemctl stop "$SVC" 2>/dev/null || true
LEG="$APP/legacy-$(date +%F-%H%M)"; mkdir -p "$LEG"
[ -d "$APP/server" ] && mv "$APP/server" "$LEG/"
[ -d "$APP/game" ] && mv "$APP/game" "$LEG/"
echo ">> old layout moved to $LEG (delete it once the new setup runs)"
fi
if [ ! -f "$APP/shared/.env" ]; then
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]
Description=Robot Clash server
After=network.target
[Service]
User=$SVC
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
Restart=always
RestartSec=2
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=$APP/shared
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable "$SVC" >/dev/null
# --- Caddy site: TLS + proxy; WebSocket /ws is proxied as-is (no compression on the socket) --------
cat > /etc/caddy/Caddyfile <<EOF
$DOMAIN {
@compress not path /ws
encode @compress gzip
reverse_proxy localhost:8080
}
EOF
systemctl reload caddy 2>/dev/null || systemctl restart caddy
# --- firewall -------------------------------------------------------------------------------------
ufw allow 22 >/dev/null; ufw allow 80 >/dev/null; ufw allow 443 >/dev/null
ufw --force enable >/dev/null
# --- daily SQLite backup (keep 14) ----------------------------------------------------------------
cat > /etc/cron.daily/robotclash-backup <<EOF
#!/usr/bin/env bash
D=$APP/backups
[ -f $APP/shared/data.sqlite ] && sqlite3 $APP/shared/data.sqlite ".backup '\$D/daily-\$(date +%F).sqlite'"
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
chmod +x /etc/cron.daily/robotclash-backup
echo ">> Setup done. node $(node -v), caddy $(caddy version | cut -d' ' -f1)"
echo ">> Next (from your machine): bash server/deploy/deploy.sh --reset-db"

64
server/economy.js Normal file
View File

@@ -0,0 +1,64 @@
/* Server-authoritative online economy. The online save of every player lives here; money, fame, parts and
robots change ONLY through RC.Eco (game/eco.js - the same rules the client runs) or fight rewards. */
'use strict';
const RC = require('../game/robot.js'); // pulls in parts.js, sets globalThis.RC
require('../game/eco.js');
require('../game/progress.js');
const { OnlineSaves, KV } = require('./db');
const Eco = RC.Eco;
function load(uid) {
let s = OnlineSaves.get(uid);
if (!s || !Array.isArray(s.robots) || !s.robots.length) { s = Eco.newOnlineSave(); OnlineSaves.put(uid, s); }
s.active = Math.max(0, Math.min(s.active | 0, s.robots.length - 1));
Eco.mirror(s); // build/paint/robotName point at robots[active] again after JSON
return s;
}
const store = (uid, s) => OnlineSaves.put(uid, s);
// 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
}
function putCosmetics(uid, incoming) {
const s = load(uid);
Eco.mergeCosmetics(s, incoming);
store(uid, s);
return view(s);
}
// the robot a player fights with (validated) + what the lobby shows
function fighter(uid, name) {
const s = load(uid);
const v = RC.validate(s.build);
return {
ok: v.ok, errors: v.errors, uid, name, flag: s.flag || 'XX', fame: s.fame | 0,
build: JSON.parse(JSON.stringify(s.build)), paint: JSON.parse(JSON.stringify(s.paint)), robotName: s.robotName,
};
}
// book a finished live fight; returns { money, fame, lines, save }
function reward(uid, o) {
const s = load(uid);
const live = KV.get('live') || {};
const ev = live.event && live.event.prizeMul && Date.now() >= (live.event.from || 0) && Date.now() <= (live.event.to || Infinity) ? live.event.prizeMul : 1;
const r = Eco.pvpReward(Object.assign({}, o, { money: s.money, prizeMul: ev }));
Eco.applyReward(s, r);
// achievements pay credits -> decided here, never on the client (same rules: game/progress.js)
const ach = RC.Progress.check(s, { won: r.won, reason: o.reason, hpPct: (o.hp || 0) / (o.maxHp || 1), dealt: o.dealt || 0, lost: (o.lost || []).length });
for (const a of ach) s.money = Math.min(1e9, s.money + (a.reward | 0));
store(uid, s);
return Object.assign(r, { ach: ach.map(a => ({ id: a.id, reward: a.reward })), save: view(s) });
}
function ranks(n = 20) { return OnlineSaves.top(Math.max(1, Math.min(100, n | 0))); }
module.exports = { load, action, putCosmetics, fighter, reward, ranks };

156
server/lobby.js Normal file
View File

@@ -0,0 +1,156 @@
/* Lobby: who is online (= has an open, authenticated socket), challenges, match creation and results.
All state is in memory and uses server time only - no heartbeats, no client clocks.
const lobby = createLobby({ runner, economy, matches })
lobby.join({ uid, name, admin, send }) socket authenticated (a second socket replaces the first)
lobby.leave(uid, send) socket closed (only if it is still the current one)
lobby.handle(uid, msg) validated client message */
'use strict';
const crypto = require('crypto');
const CHALLENGE_TTL = 15000;
function createLobby({ runner, economy, matches, now = () => Date.now() }) {
const players = new Map(); // uid -> { uid, name, room, state, send, match: {id, seat} | null }
const pending = new Map(); // challenger uid -> { to, timer }
const inMatch = new Map(); // uid -> { id, seat } (survives a disconnect)
const row = p => {
const f = economy.fighter(p.uid, p.name);
return { uid: p.uid, name: p.name, flag: f.flag, fame: f.fame, room: p.room || f.flag, state: p.state };
};
const tell = (uid, msg) => { const p = players.get(uid); if (p) p.send(msg); };
const broadcast = (msg, except) => { for (const p of players.values()) if (p.uid !== except) p.send(msg); };
const setState = (p, state) => { p.state = state; broadcast({ t: 'lobby.state', player: row(p) }); };
function join(c) {
const old = players.get(c.uid);
const p = { uid: c.uid, name: c.name, admin: !!c.admin, room: old ? old.room : null, state: 'idle', send: c.send };
if (old && old.send !== c.send) old.send({ t: 'error', code: 'REPLACED' });
players.set(c.uid, p);
const m = inMatch.get(c.uid);
const room = m && runner.get(m.id);
if (room) { p.state = 'inmatch'; room.reconnect(m.seat); }
p.send({ t: 'lobby', players: [...players.values()].filter(x => x.uid !== c.uid).map(row), you: row(p) });
if (!old) broadcast({ t: 'lobby.join', player: row(p) }, c.uid);
if (room) p.send(room.startMsg(m.seat)); // reconnect: rebuild the running fight
}
function leave(uid, send) {
const p = players.get(uid);
if (!p || (send && p.send !== send)) return; // an old, already replaced socket
players.delete(uid);
dropChallenges(uid);
const m = inMatch.get(uid), room = m && runner.get(m.id);
if (room) room.disconnect(m.seat);
broadcast({ t: 'lobby.leave', uid });
}
function dropChallenges(uid) {
const out = pending.get(uid);
if (out) { clearTimeout(out.timer); pending.delete(uid); tell(out.to, { t: 'challenge.gone', from: uid }); }
for (const [from, c] of pending) if (c.to === uid) { clearTimeout(c.timer); pending.delete(from); const f = players.get(from); if (f) { setState(f, 'idle'); f.send({ t: 'challenge.gone', to: uid }); } }
}
function challenge(p, to) {
const q = players.get(to);
if (!q || to === p.uid) return p.send({ t: 'error', code: 'NOT_AVAILABLE' });
if (p.state !== 'idle' || q.state !== 'idle') return p.send({ t: 'error', code: 'BUSY' });
const f = economy.fighter(p.uid, p.name);
if (!f.ok) return p.send({ t: 'error', code: 'INVALID_ROBOT', errors: f.errors });
const timer = setTimeout(() => {
if (!pending.has(p.uid)) return;
pending.delete(p.uid); setState(p, 'idle');
p.send({ t: 'challenge.gone', to, reason: 'timeout' }); tell(to, { t: 'challenge.gone', from: p.uid, reason: 'timeout' });
}, CHALLENGE_TTL);
if (timer.unref) timer.unref();
pending.set(p.uid, { to, timer });
setState(p, 'challenging');
q.send({ t: 'challenge.in', from: p.uid, name: p.name, flag: f.flag, fame: f.fame });
}
function cancel(p) {
const c = pending.get(p.uid); if (!c) return;
clearTimeout(c.timer); pending.delete(p.uid); setState(p, 'idle');
tell(c.to, { t: 'challenge.gone', from: p.uid, reason: 'cancelled' });
}
function decline(p, from) {
const c = pending.get(from); if (!c || c.to !== p.uid) return;
clearTimeout(c.timer); pending.delete(from);
const f = players.get(from); if (f) { setState(f, 'idle'); f.send({ t: 'challenge.gone', to: p.uid, reason: 'declined' }); }
}
function accept(p, from) {
const c = pending.get(from), q = players.get(from);
if (!c || c.to !== p.uid || !q) return p.send({ t: 'error', code: 'NOT_AVAILABLE' });
clearTimeout(c.timer); pending.delete(from);
const fa = economy.fighter(q.uid, q.name), fb = economy.fighter(p.uid, p.name);
if (!fa.ok || !fb.ok) {
setState(q, 'idle');
const code = 'INVALID_ROBOT';
if (!fa.ok) q.send({ t: 'error', code, errors: fa.errors }); else p.send({ t: 'error', code: 'OPPONENT_INVALID' });
if (!fb.ok) p.send({ t: 'error', code, errors: fb.errors }); else q.send({ t: 'error', code: 'OPPONENT_INVALID' });
return;
}
startMatch(fa, fb);
}
function startMatch(fa, fb) {
const id = crypto.randomBytes(8).toString('hex');
const seed = crypto.randomInt(1, 1e9);
const seats = seed % 2 ? [fa, fb] : [fb, fa]; // fair: who gets which start position is random
const room = runner.create({
id, seed,
players: seats.map(f => ({ uid: f.uid, name: f.name, build: f.build, paint: f.paint, flag: f.flag })),
send: (seat, msg) => tell(seats[seat].uid, msg),
rttOf: seat => { const p = players.get(seats[seat].uid); return p ? p.rtt : 0; },
onEnd: finish,
});
if (matches) matches.start.run(id, seed, room.arena, seats[0].uid, seats[1].uid, now());
seats.forEach((f, seat) => {
inMatch.set(f.uid, { id, seat });
const pl = players.get(f.uid); if (pl) setState(pl, 'inmatch');
tell(f.uid, room.startMsg(seat));
});
return room;
}
function finish(room) {
const res = room.result;
if (matches) matches.end.run(res.winner, res.reason, now(), room.id);
room.players.forEach((pl, seat) => {
inMatch.delete(pl.uid);
const sm = room.summary(seat);
const won = res.winner === seat;
const r = economy.reward(pl.uid, Object.assign({ won, winner: res.winner === -1 ? -1 : won ? 0 : 1, reason: res.reason }, sm));
tell(pl.uid, { t: 'match.end', matchId: room.id, seat, result: res, summary: sm,
reward: { money: r.money, fame: r.fame, lines: r.lines, ach: r.ach }, save: r.save });
const p = players.get(pl.uid); if (p) setState(p, 'idle');
});
}
function handle(uid, msg) {
const p = players.get(uid); if (!p) return;
switch (msg.t) {
case 'ping': return p.send({ t: 'pong', t0: msg.t0, serverTime: now() });
case 'room': p.room = msg.room === 'all' ? null : msg.room; return setState(p, p.state);
case 'challenge': return challenge(p, msg.to);
case 'challenge.cancel': return cancel(p);
case 'challenge.accept': return accept(p, msg.from);
case 'challenge.decline': return decline(p, msg.from);
case 'input': { const m = inMatch.get(uid), room = m && runner.get(m.id); if (room) room.input(m.seat, msg); return; }
case 'match.leave': { const m = inMatch.get(uid), room = m && runner.get(m.id); if (room) room.forfeit(m.seat); return; }
}
}
// ping of a player, measured by the hub (WebSocket ping/pong)
function setRtt(uid, ms) { const p = players.get(uid); if (p) p.rtt = p.rtt ? p.rtt * 0.7 + ms * 0.3 : ms; }
// the profile changed (robot, flag, fame): show it to everyone
function refresh(uid) { const p = players.get(uid); if (p) setState(p, p.state); }
return { join, leave, handle, refresh, setRtt, startMatch, players, pending, inMatch };
}
module.exports = { createLobby, CHALLENGE_TTL };

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

@@ -0,0 +1,123 @@
/* One live fight, run by the server. Pure: no sockets, no timers - the caller feeds inputs and calls tick()
at 60 Hz (see runner.js). The fight itself is the same RC.Combat the browser uses offline.
const room = new Room({ id, seed, players: [{ uid, name, build, paint }, ...], send(seat, msg), onEnd(room) })
room.input(seat, raw) latest input of that seat (validated + clamped)
room.disconnect(seat) robot idles; after GRACE ticks the AI drives it
room.reconnect(seat) player takes over again
room.tick() one 1/60 s step (countdown first), snapshots every SNAP_EVERY ticks
room.ended / room.result { winner (seat or -1), reason } once over */
'use strict';
const RC = require('../../game/robot.js');
require('../../game/combat.js');
require('../../game/ai.js');
require('../../game/protocol.js');
const DT = 1 / 60;
const COUNTDOWN = Math.round(3.5 * 60); // ticks before the fight starts (matches the client countdown)
const SNAP_EVERY = 3; // 20 snapshots per second
const GRACE = 10 * 60; // ticks a disconnected player keeps his robot before the AI takes over
const HARD_CAP = 60 * 60 * 4; // safety net: no room lives longer than 4 minutes of fight
class Room {
constructor(opt) {
this.id = opt.id;
this.seed = opt.seed || 1;
this.players = opt.players; // [{ uid, name, build, paint, flag }]
this.send = opt.send || (() => {});
this.rttOf = opt.rttOf || (() => 0); // seat -> ping in ms (measured by the WebSocket hub)
this.onEnd = opt.onEnd || (() => {});
const ids = RC.ARENAS.map(a => a.id);
this.arena = opt.arena || ids[this.seed % ids.length];
this.s = RC.Combat.create({
robots: this.players.map(p => RC.stats(p.build)), seed: this.seed,
names: this.players.map(p => p.name), arena: this.arena,
});
this.inputs = [RC.Proto.input(null), RC.Proto.input(null)];
this.acks = [0, 0];
this.away = [0, 0]; // ticks since disconnect (0 = connected)
this.ai = [null, null];
this.tickN = 0;
this.ended = false;
this.result = null;
}
input(seat, raw) {
if (this.ended || (seat !== 0 && seat !== 1)) return;
this.inputs[seat] = RC.Proto.input(raw);
if (raw && Number.isInteger(raw.seq)) this.acks[seat] = raw.seq;
}
disconnect(seat) { if (!this.away[seat]) this.away[seat] = 1; }
// player gives up: his robot is knocked out at once
forfeit(seat) {
const s = this.s, r = s.robots[seat];
if (this.ended || !r || s.result) return;
r.hp = 0; r.dead = true;
s.result = { winner: 1 - seat, reason: 'ko' }; s.endIn = 0;
if (this.tickN <= COUNTDOWN) this.tickN = COUNTDOWN; // end now even during the countdown
}
reconnect(seat) { this.away[seat] = 0; this.ai[seat] = null; }
connected(seat) { return !this.away[seat]; }
// what a (re)joining player needs to build the fight locally
startMsg(seat) {
return {
t: 'match.start', matchId: this.id, seat, seed: this.seed, arena: this.arena,
countdown: Math.max(0, (COUNTDOWN - this.tickN) * DT),
robots: this.players.map(p => ({ uid: p.uid, name: p.name, build: p.build, paint: p.paint, flag: p.flag })),
};
}
inputFor(seat) {
if (!this.away[seat]) return this.inputs[seat];
if (this.away[seat] < GRACE) return RC.Proto.input(null); // grace period: robot stands still
if (!this.ai[seat]) this.ai[seat] = RC.AI.create({ style: 'brawler', skill: 0.5, seed: this.seed + seat });
return this.ai[seat].think(this.s, this.s.robots[seat], this.s.robots[1 - seat], DT);
}
tick() {
if (this.ended) return;
this.tickN++;
for (const k of [0, 1]) if (this.away[k]) this.away[k]++;
if (this.tickN <= COUNTDOWN) return;
const s = this.s;
const t0 = process.hrtime.bigint();
RC.Combat.step(s, DT, [this.inputFor(0), this.inputFor(1)]);
const ms = Number(process.hrtime.bigint() - t0) / 1e6;
this.tickMs = this.tickMs ? this.tickMs * 0.9 + ms * 0.1 : ms; // smoothed cost of one step (server load)
if (!this.evBuf) this.evBuf = [];
if (s.events.length) this.evBuf.push(...s.events);
s.events.length = 0;
const over = s.result && s.endIn <= 0;
if (over || this.tickN % SNAP_EVERY === 0) this.publish();
if (over || this.tickN > COUNTDOWN + HARD_CAP) this.finish(s.result || { winner: -1, reason: 'time' });
}
publish() {
const s = this.s;
s.events = this.evBuf.slice(-48); // events since the last snapshot
const snap = RC.Proto.packSnap(s, this.tickN, this.acks);
s.events = []; this.evBuf.length = 0;
const away = [!!this.away[0], !!this.away[1]];
// network diagnostics for the F3 overlay: each player's ping to the server (measured here) + server step cost
const rtt = [0, 1].map(k => Math.round(this.rttOf(k) || 0));
const tickMs = Math.round((this.tickMs || 0) * 100) / 100;
for (const seat of [0, 1]) this.send(seat, Object.assign({ t: 'snap', away, rtt, tickMs, sent: Date.now() }, snap));
}
finish(result) {
if (this.ended) return;
this.ended = true;
this.result = { winner: result.winner, reason: result.reason };
this.onEnd(this);
}
// per-seat fight summary for rewards / the result screen
summary(seat) {
const r = this.s.robots[seat];
return { hp: r.hp, maxHp: r.maxHp, dealt: r.dealt, taken: r.taken, value: r.st.value || 0,
lost: Object.keys(r.lost || {}).filter(k => r.lost[k]) };
}
}
module.exports = { Room, DT, COUNTDOWN, SNAP_EVERY, GRACE };

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

@@ -0,0 +1,44 @@
/* Drives all live rooms at a fixed 60 Hz. One timer for the whole server; catches up after a hitch
(max 10 ticks per wake-up), logs when a tick takes too long. */
'use strict';
const { Room, DT } = require('./room');
function createRunner(opt = {}) {
const rooms = new Map();
const STEP = DT * 1000;
let next = 0, timer = null, slowLogged = 0;
function loop() {
const now = performance.now();
if (!next) next = now;
let n = 0;
while (now >= next && n < 10) {
const t0 = performance.now();
for (const room of rooms.values()) {
// one broken fight must never stop the others (or the server): end it as a draw and log it
try { room.tick(); } catch (e) { console.error('[match] room', room.id, 'crashed', e); try { room.finish({ winner: -1, reason: 'time' }); } catch (e2) { rooms.delete(room.id); } }
}
const ms = performance.now() - t0;
if (ms > 8 && Date.now() - slowLogged > 10000) { slowLogged = Date.now(); console.warn(`[match] slow tick ${ms.toFixed(1)} ms for ${rooms.size} rooms`); }
next += STEP; n++;
}
if (now - next > 250) next = now; // fell far behind (sleeping laptop, debugger): don't replay it
timer = setTimeout(loop, Math.max(0, next - performance.now()));
}
return {
rooms,
create(o) {
const room = new Room(Object.assign({}, o, {
onEnd: r => { rooms.delete(r.id); if (o.onEnd) o.onEnd(r); },
}));
rooms.set(room.id, room);
if (!timer && opt.autoStart !== false) loop();
return room;
},
get: id => rooms.get(id),
stop() { clearTimeout(timer); timer = null; next = 0; },
};
}
module.exports = { createRunner };

1383
server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

23
server/package.json Normal file
View File

@@ -0,0 +1,23 @@
{
"name": "robotclash-server",
"version": "0.1.0",
"private": true,
"description": "Robot Clash backend - auth, saves, ranks, lobby, live PvP, server-authoritative economy.",
"main": "app.js",
"engines": {
"node": ">=20.6"
},
"scripts": {
"start": "node app.js",
"dev": "node --env-file=.env --watch app.js",
"test": "node --test \"test/**/*.test.js\"",
"db:reset": "node scripts/reset-db.js"
},
"dependencies": {
"bcryptjs": "2.4.3",
"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

@@ -0,0 +1,33 @@
/* Reset the database to a clean state: backup copy, fresh schema, seed accounts.
Test system only (see CLAUDE.md). Stop the server first (systemctl stop robotclash), then:
npm run db:reset (in server/)
DB_FILE from the environment, default server/data.sqlite. */
'use strict';
const fs = require('fs');
const path = require('path');
// Dev phase: fixed test accounts (plan T-1: move to .env before there is ever a production system).
const DEV_SEED_USERS = [
{ name: 'michi', pass: 'Michi2000!', role: 'admin' },
{ name: 'benni', pass: 'Benni2000!', role: 'admin' },
];
const file = process.env.DB_FILE || path.join(__dirname, '..', 'data.sqlite');
if (file !== ':memory:' && fs.existsSync(file)) {
const bak = `${file}.bak-${new Date().toISOString().replace(/[:.]/g, '-')}`;
fs.copyFileSync(file, bak);
for (const ext of ['', '-wal', '-shm']) if (fs.existsSync(file + ext)) fs.rmSync(file + ext);
console.log('backup:', bak);
}
process.env.DB_FILE = file;
process.env.JWT_SECRET = process.env.JWT_SECRET || 'reset-script-signs-nothing';
const { createUser } = require('../auth'); // opens + migrates the fresh database
const economy = require('../economy');
for (const u of DEV_SEED_USERS) {
const row = createUser({ name: u.name, pass: u.pass, role: u.role });
economy.load(row.uid); // creates the starter online save
console.log(`seeded ${u.name} (${u.role})`);
}
console.log('database reset:', file);

40
server/test/bot.test.js Normal file
View File

@@ -0,0 +1,40 @@
'use strict';
const { test, before, after } = require('node:test');
const assert = require('node:assert/strict');
const { startServer, fastForward } = require('./helpers');
const { startBot, PATTERNS } = require('../../tools/bot');
const RC = globalThis.RC;
let S;
before(async () => { S = await startServer(); });
after(() => S.close());
test('every bot pattern gives valid inputs', () => {
for (const [name, f] of Object.entries(PATTERNS)) for (const t of [0, 1.3, 7.9]) {
const i = RC.Proto.input(f(t));
assert.ok(RC.Proto.check(Object.assign({ t: 'input', seq: 1 }, i)).ok, name);
}
});
test('the bot accepts a challenge, drives its pattern, and deletes itself on stop', async () => {
const bot = await startBot({ url: S.base, pattern: 'circle', quiet: true });
const me = await S.account();
const c = await S.client(me.idToken);
await c.next('lobby.join', m => m.player.uid === bot.uid).catch(() => {});
c.send({ t: 'challenge', to: bot.uid });
const st = await c.next('match.start', () => true, 5000);
assert.equal(st.robots[1 - st.seat].uid, bot.uid);
// let the real 60 Hz runner play a bit after the countdown: the bot's robot must move
const room = S.runner.get(st.matchId);
const botSeat = 1 - st.seat, x0 = room.s.robots[botSeat].x, a0 = room.s.robots[botSeat].a;
await new Promise(r => setTimeout(r, (st.countdown + 1.2) * 1000));
const moved = Math.abs(room.s.robots[botSeat].x - x0) + Math.abs(room.s.robots[botSeat].a - a0);
assert.ok(moved > 0.1, 'bot robot moves (circle pattern)');
fastForward(S.runner);
await c.next('match.end', () => true, 5000);
await bot.stop();
assert.ok(!(await S.json('GET', '/api/ranks')).body.some(r => r.uid === bot.uid), 'bot account is gone');
c.close();
});

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

@@ -0,0 +1,67 @@
'use strict';
const { test, before, after } = require('node:test');
const assert = require('node:assert/strict');
const { startServer } = require('./helpers');
let S;
before(async () => { S = await startServer(); });
after(() => S.close());
test('GET /healthz reports ok + version', async () => {
const r = await S.json('GET', '/healthz');
assert.equal(r.status, 200);
assert.equal(r.body.ok, true);
assert.equal(r.body.version, require('../package.json').version);
assert.equal(typeof r.body.uptime, 'number');
});
test('register by name -> login by name (any case) -> refresh rotates the token', async () => {
const reg = await S.json('POST', '/api/auth/register', { name: 'Alice', pass: 'secret123' });
assert.equal(reg.status, 200);
assert.ok(reg.body.idToken && reg.body.refreshToken && reg.body.uid);
const login = await S.json('POST', '/api/auth/login', { login: ' ALICE ', pass: 'secret123' });
assert.equal(login.status, 200);
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);
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 });
assert.equal(r1.status, 200);
const r2 = await S.json('POST', '/api/auth/refresh', { refreshToken: login.body.refreshToken });
assert.equal(r2.status, 401, 'an already used refresh token is rejected');
});
test('register: optional e-mail works as login too; duplicates and weak passwords are refused', async () => {
const r = await S.json('POST', '/api/auth/register', { name: 'Bob', pass: 'secret123', email: 'Bob@Test.dev' });
assert.equal(r.status, 200);
assert.equal((await S.json('POST', '/api/auth/login', { login: 'bob@test.dev', pass: 'secret123' })).status, 200);
assert.equal((await S.json('POST', '/api/auth/register', { name: 'bob', pass: 'secret123' })).body.error, 'NAME_EXISTS');
assert.equal((await S.json('POST', '/api/auth/register', { name: 'Carl', pass: 'short' })).body.error, 'WEAK_PASSWORD');
assert.equal((await S.json('POST', '/api/auth/register', { name: 'x', pass: 'secret123' })).body.error, 'BAD_NAME');
});
test('DELETE /api/me removes the account, its save and its tokens', async () => {
const r = await S.json('POST', '/api/auth/register', { name: 'Leaver', pass: 'secret123' });
await S.json('GET', '/api/online', undefined, r.body.idToken);
assert.equal((await S.json('DELETE', '/api/me', undefined, r.body.idToken)).body.ok, true);
assert.equal((await S.json('POST', '/api/auth/login', { login: 'leaver', pass: 'secret123' })).status, 400);
assert.equal((await S.json('POST', '/api/auth/refresh', { refreshToken: r.body.refreshToken })).status, 401);
});
test('wrong password is rejected', async () => {
const r = await S.json('POST', '/api/auth/login', { login: 'alice', pass: 'nope-nope' });
assert.equal(r.status, 400);
assert.equal(r.body.error, 'INVALID_LOGIN');
});
test('guest accounts get a token and an online save', async () => {
const g = await S.json('POST', '/api/auth/guest', { name: 'Gast' });
assert.equal(g.status, 200);
assert.equal(g.body.guest, true);
const s = await S.json('GET', '/api/online', undefined, g.body.idToken);
assert.equal(s.body.money, 800);
});

76
server/test/helpers.js Normal file
View File

@@ -0,0 +1,76 @@
/* Test helpers: start the real server on a random port with an in-memory database; WebSocket test clients. */
'use strict';
process.env.NODE_ENV = 'test';
process.env.DB_FILE = ':memory:';
delete process.env.JWT_SECRET;
const WebSocket = require('ws');
const srvMod = require('../app');
const RC = globalThis.RC;
let n = 0;
async function startServer() {
const srv = await srvMod.listen(0);
const port = srv.address().port;
const base = 'http://127.0.0.1:' + port;
const json = async (method, path, body, token) => {
const res = await fetch(base + path, {
method,
headers: Object.assign({ 'Content-Type': 'application/json' }, token ? { Authorization: 'Bearer ' + token } : {}),
body: body === undefined ? undefined : JSON.stringify(body),
});
return { status: res.status, body: await res.json().catch(() => null) };
};
// 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 };
}
// run every live room to its end without waiting for real time
function fastForward(runner, maxTicks = 60 * 300) {
runner.stop();
for (let i = 0; i < maxTicks && runner.rooms.size; i++) for (const r of [...runner.rooms.values()]) r.tick();
}
module.exports = { startServer, fastForward };

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

@@ -0,0 +1,177 @@
'use strict';
const { test, before, after } = require('node:test');
const assert = require('node:assert/strict');
const { startServer, fastForward } = require('./helpers');
const RC = globalThis.RC;
let S;
before(async () => { S = await startServer(); });
after(() => S.close());
test('socket must authenticate with hello first', async () => {
const c = await S.client(null, { noHello: true });
c.send({ t: 'room', room: 'DE' });
assert.equal((await c.closed).code, 4001);
const bad = await S.client('not-a-token', { expectFail: true });
assert.equal((await bad.next('error')).code, 'UNAUTH');
assert.equal((await bad.closed).code, 4003);
});
test('a token of a deleted account is refused - and the server keeps running', async () => {
const a = await S.account();
await S.json('DELETE', '/api/me', undefined, a.idToken);
const c = await S.client(a.idToken, { expectFail: true });
assert.equal((await c.next('error')).code, 'UNAUTH');
assert.equal((await S.json('GET', '/api/online', undefined, a.idToken)).status, 401);
assert.equal((await S.json('GET', '/healthz')).status, 200);
});
test('a failing message handler answers with an error instead of crashing', async () => {
const a = await S.account();
const c = await S.client(a.idToken);
const orig = S.lobby.handle;
S.lobby.handle = () => { throw new Error('boom'); };
try {
c.send({ t: 'room', room: 'DE' });
assert.equal((await c.next('error')).code, 'SERVER_ERROR');
} finally { S.lobby.handle = orig; }
assert.equal((await S.json('GET', '/healthz')).status, 200);
c.close();
});
test('old protocol version is told to reload', async () => {
const a = await S.account();
const c = await S.client(a.idToken, { v: 0, expectFail: true });
assert.equal((await c.next('error')).code, 'OUTDATED');
assert.equal((await c.closed).code, 4002);
});
test('ping is answered with pong (for the latency overlay)', async () => {
const a = await S.account();
const c = await S.client(a.idToken);
c.send({ t: 'ping', t0: 42 });
const p = await c.next('pong');
assert.equal(p.t0, 42);
assert.equal(typeof p.serverTime, 'number');
c.close();
});
test('invalid messages get an error, the socket stays open', async () => {
const a = await S.account();
const c = await S.client(a.idToken);
c.send({ t: 'input', seq: 1, throttle: 'fast' });
assert.match((await c.next('error')).code, /BAD_FIELD/);
c.ws.send('{not json');
assert.equal((await c.next('error')).code, 'BAD_JSON');
c.close();
});
test('presence: join and leave are pushed to the others', async () => {
const a = await S.account('Anna'), b = await S.account('Bert');
const ca = await S.client(a.idToken);
await ca.next('lobby');
const cb = await S.client(b.idToken);
const list = await cb.next('lobby');
assert.ok(list.players.some(p => p.uid === a.uid && p.state === 'idle'));
assert.equal((await ca.next('lobby.join', m => m.player.uid === b.uid)).player.name, 'Bert');
cb.close();
assert.equal((await ca.next('lobby.leave', m => m.uid === b.uid)).uid, b.uid);
ca.close();
});
test('challenge -> decline / cancel', async () => {
const a = await S.account(), b = await S.account();
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
ca.send({ t: 'challenge', to: b.uid });
assert.equal((await cb.next('challenge.in')).from, a.uid);
cb.send({ t: 'challenge.decline', from: a.uid });
assert.equal((await ca.next('challenge.gone')).reason, 'declined');
ca.send({ t: 'challenge', to: b.uid });
await cb.next('challenge.in');
ca.send({ t: 'challenge.cancel' });
assert.equal((await cb.next('challenge.gone')).reason, 'cancelled');
ca.send({ t: 'challenge', to: a.uid });
assert.equal((await ca.next('error')).code, 'NOT_AVAILABLE', 'cannot challenge yourself');
ca.close(); cb.close();
});
test('full live match over WebSocket: both get start, snapshots, and mirrored results with rewards', async () => {
const a = await S.account(), b = await S.account();
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
ca.send({ t: 'challenge', to: b.uid });
await cb.next('challenge.in');
cb.send({ t: 'challenge.accept', from: a.uid });
const [sa, sb] = await Promise.all([ca.next('match.start'), cb.next('match.start')]);
assert.equal(sa.matchId, sb.matchId);
assert.deepEqual([sa.seat, sb.seat].sort(), [0, 1]);
assert.equal(sa.seed, sb.seed);
assert.equal(sa.arena, sb.arena);
assert.equal(sa.robots[sa.seat].uid, a.uid, 'my seat holds my robot');
// inputs flow in, then the server plays the rest at full speed
ca.send({ t: 'input', seq: 1, throttle: 1, turn: 0, fire: true, fire2: false, fire3: false });
await new Promise(r => setTimeout(r, 50));
fastForward(S.runner);
const [ea, eb] = await Promise.all([ca.next('match.end'), cb.next('match.end')]);
assert.deepEqual(ea.result, eb.result, 'same seat-based result for both');
const la = RC.Proto.localResult(ea.seat, ea.result).winner, lb = RC.Proto.localResult(eb.seat, eb.result).winner;
if (ea.result.winner === -1) assert.ok(la === -1 && lb === -1);
else assert.ok((la === 0) !== (lb === 0), 'exactly one player won');
assert.equal(ea.save.games, 1);
assert.ok(Array.isArray(ea.reward.ach), 'achievements decided on the server');
const winner = la === 0 ? ea : lb === 0 ? eb : null;
if (winner) assert.ok(winner.reward.ach.some(x => x.id === 'first_win'), 'first win pays out');
assert.equal(eb.save.games, 1);
const snap = ca.inbox.find(m => m.t === 'snap');
assert.ok(snap, 'snapshots arrived before the end');
assert.ok(Array.isArray(snap.rtt) && snap.rtt.length === 2, 'snapshot carries both pings');
assert.equal(typeof snap.tickMs, 'number', 'snapshot carries the server step cost');
assert.equal(typeof snap.sent, 'number');
// rewards were booked on the server
const sA = await S.json('GET', '/api/online', undefined, a.idToken);
assert.equal(sA.body.money, ea.save.money);
ca.close(); cb.close();
});
test('forfeit ends the match at once; disconnect + reconnect gets the running match back', async () => {
const a = await S.account(), b = await S.account();
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
ca.send({ t: 'challenge', to: b.uid });
await cb.next('challenge.in');
cb.send({ t: 'challenge.accept', from: a.uid });
const st = await ca.next('match.start');
await cb.next('match.start');
S.runner.stop();
// b drops and comes back: gets match.start again for the same match and seat
cb.close(); await cb.closed;
await ca.next('lobby.leave', m => m.uid === b.uid);
const room = S.runner.get(st.matchId);
assert.ok(room && !room.connected(1 - st.seat), 'room marks the seat as away');
const cb2 = await S.client(b.idToken);
const again = await cb2.next('match.start');
assert.equal(again.matchId, st.matchId);
assert.equal(again.seat, 1 - st.seat);
assert.ok(room.connected(1 - st.seat));
ca.send({ t: 'match.leave' });
await new Promise(r => setTimeout(r, 30));
fastForward(S.runner);
const ea = await ca.next('match.end'), eb = await cb2.next('match.end');
assert.equal(RC.Proto.localResult(ea.seat, ea.result).winner, 1, 'the one who left lost');
assert.equal(RC.Proto.localResult(eb.seat, eb.result).winner, 0);
ca.close(); cb2.close();
});
test('an invalid robot cannot challenge', async () => {
const a = await S.account(), b = await S.account();
// strip the battery via the economy: equip refuses required slots, so break the save directly
const econ = require('../economy');
const s = econ.load(a.uid); s.robots[0].build.battery = null; require('../db').OnlineSaves.put(a.uid, s);
const ca = await S.client(a.idToken), cb = await S.client(b.idToken);
ca.send({ t: 'challenge', to: b.uid });
const e = await ca.next('error');
assert.equal(e.code, 'INVALID_ROBOT');
ca.close(); cb.close();
});

80
server/test/room.test.js Normal file
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);
});

Some files were not shown because too many files have changed in this diff Show More