Compare commits

..

12 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
42 changed files with 1968 additions and 768 deletions

2
.gitignore vendored
View File

@@ -16,3 +16,5 @@ server/node_modules/
server/.env
server/data.sqlite*
server/*.sqlite*
test-results/
playwright-report/

View File

@@ -129,7 +129,13 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
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` lokale Konten für die Offline-Kampagne (Name + Passwort-Hash, je Konto eigener Spielstand)
· `game/game.js` Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Registrieren/Gast → Shop → Liga/VS → Kampf → Ergebnis, Einstellungen.
· `game/game.js` Kern + Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Gast → Shop → Liga/VS → Kampf → Ergebnis.
Aufgeteilt (klassische Skripte, kein Build): `game/sfx.js` Sound · `game/pages.js` Menüseiten (Einstellungen,
Hilfe, Tutorial, Land, Erfolge, Missionen, Rechtliches, Rangliste) · `game/online.js` Online (act(), Abgleich mit
dem Server, Login-Karte, Lobby, Online-Kampfende) · `game/workshop.js` Waffen-Editor, Lack, Hangar. Jedes Modul
ist eine Fabrik `RC.Game<Teil>(G)`; `G` (Ende von game.js) liefert per Getter den **aktuellen** Zustand (`G.save`,
`G.mode`, `G.F` …) und per Setter das Zurückschreiben. Neue gemeinsame Variable → in `G` eintragen. Aufrufe aus
game.js laufen über kurze Weiterleitungen (`function x(...a) { return GM.<teil>.x(...a); }`).
- `game/vendor/three.min.js` three.js r149 (MIT, letzte Version mit klassischem Build – nicht auf ES-Module updaten).
- 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`
@@ -137,6 +143,12 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
`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,
@@ -163,7 +175,8 @@ ist die Aufgabenliste – Tasks der Reihe nach, Task-ID im Commit, erledigte Tas
REST-Endpunkte und WS-Nachrichten aus `game/protocol.js`. Protokolländerung = `PROTOCOL_VERSION` erhöhen.
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.
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.

View File

@@ -11,7 +11,8 @@ Stand der Analyse: 2026-11-19 (Commit `347701d`).
## Umsetzungsstand (2026-11-19)
**Erledigt:** Phase 0, Phase 1, Phase 2 (außer P2-6), aus Phase 3: P3-1b, P3-2, P3-3 (+ Teile von P3-1), aus Phase 4:
Smoke-Test (`npm run smoke -- <url>`, Vorstufe von P4-1). **Live** auf `https://roboclash.michael-media.de` (Dev).
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`).
@@ -26,8 +27,8 @@ Shop-Kauf landet in der Server-DB, Kampagne offline über `file://` (headless +
- Admin-Seite läuft jetzt unter `/admin/` auf dem Server; `admin/cleanup.js`/`setcoins.js` (Firebase) gelöscht.
**Offen / nächste Schritte:** P2-6 (Online-Turnier), P3-1 Rest (SSH-Nutzer `deploy`, Passwort-Login aus), P3-5
(Logs/Monitoring), P3-6 (Gitea Actions + act_runner), P4-1 voller Bot-Client, P4-2 Playwright, P4-3 Lasttest,
P4-4 Vorhersage (erst nach Spieltest), P4-5 `game.js` aufteilen (~2000 Zeilen), `tests/sim.test.js:442` (halber Test).
(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.
@@ -210,6 +211,15 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
- [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),
@@ -286,14 +296,14 @@ eine zweite systemd-Unit + ein Caddy-Block ist – kein Umbau.
### Phase 4 – Absicherung und Feinschliff
- [ ] **P4-1 Bot-Client** `tools/bot.js`: verbindet sich per WS, nimmt Challenges an, spielt mit `RC.AI`.
- [x] **P4-1 Bot-Client** `tools/bot.js`: verbindet sich per WS, nimmt Challenges an, spielt mit `RC.AI`.
Nutzbar für Smoke-Tests und als Gegner auf dem Dev-Server. *AK:* `node tools/bot.js --url … --count 20` spielt 10 Matches parallel.
- [ ] **P4-2 Browser-E2E** mit Playwright: zwei Browser-Kontexte, Gast-Login, Lobby, Challenge, Kampf mit `&auto`,
- [x] **P4-2 Browser-E2E** mit Playwright: zwei Browser-Kontexte, Gast-Login, Lobby, Challenge, Kampf mit `&auto`,
beide sehen spiegelbildliches Ergebnis. Läuft in CI gegen einen lokal gestarteten Server.
- [ ] **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.
- [ ] **P4-5 `game.js` aufteilen** (> 1500 Zeilen, Regel aus CLAUDE.md): `online-ui.js` (Lobby, Login),
- [x] **P4-5 `game.js` aufteilen** (> 1500 Zeilen, Regel aus CLAUDE.md): `online-ui.js` (Lobby, Login),
`fight.js` (Kampfablauf), `results.js`. Ohne Verhaltensänderung, abgesichert durch `&uicheck` + E2E.
---

View File

@@ -9,7 +9,7 @@ const gameGlobals = { RC: 'writable', Kit: 'writable', THREE: 'readonly', KIT_AS
module.exports = [
{
ignores: ['node_modules/**', 'server/node_modules/**', 'release/**', 'game/vendor/**', 'game/kit/**',
'launcher/**', 'sprite-generator/**', 'tools/shots/**', 'admin/**'],
'launcher/**', 'sprite-generator/**', 'tools/shots/**', 'admin/**', 'test-results/**', 'playwright-report/**'],
},
js.configs.recommended,
{
@@ -23,7 +23,7 @@ module.exports = [
languageOptions: { sourceType: 'script', globals: { ...globals.browser, ...gameGlobals } },
},
{
files: ['server/**/*.js', 'tests/**/*.js', 'tools/**/*.js', 'eslint.config.js'],
files: ['server/**/*.js', 'tests/**/*.js', 'tools/**/*.js', 'eslint.config.js', 'playwright.config.js'],
languageOptions: { sourceType: 'commonjs', globals: { ...globals.node } },
},
{

View File

@@ -51,6 +51,7 @@
// first start (no saved choice yet): default to English, not the browser language
if (Kit.store(ID).get('lang', null) === null) L.set('en');
const t = L.t;
const GM = {}; // feature modules, created at the end (see 'feature modules')
const store = Kit.store(ID);
// steer: 'simple' (keys = screen direction) | 'tank' · diff: 'easy' | 'normal' | 'hard' · autofire: weapon fires by itself in reach
const settings = Object.assign({ gfx: 'medium', intro: true, steer: 'tank', autofire: true, cam: 'fpv', arena: 'random', quiet: false, comfort: true }, store.get('settings', {}));
@@ -98,6 +99,7 @@
if (Kit.store(ID).get('music', null) === null) audio.setVolume(0.1, 0.35);
const DEV = new URLSearchParams(location.search);
if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop
const netProbe = DEV.has('netprobe') ? (window.__probe = []) : null; // dev: records opponent robot pos for the lag test
const net = RC.Net(NET_CFG);
const rank = RC.Ranking(net); // online ranking, computed by the server
const cloud = RC.CloudSave(net); // campaign copy for registered accounts (online saves live on the server)
@@ -106,66 +108,25 @@
let isDev = false;
function refreshDev() { isDev = !fbUser() ? true : !!fbUser().admin; }
// ---- 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(save, a);
if (!r.ok) return r;
if (gameMode === 'online' && net.enabled && net.uid) {
actQueue = actQueue.then(() => net.api('POST', '/api/online/action', a)).then(res => {
if (!res || !res.save) return;
if (!res.ok || econDiffers(res.save)) { adoptEconomy(res.save); afterEconomy(); }
}, () => {});
}
return r;
}
const econKey = s => JSON.stringify([s.money, s.fame, s.owned, s.active, (s.robots || []).map(r => r.build)]);
const econDiffers = srv => econKey(srv) !== econKey(save);
// keepLooks: robot names/paint are client-owned - keep ours (they may not be uploaded yet)
function adoptEconomy(srv, keepLooks = true) {
const looks = keepLooks && save.robots ? save.robots.map(r => ({ name: r.name, paint: r.paint })) : [];
for (const k of RC.Eco.ECONOMY) if (srv[k] !== undefined) save[k] = srv[k];
if (keepLooks && looks.length === save.robots.length) save.robots.forEach((r, i) => { r.name = looks[i].name; r.paint = looks[i].paint; });
RC.Eco.mirror(save);
slot.save(save);
}
function afterEconomy() {
hud();
if (mode === 'garage') { shop.render(); view.showGarage(save.build, paintObj()); if (editorOpen) renderWeaponEditor(); }
}
// cosmetics (names, paint, flag, ...) are client-owned: debounced upload, the server keeps only those fields
let pushTimer = null;
const cosmetics = () => {
const c = {};
for (const k of RC.Eco.COSMETIC) if (save[k] !== undefined) c[k] = save[k];
c.robots = save.robots.map(r => ({ name: r.name, paint: r.paint }));
return c;
};
function onlinePush() { clearTimeout(pushTimer); pushTimer = setTimeout(onlineFlush, 1500); }
function onlineFlush() {
clearTimeout(pushTimer);
if (gameMode === 'online' && save && net.uid) net.api('PUT', '/api/online/save', cosmetics());
}
// after login / page load: economy from the server; cosmetics from whichever copy is newer
function onlinePull() {
if (gameMode !== 'online' || !net.uid) return;
const uid = net.uid;
net.api('GET', '/api/online').then(srv => {
if (!srv || !save || gameMode !== 'online' || net.uid !== uid) return;
const serverNewer = (+srv.ts || 0) > (+save.ts || 0);
if (serverNewer) { for (const k of RC.Eco.COSMETIC) if (srv[k] !== undefined) save[k] = srv[k]; }
adoptEconomy(srv, !serverNewer);
repairSave();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (!serverNewer) onlinePush();
afterEconomy();
});
}
// ---------------------------------------------------------------- online (game/online.js)
function act(...a) { return GM.online.act(...a); }
function endOnlineFight(...a) { return GM.online.endOnlineFight(...a); }
function onlineFightLost(...a) { return GM.online.onlineFightLost(...a); }
function onlineFlush(...a) { return GM.online.onlineFlush(...a); }
function onlinePull(...a) { return GM.online.onlinePull(...a); }
function onlinePush(...a) { return GM.online.onlinePush(...a); }
function renderLobby(...a) { return GM.online.renderLobby(...a); }
function showLobby(...a) { return GM.online.showLobby(...a); }
function showOnlineLogin(...a) { return GM.online.showOnlineLogin(...a); }
function startOnline(...a) { return GM.online.startOnline(...a); }
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`;
const lobby = net.enabled ? RC.Lobby({ net }) : null;
// F3 (or ?net): network overlay - ping graph + where lag comes from (netstats.js / netoverlay.js)
const netStats = RC.NetStats();
const netOverlay = net.enabled ? RC.NetOverlay({ stats: netStats, net, t, mount: $('stage') }) : null;
if (netOverlay && DEV.has('net')) netOverlay.toggle(true);
const fx = Kit.fx();
const input = Kit.input({
@@ -182,57 +143,11 @@
},
});
// ---------------------------------------------------------------- sound (ComfyGen clips + synth fallback)
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);
}
},
};
// ---------------------------------------------------------------- sound (game/sfx.js)
const SFX = RC.GameSfx(audio, settings);
// rate limit for repeating inputs (gamepad start button)
const lastT = {};
const every = (k, ms) => { const n = performance.now(); if (lastT[k] && n - lastT[k] < ms) return false; lastT[k] = n; return true; };
// ---------------------------------------------------------------- view
const cv = $('cv');
@@ -309,146 +224,13 @@
});
addEventListener('beforeunload', () => { try { cloudFlush(); } catch (e) { /* closing anyway */ } });
// ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ----
function refreshEditorRobot() { view.showGarage(save.build, paintObj()); view.freeze(true); view.setEditWeapon(editSel); }
function reDrawEditor() { persist(); hud(); refreshEditorRobot(); shop.render(); } // after a change: 3D + tabs + meters + editor
// ---------------------------------------------------------------- workshop (game/workshop.js)
function paintLeave(...a) { return GM.workshop.paintLeave(...a); }
function paintTab(...a) { return GM.workshop.paintTab(...a); }
function refreshEditorRobot(...a) { return GM.workshop.refreshEditorRobot(...a); }
function renderHangar(...a) { return GM.workshop.renderHangar(...a); }
function renderWeaponEditor(...a) { return GM.workshop.renderWeaponEditor(...a); }
// 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 = save.build.weapons || [];
const idx = weps.findIndex(w => w.id === id);
if (idx >= 0) { editSel = idx; refreshEditorRobot(); }
else {
const pv = Object.assign({}, save.build, { weapons: weps.concat([{ id, side: 'front', up: 0 }]) });
view.showGarage(pv, paintObj()); view.freeze(true); view.setEditWeapon(weps.length);
}
}
function renderWeaponEditor() {
const cards = $('cards'), wp = $('wplace'); if (!save || !cards) return;
const b = save.build, weps = b.weapons || [];
editSel = Math.min(editSel, Math.max(0, weps.length - 1));
const cat = RC.partsFor('weapon');
const canAdd = weps.length < RC.MAX_WEAPONS;
if (!wPrev || !RC.PARTS[wPrev]) wPrev = (weps[editSel] && weps[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 ${save.money < p.cost ? 'no' : ''}">🪙 ${Kit.fmt(p.cost)}</div>`;
return `<div class="item ${p.id === 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 = () => { wPrev = x.dataset.prev; SFX.click(); previewWeapon(wPrev); renderWeaponEditor(); });
// detail panel: previewed weapon + Montieren / Entfernen (like the other slots)
const dp = $('detail'), pv = RC.PARTS[wPrev];
if (dp && pv) {
const mounted = weps.filter(w => w.id === wPrev).length, poor = save.money < pv.cost;
let act = `<button class="primary" data-wact="add" ${(!canAdd || poor) ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(pv.cost) })}</button>`;
if (mounted) act += `<button data-wact="rem">${t('sell', { n: Kit.fmt(RC.Eco.sellValue(wPrev)) })}</button>`;
if (!canAdd) act += `<span class="muted">${t('ed_max', { n: RC.MAX_WEAPONS })}</span>`;
dp.innerHTML = `${RC.pic('part_' + wPrev, GLYPH_SLOT.weapon)}
<div><div class="nm">${pv.name}${mounted ? ` <span class="badge own">×${mounted}</span>` : ''}</div>
<div class="ds">${t('pd_' + 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(wPrev);
else { const i = weps.map(w => w.id).lastIndexOf(wPrev); if (i >= 0) removeWeapon(i); }
});
}
// left (#wplace): placement of the active mounted weapon + shape (no sell list)
if (wp) {
const sel = weps[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: 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: 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[editSel] && weps[editSel].id === wPrev) view.setEditWeapon(editSel);
}
function addWeapon(id) {
if (!act({ type: 'weaponAdd', part: id }).ok) { SFX.deny(); return; }
editSel = save.build.weapons.length - 1; wPrev = id; view.setEditWeapon(editSel);
SFX.buy(); reDrawEditor();
}
function removeWeapon(i) {
if (!act({ type: 'weaponRemove', index: i }).ok) { SFX.deny(); return; }
if (editSel >= save.build.weapons.length) editSel = Math.max(0, save.build.weapons.length - 1);
view.setEditWeapon(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();
save.paint.decal = art ? layer.toDataURL('image/png') : null; save.paint.drawn = art;
painter.close(); persist();
const hdr = $('paintHdr'); if (hdr) hdr.remove();
}
function renderPaintHeader(hdr) {
const slots = save.paintSlots || [];
hdr.innerHTML =
`<div class="pslots">${slots.map((s, i) => `<div class="pslot ${i === 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) && !(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 ${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; } save.paint[key] = +sw.dataset.c; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
}
$('paintSchemes').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:${phex(b2)}"></i><i style="background:${phex(a2)}"></i></span>`; }).join('');
$('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { save.paint.body = +sw.dataset.b; save.paint.accent = +sw.dataset.a; SFX.click(); persist(); view.showGarage(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 = save.paintSlots[i]; if (!s) return;
save.paintSlot = i;
save.paint.body = s.body; save.paint.accent = s.accent; save.paint.decal = s.decal || null; save.paint.drawn = !!s.drawn;
SFX.click(); persist();
RC.layerFromData(layer, save.paint.decal, () => { view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); });
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
}
function savePaintSlot(i) {
const art = painter.hasArt();
save.paintSlots[i] = { body: save.paint.body, accent: save.paint.accent, decal: art ? layer.toDataURL('image/png') : (save.paint.decal || null), drawn: art || !!save.paint.drawn };
save.paintSlot = i; SFX.buy(); persist();
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
}
// ---------------------------------------------------------------- state
let mode = 'intro'; // intro | title | account | garage | league | fight | pause | result
@@ -636,151 +418,8 @@
});
}
// ---------------------------------------------------------------- online lobby
// The server owns presence, challenges and fights (server/lobby.js). This draws its state and forwards clicks.
let onlineReady = false, lobbyRows = [], lobbyRoom = null; // lobbyRoom = country code or 'all' (which room I view)
let joinedRoom = null; // the country room I am present in (others see me there, with MY flag); default = my flag
const myRoom = () => joinedRoom || (FLAGS.includes(save.flag) ? save.flag : 'XX');
const pendingOut = () => (lobby ? lobby.pending : null);
function wireLobby() {
lobby.onList(rows => { lobbyRows = rows; if (mode === 'lobby') renderLobby(); });
lobby.onIncoming(c => { if (mode === 'lobby' || mode === 'garage') showIncoming(c); });
lobby.onMatch(m => startOnlineFight(m));
lobby.onEnd(m => onlineFightEnded(m));
lobby.onCancel(c => {
if (mode === 'lobby') { renderLobby(); if (c.outgoing) SFX.deny(); }
else if (!c.outgoing && $('cYes')) hideOverlay(); // the challenger gave up while I was asked
});
lobby.onError(code => {
SFX.deny();
if (mode === 'lobby') { renderLobby(); const el = $('lMsg'); if (el) el.textContent = errText(code); }
else if (mode === 'garage') $('mechTip').textContent = errText(code);
});
net.socket.on('outdated', () => {
card(`<h2>${t('reload_title')}</h2><p>${t('e_OUTDATED')}</p><div class="row"><button class="primary" id="rNow">${t('reload_now')}</button></div>`, { bg: 'bg_title.jpg' });
$('rNow').onclick = () => location.reload();
});
net.socket.on('replaced', () => { if (mode === 'lobby') { const el = $('lMsg'); if (el) el.textContent = t('e_REPLACED'); } });
}
async function startOnline(dest) { // dest 'lobby' -> player list, else the workshop (main page)
if (!net.enabled) return;
if (gameMode !== 'online') { setMode('online'); if (save) { loadSave(); hud(); } } // online uses its own save
if (!net.auth.current) {
if (save && !fbAcc()) return joinAnon(); // playing as guest -> straight in, anonymously
showOnlineLogin(false, null, 'online'); return;
}
if (!save || !slot) { if (!fbAcc()) accounts.guest(); loadSave(); }
if (!onlineReady) { wireLobby(); onlineReady = true; }
lobby.enter();
ensureFlag(() => { if (dest === 'lobby') showLobby(); else openGarage(); }); // country first, then main page / lobby
}
async function joinAnon() {
if (!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 (!lobbyRoom) 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 = lobbyRows;
const myFlag = FLAGS.includes(save.flag) ? 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 = lobbyRoom === 'all' ? all : all.filter(r => code(r) === lobbyRoom);
const showMe = lobbyRoom === 'all' || lobbyRoom === mine;
const out = pendingOut();
const flagOpts = FLAGS.map(f => `<option value="${f}" ${f === myFlag ? 'selected' : ''}>${t('cc_' + f)}</option>`).join('');
const room = (f, label, flag) => `<button class="rroom ${lobbyRoom === f ? 'on' : ''} ${f === mine ? 'joined' : ''}" data-f="${f}"><span class="rfl">${flag ? flagHtml(f) : ''}</span><span class="rn">${label}${f === mine ? ' <span class="rhere">📍</span>' : ''}</span><span class="cnt ${cnt(f) ? 'live' : ''}">${f === 'all' ? total : cnt(f)}</span></button>`;
const rooms = room('all', t('all_countries'), false) + FLAGS.map(f => room(f, t('cc_' + f), true)).join('');
const action = r => (r.state === 'idle' && !out ? `<button class="chal" data-uid="${esc(r.uid)}">${t('challenge')}</button>` : `<span class="pbusy">${r.state === 'idle' ? '' : t('busy')}</span>`);
const prow = (r, me) => `<div class="prow ${me ? 'me' : ''}" ${me ? '' : `data-uid="${esc(r.uid)}"`}><span class="pf">${flagHtml(me ? save.flag : r.flag)}</span><span class="pn">${esc(me ? playerName() : r.name)}${me ? ` <span class="muted">(${t('you')})</span>` : ''}</span><span class="pfame">⭐ ${Kit.fmt((me ? save.fame : r.fame) | 0)}</span>${me ? '<span class="pbusy"></span>' : action(r)}</div>`;
const list = here.map(r => prow(r, false)).join('');
const title = lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(lobbyRoom) + ' ' + t('cc_' + lobbyRoom);
const offline = lobby && !lobby.connected ? `<p class="muted" style="margin:6px 0 0">${t('net_connecting')}</p>` : '';
overlay.innerHTML = `<div class="lobbyfull">
<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(); lobbyRoom = b.dataset.f;
if (lobbyRoom !== 'all') { joinedRoom = lobbyRoom; if (lobby) lobby.setRoom(joinedRoom); } // joining a country = be present there
renderLobby();
}; });
$('lFlag').onchange = e => { 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 (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 (mode === 'lobby') renderLobby(); else hideOverlay(); };
}
// server says: fight on (also after a reconnect into a running fight)
function startOnlineFight(m) {
const mine = m.robots[m.seat], other = m.robots[1 - m.seat];
const opp = { name: other.name, build: other.build, paint: other.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: other.flag };
prepOpp(opp, () => startFight(opp, false, false, { id: m.matchId, seat: m.seat, seed: m.seed, arena: m.arena, countdown: m.countdown, myBuild: mine.build }));
}
// server result + rewards (the fight on screen ends with it; if we missed the fight, just take the new save)
function onlineFightEnded(m) {
if (F && F.online && F.online.id === m.matchId && !F.ended) {
F.serverEnd = m;
F.s.result = RC.Proto.localResult(m.seat, m.result);
F.s.endIn = 0;
return;
}
if (m.save && gameMode === 'online') { adoptEconomy(m.save); afterEconomy(); }
}
// ---------------------------------------------------------------- accounts
function showLogin(errKey) {
setScreen('account');
@@ -920,41 +559,6 @@
}
save.paintSlot = Kit.clamp(save.paintSlot | 0, 0, 2);
}
// hangar: switch / add / delete robot slots (owned parts are shared)
function switchRobot(i) {
if (i === save.active || !save.robots[i]) return;
syncActive();
if (!act({ type: 'robotSwitch', index: i }).ok) return;
persist();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar();
}
function addRobot() {
syncActive();
if (!act({ type: 'robotNew', name: t('robot_n', { n: save.robots.length + 1 }) }).ok) { SFX.deny(); return; }
persist();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar();
SFX.buy();
}
function delRobot(i) {
syncActive();
if (!act({ type: 'robotDelete', index: i }).ok) { SFX.deny(); return; }
persist(); RC.layerFromData(layer, save.paint.decal, () => {}); shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar();
}
// hangar management (shop top-tab): list of robots with weapon, switch / delete + add button
function renderHangar(el) {
el = el || $('cards'); if (!el) return;
const rows = save.robots.map((r, i) => `<div class="hmrow ${i === save.active ? 'on' : ''}" data-i="${i}">
<div><div class="hmn">${esc(r.name)}</div><div class="hmw">${esc(weaponName(r.build))}</div></div>
${i === save.active ? `<span class="muted" style="font-size:12px">${t('active_robot')}</span>` : `<button data-use="${i}">${t('use')}</button>`}
${save.robots.length > 1 ? `<button data-del="${i}" title="${t('delete')}">✕</button>` : '<span></span>'}</div>`).join('');
el.innerHTML = `<div class="hmgr">${rows}</div>
${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'); };
}
function signOut() {
persist();
cloudFlush(); // push now, while we still have the auth token
@@ -975,256 +579,20 @@
};
function currentBack() { return mode === 'garage' ? openGarage : mode === 'league' ? showLeague : mode === 'result' ? openGarage : mode === 'title' ? showTitle : save ? openGarage : showTitle; }
// ---------------------------------------------------------------- settings / help / ranking
function showSettings(back) {
overlayEnter();
const prev = 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])))}
${save ? item(t('s_country'), `<select id="sCountry" class="selset">${FLAGS.map(f => `<option value="${f}" ${f === 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>
${isDev && 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>
${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>${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 (view) 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 (view) view.setCam(v); });
segOn('sComfort', v => { settings.comfort = v === '1'; saveSettings(); if (view && view.setComfort) 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 => { save.flag = e.target.value; 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 (isDev && 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, (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();
}
// ---------------------------------------------------------------- pages (game/pages.js)
function ensureFlag(...a) { return GM.pages.ensureFlag(...a); }
function boardHtml(...a) { return GM.pages.boardHtml(...a); }
function fillBoard(...a) { return GM.pages.fillBoard(...a); }
function liveBanner(...a) { return GM.pages.liveBanner(...a); }
function showAchievements(...a) { return GM.pages.showAchievements(...a); }
function showHelp(...a) { return GM.pages.showHelp(...a); }
function showLegal(...a) { return GM.pages.showLegal(...a); }
function showMissions(...a) { return GM.pages.showMissions(...a); }
function showRanking(...a) { return GM.pages.showRanking(...a); }
function showSettings(...a) { return GM.pages.showSettings(...a); }
function startTutorial(...a) { return GM.pages.startTutorial(...a); }
// first start: pick the country whose flag shows on the ranking / in the lobby (changeable later in settings)
function chooseFlag(done) {
overlayEnter();
let pick = (save && FLAGS.includes(save.flag)) ? 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 (save) { save.flag = pick; save.flagSet = true; persist(); } SFX.click(); done(); };
}
const ensureFlag = done => { if (save && !save.flagSet) chooseFlag(done); else done(); };
// one line for the running event and one for the admin's message
function liveBanner() {
const out = [];
if (LIVE.event) {
const n = liveText(LIVE.event.name) || t('event_running');
const extra = LIVE.event.prizeMul !== 1 ? ` · ${t('event_prize', { n: LIVE.event.prizeMul })}` : '';
out.push(`<div class="evbar"><b>${t('event')}</b><span>${esc(n)}${extra}</span></div>`);
}
const m = liveText(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(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 - save.fame) })
: t('rank_top');
const rows = P.ACHIEVEMENTS.map(a => {
const done = !!(save.ach && 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(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 = (save.missions && save.missions.daily) || [], weekly = (save.missions && 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(); };
}
let rankSub = null, titleRankSub = null, boardFame = {}, boardIdx = {};
const closeRank = () => { if (rankSub) { rankSub.close(); 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(); };
boardFame = {}; boardIdx = {};
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
closeRank();
if (rank.enabled) 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>`; boardFame = {}; 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 = 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 = boardFame[key] != null ? boardFame[key] : to;
animNum(li.querySelector('.val b'), from, to); 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 = ''; }); }
}
});
boardIdx = {}; rows.forEach((r, i) => 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(save, newSave()); RC.layerFromData(layer, null); save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); };
}
// the rank badge opens the achievements page
$('hTour').onclick = () => { SFX.click(); if (gameMode === 'campaign') { if (tourState()) showTournament(); else showLeague(); } }; // online tournament: server-side later (plan P2-6)
$('chipFame').onclick = () => {
if (!save || mode === 'intro' || mode === 'title') return;
if (mode === 'fight') togglePause();
SFX.click();
showAchievements(mode === 'pause' ? () => { mode = 'fight'; togglePause(); } : currentBack());
};
$('bSettings').onclick = () => {
if (mode === 'fight') togglePause();
if (mode === 'intro') skipIntro();
SFX.click();
const back = mode === 'pause' ? () => { mode = 'fight'; togglePause(); } : currentBack();
showSettings(back);
};
function boardHtml() { return (rank.enabled && 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>`; }
}
// ---------------------------------------------------------------- shop + league
function openGarage() {
hideOverlay();
@@ -1401,7 +769,12 @@
const count = online ? Math.max(0, +online.countdown || 0) : 3.5;
F = { s, opp, training, exhibition: !!exhibition, online, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count, beat: Math.ceil(count) + 1,
acc: [0, 0], accT: 0, banner: null, ended: false, oppAway: false };
if (online) F.nf = RC.NetFight({ net, seat: online.seat }); // the server runs the fight, we show it
if (online) { // the server runs the fight, we show it (interpolated); dev: ?netlag=base,jit[,seed], ?interp=ms
netStats.reset();
let lag = null; const nl = DEV.get('netlag');
if (nl) { const [b, j, sd] = nl.split(',').map(Number); lag = { base: b || 0, jit: j || 0, seed: sd || 1 }; }
F.nf = RC.NetFight({ net, seat: online.seat, stats: netStats, interp: +DEV.get('interp') || 0, lag });
}
// dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing)
if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 });
if (DEV.has('ff')) {
@@ -1549,6 +922,7 @@
let events;
if (F.online) {
events = F.nf.frame(s, playerInput(), dt);
if (netProbe) { netProbe.push({ t: performance.now(), x: s.robots[1].x, z: s.robots[1].z }); if (netProbe.length > 2000) netProbe.shift(); }
if (F.nf.oppAway !== F.oppAway) { F.oppAway = F.nf.oppAway; banner(t(F.oppAway ? 'peer_lost' : 'peer_back'), F.oppAway ? '#ff4a3a' : '#6dff9e', 2.2); }
// no word from the server for 20 s (and no result yet - a hidden tab may simply have slept through the end)
if (!F.serverEnd && F.nf.silentFor > 20 && !F.ended) { F.ended = true; onlineFightLost(); return; }
@@ -1791,37 +1165,6 @@
$('bTour').onclick = () => { SFX.click(); showTournament(); };
}
// live fight over: the server already booked prize, repairs and achievements - show them and take its save
function endOnlineFight(res, won, me) {
if (F.nf) F.nf.stop();
const m = F.serverEnd, rw = (m && m.reward) || { money: 0, fame: 0, lines: [], ach: [] };
if (m && m.save) { adoptEconomy(m.save); persist(); }
(won ? SFX.win : SFX.lose)();
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(F.opp.name)} ${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 (F && F.nf) F.nf.stop();
SFX.deny();
setScreen('result');
card(`<h2>${t('net_lost')}</h2><p>${t('match_lost')}</p>
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button></div>`, { bg: 'bg_lose.jpg' });
$('bLobby').onclick = () => { SFX.click(); onlinePull(); showLobby(); };
}
// ---------------------------------------------------------------- loop
let lastNow = 0, fpsN = 0, fpsT = 0, fpsVal = 0;
function render(alpha, now) {
@@ -1879,7 +1222,14 @@
function togglePause() {
overlayEnter();
if (F && F.online && mode === 'fight') { banner(t('no_pause_online'), '#ffffff', 1.4); return; }
// live fight: no pause (the server keeps running) - but you can give up; the fight goes on behind the card
if (F && F.online && mode === 'fight') {
if ($('bGiveUp')) { hideOverlay(); return; } // second press closes the card again
card(`<h2>${t('pause')}</h2><p>${t('no_pause_online')}</p><div class="row"><button id="bGiveUp">${t('give_up')}</button><button class="primary" id="bGo">${t('continue')}</button></div>`);
$('bGo').onclick = () => { SFX.click(); hideOverlay(); };
$('bGiveUp').onclick = () => { SFX.click(); hideOverlay(); if (lobby) lobby.leaveMatch(); };
return;
}
if (mode === 'fight') {
mode = 'pause'; loop.pause();
card(`<h2>${t('pause')}</h2><div class="row"><button id="bSet2">⚙ ${t('settings')}</button><button id="bQuit">${t('give_up')}</button><button class="primary" id="bGo">${t('continue')}</button></div>`);
@@ -1905,6 +1255,47 @@
if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); }
});
// ---------------------------------------------------------------- feature modules
// game.js was split by topic (pages.js, online.js, workshop.js). They share this context: getters always
// return the CURRENT value (save, mode, F change all the time), setters write back into game.js.
const G = {
get $() { return $; }, get CAMS() { return CAMS; }, get FLAGS() { return FLAGS; },
get GLYPH_SLOT() { return GLYPH_SLOT; }, get L() { return L; }, get MAX_ROBOTS() { return MAX_ROBOTS; },
get SFX() { return SFX; }, get accounts() { return accounts; }, get achHtml() { return achHtml; },
get act() { return act; }, get audio() { return audio; }, get card() { return card; },
get currentBack() { return currentBack; }, get ensureFlag() { return ensureFlag; },
get ensureMissions() { return ensureMissions; }, get enterAccount() { return enterAccount; },
get esc() { return esc; }, get fbAcc() { return fbAcc; }, get flagHtml() { return flagHtml; },
get hideOverlay() { return hideOverlay; }, get hud() { return hud; }, get img() { return img; },
get layer() { return layer; }, get liveText() { return liveText; }, get loadSave() { return loadSave; },
get lobby() { return lobby; }, get logout() { return logout; }, get net() { return net; },
get newSave() { return newSave; }, get openGarage() { return openGarage; }, get overlay() { return overlay; },
get overlayEnter() { return overlayEnter; }, get paintObj() { return paintObj; },
get painter() { return painter; }, get persist() { return persist; }, get playerName() { return playerName; },
get prepOpp() { return prepOpp; }, get rank() { return rank; }, get refreshDev() { return refreshDev; },
get renderWeaponEditor() { return renderWeaponEditor; }, get repairSave() { return repairSave; },
get saveSettings() { return saveSettings; }, get setMode() { return setMode; },
get setScreen() { return setScreen; }, get settings() { return settings; }, get shop() { return shop; },
get showLeague() { return showLeague; }, get showLegal() { return showLegal; },
get showTitle() { return showTitle; }, get showTournament() { return showTournament; },
get skipIntro() { return skipIntro; }, get startFight() { return startFight; },
get syncActive() { return syncActive; }, get t() { return t; }, get togglePause() { return togglePause; },
get tourState() { return tourState; }, get weaponName() { return weaponName; }, get F() { return F; },
get LIVE() { return LIVE; }, get boardFame() { return boardFame; }, set boardFame(v) { boardFame = v; },
get boardIdx() { return boardIdx; }, set boardIdx(v) { boardIdx = v; }, get editSel() { return editSel; },
set editSel(v) { editSel = v; }, get editorOpen() { return editorOpen; }, get gameMode() { return gameMode; },
get isDev() { return isDev; }, get joinedRoom() { return joinedRoom; }, set joinedRoom(v) { joinedRoom = v; },
get lobbyRoom() { return lobbyRoom; }, set lobbyRoom(v) { lobbyRoom = v; },
get lobbyRows() { return lobbyRows; }, set lobbyRows(v) { lobbyRows = v; }, get mode() { return mode; },
set mode(v) { mode = v; }, get onlineReady() { return onlineReady; }, set onlineReady(v) { onlineReady = v; },
get rankSub() { return rankSub; }, set rankSub(v) { rankSub = v; }, get save() { return save; },
get slot() { return slot; }, get view() { return view; }, get wPrev() { return wPrev; },
set wPrev(v) { wPrev = v; },
};
GM.pages = RC.GamePages(G);
GM.online = RC.GameOnline(G);
GM.workshop = RC.GameWorkshop(G);
// ---------------------------------------------------------------- start
// backend settings; applied as soon as they arrive and whenever the admin changes them
RC.Live.load(net, v => {

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)); }
@@ -830,9 +842,15 @@
<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

@@ -209,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',
@@ -243,6 +243,15 @@ window.LANG = {
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.',
@@ -489,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',
@@ -523,6 +532,15 @@ window.LANG = {
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.',

View File

@@ -129,6 +129,7 @@
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

View File

@@ -1,64 +1,102 @@
/* 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, seat })
nf.frame(s, input, dt) send input (on change, max 30/s, at least every 0.25 s), ease the local state toward
the newest snapshot, return the events of snapshots not seen yet
nf.oppAway true while the opponent is disconnected (server tells us)
nf.silentFor seconds since the last snapshot (connection trouble)
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.
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 SEND_MIN = 1 / 30, SEND_KEEP = 0.25;
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 sock = opt.net.socket, seat = opt.seat;
let latest = null, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
const off = sock.on('snap', m => { latest = RC.Proto.toLocal(seat, m); lastSnap = Date.now(); });
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 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 (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 applyRobot(r, d, k) {
for (const f of EASE) if (typeof d[f] === 'number') r[f] += (d[f] - r[f]) * k;
for (const f of ANG) if (typeof d[f] === 'number') r[f] += wrap(d[f] - r[f]) * k;
for (const f of RC.Proto.RF) if (!EASE.includes(f) && !ANG.includes(f) && d[f] !== undefined) r[f] = d[f];
if (d.lost) r.lost = Object.assign(r.lost || {}, d.lost);
if (d.lostW) r.lostW = d.lostW.slice();
if (d.W && r.W) d.W.forEach((w, i) => { if (r.W[i]) Object.assign(r.W[i], w); });
}
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]); };
function frame(s, inp, dt) {
sendInput(inp, dt);
if (!latest) return [];
const n = latest, k = Math.min(1, dt * 14);
s.t = n.time; s.left = n.left; s.pitOpen = n.pitOpen; s.pitAlarm = n.pitAlarm; s.endIn = n.endIn;
s.press.st = n.press.st; s.press.y = n.press.y;
Object.assign(s.crane, n.crane);
syncList(s.rockets, n.rockets, { sp: 6, t: 3 });
syncList(s.mines, n.mines, { r: 0.85 });
applyRobot(s.robots[0], n.robots[0], k);
applyRobot(s.robots[1], n.robots[1], k);
if (n.result) s.result = n.result;
if (n.tick === seenTick) return [];
seenTick = n.tick;
return n.ev || [];
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 || [];
}
return {
frame,
get oppAway() { return !!(latest && latest.away && latest.away[1]); },
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

@@ -24,7 +24,7 @@
// client -> server message schemas: field -> check
const C2S = {
hello: { v: v => Number.isInteger(v), token: v => isStr(v, 4096) },
ping: { t: v => v === undefined || isNum(v) },
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': {},
@@ -89,6 +89,7 @@
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) })),

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

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

46
package-lock.json generated
View File

@@ -9,6 +9,7 @@
"version": "0.1.0",
"devDependencies": {
"@eslint/js": "^9.39.5",
"@playwright/test": "^1.65.1",
"eslint": "^9.39.5",
"globals": "^16.5.0",
"terser": "^5.46.1"
@@ -290,6 +291,22 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@playwright/test": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.65.1.tgz",
"integrity": "sha512-y+NCIRm2LvY4slUVWvGh1nujJ8RF/hEisIsq2mtUPgdQC4L701bq5hZGMhrpeXjACvwvO9tj5dJqhvM6TP9lbw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.65.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@types/estree": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",
@@ -1037,6 +1054,35 @@
"node": ">=8"
}
},
"node_modules/playwright": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
"integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.65.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/playwright-core": {
"version": "1.65.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
"integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=20"
}
},
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",

View File

@@ -14,10 +14,13 @@
"balance": "node tests/balance.js -v",
"lint": "eslint .",
"dev": "npm --prefix server run dev",
"build:web": "node build-web.mjs"
"build:web": "node build-web.mjs",
"e2e": "playwright test",
"bot": "node tools/bot.js"
},
"devDependencies": {
"@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,
},
});

View File

@@ -45,6 +45,8 @@ app.post('/api/auth/login', authLimit, run(req => auth.login(body(req).login ||
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 ------------------------

View File

@@ -63,8 +63,12 @@ function refresh(refreshToken) {
}
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) {
try { const d = jwt.verify(String(token || ''), SECRET); return { uid: d.uid, name: d.name, guest: !!d.guest, admin: d.role === 'admin' }; } catch (e) { return null; }
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) {

View File

@@ -33,6 +33,7 @@ const Users = {
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 = {

View File

@@ -8,7 +8,7 @@ leitet an den Node-Dienst weiter, WebSocket `/ws` inklusive). Alle Befehle aus d
```
/opt/robotclash/
releases/<zeit>-<commit>/ je Deploy ein vollständiges Release (game/, server/, admin/), die letzten 5 bleiben
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
@@ -54,3 +54,12 @@ curl -s https://roboclash.michael-media.de/healthz
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.

View File

@@ -19,13 +19,13 @@ while [ $# -gt 0 ]; do
done
cd "$(git rev-parse --show-toplevel)"
git diff --quiet HEAD -- game server admin || echo "!! uncommitted changes in game/server/admin are NOT deployed (only $REF)"
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
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

@@ -104,6 +104,7 @@ function createLobby({ runner, economy, matches, now = () => Date.now() }) {
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());
@@ -143,10 +144,13 @@ function createLobby({ runner, economy, matches, now = () => Date.now() }) {
}
}
// 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, startMatch, players, pending, inMatch };
return { join, leave, handle, refresh, setRtt, startMatch, players, pending, inMatch };
}
module.exports = { createLobby, CHALLENGE_TTL };

View File

@@ -25,6 +25,7 @@ class Room {
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];
@@ -80,7 +81,10 @@ class Room {
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;
@@ -95,7 +99,10 @@ class Room {
const snap = RC.Proto.packSnap(s, this.tickN, this.acks);
s.events = []; this.evBuf.length = 0;
const away = [!!this.away[0], !!this.away[1]];
for (const seat of [0, 1]) this.send(seat, Object.assign({ t: 'snap', away }, snap));
// 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) {

View File

@@ -14,7 +14,10 @@ function createRunner(opt = {}) {
let n = 0;
while (now >= next && n < 10) {
const t0 = performance.now();
for (const room of rooms.values()) room.tick();
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++;

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

@@ -44,6 +44,14 @@ test('register: optional e-mail works as login too; duplicates and 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);

View File

@@ -17,6 +17,28 @@ test('socket must authenticate with hello first', async () => {
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 });
@@ -24,6 +46,16 @@ test('old protocol version is told to reload', async () => {
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);
@@ -90,7 +122,11 @@ test('full live match over WebSocket: both get start, snapshots, and mirrored re
const winner = la === 0 ? ea : lb === 0 ? eb : null;
if (winner) assert.ok(winner.reward.ach.some(x => x.id === 'first_win'), 'first win pays out');
assert.equal(eb.save.games, 1);
assert.ok(ca.inbox.some(m => m.t === 'snap'), 'snapshots arrived before the end');
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);

View File

@@ -7,15 +7,20 @@ const auth = require('../auth');
const HELLO_MS = 5000;
const RATE = 80; // messages per second per socket (inputs ~30/s + lobby)
const PING_MS = 15000;
const PING_MS = 2000; // ws ping every 2 s: keepalive + ping measurement
const DEAD_MS = 15000; // no pong for this long -> connection is dead
function attach(server, { lobby }) {
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: RC.Proto.MAX_MSG });
wss.on('connection', ws => {
let user = null, tokens = RATE, last = Date.now();
ws.alive = true;
ws.on('pong', () => { ws.alive = true; });
ws.lastPong = Date.now();
ws.on('pong', () => {
ws.lastPong = Date.now();
if (ws.pingSent && user) lobby.setRtt(user.uid, Number(process.hrtime.bigint() - ws.pingSent) / 1e6);
ws.pingSent = 0n;
});
const send = msg => { if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg)); };
const bye = (code, reason) => { try { ws.close(code, reason); } catch (e) { /* closed */ } };
const helloTimer = setTimeout(() => { if (!user) bye(4001, 'HELLO_TIMEOUT'); }, HELLO_MS);
@@ -36,19 +41,22 @@ function attach(server, { lobby }) {
clearTimeout(helloTimer);
user = u;
send({ t: 'welcome', uid: u.uid, name: u.name, serverTime: Date.now(), v: RC.Proto.VERSION });
lobby.join({ uid: u.uid, name: u.name, admin: u.admin, send });
try { lobby.join({ uid: u.uid, name: u.name, admin: u.admin, send }); } catch (e) { console.error('[ws] join failed', e); bye(1011, 'SERVER_ERROR'); }
return;
}
if (msg.t === 'hello') return;
lobby.handle(user.uid, msg);
try { lobby.handle(user.uid, msg); } catch (e) { console.error('[ws] handler failed for', msg.t, e); send({ t: 'error', code: 'SERVER_ERROR' }); }
});
ws.on('close', () => { clearTimeout(helloTimer); if (user) lobby.leave(user.uid, send); });
ws.on('close', () => { clearTimeout(helloTimer); if (user) { try { lobby.leave(user.uid, send); } catch (e) { console.error('[ws] leave failed', e); } } });
ws.on('error', () => {});
});
const beat = setInterval(() => {
for (const ws of wss.clients) { if (!ws.alive) { ws.terminate(); continue; } ws.alive = false; try { ws.ping(); } catch (e) { /* closed */ } }
for (const ws of wss.clients) {
if (Date.now() - ws.lastPong > DEAD_MS) { ws.terminate(); continue; }
try { ws.pingSent = process.hrtime.bigint(); ws.ping(); } catch (e) { /* closed */ }
}
}, PING_MS);
if (beat.unref) beat.unref();
wss.on('close', () => clearInterval(beat));

37
tests/e2e/helpers.js Normal file
View File

@@ -0,0 +1,37 @@
/* Shared steps for the browser tests: log in through the real UI, get from the workshop into the lobby. */
'use strict';
const { expect } = require('@playwright/test');
const mode = page => page.locator('body').getAttribute('data-mode');
// open the game in online mode and log in with name + password through the login card
async function login(page, name, pass, query = '') {
await page.goto('/?online' + query);
await page.locator('#oLogin').fill(name);
await page.locator('#oPass').fill(pass);
await page.locator('#oGo').click();
await chooseCountry(page);
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
await expect(page.locator('#hUser')).toContainText(name);
}
// first start asks for a country - take the default
async function chooseCountry(page) {
const go = page.locator('#cfGo');
try { await go.waitFor({ timeout: 4000 }); await go.click(); } catch (e) { /* already chosen */ }
}
async function toLobby(page) {
await page.locator('#bLeague').click();
await expect(page.locator('body')).toHaveAttribute('data-mode', 'lobby');
}
// the header shows big amounts short like Kit.fmt does ("10.8K", "1.20M", "3B")
const UNIT = { K: 1e3, M: 1e6, B: 1e9 };
const parseCredits = text => {
const m = String(text).replace(/[,\s]/g, '').match(/([\d.]+)([KMB]?)/i);
return m ? Math.round(parseFloat(m[1]) * (UNIT[(m[2] || '').toUpperCase()] || 1)) : NaN;
};
const credits = async page => parseCredits(await page.locator('#hMoney').textContent());
module.exports = { mode, login, chooseCountry, toLobby, credits, parseCredits };

48
tests/e2e/netlag.spec.js Normal file
View File

@@ -0,0 +1,48 @@
// Repeatable lag test: one client gets a seeded snapshot delay+jitter (?netlag). The opponent robot must still
// move SMOOTHLY on that client (entity interpolation), i.e. no large per-step jumps - the bug Michi reported.
'use strict';
const { test, expect } = require('@playwright/test');
const { login, toLobby } = require('./helpers');
test('a jittery client still sees the opponent move smoothly (interpolation buffer)', async ({ browser }) => {
const ctxA = await browser.newContext(), ctxB = await browser.newContext();
const a = await ctxA.newPage(), b = await ctxB.newPage();
const errors = [];
for (const p of [a, b]) p.on('pageerror', e => errors.push(e.message));
// michi gets a repeatable snapshot delay + jitter (80 ms +/- 40 ms, seeded) + the position probe
await login(a, 'michi', 'Michi2000!', '&netlag=80,40,7&netprobe');
await login(b, 'benni', 'Benni2000!');
await toLobby(a); await toLobby(b);
await a.locator('.prow', { hasText: 'benni' }).locator('.chal').click();
await expect(b.locator('#cYes')).toBeVisible();
await b.locator('#cYes').click();
await expect(a.locator('body')).toHaveAttribute('data-mode', 'fight');
await expect(b.locator('body')).toHaveAttribute('data-mode', 'fight');
await a.waitForTimeout(4200); // countdown
await a.evaluate(() => { globalThis.__probe.length = 0; });
await b.keyboard.down('w'); // benni drives so his robot moves across michi's screen
await a.keyboard.down('a'); // michi turns a bit (keeps both sides active)
await a.waitForTimeout(2600);
await b.keyboard.up('w'); await a.keyboard.up('a');
const probe = await a.evaluate(() => globalThis.__probe.slice());
// consider only samples while the opponent was actually moving
const deltas = [];
let moved = 0;
for (let i = 1; i < probe.length; i++) {
const dx = probe[i].x - probe[i - 1].x, dz = probe[i].z - probe[i - 1].z;
const d = Math.hypot(dx, dz);
deltas.push(d); moved += d;
}
expect(probe.length, 'probe collected samples').toBeGreaterThan(30);
expect(moved, 'the opponent actually moved (test is meaningful)').toBeGreaterThan(0.8);
const maxJump = Math.max(...deltas);
// at ~5 m/s over a 60 Hz step a smooth move is ~0.08/step; a snapshot-jump would be several times that.
expect(maxJump, 'no large per-step jump despite jitter (smooth interpolation)').toBeLessThan(0.35);
expect(errors, 'no JavaScript errors').toEqual([]);
await ctxA.close(); await ctxB.close();
});

29
tests/e2e/offline.spec.js Normal file
View File

@@ -0,0 +1,29 @@
// The offline campaign must keep working without any server (double-click on game/index.html = file://).
'use strict';
const { test, expect } = require('@playwright/test');
const path = require('path');
const { pathToFileURL } = require('url');
const { credits } = require('./helpers');
const file = pathToFileURL(path.join(__dirname, '..', '..', 'game', 'index.html')).href;
test('campaign runs from file:// : training fight with the AI pilot, layout check passes', async ({ page }) => {
const errors = [];
page.on('pageerror', e => errors.push(e.message));
await page.goto(file + '?play&fight=2&auto&ff=20&uicheck');
await expect(page.locator('body')).toHaveAttribute('data-gmode', 'campaign');
await expect(page.locator('body')).toHaveAttribute('data-mode', /fight|result/);
await expect(page.locator('#uicheck')).toContainText('UI ok');
expect(errors).toEqual([]);
});
test('campaign workshop: buying a part works offline', async ({ page }) => {
await page.goto(file + '?play');
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
const money = () => credits(page);
const before = await money();
await page.locator('.tab[data-slot="armour"]').click();
await page.locator('#cards .item:not(:has(.badge)):not(:has(.pr.no))').first().click();
await page.locator('#detail button[data-act="buy"]').click();
expect(await money()).toBeLessThan(before);
});

103
tests/e2e/online.spec.js Normal file
View File

@@ -0,0 +1,103 @@
// Two real browsers play a live fight through the server: login, lobby, challenge, accept, fight, give up, result.
'use strict';
const { test, expect } = require('@playwright/test');
const { login, toLobby, credits, chooseCountry } = require('./helpers');
test('michi challenges benni, benni gives up: mirrored result and server-booked rewards', async ({ browser }) => {
const ctxA = await browser.newContext(), ctxB = await browser.newContext();
const a = await ctxA.newPage(), b = await ctxB.newPage();
const errors = [];
for (const p of [a, b]) p.on('pageerror', e => errors.push(e.message));
await login(a, 'michi', 'Michi2000!');
await login(b, 'benni', 'Benni2000!');
const moneyA = await credits(a), moneyB = await credits(b);
await toLobby(a);
await toLobby(b);
// each sees the other in the lobby
await expect(a.locator('.prow', { hasText: 'benni' })).toBeVisible();
await expect(b.locator('.prow', { hasText: 'michi' })).toBeVisible();
// challenge -> incoming card -> accept -> both are in the fight
await a.locator('.prow', { hasText: 'benni' }).locator('.chal').click();
await expect(a.locator('#lCancel')).toBeVisible();
await expect(b.locator('#cYes')).toBeVisible();
await b.locator('#cYes').click();
await expect(a.locator('body')).toHaveAttribute('data-mode', 'fight');
await expect(b.locator('body')).toHaveAttribute('data-mode', 'fight');
await expect(a.locator('#fN1')).toHaveText('benni');
await expect(b.locator('#fN1')).toHaveText('michi');
// the fight runs on the server: after the countdown michi drives - the clock must tick down
await a.waitForTimeout(4500);
await a.keyboard.down('w');
await a.waitForTimeout(1500);
await a.keyboard.up('w');
await expect(a.locator('#fightHud')).not.toContainText('2:00');
// benni gives up through the pause card (live: no pause, the fight keeps running)
await b.keyboard.press('p');
await expect(b.locator('#bGiveUp')).toBeVisible();
await b.locator('#bGiveUp').click();
// result: michi wins, benni loses - never both "victory" (the old mirrored-result bug)
await expect(a.locator('body')).toHaveAttribute('data-mode', 'result', { timeout: 20000 });
await expect(b.locator('body')).toHaveAttribute('data-mode', 'result', { timeout: 20000 });
await expect(a.locator('#overlay h1')).toHaveText(/victory/i);
await expect(b.locator('#overlay h1')).toHaveText(/defeat/i);
// rewards came from the server and survive a reload (server is the authority)
const afterA = await credits(a), afterB = await credits(b);
expect(afterA).toBeGreaterThan(moneyA);
expect(afterB).toBeGreaterThanOrEqual(moneyB);
await a.reload();
await chooseCountry(a);
await expect(a.locator('body')).toHaveAttribute('data-mode', 'garage');
await expect.poll(() => credits(a)).toBe(afterA);
expect(errors, 'no JavaScript errors in either browser').toEqual([]);
await ctxA.close(); await ctxB.close();
});
test('shop purchase is checked and stored by the server', async ({ browser }) => {
const ctx = await browser.newContext();
const page = await ctx.newPage();
await page.goto('/?online');
await page.locator('#oAnon').click(); // guest account on the server
await chooseCountry(page);
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
const before = await credits(page);
await page.locator('.tab[data-slot="armour"]').click();
const item = page.locator('#cards .item:not(:has(.badge)):not(:has(.pr.no))').first();
await item.click();
await page.locator('#detail button[data-act="buy"]').click();
await expect.poll(() => credits(page)).toBeLessThan(before);
const after = await credits(page);
// what the server stored
const token = await page.evaluate(() => JSON.parse(localStorage.getItem('robotclash.net.session')).idToken);
const res = await page.request.get('/api/online', { headers: { Authorization: 'Bearer ' + token } });
const srv = await res.json();
expect(srv.money).toBe(after);
expect(srv.build.armour).toBeTruthy();
// the client cannot simply give itself money
const cheat = await page.request.put('/api/online/save', { headers: { Authorization: 'Bearer ' + token }, data: { money: 999999 } });
expect((await cheat.json()).money).toBe(after);
await ctx.close();
});
test('F3 network overlay: hidden at start, F3 shows it with content, F3 hides it again', async ({ page }) => {
await login(page, 'benni', 'Benni2000!');
const ov = page.locator('#netov');
await expect(ov).toBeHidden(); // regression: an empty box was always on screen
await page.keyboard.press('F3');
await expect(ov).toBeVisible();
await expect(ov).toContainText(/ping/i);
await page.keyboard.press('F3');
await expect(ov).toBeHidden(); // regression: it could not be closed again
await page.keyboard.press('F3');
await expect(ov).toBeVisible();
});

89
tests/e2e/screens.spec.js Normal file
View File

@@ -0,0 +1,89 @@
// Every menu page and workshop tool once, in the real browser, offline (file://) - guards the game.js split:
// a missing reference between the modules shows up here as a JavaScript error.
'use strict';
const { test, expect } = require('@playwright/test');
const path = require('path');
const { pathToFileURL } = require('url');
const file = pathToFileURL(path.join(__dirname, '..', '..', 'game', 'index.html')).href;
const { credits: money } = require('./helpers');
test.beforeEach(async ({ page }) => {
page.errors = [];
page.on('pageerror', e => page.errors.push(e.message));
await page.goto(file + '?play');
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
});
test.afterEach(async ({ page }) => { expect(page.errors, 'no JavaScript errors').toEqual([]); });
test('menu pages: settings, controls, legal, achievements, missions', async ({ page }) => {
await page.locator('#bSettings').click();
await expect(page.locator('#sKeys')).toBeVisible();
await page.locator('#sKeys').click(); // controls page from settings
await page.locator('#bOk').click();
await expect(page.locator('#sLegal')).toBeVisible(); // back in settings
await page.locator('#sLegal').click();
await page.locator('#bOk').click();
await page.locator('#bBack').click();
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
await page.locator('#chipFame').click(); // achievements
await expect(page.locator('.achlist')).toBeVisible();
await page.locator('#bBack').click();
await page.locator('#bMissions').click(); // campaign missions
await expect(page.locator('.misslist').first()).toBeVisible();
await page.locator('#bBack').click();
});
test('guest via the title: country, tutorial, then dev coins go through the economy', async ({ page }) => {
await page.goto(file + '?title');
await page.locator('#bGuest').click();
await page.locator('#cfGo').click(); // country card
await page.locator('#tSkip').click(); // tutorial cards
await expect(page.locator('body')).toHaveAttribute('data-mode', 'garage');
await page.locator('#bSettings').click();
await page.locator('[data-coin="10000"]').click();
await page.locator('#bBack').click();
expect(await money(page)).toBeGreaterThanOrEqual(10800);
});
test('weapon editor: buy, place, sell a weapon', async ({ page }) => {
const start = await money(page);
await page.locator('.tab[data-slot="weapon"]').click();
await expect(page.locator('#wplace')).toBeVisible();
const before = await page.locator('.wphead').first().textContent();
await page.locator('#cards .item:not(:has(.pr.no))').first().click();
await page.locator('#detail button[data-wact="add"]').click();
expect(await money(page)).toBeLessThan(start);
await expect(page.locator('.wphead').first()).not.toHaveText(before); // weapon count went up
await page.locator('[data-side="left"]').click();
await expect(page.locator('[data-side="left"]')).toHaveClass(/on/);
await page.locator('#detail button[data-wact="rem"]').click();
});
test('paint tab: colour, scheme, paint slots', async ({ page }) => {
await page.locator('#shopTabs [data-tab="paint"]').click();
await expect(page.locator('#paintHdr')).toBeVisible();
await page.locator('#paintBody .sw:not(.locked)').nth(2).click();
await expect(page.locator('#paintBody .sw.on')).toHaveCount(1);
await page.locator('#paintSchemes .sw').nth(1).click();
await page.locator('[data-save="1"]').click(); // store into slot 2
await page.locator('[data-load="0"]').click(); // load slot 1
await expect(page.locator('.pslot.on')).toHaveCount(1);
await page.locator('#shopTabs [data-tab="build"]').click();
await expect(page.locator('#paintHdr')).toHaveCount(0);
});
test('hangar: new robot, switch, delete', async ({ page }) => {
await page.locator('#shopTabs [data-tab="hangar"]').click();
await expect(page.locator('.hmrow')).toHaveCount(1);
await page.locator('#hAdd').click();
await page.locator('#shopTabs [data-tab="hangar"]').click();
await expect(page.locator('.hmrow')).toHaveCount(2);
await page.locator('[data-use="0"]').click();
await page.locator('#shopTabs [data-tab="hangar"]').click();
await expect(page.locator('.hmrow.on')).toHaveAttribute('data-i', '0');
await page.locator('[data-del="1"]').click();
await expect(page.locator('.hmrow')).toHaveCount(1);
});

17
tests/e2e/server.js Normal file
View File

@@ -0,0 +1,17 @@
/* Server for the browser tests: fresh database file every run, seed accounts michi / benni, then the real app. */
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const file = path.join(os.tmpdir(), 'robotclash-e2e.sqlite');
for (const ext of ['', '-wal', '-shm']) fs.rmSync(file + ext, { force: true });
process.env.DB_FILE = file;
process.env.NODE_ENV = 'test'; // high auth rate limit, no secret warning
process.env.PORT = process.env.PORT || '8099';
const { createUser } = require('../../server/auth');
const economy = require('../../server/economy');
for (const [name, pass] of [['michi', 'Michi2000!'], ['benni', 'Benni2000!']]) economy.load(createUser({ name, pass, role: 'admin' }).uid);
require('../../server/app').listen().then(srv => console.log('e2e server on :' + srv.address().port));

49
tests/netfight.test.js Normal file
View File

@@ -0,0 +1,49 @@
'use strict';
// Entity-interpolation math for the live fight (the jitter buffer that stops the robot from jumping).
const { test } = require('node:test');
const assert = require('node:assert');
const path = require('path');
require(path.join(__dirname, '..', 'game', 'protocol.js'));
require(path.join(__dirname, '..', 'game', 'netfight.js'));
const RC = globalThis.RC;
const { pickFrames, lerpRobot } = RC.NetFight;
test('pickFrames: brackets the render time and gives the fraction between the two snapshots', () => {
const buf = [{ at: 0, tick: 1 }, { at: 100, tick: 2 }];
const fr = pickFrames(buf, 50);
assert.strictEqual(fr.a.tick, 1);
assert.strictEqual(fr.b.tick, 2);
assert.ok(Math.abs(fr.frac - 0.5) < 1e-9);
});
test('pickFrames: past the newest snapshot holds it (no extrapolation jump)', () => {
const buf = [{ at: 0, tick: 1 }, { at: 100, tick: 2 }];
const fr = pickFrames(buf, 500);
assert.strictEqual(fr.a.tick, 2);
assert.strictEqual(fr.b.tick, 2);
assert.strictEqual(fr.frac, 1);
});
test('pickFrames: empty buffer -> null', () => {
assert.strictEqual(pickFrames([], 0), null);
});
test('lerpRobot: positions interpolate linearly', () => {
const r = lerpRobot({ x: 0, z: 0, y: 0, hp: 100 }, { x: 10, z: -4, y: 2, hp: 50 }, 0.5);
assert.ok(Math.abs(r.x - 5) < 1e-9);
assert.ok(Math.abs(r.z + 2) < 1e-9);
assert.ok(Math.abs(r.y - 1) < 1e-9);
});
test('lerpRobot: angles take the shortest path across the +/-PI seam', () => {
const r = lerpRobot({ a: 3.0 }, { a: -3.0 }, 0.5);
// short way is +0.28 rad across PI, not -6 rad the long way
assert.ok(r.a > 3.0 || r.a < -3.0, 'wrapped past PI, not back toward 0');
assert.ok(Math.abs(Math.abs(r.a) - Math.PI) < 0.2, 'lands near the seam');
});
test('lerpRobot: discrete fields come from the reached (older) snapshot, not the newer one', () => {
const r = lerpRobot({ x: 0, hp: 100, dead: false }, { x: 10, hp: 0, dead: true }, 0.5);
assert.strictEqual(r.hp, 100);
assert.strictEqual(r.dead, false);
});

56
tests/netstats.test.js Normal file
View File

@@ -0,0 +1,56 @@
'use strict';
const { test } = require('node:test');
const assert = require('node:assert/strict');
const path = require('path');
require(path.join(__dirname, '..', 'game', 'netstats.js'));
const RC = globalThis.RC;
// feed a steady fight: snapshots every `gap` ms (+ jitter), pings, inputs acked after `inDelay`
function feed({ ping = 30, gap = 50, jit = 0, opp = 40, tickMs = 0.5, inDelay = 60, secs = 6 } = {}) {
const st = RC.NetStats();
let t = 1000, seq = 0;
const sent = [];
for (let i = 0; i < secs * 20; i++) {
t += gap + (i % 2 ? jit : -jit);
if (i % 20 === 0) st.pong(ping, t);
st.inputSent(++seq, t); sent.push({ seq, at: t });
const acked = sent.filter(x => t - x.at >= inDelay).pop();
st.snap({ rtt: [ping, opp], tickMs, ack: acked ? acked.seq : 0 }, 900, t);
}
return { st, now: t };
}
test('a good connection reads as ok', () => {
const { st, now } = feed();
const s = st.summary(now);
assert.equal(s.ping, 30);
assert.equal(s.gap, 50);
assert.equal(s.oppPing, 40);
assert.ok(s.input >= 50 && s.input <= 120, 'input delay measured: ' + s.input);
assert.ok(s.kbps > 100 && s.kbps < 200, 'bandwidth ~ 900 B x 20/s = 144 kbit/s: ' + s.kbps);
assert.deepEqual(RC.NetStats.verdict(s).map(v => v.key), ['nv_ok']);
});
test('each cause is told apart: my ping, my jitter, opponent, server', () => {
const keys = o => { const { st, now } = feed(o); return RC.NetStats.verdict(st.summary(now)).map(v => v.key); };
assert.deepEqual(keys({ ping: 220 }), ['nv_me_slow']);
assert.deepEqual(keys({ jit: 45 }), ['nv_me_jitter']);
assert.deepEqual(keys({ opp: 300 }), ['nv_opp_slow']);
assert.deepEqual(keys({ tickMs: 12 }), ['nv_server']);
assert.ok(keys({ inDelay: 500 }).includes('nv_queue'));
});
test('outside a fight only the ping counts; a silent server is reported', () => {
const st = RC.NetStats();
st.pong(25, 1000);
assert.deepEqual(RC.NetStats.verdict(st.summary(1500)).map(v => v.key), ['nv_nofight']);
st.snap({ rtt: [25, 25], tickMs: 0.4 }, 500, 2000);
assert.deepEqual(RC.NetStats.verdict(st.summary(9000)).map(v => v.key), ['nv_lost']);
});
test('series gives graph points of the last seconds only', () => {
const { st, now } = feed({ secs: 15 });
const pts = st.series(now, 10);
assert.ok(pts.length > 100);
assert.ok(pts.every(p => now - p.t <= 10000));
});

View File

@@ -10,6 +10,8 @@ test('check accepts valid client messages', () => {
assert.ok(P.check({ t: 'hello', v: 1, token: 'abc' }).ok);
assert.ok(P.check({ t: 'challenge', to: 'u1' }).ok);
assert.ok(P.check({ t: 'challenge.cancel' }).ok);
assert.ok(P.check({ t: 'ping', t0: 123.4 }).ok, 'ping with a timestamp (regression: t was checked instead of t0)');
assert.ok(P.check({ t: 'ping' }).ok);
assert.ok(P.check({ t: 'room', room: 'DE' }).ok);
assert.ok(P.check({ t: 'input', seq: 3, throttle: 1, turn: -0.5, fire: true, fire2: false, fire3: false }).ok);
});
@@ -34,7 +36,7 @@ test('input clamps ranges and coerces flags', () => {
function fakeSnap() {
return {
tick: 10, ack: [4, 7], away: [false, true], time: 1, left: 100, pitOpen: 0, pitAlarm: false, endIn: 0,
tick: 10, ack: [4, 7], away: [false, true], rtt: [20, 140], time: 1, left: 100, pitOpen: 0, pitAlarm: false, endIn: 0,
result: { winner: 0, reason: 'ko' },
press: { st: 'idle', y: 1 }, crane: { st: 'grab', x: 0, z: 0, who: 1 },
rockets: [{ kind: 'rocket', owner: 0, x: 1, z: 2, y: 0.5, a: 0 }],
@@ -62,6 +64,7 @@ test('toLocal for seat 1 mirrors every robot index', () => {
assert.equal(l.result.winner, 1, 'seat 0 won -> for seat 1 the winner is the opponent (local 1)');
assert.equal(l.ack, 7);
assert.deepEqual(l.away, [true, false], 'own connection first');
assert.deepEqual(l.rtt, [140, 20], 'own ping first');
assert.equal(l.crane.who, 0);
assert.equal(l.rockets[0].owner, 1);
assert.equal(l.mines[0].owner, 0);

136
tools/bot.js Normal file
View File

@@ -0,0 +1,136 @@
#!/usr/bin/env node
/* Robot Clash test bot - a dumb fake player for testing online play alone. No AI: it drives a fixed pattern.
It logs in as a guest, waits in the lobby and ACCEPTS every challenge (or challenges a player by name),
fights, and goes back to the lobby. Ctrl+C deletes its guest account again.
npm run bot local server, circles
npm run bot -- --url https://roboclash.michael-media.de --pattern zigzag
npm run bot -- --url https://roboclash.michael-media.de --challenge benni
Options:
--url <server> default http://localhost:8080
--name <name> lobby name (default Bot-<pattern>)
--pattern <p> circle | zigzag | spin | charge | idle (default circle)
--challenge <name> challenge this player whenever both are idle (default: only accept)
--fights <n> stop after n fights (default: run until Ctrl+C)
Diagnosis tip: run the bot ON the server (ssh, then node tools/bot.js --url http://127.0.0.1:8080) - it then has
~0 ms ping, so any lag you see comes from your own connection or the server, not from the opponent.
Also usable as a module (tests): const bot = await startBot({ url, pattern }); ... await bot.stop(); */
'use strict';
const path = require('path');
const WebSocket = require(path.join(__dirname, '..', 'server', 'node_modules', 'ws'));
require(path.join(__dirname, '..', 'game', 'protocol.js'));
const RC = globalThis.RC;
// input per pattern at time t (seconds since the fight started)
const PATTERNS = {
circle: () => ({ throttle: 0.75, turn: 0.55, fire: false }),
zigzag: t => ({ throttle: 1, turn: Math.sin(t * 1.6) > 0 ? 0.8 : -0.8, fire: false }),
spin: () => ({ throttle: 0, turn: 1, fire: false }),
charge: t => ({ throttle: (t % 4) < 2.5 ? 1 : -0.6, turn: (t % 4) < 2.5 ? 0 : 0.9, fire: (t % 4) < 2.5 }),
idle: () => ({ throttle: 0, turn: 0, fire: false }),
};
function args(argv) {
const o = { url: 'http://localhost:8080', pattern: 'circle', name: null, challenge: null, fights: 0 };
for (let i = 0; i < argv.length; i++) {
const k = argv[i].replace(/^--/, ''), v = argv[i + 1];
if (k in o) { o[k] = k === 'fights' ? +v : v; i++; }
}
return o;
}
async function startBot(opt) {
const url = (opt.url || 'http://localhost:8080').replace(/\/+$/, '');
const pattern = PATTERNS[opt.pattern] ? opt.pattern : 'circle';
const drive = PATTERNS[pattern];
const log = opt.quiet ? () => {} : (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
const api = async (method, p, body, token) => {
const r = await fetch(url + p, { method, headers: Object.assign({ 'Content-Type': 'application/json' }, token ? { Authorization: 'Bearer ' + token } : {}), body: body && JSON.stringify(body) });
return r.json().catch(() => null);
};
const acc = await api('POST', '/api/auth/guest', { name: opt.name || 'Bot-' + pattern });
if (!acc || !acc.idToken) throw new Error('guest login failed: ' + JSON.stringify(acc));
log(`logged in as ${acc.name} (${pattern}) at ${url}`);
const ws = new WebSocket(url.replace(/^http/, 'ws') + '/ws');
const send = m => { if (ws.readyState === 1) ws.send(JSON.stringify(m)); };
const players = new Map();
let match = null, timer = null, fights = 0, stopped = false, seq = 0, challengeT = null;
const stats = { snaps: 0, gaps: [], last: 0 };
const done = new Promise(res => { ws.on('close', res); });
function tryChallenge() {
if (!opt.challenge || match || stopped) return;
const target = [...players.values()].find(p => p.name.toLowerCase() === opt.challenge.toLowerCase() && p.state === 'idle');
if (target) { log(`challenging ${target.name}`); send({ t: 'challenge', to: target.uid }); }
}
ws.on('open', () => send({ t: 'hello', v: RC.Proto.VERSION, token: acc.idToken }));
ws.on('message', raw => {
const m = JSON.parse(raw);
switch (m.t) {
case 'welcome': log('connected - waiting in the lobby' + (opt.challenge ? ` for ${opt.challenge}` : ' (accepts every challenge)')); break;
case 'lobby': players.clear(); for (const p of m.players) players.set(p.uid, p); tryChallenge(); break;
case 'lobby.join': case 'lobby.state': players.set(m.player.uid, m.player); tryChallenge(); break;
case 'lobby.leave': players.delete(m.uid); break;
case 'challenge.in': log(`challenged by ${m.name} - accepting`); setTimeout(() => send({ t: 'challenge.accept', from: m.from }), 800); break;
case 'challenge.gone': log(`challenge gone (${m.reason || 'gone'})`); clearTimeout(challengeT); challengeT = setTimeout(tryChallenge, 3000); break;
case 'match.start': {
match = m; seq = 0; stats.snaps = 0; stats.gaps = []; stats.last = 0;
const opp = m.robots[1 - m.seat];
log(`fight vs ${opp.name} in ${m.arena} (seat ${m.seat}), countdown ${m.countdown.toFixed(1)} s`);
const start = Date.now() + m.countdown * 1000;
clearInterval(timer);
timer = setInterval(() => { // 20 inputs per second, like a player holding keys
const t = (Date.now() - start) / 1000;
if (t < 0) return;
const i = RC.Proto.input(drive(t));
send(Object.assign({ t: 'input', seq: ++seq }, i));
}, 50);
break;
}
case 'snap': {
const now = Date.now();
if (stats.last) stats.gaps.push(now - stats.last);
stats.last = now; stats.snaps++;
if (stats.snaps % 200 === 0) {
const g = stats.gaps.slice(-200), avg = g.reduce((a, b) => a + b, 0) / g.length;
const jit = Math.sqrt(g.reduce((a, b) => a + (b - avg) ** 2, 0) / g.length);
const me = RC.Proto.toLocal(match.seat, m);
log(` snapshots every ${avg.toFixed(0)} ms (jitter ${jit.toFixed(0)} ms) · ping bot ${me.rtt[0]} ms, opponent ${me.rtt[1]} ms · server step ${m.tickMs} ms`);
}
break;
}
case 'match.end': {
clearInterval(timer); fights++;
const r = RC.Proto.localResult(m.seat, m.result);
log(`fight over: ${r.winner === -1 ? 'draw' : r.winner === 0 ? 'bot won' : 'bot lost'} (${m.result.reason})`);
match = null;
if (opt.fights && fights >= opt.fights) stop(); else { clearTimeout(challengeT); challengeT = setTimeout(tryChallenge, 4000); }
break;
}
case 'error': log('server says:', m.code); break;
}
});
async function stop() {
if (stopped) return;
stopped = true;
clearInterval(timer); clearTimeout(challengeT);
try { ws.close(); } catch (e) { /* closed */ }
await api('DELETE', '/api/me', undefined, acc.idToken).catch(() => {});
log('bot account deleted, bye');
}
return { uid: acc.uid, name: acc.name, stop, done, get fights() { return fights; }, get inMatch() { return !!match; } };
}
module.exports = { startBot, PATTERNS };
if (require.main === module) {
const o = args(process.argv.slice(2));
startBot(o).then(bot => {
process.on('SIGINT', () => bot.stop().then(() => process.exit(0)));
bot.done.then(() => { if (o.fights) process.exit(0); });
}).catch(e => { console.error(e.message); process.exit(1); });
}

View File

@@ -60,6 +60,9 @@ function client(token) {
const la = RC.Proto.localResult(ea.seat, ea.result).winner, lb = RC.Proto.localResult(eb.seat, eb.result).winner;
ok(la === 1 && lb === 0, `result mirrored: leaver lost, other won (+${eb.reward.money} credits, +${eb.reward.fame} fame)`);
ca.close(); cb.close();
// clean up: the throw-away accounts must not stay in the ranking
const del = await Promise.all([json('DELETE', '/api/me', undefined, a.body.idToken), json('DELETE', '/api/me', undefined, b.body.idToken)]);
ok(del.every(d => d.body && d.body.ok), 'test accounts deleted again');
console.log(failed ? `\n${failed} check(s) failed` : '\nsmoke test passed');
process.exit(failed ? 1 : 0);
})().catch(e => { console.error('FAIL', e.message); process.exit(1); });