Online-Lobby, Arenen, Lackiererei, ComfyGen-Grafik, Verschleierung

Grosse Erweiterung ueber die erste spielbare Version hinaus:

- Online (Firebase ueber REST, kein SDK): Konto per E-Mail, globale Lobby
  mit Laender-Raeumen, Herausfordern, Live-PvP (Host rechnet, Gast
  interpoliert, KI-Uebernahme bei Lag). Gast kann anonym beitreten.
  net.js / lobby.js / netfight.js, Regeln in docs/firebase.
- 3 Arenen in verschiedenen Groessen (RC.ARENAS, half 8/12/16), Kamera +
  Licht + Boden skalieren; Liga skaliert die Arena mit, Setting + online
  aus Seed. Harte Rams/Wandtreffer schleudern Roboter auf den Rucken.
- Intro (3D-Kamerafahrt), Titel, Einstellungen (Kamera, Schwierigkeit,
  Steuerung, Grafik, Arena), Lackiererei (painter.js, selbst bemalen).
- Shop mit ComfyGen-Sprites (aus den 3D-Teilen erzeugt), Liga-Gegner sehen
  aus wie ihre Portraits (looks.js), kraeftigere Waffen-Modelle.
- Oekonomie: Startgeld 800, Schadensbonus, Schaukaempfe, Online-Preisgeld.
- Verschleierung: build.ps1 -Obfuscate (terser), tablet-taugliche Touch-UI.
- Tests: tests/sim.test.js, balance.js, online.test.js. Dev-Tools in tools/.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-13 15:45:35 +01:00
parent 819ee0a5c3
commit 7a69651b6d
60 changed files with 1895 additions and 207 deletions

2
.gitignore vendored
View File

@@ -5,3 +5,5 @@ sprite-generator/output/
sprite-generator/__pycache__/ sprite-generator/__pycache__/
node_modules/ node_modules/
*.log *.log
tools/shots/
.claude/

View File

@@ -17,15 +17,24 @@ keine Namen, Figuren, Arenen, Hausroboter, Grafiken, Sounds oder Code aus dem Or
Hauptwaffe (Keil, Flipper, Axt, Säge, Zange, Spinner) und Turm (Flammen, Minigun, Raketen). Max. 100 kg, Hauptwaffe (Keil, Flipper, Axt, Säge, Zange, Spinner) und Turm (Flammen, Minigun, Raketen). Max. 100 kg,
Batterie muss den Strom liefern. Kaufen / einbauen / verkaufen (50 %), Lack + Akzentfarbe, Name. Batterie muss den Strom liefern. Kaufen / einbauen / verkaufen (50 %), Lack + Akzentfarbe, Name.
2. **Liga:** 8 KI-Gegner nacheinander (Stile: Raufbold, Flankierer, Schieber, Schütze), steigende Preise. 2. **Liga:** 8 KI-Gegner nacheinander (Stile: Raufbold, Flankierer, Schieber, Schütze), steigende Preise.
3. **Kampf (2 min, isometrisch 3D):** Arena mit Stachelwänden, 2 Bodensägen, 2 Flammengittern, 2 Arena-Wächtern 3. **Kampf (2 min, isometrisch 3D):** 3 Arenen in verschiedenen Größen (`RC.ARENAS` in combat.js: Werkstatt-Grube
in den Ecken (Schmiedepresse, Magnetkran) und einer Grube, die zur Halbzeit aufgeht. half 8, Gießerei half 12, Mega-Dome half 16), je mit Stachelwänden, Bodensägen, Flammengittern, 2 Wächtern
(Schmiedepresse, Magnetkran) und einer Grube ab Halbzeit. Liga skaliert die Arena mit dem Gegner, Einstellung
`arena` (Zufällig/fest), online aus dem Seed. Kamera + Licht + Boden skalieren mit `half`. Harte Rammstöße und
Wandtreffer können Roboter auf den Rücken schleudern (`flipped`).
4. **Sieg:** K.o., Gegner in der Grube, oder nach Zeit über Schaden (Fallen-Schaden zählt für den Gegner). 4. **Sieg:** K.o., Gegner in der Grube, oder nach Zeit über Schaden (Fallen-Schaden zählt für den Gegner).
5. **Ergebnis:** Preisgeld (+ K.o./Gruben-Bonus) bzw. Antrittsgeld, Reparaturkosten, Ruhm → zurück in die Werkstatt. 5. **Ergebnis:** Preisgeld (+ K.o./Gruben-Bonus) bzw. Antrittsgeld (35 %), Schadensbonus (0,6 Credits je Schaden,
auch bei Niederlage), Reparatur (6 % Teilewert × Schaden), Ruhm → zurück in die Werkstatt. Start: 800 Credits.
6. **Schaukampf:** besiegte Gegner beliebig oft nochmal – halbes Preisgeld, kein Liga-Fortschritt (Geld verdienen).
**Ziel / Ende:** Meister der Saison (alle 8 besiegt) → neue Saison, Gegner stärker, Preise ×1,5. Ruhm = Punktestand **Ziel / Ende:** Meister der Saison (alle 8 besiegt) → neue Saison, Gegner stärker, Preise ×1,5. Ruhm = Punktestand
(Online-Rangliste über `Kit.scores`, sobald `DB_URL` gesetzt ist). (Online-Rangliste über `Kit.scores`, sobald `DB_URL` gesetzt ist).
**Steuerung:** WASD/Pfeile Panzersteuerung, Leertaste Hauptwaffe, Shift/E Turm, P/Esc Pause, M Ton; Gamepad **Steuerung:** Standard „Panzer“ (W/S fahren, A/D drehen; Michael wollte das ausdrücklich zurück). Option „Einfach“: WASD = Bildschirmrichtung, Roboter dreht sich selbst hin
– liegt das Ziel hinter dem Roboter, fährt er rückwärts statt zu wenden.
Kamera (Taste C / Einstellung): Standard Cockpit (Ego-Sicht, Wunsch Michael) · Arena (iso) · Verfolger – in Verfolger/Cockpit gilt W/S fahren, A/D drehen,
dazu Minikarte unten rechts. Waffen-Hilfe (Standard an) feuert in Reichweite automatisch. Schwierigkeit
Leicht (Standard: Spieler-LP ×1,4, KI −0,2) / Normal / Schwer (`DIFF` in game.js). Leertaste Hauptwaffe, Shift/E Turm, P/Esc Pause, M Ton; Gamepad
(Stick, A Waffe, B Turm, Start Pause); Touch-Knöpfe auf Touchgeräten. (Stick, A Waffe, B Turm, Start Pause); Touch-Knöpfe auf Touchgeräten.
**Stil:** Industrielle Show-Arena bei Nacht, Flutlicht, kantige Bastel-Roboter aus Blech, Funken, Warnstreifen. **Stil:** Industrielle Show-Arena bei Nacht, Flutlicht, kantige Bastel-Roboter aus Blech, Funken, Warnstreifen.
@@ -38,14 +47,25 @@ Speichern, en/de, Synth-Sounds. **Später:** Firebase-Rangliste (URL von Michael
Roboter, KI-gesteuert), echtes PvP (WebRTC), Replays/Zuschauer, weitere Arenen + Gewichtsklassen, Icon/Musik/SFX Roboter, KI-gesteuert), echtes PvP (WebRTC), Replays/Zuschauer, weitere Arenen + Gewichtsklassen, Icon/Musik/SFX
über ComfyGen, Schrift „Russo One“ lokal in `assets/Fonts`. über ComfyGen, Schrift „Russo One“ lokal in `assets/Fonts`.
**Online (Firebase, optional):** Titel → „Online spielen" (nur wenn `NET_CFG.apiKey` gesetzt), Login per
E-Mail/Passwort, globale Lobby (alle Online-Spieler + Länderflagge), Klick auf Spieler = Herausfordern → Live-Kampf.
Rangliste läuft schon mit `DB_URL` allein. Einrichtung + Grenzen: `docs/firebase/README.md`.
**Verschleierung:** `.\build.ps1 -Web -Obfuscate` jagt die eigenen Skripte durch terser (lokal via `npm install`).
Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
**Tablet:** Touch-Steuerung (#pad), große Tap-Ziele; bei jeder neuen UI mitdenken.
## Dateien ## Dateien
- `game/parts.js` Teilekatalog · `game/robot.js` Bauregeln + Werte · `game/combat.js` Physik, Waffen, Fallen, - `game/parts.js` Teilekatalog · `game/robot.js` Bauregeln + Werte · `game/combat.js` Physik, Waffen, Fallen,
Siegregeln · `game/ai.js` KI + Liga-Kader – alle ohne DOM, laufen in Node. Siegregeln · `game/ai.js` KI + Liga-Kader – alle ohne DOM, laufen in Node.
- `game/render3d.js` three.js-Szenen (Werkstatt, Arena), Roboter-Modelle aus Teilen, Partikel. - `game/render3d.js` three.js-Szenen (Werkstatt, Arena), Roboter-Modelle aus Teilen, Partikel.
- `game/shop.js` Werkstatt-Shop (Kategorien, Teile-Karten mit Sprites, Detail mit Vergleich, Mechaniker-Tipps) - `game/shop.js` Werkstatt-Shop (Kategorien, Teile-Karten mit Sprites, Detail mit Vergleich, Mechaniker-Tipps)
· `game/net.js` Firebase über REST (Auth + RTDB + Server-Sent-Events, kein SDK) · `game/lobby.js` globale Lobby (Präsenz/Heartbeat, Herausfordern, Match) · `game/netfight.js` Live-PvP-Sync (Host rechnet + sendet Snapshots ~15/s, Gast interpoliert, KI-Übernahme bei Lag)
· `game/painter.js` Lackiererei: selbst auf den Roboter malen (Ebene 512×256: links Draufsicht, rechts Seite, · `game/painter.js` Lackiererei: selbst auf den Roboter malen (Ebene 512×256: links Draufsicht, rechts Seite,
Front jeweils rechts), 3D-Vorschau live; gespeichert als PNG-Data-URL in `save.paint.decal` Front jeweils rechts), 3D-Vorschau live; gespeichert als PNG-Data-URL in `save.paint.decal`
· `game/looks.js` Aussehen der Liga-Gegner passend zu ihren Porträts (Skin-Muster + Augen, Kabine, Höcker, Ketten-Optik)
· `game/profiles.js` Konten (v1 lokal: Name + Passwort-Hash, je Konto eigener Spielstand; später Firebase) · `game/profiles.js` Konten (v1 lokal: Name + Passwort-Hash, je Konto eigener Spielstand; später Firebase)
· `game/game.js` Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Registrieren/Gast → Shop → Liga/VS → Kampf → Ergebnis, Einstellungen. · `game/game.js` Ablauf: Intro (3D-Kamerafahrt) → Titel → Login/Registrieren/Gast → Shop → Liga/VS → Kampf → Ergebnis, Einstellungen.
- `game/vendor/three.min.js` three.js r149 (MIT, letzte Version mit klassischem Build – nicht auf ES-Module updaten). - `game/vendor/three.min.js` three.js r149 (MIT, letzte Version mit klassischem Build – nicht auf ES-Module updaten).
@@ -53,7 +73,7 @@ Roboter, KI-gesteuert), echtes PvP (WebRTC), Replays/Zuschauer, weitere Arenen +
- Grafik/Sound: `sprite-generator/prompts.py` + `audio.py` → `gen generate`, `gen adopt --all` (Sprites), `gen adopt_scene bg_*` (Hintergründe als JPG), - Grafik/Sound: `sprite-generator/prompts.py` + `audio.py` → `gen generate`, `gen adopt --all` (Sprites), `gen adopt_scene bg_*` (Hintergründe als JPG),
`gen make_tileable tex_floor`, `gen adopt_audio --all`. Fehlende Bilder → Ersatz-Symbol (`RC.pic`), fehlende Sounds → Synth. `gen make_tileable tex_floor`, `gen adopt_audio --all`. Fehlende Bilder → Ersatz-Symbol (`RC.pic`), fehlende Sounds → Synth.
- Dev-Parameter: `index.html?title` (Titel ohne Intro), `?play` (Shop als Gast), `?fight=N` (Training gegen Liga-Gegner N), `&auto` (KI fährt - Dev-Parameter: `index.html?title` (Titel ohne Intro), `?play` (Shop als Gast), `?fight=N` (Training gegen Liga-Gegner N), `&auto` (KI fährt
für dich), `&ff=30` (30 s vorspulen). für dich), `&ff=30` (30 s vorspulen), `&cam=chase|fpv` (Kamera).
## Arbeitsweise ## Arbeitsweise

View File

@@ -12,7 +12,8 @@ Angelegt am 2026-11-13 aus `_Tools\Library` (Vorlage `webgame`). Sprachen: Engli
| Taste | Wirkung | | Taste | Wirkung |
|---|---| |---|---|
| W A S D / Pfeile | fahren (Panzersteuerung) | | W A S D / Pfeile | fahren (Einfach: Bildschirmrichtung · Panzer / Verfolger / Cockpit: W/S fahren, A/D drehen) |
| C | Kamera: Arena · Verfolger · Cockpit |
| Leertaste | Hauptwaffe (Säge/Spinner: halten) | | Leertaste | Hauptwaffe (Säge/Spinner: halten) |
| Shift / E | Turmwaffe | | Shift / E | Turmwaffe |
| P / Esc | Pause | | P / Esc | Pause |
@@ -20,7 +21,7 @@ Angelegt am 2026-11-13 aus `_Tools\Library` (Vorlage `webgame`). Sprachen: Engli
| Gamepad | Stick fahren, A Waffe, B Turm, Start Pause | | Gamepad | Stick fahren, A Waffe, B Turm, Start Pause |
Dev-Parameter: `index.html?title` (Titel ohne Intro), `?play` (direkt in den Shop, als Gast), `?play&paint` (Lackiererei mit Testbild), `?fight=N` (Training gegen Liga-Gegner N = 0…7), Dev-Parameter: `index.html?title` (Titel ohne Intro), `?play` (direkt in den Shop, als Gast), `?play&paint` (Lackiererei mit Testbild), `?fight=N` (Training gegen Liga-Gegner N = 0…7),
`&auto` (KI fährt deinen Roboter), `&ff=30` (30 Sekunden vorspulen). `&auto` (KI fährt deinen Roboter), `&ff=30` (30 Sekunden vorspulen), `&cam=chase|fpv` (Kamera).
Tests (Node, ohne Browser): `node tests/sim.test.js` · Balance-Zahlen: `node tests/balance.js -v` Tests (Node, ohne Browser): `node tests/sim.test.js` · Balance-Zahlen: `node tests/balance.js -v`
@@ -31,7 +32,11 @@ game/
index.html Seite, HUD, Werkstatt-Panel, Overlays (Styles inline) index.html Seite, HUD, Werkstatt-Panel, Overlays (Styles inline)
game.js Ablauf: Intro, Titel, Konten, Einstellungen, Shop, Liga, Kampf, Ergebnis game.js Ablauf: Intro, Titel, Konten, Einstellungen, Shop, Liga, Kampf, Ergebnis
shop.js Werkstatt-Shop (Teile kaufen/einbauen/verkaufen, Vergleich, Lack, Mechaniker) shop.js Werkstatt-Shop (Teile kaufen/einbauen/verkaufen, Vergleich, Lack, Mechaniker)
looks.js Aussehen der Liga-Gegner (wie ihre Porträts)
painter.js Lackiererei: selbst auf den Roboter malen, live in 3D painter.js Lackiererei: selbst auf den Roboter malen, live in 3D
net.js Firebase über REST (Login, Datenbank, Push) – für Online
lobby.js globale Online-Lobby (wer ist da, herausfordern)
netfight.js Live-PvP-Synchronisation
profiles.js Konten: registrieren, einloggen, Gast (lokal, später Firebase) profiles.js Konten: registrieren, einloggen, Gast (lokal, später Firebase)
parts.js Teilekatalog (Werte, Preise) ┐ parts.js Teilekatalog (Werte, Preise) ┐
robot.js Bauregeln + Kampfwerte aus Teilen │ ohne DOM, robot.js Bauregeln + Kampfwerte aus Teilen │ ohne DOM,
@@ -51,11 +56,17 @@ build-web.mjs → release/robotclash.html (alles in einer Datei)
build.ps1 → release/RobotClash.exe + robotclash.html + robotclash-web.zip build.ps1 → release/RobotClash.exe + robotclash.html + robotclash-web.zip
``` ```
## Online (optional)
Rangliste läuft mit der Firebase-DB-URL allein. Für die Lobby + Live-PvP den Web-API-Key in
`game/game.js` (`NET_CFG.apiKey`) eintragen – Anleitung `docs/firebase/README.md`.
## Release ## Release
```powershell ```powershell
.\build.ps1 # exe + html + zip .\build.ps1 # exe + html + zip
.\build.ps1 -Web # nur html + zip .\build.ps1 -Web # nur html + zip
.\build.ps1 -Web -Obfuscate # zusätzlich Skripte verschleiern (braucht einmal: npm install)
``` ```
## Kit aktualisieren ## Kit aktualisieren

View File

@@ -39,8 +39,28 @@ const safe = s => s.replace(/<\/script/gi, '<\\/script');
html = html.replace(/<link\s+rel="stylesheet"\s+href="([^"]+)"\s*\/?>/g, (m, p) => html = html.replace(/<link\s+rel="stylesheet"\s+href="([^"]+)"\s*\/?>/g, (m, p) =>
local(p) ? `<style>\n${fs.readFileSync(path.join(game, p), 'utf8')}\n</style>` : m); local(p) ? `<style>\n${fs.readFileSync(path.join(game, p), 'utf8')}\n</style>` : m);
html = html.replace(/<script\s+src="([^"]+)"\s*><\/script>/g, (m, p) => // optional: run each own script through terser (mangle locals, compress) -> harder to read.
local(p) ? `<script>\n${safe(fs.readFileSync(path.join(game, p), 'utf8'))}\n</script>` : m); // Enabled with RC_OBFUSCATE=1 (build.ps1 -Obfuscate). vendor/three.min.js is already minified -> skip.
const obf = process.env.RC_OBFUSCATE === '1';
let terser = null;
if (obf) {
try { terser = await import('terser'); }
catch { console.error('RC_OBFUSCATE=1 but terser is missing - run: npm install'); process.exit(1); }
}
const minify = async (code, name) => {
if (!terser || /vendor\/three/.test(name)) return code;
const r = await terser.minify(code, { compress: true, mangle: true, format: { comments: false } });
if (r.error) { console.error(`terser failed on ${name}:`, r.error); process.exit(1); }
return r.code;
};
const scriptJobs = [];
html = html.replace(/<script\s+src="([^"]+)"\s*><\/script>/g, (m, p) => {
if (!local(p)) return m;
const token = `\u0000SCRIPT${scriptJobs.length}\u0000`;
scriptJobs.push(minify(fs.readFileSync(path.join(game, p), 'utf8'), p).then(code => [token, `<script>\n${safe(code)}\n</script>`]));
return token;
});
for (const [token, tag] of await Promise.all(scriptJobs)) html = html.replace(token, () => tag);
// static references in CSS / HTML attributes // static references in CSS / HTML attributes
html = html.replace(/url\((['"]?)(assets\/[^'")]+)\1\)/g, (m, q, p) => (assets[p] ? `url('${assets[p]}')` : m)); html = html.replace(/url\((['"]?)(assets\/[^'")]+)\1\)/g, (m, q, p) => (assets[p] ? `url('${assets[p]}')` : m));
html = html.replace(/(src|href)="(assets\/[^"]+)"/g, (m, a, p) => (assets[p] ? `${a}="${assets[p]}"` : m)); html = html.replace(/(src|href)="(assets\/[^"]+)"/g, (m, a, p) => (assets[p] ? `${a}="${assets[p]}"` : m));

View File

@@ -4,7 +4,7 @@
# robotclash-web.zip upload package for itch.io & co (the page as index.html) # robotclash-web.zip upload package for itch.io & co (the page as index.html)
# Needs .NET 8+ SDK and Node. The PC running the exe needs the Edge WebView2 Runtime (Win 10/11 has it). # Needs .NET 8+ SDK and Node. The PC running the exe needs the Edge WebView2 Runtime (Win 10/11 has it).
# .\build.ps1 all .\build.ps1 -Web only HTML + zip .\build.ps1 -Exe only exe # .\build.ps1 all .\build.ps1 -Web only HTML + zip .\build.ps1 -Exe only exe
param([switch]$Web, [switch]$Exe) param([switch]$Web, [switch]$Exe, [switch]$Obfuscate)
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$root = $PSScriptRoot $root = $PSScriptRoot
$out = Join-Path $root 'release' $out = Join-Path $root 'release'
@@ -29,6 +29,8 @@ if ($Exe) {
} }
if ($Web) { if ($Web) {
# -Obfuscate: minify/mangle own scripts in the single-file HTML (needs `npm install`, terser)
$env:RC_OBFUSCATE = if ($Obfuscate) { '1' } else { '0' }
node (Join-Path $root 'build-web.mjs') node (Join-Path $root 'build-web.mjs')
if ($LASTEXITCODE -ne 0) { throw "web build failed ($LASTEXITCODE)" } if ($LASTEXITCODE -ne 0) { throw "web build failed ($LASTEXITCODE)" }
$tmp = Join-Path $env:TEMP 'robotclash-web' $tmp = Join-Path $env:TEMP 'robotclash-web'

View File

@@ -1,26 +1,36 @@
# Online-Highscores (Firebase Realtime Database) # Firebase: Rangliste + Online-Lobby (ohne SDK, reines REST)
Das Spiel spricht die Datenbank über die REST-API an (`game/kit/kit-scores.js`), ohne SDK und ohne Login. Das Spiel spricht Firebase komplett über REST an (`game/net.js`, `game/kit/kit-scores.js`) – kein SDK,
Solange `DB_URL` in `game/game.js` leer ist, läuft alles offline (keine Namenseingabe, keine Liste). läuft per `file://` und als eine HTML-Datei.
## Einrichten (einmal, ~5 Minuten) - **Rangliste** braucht nur die DB-URL (`DB_URL` in `game/game.js`), **kein Login**.
- **Online-Lobby + Live-PvP** braucht zusätzlich den **Web-API-Key** (`NET_CFG.apiKey`) und aktivierte
Anmeldung. Ohne Key bleibt der „Online spielen"-Knopf aus; der Rest funktioniert.
1. [Firebase-Konsole](https://console.firebase.google.com/) → **Projekt hinzufügen** (Name z. B. `robotclash`, Analytics aus). ## Einrichten
2. **Build → Realtime Database → Datenbank erstellen** → Standort **europe-west1** → „Im gesperrten Modus starten“.
3. Tab **Regeln**: alles durch den Inhalt von `database.rules.json` ersetzen → **Veröffentlichen**. 1. [Firebase-Konsole](https://console.firebase.google.com/) → Projekt `robot-clash-aa37b` (schon angelegt).
4. Die URL oben im Tab **Daten** (`https://<projekt>-default-rtdb.europe-west1.firebasedatabase.app`) 2. **Realtime Database** (Standort europe-west1 o. ä.): Tab **Regeln** → Inhalt von `database.rules.json`
in `game/game.js` bei `DB_URL` eintragen. einfügen → **Veröffentlichen**. Die DB-URL ist schon in `game/game.js` eingetragen
(`https://robot-clash-aa37b-default-rtdb.firebaseio.com`).
3. **Für die Lobby:** **Authentication → Anmeldemethode** → **E-Mail/Passwort** aktivieren
(optional **Anonym** für Gast-Login).
4. **Web-API-Key** holen: ⚙ **Projekteinstellungen → Allgemein → Web-API-Schlüssel** (beginnt mit `AIza…`).
In `game/game.js` bei `NET_CFG = { apiKey: '…' }` eintragen → `.\build.ps1 -Web -Obfuscate` neu bauen.
(Der Web-API-Key ist **nicht geheim**; er darf im Client stehen. Geschützt wird über die DB-Regeln.)
## Was die Regeln erlauben ## Was die Regeln erlauben
- Lesen: nur `highscores` (sortiert/begrenzt nach `score`). - `highscores`: lesen offen, nur **neue** Einträge schreiben (Format/Bereich geprüft).
- Schreiben: nur **neue** Einträge unter `highscores` – bestehende können nicht geändert/gelöscht werden. - `users/$uid`, `lobby/$uid`, `matches/$id`, `challenges`: nur eingeloggte Nutzer; jeder schreibt nur seinen
- Jeder Eintrag hat genau `name` (1–20 Zeichen), `score` (1–10 000 000), `level` (1–999), `time` (Server-Zeit). eigenen Lobby-Eintrag / seine Eingaben; den Kampf-Zustand schreibt nur der **Host** (kleinere uid).
## Grenzen ## Grenzen (ehrlich)
Punkte lassen sich per Hand-Request fälschen; die Regeln prüfen nur Format und Bereich. Echter Schutz - Client-Code ist im Browser immer lesbar/ladbar. `-Obfuscate` erschwert das nur, verhindert es nicht.
bräuchte eine Server-Prüfung (Cloud Function). Einträge löschen: Konsole → **Daten** → `highscores` → Echter Schutz liegt serverseitig (Auth + Regeln).
Eintrag → ⋮ / Papierkorb. Schimpfwort-Namen blockt `Kit.badName` bei der Eingabe und blendet sie in der Liste aus. - Punkte/Daten lassen sich per Hand-Request fälschen; die Regeln prüfen nur Format/Besitzer, keine Spiel-Logik.
Fälschungssicher nur mit Cloud Functions (nicht eingebaut).
Referenz im Einsatz: `D:\Oculusquest\Projekt\Pipefix\docs\firebase\`. - Live-PvP: der Host schreibt ~15 Snapshots/s (~1800 Writes pro 2-Minuten-Kampf). Für wenige gleichzeitige
Kämpfe im Spark-Gratis-Tarif ok; bei vielen Spielern RTDB-Nutzung im Blick behalten.
- Stockt der Gegner > 1,5 s, übernimmt die KI seinen Roboter, der Kampf läuft zu Ende.

View File

@@ -2,6 +2,7 @@
"rules": { "rules": {
".read": false, ".read": false,
".write": false, ".write": false,
"highscores": { "highscores": {
".read": true, ".read": true,
".indexOn": ["score"], ".indexOn": ["score"],
@@ -14,6 +15,48 @@
"time": { ".validate": "newData.val() == now" }, "time": { ".validate": "newData.val() == now" },
"$other": { ".validate": false } "$other": { ".validate": false }
} }
},
"users": {
"$uid": {
".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid"
}
},
"lobby": {
".read": "auth != null",
"$uid": {
".write": "auth != null && auth.uid == $uid",
".validate": "newData.hasChildren(['name', 'ts'])",
"name": { ".validate": "newData.isString() && newData.val().length <= 20" },
"flag": { ".validate": "newData.isString() && newData.val().length <= 4" },
"ts": { ".validate": "newData.isNumber()" },
"$other": { ".validate": true }
}
},
"challenges": {
"$to": {
".read": "auth != null && auth.uid == $to",
"$from": {
".write": "auth != null && (auth.uid == $from || auth.uid == $to)",
".validate": "!newData.exists() || (newData.child('from').val() == $from)"
}
}
},
"matches": {
"$id": {
".read": "auth != null && $id.contains(auth.uid)",
".write": "auth != null && $id.contains(auth.uid)",
"state": {
".validate": "$id.beginsWith(auth.uid + '_')"
},
"in": {
".validate": "$id.endsWith('_' + auth.uid)"
}
}
} }
} }
} }

View File

@@ -114,21 +114,21 @@
const pal = (body, accent) => ({ body, accent }); const pal = (body, accent) => ({ body, accent });
RC.LEAGUE = [ RC.LEAGUE = [
{ id: 'rustbucket', name: 'Rustbucket', style: 'brawler', skill: 0.15, prize: 180, { id: 'rustbucket', name: 'Rustbucket', style: 'brawler', skill: 0.1, prize: 250,
build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'wedge', tower: null }, paint: pal(0x8a5a3a, 0xd9a066) }, build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'wedge', tower: null }, paint: pal(0x8a5a3a, 0xd9a066) },
{ id: 'tintoad', name: 'Tin Toad', style: 'pusher', skill: 0.25, prize: 240, { id: 'tintoad', name: 'Tin Toad', style: 'pusher', skill: 0.2, prize: 330,
build: { chassis: 'doorstop', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'wedge', tower: null }, paint: pal(0x5d8a3a, 0xc8e070) }, build: { chassis: 'doorstop', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'wedge', tower: null }, paint: pal(0x5d8a3a, 0xc8e070) },
{ id: 'buzzkill', name: 'Buzzkill', style: 'brawler', skill: 0.35, prize: 320, { id: 'buzzkill', name: 'Buzzkill', style: 'brawler', skill: 0.3, prize: 430,
build: { chassis: 'crate', motor: 'hornet', wheels: 'rubber', battery: 'nicd', armour: 'steel', weapon: 'saw', tower: null }, paint: pal(0xd8b020, 0x202020) }, build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'saw', tower: null }, paint: pal(0xd8b020, 0x202020) },
{ id: 'flapjack', name: 'Flapjack', style: 'flanker', skill: 0.45, prize: 420, { id: 'flapjack', name: 'Flapjack', style: 'flanker', skill: 0.38, prize: 560,
build: { chassis: 'doorstop', motor: 'hornet', wheels: 'bigtyre', battery: 'nicd', armour: 'steel', weapon: 'flipper', tower: null }, paint: pal(0x2a6fd8, 0xffffff) }, build: { chassis: 'doorstop', motor: 'sparky', wheels: 'bigtyre', battery: 'lead', armour: null, weapon: 'flipper', tower: null }, paint: pal(0x2a6fd8, 0xffffff) },
{ id: 'pincer', name: 'Pincer', style: 'pusher', skill: 0.55, prize: 540, { id: 'pincer', name: 'Pincer', style: 'pusher', skill: 0.55, prize: 700,
build: { chassis: 'bulwark', motor: 'bulldog', wheels: 'tracks', battery: 'nicd', armour: 'steel', weapon: 'crusher', tower: null }, paint: pal(0xc0392b, 0xf0c040) }, build: { chassis: 'bulwark', motor: 'bulldog', wheels: 'tracks', battery: 'nicd', armour: 'steel', weapon: 'crusher', tower: null }, paint: pal(0xc0392b, 0xf0c040) },
{ id: 'thunderclap', name: 'Thunderclap', style: 'brawler', skill: 0.65, prize: 680, { id: 'thunderclap', name: 'Thunderclap', style: 'brawler', skill: 0.65, prize: 880,
build: { chassis: 'bulwark', motor: 'hornet', wheels: 'bigtyre', battery: 'nicd', armour: 'titan', weapon: 'hammer', tower: 'flamer' }, paint: pal(0x6a3fb0, 0xffa020) }, build: { chassis: 'bulwark', motor: 'hornet', wheels: 'bigtyre', battery: 'nicd', armour: 'titan', weapon: 'hammer', tower: 'flamer' }, paint: pal(0x6a3fb0, 0xffa020) },
{ id: 'gravedigger', name: 'Gravedigger', style: 'gunner', skill: 0.8, prize: 860, { id: 'gravedigger', name: 'Gravedigger', style: 'brawler', skill: 0.8, prize: 1100,
build: { chassis: 'scarab', motor: 'hornet', wheels: 'tracks', battery: 'lipo', armour: 'titan', weapon: 'wedge', tower: 'rockets' }, paint: pal(0x2b2f36, 0x50e080) }, build: { chassis: 'scarab', motor: 'hornet', wheels: 'tracks', battery: 'lipo', armour: 'titan', weapon: 'flipper', tower: 'rockets' }, paint: pal(0x2b2f36, 0x50e080) },
{ id: 'overlord', name: 'Overlord', style: 'flanker', skill: 0.95, prize: 1200, { id: 'overlord', name: 'Overlord', style: 'flanker', skill: 0.95, prize: 1450,
build: { chassis: 'scarab', motor: 'comet', wheels: 'rubber', battery: 'lipo', armour: 'steel', weapon: 'spinner', tower: null }, paint: pal(0x101418, 0xff3030) }, build: { chassis: 'scarab', motor: 'comet', wheels: 'rubber', battery: 'lipo', armour: 'steel', weapon: 'spinner', tower: null }, paint: pal(0x101418, 0xff3030) },
]; ];
RC.DUMMY = { id: 'dummy', name: 'Dummy', style: 'dummy', skill: 0, prize: 0, RC.DUMMY = { id: 'dummy', name: 'Dummy', style: 'dummy', skill: 0, prize: 0,

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 281 KiB

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 71 KiB

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 22 KiB

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

View File

@@ -12,17 +12,36 @@
'use strict'; 'use strict';
const RC = (root.RC = root.RC || {}); const RC = (root.RC = root.RC || {});
const ARENA = (RC.ARENA = { // Arena definitions. `half` = floor from -half..half. Hazards scale with the size. The active arena is
half: 8, // floor from -8..8 // RC.ARENA; a fight snapshots it into s.arena so several arenas can exist. render3d.js reads s.arena.
duration: 120, // seconds function arena(o) {
pitOpensAt: 60, // seconds left when the pit opens const h = o.half, g = h - 1.75; // guardian corners
pit: { x: 0, z: 4.6, hw: 1.35, hd: 1.35 }, return {
saws: [{ x: -3.2, z: -3.4, r: 0.95, period: 6, on: 2.2, phase: 0 }, { x: 3.2, z: -3.4, r: 0.95, period: 6, on: 2.2, phase: 3 }], id: o.id, name: o.name, theme: o.theme || 'steel', half: h,
flames: [{ x: -2.7, z: 3.3, hw: 0.9, hd: 0.9, period: 7, on: 1.8, phase: 1 }, { x: 2.7, z: 3.3, hw: 0.9, hd: 0.9, period: 7, on: 1.8, phase: 4.5 }], duration: 120, pitOpensAt: 60,
press: { x: 6.25, z: -6.25, hw: 1.6, hd: 1.6 }, // guardian 1: forge press (corner) pit: { x: 0, z: o.pitZ != null ? o.pitZ : h * 0.52, hw: o.pitW || 1.35, hd: o.pitW || 1.35 },
crane: { x: -6.25, z: 6.25, hw: 1.6, hd: 1.6 }, // guardian 2: magnet crane (corner) saws: o.saws, flames: o.flames,
starts: [{ x: -5, z: 1.5, a: 0 }, { x: 5, z: 1.5, a: Math.PI }], press: { x: g, z: -g, hw: 1.6, hd: 1.6 }, // guardian 1: forge press (corner)
}); crane: { x: -g, z: g, hw: 1.6, hd: 1.6 }, // guardian 2: magnet crane (corner)
starts: [{ x: -h * 0.6, z: h * 0.2, a: 0 }, { x: h * 0.6, z: h * 0.2, a: Math.PI }],
};
}
const saw = (x, z, phase) => ({ x, z, r: 0.95, period: 6, on: 2.2, phase });
const flame = (x, z, phase) => ({ x, z, hw: 0.9, hd: 0.9, period: 7, on: 1.8, phase });
RC.ARENAS = [
arena({ id: 'workshop', name: 'Workshop Pit', theme: 'steel', half: 8,
saws: [saw(-3.2, -3.4, 0), saw(3.2, -3.4, 3)],
flames: [flame(-2.7, 3.3, 1), flame(2.7, 3.3, 4.5)] }),
arena({ id: 'foundry', name: 'The Foundry', theme: 'lava', half: 12, pitW: 1.7,
saws: [saw(-5, -4.5, 0), saw(5, -4.5, 3), saw(0, 4.5, 1.5)],
flames: [flame(-4.5, 1, 0), flame(4.5, 1, 3.5), flame(0, -7.5, 2), flame(-7, 6, 5)] }),
arena({ id: 'arena64', name: 'Mega Dome', theme: 'blue', half: 16, pitW: 2.1,
saws: [saw(-6.5, -6, 0), saw(6.5, -6, 3), saw(-6.5, 6, 1.5), saw(6.5, 6, 4.5), saw(0, 0, 2)],
flames: [flame(-8, 2, 0), flame(8, 2, 2), flame(0, 9, 4), flame(0, -9, 1), flame(-10, -4, 3), flame(10, -4, 5)] }),
];
let ARENA = RC.ARENAS[0];
RC.ARENA = ARENA;
RC.setArena = id => { ARENA = RC.ARENAS.find(a => a.id === id) || RC.ARENAS[0]; RC.ARENA = ARENA; return ARENA; };
const G = 22; // gravity const G = 22; // gravity
const clamp = (v, a, b) => (v < a ? a : v > b ? b : v); const clamp = (v, a, b) => (v < a ? a : v > b ? b : v);
@@ -35,8 +54,8 @@
const hazardOn = (h, t) => ((t + h.phase) % h.period) < h.on; const hazardOn = (h, t) => ((t + h.phase) % h.period) < h.on;
RC.hazardOn = hazardOn; RC.hazardOn = hazardOn;
function makeRobot(st, i, name) { function makeRobot(st, i, name, A) {
const p = ARENA.starts[i]; const p = A.starts[i];
return { return {
i, name, st, x: p.x, z: p.z, a: p.a, vx: 0, vz: 0, av: 0, y: 0, vy: 0, i, name, st, x: p.x, z: p.z, a: p.a, vx: 0, vz: 0, av: 0, y: 0, vy: 0,
hp: st.hp, maxHp: st.hp, dead: false, out: null, fall: 0, hp: st.hp, maxHp: st.hp, dead: false, out: null, fall: 0,
@@ -47,12 +66,13 @@
} }
function create(opt) { function create(opt) {
const A = opt.arena ? (RC.ARENAS.find(a => a.id === opt.arena) || RC.ARENA) : RC.ARENA;
const s = { const s = {
t: 0, left: ARENA.duration, pitOpen: 0, rand: rng(opt.seed || 1), arena: A, t: 0, left: A.duration, pitOpen: 0, rand: rng(opt.seed || 1),
robots: opt.robots.map((st, i) => makeRobot(st, i, (opt.names || [])[i] || 'Robot ' + (i + 1))), robots: opt.robots.map((st, i) => makeRobot(st, i, (opt.names || [])[i] || 'Robot ' + (i + 1), A)),
rockets: [], events: [], result: null, endIn: 0, rockets: [], events: [], result: null, endIn: 0,
press: { st: 'idle', t: 0, y: 1 }, // idle | warn | slam | up ; y 1 = top, 0 = floor press: { st: 'idle', t: 0, y: 1 }, // idle | warn | slam | up ; y 1 = top, 0 = floor
crane: { st: 'idle', t: 0, who: -1, tx: 0, tz: 0, x: ARENA.crane.x, z: ARENA.crane.z }, crane: { st: 'idle', t: 0, who: -1, tx: 0, tz: 0, x: A.crane.x, z: A.crane.z },
pitAlarm: false, pitAlarm: false,
}; };
return s; return s;
@@ -107,11 +127,11 @@
function step(s, dt, inputs) { function step(s, dt, inputs) {
if (s.endIn > 0) { s.endIn -= dt; } if (s.endIn > 0) { s.endIn -= dt; }
s.t += dt; s.t += dt;
if (!s.result) s.left = Math.max(0, ARENA.duration - s.t); if (!s.result) s.left = Math.max(0, s.arena.duration - s.t);
const R = s.robots; const R = s.robots;
// pit: opens at half time // pit: opens at half time
if (s.left <= ARENA.pitOpensAt) { if (s.left <= s.arena.pitOpensAt) {
if (!s.pitAlarm) { s.pitAlarm = true; s.events.push({ type: 'pit_open' }); } if (!s.pitAlarm) { s.pitAlarm = true; s.events.push({ type: 'pit_open' }); }
s.pitOpen = Math.min(1, s.pitOpen + dt * 0.8); s.pitOpen = Math.min(1, s.pitOpen + dt * 0.8);
} }
@@ -176,7 +196,7 @@
} }
// spike walls // spike walls
const lim = ARENA.half - st.rad * 0.9; const lim = s.arena.half - st.rad * 0.9;
for (const ax of ['x', 'z']) { for (const ax of ['x', 'z']) {
const vk = ax === 'x' ? 'vx' : 'vz'; const vk = ax === 'x' ? 'vx' : 'vz';
if (Math.abs(r[ax]) > lim) { if (Math.abs(r[ax]) > lim) {
@@ -186,6 +206,8 @@
if (vn > 1.8 && !r.out) { if (vn > 1.8 && !r.out) {
s.events.push({ type: 'wall', who: r.i, x: r.x, z: r.z, speed: vn }); s.events.push({ type: 'wall', who: r.i, x: r.x, z: r.z, speed: vn });
damage(s, r, (vn - 1.8) * 4.5, null, { kind: 'spikes' }); damage(s, r, (vn - 1.8) * 4.5, null, { kind: 'spikes' });
// slammed into the spikes hard -> bounces up and can land on its back
if (vn > 3.5 && r.y < 0.05 && !r.st.invertible && !r.st.lowProfile && s.rand() < 0.3) { r.vy = Math.max(r.vy, 2); r.flipped = 2.2; r.av += (s.rand() - 0.5) * 6; }
} }
r[vk] = -r[vk] * 0.45; r[vk] = -r[vk] * 0.45;
} }
@@ -222,7 +244,15 @@
const w = me.st.weapon; const w = me.st.weapon;
const ram = w && w.type === 'wedge' ? w.ram : 1; const ram = w && w.type === 'wedge' ? w.ram : 1;
damage(s, e, (impact - 1) * 2.2 * ram, me, { kind: 'ram' }); damage(s, e, (impact - 1) * 2.2 * ram, me, { kind: 'ram' });
if (w && w.type === 'wedge' && e.y < 0.05 && !e.st.lowProfile) { e.vy = 2.6; e.stun = Math.max(e.stun, 0.25); } // a wedge scoops lighter robots up; any hard enough ram can send one tumbling onto its roof
if (w && w.type === 'wedge' && e.y < 0.05 && !e.st.lowProfile) {
const light = Math.sqrt(me.st.mass / e.st.mass);
e.vy = Math.max(e.vy, 2.3 * light); e.stun = Math.max(e.stun, 0.25);
if (!e.st.invertible && !e.st.lowProfile && s.rand() < 0.3 * light && impact > 3) { e.flipped = 2.2; e.av += (s.rand() - 0.5) * 6; }
} else if (impact > 4.5 && e.y < 0.05 && !e.st.lowProfile && !e.st.invertible) {
const light = Math.sqrt(me.st.mass / e.st.mass);
if (s.rand() < 0.22 * light) { e.vy = Math.max(e.vy, 1.8 * light); e.flipped = 2.2; e.av += (s.rand() - 0.5) * 5; s.events.push({ type: 'flip', who: e.i, x: e.x, z: e.z }); }
}
} }
} }
} }
@@ -262,7 +292,7 @@
e.vx += fx * 3 * light; e.vz += fz * 3 * light; e.vx += fx * 3 * light; e.vz += fz * 3 * light;
e.av += (s.rand() - 0.5) * 6; e.av += (s.rand() - 0.5) * 6;
damage(s, e, w.dmg, r, { kind: 'flip' }); damage(s, e, w.dmg, r, { kind: 'flip' });
if (!e.st.invertible && s.rand() < (e.st.lowProfile ? 0.3 : 0.55)) e.flipped = 3.5; if (!e.st.invertible && s.rand() < (e.st.lowProfile ? 0.25 : 0.45)) e.flipped = 2.2;
} }
} }
break; break;
@@ -337,7 +367,7 @@
k.x += Math.cos(k.a) * k.sp * dt; k.z += Math.sin(k.a) * k.sp * dt; k.x += Math.cos(k.a) * k.sp * dt; k.z += Math.sin(k.a) * k.sp * dt;
k.y += ((tgt.y + 0.35) - k.y) * Math.min(1, dt * 3); k.y += ((tgt.y + 0.35) - k.y) * Math.min(1, dt * 3);
const hit = !tgt.out && Math.hypot(tgt.x - k.x, tgt.z - k.z) < tgt.st.rad + 0.1; const hit = !tgt.out && Math.hypot(tgt.x - k.x, tgt.z - k.z) < tgt.st.rad + 0.1;
const wall = Math.abs(k.x) > ARENA.half || Math.abs(k.z) > ARENA.half; const wall = Math.abs(k.x) > s.arena.half || Math.abs(k.z) > s.arena.half;
if (hit || wall || k.t <= 0) { if (hit || wall || k.t <= 0) {
s.events.push({ type: 'boom', x: k.x, z: k.z, y: k.y }); s.events.push({ type: 'boom', x: k.x, z: k.z, y: k.y });
if (hit) { if (hit) {
@@ -350,7 +380,7 @@
} }
function hazards(s, dt) { function hazards(s, dt) {
const A = ARENA, R = s.robots; const A = s.arena, R = s.robots;
for (const r of R) { for (const r of R) {
if (r.out) continue; if (r.out) continue;
const ground = r.y < 0.15 && r.lifted <= 0; const ground = r.y < 0.15 && r.lifted <= 0;
@@ -416,7 +446,7 @@
c.st = 'idle'; c.t = 2.5; r.lifted = 0; r.vy = 0; r.craneT = 0; c.st = 'idle'; c.t = 2.5; r.lifted = 0; r.vy = 0; r.craneT = 0;
s.events.push({ type: 'drop', who: r.i, x: r.x, z: r.z }); s.events.push({ type: 'drop', who: r.i, x: r.x, z: r.z });
damage(s, r, 8, null, { kind: 'drop' }); damage(s, r, 8, null, { kind: 'drop' });
if (!r.st.invertible && s.rand() < 0.5) r.flipped = 3.5; if (!r.st.invertible && s.rand() < 0.4) r.flipped = 2.2;
c.who = -1; c.who = -1;
} }
} }

View File

@@ -10,7 +10,12 @@
// Paste the Firebase Realtime Database URL here to switch the online fame ranking on // Paste the Firebase Realtime Database URL here to switch the online fame ranking on
// (docs/firebase/README.md). Empty = offline. // (docs/firebase/README.md). Empty = offline.
const DB_URL = ''; const DB_URL = 'https://robot-clash-aa37b-default-rtdb.firebaseio.com';
// Online lobby + live PvP: paste the Web API key (Firebase console -> Project settings -> Web API key).
// Empty key -> leaderboard still works, but no login/lobby (menu hides 'Online').
const NET_CFG = { apiKey: 'AIzaSyCE29VQnubM_9ok46nnosg07MpvhZH3O5w', dbUrl: DB_URL };
// dev/test: ?netkey=<API key> tries online without editing the file; ?online jumps to the lobby/login
if (new URLSearchParams(location.search).get('netkey')) NET_CFG.apiKey = new URLSearchParams(location.search).get('netkey');
// Credits (standard for every game): shown on the title screen, links open in the normal browser // Credits (standard for every game): shown on the title screen, links open in the normal browser
const DISCORD = 'https://discord.gg/Ej4JPmCZva'; const DISCORD = 'https://discord.gg/Ej4JPmCZva';
@@ -20,13 +25,20 @@
const L = Kit.i18n(window.LANG, { prefix: ID }); const L = Kit.i18n(window.LANG, { prefix: ID });
const t = L.t; const t = L.t;
const store = Kit.store(ID); const store = Kit.store(ID);
const settings = Object.assign({ gfx: 'high', intro: true }, store.get('settings', {})); // steer: 'simple' (keys = screen direction) | 'tank' · diff: 'easy' | 'normal' | 'hard' · autofire: weapon fires by itself in reach
const settings = Object.assign({ gfx: 'high', intro: true, steer: 'tank', diff: 'easy', autofire: true, cam: 'fpv', arena: 'random' }, store.get('settings', {}));
// v2: Michael found "simple" steering worse -> tank is the default again, old saved choice reset once
// v3: fights start in first person (cockpit) -> old saved camera reset once
if (!settings.v || settings.v < 2) settings.steer = 'tank';
if (!settings.v || settings.v < 3) { settings.cam = 'fpv'; settings.v = 3; store.set('settings', settings); }
// difficulty: player hit points x, AI skill +
const DIFF = { easy: { hp: 1.4, skill: -0.2 }, normal: { hp: 1.15, skill: -0.05 }, hard: { hp: 0.95, skill: 0.12 } };
const saveSettings = () => store.set('settings', settings); const saveSettings = () => store.set('settings', settings);
const accounts = RC.Accounts(ID); const accounts = RC.Accounts(ID);
const newSave = () => ({ const newSave = () => ({
money: 400, fame: 0, best: 0, season: 1, beaten: 0, wins: 0, losses: 0, games: 0, money: 800, fame: 0, best: 0, season: 1, beaten: 0, wins: 0, losses: 0, games: 0,
owned: Object.values(RC.STARTER).filter(Boolean), build: Object.assign({}, RC.STARTER), owned: Object.values(RC.STARTER).filter(Boolean), build: Object.assign({}, RC.STARTER),
paint: { body: 0xff7a1a, accent: 0x15171b }, robotName: 'Clank', tutorialSeen: false, paint: { body: 0xff7a1a, accent: 0x15171b }, robotName: 'Clank', flag: 'XX', tutorialSeen: false,
}); });
let slot = null, save = null; // per account, set by enterAccount() let slot = null, save = null; // per account, set by enterAccount()
const persist = () => { if (slot && save) slot.save(save); }; const persist = () => { if (slot && save) slot.save(save); };
@@ -37,17 +49,22 @@
}); });
const scores = Kit.scores({ url: DB_URL }); const scores = Kit.scores({ url: DB_URL });
const DEV = new URLSearchParams(location.search); const DEV = new URLSearchParams(location.search);
const net = RC.Net(NET_CFG);
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, getProfile: () => ({ name: playerName(), flag: save.flag || 'XX', build: save.build, paint: { body: save.paint.body, accent: save.paint.accent }, fame: save.fame | 0 }) }) : null;
const fx = Kit.fx(); const fx = Kit.fx();
const input = Kit.input({ const input = Kit.input({
keys: { keys: {
ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', ArrowRight: 'right', d: 'right', ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', ArrowRight: 'right', d: 'right',
' ': 'fire', Shift: 'fire2', e: 'fire2', p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok', ' ': 'fire', Shift: 'fire2', e: 'fire2', p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok', c: 'cam',
}, },
onPress(a) { onPress(a) {
if (mode === 'intro') { skipIntro(); return; } if (mode === 'intro') { skipIntro(); return; }
if (a === 'pause') togglePause(); if (a === 'pause') togglePause();
else if (a === 'mute') toggleMute(); else if (a === 'mute') toggleMute();
else if (a === 'cam' && mode === 'fight') cycleCam();
else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); } else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); }
}, },
}); });
@@ -109,7 +126,7 @@
$('icoFame').innerHTML = `<img src="${img('ico_fame.png')}" alt="" onerror="this.classList.add('missing')">`; $('icoFame').innerHTML = `<img src="${img('ico_fame.png')}" alt="" onerror="this.classList.add('missing')">`;
const shop = RC.Shop({ const shop = RC.Shop({
t, getSave: () => save, onSave: persist, t, getSave: () => save, onSave: () => { persist(); hud(); }, // buy / sell -> credits in the header
onBuild: () => view.showGarage(save.build, paintObj()), onBuild: () => view.showGarage(save.build, paintObj()),
onPaint: () => view.setPaint(paintObj()), onPaint: () => view.setPaint(paintObj()),
sfx: SFX, sfx: SFX,
@@ -150,13 +167,19 @@
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])); const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const seasonMul = () => 1 + (save.season - 1) * 0.5; const seasonMul = () => 1 + (save.season - 1) * 0.5;
const weaponName = b => (b.weapon ? RC.PARTS[b.weapon].name : t('unarmed')) + (b.tower ? ' + ' + RC.PARTS[b.tower].name : ''); const weaponName = b => (b.weapon ? RC.PARTS[b.weapon].name : t('unarmed')) + (b.tower ? ' + ' + RC.PARTS[b.tower].name : '');
const playerName = () => (accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : ''); // league robots dressed like their ComfyGen portraits (looks.js)
const oppPaint = o => (RC.LOOKS && RC.LOOKS[o.id] ? Object.assign({}, o.paint, { layer: RC.lookLayer(o.id, o.paint), drawn: true, look: RC.LOOKS[o.id] }) : o.paint);
const fbUser = () => (net && net.enabled ? net.auth.current : null);
const fbAcc = () => (fbUser() && !fbUser().guest ? fbUser() : null); // real (e-mail) account
const playerName = () => (fbUser() ? fbUser().name : accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : '');
// save slot: Firebase account -> robotclash.save.fb_<uid>, else local profile / guest
const saveKey = () => (fbAcc() ? ID + '.save.fb_' + fbAcc().uid : accounts.saveKey());
function hud() { function hud() {
$('hMoney').textContent = save ? Kit.fmt(save.money) : '–'; $('hMoney').textContent = save ? Kit.fmt(save.money) : '–';
$('hFame').textContent = save ? Kit.fmt(save.fame) : '–'; $('hFame').textContent = save ? Kit.fmt(save.fame) : '–';
$('hLeague').textContent = save ? t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length }) : '–'; $('hLeague').textContent = save ? t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length }) : '–';
$('hUser').textContent = accounts.current ? (accounts.current.guest ? '👤 ' + t('guest') : '👤 ' + accounts.current.name) : '👤 –'; $('hUser').textContent = fbUser() ? '👤 ' + fbUser().name : accounts.current ? (accounts.current.guest ? '👤 ' + t('guest') : '👤 ' + accounts.current.name) : save ? '👤 ' + t('guest') : '👤 –';
$('bMute').textContent = audio.muted ? t('sound_off') : t('sound_on'); $('bMute').textContent = audio.muted ? t('sound_off') : t('sound_on');
} }
function setScreen(m) { function setScreen(m) {
@@ -175,7 +198,7 @@
hideOverlay(); hideOverlay();
if (!view) { showTitle(); return; } if (!view) { showTitle(); return; }
const a = RC.LEAGUE[7], b = RC.LEAGUE[4]; const a = RC.LEAGUE[7], b = RC.LEAGUE[4];
view.showIntro([a.build, b.build], [a.paint, b.paint]); view.showIntro([a.build, b.build], [oppPaint(a), oppPaint(b)]);
introCue = 0; introCue = 0;
audio.music('music_title'); audio.music('music_title');
if (!settings.intro) view.skipIntro(); if (!settings.intro) view.skipIntro();
@@ -196,10 +219,12 @@
function showTitle() { function showTitle() {
setScreen('title'); setScreen('title');
audio.music('music_title'); audio.music('music_title');
const acc = accounts.current && !accounts.current.guest ? accounts.current : null; const fb = net && net.enabled;
const acc = fb ? fbAcc() : (accounts.current && !accounts.current.guest ? accounts.current : null);
const online = fb ? `<button id="bOnline">🌍 ${t('online_play')}</button>` : '';
const btns = acc const btns = acc
? `<button class="primary" id="bPlay">${t('play_as', { name: esc(acc.name) })}</button><button id="bSwitch">${t('switch_account')}</button>` ? `<button class="primary" id="bPlay">${t('play_as', { name: esc(acc.name) })}</button>${online}<button id="bSwitch">${t('switch_account')}</button>`
: `<button class="primary" id="bLogin">${t('login')}</button><button id="bReg">${t('register')}</button><button id="bGuest">${t('play_guest')}</button>`; : `<button class="primary" id="bLogin">${t('login')}</button><button id="bReg">${t('register')}</button><button id="bGuest">${t('play_guest')}</button>${online}`;
overlay.innerHTML = `<div class="title"><div class="big">ROBOT CLASH</div><div class="tag">${t('menu_text')}</div> overlay.innerHTML = `<div class="title"><div class="big">ROBOT CLASH</div><div class="tag">${t('menu_text')}</div>
<div class="row">${btns}</div> <div class="row">${btns}</div>
<div class="row"><button id="bSet">⚙ ${t('settings')}</button><button id="bHelp">${t('how_to')}</button> <div class="row"><button id="bSet">⚙ ${t('settings')}</button><button id="bHelp">${t('how_to')}</button>
@@ -208,10 +233,11 @@
overlay.classList.remove('hide'); overlay.classList.add('clear'); overlay.style.backgroundImage = ''; overlay.classList.remove('hide'); overlay.classList.add('clear'); overlay.style.backgroundImage = '';
const on = (id, f) => { const el = $(id); if (el) el.onclick = () => { SFX.click(); f(); }; }; const on = (id, f) => { const el = $(id); if (el) el.onclick = () => { SFX.click(); f(); }; };
on('bPlay', () => enterAccount()); on('bPlay', () => enterAccount());
on('bSwitch', () => { accounts.logout(); hud(); showLogin(); }); on('bOnline', () => startOnline());
on('bLogin', () => showLogin()); on('bSwitch', () => { signOut(); fb ? showOnlineLogin(false, null, 'career') : showLogin(); });
on('bReg', () => showRegister()); on('bLogin', () => (fb ? showOnlineLogin(false, null, 'career') : showLogin()));
on('bGuest', () => { accounts.guest(); enterAccount(); }); on('bReg', () => (fb ? showOnlineLogin(true, null, 'career') : showRegister()));
on('bGuest', () => { if (fbAcc()) net.auth.logout(); accounts.guest(); enterAccount(); });
on('bSet', () => showSettings(showTitle)); on('bSet', () => showSettings(showTitle));
on('bHelp', () => showHelp(showTitle)); on('bHelp', () => showHelp(showTitle));
on('bLang', () => L.next()); on('bLang', () => L.next());
@@ -219,6 +245,95 @@
hud(); hud();
} }
// ---------------------------------------------------------------- online lobby
let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker)
async function startOnline() {
if (!net.enabled) return;
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) {
lobby.enter(); onlineReady = true;
lobby.onList(rows => { lobbyRows = rows; if (mode === 'lobby') renderLobby(); });
lobby.onIncoming(c => { if (mode === 'lobby' || mode === 'garage') showIncoming(c); });
lobby.onMatch(m => startFight({ name: m.opp.name, build: m.opp.build, paint: m.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: m.opp.flag }, false, false, { id: m.id, host: m.host, seed: m.seed }));
lobby.onCancel(() => { pendingOut = null; if (mode === 'lobby') { renderLobby(); SFX.deny(); } });
}
showLobby();
}
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(); 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="nickname">`
: '';
card(`<h2>${reg ? t('register') : t('login')}</h2><p>${t('online_login_text')}</p>
<div class="form">${f}<label>${t('f_email')}</label><input type="email" id="oMail" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" inputmode="email">
<label>${t('f_pass')}</label><input type="password" id="oPass" autocomplete="${reg ? 'new-password' : 'current-password'}"></div>
<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(); };
$('oBack').onclick = () => { SFX.click(); showTitle(); };
$('oToggle').onclick = () => { SFX.click(); showOnlineLogin(!reg, null, next); };
$('oGo').onclick = async () => {
$('oGo').disabled = true;
const r = reg ? await net.auth.register($('oMail').value.trim(), $('oPass').value, $('oName') ? $('oName').value : '')
: await net.auth.login($('oMail').value.trim(), $('oPass').value);
if (!r.ok) { SFX.deny(); showOnlineLogin(reg, r.error, next); return; }
SFX.click(); hud();
if (next === 'online') startOnline(); else enterAccount(reg);
};
overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Enter') $('oGo').click(); }));
}
function showLobby() {
setScreen('lobby'); renderLobby();
}
function renderLobby() {
if (!lobbyRoom) return renderRooms();
const here = lobbyRows.filter(r => (FLAGS.includes(r.flag) ? r.flag : 'XX') === lobbyRoom);
const meRow = `<div class="prow me"><span class="pf">${flagHtml(lobbyRoom)}</span><span class="pn">${esc(playerName())} <span class="muted">(${t('you')})</span></span><span class="pfame">⭐ ${Kit.fmt(save.fame | 0)}</span><span class="pbusy"></span></div>`;
const list = here.map(r => `<div class="prow" data-uid="${r.uid}"><span class="pf">${flagHtml(r.flag)}</span><span class="pn">${esc(r.name)}</span><span class="pfame">⭐ ${Kit.fmt(r.fame | 0)}</span>${r.state === 'idle' ? `<button class="chal" data-uid="${r.uid}">${t('challenge')}</button>` : `<span class="pbusy">${t('busy')}</span>`}</div>`).join('');
card(`<h2>${flagHtml(lobbyRoom)} ${t('room_title', { room: t('cc_' + lobbyRoom) })}</h2>
<p class="muted">${t('room_count', { n: here.length + 1 })}</p>
<div class="plist">${meRow}${list || `<div class="muted" style="padding:14px">${t('lobby_empty')}</div>`}</div>
${pendingOut ? `<p class="muted">${t('waiting_accept')} <button class="link" id="lCancel">${t('cancel')}</button></p>` : ''}
<div class="row"><button id="lRooms">🌍 ${t('other_rooms')}</button><button id="lQuick">${t('quick_match')}</button><button id="lBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
overlay.querySelectorAll('.chal').forEach(b => { b.onclick = () => { SFX.click(); pendingOut = b.dataset.uid; lobby.challenge(b.dataset.uid); renderLobby(); }; });
if ($('lCancel')) $('lCancel').onclick = () => { SFX.click(); lobby.cancel(); pendingOut = null; renderLobby(); };
$('lQuick').onclick = () => { const idle = here.find(r => r.state === 'idle'); if (idle) { SFX.click(); pendingOut = idle.uid; lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); };
$('lRooms').onclick = () => { SFX.click(); lobbyRoom = null; renderLobby(); };
$('lBack').onclick = () => { SFX.click(); lobbyRoom = null; if (save) openGarage(); else showTitle(); };
}
// room picker: every country with how many players sit in it right now
function renderRooms() {
const count = f => lobbyRows.filter(r => (FLAGS.includes(r.flag) ? r.flag : 'XX') === f).length;
const rooms = FLAGS.map(f => { const n = count(f); return `<button class="room ${n ? 'live' : ''}" data-f="${f}">${flagHtml(f)}<span class="rn">${t('cc_' + f)}</span><span class="rc">${n ? '● ' + n : '0'}</span></button>`; }).join('');
card(`<h2>🌍 ${t('lobby')}</h2><p class="muted">${t('pick_room')}</p>
<div class="rooms">${rooms}</div>
<div class="row"><button id="lBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
overlay.querySelectorAll('.room').forEach(b => { b.onclick = () => {
SFX.click(); lobbyRoom = b.dataset.f; save.flag = lobbyRoom; persist(); if (lobby) lobby.refresh(); renderLobby();
}; });
$('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(); };
}
// ---------------------------------------------------------------- accounts // ---------------------------------------------------------------- accounts
function showLogin(errKey) { function showLogin(errKey) {
setScreen('account'); setScreen('account');
@@ -270,12 +385,16 @@
})); }));
} }
function enterAccount(fresh) { function loadSave() {
slot = Kit.saveSlot(accounts.saveKey(), newSave); slot = Kit.saveSlot(saveKey(), newSave);
save = slot.load(); save = slot.load();
repairSave(); repairSave();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (fresh && accounts.current && !accounts.current.guest) save.robotName = accounts.current.name.slice(0, 18); }
function enterAccount(fresh) {
loadSave();
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
if (fresh && who) save.robotName = who.name.slice(0, 18);
persist(); persist();
hud(); hud();
shop.reset(); shop.reset();
@@ -291,14 +410,20 @@
for (const sl of Object.keys(RC.REQUIRED)) if (!save.build[sl]) { save.build[sl] = RC.STARTER[sl]; if (!save.owned.includes(RC.STARTER[sl])) save.owned.push(RC.STARTER[sl]); } for (const sl of Object.keys(RC.REQUIRED)) if (!save.build[sl]) { save.build[sl] = RC.STARTER[sl]; if (!save.owned.includes(RC.STARTER[sl])) save.owned.push(RC.STARTER[sl]); }
save.beaten = Kit.clamp(save.beaten | 0, 0, RC.LEAGUE.length - 1); save.beaten = Kit.clamp(save.beaten | 0, 0, RC.LEAGUE.length - 1);
} }
function logout() { persist(); accounts.logout(); save = null; slot = null; F = null; hud(); startIntroOrTitle(); } function signOut() {
function startIntroOrTitle() { if (view) { const a = RC.LEAGUE[7], b = RC.LEAGUE[4]; view.showIntro([a.build, b.build], [a.paint, b.paint]); view.skipIntro(); } showTitle(); } persist();
if (lobby && onlineReady) { lobby.leave(); onlineReady = false; lobbyRows = []; pendingOut = null; }
if (net && net.enabled) net.auth.logout();
accounts.logout(); save = null; slot = null; F = null; hud();
}
function logout() { signOut(); startIntroOrTitle(); }
function startIntroOrTitle() { if (view) { const a = RC.LEAGUE[7], b = RC.LEAGUE[4]; view.showIntro([a.build, b.build], [oppPaint(a), oppPaint(b)]); view.skipIntro(); } showTitle(); }
$('hUser').onclick = () => { $('hUser').onclick = () => {
if (!accounts.current || mode === 'fight' || mode === 'pause') return; if (!save || mode === 'fight' || mode === 'pause') return;
SFX.click(); SFX.click();
const back = currentBack(); const back = currentBack(), who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
card(`<h2>${t('account')}</h2><p>${accounts.current.guest ? t('guest_text') : t('logged_in_as', { name: esc(accounts.current.name) })}</p> card(`<h2>${t('account')}</h2><p>${who ? t('logged_in_as', { name: esc(who.name) }) + (who.email ? `<br><span class="muted">${esc(who.email)}</span>` : '') : t('guest_text')}</p>
<div class="row"><button id="bOut">${accounts.current.guest ? t('to_title') : t('logout')}</button><button class="primary" id="bBack">${t('back')}</button></div>`); <div class="row"><button id="bOut">${who ? t('logout') : t('to_title')}</button><button class="primary" id="bBack">${t('back')}</button></div>`);
$('bOut').onclick = () => { SFX.click(); logout(); }; $('bOut').onclick = () => { SFX.click(); logout(); };
$('bBack').onclick = () => { SFX.click(); back(); }; $('bBack').onclick = () => { SFX.click(); back(); };
}; };
@@ -308,33 +433,48 @@
function showSettings(back) { function showSettings(back) {
const prev = mode; 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 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>`;
card(`<h2>${t('settings')}</h2><div class="set"> const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
<span>${t('s_lang')}</span>${seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self]))} const item = (label, ctl) => `<span class="sl">${label}</span>${ctl}`;
<span>${t('s_music')}</span><input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}"> card(`<h2>${t('settings')}</h2><div class="set2">
<span>${t('s_sfx')}</span><input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}"> ${item(t('s_lang'), seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self])))}
<span>${t('s_mute')}</span>${seg('sMute', audio.muted ? '1' : '0', [['0', t('on')], ['1', t('off')]])} ${item(t('s_mute'), seg('sMute', audio.muted ? '1' : '0', [['0', t('on')], ['1', t('off')]]))}
<span>${t('s_gfx')}</span>${seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]])} ${item(t('s_music'), `<input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">`)}
<span>${t('s_intro')}</span>${seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]])} ${item(t('s_sfx'), `<input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">`)}
<span>${t('s_screen')}</span><div><button id="sFull">${t('win_full')}</button></div> ${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))}
${item(t('s_diff'), seg('sDiff', settings.diff, [['easy', t('diff_easy')], ['normal', t('diff_normal')], ['hard', t('diff_hard')]]))}
${item(t('s_cam'), seg('sCam', settings.cam, CAMS.map(c => [c, t('cam_' + c)])))}
${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_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> </div>
<h3>${t('s_controls')}</h3>${keysHtml()} <div class="setacc"><span class="sl">${t('s_account')}</span>
${save ? `<h3>${t('s_career')}</h3><div style="text-align:left"><button id="sReset">${t('reset')}</button></div>` : ''} <span class="who">${who ? '👤 <b>' + esc(who.name) + '</b>' + (who.email ? ' <span class="muted">' + esc(who.email) + '</span>' : '') : '👤 ' + t('guest')}</span>
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, clear: prev === 'title' || prev === 'intro' }); ${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>
${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)); }; }); 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('sLang', v => { L.set(v); showSettings(back); });
segOn('sMute', v => { if ((v === '1') !== audio.muted) audio.toggleMute(); hud(); }); segOn('sMute', v => { if ((v === '1') !== audio.muted) audio.toggleMute(); hud(); });
segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (view) view.setQuality(v); }); segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (view) view.setQuality(v); });
segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); }); segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); });
segOn('sDiff', v => { settings.diff = v; saveSettings(); });
segOn('sSteer', v => { settings.steer = v; saveSettings(); });
segOn('sCam', v => { settings.cam = v; saveSettings(); if (view) view.setCam(v); });
segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); });
segOn('sArena', v => { settings.arena = v; saveSettings(); });
$('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol); $('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol);
$('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value); $('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value);
$('sSfx').onchange = () => SFX.click(); $('sSfx').onchange = () => SFX.click();
$('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); }; $('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); };
if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => 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)); };
$('bBack').onclick = () => { SFX.click(); back(); }; $('bBack').onclick = () => { SFX.click(); back(); };
} }
function keysHtml() { 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> 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>P / Esc</b><span>${t('pause')}</span><b>M</b><span>${t('sound_on')} / ${t('sound_off')}</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>`; <b>${t('key_pad')}</b><span>${t('key_pad_text')}</span></div>`;
} }
function showHelp(back) { function showHelp(back) {
@@ -381,6 +521,8 @@
shop.render(); hud(); shop.render(); hud();
} }
$('bGMenu').onclick = () => { SFX.click(); persist(); startIntroOrTitle(); }; $('bGMenu').onclick = () => { SFX.click(); persist(); startIntroOrTitle(); };
$('bGOnline').onclick = () => { SFX.click(); persist(); startOnline(); };
if (!(net && net.enabled)) $('bGOnline').style.display = 'none';
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); }; $('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
$('bLeague').onclick = () => { SFX.click(); showLeague(); }; $('bLeague').onclick = () => { SFX.click(); showLeague(); };
@@ -393,33 +535,50 @@
<div class="pz">${RC.pic('ico_credits', '🪙')}${Kit.fmt(Math.round(o.prize * seasonMul()))}</div></div>`; <div class="pz">${RC.pic('ico_credits', '🪙')}${Kit.fmt(Math.round(o.prize * seasonMul()))}</div></div>`;
}).join(''); }).join('');
card(`<h2>${t('league_title', { s: save.season })}</h2><p>${t('league_text')}</p><div class="opps">${cards}</div> card(`<h2>${t('league_title', { s: save.season })}</h2><p>${t('league_text')}</p><div class="opps">${cards}</div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bFight">${t('fight_vs', { name: RC.LEAGUE[save.beaten].name })}</button></div>`, <div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bFight">${t('fight_vs', { name: RC.LEAGUE[save.beaten].name })}</button></div>
${save.beaten ? `<p class="muted">${t('exhibition_hint')}</p>` : ''}`,
{ wide: true, bg: 'bg_title.jpg' }); { wide: true, bg: 'bg_title.jpg' });
overlay.querySelectorAll('.opp.next').forEach(el => { el.style.cursor = 'pointer'; el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); }; }); overlay.querySelectorAll('.opp.next').forEach(el => { el.style.cursor = 'pointer'; el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); }; });
// beaten opponents: repeatable exhibition fights for half the prize (steady income)
overlay.querySelectorAll('.opp.done').forEach(el => { el.style.cursor = 'pointer'; el.title = t('exhibition_note'); el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[+el.dataset.i], true); }; });
$('bFight').onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); }; $('bFight').onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); };
$('bBack').onclick = () => { SFX.click(); openGarage(); }; $('bBack').onclick = () => { SFX.click(); openGarage(); };
} }
function showVs(opp) { function showVs(opp, exhibition) {
const me = RC.stats(save.build), en = RC.stats(opp.build); const me = RC.stats(save.build), en = RC.stats(opp.build);
const line = s => `${Math.round(s.hp)} ${t('m_hp')} · ${Math.round(s.reduce * 100)}% ${t('m_armour')} · ${s.top.toFixed(1)} m/s`; const line = s => `${Math.round(s.hp)} ${t('m_hp')} · ${Math.round(s.reduce * 100)}% ${t('m_armour')} · ${s.top.toFixed(1)} m/s`;
card(`<div class="vs"><div class="side">${RC.pic('icon', '🤖')}<div class="nm">${esc(save.robotName)}</div><div class="muted">${weaponName(save.build)}</div><div class="muted">${line(me)}</div></div> const mine = view.portrait(save.build, paintObj());
const myPic = mine ? `<span class="pic"><img src="${mine}" alt="" draggable="false"></span>` : RC.pic('icon', '🤖');
card(`<div class="vs"><div class="side">${myPic}<div class="nm">${esc(save.robotName)}</div><div class="muted">${weaponName(save.build)}</div><div class="muted">${line(me)}</div></div>
<div class="mid">VS</div> <div class="mid">VS</div>
<div class="side">${RC.pic('opp_' + opp.id, '🤖')}<div class="nm">${opp.name}</div><div class="muted">${weaponName(opp.build)}</div><div class="muted">${line(en)}</div></div></div> <div class="side">${RC.pic('opp_' + opp.id, '🤖')}<div class="nm">${opp.name}</div><div class="muted">${weaponName(opp.build)}</div><div class="muted">${line(en)}</div></div></div>
<p>${t('style_' + opp.style)}</p> <p>${t('style_' + opp.style)}</p>${exhibition ? `<p class="muted">${t('exhibition_note')}</p>` : ''}
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('fight_go_btn')}</button></div>`, { wide: true, bg: 'bg_title.jpg' }); <div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${exhibition ? t('exhibition_btn') : t('fight_go_btn')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showLeague(); }; $('bBack').onclick = () => { SFX.click(); showLeague(); };
$('bGo').onclick = () => { SFX.click(); startFight(opp, false); }; $('bGo').onclick = () => { SFX.click(); startFight(opp, false, exhibition); };
} }
// ---------------------------------------------------------------- fight // ---------------------------------------------------------------- fight
function startFight(opp, training) { function startFight(opp, training, exhibition, online) {
hideOverlay(); hideOverlay();
const D = DIFF[settings.diff] || DIFF.easy;
const stA = RC.stats(save.build), stB = RC.stats(opp.build); const stA = RC.stats(save.build), stB = RC.stats(opp.build);
const seed = (Date.now() & 0xffff) + save.games * 31; if (!online) stA.hp = Math.round(stA.hp * D.hp); // no handicap in live PvP
const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name] }); const seed = online ? online.seed : (Date.now() & 0xffff) + save.games * 31;
const skill = Math.min(1, opp.skill + (save.season - 1) * 0.12); // arena: league scales with the opponent, online derives from the shared seed, training uses the setting
F = { s, opp, training, brain: RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4, const ids = RC.ARENAS.map(a => a.id), idx = RC.LEAGUE.indexOf(opp);
const arenaId = DEV.get('arena') ? DEV.get('arena')
: online ? ids[seed % ids.length]
: idx >= 0 ? ids[Math.min(ids.length - 1, Math.floor(idx / 3))]
: settings.arena === 'random' || !settings.arena ? ids[(Math.random() * ids.length) | 0] : settings.arena;
const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name], arena: arenaId });
const skill = Kit.clamp(opp.skill + (save.season - 1) * 0.12 + D.skill, 0, 1);
F = { s, opp, training, exhibition: !!exhibition, online, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4,
acc: [0, 0], accT: 0, banner: null, ended: false }; acc: [0, 0], accT: 0, banner: null, ended: false };
if (online) {
F.nf = RC.NetFight({ net, id: online.id, host: online.host, oppStyle: 'brawler', oppSkill: 0.6, onPeerLost: () => banner(t('peer_lost'), '#ff4a3a', 2.5), onPeerBack: () => banner(t('peer_back'), '#6dff9e', 1.6) });
F.nf.start();
}
// dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing) // dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing)
if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 }); if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 });
if (DEV.has('ff')) { if (DEV.has('ff')) {
@@ -430,13 +589,15 @@
s.events.length = 0; s.events.length = 0;
} }
} }
view.showArena(s, [save.build, opp.build], [paintObj(), opp.paint]); view.showArena(s, [save.build, opp.build], [paintObj(), oppPaint(opp)]);
view.setCam(DEV.get('cam') || settings.cam); // dev: &cam=chase|fpv
$('fN0').textContent = save.robotName; $('fN1').textContent = opp.name; $('fN0').textContent = save.robotName; $('fN1').textContent = opp.name;
$('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(opp.build); $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(opp.build);
$('fH0').style.background = hex(save.paint.body); $('fH1').style.background = hex(opp.paint.body); $('fH0').style.background = barCol(save.paint); $('fH1').style.background = barCol(opp.paint);
fx.clear(); fx.clear();
setScreen('fight'); setScreen('fight');
audio.music('music_fight'); audio.music('music_fight');
banner('📍 ' + t('arena_' + s.arena.id), '#ff7a1a', 2.2);
fightHud(); fightHud();
} }
@@ -449,20 +610,81 @@
return { throttle: -dz(gp.axes[1] || 0) + (b(12) ? 1 : 0) - (b(13) ? 1 : 0), turn: dz(gp.axes[0] || 0) + (b(15) ? 1 : 0) - (b(14) ? 1 : 0), return { throttle: -dz(gp.axes[1] || 0) + (b(12) ? 1 : 0) - (b(13) ? 1 : 0), turn: dz(gp.axes[0] || 0) + (b(15) ? 1 : 0) - (b(14) ? 1 : 0),
fire: b(0) || b(7), fire2: b(1) || b(2) || b(6) }; fire: b(0) || b(7), fire2: b(1) || b(2) || b(6) };
} }
// up/down + left/right from keys, touch pad and gamepad
function playerInput() { function playerInput() {
const k = { let ky = (input.down('up') ? 1 : 0) - (input.down('down') ? 1 : 0);
throttle: (input.down('up') ? 1 : 0) - (input.down('down') ? 1 : 0), let kx = (input.down('right') ? 1 : 0) - (input.down('left') ? 1 : 0);
turn: (input.down('right') ? 1 : 0) - (input.down('left') ? 1 : 0), let fire = input.down('fire'), fire2 = input.down('fire2');
fire: input.down('fire'), fire2: input.down('fire2'),
};
const g = pad(); const g = pad();
if (g) { if (g) { ky = Kit.clamp(ky + g.throttle, -1, 1); kx = Kit.clamp(kx + g.turn, -1, 1); fire = fire || g.fire; fire2 = fire2 || g.fire2; }
k.throttle = Kit.clamp(k.throttle + g.throttle, -1, 1); k.turn = Kit.clamp(k.turn + g.turn, -1, 1); const s = F.s, me = s.robots[0], en = s.robots[1];
k.fire = k.fire || g.fire; k.fire2 = k.fire2 || g.fire2; let k = { throttle: ky, turn: kx, fire, fire2 };
if (settings.steer === 'simple' && view.camMode === 'iso') {
// keys = direction on screen; the robot turns towards it and drives
// (iso camera: screen up = world (-1,-1), screen right = world (1,-1))
const dx = (kx - ky) / Math.SQRT2, dz = (-kx - ky) / Math.SQRT2;
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
if (Math.hypot(dx, dz) < 0.2) k = { throttle: 0, turn: 0, fire, fire2 };
else {
let diff = wrap(Math.atan2(dz, dx) - me.a);
// target behind: drive backwards there instead of a slow 180° turn on the spot
// (with a little hysteresis so it does not flip between forward and reverse)
const back = F.revDir ? Math.abs(diff) > 1.2 : Math.abs(diff) > 2.1;
F.revDir = back;
if (back) diff = wrap(diff + Math.PI);
const ad = Math.abs(diff);
const thr = ad < 0.9 ? 1 : ad < 1.6 ? 0.6 : 0.2; // keep rolling while turning
k = { throttle: back ? -thr : thr, turn: Kit.clamp(diff * 3.5, -1, 1), fire, fire2 };
}
}
// weapon helper: fires the main weapon in reach, the tower when in range
if (settings.autofire) {
const w = me.st.weapon, tw = me.st.tower, dist = Math.hypot(en.x - me.x, en.z - me.z);
if (w && !k.fire) {
if (w.type === 'spinner') k.fire = dist < 5;
else if (w.type === 'saw') k.fire = dist < 2.4;
else if (w.type !== 'wedge') k.fire = RC.Combat.inZone(s, me, en);
}
if (tw && !k.fire2) k.fire2 = dist < tw.range * 0.95;
} }
return k; return k;
} }
// health bar colour: paint, or the accent when the paint is too dark to read
const barCol = p => { const c = p.body >>> 0, l = ((c >> 16) & 255) * 0.3 + ((c >> 8) & 255) * 0.59 + (c & 255) * 0.11; return hex(l < 60 ? p.accent : p.body); };
const CAMS = ['iso', 'chase', 'fpv'];
function cycleCam() {
settings.cam = CAMS[(CAMS.indexOf(settings.cam) + 1) % CAMS.length];
saveSettings(); view.setCam(settings.cam); SFX.click();
banner(t('cam_' + settings.cam), '#ffffff', 1);
}
// minimap for chase / cockpit view: arena, traps, pit, both robots
function minimap() {
const touch = window.matchMedia && matchMedia('(pointer: coarse)').matches;
const s = F.s, A = RC.ARENA, S = touch ? 104 : 128, X = W - S - 14, Y = touch ? 84 : H - S - 14, k = S / (A.half * 2);
// rotate 45° like the iso view, so "up" matches the arena camera
const P = (x, z) => [X + S / 2 + (x - z) * k * 0.7071, Y + S / 2 + (x + z) * k * 0.7071];
ctx.save();
ctx.fillStyle = 'rgba(10,12,16,.72)'; ctx.strokeStyle = 'rgba(255,255,255,.25)'; ctx.lineWidth = 1;
const poly = pts => { ctx.beginPath(); pts.forEach(([x, z], i) => { const [px, py] = P(x, z); if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py); }); ctx.closePath(); };
const h = A.half;
poly([[-h, -h], [h, -h], [h, h], [-h, h]]); ctx.fill(); ctx.stroke();
const rect = (o, col) => { ctx.fillStyle = col; poly([[o.x - o.hw, o.z - o.hd], [o.x + o.hw, o.z - o.hd], [o.x + o.hw, o.z + o.hd], [o.x - o.hw, o.z + o.hd]]); ctx.fill(); };
rect(A.press, 'rgba(242,181,28,.35)'); rect(A.crane, 'rgba(242,181,28,.35)');
rect(A.pit, s.pitOpen >= 1 ? 'rgba(255,40,40,.85)' : 'rgba(255,255,255,.12)');
for (const f of A.flames) rect(f, RC.hazardOn(f, s.t) ? 'rgba(255,110,20,.85)' : 'rgba(255,110,20,.25)');
for (const sw of A.saws) { const [px, py] = P(sw.x, sw.z); ctx.fillStyle = RC.hazardOn(sw, s.t) ? 'rgba(255,60,60,.9)' : 'rgba(200,200,200,.3)'; ctx.beginPath(); ctx.arc(px, py, sw.r * k, 0, 7); ctx.fill(); }
s.robots.forEach((r, i) => {
if (r.out) return;
const [px, py] = P(r.x, r.z), [qx, qy] = P(r.x + Math.cos(r.a), r.z + Math.sin(r.a)), ang = Math.atan2(qy - py, qx - px);
ctx.save(); ctx.translate(px, py); ctx.rotate(ang);
ctx.fillStyle = i === 0 ? hex(save.paint.body) : hex(F.opp.paint.body); ctx.strokeStyle = i === 0 ? '#fff' : '#000'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(7, 0); ctx.lineTo(-5, 5); ctx.lineTo(-5, -5); ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.restore();
});
ctx.restore();
}
function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; } function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; }
function update(dt) { function update(dt) {
@@ -470,21 +692,28 @@
introTick(); introTick();
if (mode !== 'fight' || !F) return; if (mode !== 'fight' || !F) return;
if (F.count > 0) { if (F.count > 0) {
if (F.nf) F.nf.idle(dt);
F.count -= dt; F.count -= dt;
const n = Math.ceil(F.count); const n = Math.ceil(F.count);
if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } } if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } }
return; return;
} }
const s = F.s, [me, en] = s.robots; const s = F.s, [me, en] = s.robots;
RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]); let events;
for (const e of s.events) { if (F.online) {
events = F.online.host ? F.nf.hostStep(s, playerInput(), dt) : F.nf.guestFrame(s, playerInput(), dt);
} else {
RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]);
events = s.events;
}
for (const e of events) {
SFX.event(e); SFX.event(e);
if (e.type === 'dmg') F.acc[e.who] += e.amount; if (e.type === 'dmg') F.acc[e.who] += e.amount;
else if (e.type === 'pit_open') banner(t('pit_open'), '#ff4a3a', 2); else if (e.type === 'pit_open') banner(t('pit_open'), '#ff4a3a', 2);
else if (e.type === 'pit') banner(t('into_pit'), '#ff4a3a', 2.2); else if (e.type === 'pit') banner(t('into_pit'), '#ff4a3a', 2.2);
else if (e.type === 'ko') banner(t('knockout'), '#ff7a1a', 2.2); else if (e.type === 'ko') banner(t('knockout'), '#ff7a1a', 2.2);
} }
view.events(s.events); view.events(events);
s.events.length = 0; s.events.length = 0;
SFX.loops(s); SFX.loops(s);
// damage numbers, grouped // damage numbers, grouped
@@ -519,12 +748,17 @@
function endFight() { function endFight() {
const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp); const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp);
const won = res.winner === 0, me = s.robots[0]; const won = res.winner === 0, me = s.robots[0];
if (F.online) { endOnlineFight(res, won, me); return; }
const lines = []; const lines = [];
let money = 0, fame = 0, champion = false; let money = 0, fame = 0, champion = false;
if (!F.training) { if (!F.training) {
const prize = Math.round(opp.prize * seasonMul()); const prize = Math.round(opp.prize * seasonMul() * (F.exhibition ? 0.5 : 1));
save.games++; save.games++;
if (won) { if (won && F.exhibition) {
money += prize; lines.push([t('r_exhibition'), prize]);
fame = (idx + 1) * 10 * save.season;
save.wins++;
} else if (won) {
const bonus = res.reason === 'pit' ? 0.3 : res.reason === 'ko' ? 0.2 : 0; const bonus = res.reason === 'pit' ? 0.3 : res.reason === 'ko' ? 0.2 : 0;
money += prize; lines.push([t('r_prize'), prize]); money += prize; lines.push([t('r_prize'), prize]);
if (bonus) { const b = Math.round(prize * bonus); money += b; lines.push([t('r_bonus_' + res.reason), b]); } if (bonus) { const b = Math.round(prize * bonus); money += b; lines.push([t('r_bonus_' + res.reason), b]); }
@@ -537,10 +771,13 @@
save.season++; save.beaten = 0; save.season++; save.beaten = 0;
} }
} else { } else {
const ap = Math.round(prize * 0.2); money += ap; lines.push([t('r_appearance'), ap]); const ap = Math.round(prize * 0.35); money += ap; lines.push([t('r_appearance'), ap]);
save.losses++; save.losses++;
} }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.12 + (res.reason === 'pit' && !won ? me.st.value * 0.05 : 0)); // every hit pays: damage bonus win or lose
const db = Math.round(me.dealt * 0.6 * (F.exhibition ? 0.5 : 1));
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06 + (res.reason === 'pit' && !won ? me.st.value * 0.03 : 0));
const paid = Math.min(repair, save.money + money); const paid = Math.min(repair, save.money + money);
if (paid) lines.push([t('r_repair'), -paid]); if (paid) lines.push([t('r_repair'), -paid]);
money -= paid; money -= paid;
@@ -561,13 +798,46 @@
<div class="row"><button class="primary" id="bGarage">${t('to_garage')}</button>${!F.training && !won ? `<button id="bRetry">${t('retry')}</button>` : ''}</div>${boardHtml()}`, <div class="row"><button class="primary" id="bGarage">${t('to_garage')}</button>${!F.training && !won ? `<button id="bRetry">${t('retry')}</button>` : ''}</div>${boardHtml()}`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' }); { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bGarage').onclick = () => { SFX.click(); openGarage(); }; $('bGarage').onclick = () => { SFX.click(); openGarage(); };
if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false); }; if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false, F.exhibition); };
if (!F.training && save.fame > save.best) { if (!F.training && save.fame > save.best) {
save.best = save.fame; persist(); save.best = save.fame; persist();
scores.submit({ name: playerName(), score: save.fame, level: save.season }).then(fillBoard); scores.submit({ name: playerName(), score: save.fame, level: save.season }).then(fillBoard);
} else fillBoard(); } else fillBoard();
} }
function endOnlineFight(res, won, me) {
if (F.nf) F.nf.stop();
if (lobby) lobby.endMatch();
(won ? SFX.win : SFX.lose)();
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
// online rewards: prize (win) / half (draw) / appearance fee (loss) + damage bonus - repairs; fame on a win
const PVP = 600, lines = [];
let money = 0, fame = 0;
const draw = res.winner === -1;
if (won) { money += PVP; lines.push([t('r_prize'), PVP]); fame = 150 + (res.reason === 'ko' ? 40 : res.reason === 'pit' ? 60 : 0); }
else if (draw) { money += PVP / 2; lines.push([t('r_draw_prize'), PVP / 2]); fame = 40; }
else { const ap = Math.round(PVP * 0.35); money += ap; lines.push([t('r_appearance'), ap]); }
if (won && res.reason !== 'time') { const b = Math.round(PVP * (res.reason === 'pit' ? 0.3 : 0.2)); money += b; lines.push([t('r_bonus_' + res.reason), b]); }
const db = Math.round(me.dealt * 0.6);
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06);
const paid = Math.min(repair, save.money + money);
if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); }
save.money += money; save.fame += fame; save.games++;
if (won) save.wins++; else if (!draw) save.losses++;
persist(); hud();
if (save.fame > save.best) { save.best = save.fame; persist(); scores.submit({ name: playerName(), score: save.fame, level: save.season }); }
const rows = lines.map(([k, v]) => `<span>${k}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
setScreen('result');
card(`<h1>${title}</h1><p>${esc(F.opp.name)} ${F.nf && !F.nf.peerAlive ? t('peer_left') : ''}</p>
<div class="res"><span>${t('r_dealt')}</span><span>${Math.round(me.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(me.taken)}</span>${rows}
${fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div>
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button><button id="bShopO">${t('to_garage')}</button></div>`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bLobby').onclick = () => { SFX.click(); showLobby(); };
$('bShopO').onclick = () => { SFX.click(); openGarage(); };
}
// ---------------------------------------------------------------- loop // ---------------------------------------------------------------- loop
let lastNow = 0; let lastNow = 0;
function render(alpha, now) { function render(alpha, now) {
@@ -604,15 +874,17 @@
ctx.fillStyle = b.color; ctx.fillText(b.text, 0, 0); ctx.fillStyle = b.color; ctx.fillText(b.text, 0, 0);
ctx.restore(); ctx.restore();
} }
if (view.camMode !== 'iso') minimap();
if (mode === 'fight' && F.s.t < 7 && F.count <= 0) { if (mode === 'fight' && F.s.t < 7 && F.count <= 0) {
ctx.font = '13px "Segoe UI", sans-serif'; ctx.textAlign = 'center'; ctx.fillStyle = 'rgba(232,235,242,.75)'; ctx.font = '13px "Segoe UI", sans-serif'; ctx.textAlign = 'center'; ctx.fillStyle = 'rgba(232,235,242,.75)';
ctx.fillText(t('fight_hint'), W / 2, H - 16); ctx.fillText(t(settings.steer === 'simple' && view.camMode === 'iso' ? 'fight_hint_simple' : 'fight_hint'), W / 2, H - 16);
} }
} }
} }
const loop = Kit.loop({ step: 1000 / 60, update, render }).start(); const loop = Kit.loop({ step: 1000 / 60, update, render }).start();
function togglePause() { function togglePause() {
if (F && F.online && mode === 'fight') { banner(t('no_pause_online'), '#ffffff', 1.4); return; }
if (mode === 'fight') { if (mode === 'fight') {
mode = 'pause'; loop.pause(); 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>`); 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>`);
@@ -627,33 +899,54 @@
function toggleMute() { audio.toggleMute(); hud(); } function toggleMute() { audio.toggleMute(); hud(); }
$('bMute').onclick = toggleMute; $('bMute').onclick = toggleMute;
$('bPause').onclick = togglePause; $('bPause').onclick = togglePause;
addEventListener('blur', () => { if (mode === 'fight') togglePause(); }); addEventListener('blur', () => { if (mode === 'fight' && !(F && F.online)) togglePause(); });
// language switch: static texts update themselves (data-i18n), dynamic screens are drawn again // language switch: static texts update themselves (data-i18n), dynamic screens are drawn again
L.onChange(() => { L.onChange(() => {
hud(); hud();
if (mode === 'title') showTitle(); if (mode === 'title') showTitle();
else if (mode === 'garage') shop.render(); else if (mode === 'garage') shop.render();
else if (mode === 'league') showLeague(); else if (mode === 'league') showLeague();
else if (mode === 'lobby') renderLobby();
if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); } if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); }
}); });
// ---------------------------------------------------------------- start // ---------------------------------------------------------------- start
accounts.resume(); accounts.resume();
if (net && net.enabled) { net.auth.resume(); net.auth.onChange(() => { hud(); if (mode === 'title') showTitle(); }); }
hud(); hud();
if (!view) { if (!view) {
card(`<h1>Robot Clash</h1><p>${t('no_webgl')}</p><p class="credits">${CREDITS}</p>`); card(`<h1>Robot Clash</h1><p>${t('no_webgl')}</p><p class="credits">${CREDITS}</p>`);
} else if (DEV.has('fight') || DEV.has('play')) { } else if (DEV.has('fight') || DEV.has('play')) {
// dev: ?play = straight into the shop, ?fight=N = training fight against league robot N // dev: ?play = straight into the shop, ?fight=N = training fight against league robot N
if (!accounts.current) accounts.guest(); if (!accounts.current) accounts.guest();
slot = Kit.saveSlot(accounts.saveKey(), newSave); save = slot.load(); repairSave(); hud(); loadSave(); hud();
if (DEV.get('equip')) for (const id of DEV.get('equip').split(',')) { const p = RC.PARTS[id]; if (p) { if (!save.owned.includes(id)) save.owned.push(id); save.build[p.slot] = id; } }
if (DEV.get('arena')) settings.arena = DEV.get('arena');
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true); else openGarage(); if (DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true); else openGarage();
// dev: ?play&screen=league|vs|settings|help|lobby|pause opens that screen (layout screenshots)
const scr = DEV.get('screen');
if (scr === 'league') { save.beaten = Math.max(save.beaten, 3); showLeague(); }
else if (scr === 'vs') showVs(RC.LEAGUE[4]);
else if (scr === 'settings') showSettings(openGarage);
else if (scr === 'help') showHelp(openGarage);
else if (scr === 'lobby') {
lobbyRows = [{ uid: 'a', name: 'BlechBrecher', flag: 'DE', fame: 1250, state: 'idle' }, { uid: 'b', name: 'SawQueen', flag: 'DE', fame: 430, state: 'inmatch' }, { uid: 'c', name: 'Rostlaube77', flag: 'AT', fame: 90, state: 'idle' }, { uid: 'd', name: 'Flipmaster', flag: 'GB', fame: 600, state: 'idle' }];
lobbyRoom = DEV.get('room') || null;
showLobby();
}
if (DEV.get('tab')) { const tb = document.querySelector(`.tab[data-slot="${DEV.get('tab')}"]`); if (tb) tb.click(); }
// dev: &buy=<part id> buys it through the real shop buttons (header check)
if (DEV.get('buy')) { const it = document.querySelector(`.item[data-id="${DEV.get('buy')}"]`); if (it) { it.click(); const b = document.querySelector('#detail button[data-act="buy"]'); if (b) b.click(); } }
// dev: &equip=wedge,flamer forces parts onto the robot (ignores cost), then shows the garage
if (DEV.get('equip') && !DEV.has('fight')) { for (const id of DEV.get('equip').split(',')) { const p = RC.PARTS[id]; if (p) { if (!save.owned.includes(id)) save.owned.push(id); save.build[p.slot] = id; } } persist(); view.showGarage(save.build, paintObj()); shop.render(); }
if (DEV.has('paint')) { // dev: open the paint booth with a test drawing if (DEV.has('paint')) { // dev: open the paint booth with a test drawing
const c = layer.getContext('2d'); const c = layer.getContext('2d');
c.fillStyle = '#15171b'; c.fillRect(0, 100, 256, 56); c.fillStyle = '#f2c230'; c.font = 'bold 70px sans-serif'; c.fillText('★ 7', 300, 170); c.fillStyle = '#15171b'; c.fillRect(0, 100, 256, 56); c.fillStyle = '#f2c230'; c.font = 'bold 70px sans-serif'; c.fillText('★ 7', 300, 170);
c.strokeStyle = '#00e5ff'; c.lineWidth = 14; c.beginPath(); c.moveTo(270, 220); c.lineTo(500, 200); c.stroke(); c.strokeStyle = '#00e5ff'; c.lineWidth = 14; c.beginPath(); c.moveTo(270, 220); c.lineTo(500, 200); c.stroke();
painter.open(); view.showGarage(save.build, paintObj()); painter.open(); view.showGarage(save.build, paintObj());
} }
} else if (DEV.has('title')) startIntroOrTitle(); } else if (DEV.has('online') && net.enabled) { startIntroOrTitle(); startOnline(); }
else if (DEV.has('title')) startIntroOrTitle();
else startIntro(); else startIntro();
})(); })();

View File

@@ -46,7 +46,7 @@
button:disabled { opacity: .4; cursor: default; } button:disabled { opacity: .4; cursor: default; }
button:disabled:hover { border-color: var(--line); } button:disabled:hover { border-color: var(--line); }
button.link { background: none; border: none; color: var(--accent); padding: 2px 4px; text-decoration: underline; } button.link { background: none; border: none; color: var(--accent); padding: 2px 4px; text-decoration: underline; }
input[type=text], input[type=password] { font: inherit; width: 100%; padding: 9px 11px; border-radius: 8px; border: 1px solid var(--line); input[type=text], input[type=password], input[type=email] { font: inherit; width: 100%; padding: 9px 11px; border-radius: 8px; border: 1px solid var(--line);
background: #0b0e14; color: var(--text); } background: #0b0e14; color: var(--text); }
input:focus { outline: none; border-color: var(--accent); } input:focus { outline: none; border-color: var(--accent); }
@@ -56,7 +56,7 @@
#overlay.hide { display: none; } #overlay.hide { display: none; }
#overlay.clear { background-color: transparent; } #overlay.clear { background-color: transparent; }
.card { background: rgba(21, 25, 32, .94); border: 1px solid var(--line); border-radius: 14px; padding: 22px 30px; .card { background: rgba(21, 25, 32, .94); border: 1px solid var(--line); border-radius: 14px; padding: 22px 30px;
min-width: 380px; max-width: 760px; text-align: center; box-shadow: 0 20px 60px #000a; } min-width: 380px; max-width: 760px; max-height: 520px; overflow-y: auto; text-align: center; box-shadow: 0 20px 60px #000a; }
.card h1 { margin: 0 0 6px; font: 44px var(--head); letter-spacing: .05em; color: var(--accent); text-shadow: 0 3px 0 #5a2600; } .card h1 { margin: 0 0 6px; font: 44px var(--head); letter-spacing: .05em; color: var(--accent); text-shadow: 0 3px 0 #5a2600; }
.card h2 { margin: 0 0 8px; font: 26px var(--head); letter-spacing: .04em; color: var(--accent); } .card h2 { margin: 0 0 8px; font: 26px var(--head); letter-spacing: .04em; color: var(--accent); }
.card h3 { margin: 12px 0 6px; font: 14px var(--head); letter-spacing: .06em; color: var(--dim); text-align: left; } .card h3 { margin: 12px 0 6px; font: 14px var(--head); letter-spacing: .06em; color: var(--dim); text-align: left; }
@@ -93,6 +93,14 @@
.seg { display: flex; gap: 4px; } .seg { display: flex; gap: 4px; }
.seg button { flex: 1; padding: 5px 8px; font-size: 13px; } .seg button { flex: 1; padding: 5px 8px; font-size: 13px; }
.seg button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; } .seg button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
/* compact settings: two columns of label + control */
.set2 { display: grid; grid-template-columns: 96px 1fr 96px 1fr; gap: 7px 12px; align-items: center; text-align: left; min-width: 680px; }
.set2 .sl, .setacc .sl { font-size: 13px; color: var(--dim); }
.set2 .seg button { padding: 6px 4px; font-size: 12px; min-height: 32px; }
.set2 input[type=range] { width: 100%; accent-color: var(--accent); height: 28px; }
.setacc { display: grid; grid-template-columns: 96px 1fr auto; gap: 12px; align-items: center; text-align: left; margin-top: 12px;
padding-top: 10px; border-top: 1px solid var(--line); }
.setacc .who { font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* league */ /* league */
.opps { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 10px 0; } .opps { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 10px 0; }
@@ -196,6 +204,45 @@
.pt-colors input[type=color] { width: 34px; height: 26px; border: none; background: none; padding: 0; cursor: pointer; } .pt-colors input[type=color] { width: 34px; height: 26px; border: none; background: none; padding: 0; cursor: pointer; }
#bPaint { align-self: flex-start; } #bPaint { align-self: flex-start; }
/* lobby (touch-friendly: big rows + buttons) */
.lobbybar { display: flex; align-items: center; gap: 10px; margin: 6px 0 10px; flex-wrap: wrap; }
.flags { display: flex; gap: 4px; flex-wrap: wrap; }
.flag { padding: 5px 6px; line-height: 0; }
/* flags drawn with CSS (no flag emoji on Windows) */
.fl { display: inline-block; width: 30px; height: 20px; border-radius: 3px; vertical-align: middle; box-shadow: 0 0 0 1px rgba(255,255,255,.25); background: #555; }
.fl-DE { background: linear-gradient(#000 33.3%, #dd0000 33.3% 66.6%, #ffce00 66.6%); }
.fl-AT { background: linear-gradient(#c8102e 33.3%, #fff 33.3% 66.6%, #c8102e 66.6%); }
.fl-CH { background: linear-gradient(#fff, #fff) center / 56% 20% no-repeat, linear-gradient(#fff, #fff) center / 20% 56% no-repeat, #d52b1e; }
.fl-GB { background: linear-gradient(#c8102e, #c8102e) center / 100% 18% no-repeat, linear-gradient(#c8102e, #c8102e) center / 12% 100% no-repeat,
linear-gradient(#fff, #fff) center / 100% 34% no-repeat, linear-gradient(#fff, #fff) center / 22% 100% no-repeat, #012169; }
.fl-US { background: linear-gradient(#3c3b6e, #3c3b6e) left top / 42% 54% no-repeat, repeating-linear-gradient(#b22234 0 15.4%, #fff 15.4% 30.8%); }
.fl-FR { background: linear-gradient(90deg, #0055a4 33.3%, #fff 33.3% 66.6%, #ef4135 66.6%); }
.fl-ES { background: linear-gradient(#aa151b 25%, #f1bf00 25% 75%, #aa151b 75%); }
.fl-IT { background: linear-gradient(90deg, #009246 33.3%, #fff 33.3% 66.6%, #ce2b37 66.6%); }
.fl-NL { background: linear-gradient(#ae1c28 33.3%, #fff 33.3% 66.6%, #21468b 66.6%); }
.fl-PL { background: linear-gradient(#fff 50%, #dc143c 50%); }
.fl-TR { background: radial-gradient(circle at 42% 50%, #fff 0 20%, transparent 21%), #e30a17; }
.fl-RU { background: linear-gradient(#fff 33.3%, #0039a6 33.3% 66.6%, #d52b1e 66.6%); }
.fl-BR { background: radial-gradient(circle, #002776 0 22%, #fedf00 23% 46%, transparent 47%), #009b3a; }
.fl-JP { background: radial-gradient(circle, #bc002d 0 30%, transparent 31%), #fff; }
.fl-KR { background: radial-gradient(circle, #cd2e3a 0 14%, #0047a0 15% 28%, transparent 29%), #fff; }
.fl-XX { background: repeating-linear-gradient(45deg, #5a6272 0 5px, #454c5a 5px 10px); }
.flag.on { background: var(--accent); border-color: var(--accent); }
.plist { max-height: 300px; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; margin: 4px 0; }
.prow { display: grid; grid-template-columns: 34px 1fr auto auto; gap: 10px; align-items: center;
background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 9px 12px; }
.prow .pf { line-height: 0; } .prow .pn { font: 16px var(--head); letter-spacing: .02em; text-align: left; }
.prow .pfame { color: var(--gold); font-size: 13px; font-variant-numeric: tabular-nums; }
.prow .chal { padding: 8px 16px; background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
.prow .pbusy { color: var(--dim); font-size: 13px; padding: 8px 10px; }
.prow.me { border-color: var(--accent); background: #2a1c10; }
/* country rooms */
.rooms { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 8px 0; }
.room { display: grid; grid-template-columns: 34px 1fr auto; gap: 8px; align-items: center; padding: 10px 12px; min-height: 48px; text-align: left; }
.room .rn { font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.room .rc { font-size: 12px; color: var(--dim); font-variant-numeric: tabular-nums; }
.room.live .rc { color: var(--good); font-weight: 700; }
/* fight HUD */ /* fight HUD */
#fightHud { position: absolute; left: 0; right: 0; top: 0; padding: 10px 14px; display: grid; grid-template-columns: 1fr 150px 1fr; #fightHud { position: absolute; left: 0; right: 0; top: 0; padding: 10px 14px; display: grid; grid-template-columns: 1fr 150px 1fr;
gap: 12px; pointer-events: none; z-index: 4; } gap: 12px; pointer-events: none; z-index: 4; }
@@ -218,6 +265,10 @@
#pad .fire button { height: 74px; font-size: 14px; font-weight: 700; } #pad .fire button { height: 74px; font-size: 14px; font-weight: 700; }
@media (pointer: coarse) { body.fighting #pad { display: flex; } } @media (pointer: coarse) { body.fighting #pad { display: flex; } }
/* tablets / phones held upright: ask to rotate (the stage is 16:9) */
#rotate { display: none; position: fixed; left: 0; right: 0; bottom: 12%; text-align: center; z-index: 20; font: 20px var(--head); color: var(--accent); padding: 0 20px; }
@media (pointer: coarse) and (orientation: portrait) { #rotate { display: block; } }
/* window buttons: only inside the exe (html.exe set by kit-host.js) */ /* window buttons: only inside the exe (html.exe set by kit-host.js) */
#winctl { position: fixed; top: 8px; right: 8px; display: none; gap: 6px; z-index: 10; } #winctl { position: fixed; top: 8px; right: 8px; display: none; gap: 6px; z-index: 10; }
html.exe #winctl { display: flex; } html.exe #winctl { display: flex; }
@@ -231,6 +282,7 @@
<button onclick="Kit.host.quit()" data-i18n-title="win_close">&#10005;</button> <button onclick="Kit.host.quit()" data-i18n-title="win_close">&#10005;</button>
</div> </div>
<div id="rotate">&#x21BB; <span data-i18n="rotate_hint">Turn your device sideways</span></div>
<div id="app"> <div id="app">
<div id="hud"> <div id="hud">
<div class="logo">ROBOT CLASH</div> <div class="logo">ROBOT CLASH</div>
@@ -265,6 +317,7 @@
<div class="gbar"> <div class="gbar">
<div class="err" id="gErr"></div> <div class="err" id="gErr"></div>
<button id="bGMenu" data-i18n="menu">Menu</button> <button id="bGMenu" data-i18n="menu">Menu</button>
<button id="bGOnline" data-i18n="online_short">Online</button>
<button id="bTrain" data-i18n="training">Training</button> <button id="bTrain" data-i18n="training">Training</button>
<button class="primary" id="bLeague" data-i18n="to_league">League</button> <button class="primary" id="bLeague" data-i18n="to_league">League</button>
</div> </div>
@@ -305,7 +358,11 @@
<script src="combat.js"></script> <script src="combat.js"></script>
<script src="ai.js"></script> <script src="ai.js"></script>
<script src="profiles.js"></script> <script src="profiles.js"></script>
<script src="net.js"></script>
<script src="lobby.js"></script>
<script src="looks.js"></script>
<script src="render3d.js"></script> <script src="render3d.js"></script>
<script src="netfight.js"></script>
<script src="shop.js"></script> <script src="shop.js"></script>
<script src="painter.js"></script> <script src="painter.js"></script>
<script src="game.js"></script> <script src="game.js"></script>

View File

@@ -17,7 +17,7 @@ window.LANG = {
reset_text: 'Delete your robot, credits and league progress and start again?', reset_text: 'Delete your robot, credits and league progress and start again?',
reset_yes: 'Yes, start over', cancel: 'Cancel', ok: 'OK', back: 'Back', menu: 'Menu', reset_yes: 'Yes, start over', cancel: 'Cancel', ok: 'OK', back: 'Back', menu: 'Menu',
help_text: 'In the <b>workshop</b> you fit one chassis, motor, wheels and battery, plus armour, a weapon and a tower. Keep under <b>100 kg</b>, and the battery must supply enough power. Win fights for credits and buy better parts.', help_text: 'In the <b>workshop</b> you fit one chassis, motor, wheels and battery, plus armour, a weapon and a tower. Keep under <b>100 kg</b>, and the battery must supply enough power. Win fights for credits and buy better parts.',
key_drive: 'drive (tank steering)', key_space: 'Space', key_weapon: 'main weapon', key_tower: 'tower weapon', key_drive: 'drive (simple: screen direction, tank: turn + throttle)', key_space: 'Space', key_weapon: 'main weapon', key_tower: 'tower weapon',
key_pad: 'Gamepad', key_pad_text: 'stick, A = weapon, B = tower', key_pad: 'Gamepad', key_pad_text: 'stick, A = weapon, B = tower',
help_arena: 'You win by <b>knockout</b>, by pushing the enemy into the <b>pit</b> (it opens at half time) or on damage when the time runs out. Watch the floor saws, flame grilles, spike walls, the <b>forge press</b> and the <b>magnet crane</b> in the corners!', help_arena: 'You win by <b>knockout</b>, by pushing the enemy into the <b>pit</b> (it opens at half time) or on damage when the time runs out. Watch the floor saws, flame grilles, spike walls, the <b>forge press</b> and the <b>magnet crane</b> in the corners!',
loading: 'loading…', ranking: 'Fame ranking', loading: 'loading…', ranking: 'Fame ranking',
@@ -69,7 +69,7 @@ window.LANG = {
// fight // fight
pad_weapon: 'Weapon', pad_tower: 'Tower', pad_weapon: 'Weapon', pad_tower: 'Tower',
fight_go: 'ACTIVATE!', pit_open: 'PIT OPEN!', into_pit: 'INTO THE PIT!', knockout: 'KNOCKOUT!', fight_go: 'ACTIVATE!', pit_open: 'PIT OPEN!', into_pit: 'INTO THE PIT!', knockout: 'KNOCKOUT!',
fight_hint: 'W A S D drive · Space weapon · Shift / E tower · P pause', fight_hint: 'W/S drive · A/D turn · Space weapon · Shift / E tower · C camera · P pause',
st_lifted: 'MAGNET!', st_grabbed: 'GRABBED!', st_flipped: 'UPSIDE DOWN!', st_stunned: 'STUNNED', pit_is_open: 'PIT IS OPEN', pit_soon: 'pit opens soon', st_lifted: 'MAGNET!', st_grabbed: 'GRABBED!', st_flipped: 'UPSIDE DOWN!', st_stunned: 'STUNNED', pit_is_open: 'PIT IS OPEN', pit_soon: 'pit opens soon',
continue: 'Continue', give_up: 'Give up', continue: 'Continue', give_up: 'Give up',
// result // result
@@ -102,16 +102,62 @@ window.LANG = {
s_screen: 'Display', s_controls: 'Controls', s_career: 'Career', on: 'On', off: 'Off', s_screen: 'Display', s_controls: 'Controls', s_career: 'Career', on: 'On', off: 'Off',
gfx_low: 'Low', gfx_medium: 'Medium', gfx_high: 'High', gfx_low: 'Low', gfx_medium: 'Medium', gfx_high: 'High',
// paint booth // paint booth
// online lobby + live PvP
rotate_hint: 'Turn your device sideways for a bigger picture',
s_account: 'Account',
s_arena: 'Arena', arena_random: 'Random', arena_workshop: 'Workshop Pit', arena_foundry: 'The Foundry', arena_arena64: 'Mega Dome',
peer_back: 'Opponent is back', no_pause_online: 'No pause in live fights',
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',
pick_room: 'Pick your country - then you see who is sitting in that lobby.',
cc_DE: 'Germany',
cc_AT: 'Austria',
cc_CH: 'Switzerland',
cc_GB: 'United Kingdom',
cc_US: 'USA',
cc_FR: 'France',
cc_ES: 'Spain',
cc_IT: 'Italy',
cc_NL: 'Netherlands',
cc_PL: 'Poland',
cc_TR: 'Turkey',
cc_RU: 'Russia',
cc_BR: 'Brazil',
cc_JP: 'Japan',
cc_KR: 'Korea',
cc_XX: 'International',
online_play: 'Play online', online_login_text: 'One account for your career and the online lobby - your robot and progress go with it.',
f_email: 'E-mail',
lobby: 'Global lobby', lobby_empty: 'Nobody else online right now. Keep this open - players show up here.',
your_flag: 'Your flag:', challenge: 'Challenge', busy: 'in a fight', quick_match: 'Quick match',
waiting_accept: 'Waiting for the other player...', challenge_in: 'Challenge!', wants_fight: 'wants to fight you!',
accept: 'Accept', decline: 'Decline', back_to_lobby: 'Back to lobby',
peer_lost: 'Connection to opponent lost - AI takes over', peer_left: '(left the fight)',
e_EMAIL_EXISTS: 'That e-mail is already registered.', e_EMAIL_NOT_FOUND: 'No account with that e-mail.',
e_INVALID_PASSWORD: 'Wrong password.', e_INVALID_LOGIN_CREDENTIALS: 'Wrong e-mail or password.',
e_WEAK_PASSWORD: 'Password needs at least 6 characters.', e_INVALID_EMAIL: 'That is not a valid e-mail.',
e_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.',
pt_open: '🎨 Paint it yourself', pt_title: 'Paint booth', pt_top: 'TOP VIEW · front', pt_side: 'SIDE · front', pt_open: '🎨 Paint it yourself', pt_title: 'Paint booth', pt_top: 'TOP VIEW · front', pt_side: 'SIDE · front',
pt_view_top: 'Top', pt_view_right: 'Right', pt_view_left: 'Left', pt_view_front: 'Front', pt_view_free: 'Turn', pt_view_top: 'Top', pt_view_right: 'Right', pt_view_left: 'Left', pt_view_front: 'Front', pt_view_free: 'Turn',
pt_brush: 'Brush', pt_spray: 'Spray', pt_erase: 'Eraser', pt_stamp: 'Stamp', pt_text: 'Text', pt_fill: 'Fill', pt_brush: 'Brush', pt_spray: 'Spray', pt_erase: 'Eraser', pt_stamp: 'Stamp', pt_text: 'Text', pt_fill: 'Fill',
pt_mirror: 'Mirror both sides', pt_size: 'Size', pt_undo: 'Undo', pt_clear: 'Clear all', pt_done: 'Done', pt_text_ph: 'Text or number', pt_mirror: 'Mirror both sides', pt_size: 'Size', pt_undo: 'Undo', pt_clear: 'Clear all', pt_done: 'Done', pt_text_ph: 'Text or number',
s_cam: 'Camera', cam_iso: 'Arena', cam_chase: 'Chase', cam_fpv: 'Cockpit', key_cam: 'switch camera',
// easier play + income
s_diff: 'Difficulty', diff_easy: 'Easy', diff_normal: 'Normal', diff_hard: 'Hard',
s_steer: 'Steering', steer_simple: 'Simple', steer_tank: 'Tank',
s_autofire: 'Weapon helper',
fight_hint_simple: 'W A S D: drive in that direction · Space weapon · Shift / E tower · C camera · P pause',
exhibition_hint: 'Tip: click a beaten opponent for an exhibition fight - half the prize, as often as you like.',
exhibition_note: 'Exhibition fight: half prize money, no league progress.',
exhibition_btn: 'Exhibition fight!', r_exhibition: 'Exhibition prize', r_dmg_bonus: 'Damage bonus',
// shop // shop
owned: 'owned', need_money: '{n} credits missing', fight_go_btn: 'Into the arena!', owned: 'owned', need_money: '{n} credits missing', fight_go_btn: 'Into the arena!',
tip_bought: '{name}? Good choice. Let me bolt that on.', tip_bought: '{name}? Good choice. Let me bolt that on.',
tip_overweight: 'Too heavy! The judges weigh every robot - drop a part or pick lighter armour.', tip_overweight: 'Too heavy! The judges weigh every robot - drop a part or pick lighter armour.',
tip_power: 'Your battery can\'t feed all that. Buy a stronger battery or a weapon that needs less power.', tip_power: 'Your battery can\'t feed all that. Buy a stronger battery or a weapon that needs less power.',
tip_0: 'Welcome to the workshop! Pick a category on top and click a part to see what it does.', tip_0: 'Welcome to the workshop! Pick a category on top and click a part to see what it does. Tip: a flipper is a great first buy.',
tip_1: 'The white bar in the stats shows how your robot changes with the selected part.', tip_1: 'The white bar in the stats shows how your robot changes with the selected part.',
tip_2: 'A wedge plus a strong motor is cheap and nasty - shove them into the saws!', tip_2: 'A wedge plus a strong motor is cheap and nasty - shove them into the saws!',
tip_3: 'Big tyres keep you driving when a flipper turns you over.', tip_3: 'Big tyres keep you driving when a flipper turns you over.',
@@ -119,7 +165,10 @@ window.LANG = {
tip_5: 'Stay out of the corners: the forge press and the magnet crane don\'t care whose robot it is.', tip_5: 'Stay out of the corners: the forge press and the magnet crane don\'t care whose robot it is.',
tip_6: 'Tracks win every shoving match, but they are slow.', tip_6: 'Tracks win every shoving match, but they are slow.',
tip_7: 'Hammers ignore half of the armour. Great against heavy plates.', tip_7: 'Hammers ignore half of the armour. Great against heavy plates.',
tip_8: 'Lost a fight? You still get an appearance fee - repairs come off your winnings.', tip_8: 'Lost a fight? You still get an appearance fee and a bonus for every hit.',
tip_9: 'Short on credits? Beat an old opponent again in an exhibition fight.',
tip_10: 'Too hard? Settings: difficulty Easy, weapon helper on.',
tip_11: 'Your 800 starting credits buy a flipper right away - it beats saw robots easily.',
}, },
de: { de: {
lang_self: 'Deutsch', lang_self: 'Deutsch',
@@ -135,7 +184,7 @@ window.LANG = {
reset_text: 'Roboter, Credits und Liga-Fortschritt löschen und neu anfangen?', reset_text: 'Roboter, Credits und Liga-Fortschritt löschen und neu anfangen?',
reset_yes: 'Ja, neu anfangen', cancel: 'Abbrechen', ok: 'OK', back: 'Zurück', menu: 'Menü', reset_yes: 'Ja, neu anfangen', cancel: 'Abbrechen', ok: 'OK', back: 'Zurück', menu: 'Menü',
help_text: 'In der <b>Werkstatt</b> baust du je ein Chassis, einen Motor, Räder und eine Batterie ein, dazu Panzerung, Waffe und Turm. Bleib unter <b>100 kg</b>, und die Batterie muss genug Strom liefern. Siege bringen Credits für bessere Teile.', help_text: 'In der <b>Werkstatt</b> baust du je ein Chassis, einen Motor, Räder und eine Batterie ein, dazu Panzerung, Waffe und Turm. Bleib unter <b>100 kg</b>, und die Batterie muss genug Strom liefern. Siege bringen Credits für bessere Teile.',
key_drive: 'fahren (Panzersteuerung)', key_space: 'Leertaste', key_weapon: 'Hauptwaffe', key_tower: 'Turmwaffe', key_drive: 'fahren (einfach: Bildschirmrichtung, Panzer: drehen + Gas)', key_space: 'Leertaste', key_weapon: 'Hauptwaffe', key_tower: 'Turmwaffe',
key_pad: 'Gamepad', key_pad_text: 'Stick, A = Waffe, B = Turm', key_pad: 'Gamepad', key_pad_text: 'Stick, A = Waffe, B = Turm',
help_arena: 'Du gewinnst durch <b>K.o.</b>, indem du den Gegner in die <b>Grube</b> schiebst (öffnet zur Halbzeit) oder nach Schaden, wenn die Zeit abläuft. Achtung vor Bodensägen, Flammengittern, Stachelwänden, der <b>Schmiedepresse</b> und dem <b>Magnetkran</b> in den Ecken!', help_arena: 'Du gewinnst durch <b>K.o.</b>, indem du den Gegner in die <b>Grube</b> schiebst (öffnet zur Halbzeit) oder nach Schaden, wenn die Zeit abläuft. Achtung vor Bodensägen, Flammengittern, Stachelwänden, der <b>Schmiedepresse</b> und dem <b>Magnetkran</b> in den Ecken!',
loading: 'lädt…', ranking: 'Ruhmesliste', loading: 'lädt…', ranking: 'Ruhmesliste',
@@ -187,7 +236,7 @@ window.LANG = {
// fight // fight
pad_weapon: 'Waffe', pad_tower: 'Turm', pad_weapon: 'Waffe', pad_tower: 'Turm',
fight_go: 'AKTIVIEREN!', pit_open: 'GRUBE OFFEN!', into_pit: 'IN DIE GRUBE!', knockout: 'K.O.!', fight_go: 'AKTIVIEREN!', pit_open: 'GRUBE OFFEN!', into_pit: 'IN DIE GRUBE!', knockout: 'K.O.!',
fight_hint: 'W A S D fahren · Leertaste Waffe · Shift / E Turm · P Pause', fight_hint: 'W/S fahren · A/D drehen · Leertaste Waffe · Shift / E Turm · C Kamera · P Pause',
st_lifted: 'MAGNET!', st_grabbed: 'GEPACKT!', st_flipped: 'AUF DEM KOPF!', st_stunned: 'BETÄUBT', pit_is_open: 'GRUBE IST OFFEN', pit_soon: 'Grube öffnet gleich', st_lifted: 'MAGNET!', st_grabbed: 'GEPACKT!', st_flipped: 'AUF DEM KOPF!', st_stunned: 'BETÄUBT', pit_is_open: 'GRUBE IST OFFEN', pit_soon: 'Grube öffnet gleich',
continue: 'Weiter', give_up: 'Aufgeben', continue: 'Weiter', give_up: 'Aufgeben',
// result // result
@@ -220,16 +269,62 @@ window.LANG = {
s_screen: 'Anzeige', s_controls: 'Steuerung', s_career: 'Karriere', on: 'An', off: 'Aus', s_screen: 'Anzeige', s_controls: 'Steuerung', s_career: 'Karriere', on: 'An', off: 'Aus',
gfx_low: 'Niedrig', gfx_medium: 'Mittel', gfx_high: 'Hoch', gfx_low: 'Niedrig', gfx_medium: 'Mittel', gfx_high: 'Hoch',
// paint booth // paint booth
// online lobby + live PvP
rotate_hint: 'Dreh dein Gerät quer für ein größeres Bild',
s_account: 'Konto',
s_arena: 'Arena', arena_random: 'Zufällig', arena_workshop: 'Werkstatt-Grube', arena_foundry: 'Die Gießerei', arena_arena64: 'Mega-Dome',
peer_back: 'Gegner ist wieder da', no_pause_online: 'Keine Pause im Live-Kampf',
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',
pick_room: 'Wähl dein Land - dann siehst du, wer in dieser Lobby sitzt.',
cc_DE: 'Deutschland',
cc_AT: 'Österreich',
cc_CH: 'Schweiz',
cc_GB: 'Großbritannien',
cc_US: 'USA',
cc_FR: 'Frankreich',
cc_ES: 'Spanien',
cc_IT: 'Italien',
cc_NL: 'Niederlande',
cc_PL: 'Polen',
cc_TR: 'Türkei',
cc_RU: 'Russland',
cc_BR: 'Brasilien',
cc_JP: 'Japan',
cc_KR: 'Korea',
cc_XX: 'International',
online_play: 'Online spielen', online_login_text: 'Ein Konto für Karriere und Online-Lobby - dein Roboter und Fortschritt gehören dazu.',
f_email: 'E-Mail',
lobby: 'Globale Lobby', lobby_empty: 'Gerade ist niemand sonst online. Lass das Fenster offen - Spieler erscheinen hier.',
your_flag: 'Deine Flagge:', challenge: 'Herausfordern', busy: 'im Kampf', quick_match: 'Schnelles Match',
waiting_accept: 'Warte auf den anderen Spieler...', challenge_in: 'Herausforderung!', wants_fight: 'will gegen dich kämpfen!',
accept: 'Annehmen', decline: 'Ablehnen', back_to_lobby: 'Zurück zur Lobby',
peer_lost: 'Verbindung zum Gegner weg - KI übernimmt', peer_left: '(hat den Kampf verlassen)',
e_EMAIL_EXISTS: 'Diese E-Mail ist schon registriert.', e_EMAIL_NOT_FOUND: 'Kein Konto mit dieser E-Mail.',
e_INVALID_PASSWORD: 'Falsches Passwort.', e_INVALID_LOGIN_CREDENTIALS: 'E-Mail oder Passwort falsch.',
e_WEAK_PASSWORD: 'Passwort braucht mindestens 6 Zeichen.', e_INVALID_EMAIL: 'Das ist keine gültige E-Mail.',
e_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.',
pt_open: '🎨 Selbst bemalen', pt_title: 'Lackiererei', pt_top: 'OBEN · vorne', pt_side: 'SEITE · vorne', pt_open: '🎨 Selbst bemalen', pt_title: 'Lackiererei', pt_top: 'OBEN · vorne', pt_side: 'SEITE · vorne',
pt_view_top: 'Oben', pt_view_right: 'Rechts', pt_view_left: 'Links', pt_view_front: 'Vorne', pt_view_free: 'Drehen', pt_view_top: 'Oben', pt_view_right: 'Rechts', pt_view_left: 'Links', pt_view_front: 'Vorne', pt_view_free: 'Drehen',
pt_brush: 'Pinsel', pt_spray: 'Spray', pt_erase: 'Radierer', pt_stamp: 'Stempel', pt_text: 'Text', pt_fill: 'Füllen', pt_brush: 'Pinsel', pt_spray: 'Spray', pt_erase: 'Radierer', pt_stamp: 'Stempel', pt_text: 'Text', pt_fill: 'Füllen',
pt_mirror: 'Beide Seiten spiegeln', pt_size: 'Größe', pt_undo: 'Zurück', pt_clear: 'Alles löschen', pt_done: 'Fertig', pt_text_ph: 'Text oder Nummer', pt_mirror: 'Beide Seiten spiegeln', pt_size: 'Größe', pt_undo: 'Zurück', pt_clear: 'Alles löschen', pt_done: 'Fertig', pt_text_ph: 'Text oder Nummer',
s_cam: 'Kamera', cam_iso: 'Arena', cam_chase: 'Verfolger', cam_fpv: 'Cockpit', key_cam: 'Kamera wechseln',
// easier play + income
s_diff: 'Schwierigkeit', diff_easy: 'Leicht', diff_normal: 'Normal', diff_hard: 'Schwer',
s_steer: 'Steuerung', steer_simple: 'Einfach', steer_tank: 'Panzer',
s_autofire: 'Waffen-Hilfe',
fight_hint_simple: 'W A S D: in diese Richtung fahren · Leertaste Waffe · Shift / E Turm · C Kamera · P Pause',
exhibition_hint: 'Tipp: Klick einen besiegten Gegner für einen Schaukampf – halbes Preisgeld, so oft du willst.',
exhibition_note: 'Schaukampf: halbes Preisgeld, kein Liga-Fortschritt.',
exhibition_btn: 'Schaukampf!', r_exhibition: 'Schaukampf-Preis', r_dmg_bonus: 'Schadensbonus',
// shop // shop
owned: 'im Besitz', need_money: 'Es fehlen {n} Credits', fight_go_btn: 'Ab in die Arena!', owned: 'im Besitz', need_money: 'Es fehlen {n} Credits', fight_go_btn: 'Ab in die Arena!',
tip_bought: '{name}? Gute Wahl. Ich schraub das gleich dran.', tip_bought: '{name}? Gute Wahl. Ich schraub das gleich dran.',
tip_overweight: 'Zu schwer! Jeder Roboter wird gewogen – lass ein Teil weg oder nimm leichtere Panzerung.', tip_overweight: 'Zu schwer! Jeder Roboter wird gewogen – lass ein Teil weg oder nimm leichtere Panzerung.',
tip_power: 'Deine Batterie schafft das nicht. Kauf eine stärkere oder nimm eine Waffe mit weniger Strombedarf.', tip_power: 'Deine Batterie schafft das nicht. Kauf eine stärkere oder nimm eine Waffe mit weniger Strombedarf.',
tip_0: 'Willkommen in der Werkstatt! Wähl oben eine Kategorie und klick ein Teil an, um zu sehen, was es kann.', tip_0: 'Willkommen in der Werkstatt! Wähl oben eine Kategorie und klick ein Teil an, um zu sehen, was es kann. Tipp: Ein Flipper ist ein super erster Kauf.',
tip_1: 'Der weiße Balken bei den Werten zeigt, wie sich dein Roboter mit dem gewählten Teil ändert.', tip_1: 'Der weiße Balken bei den Werten zeigt, wie sich dein Roboter mit dem gewählten Teil ändert.',
tip_2: 'Keil plus starker Motor: billig und gemein – schieb sie in die Sägen!', tip_2: 'Keil plus starker Motor: billig und gemein – schieb sie in die Sägen!',
tip_3: 'Große Reifen fahren weiter, wenn dich ein Flipper umdreht.', tip_3: 'Große Reifen fahren weiter, wenn dich ein Flipper umdreht.',
@@ -237,6 +332,9 @@ window.LANG = {
tip_5: 'Bleib aus den Ecken: Schmiedepresse und Magnetkran ist egal, wessen Roboter da steht.', tip_5: 'Bleib aus den Ecken: Schmiedepresse und Magnetkran ist egal, wessen Roboter da steht.',
tip_6: 'Ketten gewinnen jedes Schiebeduell, sind aber langsam.', tip_6: 'Ketten gewinnen jedes Schiebeduell, sind aber langsam.',
tip_7: 'Hämmer ignorieren die halbe Panzerung. Ideal gegen dicke Platten.', tip_7: 'Hämmer ignorieren die halbe Panzerung. Ideal gegen dicke Platten.',
tip_8: 'Kampf verloren? Antrittsgeld gibt es trotzdem – die Reparatur geht davon ab.', tip_8: 'Kampf verloren? Antrittsgeld gibt es trotzdem, dazu einen Bonus für jeden Treffer.',
tip_9: 'Knapp bei Kasse? Besieg einen alten Gegner nochmal im Schaukampf.',
tip_10: 'Zu schwer? Einstellungen: Schwierigkeit Leicht, Waffen-Hilfe an.',
tip_11: 'Mit deinen 800 Start-Credits kannst du sofort einen Flipper kaufen – der schlägt Säge-Roboter locker.',
}, },
}; };

132
game/lobby.js Normal file
View File

@@ -0,0 +1,132 @@
/* Robot Clash - online lobby: presence, player list, challenges, match creation. No DOM.
Needs net.js (RC.Net). Transport is Firebase RTDB (net.db). All cosmetic/casual, see docs/firebase.
const lobby = RC.Lobby({ net, getProfile: () => ({ name, flag, build, paint, fame }) });
lobby.enter() announce presence, start heartbeat, watch list + incoming challenges
lobby.leave() remove presence, stop everything
lobby.onList(fn) fn([{ uid, name, flag, state, fame }]) - online players except me, newest first
lobby.onIncoming(fn) fn({ from, fromName, fromFlag, build, paint, seed }) - someone challenges me
lobby.onMatch(fn) fn({ id, host (bool), opp: { uid, name, flag, build, paint }, seed }) - fight on
lobby.onCancel(fn) fn() - a pending challenge I sent/got fell through
await lobby.challenge(uid) invite a player (writes to their inbox, waits for accept)
await lobby.accept(from) accept an incoming challenge -> creates the match
lobby.decline(from) reject an incoming challenge
lobby.cancel() withdraw the challenge I sent
Presence TTL: entries older than STALE ms count as offline (no SDK onDisconnect). */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const HEARTBEAT = 4000, STALE = 12000;
const now = () => Date.now();
// match id = both uids sorted + join -> same id on both sides; lower uid hosts (authority)
const matchId = (a, b) => [a, b].sort().join('_');
const isHost = (a, b) => a < b;
RC.Lobby = (opt) => {
const net = opt.net, db = net.db;
const cbs = { list: [], incoming: [], match: [], cancel: [] };
const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { /* ignore */ } });
let hb = null, subList = null, subIn = null, subMatch = null;
let outgoing = null; // uid I challenged
let inMatch = null; // active match id
const me = () => net.uid;
const prof = () => opt.getProfile();
async function beat(state) {
const p = prof();
await db.put(`lobby/${me()}`, { name: p.name, flag: p.flag || 'XX', fame: p.fame | 0, ver: 2, state: state || 'idle', ts: { '.sv': 'timestamp' } });
}
function watchList() {
subList = db.stream('lobby', data => {
const t = now(), mine = me();
const rows = Object.entries(data || {})
.map(([uid, v]) => Object.assign({ uid }, v))
.filter(v => v.uid !== mine && v.name && (t - (v.ts || 0)) < STALE)
.sort((a, b) => (b.ts || 0) - (a.ts || 0));
emit('list', rows);
});
}
// incoming challenges land under challenges/<me>/<fromUid>
function watchIncoming() {
subIn = db.stream(`challenges/${me()}`, data => {
const entries = Object.entries(data || {}).filter(([, v]) => v && v.from && (now() - (v.ts || 0)) < STALE);
if (!entries.length) return;
const [, c] = entries[0];
emit('incoming', { from: c.from, fromName: c.fromName, fromFlag: c.fromFlag, build: c.build, paint: c.paint, seed: c.seed });
});
}
// the match node appears for both players once created (host writes it on accept)
function watchMatch(id, oppUid, host) {
cleanupMatch();
inMatch = id;
subMatch = db.stream(`matches/${id}/meta`, meta => {
// wait until BOTH players have written their robot (each side patches its own entry)
if (!meta || inMatch !== id || meta.seed == null || !meta[oppUid] || !meta[me()]) return;
emit('match', { id, host, opp: { uid: oppUid, name: meta[oppUid] && meta[oppUid].name, flag: meta[oppUid] && meta[oppUid].flag, build: meta[oppUid] && meta[oppUid].build, paint: meta[oppUid] && meta[oppUid].paint }, seed: meta.seed });
if (subMatch) { subMatch.close(); subMatch = null; } // meta is fixed; stop watching
});
}
function cleanupMatch() { if (subMatch) { subMatch.close(); subMatch = null; } }
async function challenge(uid) {
if (outgoing) return;
outgoing = uid;
const p = prof();
await beat('searching');
await db.put(`challenges/${uid}/${me()}`, { from: me(), fromName: p.name, fromFlag: p.flag || 'XX', build: p.build, paint: p.paint, seed: (Math.random() * 1e9) | 0, ts: { '.sv': 'timestamp' } });
// wait for the other side to create the match (they host if their uid < mine)
const id = matchId(me(), uid), host = isHost(me(), uid);
const give = setTimeout(() => { if (outgoing === uid) { emit('cancel'); cancel(); } }, STALE);
const watch = db.stream(`matches/${id}/meta/seed`, seed => {
if (seed == null) return;
clearTimeout(give); watch.close(); outgoing = null;
createMatch(uid); // add my own robot to the match meta
watchMatch(id, uid, host);
});
}
async function accept(from) {
const id = matchId(me(), from), host = isHost(me(), from);
await db.del(`challenges/${me()}/${from}`);
await createMatch(from);
watchMatch(id, from, host);
}
function decline(from) { db.del(`challenges/${me()}/${from}`); }
function cancel() { if (outgoing) { db.del(`challenges/${outgoing}/${me()}`); outgoing = null; beat('idle'); } }
async function createMatch(oppUid) {
const id = matchId(me(), oppUid), p = prof();
const seed = (parseInt(id.slice(-6), 36) % 1e9) || 1; // same on both sides
// meta holds both players' robots; written once, guarded so the first writer wins
await db.patch(`matches/${id}/meta`, { seed, [me()]: { name: p.name, flag: p.flag || 'XX', build: p.build, paint: p.paint } });
await beat('inmatch');
}
return {
onList: fn => cbs.list.push(fn),
onIncoming: fn => cbs.incoming.push(fn),
onMatch: fn => cbs.match.push(fn),
onCancel: fn => cbs.cancel.push(fn),
challenge, accept, decline, cancel,
async enter() {
if (!net.enabled || !me()) return;
await beat('idle');
hb = setInterval(() => db.patch(`lobby/${me()}`, { ts: { '.sv': 'timestamp' }, state: outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle' }), HEARTBEAT);
watchList(); watchIncoming();
},
refresh() { if (me()) beat(outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle'); },
endMatch() { const id = inMatch; inMatch = null; cleanupMatch(); if (id) db.del(`matches/${id}`); if (me()) beat('idle'); },
leave() {
clearInterval(hb); hb = null;
if (subList) subList.close(); if (subIn) subIn.close(); cleanupMatch();
if (me()) db.del(`lobby/${me()}`);
},
matchId, isHost,
};
};
})(typeof window !== 'undefined' ? window : globalThis);

101
game/looks.js Normal file
View File

@@ -0,0 +1,101 @@
/* Robot Clash - opponent looks: makes the 3D league robots resemble their ComfyGen portraits
(assets/Sprites/opp_<id>.png). A look = a painted skin layer (same 512x256 layout as the player's
own drawing: left half top view, right half side view, front to the right) + a few extra model
parts that render3d.js adds (eyes, cab, bumps, track covers).
RC.LOOKS[id] = { pattern, accent2, eyes, cab, bumps, tracksLook, wheelScale }
RC.lookLayer(look, paint) -> canvas (cached per id), used as paint.layer with paint.drawn = true */
(function (root) {
'use strict';
const RC = root.RC;
const LW = 512, LH = 256;
const css = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
RC.LOOKS = {
rustbucket: { pattern: 'rust', cab: true, wheelScale: 1.35, eyes: 0xffb040 },
tintoad: { pattern: 'rivets', bumps: true, eyes: 0xd8ff60 },
buzzkill: { pattern: 'hazard', tracksLook: true, eyes: 0xff3a20 },
flapjack: { pattern: 'twotone', accent2: 0xf2f2f2, eyes: 0x9fd8ff },
pincer: { pattern: 'twotone', accent2: 0xe0b030, eyes: 0xffd040 },
thunderclap: { pattern: 'scratches', eyes: 0xffa020 },
gravedigger: { pattern: 'dark', eyes: 0x50ff80 },
overlord: { pattern: 'redstripe', accent2: 0xd02020, eyes: 0xff2020 },
};
const cache = {};
RC.lookLayer = (id, paint) => {
if (cache[id]) return cache[id];
const look = RC.LOOKS[id];
if (!look || typeof document === 'undefined') return null;
const cv = document.createElement('canvas'); cv.width = LW; cv.height = LH;
const c = cv.getContext('2d');
let seed = 1; for (const ch of id) seed = (seed * 31 + ch.charCodeAt(0)) >>> 0;
const r = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 4294967296; };
const halves = fn => { for (const h of [0, 1]) { c.save(); c.beginPath(); c.rect(h * 256, 0, 256, 256); c.clip(); c.translate(h * 256, 0); fn(h); c.restore(); } };
const scratches = (n, a) => {
for (let i = 0; i < n; i++) {
c.strokeStyle = `rgba(${r() < 0.6 ? '255,255,255' : '0,0,0'},${a * (0.5 + r())})`; c.lineWidth = 0.6 + r() * 1.6;
const x = r() * LW, y = r() * LH, ang = r() * 6.3, l = 6 + r() * 34;
c.beginPath(); c.moveTo(x, y); c.lineTo(x + Math.cos(ang) * l, y + Math.sin(ang) * l); c.stroke();
}
};
const rivets = (step, col) => halves(() => {
c.fillStyle = col;
for (let x = 12; x < 256; x += step) for (const y of [12, 244]) { c.beginPath(); c.arc(x, y, 3.2, 0, 7); c.fill(); }
for (let y = 12; y < 256; y += step) for (const x of [12, 244]) { c.beginPath(); c.arc(x, y, 3.2, 0, 7); c.fill(); }
});
switch (look.pattern) {
case 'rust': // brown base with orange rust blotches and dark holes
for (let i = 0; i < 90; i++) {
c.fillStyle = `rgba(${150 + r() * 70 | 0},${60 + r() * 40 | 0},${20 + r() * 20 | 0},${0.25 + r() * 0.4})`;
c.beginPath(); c.ellipse(r() * LW, r() * LH, 6 + r() * 28, 4 + r() * 18, r() * 3, 0, 7); c.fill();
}
for (let i = 0; i < 40; i++) { c.fillStyle = `rgba(30,18,10,${0.3 + r() * 0.4})`; c.beginPath(); c.arc(r() * LW, r() * LH, 1 + r() * 4, 0, 7); c.fill(); }
rivets(40, 'rgba(40,25,15,.8)'); scratches(120, 0.12);
break;
case 'rivets': // panel lines + rivet rows
halves(() => {
c.strokeStyle = 'rgba(0,0,0,.35)'; c.lineWidth = 3;
for (const x of [86, 170]) { c.beginPath(); c.moveTo(x, 0); c.lineTo(x, 256); c.stroke(); }
c.beginPath(); c.moveTo(0, 128); c.lineTo(256, 128); c.stroke();
});
rivets(22, 'rgba(20,30,10,.85)'); scratches(80, 0.1);
break;
case 'hazard': // yellow/black stripes, darker band in the middle of the top
halves(h => {
c.fillStyle = '#16181c';
for (let k = -256; k < 512; k += 64) { c.beginPath(); c.moveTo(k, 0); c.lineTo(k + 32, 0); c.lineTo(k + 32 - 256, 256); c.lineTo(k - 256, 256); c.fill(); }
if (h === 0) { c.fillStyle = 'rgba(20,22,26,.9)'; c.fillRect(0, 96, 256, 64); }
});
scratches(140, 0.12);
break;
case 'twotone': // second colour on the top and as a band on the sides
c.fillStyle = css(look.accent2); c.fillRect(20, 30, 216, 196);
c.fillRect(256, 0, 256, 92);
c.fillStyle = 'rgba(0,0,0,.25)'; c.fillRect(256, 90, 256, 6);
rivets(32, 'rgba(0,0,0,.45)'); scratches(90, 0.1);
break;
case 'scratches':
scratches(260, 0.16); rivets(36, 'rgba(0,0,0,.5)');
break;
case 'dark': // dark hex plates with faint green seams
halves(() => {
c.strokeStyle = 'rgba(80,255,128,.18)'; c.lineWidth = 2;
for (let y = 0; y < 280; y += 36) for (let x = (y / 36) % 2 ? 0 : 21; x < 280; x += 42) {
c.beginPath(); for (let k = 0; k < 6; k++) { const a = k * Math.PI / 3; c.lineTo(x + Math.cos(a) * 20, y + Math.sin(a) * 20); } c.closePath(); c.stroke();
}
});
scratches(70, 0.1);
break;
case 'redstripe': // racing stripe along the top, red band on the sides
c.fillStyle = css(look.accent2); c.fillRect(0, 100, 256, 56);
c.fillStyle = 'rgba(255,255,255,.8)'; c.fillRect(0, 96, 256, 4); c.fillRect(0, 156, 256, 4);
c.fillStyle = css(look.accent2); c.fillRect(256, 120, 256, 36);
scratches(110, 0.12);
break;
}
cache[id] = cv;
return cv;
};
})(window);

175
game/net.js Normal file
View File

@@ -0,0 +1,175 @@
/* Robot Clash - Firebase over plain REST (no SDK, classic script, runs from file://).
Auth = Identity Toolkit REST, database = Realtime Database REST + Server-Sent-Events for push.
const net = RC.Net({ apiKey: '...', dbUrl: 'https://<proj>-default-rtdb.firebaseio.com' });
net.enabled false without a full config -> game stays offline
await net.auth.register(email, pass, name) -> { ok, error } (error: 'EMAIL_EXISTS' | 'WEAK_PASSWORD' | ...)
await net.auth.login(email, pass) -> { ok, error } ('EMAIL_NOT_FOUND' | 'INVALID_PASSWORD' | ...)
await net.auth.guest(name) -> { ok, error } (anonymous sign-in, must be enabled in Firebase)
net.auth.resume() -> true if a saved session was restored (async refresh follows)
net.auth.logout() / net.auth.current -> { uid, name, email, guest } | null
net.auth.onChange(fn) called after login/logout/refresh
await net.db.get(path) -> value | null
await net.db.put(path, value) -> ok (PUT, replaces)
await net.db.patch(path, obj) -> ok (PATCH, merges)
await net.db.push(path, value) -> key | null (POST, new child)
await net.db.del(path) -> ok
const sub = net.db.stream(path, onValue) -> { close() } push updates via EventSource
onValue(value) fires with the whole subtree on connect and on every change.
All DB calls carry the id token (?auth=). Token auto-refreshes before it expires.
Every call is best effort: on error db.get -> null, writes -> false, never throws. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const AUTH = 'https://identitytoolkit.googleapis.com/v1/accounts:';
const TOKEN = 'https://securetoken.googleapis.com/v1/token';
RC.Net = (cfg = {}) => {
const apiKey = cfg.apiKey || '';
const dbUrl = (cfg.dbUrl || '').replace(/\/+$/, '');
const enabled = /^AIza[\w-]+$/.test(apiKey) && /^https:\/\/.+firebase(io|database)\.(com|app)$/.test(dbUrl);
const store = Kit.store('robotclash.net');
let session = null; // { idToken, refreshToken, uid, name, email, guest, exp }
const listeners = [];
const fire = () => listeners.forEach(fn => { try { fn(cur()); } catch (e) { /* ignore */ } });
function cur() { return session ? { uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null; }
async function postJson(url, body) {
const res = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
const data = await res.json().catch(() => ({}));
if (!res.ok) { const msg = (data.error && data.error.message) || ('HTTP_' + res.status); const e = new Error(msg); e.code = msg.split(/[ :]/)[0]; throw e; }
return data;
}
function save() { store.set('session', session ? { refreshToken: session.refreshToken, uid: session.uid, name: session.name, email: session.email, guest: session.guest } : null); }
function setAuth(d, name, guest) {
session = {
idToken: d.idToken || d.id_token, refreshToken: d.refreshToken || d.refresh_token,
uid: d.localId || d.user_id, name: name || (session && session.name) || '', email: d.email || (session && session.email) || '', guest: !!guest,
exp: Date.now() + (+(d.expiresIn || d.expires_in || 3600) - 60) * 1000,
};
save(); fire();
}
async function refresh() {
if (!session || !session.refreshToken) return false;
try {
const d = await postJson(`${TOKEN}?key=${apiKey}`, { grant_type: 'refresh_token', refresh_token: session.refreshToken });
session.idToken = d.id_token; session.refreshToken = d.refresh_token; session.uid = d.user_id;
session.exp = Date.now() + (+d.expires_in - 60) * 1000; save(); return true;
} catch (e) { session = null; save(); fire(); return false; }
}
async function token() {
if (!session) return null;
if (Date.now() >= session.exp) { if (!await refresh()) return null; }
return session.idToken;
}
const auth = {
get current() { return cur(); },
onChange(fn) { listeners.push(fn); },
async register(email, pass, name) {
if (!enabled) return { ok: false, error: 'OFFLINE' };
email = String(email || '').trim().toLowerCase();
try {
const d = await postJson(`${AUTH}signUp?key=${apiKey}`, { email, password: pass, returnSecureToken: true });
setAuth(d, Kit.cleanName(name) || email.split('@')[0], false);
await dbWrite('PUT', `users/${session.uid}/name`, session.name); // name for later logins
return { ok: true };
} catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
},
async login(email, pass) {
if (!enabled) return { ok: false, error: 'OFFLINE' };
email = String(email || '').trim().toLowerCase();
try {
const d = await postJson(`${AUTH}signInWithPassword?key=${apiKey}`, { email, password: pass, returnSecureToken: true });
setAuth(d, email.split('@')[0], false);
const name = await dbGet(`users/${session.uid}/name`); // needs the token -> after setAuth
if (typeof name === 'string' && name) { session.name = name; save(); fire(); }
return { ok: true };
} catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
},
async guest(name) {
if (!enabled) return { ok: false, error: 'OFFLINE' };
try {
const d = await postJson(`${AUTH}signUp?key=${apiKey}`, { returnSecureToken: true });
setAuth(d, Kit.cleanName(name) || 'Guest', true);
return { ok: true };
} catch (e) { return { ok: false, error: e.code || 'ERROR' }; }
},
resume() {
const s = store.get('session', null);
if (!s || !s.refreshToken) return false;
session = Object.assign({ idToken: '', exp: 0 }, s);
refresh().then(ok => { if (ok) fire(); });
return true;
},
logout() { session = null; save(); fire(); },
};
async function dbGet(path) {
if (!enabled) return null;
const t = await token();
try {
const res = await fetch(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`, { cache: 'no-store' });
return res.ok ? await res.json() : null;
} catch (e) { return null; }
}
async function dbWrite(method, path, value) {
if (!enabled) return false;
const t = await token();
try {
const res = await fetch(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`, {
method, headers: { 'Content-Type': 'application/json' }, body: value === undefined ? undefined : JSON.stringify(value),
});
return res.ok ? (method === 'POST' ? (await res.json()).name : true) : false;
} catch (e) { return false; }
}
const db = {
get: dbGet,
put: (p, v) => dbWrite('PUT', p, v),
patch: (p, v) => dbWrite('PATCH', p, v),
push: (p, v) => dbWrite('POST', p, v),
del: p => dbWrite('DELETE', p),
// EventSource push stream. RTDB sends 'put' (whole subtree at /) and 'patch' (partial) events.
stream(path, onValue) {
if (!enabled || typeof EventSource === 'undefined') return { close() {} };
let es = null, closed = false, value = null, retry = null;
const open = async () => {
if (closed) return;
const t = await token();
es = new EventSource(`${dbUrl}/${path}.json${t ? '?auth=' + t : ''}`);
// 'put' = replace the value at d.path; 'patch' = merge d.data's children into d.path
const setAt = (keys, data) => {
if (!keys.length) { value = data; return; }
if (value == null || typeof value !== 'object') value = {};
let o = value;
for (let i = 0; i < keys.length - 1; i++) { if (o[keys[i]] == null || typeof o[keys[i]] !== 'object') o[keys[i]] = {}; o = o[keys[i]]; }
if (data == null) delete o[keys[keys.length - 1]]; else o[keys[keys.length - 1]] = data;
};
const apply = ev => {
let d; try { d = JSON.parse(ev.data); } catch (e) { return; }
if (!d || typeof d.path !== 'string') return;
const keys = d.path.split('/').filter(Boolean);
if (ev.type === 'patch' && d.data && typeof d.data === 'object') {
for (const [k, v] of Object.entries(d.data)) setAt(keys.concat(k.split('/').filter(Boolean)), v);
} else setAt(keys, d.data);
try { onValue(value); } catch (e) { /* ignore */ }
};
es.addEventListener('put', apply);
es.addEventListener('patch', apply);
es.onerror = () => { if (closed) return; es.close(); retry = setTimeout(open, 1500); };
};
open();
return { close() { closed = true; clearTimeout(retry); if (es) es.close(); } };
},
};
return { enabled, auth, db, get uid() { return session ? session.uid : null; }, token };
};
})(typeof window !== 'undefined' ? window : globalThis);

138
game/netfight.js Normal file
View File

@@ -0,0 +1,138 @@
/* Robot Clash - live PvP sync over an existing deterministic fight. Needs net.js, combat.js, ai.js.
Robot 0 is always the local player, robot 1 the opponent (both clients see it that way, so the host
mirrors indices when it publishes). The lower-uid player is the host (authority): it runs the real
RC.Combat.step and publishes snapshots; the guest renders them and only sends its input.
const nf = RC.NetFight({ net, id, host, mySeat, oppStyle, oppSkill, onPeerLost(wasHost) });
nf.start()
HOST each tick, instead of the normal step:
nf.hostStep(s, localInput, dt) runs step with [local, remote|AI], publishes ~15 Hz, returns events
GUEST each frame, instead of step:
nf.guestFrame(s, localInput, dt) eases robots toward the last snapshot, returns events to play
nf.peerAlive false once the peer went silent > GRACE (AI takes over)
nf.stop()
mySeat: 0 if I am meta[myUid] rendered as robot 0 (always true locally). The host publishes with robots
ordered [host, guest]; each side maps so that *its* robot is index 0. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const PUB = 1 / 15, GRACE = 4000; // ms without news before the AI covers for the peer
// robot fields the view / HUD / sound read - kept small for the wire
const RF = ['x', 'z', 'a', 'y', 'hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'turretA', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'boost', 'dead', 'out'];
const packRobot = r => { const o = {}; for (const k of RF) o[k] = r[k]; return o; };
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
RC.NetFight = (opt) => {
const net = opt.net, db = net.db, id = opt.id, host = opt.host;
const base = `matches/${id}`;
let pubT = 0, seq = 0, sendT = 0, beatT = 0, lastInSeq = -1, evBuf = [];
let remoteInput = { throttle: 0, turn: 0, fire: false, fire2: false };
let started = false, lastPeer = Date.now(), peerAlive = true, ai = null, subIn = null, subState = null, subPing = null, lastState = null, stateApplied = -1;
function start() {
if (host) {
// host reads the guest's input stream
subIn = db.stream(`${base}/in`, v => { if (v && typeof v.seq === 'number') { remoteInput = v; lastPeer = Date.now(); } });
} else {
// guest reads the host's state stream
subState = db.stream(`${base}/state`, v => { if (v && typeof v.seq === 'number') { lastState = v; lastPeer = Date.now(); } });
subPing = db.stream(`${base}/ping`, v => { if (v) lastPeer = Date.now(); }); // host alive during the countdown
}
}
function checkPeer() {
if (!started) { started = true; lastPeer = Math.max(lastPeer, Date.now()); } // countdown is over: start the clock
if (!peerAlive && Date.now() - lastPeer < GRACE) { peerAlive = true; if (opt.onPeerBack) opt.onPeerBack(host); }
if (peerAlive && Date.now() - lastPeer > GRACE) {
peerAlive = false;
if (host && !ai) ai = RC.AI.create({ style: opt.oppStyle || 'brawler', skill: opt.oppSkill != null ? opt.oppSkill : 0.5, seed: 7 });
if (opt.onPeerLost) opt.onPeerLost(host);
}
}
// HOST: step with [local, guest-or-AI], publish robots as [host, guest] but return a state where
// index 0 is the LOCAL player (so game.js renders identically on both sides).
function hostStep(s, localInput, dt) {
checkPeer();
const guestInput = peerAlive ? remoteInput : ai.think(s, s.robots[1], s.robots[0], dt);
RC.Combat.step(s, dt, [localInput, guestInput]);
if (s.events.length) evBuf.push.apply(evBuf, s.events); // batch events between publishes for the guest
pubT -= dt;
if (pubT <= 0) {
pubT = PUB;
db.put(`${base}/state`, {
seq: ++seq, t: s.t, left: s.left, pitOpen: s.pitOpen, pitAlarm: s.pitAlarm,
press: { st: s.press.st, y: s.press.y }, crane: { st: s.crane.st, x: s.crane.x, z: s.crane.z, who: s.crane.who },
rockets: s.rockets.map(k => ({ x: k.x, z: k.z, y: k.y, a: k.a })),
r: [packRobot(s.robots[0]), packRobot(s.robots[1])],
ev: evBuf.slice(-24), result: s.result, endIn: s.endIn,
});
evBuf.length = 0;
}
return s.events;
}
// GUEST: no simulation. Ease local robots toward the latest snapshot; snap flags/hp; play its events once.
function guestFrame(s, localInput, dt) {
checkPeer();
// send my input (I am robot 0 locally = guest = snapshot index 1)
sendT -= dt;
beatT -= dt;
// send on change, and at least every 0.5 s as a heartbeat (otherwise the host thinks I am gone)
if (sendT <= 0 && (changed(localInput) || beatT <= 0)) {
sendT = PUB; beatT = 0.5; lastInSeq++;
db.put(`${base}/in`, { seq: lastInSeq, throttle: localInput.throttle || 0, turn: localInput.turn || 0, fire: !!localInput.fire, fire2: !!localInput.fire2 });
prevInput = localInput;
}
const ev = [];
if (lastState) {
const snap = lastState;
s.t = snap.t; s.left = snap.left; s.pitOpen = snap.pitOpen; s.pitAlarm = snap.pitAlarm;
s.press.st = snap.press.st; s.press.y = snap.press.y;
s.crane.st = snap.crane.st; s.crane.x = snap.crane.x; s.crane.z = snap.crane.z; s.crane.who = snap.crane.who;
syncRockets(s, snap.rockets);
s.result = snap.result; s.endIn = snap.endIn;
// snapshot order [host, guest]; locally guest must be index 0 -> swap
applyRobot(s.robots[0], snap.r[1], dt); // me (guest)
applyRobot(s.robots[1], snap.r[0], dt); // host
if (snap.seq !== stateApplied) {
stateApplied = snap.seq;
for (const e of snap.ev || []) { const c = Object.assign({}, e); if (c.who === 0) c.who = 1; else if (c.who === 1) c.who = 0; ev.push(c); }
}
}
return ev;
}
function applyRobot(r, d, dt) {
if (!d) return;
const k = Math.min(1, dt * 14); // ease position/angle, snap the rest
r.x += (d.x - r.x) * k; r.z += (d.z - r.z) * k; r.y += (d.y - r.y) * k;
r.a += wrap(d.a - r.a) * k;
r.turretA += wrap(d.turretA - r.turretA) * k;
for (const f of ['hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'boost', 'dead', 'out']) r[f] = d[f];
}
function syncRockets(s, list) {
list = list || [];
s.rockets.length = list.length;
for (let i = 0; i < list.length; i++) s.rockets[i] = Object.assign(s.rockets[i] || { owner: 1, sp: 6, t: 3 }, list[i]);
}
let prevInput = null;
function changed(inp) { return !prevInput || inp.throttle !== prevInput.throttle || inp.turn !== prevInput.turn || inp.fire !== prevInput.fire || inp.fire2 !== prevInput.fire2; }
return {
start, hostStep, guestFrame,
// during the countdown: keep the line alive (guest sends a neutral input, host an empty state ping)
idle(dt) {
sendT -= dt;
if (sendT > 0) return;
sendT = 0.5;
if (host) db.patch(`${base}/ping`, { h: Date.now() });
else { lastInSeq++; db.put(`${base}/in`, { seq: lastInSeq, throttle: 0, turn: 0, fire: false, fire2: false }); }
},
get peerAlive() { return peerAlive; },
stop() { if (subIn) subIn.close(); if (subState) subState.close(); if (subPing) subPing.close(); },
};
};
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -41,8 +41,8 @@
c.fillStyle = g; c.fillRect(0, 0, 64, 64); c.fillStyle = g; c.fillRect(0, 0, 64, 64);
}); });
function floorTex() { function floorTex(A) {
const A = RC.ARENA, S = 64, N = A.half * 2 * S; // 64 px per metre const S = 64, N = A.half * 2 * S; // 64 px per metre
const P = (x, z) => [(x + A.half) * S, (z + A.half) * S]; const P = (x, z) => [(x + A.half) * S, (z + A.half) * S];
let plate = null; // tex_floor.jpg from ComfyGen (make_tileable) let plate = null; // tex_floor.jpg from ComfyGen (make_tileable)
const tex = canvasTex(N, N, draw); const tex = canvasTex(N, N, draw);
@@ -105,6 +105,20 @@
} }
} }
// image from assets/Sprites as a WebGL texture; skipped quietly where file:// taints it (release embeds data: URIs)
function loadTex(file, onReady) {
const im = new Image();
im.onload = () => {
const probe = document.createElement('canvas').getContext('2d');
probe.drawImage(im, 0, 0, 1, 1);
try { probe.getImageData(0, 0, 1, 1); } catch (e) { return; }
const tex = new T.Texture(im);
tex.encoding = T.sRGBEncoding; tex.anisotropy = 4; tex.needsUpdate = true;
onReady(tex);
};
im.src = Kit.asset('assets/Sprites/' + file);
}
// ---------------------------------------------------------------- particles // ---------------------------------------------------------------- particles
function Particles(scene, max, size, additive, tex) { function Particles(scene, max, size, additive, tex) {
const pos = new Float32Array(max * 3), col = new Float32Array(max * 4); const pos = new Float32Array(max * 3), col = new Float32Array(max * 4);
@@ -161,6 +175,8 @@
M.flame = new T.MeshBasicMaterial({ color: 0xff3a08, transparent: true, opacity: 0.42, blending: T.AdditiveBlending, depthWrite: false, side: T.DoubleSide }); M.flame = new T.MeshBasicMaterial({ color: 0xff3a08, transparent: true, opacity: 0.42, blending: T.AdditiveBlending, depthWrite: false, side: T.DoubleSide });
M.trackTex = canvasTex(64, 16, (c, w, h) => { c.fillStyle = '#17181b'; c.fillRect(0, 0, w, h); c.fillStyle = '#2c2e33'; for (let x = 0; x < w; x += 8) c.fillRect(x, 0, 4, h); }, [6, 1]); M.trackTex = canvasTex(64, 16, (c, w, h) => { c.fillStyle = '#17181b'; c.fillRect(0, 0, w, h); c.fillStyle = '#2c2e33'; for (let x = 0; x < w; x += 8) c.fillRect(x, 0, 4, h); }, [6, 1]);
M.track = new T.MeshStandardMaterial({ map: M.trackTex, roughness: 0.85, metalness: 0.2 }); M.track = new T.MeshStandardMaterial({ map: M.trackTex, roughness: 0.85, metalness: 0.2 });
M.wsteel = new T.MeshStandardMaterial({ color: 0xd2d7de, metalness: 0.95, roughness: 0.22 }); // bright weapon steel
M.wedge = new T.MeshStandardMaterial({ color: 0x9aa0a8, metalness: 0.85, roughness: 0.35 });
return M; return M;
} }
const box = (w, h, d, m) => { const o = new T.Mesh(new T.BoxGeometry(w, h, d), m); o.castShadow = true; o.receiveShadow = true; return o; }; const box = (w, h, d, m) => { const o = new T.Mesh(new T.BoxGeometry(w, h, d), m); o.castShadow = true; o.receiveShadow = true; return o; };
@@ -216,10 +232,16 @@
root.add(tilt); root.add(tilt);
const out = { root, tilt, body, skin, st, build, roll: 0, flash: 0, spinA: 0, sawA: 0, gunA: 0, smokeT: 0 }; const out = { root, tilt, body, skin, st, build, roll: 0, flash: 0, spinA: 0, sawA: 0, gunA: 0, smokeT: 0 };
const sk = (geo, w, h, d, y0) => { const o = new T.Mesh(skinUV(geo, w, d, h, y0), body); o.castShadow = o.receiveShadow = true; return o; }; const sk = (geo, w, h, d, y0) => { const o = new T.Mesh(skinUV(geo, w, d, h, y0), body); o.castShadow = o.receiveShadow = true; return o; };
const look = paint.look || {}; // opponent look (looks.js), cosmetic only
const big = wh && wh.kind === 'big'; const big = wh && wh.kind === 'big';
const c = big ? 0.12 : 0.1; // ground clearance const ws = look.wheelScale || 1;
const c = big ? 0.12 : 0.1 * ws; // ground clearance
out.c = c; out.c = c;
// every piece gets userData.part = slot (lets tools/partshot.html render one part alone)
let from = 0;
const mark = part => { for (let i = from; i < tilt.children.length; i++) tilt.children[i].userData.part = part; from = tilt.children.length; };
// chassis // chassis
let top = c + H; let top = c + H;
if (ch.shape === 'wedge') { if (ch.shape === 'wedge') {
@@ -243,7 +265,21 @@
const s2 = box(0.06, H * 0.6, Wd * 1.002, m.stripe); s2.position.set(-L / 2 + 0.08, c + H / 2, 0); tilt.add(s2); const s2 = box(0.06, H * 0.6, Wd * 1.002, m.stripe); s2.position.set(-L / 2 + 0.08, c + H / 2, 0); tilt.add(s2);
} }
} }
// look extras: raised cab with window slit, eye bumps (like the portraits)
if (look.cab) {
const cw = L * 0.4, chh = H * 0.62, cd = Wd * 0.64;
const cab = sk(new T.BoxGeometry(cw, chh, cd), cw, chh, cd, -chh / 2); cab.position.set(-L * 0.16, top + chh / 2, 0); tilt.add(cab);
const win = box(0.02, chh * 0.25, cd * 0.8, m.dark); win.position.set(-L * 0.16 + cw / 2 + 0.005, top + chh * 0.62, 0); tilt.add(win);
top += chh;
}
if (look.bumps) {
for (const sz of [-1, 1]) {
const b = sk(new T.SphereGeometry(1, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2), 2, 1, 2, 0);
b.scale.set(0.13, 0.11, 0.13); b.position.set(L * 0.18, top - (ch.shape === 'wedge' ? H * 0.45 : 0), sz * Wd * 0.26); tilt.add(b);
}
}
out.top = top; out.top = top;
mark('chassis');
// armour plates (sides + rear), bolts // armour plates (sides + rear), bolts
if (armour) { if (armour) {
@@ -255,10 +291,12 @@
const r = box(0.05, H * 0.78, Wd * 0.95, armour); r.position.set(-L / 2 - 0.028, c + H * 0.42, 0); tilt.add(r); const r = box(0.05, H * 0.78, Wd * 0.95, armour); r.position.set(-L / 2 - 0.028, c + H * 0.42, 0); tilt.add(r);
} }
mark('armour');
// wheels // wheels
out.wheels = []; out.wheels = [];
const side = Wd / 2 + (armour ? 0.13 : 0.08); const side = Wd / 2 + (armour ? 0.13 : 0.08);
if (wh.kind === 'tracks') { if (wh.kind === 'tracks' || look.tracksLook) {
for (const sz of [-1, 1]) { for (const sz of [-1, 1]) {
const t = box(L * 1.02, 0.3, 0.2, m.track); t.position.set(0, 0.15, sz * side); tilt.add(t); const t = box(L * 1.02, 0.3, 0.2, m.track); t.position.set(0, 0.15, sz * side); tilt.add(t);
for (const bx of [-0.42, 0.42]) { const w = cyl(0.15, 0.15, 0.21, m.hub, 14); w.rotation.x = Math.PI / 2; w.position.set(bx * L, 0.15, sz * side); tilt.add(w); } for (const bx of [-0.42, 0.42]) { const w = cyl(0.15, 0.15, 0.21, m.hub, 14); w.rotation.x = Math.PI / 2; w.position.set(bx * L, 0.15, sz * side); tilt.add(w); }
@@ -274,61 +312,83 @@
out.wheelR = r; out.wheelR = r;
} else { } else {
for (const sx of [-1, 1]) for (const sz of [-1, 1]) { for (const sx of [-1, 1]) for (const sz of [-1, 1]) {
const w = new T.Group(); w.position.set(sx * L * 0.32, 0.16, sz * side); const wr = 0.16 * ws;
const tyre = cyl(0.16, 0.16, 0.12, m.rubber, 16); tyre.rotation.x = Math.PI / 2; w.add(tyre); const w = new T.Group(); w.position.set(sx * L * 0.32, wr, sz * (side + (ws - 1) * 0.08));
const hub = cyl(0.07, 0.07, 0.13, m.hub, 8); hub.rotation.x = Math.PI / 2; w.add(hub); const tyre = cyl(wr, wr, 0.12 * ws, m.rubber, 16); tyre.rotation.x = Math.PI / 2; w.add(tyre);
const hub = cyl(wr * 0.44, wr * 0.44, 0.13 * ws, m.hub, 8); hub.rotation.x = Math.PI / 2; w.add(hub);
tilt.add(w); out.wheels.push(w); tilt.add(w); out.wheels.push(w);
} }
out.wheelR = 0.16; out.wheelR = 0.16 * ws;
} }
// headlights + antenna mark('wheels');
for (const sz of [-0.3, 0.3]) { const l = box(0.03, 0.05, 0.1, m.glowW); l.position.set(L / 2 + 0.005, c + H * 0.62, sz * Wd); tilt.add(l); }
// headlights, or glowing eyes for opponents with a look
if (look.eyes) {
const eyeMat = new T.MeshStandardMaterial({ color: look.eyes, emissive: look.eyes, emissiveIntensity: 2.2 });
for (const sz of [-1, 1]) {
const e = new T.Mesh(new T.SphereGeometry(0.055, 12, 8), eyeMat);
e.position.set(L / 2 + 0.01, c + H * (ch.shape === 'wedge' ? 0.3 : 0.7), sz * Wd * 0.24); tilt.add(e);
}
} else for (const sz of [-0.3, 0.3]) { const l = box(0.03, 0.05, 0.1, m.glowW); l.position.set(L / 2 + 0.005, c + H * 0.62, sz * Wd); tilt.add(l); }
const ant = cyl(0.01, 0.01, 0.45, m.dark, 6); ant.position.set(-L / 2 + 0.12, top + 0.22, Wd / 2 - 0.12); tilt.add(ant); const ant = cyl(0.01, 0.01, 0.45, m.dark, 6); ant.position.set(-L / 2 + 0.12, top + 0.22, Wd / 2 - 0.12); tilt.add(ant);
const tip = new T.Mesh(new T.SphereGeometry(0.035, 8, 6), new T.MeshStandardMaterial({ color: paint.accent, emissive: paint.accent, emissiveIntensity: 0.9 })); const tip = new T.Mesh(new T.SphereGeometry(0.035, 8, 6), new T.MeshStandardMaterial({ color: paint.accent, emissive: paint.accent, emissiveIntensity: 0.9 }));
tip.position.set(-L / 2 + 0.12, top + 0.46, Wd / 2 - 0.12); tilt.add(tip); tip.position.set(-L / 2 + 0.12, top + 0.46, Wd / 2 - 0.12); tilt.add(tip);
mark('lights');
// main weapon (front = +x) // main weapon (front = +x)
const w = st.weapon; const w = st.weapon;
if (w) { if (w) {
const WS = m.wsteel, ED = m.wedge, HZ = m.stripe; // weapon steel, edge, hazard stripe
if (w.type === 'wedge') { if (w.type === 'wedge') {
const p = box(0.55, 0.04, Wd * 1.05, m.steel); p.position.set(L / 2 + 0.22, c * 0.5 + 0.08, 0); p.rotation.z = -0.42; tilt.add(p); // short ramp plate at the front (as before - stays close to the body so it does not poke through)
const p = box(0.5, 0.05, Wd * 1.05, ED); p.position.set(L / 2 + 0.18, c * 0.5 + 0.08, 0); p.rotation.z = -0.42; tilt.add(p);
const edge = box(0.12, 0.16, Wd * 1.06, HZ); edge.position.set(L / 2 + 0.34, 0.02, 0); tilt.add(edge);
} else if (w.type === 'flipper') { } else if (w.type === 'flipper') {
const piv = new T.Group(); piv.position.set(L / 2 - 0.08, c + H * 0.3, 0); tilt.add(piv); const piv = new T.Group(); piv.position.set(L / 2 - 0.1, c + H * 0.22, 0); tilt.add(piv);
const p = box(0.62, 0.05, Wd * 0.92, m.steel); p.position.x = 0.31; piv.add(p); const p = box(0.78, 0.09, Wd * 0.95, WS); p.position.x = 0.39; piv.add(p);
const s = box(0.6, 0.012, Wd * 0.3, accent); s.position.set(0.31, 0.03, 0); piv.add(s); const s = box(0.78, 0.03, Wd * 0.4, accent); s.position.set(0.39, 0.06, 0); piv.add(s);
const edge = box(0.12, 0.14, Wd * 0.98, HZ); edge.position.set(0.78, 0, 0); piv.add(edge);
const pist = cyl(0.05, 0.05, 0.4, m.hub, 8); pist.rotation.z = 1.0; pist.position.set(0.2, -0.16, 0); tilt.add(pist); // ram
out.flipper = piv; out.flipper = piv;
} else if (w.type === 'hammer') { } else if (w.type === 'hammer') {
const piv = new T.Group(); piv.position.set(-L * 0.08, top + 0.06, 0); tilt.add(piv); const post = box(0.16, 0.26, 0.24, m.dark); post.position.set(-L * 0.1, top + 0.11, 0); tilt.add(post);
const post = box(0.12, 0.14, 0.18, m.dark); post.position.set(-L * 0.08, top + 0.03, 0); tilt.add(post); const piv = new T.Group(); piv.position.set(-L * 0.1, top + 0.16, 0); tilt.add(piv);
const arm = box(L * 0.72, 0.07, 0.07, m.dark); arm.position.x = L * 0.36; piv.add(arm); const arm = box(L * 0.82, 0.1, 0.1, m.dark); arm.position.x = L * 0.41; piv.add(arm);
const head = box(0.1, 0.34, 0.06, m.steel); head.position.set(L * 0.72, -0.1, 0); piv.add(head); const head = box(0.26, 0.42, 0.26, WS); head.position.set(L * 0.82, -0.12, 0); piv.add(head); // big mallet head
const back = box(0.14, 0.12, 0.12, accent); back.position.set(L * 0.72, 0.08, 0); piv.add(back); const face = box(0.1, 0.44, 0.28, HZ); face.position.set(L * 0.82 + 0.17, -0.12, 0); piv.add(face);
const spike = box(0.18, 0.12, 0.12, accent); spike.position.set(L * 0.82, 0.12, 0); piv.add(spike);
out.hammer = piv; out.hammer = piv;
} else if (w.type === 'saw') { } else if (w.type === 'saw') {
const arm = box(0.35, 0.08, 0.08, m.dark); arm.position.set(L / 2 + 0.05, c + H * 0.55, 0); tilt.add(arm); const arm = box(0.4, 0.12, 0.12, m.dark); arm.position.set(L / 2 + 0.06, c + H * 0.5, 0); tilt.add(arm);
const g = new T.Group(); g.position.set(L / 2 + 0.2, c + H * 0.55, 0); tilt.add(g); const guard = new T.Mesh(new T.TorusGeometry(0.42, 0.05, 8, 20, Math.PI), accent); // orange guard over the top
const d = cyl(0.3, 0.3, 0.025, m.steel, 28); d.rotation.x = Math.PI / 2; g.add(d); guard.position.set(L / 2 + 0.28, c + H * 0.5, 0); tilt.add(guard);
for (let k = 0; k < 14; k++) { const t = box(0.07, 0.04, 0.026, m.steel); const a = k / 14 * Math.PI * 2; t.position.set(Math.cos(a) * 0.31, Math.sin(a) * 0.31, 0); t.rotation.z = a + 0.6; g.add(t); } const g = new T.Group(); g.position.set(L / 2 + 0.28, c + H * 0.5, 0); tilt.add(g);
const hub = cyl(0.06, 0.06, 0.04, accent, 10); hub.rotation.x = Math.PI / 2; g.add(hub); const d = cyl(0.38, 0.38, 0.04, WS, 32); d.rotation.x = Math.PI / 2; g.add(d);
for (let k = 0; k < 16; k++) { const t = box(0.11, 0.06, 0.05, WS); const a = k / 16 * Math.PI * 2; t.position.set(Math.cos(a) * 0.4, Math.sin(a) * 0.4, 0); t.rotation.z = a + 0.6; g.add(t); }
const hub = cyl(0.09, 0.09, 0.07, accent, 12); hub.rotation.x = Math.PI / 2; g.add(hub);
out.saw = g; out.saw = g;
} else if (w.type === 'spinner') { } else if (w.type === 'spinner') {
const post = cyl(0.07, 0.07, 0.25, m.dark, 10); post.position.set(L / 2 + 0.02, c + H * 0.35, 0); tilt.add(post); const post = cyl(0.1, 0.12, 0.3, m.dark, 12); post.position.set(L / 2 + 0.04, c + H * 0.32, 0); tilt.add(post);
const g = new T.Group(); g.position.set(L / 2 + 0.02, c + H * 0.32, 0); tilt.add(g); const g = new T.Group(); g.position.set(L / 2 + 0.04, c + H * 0.3, 0); tilt.add(g);
const bar = box(1.25, 0.07, 0.16, m.steel); g.add(bar); const bar = box(1.5, 0.12, 0.22, WS); g.add(bar);
for (const sx of [-1, 1]) { const t = box(0.1, 0.09, 0.2, accent); t.position.x = sx * 0.6; g.add(t); } const stripe = box(1.5, 0.13, 0.08, HZ); g.add(stripe);
for (const sx of [-1, 1]) { const t = box(0.18, 0.16, 0.32, accent); t.position.x = sx * 0.72; g.add(t); }
out.spinner = g; out.spinner = g;
} else if (w.type === 'crusher') { } else if (w.type === 'crusher') {
out.jaws = []; out.jaws = [];
for (const sz of [-1, 1]) { for (const sz of [-1, 1]) {
const piv = new T.Group(); piv.position.set(L / 2 - 0.02, c + H * 0.45, sz * Wd * 0.34); tilt.add(piv); const piv = new T.Group(); piv.position.set(L / 2 - 0.02, c + H * 0.45, sz * Wd * 0.32); tilt.add(piv);
const j = box(0.58, 0.14, 0.08, m.steel); j.position.x = 0.29; piv.add(j); const j = box(0.68, 0.2, 0.14, WS); j.position.x = 0.34; piv.add(j);
const tooth = box(0.08, 0.14, 0.14, accent); tooth.position.set(0.56, 0, -sz * 0.05); piv.add(tooth); for (let k = 0; k < 3; k++) { const tooth = box(0.1, 0.18, 0.14, accent); tooth.position.set(0.3 + k * 0.18, -sz * 0.02, -sz * 0.07); tooth.rotation.z = -sz * 0.25; piv.add(tooth); }
piv.userData.side = sz; out.jaws.push(piv); piv.userData.side = sz; out.jaws.push(piv);
} }
} }
} }
mark('weapon');
// tower on top // tower on top
const tw = st.tower; const tw = st.tower;
if (tw) { if (tw) {
@@ -353,6 +413,7 @@
} }
out.turret = g; out.turret = g;
} }
mark('tower');
root.traverse(o => { if (o.isMesh && !o.material.transparent) { o.castShadow = true; } }); root.traverse(o => { if (o.isMesh && !o.material.transparent) { o.castShadow = true; } });
return out; return out;
} }
@@ -392,38 +453,77 @@
} }
// ---------------------------------------------------------------- arena // ---------------------------------------------------------------- arena
function buildArena(scene) { // theme colours per arena (combat.js arena.theme)
const A = RC.ARENA, m = mats(), half = A.half; const THEME = {
const out = {}; steel: { bg: 0x07090d, fog: 0x07090d, rimA: 0xff7a1a, rimB: 0x4fa8ff, hazard: 0xd33 },
scene.background = new T.Color(0x07090d); lava: { bg: 0x0d0604, fog: 0x1a0a06, rimA: 0xff5a1a, rimB: 0xff2a10, hazard: 0xff6020 },
scene.fog = new T.Fog(0x07090d, 26, 60); blue: { bg: 0x05080f, fog: 0x070d1a, rimA: 0x3aa0ff, rimB: 0x9a60ff, hazard: 0x40c0ff },
};
// lights: one shadow-casting key light + floodlight colours // persistent lights (reused across arena rebuilds)
function buildArena(scene) {
const out = {};
scene.add(new T.HemisphereLight(0x8fa6c8, 0x1a140f, 0.55)); scene.add(new T.HemisphereLight(0x8fa6c8, 0x1a140f, 0.55));
const key = new T.DirectionalLight(0xfff1dc, 1.25); const key = new T.DirectionalLight(0xfff1dc, 1.25);
key.position.set(6, 16, 9); key.castShadow = true; key.position.set(6, 16, 9); key.castShadow = true;
key.shadow.mapSize.set(2048, 2048); key.shadow.mapSize.set(2048, 2048);
Object.assign(key.shadow.camera, { left: -11, right: 11, top: 11, bottom: -11, near: 1, far: 40 }); Object.assign(key.shadow.camera, { left: -11, right: 11, top: 11, bottom: -11, near: 1, far: 50 });
key.shadow.bias = -0.0008; key.shadow.bias = -0.0008;
scene.add(key); scene.add(key);
const rimA = new T.PointLight(0xff7a1a, 1.1, 22); rimA.position.set(-9, 5, 9); scene.add(rimA); const rimA = new T.PointLight(0xff7a1a, 1.1, 22); scene.add(rimA);
const rimB = new T.PointLight(0x4fa8ff, 0.9, 22); rimB.position.set(9, 5, -9); scene.add(rimB); const rimB = new T.PointLight(0x4fa8ff, 0.9, 22); scene.add(rimB);
out.lights = { key, rimA, rimB, hemi: scene.children.find(o => o.isHemisphereLight) }; out.lights = { key, rimA, rimB, hemi: scene.children.find(o => o.isHemisphereLight) };
out.flashLight = new T.PointLight(0xffaa55, 0, 9); scene.add(out.flashLight); out.flashLight = new T.PointLight(0xffaa55, 0, 9); scene.add(out.flashLight);
out.scene = scene; out.group = null; out.id = null;
out.rocketGeo = new T.CylinderGeometry(0.05, 0.05, 0.32, 8); out.rocketGeo.rotateZ(Math.PI / 2);
out.rocketMat = new T.MeshStandardMaterial({ color: 0xdddddd, emissive: 0x331100 });
out.rocketMeshes = [];
buildArenaGeo(out, RC.ARENA);
return out;
}
function disposeGroup(g) {
g.traverse(o => {
if (o.geometry) o.geometry.dispose();
if (o.material) [].concat(o.material).forEach(mm => { if (mm.map && mm.map.dispose) mm.map.dispose(); mm.dispose(); });
});
}
// (re)build all arena geometry for arena def A into a fresh group
function buildArenaGeo(out, A) {
const m = mats(), half = A.half, th = THEME[A.theme] || THEME.steel;
const scene = out.scene;
if (out.group) { scene.remove(out.group); disposeGroup(out.group); }
const group = new T.Group(); scene.add(group); out.group = group; out.id = A.id;
const scene_add = o => group.add(o);
scene.background = new T.Color(th.bg);
scene.fog = new T.Fog(th.fog, half * 3, half * 5.5);
const { key, rimA, rimB, flashLight } = out.lights;
const sc = Math.max(11, half + 3);
Object.assign(key.shadow.camera, { left: -sc, right: sc, top: sc, bottom: -sc }); key.shadow.camera.updateProjectionMatrix();
rimA.color.setHex(th.rimA); rimA.position.set(-half - 1, 5, half + 1); rimA.distance = half * 2.6;
rimB.color.setHex(th.rimB); rimB.position.set(half + 1, 5, -half - 1); rimB.distance = half * 2.6;
out.hazardCol = th.hazard;
{ const scene = { add: scene_add }; buildArenaBody(scene, out, A, m, half, th); }
}
function buildArenaBody(scene, out, A, m, half, th) {
// floor // floor
const floor = new T.Mesh(new T.PlaneGeometry(half * 2, half * 2), new T.MeshStandardMaterial({ map: floorTex(), metalness: 0.55, roughness: 0.62 })); const floor = new T.Mesh(new T.PlaneGeometry(half * 2, half * 2), new T.MeshStandardMaterial({ map: floorTex(A), metalness: 0.55, roughness: 0.62 }));
floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor); floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);
const outer = new T.Mesh(new T.PlaneGeometry(80, 80), new T.MeshStandardMaterial({ color: 0x0d0f13, roughness: 1 })); const outer = new T.Mesh(new T.PlaneGeometry(80, 80), new T.MeshStandardMaterial({ color: 0x0d0f13, roughness: 1 }));
outer.rotation.x = -Math.PI / 2; outer.position.y = -0.02; outer.receiveShadow = true; scene.add(outer); outer.rotation.x = -Math.PI / 2; outer.position.y = -0.02; outer.receiveShadow = true; scene.add(outer);
// spike walls (instanced spikes) // spike walls (instanced spikes)
const wallMat = new T.MeshStandardMaterial({ color: 0x30343b, metalness: 0.7, roughness: 0.45 }); const wallMat = new T.MeshStandardMaterial({ color: 0x30343b, metalness: 0.7, roughness: 0.45 });
// ComfyGen wall panels (tex_wall.jpg) on the arena walls, if the browser lets the image into WebGL
const panelMat = new T.MeshStandardMaterial({ color: 0x30343b, metalness: 0.6, roughness: 0.5 });
loadTex('tex_wall.jpg', tex => { tex.wrapS = T.RepeatWrapping; tex.repeat.set(5, 1); panelMat.map = tex; panelMat.color.set(0xb0b4bc); panelMat.needsUpdate = true; });
const n = Math.round(half * 2 / 0.5); const n = Math.round(half * 2 / 0.5);
const spikes = new T.InstancedMesh(new T.ConeGeometry(0.07, 0.28, 8), m.steel, n * 4); const spikes = new T.InstancedMesh(new T.ConeGeometry(0.07, 0.28, 8), m.steel, n * 4);
const dm = new T.Object3D(); let si = 0; const dm = new T.Object3D(); let si = 0;
for (const [nx, nz] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { for (const [nx, nz] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
const wall = box(nz ? half * 2 + 0.5 : 0.25, 0.55, nz ? 0.25 : half * 2 + 0.5, wallMat); const wall = box(nz ? half * 2 + 0.5 : 0.25, 0.55, nz ? 0.25 : half * 2 + 0.5, panelMat);
wall.position.set(nx * (half + 0.12), 0.275, nz * (half + 0.12)); scene.add(wall); wall.position.set(nx * (half + 0.12), 0.275, nz * (half + 0.12)); scene.add(wall);
const strip = box(nz ? half * 2 + 0.5 : 0.26, 0.08, nz ? 0.26 : half * 2 + 0.5, m.stripe); const strip = box(nz ? half * 2 + 0.5 : 0.26, 0.08, nz ? 0.26 : half * 2 + 0.5, m.stripe);
strip.position.set(nx * (half + 0.12), 0.58, nz * (half + 0.12)); scene.add(strip); strip.position.set(nx * (half + 0.12), 0.58, nz * (half + 0.12)); scene.add(strip);
@@ -522,11 +622,6 @@
const l = new T.Mesh(new T.SphereGeometry(0.09, 10, 6), new T.MeshStandardMaterial({ color: 0x400000, emissive: 0xff1a1a, emissiveIntensity: 0 })); const l = new T.Mesh(new T.SphereGeometry(0.09, 10, 6), new T.MeshStandardMaterial({ color: 0x400000, emissive: 0xff1a1a, emissiveIntensity: 0 }));
l.position.set(pit.x + sx * (pit.hw + 0.12), 0.08, pit.z + sz * (pit.hd + 0.12)); scene.add(l); return l; l.position.set(pit.x + sx * (pit.hw + 0.12), 0.08, pit.z + sz * (pit.hd + 0.12)); scene.add(l); return l;
}); });
// rockets
out.rocketGeo = new T.CylinderGeometry(0.05, 0.05, 0.32, 8); out.rocketGeo.rotateZ(Math.PI / 2);
out.rocketMat = new T.MeshStandardMaterial({ color: 0xdddddd, emissive: 0x331100 });
out.rocketMeshes = [];
return out;
} }
// ---------------------------------------------------------------- garage // ---------------------------------------------------------------- garage
@@ -550,6 +645,8 @@
} }
// ---------------------------------------------------------------- view // ---------------------------------------------------------------- view
RC.buildRobotModel = buildRobot;
RC.Render = function (canvas, W, H) { RC.Render = function (canvas, W, H) {
const renderer = new T.WebGLRenderer({ canvas, antialias: true, alpha: true }); const renderer = new T.WebGLRenderer({ canvas, antialias: true, alpha: true });
renderer.setClearColor(0x000000, 0); renderer.setClearColor(0x000000, 0);
@@ -567,9 +664,18 @@
const smoke = Particles(arenaScene, 300, 34, false, tex); const smoke = Particles(arenaScene, 300, 34, false, tex);
const fire = Particles(arenaScene, 300, 18, true, tex); const fire = Particles(arenaScene, 300, 18, true, tex);
const VIEW = 15.4, asp = W / H; const asp = W / H;
const cam = new T.OrthographicCamera(-VIEW * asp / 2, VIEW * asp / 2, VIEW / 2, -VIEW / 2, 0.1, 120); const cam = new T.OrthographicCamera(-1, 1, 1, -1, 0.1, 200);
const camBase = new T.Vector3(15.2, 15.5, 15.2), camLook = new T.Vector3(-1.25, 0, -1.25); const camBase = new T.Vector3(15.2, 15.5, 15.2), camLook = new T.Vector3(-1.25, 0, -1.25);
// fit the orthographic camera to an arena of half-size h
function fitCam(h) {
const VIEW = h * 1.95;
cam.left = -VIEW * asp / 2; cam.right = VIEW * asp / 2; cam.top = VIEW / 2; cam.bottom = -VIEW / 2;
cam.updateProjectionMatrix();
const d = h * 1.9;
camBase.set(d, h * 1.95, d); camLook.set(-h * 0.16, 0, -h * 0.16);
}
fitCam(RC.ARENA.half);
cam.position.copy(camBase); cam.lookAt(camLook); cam.position.copy(camBase); cam.lookAt(camLook);
const gcam = new T.PerspectiveCamera(34, asp, 0.1, 60); const gcam = new T.PerspectiveCamera(34, asp, 0.1, 60);
gcam.position.set(3.7, 2.5, 4.4); gcam.lookAt(0, 0.3, 0); gcam.position.set(3.7, 2.5, 4.4); gcam.lookAt(0, 0.3, 0);
@@ -578,7 +684,7 @@
const pcam = new T.PerspectiveCamera(40, asp, 0.1, 120); const pcam = new T.PerspectiveCamera(40, asp, 0.1, 120);
let mode = 'garage', gRobot = null, robots = [], state = null, shake = 0, flashT = 0, introT = 0, scale = 1, hold = 0; let mode = 'garage', gRobot = null, robots = [], state = null, shake = 0, flashT = 0, introT = 0, scale = 1, hold = 0;
let quality = 'high', fxMul = 1; let quality = 'high', fxMul = 1, camMode = 'iso', chaseInit = false;
const PX = [6, 34, 18], WORLD = [0.07, 0.7, 0.32]; // particle sizes: ortho px / perspective m const PX = [6, 34, 18], WORLD = [0.07, 0.7, 0.32]; // particle sizes: ortho px / perspective m
const pointMode = persp => [sparks, smoke, fire].forEach((p, i) => { p.pts.material.size = persp ? WORLD[i] : PX[i]; }); const pointMode = persp => [sparks, smoke, fire].forEach((p, i) => { p.pts.material.size = persp ? WORLD[i] : PX[i]; });
@@ -602,7 +708,7 @@
}, },
// intro fly-over, then a slow orbit behind the title screen; skip() jumps to the orbit // intro fly-over, then a slow orbit behind the title screen; skip() jumps to the orbit
showIntro(builds, paints) { showIntro(builds, paints) {
api.showArena(RC.Combat.create({ robots: builds.map(b => RC.stats(b)), seed: 3 }), builds, paints); api.showArena(RC.Combat.create({ robots: builds.map(b => RC.stats(b)), seed: 3, arena: 'workshop' }), builds, paints);
mode = 'intro'; introT = 0; pointMode(true); mode = 'intro'; introT = 0; pointMode(true);
}, },
skipIntro() { if (mode === 'intro' && introT < INTRO_END) introT = INTRO_END; }, skipIntro() { if (mode === 'intro' && introT < INTRO_END) introT = INTRO_END; },
@@ -625,9 +731,28 @@
// turntable angle that points the robot's side (+z = right) at the camera // turntable angle that points the robot's side (+z = right) at the camera
garage.turntable.rotation.y = Math.atan2(gcam.position.x, gcam.position.z) + a; hold = 1e9; garage.turntable.rotation.y = Math.atan2(gcam.position.x, gcam.position.z) + a; hold = 1e9;
}, },
portrait(build, paint) {
api.showGarage(build, paint);
garage.turntable.rotation.y = 0.55;
gcam.clearViewOffset(); gcam.position.set(1.75, 1.3, 2.1); gcam.lookAt(0, 0.4, 0);
renderer.render(garageScene, gcam);
let url = '';
try { url = canvas.toDataURL('image/png'); } catch (e) { /* tainted canvas: no picture */ }
gcam.setViewOffset(W, H, 300, 40, W, H); api.paintCam(false);
return url;
},
paintCam(on) { gcam.position.set(on ? 2.6 : 3.7, on ? 2.2 : 2.5, on ? 3.1 : 4.4); gcam.lookAt(0, 0.3, 0); }, paintCam(on) { gcam.position.set(on ? 2.6 : 3.7, on ? 2.2 : 2.5, on ? 3.1 : 4.4); gcam.lookAt(0, 0.3, 0); },
// rebuild the arena scene if the fight uses a different one; rescale the camera
setArena(A) {
if (!A || arena.id === A.id) { if (A) fitCam(A.half); return; }
RC.setArena(A.id);
robots.forEach(R => arenaScene.remove(R.root)); robots = [];
buildArenaGeo(arena, A);
fitCam(A.half);
},
showArena(s, builds, paints) { showArena(s, builds, paints) {
mode = 'arena'; state = s; pointMode(false); lightsOn(1); api.setArena(s.arena);
mode = 'arena'; state = s; pointMode(camMode !== 'iso'); lightsOn(1); chaseInit = false;
for (const R of robots) arenaScene.remove(R.root); for (const R of robots) arenaScene.remove(R.root);
robots = builds.map((b, i) => { const R = buildRobot(b, paints[i]); arenaScene.add(R.root); return R; }); robots = builds.map((b, i) => { const R = buildRobot(b, paints[i]); arenaScene.add(R.root); return R; });
sparks.clear(); smoke.clear(); fire.clear(); shake = 0; sparks.clear(); smoke.clear(); fire.clear(); shake = 0;
@@ -657,8 +782,18 @@
} }
} }
}, },
// fight camera: 'iso' (whole arena) | 'chase' (behind robot 0) | 'fpv' (cockpit of robot 0)
get camMode() { return camMode; },
setCam(m) {
camMode = m; chaseInit = false;
pcam.fov = m === 'fpv' ? 72 : 55; pcam.updateProjectionMatrix();
if (mode === 'arena') pointMode(m !== 'iso');
if (robots[0] && robots[0].turret) robots[0].turret.visible = m !== 'fpv';
},
project(x, y, z) { project(x, y, z) {
const v = new T.Vector3(x, y, z).project(cam); const v = new T.Vector3(x, y, z).project(mode === 'arena' && camMode !== 'iso' ? pcam : cam);
// behind the camera (chase / cockpit): off screen
if (v.z > 1) return { x: -999, y: -999 };
return { x: (v.x + 1) / 2 * W, y: (1 - v.y) / 2 * H }; return { x: (v.x + 1) / 2 * W, y: (1 - v.y) / 2 * H };
}, },
frame(dt, now) { frame(dt, now) {
@@ -679,14 +814,40 @@
sparks.update(dt, 9, 1.2); smoke.update(dt, -0.6, 1.4); fire.update(dt, -2.5, 2); sparks.update(dt, 9, 1.2); smoke.update(dt, -0.6, 1.4); fire.update(dt, -2.5, 2);
shake = Math.max(0, shake - dt * 1.2); shake = Math.max(0, shake - dt * 1.2);
const sx = (Math.random() - 0.5) * shake, sz = (Math.random() - 0.5) * shake; const sx = (Math.random() - 0.5) * shake, sz = (Math.random() - 0.5) * shake;
cam.position.set(camBase.x + sx, camBase.y, camBase.z + sz);
cam.lookAt(camLook.x + sx, camLook.y, camLook.z + sz);
flashT = Math.max(0, flashT - dt * 3); flashT = Math.max(0, flashT - dt * 3);
arena.flashLight.intensity = flashT * 4; arena.flashLight.intensity = flashT * 4;
if (camMode !== 'iso' && state && robots[0]) {
followCam(dt, sx, sz);
renderer.render(arenaScene, pcam);
return;
}
cam.position.set(camBase.x + sx, camBase.y, camBase.z + sz);
cam.lookAt(camLook.x + sx, camLook.y, camLook.z + sz);
renderer.render(arenaScene, cam); renderer.render(arenaScene, cam);
}, },
}; };
// chase: smooth camera behind and above robot 0 · fpv: eyes at the front edge of its top
const cpos = new T.Vector3(), clook = new T.Vector3();
function followCam(dt, sx, sz) {
const r = state.robots[0], R = robots[0], half = (state.arena || RC.ARENA).half;
const fx = Math.cos(r.a), fz = Math.sin(r.a);
let px, py, pz, lx, ly, lz;
if (camMode === 'fpv') {
const k = R.st.len * 0.08;
px = r.x + fx * k; pz = r.z + fz * k; py = Math.max(0.25, r.y) + R.top + 0.55;
lx = px + fx * 6; lz = pz + fz * 6; ly = py - 1.25;
cpos.set(px + sx * 0.3, py, pz + sz * 0.3); clook.set(lx, ly, lz);
} else {
px = Kit.clamp(r.x - fx * 3.6, -half - 1.2, half + 1.2); pz = Kit.clamp(r.z - fz * 3.6, -half - 1.2, half + 1.2); py = 2.2 + r.y * 0.5;
lx = r.x + fx * 1.6; lz = r.z + fz * 1.6; ly = 0.3 + r.y * 0.5;
const k = chaseInit ? Math.min(1, dt * 5) : 1;
chaseInit = true;
cpos.lerp(new T.Vector3(px + sx, py, pz + sz), k); clook.lerp(new T.Vector3(lx, ly, lz), k);
}
pcam.position.copy(cpos); pcam.lookAt(clook);
}
// ---- intro: dark arena -> floodlights flicker on -> camera sweeps up -> two robots are lowered in // ---- intro: dark arena -> floodlights flicker on -> camera sweeps up -> two robots are lowered in
const INTRO_END = RC.INTRO_END = 7.5; const INTRO_END = RC.INTRO_END = 7.5;
const ease = u => (u < 0.5 ? 2 * u * u : 1 - Math.pow(-2 * u + 2, 2) / 2); const ease = u => (u < 0.5 ? 2 * u * u : 1 - Math.pow(-2 * u + 2, 2) / 2);
@@ -744,7 +905,7 @@
function animateArena(dt, now) { function animateArena(dt, now) {
const s = state; if (!s) return; const s = state; if (!s) return;
const A = RC.ARENA; const A = state.arena || RC.ARENA;
robots.forEach((R, i) => { robots.forEach((R, i) => {
const r = s.robots[i]; const r = s.robots[i];
poseRobot(R, r, dt); poseRobot(R, r, dt);

View File

@@ -45,7 +45,7 @@
grip: wh ? wh.grip : 6, grip: wh ? wh.grip : 6,
push: wh ? wh.push : 1, push: wh ? wh.push : 1,
len, wid, h: ch ? ch.h : 0.42, len, wid, h: ch ? ch.h : 0.42,
rad: Math.hypot(len, wid) / 2 * 0.82, rad: Math.hypot(len, wid) / 2 * 0.9, // close to the body corners so robots do not clip through each other
weapon: we, tower: to, weapon: we, tower: to,
invertible: !!(wh && wh.invertible), invertible: !!(wh && wh.invertible),
lowProfile: !!(ch && ch.lowProfile), lowProfile: !!(ch && ch.lowProfile),

View File

@@ -96,7 +96,7 @@
['armour', t('m_armour'), bar(st.reduce, 0.4, false, alt && alt.reduce), Math.round(st.reduce * 100) + '%'], ['armour', t('m_armour'), bar(st.reduce, 0.4, false, alt && alt.reduce), Math.round(st.reduce * 100) + '%'],
['speed', t('m_speed'), bar(st.top, 7, false, alt && alt.top), st.top.toFixed(1) + ' m/s'], ['speed', t('m_speed'), bar(st.top, 7, false, alt && alt.top), st.top.toFixed(1) + ' m/s'],
['accel', t('m_accel'), bar(st.accel, 30, false, alt && alt.accel), st.accel.toFixed(1)], ['accel', t('m_accel'), bar(st.accel, 30, false, alt && alt.accel), st.accel.toFixed(1)],
['turn', t('m_turn'), bar(st.turn, 3, false, alt && alt.turn), st.turn.toFixed(1)], ['turn', t('m_turn'), bar(st.turn, 3.6, false, alt && alt.turn), st.turn.toFixed(1)],
].map(r => `<span class="st" title="${r[1]}">${ico(r[0])}${r[2]}<span>${r[3]}</span></span>`).join(''); ].map(r => `<span class="st" title="${r[1]}">${ico(r[0])}${r[2]}<span>${r[3]}</span></span>`).join('');
// paint // paint

132
package-lock.json generated Normal file
View File

@@ -0,0 +1,132 @@
{
"name": "robot-clash",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "robot-clash",
"version": "1.0.0",
"devDependencies": {
"terser": "^5.46.1"
}
},
"node_modules/@jridgewell/gen-mapping": {
"version": "0.3.13",
"resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz",
"integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/sourcemap-codec": "^1.5.0",
"@jridgewell/trace-mapping": "^0.3.24"
}
},
"node_modules/@jridgewell/resolve-uri": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz",
"integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.0.0"
}
},
"node_modules/@jridgewell/source-map": {
"version": "0.3.11",
"resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz",
"integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.25"
}
},
"node_modules/@jridgewell/sourcemap-codec": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
"integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
"dev": true,
"license": "MIT"
},
"node_modules/@jridgewell/trace-mapping": {
"version": "0.3.31",
"resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
"integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/resolve-uri": "^3.1.0",
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/acorn": {
"version": "8.19.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz",
"integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==",
"dev": true,
"license": "MIT",
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"dev": true,
"license": "MIT"
},
"node_modules/commander": {
"version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
"dev": true,
"license": "MIT"
},
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/source-map-support": {
"version": "0.5.21",
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
"integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
"dev": true,
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"source-map": "^0.6.0"
}
},
"node_modules/terser": {
"version": "5.51.2",
"resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz",
"integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"@jridgewell/source-map": "^0.3.3",
"acorn": "^8.15.0",
"commander": "^2.20.0",
"source-map-support": "~0.5.20"
},
"bin": {
"terser": "bin/terser"
},
"engines": {
"node": ">=10"
}
}
}
}

9
package.json Normal file
View File

@@ -0,0 +1,9 @@
{
"name": "robot-clash",
"version": "1.0.0",
"private": true,
"description": "Robot Clash - build helpers only (the game itself needs no build step).",
"devDependencies": {
"terser": "^5.46.1"
}
}

View File

@@ -18,7 +18,14 @@ if /i "%SCRIPT%"=="generate_voice" set PY="%TOOLS%\.venv-tts\Scripts\python.exe
if /i "%SCRIPT%"=="make_voice_refs" set PY="%TOOLS%\.venv-tts\Scripts\python.exe" if /i "%SCRIPT%"=="make_voice_refs" set PY="%TOOLS%\.venv-tts\Scripts\python.exe"
set PYTHONIOENCODING=utf-8 set PYTHONIOENCODING=utf-8
pushd "%HERE%" pushd "%HERE%"
%PY% "%TOOLS%\%SCRIPT%.py" %1 %2 %3 %4 %5 %6 %7 %8 %9 set ARGS=
:collect
if "%~1"=="" goto run
set ARGS=%ARGS% %1
shift
goto collect
:run
%PY% "%TOOLS%\%SCRIPT%.py"%ARGS%
set RC=%ERRORLEVEL% set RC=%ERRORLEVEL%
popd popd
exit /b %RC% exit /b %RC%

View File

@@ -22,8 +22,9 @@ _SCENE = "digital painting, cinematic lighting, high detail, dark industrial moo
PROMPTS = [ PROMPTS = [
# app icon # app icon
("icon", "game app icon: a fierce armoured battle robot for arena fights, heavy riveted steel box body with a huge raised front flipper plate and a spinning saw, angry glowing orange eyes on the front armour, chunky, not a car, no windows, no arms, no legs, " ("icon", "game app icon: a low flat wedge-shaped battle robot shaped like a steel doorstop on hidden wheels, seen from the front at an angle, "
"orange and black hazard paint, sparks flying, bold silhouette, plain solid black background"), "huge raised front flipper plate, two glowing orange eye lights in the armour, orange and black hazard paint, sparks flying, "
"bold simple silhouette, centred, plain solid black background"),
# scenes (not cut out) # scenes (not cut out)
("bg_workshop", f"interior of a cluttered robot workshop garage at night, workbenches with tools, welding sparks, " ("bg_workshop", f"interior of a cluttered robot workshop garage at night, workbenches with tools, welding sparks, "
@@ -85,9 +86,9 @@ PROMPTS = [
("opp_buzzkill", f"yellow and black striped robot with a big front circular saw, {_ROBOT}"), ("opp_buzzkill", f"yellow and black striped robot with a big front circular saw, {_ROBOT}"),
("opp_flapjack", f"blue and white low robot with a huge flipper plate and big tyres, {_ROBOT}"), ("opp_flapjack", f"blue and white low robot with a huge flipper plate and big tyres, {_ROBOT}"),
("opp_pincer", f"red and gold heavy robot on tank tracks with hydraulic crushing jaws, {_ROBOT}"), ("opp_pincer", f"red and gold heavy robot on tank tracks with hydraulic crushing jaws, {_ROBOT}"),
("opp_thunderclap", f"purple robot with an overhead axe hammer and a flamethrower turret, {_ROBOT}"), ("opp_thunderclap", f"purple low flat armoured box robot on four wheels with a long axe arm hinged on top lying along its back and a small flamethrower nozzle turret, {_ROBOT}"),
("opp_gravedigger", f"black domed robot with green lights, tank tracks and a rocket pod turret, {_ROBOT}"), ("opp_gravedigger", f"black domed robot with green lights, tank tracks and a rocket pod turret, {_ROBOT}"),
("opp_overlord", f"menacing black and red domed robot with a heavy horizontal spinning bar weapon, {_ROBOT}"), ("opp_overlord", f"menacing black and red round dome shell robot like an upturned wok on hidden wheels, long horizontal spinning steel bar across the front at floor height, {_ROBOT}"),
# shop mechanic (original character) # shop mechanic (original character)
("npc_mechanic", "game character portrait, gruff middle-aged robot mechanic with welding goggles pushed up on the forehead, " ("npc_mechanic", "game character portrait, gruff middle-aged robot mechanic with welding goggles pushed up on the forehead, "

View File

@@ -0,0 +1,53 @@
"""Robot Clash - shop images made from the real 3D parts (generate_variants.py, Flux.2 Klein + ReferenceLatent).
Reference r3d_<id> = the part exactly as the game builds it (tools/partshots.ps1 renders them into output/).
Flux keeps shape, proportions and viewing angle and paints it in the sprite style, so the shop picture
matches what ends up on the robot.
..\\tools\\partshots.ps1 3D renders -> output/r3d_<id>_raw_00001_.png
gen generate_variants all part images (part_<id>)
gen adopt --size 192 part_<id>
VARIANTS = [(name, ref_name, prompt)]
"""
STYLE = (
"keep exactly the same object, the same shape, proportions, parts and viewing angle as the reference image; "
"render it as a detailed game sprite: scratched painted steel, bolts and rivets, small yellow and black hazard stripe details, "
"soft studio lighting, crisp edges, high detail, centred single subject, plain solid black background, no text"
)
_P = {
'crate': "a plain rectangular steel robot chassis box with a raised accent strip on top",
'doorstop': "a low wedge-shaped steel robot chassis, flat sloped front, hazard stripes on the flat rear deck",
'bulwark': "a large heavy rectangular steel robot chassis box with a raised accent strip on top",
'scarab': "a robot chassis base plate with a smooth round steel dome shell and an accent ring around the dome",
'rubber': "a set of four small rubber robot wheels with steel hubs",
'bigtyre': "a pair of huge chunky rubber tyres with steel hubs",
'tracks': "a pair of long tank crawler tracks with round end wheels",
'steel': "a U-shaped set of three plain grey riveted steel armour plates (two side plates and a rear plate)",
'titan': "a U-shaped set of three light blue-grey titanium armour panels with bolts",
'hardox': "a U-shaped set of three thick yellowish hardened steel wear plates with heavy bolts",
'wedge': "a flat angled steel ramming wedge plate",
'flipper': "a flat steel flipper plate with an accent stripe, hinged at its rear edge",
'hammer': "a robot axe hammer: long steel arm on a pivot block with an axe head pointing down at the end",
'saw': "a large circular saw blade on a short motor arm",
'crusher': "two hydraulic crusher jaw arms side by side with sharp teeth at the tips",
'spinner': "a long horizontal steel spinner bar with hardened teeth blocks at both ends on a central hub",
'flamer': "a small robot turret base with a red fuel tank and a steel flamethrower nozzle",
'minigun': "a small robot turret base with a housing and a rotating multi-barrel minigun",
'rockets': "a small robot turret base carrying a box-shaped rocket pod with four tubes",
}
VARIANTS = [(f"part_{k}", f"r3d_{k}", v) for k, v in _P.items()]
# motor + battery are not visible on the 3D robot: restyle the existing picture (reference = itself)
_INNER = {
'sparky': "a small cheap electric motor with a few wires",
'hornet': "a sleek electric motor with cooling fins",
'bulldog': "a massive high torque gear motor with a big gearbox",
'comet': "a high speed racing electric motor with a glowing blue cooling ring",
'lead': "a heavy old lead acid battery block with two terminals",
'nicd': "a pack of green battery cells strapped together",
'lipo': "a slim modern lithium battery stack with small charge lights",
}
VARIANTS += [(f"part_{k}", f"part_{k}", v) for k, v in _INNER.items()]

84
tests/online.test.js Normal file
View File

@@ -0,0 +1,84 @@
// Live test against the real Firebase project (needs network): node --experimental-eventsource tests/online.test.js
// Creates two throw-away accounts, runs lobby -> challenge -> match -> state/input sync, then deletes everything.
'use strict';
const path = require('path');
const mem = {};
global.window = globalThis;
global.Kit = { store: () => ({ get: (k, d) => (k in mem ? mem[k] : d), set: (k, v) => { mem[k] = v; } }), cleanName: s => String(s || '').slice(0, 20) };
for (const f of ['parts.js', 'robot.js', 'combat.js', 'ai.js', 'net.js', 'lobby.js', 'netfight.js']) require(path.join(__dirname, '..', 'game', f));
const RC = globalThis.RC;
const CFG = { apiKey: 'AIzaSyCE29VQnubM_9ok46nnosg07MpvhZH3O5w', dbUrl: 'https://robot-clash-aa37b-default-rtdb.firebaseio.com' };
const sleep = ms => new Promise(r => setTimeout(r, ms));
let fails = 0;
const ok = (c, msg) => { console.log((c ? 'ok ' : 'FAIL ') + msg); if (!c) fails++; };
(async () => {
const stamp = Date.now();
const A = RC.Net(CFG), B = RC.Net(CFG);
ok(A.enabled, 'config accepted');
const ra = await A.auth.register(`rc-test-a-${stamp}@example.com`, 'test-pass-123', 'TestA');
const rb = await B.auth.register(`rc-test-b-${stamp}@example.com`, 'test-pass-123', 'TestB');
ok(ra.ok && rb.ok, `register two accounts ${ra.error || ''} ${rb.error || ''}`);
if (!ra.ok || !rb.ok) process.exit(1);
const again = RC.Net(CFG); const rl = await again.auth.login(`RC-TEST-A-${stamp}@example.com `, 'test-pass-123');
ok(rl.ok && again.auth.current.name === 'TestA', `login again shows the real name (${again.auth.current && again.auth.current.name}), e-mail case/space tolerant`);
const G = RC.Net(CFG); const rg = await G.auth.guest('GastTest');
ok(rg.ok && G.auth.current.guest, 'anonymous guest sign-in ' + (rg.error || ''));
const LG = RC.Lobby({ net: G, getProfile: () => ({ name: 'GastTest', flag: 'DE', build: RC.STARTER, paint: { body: 1, accent: 2 }, fame: 0 }) });
await LG.enter();
const wrong = await RC.Net(CFG).auth.login(`rc-test-a-${stamp}@example.com`, 'nope-nope');
ok(!wrong.ok, 'wrong password rejected: ' + wrong.error);
const prof = n => () => ({ name: n, flag: 'DE', build: RC.STARTER, paint: { body: 1, accent: 2 }, fame: 5 });
const LA = RC.Lobby({ net: A, getProfile: prof('TestA') }), LB = RC.Lobby({ net: B, getProfile: prof('TestB') });
let listA = [], incomingB = null, matchA = null, matchB = null;
LA.onList(r => { listA = r; }); LB.onIncoming(c => { incomingB = c; });
LA.onMatch(m => { matchA = m; }); LB.onMatch(m => { matchB = m; });
await LA.enter(); await LB.enter();
await sleep(2500);
ok(listA.some(r => r.uid === B.uid && r.name === 'TestB' && r.flag === 'DE'), 'A sees B in the lobby (push stream)');
ok(listA.some(r => r.uid === G.uid && r.name === 'GastTest'), 'A sees the anonymous guest in the lobby');
LG.leave();
LA.challenge(B.uid);
await sleep(2500);
ok(incomingB && incomingB.from === A.uid, 'B receives the challenge');
const t0 = Date.now();
if (incomingB) await LB.accept(A.uid);
while (!(matchA && matchB) && Date.now() - t0 < 12000) await sleep(100);
console.log(` match start took ${Date.now() - t0} ms (A ${!!matchA}, B ${!!matchB})`);
ok(matchA && matchB && matchA.id === matchB.id, 'both sides get the match');
ok(matchA && matchB && matchA.host !== matchB.host, 'exactly one host');
ok(matchA && matchA.opp.name === 'TestB' && matchB.opp.name === 'TestA', 'opponent data arrives');
if (matchA && matchB) {
const host = matchA.host ? A : B, guest = matchA.host ? B : A, id = matchA.id;
const mk = () => RC.Combat.create({ robots: [RC.stats(RC.STARTER), RC.stats(RC.STARTER)], seed: matchA.seed });
const sH = mk(), sG = mk();
const nfH = RC.NetFight({ net: host, id, host: true }), nfG = RC.NetFight({ net: guest, id, host: false });
nfH.start(); nfG.start();
for (let i = 0; i < 35; i++) { nfH.idle(0.1); nfG.idle(0.1); await sleep(100); } // 3.5 s countdown like the game
for (let i = 0; i < 180; i++) { // 3 s real time
nfH.hostStep(sH, { throttle: 1, turn: 0 }, 1 / 60); sH.events.length = 0;
nfG.guestFrame(sG, { throttle: 1, turn: 0.5, fire: false, fire2: false }, 1 / 60);
await sleep(16);
}
await sleep(800);
nfG.guestFrame(sG, { throttle: 1, turn: 0.5, fire: false, fire2: false }, 1 / 60);
ok(sG.t > 1, `guest receives host snapshots (t=${sG.t.toFixed(2)})`);
ok(Math.abs(sG.robots[1].x - sH.robots[0].x) < 1.5, `guest sees host robot near its real place (${sG.robots[1].x.toFixed(2)} vs ${sH.robots[0].x.toFixed(2)})`);
ok(Math.abs(sH.robots[1].a - Math.PI) > 0.2, `host applies guest input (guest robot turned, a=${sH.robots[1].a.toFixed(2)})`);
ok(nfH.peerAlive && nfG.peerAlive, 'both peers alive');
// rules: guest must not be able to write the state, a stranger must not read the match
ok((await guest.db.put(`matches/${id}/state`, { seq: 1 })) === false, 'rule: guest cannot write host state');
nfH.stop(); nfG.stop();
}
// cleanup: lobby, match, challenge, accounts
LA.endMatch(); LB.endMatch(); await sleep(500); LA.leave(); LB.leave(); await sleep(800);
for (const n of [A, B, G]) {
const t = await n.token();
await fetch(`https://identitytoolkit.googleapis.com/v1/accounts:delete?key=${CFG.apiKey}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ idToken: t }) });
}
console.log(fails ? `${fails} failure(s)` : 'all ok');
process.exit(fails ? 1 : 0);
})();

56
tools/partshot.html Normal file
View File

@@ -0,0 +1,56 @@
<!doctype html>
<!-- Dev tool (not shipped): renders ONE robot part exactly as the game builds it in 3D, on black,
3/4 view from the front right. Used as reference for the shop images (ComfyGen generate_variants).
partshot.html?id=flipper part id from game/parts.js (chassis, armour, wheels, weapon, tower)
partshot.html?id=flipper&size=768 canvas size in px
Screenshot via Chrome headless: tools/partshots.ps1 -->
<html><head><meta charset="utf-8"><title>partshot</title>
<style>html,body{margin:0;background:#000;overflow:hidden}canvas{display:block}</style></head>
<body>
<canvas id="c"></canvas>
<script src="../game/vendor/three.min.js"></script>
<script src="../game/kit/kit-core.js"></script>
<script src="../game/parts.js"></script>
<script src="../game/robot.js"></script>
<script src="../game/combat.js"></script>
<script src="../game/looks.js"></script>
<script src="../game/render3d.js"></script>
<script>
(function () {
'use strict';
const T = THREE, q = new URLSearchParams(location.search);
const id = q.get('id') || 'flipper', size = +q.get('size') || 768, p = RC.PARTS[id];
const cv = document.getElementById('c');
const renderer = new T.WebGLRenderer({ canvas: cv, antialias: true, preserveDrawingBuffer: true });
renderer.setPixelRatio(1); renderer.setSize(size, size);
renderer.outputEncoding = T.sRGBEncoding; renderer.toneMapping = T.ACESFilmicToneMapping; renderer.toneMappingExposure = 0.85;
const scene = new T.Scene(); scene.background = new T.Color(0x000000);
scene.add(new T.HemisphereLight(0xc8d4ea, 0x2a2018, 0.9));
const key = new T.DirectionalLight(0xfff2e0, 1.9); key.position.set(3, 6, 4); scene.add(key);
const rimA = new T.DirectionalLight(0xff8a3a, 0.9); rimA.position.set(-4, 2, 3); scene.add(rimA);
const rimB = new T.DirectionalLight(0x6aa8ff, 0.8); rimB.position.set(-2, 3, -5); scene.add(rimB);
// neutral steel paint with orange accent - the player paints the body later, parts keep their own colours
const build = Object.assign({}, RC.STARTER, { [p.slot]: id });
if (p.slot === 'weapon' || p.slot === 'tower') build.armour = null;
const R = RC.buildRobotModel(build, { body: 0x8d939c, accent: 0xff7a1a });
scene.add(R.root);
R.tilt.children.forEach(o => { o.visible = o.userData.part === p.slot; });
// frame the visible pieces
// only visible, solid meshes (the hidden flame cone of the flamer would blow up the frame)
R.root.updateMatrixWorld(true);
const bb = new T.Box3();
R.tilt.children.forEach(o => { if (o.visible) o.traverse(m => {
if (m.isMesh && m.visible && !m.material.transparent) { m.geometry.computeBoundingBox(); bb.union(m.geometry.boundingBox.clone().applyMatrix4(m.matrixWorld)); }
}); });
const c = bb.getCenter(new T.Vector3()), s = bb.getSize(new T.Vector3()), r = s.length() / 2;
const cam = new T.PerspectiveCamera(28, 1, 0.05, 100);
const dir = new T.Vector3(1, 0.78, 0.95).normalize();
cam.position.copy(c).addScaledVector(dir, r / Math.sin(T.MathUtils.degToRad(14)) * 1.12);
cam.lookAt(c);
renderer.render(scene, cam);
document.title = 'done';
})();
</script>
</body></html>

26
tools/partshots.ps1 Normal file
View File

@@ -0,0 +1,26 @@
# Renders every visible robot part (chassis, armour, wheels, weapon, tower) with tools/partshot.html
# into sprite-generator/output/r3d_<id>_raw_00001_.png - references for the shop images:
# .\tools\partshots.ps1 all parts
# .\tools\partshots.ps1 flipper one part
# Then in sprite-generator: gen generate_variants (variants.py), gen adopt --size 192 part_<id>
param([string[]]$Ids)
$ErrorActionPreference = 'Stop'
$root = Split-Path $PSScriptRoot -Parent
$chrome = @("$env:ProgramFiles\Google\Chrome\Application\chrome.exe", "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe") |
Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $chrome) { throw 'Chrome or Edge not found' }
if (-not $Ids) {
$Ids = 'crate', 'doorstop', 'bulwark', 'scarab', 'rubber', 'bigtyre', 'tracks', 'steel', 'titan', 'hardox',
'wedge', 'flipper', 'hammer', 'saw', 'crusher', 'spinner', 'flamer', 'minigun', 'rockets'
}
$out = Join-Path $root 'sprite-generator\output'
New-Item -ItemType Directory -Force $out | Out-Null
$profileDir = Join-Path $env:TEMP 'robotclash-partshot'
$page = 'file:///' + ((Join-Path $root 'tools\partshot.html') -replace '\\', '/' -replace ' ', '%20')
$ErrorActionPreference = 'Continue' # Chrome reports "bytes written" on stderr
foreach ($id in $Ids) {
$png = Join-Path $out "r3d_${id}_raw_00001_.png"
& $chrome --headless=new --use-angle=swiftshader --enable-unsafe-swiftshader --hide-scrollbars --window-size=768,768 `
--virtual-time-budget=3000 --user-data-dir="$profileDir" --screenshot="$png" "${page}?id=$id&size=768" 2>&1 | Out-Null
if (Test-Path $png) { " r3d_$id -> $png" } else { " r3d_$id FAILED" }
}

27
tools/uishots.ps1 Normal file
View File

@@ -0,0 +1,27 @@
# Layout check: screenshots of every screen (Chrome headless) into tools\shots\.
# .\tools\uishots.ps1 desktop 1280x800
# .\tools\uishots.ps1 -Tablet tablet landscape 1024x768 + portrait 768x1024 (touch emulation)
param([switch]$Tablet)
$root = Split-Path $PSScriptRoot -Parent
$chrome = @("$env:ProgramFiles\Google\Chrome\Application\chrome.exe", "${env:ProgramFiles(x86)}\Microsoft\Edge\Application\msedge.exe") |
Where-Object { Test-Path $_ } | Select-Object -First 1
if (-not $chrome) { throw 'Chrome or Edge not found' }
$out = Join-Path $PSScriptRoot 'shots'
New-Item -ItemType Directory -Force $out | Out-Null
$page = 'file:///' + ((Join-Path $root 'game\index.html') -replace '\\', '/' -replace ' ', '%20')
$screens = [ordered]@{
title = 'title'; shop_weapon = 'play'; shop_chassis = 'play&tab=chassis'; shop_wheels = 'play&tab=wheels'; shop_tower = 'play&tab=tower'
paint = 'play&paint'; league = 'play&screen=league'; vs = 'play&screen=vs'; settings = 'play&screen=settings'
help = 'play&screen=help'; lobby = 'play&screen=lobby'; fight_fpv = 'fight=3&ff=4'; fight_iso = 'fight=3&ff=4&cam=iso'
}
$sizes = if ($Tablet) { @(@{n='tabL';s='1024,768'}, @{n='tabP';s='768,1024'}) } else { @(@{n='desk';s='1280,800'}) }
foreach ($sz in $sizes) {
foreach ($k in $screens.Keys) {
$png = Join-Path $out "$($sz.n)_$k.png"
$cargs = @('--headless=new', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--hide-scrollbars', "--window-size=$($sz.s)",
'--virtual-time-budget=5000', "--user-data-dir=$env:TEMP\robotclash-uishots", "--screenshot=$png")
if ($Tablet) { $cargs += '--touch-events=enabled'; $cargs += '--blink-settings=primaryPointerType=2,availablePointerTypes=2,primaryHoverType=1,availableHoverTypes=1' }
& $chrome @cargs "${page}?$($screens[$k])" 2>&1 | Out-Null
" $($sz.n)_$k"
}
}