view update

This commit is contained in:
2026-11-17 14:17:50 +01:00
parent 3e565cf8c7
commit e0496fa089
45 changed files with 2024 additions and 149 deletions

View File

@@ -12,6 +12,14 @@ keine Namen, Figuren, Arenen, Hausroboter, Grafiken, Sounds oder Code aus dem Or
## Spielkonzept ## Spielkonzept
**Zwei getrennte Spiele.** Beim Seitenaufruf startet immer der **Online-Modus**; in der Werkstatt schaltet ein
Knopf auf **Kampagne** um (`gameMode` in game.js, `setMode`/`switchMode`). Getrennt wird über den
Speicher-Schlüssel: die Kampagne behält den bisherigen Schlüssel (alte Spielstände laufen als Kampagne weiter),
Online hängt `.online` an. **Geld, Teile, Roboter und Ruhm wandern nie hinüber.** Kampagne = Liga, Saisons,
Schaukampf; Online = Werkstatt, PvP über die Lobby, Training gegen die KI (keine Liga). Ohne Firebase-Schlüssel
fällt alles auf die Kampagne zurück. Dev: `&gmode=campaign|online`.
**Ablauf** **Ablauf**
1. **Werkstatt:** Roboter aus Teilen bauen – je 1 Chassis, Motor, Räder, Batterie (Pflicht), dazu Panzerung, 1. **Werkstatt:** Roboter aus Teilen bauen – je 1 Chassis, Motor, Räder, Batterie (Pflicht), dazu Panzerung,
Hauptwaffe, Turm und Gadget. Stand: 10 Chassis (Formen box/wedge/dome/frame/hex/barrel/arrow/plow/saucer), Hauptwaffe, Turm und Gadget. Stand: 10 Chassis (Formen box/wedge/dome/frame/hex/barrel/arrow/plow/saucer),
@@ -20,7 +28,12 @@ keine Namen, Figuren, Arenen, Hausroboter, Grafiken, Sounds oder Code aus dem Or
Stacheln, Kacheln – `style` in parts.js, Zweig in render3d), 3 Türme, 5 Gadgets; jedes Teil zeigt im Detail seinen Hotkey und Stacheln, Kacheln – `style` in parts.js, Zweig in render3d), 3 Türme, 5 Gadgets; jedes Teil zeigt im Detail seinen Hotkey und
führt seine Bewegung in der Werkstatt-Vorschau vor. Max. 100 kg, führt seine Bewegung in der Werkstatt-Vorschau vor. 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, drei Gewichtsklassen:** Leicht ≤ 60 kg · Mittel ≤ 100 kg · Schwer ≤ 130 kg (`RC.CLASSES`),
je Klasse **eigene 8 Gegner** (`RC.LEAGUES`, Rosters in ai.js) und **eigener Fortschritt** (`save.leagues`,
aktive Werte stehen in `save.beaten`/`save.season`, `syncClass()` schreibt sie zurück). `RC.setClass(id)`
tauscht `RC.LEAGUE` **und** `RC.WEIGHT_LIMIT` – deshalb musste sonst nichts umgebaut werden. Klassenwahl über
Reiter auf der Liga-Seite. Eine Schwierigkeitseinstellung gibt es nicht mehr; die Klasse ist der Regler
(fester Balance-Sockel `BASE` in game.js = die frühere Voreinstellung „Leicht").
**Kampfschaden:** Teile reißen bei festen LP-Anteilen ab (Panzer 60 %, Rad 40 %, Hauptwaffe 25 %, Turm 18 % – **Kampfschaden:** Teile reißen bei festen LP-Anteilen ab (Panzer 60 %, Rad 40 %, Hauptwaffe 25 %, Turm 18 % –
deterministisch, `BREAK_AT` in combat.js). Das Teil verlässt das 3D-Modell und poltert über den Boden deterministisch, `BREAK_AT` in combat.js). Das Teil verlässt das 3D-Modell und poltert über den Boden
(`breakPart`/`dropPiece`), wirkt sich aus (Rad: langsamer; Panzer: weniger Schutz; Waffe/Turm: tot) und steht (`breakPart`/`dropPiece`), wirkt sich aus (Rad: langsamer; Panzer: weniger Schutz; Waffe/Turm: tot) und steht
@@ -95,6 +108,9 @@ Client bleibt grundsätzlich lesbar – nur erschwert, kein Kopierschutz.
## Dateien ## Dateien
- `game/progress.js` Ränge (Ruhm-Schwellen) + Erfolge (DOM-frei, Node-testbar); je Modus eigener Stand in `save.ach`.
- `game/tourney.js` 8er-K.-o.-Turnier (DOM-frei): Feld aus dir + 7 Liga-Robotern, die anderen Partien werden
mit `RC.Combat`/`RC.AI` wirklich ausgefochten (~75 ms gesamt). Einstieg über die Liga-Seite, Stand in `save.tour`.
- `game/parts.js` Teilekatalog · `game/robot.js` Bauregeln + Werte · `game/combat.js` Physik, Waffen, Fallen, - `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.

355
admin/index.html Normal file
View File

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

View File

@@ -19,11 +19,43 @@ läuft per `file://` und als eine HTML-Datei.
In `game/game.js` bei `NET_CFG = { apiKey: '…' }` eintragen → `.\build.ps1 -Web -Obfuscate` neu bauen. 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.) (Der Web-API-Key ist **nicht geheim**; er darf im Client stehen. Geschützt wird über die DB-Regeln.)
## Admin-Zugang (Events, Freischaltungen, Nachricht an alle)
**Das Passwort wird nirgends im Projekt hinterlegt.** Es gehört zu einem ganz normalen Firebase-Konto;
Firebase speichert es (gehasht) auf dem Server. Im Projekt steht nur die **Kennung (UID)** dieses Kontos –
und zwar in den Datenbankregeln. Ein Passwort, das der Client prüft, wäre wertlos: Jeder könnte es aus der
heruntergeladenen Datei lesen.
**Einmalig einrichten:**
1. [Firebase-Konsole](https://console.firebase.google.com/) → Projekt `robot-clash-aa37b`
→ **Authentication → Users → Nutzer hinzufügen**.
Dort E-Mail + Passwort eintragen – **das sind dein Benutzername und dein Master-Passwort.**
(Am besten ein eigenes Konto, nicht dein Spieler-Konto.)
2. In derselben Liste steht jetzt die Spalte **User UID** (z. B. `k3Jd9…`). Diese Kennung kopieren.
3. **Realtime Database → Regeln**: im Block `"live"` den Platzhalter `PUT-ADMIN-UID-HERE` durch die UID
ersetzen → **Veröffentlichen**.
Die Datei `database.rules.json` hier im Ordner ist nur die Vorlage – Firebase liest sie **nicht**
automatisch, der Inhalt muss in die Konsole eingefügt werden.
Ab dann gilt: Nur dieses eine Konto darf `/live` beschreiben. Lesen darf jeder (auch ohne Login), damit
Gäste Events und Nachrichten sehen.
**Oberfläche aufrufen:** Datei `admin/index.html` im Projektordner **per Doppelklick** öffnen (läuft lokal,
kein Webserver nötig), mit E-Mail + Master-Passwort anmelden, Werte setzen, speichern. Die Seite zeigt nach
dem Login auch die eigene UID an – praktisch, falls du Schritt 2 nachholen willst.
**Diese Datei nie hochladen.** Sie gehört nicht ins `game/`-Verzeichnis und landet deshalb auch nicht in
`release
obotclash.html`. Selbst wenn sie jemand hätte: Ohne dein Konto schreibt sie nichts – die Regel
oben lässt es nicht zu.
## Was die Regeln erlauben ## Was die Regeln erlauben
- `highscores`: lesen offen, nur **neue** Einträge schreiben (Format/Bereich geprüft). - `highscores`: lesen offen, nur **neue** Einträge schreiben (Format/Bereich geprüft).
- `users/$uid`, `lobby/$uid`, `matches/$id`, `challenges`: nur eingeloggte Nutzer; jeder schreibt nur seinen - `users/$uid`, `lobby/$uid`, `matches/$id`, `challenges`: nur eingeloggte Nutzer; jeder schreibt nur seinen
eigenen Lobby-Eintrag / seine Eingaben; den Kampf-Zustand schreibt nur der **Host** (kleinere uid).
- `live`: lesen offen (auch ohne Login), schreiben **nur** das Admin-Konto.
- `ranks/$uid`: lesen offen, schreiben nur das Konto selbst – eine Zeile je Spieler, dadurch keine Dubletten. - `ranks/$uid`: lesen offen, schreiben nur das Konto selbst – eine Zeile je Spieler, dadurch keine Dubletten.
## Grenzen (ehrlich) ## Grenzen (ehrlich)

View File

@@ -2,40 +2,56 @@
"rules": { "rules": {
".read": false, ".read": false,
".write": false, ".write": false,
"highscores": { "highscores": {
".read": true, ".read": true,
".indexOn": ["score"], ".indexOn": [
"score"
],
"$entry": { "$entry": {
".write": "!data.exists()", ".write": "!data.exists()",
".validate": "newData.hasChildren(['name', 'score', 'level', 'time'])", ".validate": "newData.hasChildren(['name', 'score', 'level', 'time'])",
"name": { ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 20" }, "name": {
"score": { ".validate": "newData.isNumber() && newData.val() > 0 && newData.val() <= 10000000" }, ".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 20"
"level": { ".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 999" }, },
"time": { ".validate": "newData.val() == now" }, "score": {
"$other": { ".validate": false } ".validate": "newData.isNumber() && newData.val() > 0 && newData.val() <= 10000000"
},
"level": {
".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 999"
},
"time": {
".validate": "newData.val() == now"
},
"$other": {
".validate": false
}
} }
}, },
"users": { "users": {
"$uid": { "$uid": {
".read": "auth != null && auth.uid == $uid", ".read": "auth != null && auth.uid == $uid",
".write": "auth != null && auth.uid == $uid" ".write": "auth != null && auth.uid == $uid"
} }
}, },
"lobby": { "lobby": {
".read": "auth != null", ".read": "auth != null",
"$uid": { "$uid": {
".write": "auth != null && auth.uid == $uid", ".write": "auth != null && auth.uid == $uid",
".validate": "newData.hasChildren(['name', 'ts'])", ".validate": "newData.hasChildren(['name', 'ts'])",
"name": { ".validate": "newData.isString() && newData.val().length <= 20" }, "name": {
"flag": { ".validate": "newData.isString() && newData.val().length <= 4" }, ".validate": "newData.isString() && newData.val().length <= 20"
"ts": { ".validate": "newData.isNumber()" }, },
"$other": { ".validate": true } "flag": {
".validate": "newData.isString() && newData.val().length <= 4"
},
"ts": {
".validate": "newData.isNumber()"
},
"$other": {
".validate": true
}
} }
}, },
"challenges": { "challenges": {
"$to": { "$to": {
".read": "auth != null && auth.uid == $to", ".read": "auth != null && auth.uid == $to",
@@ -45,7 +61,6 @@
} }
} }
}, },
"matches": { "matches": {
"$id": { "$id": {
".read": "auth != null && $id.contains(auth.uid)", ".read": "auth != null && $id.contains(auth.uid)",
@@ -57,6 +72,51 @@
".validate": "$id.endsWith('_' + auth.uid)" ".validate": "$id.endsWith('_' + auth.uid)"
} }
} }
},
"live": {
".read": true,
".write": "auth != null && auth.uid === 'sQwhv1p7KvNHuRLHuyf2fbQI86F2'"
},
"ranks": {
".read": true,
".indexOn": [
"fame"
],
"$uid": {
".write": "auth != null && auth.uid == $uid",
".validate": "newData.hasChildren(['name','fame','ts'])",
"name": {
".validate": "newData.isString() && newData.val().length >= 1 && newData.val().length <= 20"
},
"fame": {
".validate": "newData.isNumber() && newData.val() >= 0 && newData.val() <= 10000000"
},
"cls": {
".validate": "newData.isString() && newData.val().length <= 10"
},
"season": {
".validate": "newData.isNumber() && newData.val() >= 1 && newData.val() <= 999"
},
"ts": {
".validate": "newData.val() == now"
},
"$other": {
".validate": false
}
}
},
"admin": {
".read": "auth != null && auth.uid === 'sQwhv1p7KvNHuRLHuyf2fbQI86F2'",
".write": "auth != null && auth.uid === 'sQwhv1p7KvNHuRLHuyf2fbQI86F2'"
},
"tourney": {
".read": "auth != null",
".write": "auth != null",
"reg": {
"$uid": {
".write": "auth != null && auth.uid == $uid"
}
}
} }
} }
} }

View File

@@ -139,6 +139,58 @@
{ id: 'overlord', name: 'Overlord', style: 'flanker', skill: 0.95, prize: 1450, { id: 'overlord', name: 'Overlord', style: 'flanker', skill: 0.95, prize: 1450,
build: { chassis: 'discus', motor: 'comet', wheels: 'rubber', battery: 'lipo', armour: 'steel', weapon: 'spinner', tower: null, gadget: 'righter' }, paint: pal(0x101418, 0xff3030) }, build: { chassis: 'discus', motor: 'comet', wheels: 'rubber', battery: 'lipo', armour: 'steel', weapon: 'spinner', tower: null, gadget: 'righter' }, paint: pal(0x101418, 0xff3030) },
]; ];
// --- lightweight league (max 60 kg): quick, fragile, cheap ---
RC.LEAGUE_LIGHT = [
{ id: 'tinflea', name: 'Tin Flea', style: 'brawler', skill: 0.1, prize: 200,
build: { chassis: 'cage', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'wedge', tower: null }, paint: pal(0x9aa3ad, 0xf2c230) },
{ id: 'sparrow', name: 'Sparrow', style: 'flanker', skill: 0.18, prize: 280,
build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'lance', tower: null }, paint: pal(0x2e9c8f, 0xffffff) },
{ id: 'needle', name: 'Needle', style: 'brawler', skill: 0.3, prize: 370,
build: { chassis: 'cage', motor: 'hornet', wheels: 'omni', battery: 'nicd', armour: 'mesh', weapon: 'saw', tower: null }, paint: pal(0xd8452b, 0x15171b) },
{ id: 'jackrabbit', name: 'Jackrabbit', style: 'pusher', skill: 0.4, prize: 470,
build: { chassis: 'doorstop', motor: 'sparky', wheels: 'bigtyre', battery: 'nicd', armour: null, weapon: 'lifter', tower: null }, paint: pal(0x5fae3b, 0xf2c230) },
{ id: 'switchblade', name: 'Switchblade', style: 'flanker', skill: 0.52, prize: 590,
build: { chassis: 'hexpod', motor: 'hornet', wheels: 'omni', battery: 'lipo', armour: 'titan', weapon: 'wedge', tower: null }, paint: pal(0x6a3fb0, 0xe6e6e6) },
{ id: 'wasp', name: 'Wasp', style: 'brawler', skill: 0.64, prize: 720,
build: { chassis: 'fang', motor: 'hornet', wheels: 'rubber', battery: 'lipo', armour: null, weapon: 'lance', tower: null, gadget: 'righter' }, paint: pal(0xf2c230, 0x15171b) },
{ id: 'firefly', name: 'Firefly', style: 'gunner', skill: 0.78, prize: 900,
build: { chassis: 'crate', motor: 'comet', wheels: 'omni', battery: 'lipo', armour: null, weapon: 'saw', tower: 'flamer' }, paint: pal(0xff7a1a, 0x3a3d44) },
{ id: 'pinpoint', name: 'Pinpoint', style: 'flanker', skill: 0.92, prize: 1150,
build: { chassis: 'fang', motor: 'comet', wheels: 'rubber', battery: 'lipo', armour: null, weapon: 'mace', tower: null }, paint: pal(0x101418, 0x4fa8ff) },
];
// --- heavyweight league (max 130 kg): slow, armoured, brutal ---
RC.LEAGUE_HEAVY = [
{ id: 'bulldozer', name: 'Bulldozer', style: 'pusher', skill: 0.14, prize: 420,
build: { chassis: 'bulwark', motor: 'bulldog', wheels: 'tracks', battery: 'lead', armour: 'steel', weapon: 'wedge', tower: null }, paint: pal(0xf2c230, 0x15171b) },
{ id: 'anvil', name: 'Anvil', style: 'brawler', skill: 0.26, prize: 540,
build: { chassis: 'plough', motor: 'bulldog', wheels: 'studs', battery: 'nicd', armour: 'steel', weapon: 'lance', tower: null }, paint: pal(0x8c8c8c, 0xd8452b) },
{ id: 'boilerplate', name: 'Boilerplate', style: 'brawler', skill: 0.38, prize: 680,
build: { chassis: 'boiler', motor: 'hornet', wheels: 'drumwh', battery: 'nicd', armour: 'spiked', weapon: 'hammer', tower: null }, paint: pal(0x5a5048, 0xff7a1a) },
{ id: 'grinder', name: 'Grinder', style: 'brawler', skill: 0.5, prize: 850,
build: { chassis: 'discus', motor: 'comet', wheels: 'tracks', battery: 'lipo', armour: 'ceramic', weapon: 'drum', tower: null }, paint: pal(0x3a3d44, 0x6dff9e) },
{ id: 'juggernaut', name: 'Juggernaut', style: 'pusher', skill: 0.62, prize: 1050,
build: { chassis: 'bulwark', motor: 'bulldog', wheels: 'tracks', battery: 'liion', armour: 'hardox', weapon: 'crusher', tower: null, gadget: 'repair' }, paint: pal(0xc0392b, 0xf2c230) },
{ id: 'warhound', name: 'Warhound', style: 'gunner', skill: 0.74, prize: 1300,
build: { chassis: 'plough', motor: 'hornet', wheels: 'studs', battery: 'liion', armour: 'ceramic', weapon: 'mace', tower: 'flamer', gadget: 'shield' }, paint: pal(0x6a3fb0, 0xffa020) },
{ id: 'colossus', name: 'Colossus', style: 'brawler', skill: 0.86, prize: 1600,
build: { chassis: 'scarab', motor: 'comet', wheels: 'tracks', battery: 'supercap', armour: 'hardox', weapon: 'spinner', tower: 'zapper' }, paint: pal(0x2b2f36, 0x4fa8ff) },
{ id: 'doomsday', name: 'Doomsday', style: 'flanker', skill: 0.97, prize: 2000,
build: { chassis: 'plough', motor: 'bulldog', wheels: 'tracks', battery: 'supercap', armour: 'hardox', weapon: 'vdisc', tower: 'swarm', gadget: 'mines' }, paint: pal(0x101418, 0xff3030) },
];
RC.LEAGUES = { light: RC.LEAGUE_LIGHT, medium: RC.LEAGUE, heavy: RC.LEAGUE_HEAVY };
// Swap the active class: RC.LEAGUE and the weight limit follow, like RC.setArena does for arenas.
RC.setClass = id => {
const c = RC.CLASSES.find(x => x.id === id) || RC.CLASSES[1];
RC.CLASS = c.id;
RC.WEIGHT_LIMIT = c.max;
RC.LEAGUE = RC.LEAGUES[c.id];
return c;
};
RC.CLASS = 'medium';
RC.DUMMY = { id: 'dummy', name: 'Dummy', style: 'dummy', skill: 0, prize: 0, RC.DUMMY = { id: 'dummy', name: 'Dummy', style: 'dummy', skill: 0, prize: 0,
build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: 'steel', weapon: null, tower: null }, paint: pal(0x8c8c8c, 0xff7a1a) }; build: { chassis: 'crate', motor: 'sparky', wheels: 'rubber', battery: 'lead', armour: 'steel', weapon: null, tower: null }, paint: pal(0x8c8c8c, 0xff7a1a) };

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 291 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 344 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 251 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 254 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 306 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 290 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 241 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 275 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 288 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 265 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 205 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 67 KiB

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 233 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 KiB

View File

@@ -138,6 +138,7 @@
shield: 0, gcd: 0, gUses: st.gadget && st.gadget.charges || 0, shield: 0, gcd: 0, gUses: st.gadget && st.gadget.charges || 0,
lost: { armour: false, wheels: false, weapon: false, tower: false }, // parts torn off during the fight lost: { armour: false, wheels: false, weapon: false, tower: false }, // parts torn off during the fight
onOil: false, // standing in a slick: less grip, lazy steering onOil: false, // standing in a slick: less grip, lazy steering
g3: false, // last gadget button state (for one-shot gadgets)
cd: 0, cd2: 0, spin: 0, swing: 0, flipAnim: 0, boost: 0, sawOn: false, flameOn: false, gunOn: false, cd: 0, cd2: 0, spin: 0, swing: 0, flipAnim: 0, boost: 0, sawOn: false, flameOn: false, gunOn: false,
turretA: p.a, dealt: 0, taken: 0, pressT: 0, craneT: 0, fx: 0, turretA: p.a, dealt: 0, taken: 0, pressT: 0, craneT: 0, fx: 0,
}; };
@@ -312,7 +313,7 @@
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 // slammed into the spikes hard -> bounces up and can land on its back
if (vn > 3.5 && r.y < 0.05 && !r.st.invertible && !r.st.lowProfile && s.rand() < 0.3) { r.vy = Math.max(r.vy, 2); r.flipped = 2.2; r.av += (s.rand() - 0.5) * 6; } if (vn > 3.5 && r.y < 0.05 && !r.st.invertible && !r.st.lowProfile && s.rand() < 0.3 * (r.st.topHeavy || 1)) { r.vy = Math.max(r.vy, 2); r.flipped = 2.2; r.av += (s.rand() - 0.5) * 6; }
} }
r.vx += w.nx * vn * 1.45; r.vz += w.nz * vn * 1.45; // bounce (0.45 restitution) r.vx += w.nx * vn * 1.45; r.vz += w.nz * vn * 1.45; // bounce (0.45 restitution)
} }
@@ -364,10 +365,10 @@
if (w && w.type === 'wedge' && e.y < 0.05 && !e.st.lowProfile) { if (w && w.type === 'wedge' && e.y < 0.05 && !e.st.lowProfile) {
const light = Math.sqrt(me.st.mass / e.st.mass); 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); e.vy = Math.max(e.vy, 2.3 * light); e.stun = Math.max(e.stun, 0.25);
if (!e.st.invertible && !e.st.lowProfile && s.rand() < 0.3 * light && impact > 3) { e.flipped = 2.2; e.av += (s.rand() - 0.5) * 6; } if (!e.st.invertible && !e.st.lowProfile && s.rand() < 0.3 * light * (e.st.topHeavy || 1) && impact > 3) { e.flipped = 2.2; e.av += (s.rand() - 0.5) * 6; }
} else if (impact > 4.5 && e.y < 0.05 && !e.st.lowProfile && !e.st.invertible) { } 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); const light = Math.sqrt(me.st.mass / e.st.mass);
if (s.rand() < 0.22 * light) { e.vy = Math.max(e.vy, 1.8 * light); e.flipped = 2.2; e.av += (s.rand() - 0.5) * 5; s.events.push({ type: 'flip', who: e.i, x: e.x, z: e.z }); } if (s.rand() < 0.22 * light * (e.st.topHeavy || 1)) { e.vy = Math.max(e.vy, 1.8 * light); e.flipped = 2.2; e.av += (s.rand() - 0.5) * 5; s.events.push({ type: 'flip', who: e.i, x: e.x, z: e.z }); }
} }
} }
} }
@@ -408,7 +409,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.25 : 0.45)) e.flipped = 2.2; if (!e.st.invertible && s.rand() < (e.st.lowProfile ? 0.25 : 0.45) * (e.st.topHeavy || 1)) e.flipped = 2.2;
} }
} }
break; break;
@@ -452,7 +453,7 @@
damage(s, e, w.dmg * k, r, { kind: 'spin' }); damage(s, e, w.dmg * k, r, { kind: 'spin' });
e.vy = Math.max(e.vy, 6.5 * k * light); e.vy = Math.max(e.vy, 6.5 * k * light);
e.vx += fx * 1.5 * k; e.vz += fz * 1.5 * k; e.av += 7 * k; e.vx += fx * 1.5 * k; e.vz += fz * 1.5 * k; e.av += 7 * k;
if (!e.st.invertible && s.rand() < 0.5 * k) e.flipped = 2.2; if (!e.st.invertible && s.rand() < 0.5 * k * (e.st.topHeavy || 1)) e.flipped = 2.2;
r.spin *= 0.3; r.cd = 0.35; r.spin *= 0.3; r.cd = 0.35;
s.events.push({ type: 'spinhit', who: r.i, x: (r.x + e.x) / 2, z: (r.z + e.z) / 2, k }); s.events.push({ type: 'spinhit', who: r.i, x: (r.x + e.x) / 2, z: (r.z + e.z) / 2, k });
} }
@@ -523,7 +524,10 @@
r.gcd = Math.max(0, r.gcd - dt); r.gcd = Math.max(0, r.gcd - dt);
if (r.shield > 0) r.shield = Math.max(0, r.shield - dt); if (r.shield > 0) r.shield = Math.max(0, r.shield - dt);
const g = r.st.gadget; const g = r.st.gadget;
const pressed = !!inp.fire3 && !r.g3; // rising edge: one action per press
r.g3 = !!inp.fire3;
if (!g || r.out || r.dead || !inp.fire3 || r.gcd > 0) return; if (!g || r.out || r.dead || !inp.fire3 || r.gcd > 0) return;
if (g.type === 'mines' && !pressed) return; // one mine per press, never a whole trail
const held = r.lifted > 0 || r.grabbedBy !== null; const held = r.lifted > 0 || r.grabbedBy !== null;
switch (g.type) { switch (g.type) {
case 'righter': // flip back upright case 'righter': // flip back upright

View File

@@ -19,6 +19,21 @@
// 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';
// live settings from the backend (/live): news, events, unlocks, kill switch.
// Always usable - without a backend or network this is simply "nothing special running".
let LIVE = RC.Live.parse(null, Date.now(), BUILD_ID());
const liveText = o => (o && (o[L.lang] || o.en || o.de)) || '';
const evMul = () => (LIVE.event ? LIVE.event.prizeMul : 1);
// extra earnings from a running event, shown as its own result line
function applyEvent(money, lines) {
const m = evMul();
if (m === 1 || money <= 0) return money;
const bonus = Math.round(money * m) - money;
if (bonus) lines.push([t('event_bonus'), bonus]);
return money + bonus;
}
function BUILD_ID() { return (typeof window !== 'undefined' && window.RC_BUILD) || ''; }
const SITE = 'https://michael-media.de'; const SITE = 'https://michael-media.de';
// build stamp comes from build-web.mjs; identifies the exact release in a leaked copy // build stamp comes from build-web.mjs; identifies the exact release in a leaked copy
const BUILD = (typeof window !== 'undefined' && window.RC_BUILD) || ''; const BUILD = (typeof window !== 'undefined' && window.RC_BUILD) || '';
@@ -33,22 +48,26 @@
// ---------------------------------------------------------------- services // ---------------------------------------------------------------- services
const L = Kit.i18n(window.LANG, { prefix: ID }); const L = Kit.i18n(window.LANG, { prefix: ID });
// first start (no saved choice yet): default to English, not the browser language
if (Kit.store(ID).get('lang', null) === null) L.set('en');
const t = L.t; const t = L.t;
const store = Kit.store(ID); const store = Kit.store(ID);
// steer: 'simple' (keys = screen direction) | 'tank' · diff: 'easy' | 'normal' | 'hard' · autofire: weapon fires by itself in reach // steer: 'simple' (keys = screen direction) | 'tank' · diff: 'easy' | 'normal' | 'hard' · autofire: weapon fires by itself in reach
const settings = Object.assign({ gfx: 'medium', intro: true, steer: 'tank', diff: 'easy', autofire: true, cam: 'fpv', arena: 'random' }, store.get('settings', {})); const settings = Object.assign({ gfx: 'medium', intro: true, steer: 'tank', autofire: true, cam: 'fpv', arena: 'random', quiet: false }, store.get('settings', {}));
// v2: Michael found "simple" steering worse -> tank is the default again, old saved choice reset once // 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 // 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 < 2) settings.steer = 'tank';
if (!settings.v || settings.v < 3) { settings.cam = 'fpv'; settings.v = 3; store.set('settings', settings); } if (!settings.v || settings.v < 3) { settings.cam = 'fpv'; settings.v = 3; store.set('settings', settings); }
// difficulty: player hit points x, AI skill + // 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 } }; // fixed balance baseline (used to be the "easy" setting, which was the default anyway).
// The weight class is meant to be the dial from here on, not a difficulty menu.
const BASE = { hp: 1.4, skill: -0.2 };
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: 800, 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', flag: 'XX', tutorialSeen: false, paint: { body: 0xff7a1a, accent: 0x15171b }, robotName: 'Clank', flag: 'XX', tutorialSeen: false, ach: {}, tour: null, cls: 'medium', leagues: null,
robots: [], active: 0, // hangar: saved robot builds; the active one mirrors build/paint/robotName robots: [], active: 0, // hangar: saved robot builds; the active one mirrors build/paint/robotName
}); });
const MAX_ROBOTS = 6; const MAX_ROBOTS = 6;
@@ -60,12 +79,17 @@
r.name = save.robotName; r.build = save.build; r.paint = save.paint; r.name = save.robotName; r.build = save.build; r.paint = save.paint;
} }
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) { syncActive(); slot.save(save); } }; // the active class's league progress lives in save.beaten/season while you play,
// and is written back to its own slot on every save (same idea as the active robot)
const syncClass = () => { if (save && save.leagues && save.cls) save.leagues[save.cls] = { beaten: save.beaten | 0, season: save.season || 1 }; };
const persist = () => { if (slot && save) { syncActive(); syncClass(); slot.save(save); } };
const audio = Kit.createAudio({ const audio = Kit.createAudio({
prefix: ID, prefix: ID,
files: ['sfx_click', 'sfx_buy', 'sfx_hit', 'sfx_saw', 'sfx_boom', 'sfx_win', 'sfx_lose', 'music_title', 'music_garage', 'music_fight'], files: ['sfx_click', 'sfx_buy', 'sfx_hit', 'sfx_saw', 'sfx_boom', 'sfx_win', 'sfx_lose', 'music_title', 'music_garage', 'music_fight'],
throttle: { sfx_hit: 80, sfx_saw: 120, sfx_boom: 100 }, throttle: { sfx_hit: 80, sfx_saw: 120, sfx_boom: 100 },
}); });
// first start (nothing saved yet): start very quiet; gain is squared, so these are low
if (Kit.store(ID).get('music', null) === null) audio.setVolume(0.1, 0.35);
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);
if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop
@@ -98,6 +122,12 @@
deny() { audio.tone(160, 0.15, 'square', 0.12, -40); }, deny() { audio.tone(160, 0.15, 'square', 0.12, -40); },
beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); }, beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); },
clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); }, clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); },
gate() { // metal garage door rolling open
audio.noise(1.0, 0.4, 1500); audio.noise(0.9, 0.3, 500, 0.05); // metal roll rumble
audio.tone(110, 0.9, 'sawtooth', 0.1, 70); // servo whir rising
for (let k = 0; k < 6; k++) audio.tone(170 + k * 28, 0.05, 'square', 0.07, 0, k * 0.11); // chain clanks
audio.noise(0.25, 0.55, 300, 0.9); audio.tone(58, 0.4, 'sine', 0.5, -22, 0.9); // heavy end clunk
},
win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); }, win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); },
lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); }, lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); },
event(e) { event(e) {
@@ -126,10 +156,11 @@
}, },
loops(s) { // continuous weapons as short repeated bursts loops(s) { // continuous weapons as short repeated bursts
for (const r of s.robots) { for (const r of s.robots) {
if (r.sawOn && every('saw' + r.i, 110)) { audio.sfx('sfx_saw'); audio.tone(900 + Math.random() * 60, 0.1, 'sawtooth', 0.03); } const q = settings.quiet ? 0.3 : 1, slow = settings.quiet ? 1.7 : 1; // quiet mode: softer + less often
if (r.flameOn && every('fl' + r.i, 120)) audio.noise(0.14, 0.12, 900); if (r.sawOn && every('saw' + r.i, 200 * slow)) { if (!settings.quiet) audio.sfx('sfx_saw', 0.35); audio.tone(360 + Math.random() * 40, 0.12, 'triangle', 0.02 * q); }
if (r.gunOn && every('gun' + r.i, 70)) audio.noise(0.04, 0.16, 3500); if (r.flameOn && every('fl' + r.i, 120 * slow)) audio.noise(0.14, 0.12 * q, 900);
if (r.spin > 0.2 && every('spin' + r.i, 100)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin); if (r.gunOn && every('gun' + r.i, 70 * slow)) audio.noise(0.04, 0.16 * q, 3500);
if (r.spin > 0.2 && every('spin' + r.i, 100 * slow)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin * q);
} }
}, },
}; };
@@ -155,6 +186,7 @@
onPaint: () => view.setPaint(paintObj()), onPaint: () => view.setPaint(paintObj()),
onPreview: b => { if (mode === 'garage') view.showGarage(b, paintObj()); }, // show the selected part on the robot onPreview: b => { if (mode === 'garage') view.showGarage(b, paintObj()); }, // show the selected part on the robot
onHangarView: el => renderHangar(el), // Hangar tab content onHangarView: el => renderHangar(el), // Hangar tab content
locked: id => LIVE.locked('parts', id), // event/unlock: part not released yet
sfx: SFX, sfx: SFX,
}); });
@@ -202,12 +234,42 @@
const fbAcc = () => (fbUser() && !fbUser().guest ? fbUser() : null); // real (e-mail) account const fbAcc = () => (fbUser() && !fbUser().guest ? fbUser() : null); // real (e-mail) account
const playerName = () => (fbUser() ? fbUser().name : accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : ''); const playerName = () => (fbUser() ? fbUser().name : accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : '');
// save slot: Firebase account -> robotclash.save.fb_<uid>, else local profile / guest // save slot: Firebase account -> robotclash.save.fb_<uid>, else local profile / guest
const saveKey = () => (fbAcc() ? ID + '.save.fb_' + fbAcc().uid : accounts.saveKey()); // Two completely separate games: the campaign (league, seasons) and online play (PvP).
// Money, parts and robots never cross over - they simply live in different saves.
// Opening the page always starts in online mode; the campaign keeps the old save key,
// so an existing game carries on as the campaign.
let gameMode = 'online';
const saveKey = () => (fbAcc() ? ID + '.save.fb_' + fbAcc().uid : accounts.saveKey())
+ (gameMode === 'online' ? '.online' : '');
function setMode(m) {
const onlineOk = net && net.enabled && !LIVE.onlineOff;
gameMode = onlineOk ? m : 'campaign'; // no Firebase or switched off: campaign only
document.body.dataset.gmode = gameMode;
}
function switchMode(m) {
if (m === gameMode) return;
persist(); // keep the mode we are leaving
setMode(m);
loadSave(); hud(); shop.reset();
openGarage();
// banner() only works during a fight (it writes to F) - the mechanic says it instead
$('mechTip').textContent = t(gameMode === 'online' ? 'mode_online' : 'mode_campaign') + ': ' + t('mode_switched');
}
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 }) : '–'; $('hRank').textContent = save ? t('rank_' + RC.Progress.rankOf(save.fame).key) : '';
const ht = $('hTour');
if (ht) {
const running = save && save.tour && !save.tour.done;
const on = running || (typeof tourOpen === 'function' && tourOpen());
ht.classList.toggle('hide', !on);
if (on) ht.textContent = '🏆 ' + (running ? t('tour_continue') : t('tournament'));
}
const camp = gameMode === 'campaign';
$('hModeLbl').textContent = camp ? t('hud_league') : t('mode_online');
$('hLeague').textContent = !save ? '–' : camp ? t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length }) : t('mode_pvp');
$('hUser').textContent = fbUser() ? '👤 ' + fbUser().name : accounts.current ? (accounts.current.guest ? '👤 ' + t('guest') : '👤 ' + accounts.current.name) : save ? '👤 ' + t('guest') : '👤 –'; $('hUser').textContent = fbUser() ? '👤 ' + fbUser().name : accounts.current ? (accounts.current.guest ? '👤 ' + t('guest') : '👤 ' + accounts.current.name) : save ? '👤 ' + t('guest') : '👤 –';
$('bMute').textContent = audio.muted ? '🔇' : '🔊'; $('bMute').textContent = audio.muted ? '🔇' : '🔊';
$('bMute').title = (audio.muted ? t('sound_off') : t('sound_on')) + ' (M)'; $('bMute').title = (audio.muted ? t('sound_off') : t('sound_on')) + ' (M)';
@@ -218,6 +280,7 @@
mode = m; mode = m;
document.body.dataset.mode = m; // CSS shows/places the HUD per screen document.body.dataset.mode = m; // CSS shows/places the HUD per screen
document.body.classList.toggle('fighting', m === 'fight' || m === 'pause'); document.body.classList.toggle('fighting', m === 'fight' || m === 'pause');
if (m !== 'fight' && m !== 'pause') { const dv = $('dmgvig'); if (dv) dv.style.opacity = 0; } // clear the red damage glow when the fight is over
show('shop', m === 'garage'); show('shop', m === 'garage');
show('fightHud', m === 'fight' || m === 'pause' || m === 'result'); show('fightHud', m === 'fight' || m === 'pause' || m === 'result');
backdrop(m === 'garage' ? 'bg_workshop.jpg' : null); backdrop(m === 'garage' ? 'bg_workshop.jpg' : null);
@@ -235,7 +298,8 @@
overlay.innerHTML = `<div class="title"><div class="tpanel">${logo} overlay.innerHTML = `<div class="title"><div class="tpanel">${logo}
<div class="hazbar"></div><p class="tag">${t('click_start')}</p> <div class="hazbar"></div><p class="tag">${t('click_start')}</p>
<p class="credits">${CREDITS}</p></div></div>`; <p class="credits">${CREDITS}</p></div></div>`;
overlay.classList.remove('hide'); overlay.classList.add('clear'); overlay.style.backgroundImage = ''; overlay.classList.remove('hide'); overlay.classList.remove('clear');
overlay.style.backgroundImage = `url("${img('bg_start.jpg')}")`; // start screen backdrop (ComfyGen)
const go = e => { const go = e => {
if (e) { e.stopPropagation(); if (e.preventDefault) e.preventDefault(); } // must not also skip the intro if (e) { e.stopPropagation(); if (e.preventDefault) e.preventDefault(); } // must not also skip the intro
removeEventListener('pointerdown', go, true); removeEventListener('keydown', go, true); removeEventListener('pointerdown', go, true); removeEventListener('keydown', go, true);
@@ -284,10 +348,11 @@
overlay.innerHTML = `<div class="title"><div class="tpanel"> overlay.innerHTML = `<div class="title"><div class="tpanel">
${logo} ${logo}
<div class="tag">${t('menu_text')}</div> <div class="tag">${t('menu_text')}</div>
${liveBanner()}
<div class="hazbar"></div> <div class="hazbar"></div>
<div class="tmenu">${btns}</div> <div class="tmenu">${btns}</div>
<div class="trow2"><button id="bSet">⚙ ${t('settings')}</button><button id="bHelp">${t('how_to')}</button> <div class="trow2"><button id="bSet">⚙ ${t('settings')}</button><button id="bHelp">${t('how_to')}</button>
<button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>${scores.enabled ? `<button id="bRank">🏆 ${t('ranking')}</button>` : ''}</div> <button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>${save ? `<button id="bAch">🏅 ${t('achievements')}</button>` : ''}${scores.enabled ? `<button id="bRank">🏆 ${t('ranking')}</button>` : ''}</div>
<p class="credits">${CREDITS}</p></div></div>`; <p class="credits">${CREDITS}</p></div></div>`;
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(); }; };
@@ -300,14 +365,17 @@
on('bSet', () => showSettings(showTitle)); on('bSet', () => showSettings(showTitle));
on('bHelp', () => showHelp(showTitle)); on('bHelp', () => showHelp(showTitle));
on('bLang', () => L.next()); on('bLang', () => L.next());
on('bAch', () => showAchievements(showTitle));
on('bRank', () => showRanking(showTitle)); on('bRank', () => showRanking(showTitle));
hud(); hud();
} }
// ---------------------------------------------------------------- online lobby // ---------------------------------------------------------------- online lobby
let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker) let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker)
let ntour = null, inNetTour = false; // live multiplayer tournament
async function startOnline() { async function startOnline() {
if (!net.enabled) return; if (!net.enabled) return;
if (gameMode !== 'online') { setMode('online'); if (save) { loadSave(); hud(); } } // online uses its own save
if (!net.auth.current) { if (!net.auth.current) {
if (save && !fbAcc()) return joinAnon(); // playing as guest -> straight in, anonymously if (save && !fbAcc()) return joinAnon(); // playing as guest -> straight in, anonymously
showOnlineLogin(false, null, 'online'); return; showOnlineLogin(false, null, 'online'); return;
@@ -383,7 +451,7 @@
<label class="flagpick">${t('your_flag')} <select id="lFlag">${flagOpts}</select></label></div> <label class="flagpick">${t('your_flag')} <select id="lFlag">${flagOpts}</select></label></div>
<div class="plist">${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `<div class="muted" style="padding:16px;text-align:center">${t('lobby_empty')}</div>`)}</div> <div class="plist">${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `<div class="muted" style="padding:16px;text-align:center">${t('lobby_empty')}</div>`)}</div>
${pendingOut ? `<p class="muted" style="margin:6px 0 0">${t('waiting_accept')} <button class="link" id="lCancel">${t('cancel')}</button></p>` : ''} ${pendingOut ? `<p class="muted" style="margin:6px 0 0">${t('waiting_accept')} <button class="link" id="lCancel">${t('cancel')}</button></p>` : ''}
<div class="row" style="margin-top:8px"><button id="lBack">${t('back')}</button><button class="primary" id="lQuick">${t('quick_match')}</button></div> <div class="row" style="margin-top:8px"><button id="lBack">${t('back')}</button><button id="lTour">🏆 ${t('ltour_title')}</button><button class="primary" id="lQuick">${t('quick_match')}</button></div>
</div></div>`; </div></div>`;
overlay.classList.remove('hide'); overlay.classList.remove('clear'); overlay.classList.remove('hide'); overlay.classList.remove('clear');
overlay.style.backgroundImage = `linear-gradient(rgba(5,6,10,.6), rgba(5,6,10,.8)), url("${img('bg_title.jpg')}")`; overlay.style.backgroundImage = `linear-gradient(rgba(5,6,10,.6), rgba(5,6,10,.8)), url("${img('bg_title.jpg')}")`;
@@ -393,6 +461,80 @@
if ($('lCancel')) $('lCancel').onclick = () => { SFX.click(); lobby.cancel(); pendingOut = null; renderLobby(); }; if ($('lCancel')) $('lCancel').onclick = () => { SFX.click(); lobby.cancel(); pendingOut = null; renderLobby(); };
$('lQuick').onclick = () => { const idle = here.find(r => r.state === 'idle') || all.find(r => r.state === 'idle'); if (idle) { SFX.click(); pendingOut = idle.uid; lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); }; $('lQuick').onclick = () => { const idle = here.find(r => r.state === 'idle') || all.find(r => r.state === 'idle'); if (idle) { SFX.click(); pendingOut = idle.uid; lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); };
$('lBack').onclick = () => { SFX.click(); if (save) openGarage(); else showTitle(); }; $('lBack').onclick = () => { SFX.click(); if (save) openGarage(); else showTitle(); };
$('lTour').onclick = () => { SFX.click(); openNetTourney(); };
}
// ---------------------------------------------------------------- live multiplayer tournament
function openNetTourney() {
if (!(net && net.enabled && net.auth.current)) { showOnlineLogin(false, null, 'online'); return; }
const u = net.auth.current;
if (!ntour) ntour = RC.NetTourney(net, { uid: u.uid, name: u.name || playerName(), flag: save.flag || 'XX' }, {
onView: v => { if (inNetTour) renderNetTourney(v); },
startMatch: info => startNetTourMatch(info),
});
inNetTour = true;
ntour.join(save.build, paintObj());
renderNetTourney(ntour.view());
}
function leaveNetTourney() {
inNetTour = false;
if (ntour) { ntour.leave(); }
}
function renderNetTourney(v) {
if (!inNetTour) return;
const pls = v.players.map(p => `<div class="prow ${p.me ? 'me' : ''}"><span class="pf">${flagHtml(p.flag)}</span>`
+ `<span class="pn">${esc(p.name)}${p.me ? ` <span class="muted">(${t('you')})</span>` : ''}</span>`
+ `<span class="${p.ready ? 'plus' : 'muted'}">${p.ready ? '✔ ' + t('ltour_ready') : t('ltour_waiting')}</span></div>`).join('')
|| `<p class="muted" style="text-align:center;padding:12px">${t('ltour_empty')}</p>`;
let body, buttons = '';
if (v.phase === 'running' || v.phase === 'done') {
body = netBracketHtml(v);
if (v.me.match) buttons = `<button class="primary" id="ntFight">▶ ${t('tour_fight')} (${esc(v.me.match.opp || 'Bye')})</button>`;
else if (v.me.champion) body += `<p class="plus" style="text-align:center">🏆 ${t('tour_won')}</p>`;
else if (v.me.out) body += `<p class="muted" style="text-align:center">${t('tour_out')}</p>`;
else body += `<p class="muted" style="text-align:center">${t('ltour_wait_round')}</p>`;
} else {
const me = v.players.find(p => p.me);
body = `<p class="muted">${v.phase === 'countdown' ? t('ltour_countdown', { n: v.countdown }) : t('ltour_lobby', { n: v.readyCount })}</p>`
+ `<div class="plist" style="min-width:0;max-width:420px;margin:0 auto">${pls}</div>`;
buttons = me ? `<button class="${me.ready ? '' : 'primary'}" id="ntReady">${me.ready ? t('ltour_unready') : t('ltour_setready')}</button>` : '';
}
card(`<h1>🏆 ${t('ltour_title')}</h1>${body}
<div class="row">${buttons}<button id="ntBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
if ($('ntReady')) $('ntReady').onclick = () => { SFX.click(); const me = v.players.find(p => p.me); ntour.setReady(!(me && me.ready)); };
if ($('ntFight')) $('ntFight').onclick = () => { SFX.click(); if (v.me.match && v.me.match.opp == null) return; /* bye */ };
$('ntBack').onclick = () => { SFX.click(); leaveNetTourney(); showLobby(); };
}
function netBracketHtml(v) {
if (!v.order) return '';
const rounds = RC.LTourney.rounds(v.order, v.results);
const name = u => (u ? (v.players.find(p => p.uid === u) || {}).name || u.slice(0, 5) : '—');
let cols = '';
for (let r = 0; r < rounds.length; r++) {
const col = rounds[r]; if (col.length < 2 && r) continue;
let rows = '';
for (let i = 0; i < col.length; i += 2) {
rows += `<div class="tpair">${[col[i], col[i + 1]].map(u => {
const mine = u === net.auth.current.uid;
return `<div class="tslot ${mine ? 'you' : ''}">${esc(name(u))}</div>`; }).join('')}</div>`;
}
cols += `<div class="tcol"><div class="tch">${t('tour_round_' + (RC.Tourney.ROUND_KEY[r] || 'final'))}</div>${rows}</div>`;
}
return `<div class="bracket">${cols}</div>`;
}
function startNetTourMatch(info) {
const opp = { name: info.opp.name || 'Rival', build: info.opp.build, paint: info.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: info.opp.flag };
startFight(opp, false, false, { id: info.id, host: info.host, seed: info.seed, tourney: { round: info.round, pair: info.pairIndex, oppUid: info.oppUid } });
}
function endNetTourFight(res, won, me) {
if (ntour) ntour.reportWin(F.online.tourney.round, F.online.tourney.pair, won ? net.auth.current.uid : F.online.tourney.oppUid);
save.games++; if (won) save.wins++; else save.losses++;
save.fame += won ? 120 : 30; persist(); hud();
(won ? SFX.win : SFX.lose)();
setScreen('result');
card(`<h1>${won ? t('victory') : t('defeat')}</h1><p>${esc(F.opp.name)}</p>
<div class="row"><button class="primary" id="ntRes">🏆 ${t('ltour_title')}</button></div>`, { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('ntRes').onclick = () => { SFX.click(); inNetTour = true; renderNetTourney(ntour.view()); };
} }
function showIncoming(c) { function showIncoming(c) {
card(`<h2>${t('challenge_in')}</h2><p>${flagHtml(c.fromFlag)} <b>${esc(c.fromName)}</b> ${t('wants_fight')}</p> card(`<h2>${t('challenge_in')}</h2><p>${flagHtml(c.fromFlag)} <b>${esc(c.fromName)}</b> ${t('wants_fight')}</p>
@@ -470,6 +612,16 @@
// saves from older versions: missing parts, invalid ids, hangar migration // saves from older versions: missing parts, invalid ids, hangar migration
function repairSave() { function repairSave() {
save.owned = (save.owned || []).filter(id => RC.PARTS[id]); save.owned = (save.owned || []).filter(id => RC.PARTS[id]);
// weight classes: an older save has one league - that progress becomes the medium class
if (!save.leagues) {
save.leagues = { light: { beaten: 0, season: 1 },
medium: { beaten: save.beaten | 0, season: save.season || 1 },
heavy: { beaten: 0, season: 1 } };
}
for (const c of RC.CLASSES) if (!save.leagues[c.id]) save.leagues[c.id] = { beaten: 0, season: 1 };
if (!RC.CLASSES.some(c => c.id === save.cls)) save.cls = 'medium';
RC.setClass(save.cls);
save.beaten = save.leagues[save.cls].beaten; save.season = save.leagues[save.cls].season;
// hangar migration: older saves have only build/paint/robotName -> make it robot slot 0 // hangar migration: older saves have only build/paint/robotName -> make it robot slot 0
if (!Array.isArray(save.robots) || !save.robots.length) { if (!Array.isArray(save.robots) || !save.robots.length) {
save.robots = [{ name: save.robotName || 'Clank', build: save.build || Object.assign({}, RC.STARTER), paint: save.paint || { body: 0xff7a1a, accent: 0x15171b } }]; save.robots = [{ name: save.robotName || 'Clank', build: save.build || Object.assign({}, RC.STARTER), paint: save.paint || { body: 0xff7a1a, accent: 0x15171b } }];
@@ -530,6 +682,7 @@
function signOut() { function signOut() {
persist(); persist();
if (lobby && onlineReady) { lobby.leave(); onlineReady = false; lobbyRows = []; pendingOut = null; } if (lobby && onlineReady) { lobby.leave(); onlineReady = false; lobbyRows = []; pendingOut = null; }
if (ntour) { ntour.leave(); inNetTour = false; }
if (net && net.enabled) net.auth.logout(); if (net && net.enabled) net.auth.logout();
accounts.logout(); save = null; slot = null; F = null; hud(); accounts.logout(); save = null; slot = null; F = null; hud();
} }
@@ -559,10 +712,10 @@
${item(t('s_music'), `<input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">`)} ${item(t('s_music'), `<input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">`)}
${item(t('s_sfx'), `<input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">`)} ${item(t('s_sfx'), `<input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">`)}
${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))} ${item(t('s_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_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_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_autofire'), seg('sAuto', settings.autofire ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
${item(t('s_quiet'), seg('sQuiet', settings.quiet ? '1' : '0', [['0', t('off')], ['1', t('on')]]))}
${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))} ${item(t('s_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')]]))} ${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
</div> </div>
@@ -576,10 +729,10 @@
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('sSteer', v => { settings.steer = v; saveSettings(); });
segOn('sCam', v => { settings.cam = v; saveSettings(); if (view) view.setCam(v); }); segOn('sCam', v => { settings.cam = v; saveSettings(); if (view) view.setCam(v); });
segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); }); segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); });
segOn('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); });
segOn('sArena', v => { settings.arena = v; 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);
@@ -614,6 +767,41 @@
step(); step();
} }
// one line for the running event and one for the admin's message
function liveBanner() {
const out = [];
if (LIVE.event) {
const n = liveText(LIVE.event.name) || t('event_running');
const extra = LIVE.event.prizeMul !== 1 ? ` · ${t('event_prize', { n: LIVE.event.prizeMul })}` : '';
out.push(`<div class="evbar"><b>${t('event')}</b><span>${esc(n)}${extra}</span></div>`);
}
const m = liveText(LIVE.motd);
if (m) out.push(`<p class="motd">${esc(m)}</p>`);
return out.join('');
}
function showAchievements(back) {
overlayEnter();
const P = RC.Progress, r = P.rankOf(save.fame);
const pct = Math.round(r.pct * 100);
const nextLine = r.next
? t('rank_next', { n: t('rank_' + r.next.key), f: Kit.fmt(r.next.at - save.fame) })
: t('rank_top');
const rows = P.ACHIEVEMENTS.map(a => {
const done = !!(save.ach && save.ach[a.id]);
return `<div class="achrow ${done ? 'done' : 'todo'}"><span class="am">${done ? '🏅' : '🔒'}</span>
<span><span class="an">${t('ach_' + a.id)}</span><br><span class="ad">${t('achd_' + a.id)}</span></span>
<span class="${done ? 'plus' : 'muted'}">${Kit.fmt(a.reward)}</span></div>`;
}).join('');
card(`<h2>🏅 ${t('achievements')}</h2>
<div class="rankbar"><div class="rt"><b>${t('rank_' + r.key)}</b><span class="muted">${nextLine}</span></div>
<div class="bar"><i style="width:${pct}%"></i></div></div>
<p class="muted">${t('ach_done', { n: P.earned(save), m: P.total })}</p>
<div class="achlist">${rows}</div>
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); back(); };
}
function showHelp(back) { function showHelp(back) {
overlayEnter(); overlayEnter();
card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>${keysHtml()} card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>${keysHtml()}
@@ -631,6 +819,14 @@
$('bNo').onclick = () => { SFX.click(); back(); }; $('bNo').onclick = () => { SFX.click(); back(); };
$('bYes').onclick = () => { Object.assign(save, newSave()); RC.layerFromData(layer, null); save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); }; $('bYes').onclick = () => { Object.assign(save, newSave()); RC.layerFromData(layer, null); save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); };
} }
// the rank badge opens the achievements page
$('hTour').onclick = () => { SFX.click(); openNetTourney(); };
$('chipFame').onclick = () => {
if (!save || mode === 'intro' || mode === 'title') return;
if (mode === 'fight') togglePause();
SFX.click();
showAchievements(mode === 'pause' ? () => { mode = 'fight'; togglePause(); } : currentBack());
};
$('bSettings').onclick = () => { $('bSettings').onclick = () => {
if (mode === 'fight') togglePause(); if (mode === 'fight') togglePause();
if (mode === 'intro') skipIntro(); if (mode === 'intro') skipIntro();
@@ -657,17 +853,98 @@
setScreen('garage'); setScreen('garage');
view.showGarage(save.build, paintObj()); view.showGarage(save.build, paintObj());
audio.music('music_garage'); audio.music('music_garage');
shop.render(); hud(); shop.render(); hud(); updateShopBar();
$('zIn').onclick = () => { SFX.click(); view.zoomGarage(1.18); }; $('zIn').onclick = () => { SFX.click(); view.zoomGarage(1.18); };
$('zOut').onclick = () => { SFX.click(); view.zoomGarage(1 / 1.18); }; $('zOut').onclick = () => { SFX.click(); view.zoomGarage(1 / 1.18); };
} }
$('bGMenu').onclick = () => { SFX.click(); persist(); startIntroOrTitle(); }; $('bGMenu').onclick = () => { SFX.click(); persist(); startIntroOrTitle(); };
$('bGOnline').onclick = () => { SFX.click(); persist(); startOnline(); }; $('bGMode').onclick = () => { SFX.click(); switchMode(gameMode === 'online' ? 'campaign' : 'online'); };
if (!(net && net.enabled)) $('bGOnline').style.display = 'none'; const onlineUsable = () => !!(net && net.enabled && !LIVE.onlineOff);
if (!onlineUsable()) $('bGMode').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(); if (gameMode === 'online') { persist(); startOnline(); } else showLeague(); };
function updateShopBar() {
const on = gameMode === 'online';
$('bGMode').style.display = onlineUsable() ? '' : 'none';
$('bGMode').textContent = on ? '🏆 ' + t('mode_campaign') : '🌍 ' + t('mode_online');
$('bLeague').textContent = on ? t('to_lobby') : t('to_league');
}
function applyClass(id) {
if (id === save.cls) return;
persist(); // write the ladder we are leaving
save.cls = id;
RC.setClass(id);
save.beaten = save.leagues[id].beaten; save.season = save.leagues[id].season;
save.tour = null; // a running bracket belongs to its class
persist(); hud(); shop.render();
}
// ---------------------------------------------------------------- tournament
function tourState() { return save.tour || null; }
const tourOpen = () => !!LIVE.tournament; // admin switch
const tourFee = () => (tourOpen() ? 0 : RC.Tourney.ENTRY_FEE);
function startTournament() {
if (save.money < tourFee()) { SFX.deny(); return; }
save.money -= tourFee();
save.tour = RC.Tourney.create({ me: { name: save.robotName, build: save.build, paint: paintObj() }, seed: (Date.now() & 0xffffff) || 1 });
persist(); hud();
showTournament();
}
function showTournament() {
const st = tourState();
if (!st) { showLeague(); return; }
overlayEnter();
const nameOf = e => (e.player ? save.robotName : e.name);
// a slot won its match if it shows up again in the next round's line-up (same object)
const advanced = (e, r) => st.rounds[r + 1] && st.rounds[r + 1].indexOf(e) >= 0;
const pr = RC.Tourney.pair(st); // the player's match this round (null if done)
const playerMatch = !st.done && pr ? pr : null;
// draw the bracket column by column: quarters -> semis -> final -> champion
let cols = '';
for (let r = 0; r < st.rounds.length; r++) {
const col = st.rounds[r];
if (col.length < 2) continue; // single entry = champion, shown separately
let rows = '';
for (let i = 0; i < col.length; i += 2) {
const pair = [col[i], col[i + 1]].filter(Boolean);
const isPlayerPair = !st.done && r === st.round && pair.indexOf(pr && pr[0]) >= 0;
const slots = pair.map(e => {
const you = e.player, win = advanced(e, r);
return `<div class="tslot ${you ? 'you' : ''} ${win ? 'win' : ''}" title="${esc(nameOf(e))}">${esc(nameOf(e))}${you ? '' : ` <span class="ki">${t('ai_tag')}</span>`}</div>`;
}).join('');
rows += `<div class="tpair ${isPlayerPair ? 'now' : ''}" ${isPlayerPair ? 'data-go="1"' : ''}>${slots}${isPlayerPair ? `<div class="tgo">▶ ${t('tour_fight')}</div>` : ''}</div>`;
}
cols += `<div class="tcol"><div class="tch">${t('tour_round_' + (RC.Tourney.ROUND_KEY[r] || 'final'))}</div>${rows}</div>`;
}
// champion column
const champ = st.done && st.won ? save.robotName : (st.rounds.length && st.rounds[st.rounds.length - 1].length === 1 ? nameOf(st.rounds[st.rounds.length - 1][0]) : '?');
cols += `<div class="tcol"><div class="tch">🏆 ${t('tour_champion')}</div><div class="tpair"><div class="tslot ${st.won ? 'you win' : 'win'}">${st.done ? esc(champ) : '…'}</div></div></div>`;
let head, buttons;
if (st.done) {
head = st.won
? `<p class="plus">🏆 ${t('tour_won')} · ${t('tour_won_text', { n: Kit.fmt(st.prize) })}</p>`
: `<p>${t('tour_out')} · ${t('tour_out_text', { n: Kit.fmt(st.prize) })}</p>`;
buttons = `<button class="primary" id="tDone">${t('to_garage')}</button>`;
} else {
head = `<p>${t('tour_round_' + RC.Tourney.ROUND_KEY[st.round])} · ${playerMatch ? t('tour_your_match', { name: esc(playerMatch[1].name) }) : ''}</p>`;
buttons = `<button id="tLater">${t('back')}</button><button class="primary" id="tGo">${t('tour_fight')}</button>`;
}
card(`<h1>🏆 ${t('tournament')}</h1>${head}
<div class="bracket">${cols}</div>
<div class="row">${buttons}</div>`, { wide: true, bg: 'bg_title.jpg' });
const go = () => { SFX.click(); const p = RC.Tourney.pair(st); RC.Tourney.simOthers(st); persist(); startFight(p[1], false, false, null, true); };
if ($('tGo')) $('tGo').onclick = go;
overlay.querySelectorAll('.tpair.now').forEach(el => { el.style.cursor = 'pointer'; el.onclick = go; });
if ($('tLater')) $('tLater').onclick = () => { SFX.click(); openGarage(); };
if ($('tDone')) $('tDone').onclick = () => { SFX.click(); save.tour = null; persist(); openGarage(); };
}
function showLeague() { function showLeague() {
if (gameMode !== 'campaign') { switchMode('campaign'); return; } // league is campaign-only
setScreen('league'); setScreen('league');
const cards = RC.LEAGUE.map((o, i) => { const cards = RC.LEAGUE.map((o, i) => {
const cls = i < save.beaten ? 'done' : i === save.beaten ? 'next' : 'locked'; const cls = i < save.beaten ? 'done' : i === save.beaten ? 'next' : 'locked';
@@ -675,10 +952,21 @@
<div class="sm">${i <= save.beaten ? t('style_' + o.style) : '???'}</div> <div class="sm">${i <= save.beaten ? t('style_' + o.style) : '???'}</div>
<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> const tabs = RC.CLASSES.map(c => {
<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> const pr = save.leagues[c.id] || { beaten: 0, season: 1 };
return `<button data-v="${c.id}" class="${c.id === save.cls ? 'on' : ''}">${t('cls_' + c.id)}
<small>${c.max} kg · ${pr.beaten}/${RC.LEAGUES[c.id].length}</small></button>`;
}).join('');
card(`<h2>${t('league_title', { s: save.season })}</h2>
<div class="seg clstabs" id="clsTabs">${tabs}</div>
<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>
${save.beaten ? `<p class="muted">${t('exhibition_hint')}</p>` : ''}`, ${save.beaten ? `<p class="muted">${t('exhibition_hint')}</p>` : ''}`,
{ wide: true, bg: 'bg_title.jpg' }); { wide: true, bg: 'bg_title.jpg' });
$('clsTabs').querySelectorAll('button').forEach(b => {
b.onclick = () => { SFX.click(); applyClass(b.dataset.v); showLeague(); };
});
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) // 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); }; }); 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); }; });
@@ -700,9 +988,19 @@
} }
// ---------------------------------------------------------------- fight // ---------------------------------------------------------------- fight
function startFight(opp, training, exhibition, online) { // spawn intro: the steel gate is shut over the arena, then splits open with a metal sound
function gateOpen() {
const g = $('gate'); if (!g) return;
g.classList.remove('open', 'hide');
void g.offsetWidth; // reflow so the transition runs from the shut state
SFX.gate();
requestAnimationFrame(() => g.classList.add('open'));
setTimeout(() => g.classList.add('hide'), 1150);
}
function startFight(opp, training, exhibition, online, tour) {
hideOverlay(); hideOverlay();
const D = DIFF[settings.diff] || DIFF.easy; const D = BASE;
const stA = RC.stats(save.build), stB = RC.stats(opp.build); const stA = RC.stats(save.build), stB = RC.stats(opp.build);
if (!online) stA.hp = Math.round(stA.hp * D.hp); // no handicap in live PvP if (!online) stA.hp = Math.round(stA.hp * D.hp); // no handicap in live PvP
const seed = online ? online.seed : (Date.now() & 0xffff) + save.games * 31; const seed = online ? online.seed : (Date.now() & 0xffff) + save.games * 31;
@@ -710,12 +1008,13 @@
const ids = RC.ARENAS.map(a => a.id), idx = RC.LEAGUE.indexOf(opp); const ids = RC.ARENAS.map(a => a.id), idx = RC.LEAGUE.indexOf(opp);
const bySize = RC.ARENAS.slice().sort((a, b) => a.half - b.half).map(a => a.id); // small -> big for league progression const bySize = RC.ARENAS.slice().sort((a, b) => a.half - b.half).map(a => a.id); // small -> big for league progression
const arenaId = DEV.get('arena') ? DEV.get('arena') const arenaId = DEV.get('arena') ? DEV.get('arena')
: (LIVE.event && LIVE.event.arena && !online) ? LIVE.event.arena
: online ? ids[seed % ids.length] : online ? ids[seed % ids.length]
: idx >= 0 ? bySize[Math.min(bySize.length - 1, Math.floor(idx * bySize.length / RC.LEAGUE.length))] : idx >= 0 ? bySize[Math.min(bySize.length - 1, Math.floor(idx * bySize.length / RC.LEAGUE.length))]
: settings.arena === 'random' || !settings.arena ? ids[(Math.random() * ids.length) | 0] : settings.arena; : settings.arena === 'random' || !settings.arena ? ids[(Math.random() * ids.length) | 0] : settings.arena;
const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name], arena: arenaId }); const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name], arena: arenaId });
const skill = Kit.clamp(opp.skill + (save.season - 1) * 0.12 + D.skill, 0, 1); const skill = Kit.clamp(opp.skill + (save.season - 1) * 0.12 + D.skill, 0, 1);
F = { s, opp, training, exhibition: !!exhibition, online, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4, F = { s, opp, training, exhibition: !!exhibition, online, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4,
acc: [0, 0], accT: 0, banner: null, ended: false }; acc: [0, 0], accT: 0, banner: null, ended: false };
if (online) { 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 = 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) });
@@ -739,6 +1038,7 @@
fx.clear(); fx.clear();
setScreen('fight'); setScreen('fight');
audio.music('music_fight'); audio.music('music_fight');
gateOpen();
banner('📍 ' + t('arena_' + s.arena.id), '#ff7a1a', 2.2); banner('📍 ' + t('arena_' + s.arena.id), '#ff7a1a', 2.2);
if (save.games === 0 && !F.online) setTimeout(() => { if (mode === 'fight') banner(t('tut_controls'), '#ffffff', 5); }, 2400); if (save.games === 0 && !F.online) setTimeout(() => { if (mode === 'fight') banner(t('tut_controls'), '#ffffff', 5); }, 2400);
const pg = $('padGadget'); if (pg) pg.style.display = s.robots[0].st.gadget ? '' : 'none'; const pg = $('padGadget'); if (pg) pg.style.display = s.robots[0].st.gadget ? '' : 'none';
@@ -798,7 +1098,8 @@
const near = tw.type === 'flamer' || tw.type === 'zapper'; const near = tw.type === 'flamer' || tw.type === 'zapper';
k.fire2 = dist < tw.range * 0.95 && ahead < (near ? 0.5 : 0.3); k.fire2 = dist < tw.range * 0.95 && ahead < (near ? 0.5 : 0.3);
} }
if (me.st.gadget && !k.fire3) k.fire3 = RC.Combat.wantGadget(s, me, en); // the mine layer stays manual - you decide where a mine goes, the helper does not
if (me.st.gadget && me.st.gadget.type !== 'mines' && !k.fire3) k.fire3 = RC.Combat.wantGadget(s, me, en);
} }
return k; return k;
} }
@@ -852,7 +1153,9 @@
function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; } function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; }
let ntourT = 0;
function update(dt) { function update(dt) {
if (ntour && inNetTour) { ntourT -= dt; if (ntourT <= 0) { ntourT = 2; ntour.tick(); } }
fx.update(dt); fx.update(dt);
introTick(); introTick();
if (mode !== 'fight' || !F) return; if (mode !== 'fight' || !F) return;
@@ -960,10 +1263,27 @@
$('fState').textContent = st; $('fState').textContent = st;
} }
// achievements are part of the save, so campaign and online each have their own
function awardAch(ctx) {
const got = RC.Progress.check(save, ctx);
if (!got.length) return got;
let pay = 0;
for (const a of got) pay += a.reward;
save.money += pay;
persist();
SFX.buy && SFX.buy();
return got;
}
const achHtml = got => (!got || !got.length ? '' :
`<div class="achwon"><b>🏅 ${t('ach_new')}</b>` + got.map(a =>
`<div><span>${t('ach_' + a.id)}</span><span class="plus">+${Kit.fmt(a.reward)}</span></div>`).join('') + '</div>');
function endFight() { function endFight() {
const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp); const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp);
const won = res.winner === 0, me = s.robots[0]; const won = res.winner === 0, me = s.robots[0];
if (F.online && F.online.tourney) { endNetTourFight(res, won, me); return; }
if (F.online) { endOnlineFight(res, won, me); return; } if (F.online) { endOnlineFight(res, won, me); return; }
if (F.tour) { endTourFight(res, won, me); return; }
const lines = []; const lines = [];
let money = 0, fame = 0, champion = false; let money = 0, fame = 0, champion = false;
if (!F.training) { if (!F.training) {
@@ -995,10 +1315,14 @@
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 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 = applyEvent(money, lines);
money -= paid; money -= paid;
save.money += money; save.fame += fame; save.money += money; save.fame += fame;
persist(); persist();
} }
const gotAch = awardAch({ won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt,
lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length,
training: F.training, exhibition: F.exhibition, champion });
hud(); hud();
(won ? SFX.win : SFX.lose)(); (won ? SFX.win : SFX.lose)();
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat'); const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
@@ -1009,6 +1333,7 @@
card(`<h1>${title}</h1><p>${why}</p> card(`<h1>${title}</h1><p>${why}</p>
${champion ? `<h2>${t('champion_title', { s: save.season - 1 })}</h2><p>${t('champion_text')}</p>` : ''} ${champion ? `<h2>${t('champion_title', { s: save.season - 1 })}</h2><p>${t('champion_text')}</p>` : ''}
<div class="res">${stats}${rows}${!F.training && fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div> <div class="res">${stats}${rows}${!F.training && fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div>
${achHtml(gotAch)}
${F.training ? `<p class="muted">${t('training_note')}</p>` : ''} ${F.training ? `<p class="muted">${t('training_note')}</p>` : ''}
<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' });
@@ -1020,6 +1345,40 @@
} else fillBoard(); } else fillBoard();
} }
// a tournament round: the bracket moves on, the round prize is paid, then back to the bracket
function endTourFight(res, won, me) {
const st = save.tour, lines = [];
const before = st.prize;
RC.Tourney.advance(st, won);
const roundPay = st.prize - before;
save.games++;
if (won) save.wins++; else save.losses++;
let money = 0, fame = won ? 70 * st.round : 20;
if (roundPay) { money += roundPay; lines.push([t('tour_round_prize'), roundPay]); }
const db = Math.round(me.dealt * 0.6);
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
if (st.won) { money += 2000; fame += 400; lines.push([t('tour_trophy'), 2000]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06);
money = applyEvent(money, lines);
const paid = Math.min(repair, save.money + money);
if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); }
save.money += money; save.fame += fame;
persist();
const gotAch = awardAch({ won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt,
lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length, tourWon: st.won });
hud();
(won ? SFX.win : SFX.lose)();
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>${won ? t('victory') : t('defeat')}</h1><p>${esc(F.opp.name)}</p>
<div class="res"><span>${t('r_dealt')}</span><span>${Math.round(me.dealt)}</span>${rows}
<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span></div>
${achHtml(gotAch)}
<div class="row"><button class="primary" id="bTour">🏆 ${t('tournament')}</button></div>`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bTour').onclick = () => { SFX.click(); showTournament(); };
}
function endOnlineFight(res, won, me) { function endOnlineFight(res, won, me) {
if (F.nf) F.nf.stop(); if (F.nf) F.nf.stop();
if (lobby) lobby.endMatch(); if (lobby) lobby.endMatch();
@@ -1036,17 +1395,22 @@
const db = Math.round(me.dealt * 0.6); const db = Math.round(me.dealt * 0.6);
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); } 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 repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06);
money = applyEvent(money, lines);
const paid = Math.min(repair, save.money + money); const paid = Math.min(repair, save.money + money);
if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); } if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); }
save.money += money; save.fame += fame; save.games++; save.money += money; save.fame += fame; save.games++;
if (won) save.wins++; else if (!draw) save.losses++; if (won) save.wins++; else if (!draw) save.losses++;
persist(); hud(); persist();
const gotAch = awardAch({ won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt,
lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length });
hud();
if (save.fame > save.best) { save.best = save.fame; persist(); scores.submit({ name: playerName(), score: save.fame, level: save.season }); } 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(''); const rows = lines.map(([k, v]) => `<span>${k}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
setScreen('result'); setScreen('result');
card(`<h1>${title}</h1><p>${esc(F.opp.name)} ${F.nf && !F.nf.peerAlive ? t('peer_left') : ''}</p> card(`<h1>${title}</h1><p>${esc(F.opp.name)} ${F.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} <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> ${fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div>
${achHtml(gotAch)}
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button><button id="bShopO">${t('to_garage')}</button></div>`, <div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button><button id="bShopO">${t('to_garage')}</button></div>`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' }); { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bLobby').onclick = () => { SFX.click(); showLobby(); }; $('bLobby').onclick = () => { SFX.click(); showLobby(); };
@@ -1128,7 +1492,7 @@
addEventListener('blur', () => { if (mode === 'fight' && !(F && F.online)) 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(); updateShopBar();
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();
@@ -1137,11 +1501,37 @@
}); });
// ---------------------------------------------------------------- start // ---------------------------------------------------------------- start
// backend settings; applied as soon as they arrive and whenever the admin changes them
RC.Live.load(net, v => {
LIVE = v;
if (LIVE.onlineOff && gameMode === 'online' && save) switchMode('campaign');
if (mode === 'title') showTitle(); else if (mode === 'lobby') renderLobby();
});
if (DEV.get('live')) { // dev: &live=event|off|old|lock (no Firebase needed)
const k = DEV.get('live'), now = Date.now();
const demo = {
event: { event: { id: 'demo', name: { de: 'Schwergewichts-Wochenende', en: 'Heavyweight weekend' }, type: 'prize', prizeMul: 2, from: now - 1000, to: now + 36e5 } },
off: { flags: { onlineOff: true, note: { de: 'Wartung', en: 'Maintenance' } } },
old: { build: { min: '99999999.9999' } }, // paired with a fake stamp below
lock: { unlock: { parts: ['crate', 'sparky', 'rubber', 'lead', 'wedge'] } },
motd: { motd: { de: 'Turnier am Samstag um 20 Uhr!', en: 'Tournament on Saturday, 8pm!' } },
}[k];
if (k === 'old' && !BUILD_ID()) window.RC_BUILD = '20000101.0000';
if (demo) LIVE = RC.Live.parse(demo, now, BUILD_ID());
}
setMode('online'); // every page load starts in online play
accounts.resume(); accounts.resume();
if (net && net.enabled) { net.auth.resume(); net.auth.onChange(() => { hud(); if (mode === 'title') showTitle(); }); } if (net && net.enabled) { net.auth.resume(); net.auth.onChange(() => { hud(); if (mode === 'title') showTitle(); }); }
hud(); hud();
if (!hostOk()) { if (!hostOk()) {
card(`<h1>Robot Clash</h1><p>${t('wrong_host')}</p><p class="credits">${CREDITS}</p>`); card(`<h1>Robot Clash</h1><p>${t('wrong_host')}</p><p class="credits">${CREDITS}</p>`);
} else if (LIVE.needsReload) {
// the admin published a newer build; browsers happily serve the cached old file
setScreen('intro'); // defined UI state while this card is up
card(`<h2>${t('reload_title')}</h2><p>${t('reload_text')}</p>
<div class="row"><button class="primary" id="rNow">${t('reload_now')}</button><button id="rSkip">${t('reload_skip')}</button></div>`);
$('rNow').onclick = () => location.reload();
$('rSkip').onclick = () => { LIVE.needsReload = false; SFX.click(); startGate(startIntro); };
} else if (!view) { } else 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')) {
@@ -1156,11 +1546,14 @@
if (DEV.get('shoptab') && mode === 'garage') shop.setTab(DEV.get('shoptab')); if (DEV.get('shoptab') && mode === 'garage') shop.setTab(DEV.get('shoptab'));
if (DEV.get('sel') && mode === 'garage') { const id = DEV.get('sel'), p = RC.PARTS[id]; if (p) { const tb = document.querySelector(`.tab[data-slot="${p.slot}"]`); if (tb) tb.click(); const it = document.querySelector(`.item[data-id="${id}"]`); if (it) it.click(); } } if (DEV.get('sel') && mode === 'garage') { const id = DEV.get('sel'), p = RC.PARTS[id]; if (p) { const tb = document.querySelector(`.tab[data-slot="${p.slot}"]`); if (tb) tb.click(); const it = document.querySelector(`.item[data-id="${id}"]`); if (it) it.click(); } }
// dev: ?play&screen=league|vs|settings|help|lobby|pause opens that screen (layout screenshots) // dev: ?play&screen=league|vs|settings|help|lobby|pause opens that screen (layout screenshots)
if (DEV.get('gmode')) switchMode(DEV.get('gmode')); // dev: &gmode=campaign|online
const scr = DEV.get('screen'); const scr = DEV.get('screen');
if (scr === 'league') { save.beaten = Math.max(save.beaten, 3); showLeague(); } if (scr === 'league') { save.beaten = Math.max(save.beaten, 3); showLeague(); }
else if (scr === 'vs') showVs(RC.LEAGUE[4]); else if (scr === 'vs') showVs(RC.LEAGUE[4]);
else if (scr === 'settings') showSettings(openGarage); else if (scr === 'settings') showSettings(openGarage);
else if (scr === 'help') showHelp(openGarage); else if (scr === 'help') showHelp(openGarage);
else if (scr === 'tour') { save.money = 3000; startTournament(); }
else if (scr === 'ach') { save.fame = 1200; save.ach = { first_win: true, ko: true, rich: true }; showAchievements(openGarage); }
else if (scr === 'lobby') { 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' }]; 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; lobbyRoom = DEV.get('room') || null;
@@ -1178,7 +1571,7 @@
painter.open(); view.showGarage(save.build, paintObj()); painter.open(); view.showGarage(save.build, paintObj());
} }
} else if (DEV.has('online') && net.enabled) { startIntroOrTitle(); startOnline(); } } else if (DEV.has('online') && net.enabled) { startIntroOrTitle(); startOnline(); }
else if (DEV.has('title')) startGate(startIntroOrTitle); else if (DEV.has('title')) startIntroOrTitle();
else startGate(startIntro); else startGate(startIntro);
if (DEV.has('tut')) startTutorial(openGarage); // dev: ?play&tut previews the first-start cards if (DEV.has('tut')) startTutorial(openGarage); // dev: ?play&tut previews the first-start cards
if (DEV.has('uicheck') && RC.uiCheckRun) RC.uiCheckRun(); // dev: &uicheck prints layout faults as text if (DEV.has('uicheck') && RC.uiCheckRun) RC.uiCheckRun(); // dev: &uicheck prints layout faults as text

View File

@@ -105,7 +105,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; max-height: 600px; overflow-y: auto; text-align: center; box-shadow: 0 20px 60px #000a; } min-width: 380px; max-width: 760px; max-height: 624px; overflow-y: auto; text-align: center; box-shadow: 0 20px 60px #000a; }
.card h1 { margin: 0 0 6px; font: 44px var(--head); letter-spacing: .05em; color: var(--accent); text-shadow: 0 3px 0 #5a2600; } .card h1 { margin: 0 0 6px; font: 44px var(--head); letter-spacing: .05em; color: var(--accent); text-shadow: 0 3px 0 #5a2600; }
.card h2 { margin: 0 0 10px; padding-bottom: 8px; font: 26px var(--head); letter-spacing: .04em; color: var(--accent); .card h2 { margin: 0 0 10px; padding-bottom: 8px; font: 26px var(--head); letter-spacing: .04em; color: var(--accent);
position: relative; } position: relative; }
@@ -165,9 +165,29 @@
.setacc .who { font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .setacc .who { font-size: 14px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* league */ /* league */
/* tournament bracket */
.bracket { display: flex; gap: 10px; justify-content: center; align-items: center; margin: 10px 0; }
.tcol { display: flex; flex-direction: column; justify-content: space-around; gap: 6px; flex: 1; min-width: 0; }
.tch { font: 10px var(--head); letter-spacing: .08em; text-transform: uppercase; color: var(--dim); text-align: center; margin-bottom: 2px; }
.tpair { background: rgba(12,14,19,.7); border: 1px solid var(--line); border-radius: var(--r2); padding: 3px;
display: flex; flex-direction: column; gap: 3px; position: relative; }
.tpair.now { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,122,26,.3); }
.tslot { font-size: 11.5px; padding: 3px 7px; border-radius: var(--r1); background: var(--panel2);
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--dim); }
.tslot.win { color: var(--text); font-weight: 700; }
.tslot .ki { font-size: 9px; background: #3c4556; color: #c9cfdc; border-radius: 3px; padding: 0 3px; vertical-align: middle; }
.tslot.you { background: #2a1c10; color: var(--accent); border: 1px solid var(--accent); }
.tslot.you.win { background: var(--accent); color: #1a0c02; }
.tgo { position: absolute; right: -9px; top: 50%; transform: translateY(-50%); background: var(--accent);
color: #1a0c02; font: 10px var(--head); padding: 2px 6px; border-radius: 5px; z-index: 1; white-space: nowrap; }
@media (hover: hover) { .tpair.now:hover { filter: brightness(1.1); } }
.clstabs { margin: 0 auto 10px; max-width: 520px; }
.clstabs button { flex: 1; padding: 6px 8px; font: 13px var(--head); letter-spacing: .03em; line-height: 1.25; }
.clstabs button small { display: block; font: 11px "Segoe UI", sans-serif; letter-spacing: 0; color: var(--dim); }
.clstabs button.on small { color: #4a2a08; }
.opps { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 10px 0; } .opps { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 10px 0; }
.opp { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 6px; text-align: center; position: relative; } .opp { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 6px; text-align: center; position: relative; }
.opp > .pic { width: 100%; height: 92px; font-size: 56px; } .opp > .pic { width: 100%; height: 78px; font-size: 48px; }
.opp .nm { font: 14px var(--head); letter-spacing: .03em; } .opp .nm { font: 14px var(--head); letter-spacing: .03em; }
.opp .sm { font-size: 11px; color: var(--dim); min-height: 28px; } .opp .sm { font-size: 11px; color: var(--dim); min-height: 28px; }
.opp .pz { color: var(--gold); font-size: 13px; display: flex; gap: 4px; justify-content: center; align-items: center; } .opp .pz { color: var(--gold); font-size: 13px; display: flex; gap: 4px; justify-content: center; align-items: center; }
@@ -184,7 +204,7 @@
.res .plus { color: var(--good); } .res .minus { color: var(--warn); } .res .plus { color: var(--good); } .res .minus { color: var(--warn); }
/* shop */ /* shop */
#shop { position: absolute; inset: 44px 0 0; display: grid; grid-template-columns: 340px 1fr; z-index: 3; pointer-events: none; } #shop { position: absolute; inset: 44px 0 0; display: grid; grid-template-columns: 300px 1fr; z-index: 3; pointer-events: none; }
#shop.hide, #fightHud.hide { display: none; } #shop.hide, #fightHud.hide { display: none; }
#shop > * { pointer-events: auto; } #shop > * { pointer-events: auto; }
#sLeft { display: flex; flex-direction: column; padding: 12px; gap: 8px; pointer-events: none; } #sLeft { display: flex; flex-direction: column; padding: 12px; gap: 8px; pointer-events: none; }
@@ -198,13 +218,13 @@
.hslot .hdel:hover { background: rgba(0,0,0,.25); opacity: 1; } .hslot .hdel:hover { background: rgba(0,0,0,.25); opacity: 1; }
.hadd { padding: 4px 11px; font-size: 15px; font-weight: 700; color: var(--accent); } .hadd { padding: 4px 11px; font-size: 15px; font-weight: 700; color: var(--accent); }
/* name plate riveted to the robot, always readable (not only on hover) */ /* name plate riveted to the robot, always readable (not only on hover) */
#rname { width: 100%; font: 24px var(--head); letter-spacing: .04em; background: rgba(11,14,20,.82); #rname { width: 100%; font: 20px var(--head); letter-spacing: .04em; background: rgba(11,14,20,.82);
border: 1px solid var(--line); border-left: 3px solid var(--accent); border-radius: var(--r2); border: 1px solid var(--line); border-left: 3px solid var(--accent); border-radius: var(--r2);
color: var(--text); padding: 4px 10px; text-shadow: 0 2px 6px #000; box-shadow: var(--hl); } color: var(--text); padding: 4px 10px; text-shadow: 0 2px 6px #000; box-shadow: var(--hl); }
#rname:hover, #rname:focus { border-color: var(--accent); outline: none; } #rname:hover, #rname:focus { border-color: var(--accent); outline: none; }
.mech { display: flex; gap: 8px; align-items: flex-end; } .mech { display: flex; gap: 8px; align-items: flex-end; }
.mech .pic { width: 50px; height: 60px; font-size: 34px; border-radius: 8px; overflow: hidden; background: rgba(0,0,0,.35); border: 1px solid var(--line); } .mech .pic { width: 42px; height: 50px; font-size: 28px; border-radius: 8px; overflow: hidden; background: rgba(0,0,0,.35); border: 1px solid var(--line); }
.mech .bubble { background: rgba(250,246,238,.95); color: #1b1d22; border-radius: 10px 10px 10px 2px; padding: 5px 8px; font-size: 12px; max-width: 262px; box-shadow: 0 4px 14px #0008; } .mech .bubble { background: rgba(250,246,238,.95); color: #1b1d22; border-radius: 10px 10px 10px 2px; padding: 5px 8px; font-size: 11.5px; max-width: 210px; box-shadow: 0 4px 14px #0008; }
.spacer { flex: 1; pointer-events: none !important; } .spacer { flex: 1; pointer-events: none !important; }
.stats { background: rgba(12,14,19,.8); border: 1px solid var(--line); border-radius: 10px; padding: 6px 8px; display: grid; grid-template-columns: 1fr 1fr; gap: 3px 10px; font-size: 11px; font-variant-numeric: tabular-nums; } .stats { background: rgba(12,14,19,.8); border: 1px solid var(--line); border-radius: 10px; padding: 6px 8px; display: grid; grid-template-columns: 1fr 1fr; gap: 3px 10px; font-size: 11px; font-variant-numeric: tabular-nums; }
.stats .st { display: grid; grid-template-columns: 18px 1fr 54px; gap: 5px; align-items: center; } .stats .st { display: grid; grid-template-columns: 18px 1fr 54px; gap: 5px; align-items: center; }
@@ -232,13 +252,13 @@
.zoombar button { width: 30px; height: 26px; padding: 0; font-size: 16px; font-weight: 700; } .zoombar button { width: 30px; height: 26px; padding: 0; font-size: 16px; font-weight: 700; }
/* fitted parts strip (bottom of the parts view): 7 compact chips, does not cover the robot preview */ /* fitted parts strip (bottom of the parts view): 7 compact chips, does not cover the robot preview */
.fittedwrap { border-top: 1px solid var(--line); padding-top: 5px; } .fittedwrap { border-top: 1px solid var(--line); padding-top: 5px; }
.flabel { font: 10.5px var(--head); letter-spacing: .12em; text-transform: uppercase; color: var(--dim); margin-bottom: 4px; } .flabel { font: 10px var(--head); letter-spacing: .12em; text-transform: uppercase; color: var(--dim); margin-bottom: 3px; }
.fitted { display: grid; grid-template-columns: repeat(8, 1fr); gap: 4px; } .fitted { display: grid; grid-template-columns: repeat(8, 1fr); gap: 4px; }
.fitted .frow { display: flex; flex-direction: column; align-items: center; gap: 1px; background: rgba(8,10,14,.75); .fitted .frow { display: flex; flex-direction: column; align-items: center; gap: 1px; background: rgba(8,10,14,.75);
border: 1px solid #262c36; border-radius: var(--r1); padding: 3px 3px 2px; font-size: 11.5px; cursor: pointer; border: 1px solid #262c36; border-radius: var(--r1); padding: 2px 3px; font-size: 11px; cursor: pointer;
position: relative; min-width: 0; box-shadow: none; } position: relative; min-width: 0; box-shadow: none; }
@media (hover: hover) { .fitted .frow:hover { border-color: var(--accent); } } @media (hover: hover) { .fitted .frow:hover { border-color: var(--accent); } }
.fitted .frow .pic { width: 18px; height: 18px; font-size: 14px; } .fitted .frow .pic { width: 16px; height: 16px; font-size: 13px; }
.fitted .frow .fn { width: 100%; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .fitted .frow .fn { width: 100%; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.fitted .frow .fn.empty { color: var(--dim); } .fitted .frow .fn.empty { color: var(--dim); }
.fitted .frow .frm { position: absolute; top: -5px; right: -4px; font-size: 11px; color: #fff; background: var(--warn); .fitted .frow .frm { position: absolute; top: -5px; right: -4px; font-size: 11px; color: #fff; background: var(--warn);
@@ -253,46 +273,90 @@
/* category tabs: a strip of folder tabs sitting ON the card panel - clearly navigation, not parts */ /* category tabs: a strip of folder tabs sitting ON the card panel - clearly navigation, not parts */
.tabs { display: grid; grid-template-columns: repeat(8, 1fr); gap: 3px; border-bottom: 2px solid var(--line); } .tabs { display: grid; grid-template-columns: repeat(8, 1fr); gap: 3px; border-bottom: 2px solid var(--line); }
.tab { background: #141922; border: 1px solid var(--line); border-bottom: none; .tab { background: #141922; border: 1px solid var(--line); border-bottom: none;
border-radius: var(--r2) var(--r2) 0 0; margin-bottom: -2px; padding: 3px 2px 5px; border-radius: var(--r2) var(--r2) 0 0; margin-bottom: -2px; padding: 2px 2px 4px;
display: flex; flex-direction: column; align-items: center; gap: 1px; cursor: pointer; display: flex; flex-direction: column; align-items: center; gap: 0; cursor: pointer;
font-size: 11.5px; letter-spacing: .02em; color: var(--dim); } font-size: 10.5px; letter-spacing: .02em; color: var(--dim); }
.tab .pic { width: 24px; height: 24px; font-size: 19px; } .tab .pic { width: 20px; height: 20px; font-size: 16px; }
@media (hover: hover) { .tab:hover { border-color: var(--accent); } } @media (hover: hover) { .tab:hover { border-color: var(--accent); } }
.tab.on { background: linear-gradient(#3a2414, #1d1410); border-color: var(--accent); color: var(--accent); .tab.on { background: linear-gradient(#3a2414, #1d1410); border-color: var(--accent); color: var(--accent);
font-weight: 700; border-bottom: 2px solid #1d1410; } /* open tab merges into the panel below */ font-weight: 700; border-bottom: 2px solid #1d1410; } /* open tab merges into the panel below */
.tab.miss { border-color: var(--warn); } .tab.miss { border-color: var(--warn); }
#cards { flex: 1; min-height: 0; overflow-y: auto; display: grid; grid-template-columns: repeat(7, 1fr); gap: 6px; #designer { background: var(--panel2); background-image: var(--sheen); border: 1px solid var(--line);
align-content: start; padding: 9px; background: rgba(0,0,0,.26); border: 1px solid var(--line); border-top: none; border-left: 3px solid var(--accent); border-radius: var(--r2); box-shadow: var(--hl); padding: 5px 10px; }
#designer.hide { display: none; }
#designer.shut { padding: 3px 10px; }
#designer .dh { display: flex; align-items: center; gap: 8px; font: 11px var(--head); letter-spacing: .05em;
text-transform: uppercase; color: var(--accent); }
#designer.open .dh { margin-bottom: 3px; }
#designer .dh .dtitle { cursor: pointer; display: flex; align-items: center; gap: 6px; flex: 1; user-select: none; }
#designer .dh .dtitle .caret { font-size: 9px; opacity: .8; }
#designer .dh button { padding: 2px 9px; font-size: 11px; min-height: 0; }
#designer .drow { display: grid; grid-template-columns: 48px 1fr 34px; gap: 8px; align-items: center; font-size: 11px; margin: 2px 0; }
#designer .drow input[type=range] { width: 100%; accent-color: var(--accent); height: 20px; }
#designer .drow .dv { text-align: right; color: var(--dim); font-variant-numeric: tabular-nums; }
#cards { flex: 1; min-height: 0; overflow-y: auto; display: grid; grid-template-columns: repeat(8, 1fr); gap: 5px;
align-content: start; padding: 7px; background: rgba(0,0,0,.26); border: 1px solid var(--line); border-top: none;
border-radius: 0 0 var(--r2) var(--r2); } border-radius: 0 0 var(--r2) var(--r2); }
.item { background: linear-gradient(#252b37, #171b23); border: 1px solid #39414f; border-radius: var(--r2); .item { background: linear-gradient(#252b37, #171b23); border: 1px solid #39414f; border-radius: var(--r2);
padding: 5px 5px 4px; cursor: pointer; text-align: center; position: relative; padding: 4px 4px 3px; cursor: pointer; text-align: center; position: relative;
box-shadow: var(--hl), 0 2px 0 rgba(0,0,0,.45); } box-shadow: var(--hl), 0 2px 0 rgba(0,0,0,.45); }
@media (hover: hover) { .item:hover { border-color: #5a6478; } } @media (hover: hover) { .item:hover { border-color: #5a6478; } }
.item.sel { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,122,26,.3); } .item.sel { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,122,26,.3); }
.item > .pic { width: 100%; height: 52px; font-size: 38px; } .item > .pic { width: 100%; height: 40px; font-size: 30px; }
.item .nm { font-size: 12px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .item .nm { font-size: 11px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item .pr { font-size: 12px; color: var(--gold); display: flex; gap: 3px; justify-content: center; align-items: center; .item .pr { font-size: 11px; color: var(--gold); display: flex; gap: 3px; justify-content: center; align-items: center;
font-variant-numeric: tabular-nums; background: rgba(0,0,0,.3); border-radius: var(--r1); padding: 0 4px; margin: 2px auto 0; width: fit-content; } font-variant-numeric: tabular-nums; background: rgba(0,0,0,.3); border-radius: var(--r1); padding: 0 4px; margin: 2px auto 0; width: fit-content; }
.item .pr .pic { width: 14px; height: 14px; } .item .pr .pic { width: 14px; height: 14px; }
.item .pr.no { color: var(--warn); } .item .pr.no { color: var(--warn); }
.item .badge { position: absolute; top: 5px; left: 5px; font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 6px; background: var(--accent); color: #1a0c02; } .item .badge { position: absolute; top: 5px; left: 5px; font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 6px; background: var(--accent); color: #1a0c02; }
.item .badge.own { background: #3c4556; color: var(--text); } .item .badge.own { background: #3c4556; color: var(--text); }
#detail { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; display: grid; grid-template-columns: 76px 1fr auto; gap: 10px; align-items: center; min-height: 86px; } #detail { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 6px 9px; display: grid; grid-template-columns: 46px 1fr auto; gap: 9px; align-items: center; min-height: 56px; }
#detail > .pic { width: 76px; height: 76px; font-size: 52px; } #detail > .pic { width: 46px; height: 46px; font-size: 32px; }
#detail .nm { font: 17px var(--head); letter-spacing: .03em; } #detail .nm { font: 15px var(--head); letter-spacing: .03em; }
#detail .ds { font-size: 12.5px; color: var(--dim); margin: 2px 0 5px; } #detail .ds { font-size: 11.5px; color: var(--dim); margin: 1px 0 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.chips { display: flex; flex-wrap: wrap; gap: 4px; } .chips { display: flex; flex-wrap: wrap; gap: 3px; }
.chips span { background: #0f1218; border: 1px solid var(--line); border-radius: 6px; padding: 1px 6px; font-size: 11.5px; display: inline-flex; gap: 3px; align-items: center; font-variant-numeric: tabular-nums; } .chips span { background: #0f1218; border: 1px solid var(--line); border-radius: 6px; padding: 1px 5px; font-size: 11px; display: inline-flex; gap: 3px; align-items: center; font-variant-numeric: tabular-nums; }
.chips span .pic { width: 13px; height: 13px; font-size: 11px; } .chips span .pic { width: 12px; height: 12px; font-size: 10px; }
.chips span.up { color: var(--good); border-color: #2e5a3e; } .chips span.down { color: var(--warn); border-color: #5a2e2e; } .chips span.up { color: var(--good); border-color: #2e5a3e; } .chips span.down { color: var(--warn); border-color: #5a2e2e; }
.chips span.key { color: var(--accent); border-color: #5a3a18; background: #1d1409; font-weight: 700; } .chips span.key { color: var(--accent); border-color: #5a3a18; background: #1d1409; font-weight: 700; }
#detail .act { display: flex; flex-direction: column; gap: 6px; min-width: 120px; } #detail .act { display: flex; flex-direction: column; gap: 5px; min-width: 116px; }
#detail .act button { padding: 8px 10px; min-height: 40px; } #detail .act button { padding: 7px 10px; min-height: 36px; }
#detail .act .primary { min-height: 44px; font-size: 15px; } #detail .act .primary { min-height: 42px; font-size: 14px; }
.gbar { display: flex; gap: 6px; align-items: center; } .gbar { display: flex; gap: 6px; align-items: center; }
.gbar .err { flex: 1; margin: 0; font-size: 12px; text-align: left; } .gbar .err { flex: 1; margin: 0; font-size: 12px; text-align: left; }
.gbar .primary { padding: 9px 26px; } .gbar .primary { padding: 9px 26px; }
#hud .rank { font-size: 11.5px; color: var(--dim); letter-spacing: .02em; }
.htour { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700;
font-size: 13px; animation: tourpulse 1.6s ease-in-out infinite; }
@keyframes tourpulse { 50% { box-shadow: 0 0 0 3px rgba(255,122,26,.35); } }
.htour.hide { display: none; }
/* backend news + running event */
.motd { margin: 6px 0 0; font-size: 13px; color: #c9cfdc; text-shadow: 0 2px 4px #000; }
.evbar { display: inline-flex; align-items: center; gap: 8px; margin: 6px 0 0; padding: 5px 10px;
background: rgba(255,122,26,.16); border: 1px solid var(--accent); border-radius: var(--r2);
font-size: 13px; text-align: left; }
.evbar b { font: 13px var(--head); letter-spacing: .04em; color: var(--accent); }
.chip.clickable { cursor: pointer; }
@media (hover: hover) { .chip.clickable:hover { border-color: var(--accent); } }
/* achievements */
.achwon { margin: 10px auto 0; max-width: 340px; text-align: left; font-size: 13px;
background: rgba(255,122,26,.1); border: 1px solid var(--accent); border-radius: var(--r2); padding: 8px 10px; }
.achwon b { display: block; margin-bottom: 4px; color: var(--accent); font: 13px var(--head); letter-spacing: .04em; }
.achwon div { display: flex; justify-content: space-between; gap: 10px; }
.rankbar { margin: 4px 0 12px; }
.rankbar .rt { display: flex; justify-content: space-between; align-items: baseline; font-size: 13px; margin-bottom: 4px; }
.rankbar .rt b { font: 17px var(--head); color: var(--accent); letter-spacing: .03em; }
.achlist { display: grid; grid-template-columns: 1fr 1fr; gap: 6px; text-align: left; }
.achrow { display: grid; grid-template-columns: 24px 1fr auto; gap: 8px; align-items: center; font-size: 12.5px;
background: var(--panel2); background-image: var(--sheen); border: 1px solid var(--line);
border-radius: var(--r2); padding: 6px 9px; box-shadow: var(--hl); }
.achrow.done { border-color: var(--good); }
.achrow.todo { opacity: .55; }
.achrow .an { font-weight: 700; }
.achrow .ad { font-size: 11.5px; color: var(--dim); font-weight: 400; }
.achrow .am { font-size: 16px; text-align: center; }
/* paint tab: proper colour chips instead of tiny dots */ /* paint tab: proper colour chips instead of tiny dots */
#paintView { gap: 10px; } #paintView { gap: 10px; }
.psec h4 { margin: 0 0 6px; font: 12px var(--head); letter-spacing: .1em; text-transform: uppercase; color: var(--dim); } .psec h4 { margin: 0 0 6px; font: 12px var(--head); letter-spacing: .1em; text-transform: uppercase; color: var(--dim); }
@@ -452,6 +516,23 @@
#dmgvig { position: absolute; inset: 0; z-index: 3; pointer-events: none; opacity: 0; transition: opacity .25s; #dmgvig { position: absolute; inset: 0; z-index: 3; pointer-events: none; opacity: 0; transition: opacity .25s;
background: radial-gradient(ellipse at 50% 50%, transparent 45%, rgba(190,20,10,.75) 100%); } background: radial-gradient(ellipse at 50% 50%, transparent 45%, rgba(190,20,10,.75) 100%); }
/* spawn gate: two steel garage-door halves that split open when a fight starts */
#gate { position: absolute; inset: 0; z-index: 8; pointer-events: none; overflow: hidden; }
#gate.hide { display: none; }
#gate .gh { position: absolute; left: 0; right: 0; height: 50%;
background:
radial-gradient(circle at 14px 14px, rgba(255,255,255,.12) 0 2px, transparent 3px),
repeating-linear-gradient(180deg, rgba(0,0,0,.35) 0 2px, transparent 2px 26px),
linear-gradient(90deg, #22272f 0%, #3c4452 48%, #434b59 52%, #22272f 100%);
background-size: 28px 28px, auto, auto;
box-shadow: inset 0 0 70px rgba(0,0,0,.65);
transition: transform .85s cubic-bezier(.55,.03,.3,1); will-change: transform; }
#gate .gh-top { top: 0; } #gate .gh-bot { bottom: 0; }
#gate .gh::after { content: ''; position: absolute; left: 0; right: 0; height: 11px; background: var(--hazard); opacity: .95; }
#gate .gh-top::after { bottom: 0; } #gate .gh-bot::after { top: 0; }
#gate.open .gh-top { transform: translateY(-100%); }
#gate.open .gh-bot { transform: translateY(100%); }
/* touch pad: only on touch screens */ /* touch pad: only on touch screens */
#pad { position: absolute; left: 14px; right: 14px; bottom: 14px; display: none; justify-content: space-between; pointer-events: none; z-index: 5; } #pad { position: absolute; left: 14px; right: 14px; bottom: 14px; display: none; justify-content: space-between; pointer-events: none; z-index: 5; }
#pad > div { display: grid; grid-template-columns: repeat(3, 60px); gap: 6px; pointer-events: auto; } #pad > div { display: grid; grid-template-columns: repeat(3, 60px); gap: 6px; pointer-events: auto; }
@@ -504,6 +585,7 @@
<div class="tabs" id="tabs"></div> <div class="tabs" id="tabs"></div>
<div id="cards"></div> <div id="cards"></div>
<div id="detail"></div> <div id="detail"></div>
<div id="designer" class="hide"></div>
<div class="fittedwrap"><div class="flabel" data-i18n="fitted_parts">Fitted</div><div id="fitted" class="fitted"></div></div> <div class="fittedwrap"><div class="flabel" data-i18n="fitted_parts">Fitted</div><div id="fitted" class="fitted"></div></div>
</div> </div>
<div id="paintView" class="hide"> <div id="paintView" class="hide">
@@ -520,9 +602,9 @@
<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="bGMode">Kampagne</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">League</button>
</div> </div>
</div> </div>
</div> </div>
@@ -548,14 +630,16 @@
<div id="hud"> <div id="hud">
<div class="logo">ROBOT CLASH</div> <div class="logo">ROBOT CLASH</div>
<div class="chip" data-i18n-title="hud_money"><span class="pic" data-f="🪙" id="icoMoney"></span><b id="hMoney">0</b></div> <div class="chip" data-i18n-title="hud_money"><span class="pic" data-f="🪙" id="icoMoney"></span><b id="hMoney">0</b></div>
<div class="chip" data-i18n-title="hud_fame"><span class="pic" data-f="⭐" id="icoFame"></span><b id="hFame">0</b></div> <div class="chip clickable" id="chipFame" data-i18n-title="achievements"><span class="pic" data-f="⭐" id="icoFame"></span><b id="hFame">0</b><span id="hRank" class="rank"></span></div>
<div class="chip"><span data-i18n="hud_league">League</span> <b id="hLeague">-</b></div> <div class="chip"><span id="hModeLbl">League</span> <b id="hLeague">-</b></div>
<button id="hTour" class="chip clickable htour hide">🏆</button>
<div class="grow"></div> <div class="grow"></div>
<div class="chip" id="hUser" data-i18n-title="account"></div> <div class="chip" id="hUser" data-i18n-title="account"></div>
<button id="bSettings" class="icobtn" data-i18n-title="settings">⚙</button> <button id="bSettings" class="icobtn" data-i18n-title="settings">⚙</button>
<button id="bMute" class="icobtn" title="M">🔊</button> <button id="bMute" class="icobtn" title="M">🔊</button>
<button id="bPause" class="icobtn" title="P / Esc" data-i18n-title="pause">⏸</button> <button id="bPause" class="icobtn" title="P / Esc" data-i18n-title="pause">⏸</button>
</div> </div>
<div id="gate" class="hide"><div class="gh gh-top"></div><div class="gh gh-bot"></div></div>
<div id="overlay" class="hide"></div> <div id="overlay" class="hide"></div>
</div> </div>
</div> </div>
@@ -571,6 +655,10 @@
<script src="kit/kit-i18n.js"></script> <script src="kit/kit-i18n.js"></script>
<script src="lang.js"></script> <script src="lang.js"></script>
<script src="parts.js"></script> <script src="parts.js"></script>
<script src="progress.js"></script>
<script src="live.js"></script>
<script src="ltourney.js"></script>
<script src="tourney.js"></script>
<script src="robot.js"></script> <script src="robot.js"></script>
<script src="combat.js"></script> <script src="combat.js"></script>
<script src="ai.js"></script> <script src="ai.js"></script>
@@ -580,6 +668,7 @@
<script src="looks.js"></script> <script src="looks.js"></script>
<script src="render3d.js"></script> <script src="render3d.js"></script>
<script src="netfight.js"></script> <script src="netfight.js"></script>
<script src="netourney.js"></script>
<script src="shop.js"></script> <script src="shop.js"></script>
<script src="painter.js"></script> <script src="painter.js"></script>
<script src="uicheck.js"></script> <script src="uicheck.js"></script>

View File

@@ -9,6 +9,34 @@ window.LANG = {
league_chip: 'S{s} · {n}/{m}', league_chip: 'S{s} · {n}/{m}',
sound_on: 'Sound on', sound_off: 'Sound off', pause: 'Pause', sound_on: 'Sound on', sound_off: 'Sound off', pause: 'Pause',
win_min: 'Minimise', win_full: 'Fullscreen (F11)', win_close: 'Close', win_min: 'Minimise', win_full: 'Fullscreen (F11)', win_close: 'Close',
event: 'Event', event_running: 'Event running', event_prize: 'prize money x{n}', event_bonus: 'Event bonus', tour_free: 'Tournament (free)', tour_join: 'Join tournament ({n})', tour_join_free: 'Join tournament (free)',
reload_now: 'Reload', reload_skip: 'Play anyway',
reload_title: 'New version', reload_text: 'A newer version of Robot Clash is online. Please reload the page (Ctrl+F5).',
cls_light: 'Lightweight', cls_medium: 'Middleweight', cls_heavy: 'Heavyweight',
tournament: 'Tournament', tour_enter: 'Tournament ({n})', tour_continue: 'Tournament', tour_fight: 'Fight',
tour_round_quarter: 'Quarter final', tour_round_semi: 'Semi final', tour_round_final: 'Final',
tour_left: '{n} robots left', tour_beat: 'beat', title_campaign: 'Campaign', title_online: 'Online', ltour_title: 'Live Tournament', ltour_ready: 'ready', ltour_waiting: 'not ready', ltour_setready: "I'm ready", ltour_unready: 'Not ready', ltour_empty: 'No one here yet - invite a friend!', ltour_lobby: '{n} ready (2 needed to start)', ltour_countdown: 'Starts in {n} s...', ltour_wait_round: 'Waiting for the other matches...', ai_tag: 'AI', tour_champion: 'Champion', tour_your_match: 'your match: {name}', tour_round_prize: 'Round prize', tour_trophy: 'Trophy',
tour_won: 'Tournament won!', tour_won_text: 'The whole bracket, beaten. Prize money: {n}.',
tour_out: 'Knocked out', tour_out_text: 'That is the end of the run. You take {n} with you.',
ach_tourney: 'Bracket Buster', achd_tourney: 'Win a tournament',
achievements: 'Achievements', ach_new: 'Unlocked', ach_done: '{n} of {m} done',
rank_next: 'to {n}: {f} fame', rank_top: 'top rank reached',
rank_scrap: 'Scrap Hauler', rank_rookie: 'Rookie', rank_contender: 'Contender', rank_pro: 'Pro',
rank_veteran: 'Veteran', rank_champion: 'Champion', rank_master: 'Master', rank_legend: 'Legend',
ach_first_win: 'First Blood', achd_first_win: 'Win a fight',
ach_ko: 'Lights Out', achd_ko: 'Win by knockout',
ach_pit: 'Down You Go', achd_pit: 'Push someone into the pit',
ach_tough: 'On The Ropes', achd_tough: 'Win with under 15% health left',
ach_flawless: 'Not A Scratch', achd_flawless: 'Win above 90% health, nothing broken off',
ach_demolition: 'Demolition', achd_demolition: 'Deal 600 damage in one fight',
ach_champion: 'Season Champion', achd_champion: 'Beat the whole league',
ach_veteran: 'Old Hand', achd_veteran: 'Fight 25 matches',
ach_rich: 'Loaded', achd_rich: 'Hold 5,000 credits',
ach_collector: 'Collector', achd_collector: 'Own 20 parts',
ach_garage: 'Full Garage', achd_garage: 'Keep 3 robots',
ach_artist: 'Own Colours', achd_artist: 'Paint your own design',
mode_online: 'Online', mode_campaign: 'Campaign', mode_pvp: 'vs. players', to_lobby: 'Lobby',
mode_switched: 'Separate game - own money and parts',
click_start: 'Click or press any key to start', click_start: 'Click or press any key to start',
tut_title: 'Quick start', tut_next: 'Next', tut_skip: 'Skip', tut_go: "Let's build", tut_title: 'Quick start', tut_next: 'Next', tut_skip: 'Skip', tut_go: "Let's build",
tut_1: 'Every robot needs four parts: chassis, motor, wheels and a battery. You pick them under Parts.', tut_1: 'Every robot needs four parts: chassis, motor, wheels and a battery. You pick them under Parts.',
@@ -50,6 +78,9 @@ window.LANG = {
pd_hornet: 'Faster all-rounder.', pd_hornet: 'Faster all-rounder.',
pd_bulldog: 'Huge torque for pushing.', pd_bulldog: 'Huge torque for pushing.',
pd_comet: 'Top speed for hit and run.', pd_comet: 'Top speed for hit and run.',
pd_pico: 'Tiny cheap motor - weak but featherlight, good for a lightweight.',
pd_turbine: 'A solid all-round motor, decent push and speed.',
pd_titandrive: 'Monster torque to shove the heaviest builds, but slow and heavy.',
pd_rubber: 'Four small wheels, nimble.', pd_rubber: 'Four small wheels, nimble.',
pd_cage: 'Open scrap frame: dirt cheap and light, but it dents fast.', pd_cage: 'Open scrap frame: dirt cheap and light, but it dents fast.',
pd_hexpod: 'Six-sided shell, angled all round so hits glance off.', pd_hexpod: 'Six-sided shell, angled all round so hits glance off.',
@@ -57,6 +88,9 @@ window.LANG = {
pd_fang: 'Long pointed prow, low and quick - hard to flip.', pd_fang: 'Long pointed prow, low and quick - hard to flip.',
pd_plough: 'Heavy plough blade bolted to the nose, shrugs off front hits.', pd_plough: 'Heavy plough blade bolted to the nose, shrugs off front hits.',
pd_discus: 'Wide flat disc, sits low and takes a beating.', pd_discus: 'Wide flat disc, sits low and takes a beating.',
pd_orb: 'Round armoured ball - hits glance off from every side.',
pd_tower: 'Tall upright build - towers over rivals, but tips easily.',
pd_slab: 'Very wide and flat - almost impossible to flip over.',
pd_omni: 'Caster wheels: spins on the spot, great steering.', pd_omni: 'Caster wheels: spins on the spot, great steering.',
pd_bigtyre: 'Taller than the robot: keeps driving when flipped.', pd_bigtyre: 'Taller than the robot: keeps driving when flipped.',
pd_studs: 'Studded grip, drives upside down, strong shove.', pd_studs: 'Studded grip, drives upside down, strong shove.',
@@ -193,9 +227,9 @@ window.LANG = {
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', s_cam: 'Camera', cam_iso: 'Arena', cam_chase: 'Chase', cam_fpv: 'Cockpit', key_cam: 'switch camera',
// easier play + income // 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_steer: 'Steering', steer_simple: 'Simple', steer_tank: 'Tank',
s_autofire: 'Weapon helper', s_autofire: 'Weapon helper', s_quiet: 'Quiet mode',
s_body: 'Shape', des_height: 'Height', des_width: 'Width', des_length: 'Length', des_reset: 'Reset',
fight_hint_simple: 'W A S D: drive in that direction · Space weapon · Shift / E tower · C camera · P pause', 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_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_note: 'Exhibition fight: half prize money, no league progress.',
@@ -224,6 +258,34 @@ window.LANG = {
league_chip: 'S{s} · {n}/{m}', league_chip: 'S{s} · {n}/{m}',
sound_on: 'Sound an', sound_off: 'Sound aus', pause: 'Pause', sound_on: 'Sound an', sound_off: 'Sound aus', pause: 'Pause',
win_min: 'Minimieren', win_full: 'Vollbild (F11)', win_close: 'Schließen', win_min: 'Minimieren', win_full: 'Vollbild (F11)', win_close: 'Schließen',
event: 'Event', event_running: 'Event läuft', event_prize: 'Preisgeld x{n}', event_bonus: 'Event-Bonus', tour_free: 'Turnier (gratis)', tour_join: 'Turnier beitreten ({n})', tour_join_free: 'Turnier beitreten (gratis)',
reload_now: 'Neu laden', reload_skip: 'Trotzdem spielen',
reload_title: 'Neue Version', reload_text: 'Es gibt eine neuere Fassung von Robot Clash. Bitte die Seite neu laden (Strg+F5).',
cls_light: 'Leichtgewicht', cls_medium: 'Mittelgewicht', cls_heavy: 'Schwergewicht',
tournament: 'Turnier', tour_enter: 'Turnier ({n})', tour_continue: 'Turnier', tour_fight: 'Kämpfen',
tour_round_quarter: 'Viertelfinale', tour_round_semi: 'Halbfinale', tour_round_final: 'Finale',
tour_left: 'noch {n} Roboter', tour_beat: 'schlägt', title_campaign: 'Kampagne', title_online: 'Online', ltour_title: 'Live-Turnier', ltour_ready: 'bereit', ltour_waiting: 'nicht bereit', ltour_setready: 'Ich bin bereit', ltour_unready: 'Doch nicht', ltour_empty: 'Noch niemand da - lad einen Freund ein!', ltour_lobby: '{n} bereit (2 zum Start noetig)', ltour_countdown: 'Start in {n} s...', ltour_wait_round: 'Warte auf die anderen Kaempfe...', ai_tag: 'KI', tour_champion: 'Sieger', tour_your_match: 'dein Kampf: {name}', tour_round_prize: 'Rundenpreis', tour_trophy: 'Pokal',
tour_won: 'Turnier gewonnen!', tour_won_text: 'Das ganze Feld besiegt. Preisgeld: {n}.',
tour_out: 'Ausgeschieden', tour_out_text: 'Hier ist Schluss. {n} nimmst du mit.',
ach_tourney: 'Turniersieger', achd_tourney: 'Gewinne ein Turnier',
achievements: 'Erfolge', ach_new: 'Freigeschaltet', ach_done: '{n} von {m} geschafft',
rank_next: 'bis {n}: {f} Ruhm', rank_top: 'höchster Rang erreicht',
rank_scrap: 'Schrottsammler', rank_rookie: 'Neuling', rank_contender: 'Herausforderer', rank_pro: 'Profi',
rank_veteran: 'Veteran', rank_champion: 'Champion', rank_master: 'Meister', rank_legend: 'Legende',
ach_first_win: 'Erster Sieg', achd_first_win: 'Gewinne einen Kampf',
ach_ko: 'Licht aus', achd_ko: 'Gewinne durch K.o.',
ach_pit: 'Ab in die Grube', achd_pit: 'Schieb jemanden in die Grube',
ach_tough: 'Zäher Hund', achd_tough: 'Gewinne mit unter 15% Leben',
ach_flawless: 'Kein Kratzer', achd_flawless: 'Gewinne über 90% Leben, nichts abgerissen',
ach_demolition: 'Abrissbirne', achd_demolition: 'Mach 600 Schaden in einem Kampf',
ach_champion: 'Saisonmeister', achd_champion: 'Besiege die ganze Liga',
ach_veteran: 'Alter Hase', achd_veteran: 'Bestreite 25 Kämpfe',
ach_rich: 'Gut betucht', achd_rich: 'Besitze 5.000 Credits',
ach_collector: 'Sammler', achd_collector: 'Besitze 20 Teile',
ach_garage: 'Volle Halle', achd_garage: 'Halte 3 Roboter',
ach_artist: 'Eigene Farben', achd_artist: 'Male ein eigenes Design',
mode_online: 'Online', mode_campaign: 'Kampagne', mode_pvp: 'gegen Spieler', to_lobby: 'Lobby',
mode_switched: 'Eigenes Spiel – eigenes Geld und eigene Teile',
click_start: 'Klicken oder Taste drücken zum Starten', click_start: 'Klicken oder Taste drücken zum Starten',
tut_title: 'Kurzanleitung', tut_next: 'Weiter', tut_skip: 'Überspringen', tut_go: 'Los bauen', tut_title: 'Kurzanleitung', tut_next: 'Weiter', tut_skip: 'Überspringen', tut_go: 'Los bauen',
tut_1: 'Jeder Roboter braucht vier Teile: Chassis, Motor, Räder und Batterie. Die wählst du unter „Teile".', tut_1: 'Jeder Roboter braucht vier Teile: Chassis, Motor, Räder und Batterie. Die wählst du unter „Teile".',
@@ -265,6 +327,9 @@ window.LANG = {
pd_hornet: 'Schnellerer Allrounder.', pd_hornet: 'Schnellerer Allrounder.',
pd_bulldog: 'Riesiges Drehmoment zum Schieben.', pd_bulldog: 'Riesiges Drehmoment zum Schieben.',
pd_comet: 'Höchsttempo für Angriff und Rückzug.', pd_comet: 'Höchsttempo für Angriff und Rückzug.',
pd_pico: 'Winziger Billigmotor – schwach, aber federleicht, gut fürs Leichtgewicht.',
pd_turbine: 'Solider Allround-Motor, ordentlich Schub und Tempo.',
pd_titandrive: 'Monster-Drehmoment für die schwersten Bauten, aber langsam und schwer.',
pd_rubber: 'Vier kleine Räder, wendig.', pd_rubber: 'Vier kleine Räder, wendig.',
pd_cage: 'Offener Schrottrahmen: spottbillig und leicht, aber schnell verbeult.', pd_cage: 'Offener Schrottrahmen: spottbillig und leicht, aber schnell verbeult.',
pd_hexpod: 'Sechseckige Schale, rundum abgeschrägt – Treffer rutschen ab.', pd_hexpod: 'Sechseckige Schale, rundum abgeschrägt – Treffer rutschen ab.',
@@ -272,6 +337,9 @@ window.LANG = {
pd_fang: 'Lange Spitze vorn, flach und flink – schwer umzuwerfen.', pd_fang: 'Lange Spitze vorn, flach und flink – schwer umzuwerfen.',
pd_plough: 'Schweres Räumschild an der Nase, steckt Fronttreffer weg.', pd_plough: 'Schweres Räumschild an der Nase, steckt Fronttreffer weg.',
pd_discus: 'Breite flache Scheibe, liegt tief und hält viel aus.', pd_discus: 'Breite flache Scheibe, liegt tief und hält viel aus.',
pd_orb: 'Runde Panzerkugel – Treffer rutschen von allen Seiten ab.',
pd_tower: 'Hoher, aufrechter Bau – überragt alle, kippt aber leicht.',
pd_slab: 'Sehr breit und flach – kaum umzuwerfen.',
pd_omni: 'Lenkrollen: dreht auf der Stelle, top Lenkung.', pd_omni: 'Lenkrollen: dreht auf der Stelle, top Lenkung.',
pd_bigtyre: 'Höher als der Roboter: fährt auch umgedreht weiter.', pd_bigtyre: 'Höher als der Roboter: fährt auch umgedreht weiter.',
pd_studs: 'Spike-Grip, fährt auch umgedreht, starkes Schieben.', pd_studs: 'Spike-Grip, fährt auch umgedreht, starkes Schieben.',
@@ -408,9 +476,9 @@ window.LANG = {
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', s_cam: 'Kamera', cam_iso: 'Arena', cam_chase: 'Verfolger', cam_fpv: 'Cockpit', key_cam: 'Kamera wechseln',
// easier play + income // 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_steer: 'Steuerung', steer_simple: 'Einfach', steer_tank: 'Panzer',
s_autofire: 'Waffen-Hilfe', s_autofire: 'Waffen-Hilfe', s_quiet: 'Leiser Modus',
s_body: 'Form', des_height: 'Höhe', des_width: 'Breite', des_length: 'Länge', des_reset: 'Zurücksetzen',
fight_hint_simple: 'W A S D: in diese Richtung fahren · Leertaste Waffe · Shift / E Turm · C Kamera · P Pause', 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_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_note: 'Schaukampf: halbes Preisgeld, kein Liga-Fortschritt.',

85
game/live.js Normal file
View File

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

93
game/ltourney.js Normal file
View File

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

121
game/netourney.js Normal file
View File

@@ -0,0 +1,121 @@
/* Robot Clash - live multiplayer tournament over Firebase (needs net.js + ltourney.js).
Players register, tick "ready", a 30 s countdown starts once >=2 are ready, then the bracket is
frozen and each pairing is played as a normal live PvP match (game.js supplies startMatch).
No server: the bracket is computed the same way on every client from the frozen list + seed
(RC.LTourney), results are shared through /tourney/results, a missing opponent is a walkover.
const T = RC.NetTourney(net, { uid, name, flag }, {
onView(v){} // v = { phase, players, readyCount, countdown, order, results, me:{match,champion,out} }
startMatch(info){} // info = { id, host, seed, opp:{uid,name,build,paint,flag} } -> game starts the fight
});
T.join(build, paint) / T.leave() / T.setReady(bool) / T.tick(dt) / T.reportWin(round, pair, uid)
T.close()
/tourney in Firebase:
reg/<uid> = { name, flag, build, paint, ready, ts } (each writes only their own)
meta = { phase:'open'|'countdown'|'running'|'done', startAt, seed, frozen:[uid...] }
results/<round>/<pair> = winnerUid */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const COUNTDOWN = 30000, WALKOVER = 60000, STALE = 15000;
RC.NetTourney = function (net, me, opt) {
const db = net.db, cb = opt || {};
let reg = {}, meta = {}, results = {};
let inMatch = false, roundStart = 0, lastRound = -1, wroteRun = false, wroteCount = false;
const subs = [];
subs.push(db.stream('tourney/reg', v => { reg = v || {}; emit(); }));
subs.push(db.stream('tourney/meta', v => { meta = v || {}; emit(); }));
subs.push(db.stream('tourney/results', v => { results = v || {}; emit(); }));
const now = () => Date.now();
const readyUids = () => Object.keys(reg).filter(u => reg[u] && reg[u].ready && now() - (reg[u].ts || 0) < STALE * 3);
const frozen = () => (meta.frozen && meta.frozen.length ? meta.frozen : null);
function view() {
const phase = meta.phase || 'open';
const players = Object.keys(reg).map(u => ({ uid: u, name: reg[u].name, flag: reg[u].flag, ready: !!reg[u].ready, me: u === me.uid }));
const v = { phase, players, readyCount: readyUids().length, countdown: null, order: null, results: results, me: {} };
if (phase === 'countdown' && meta.startAt) v.countdown = Math.max(0, Math.ceil((meta.startAt - now()) / 1000));
const fr = frozen();
if (fr && (phase === 'running' || phase === 'done')) {
const ord = RC.LTourney.order(fr, meta.seed || 1);
v.order = ord;
const m = RC.LTourney.myMatch(ord, results, me.uid);
if (!m) v.me.out = true;
else if (m.done) v.me.champion = m.champion;
else v.me.match = m;
}
return v;
}
function emit() { if (cb.onView) cb.onView(view()); drive(); }
// my own registration row (heartbeat keeps it fresh)
let myRow = null;
function writeRow() {
if (!myRow) return;
db.put('tourney/reg/' + me.uid, Object.assign({ ts: now() }, myRow));
}
function join(build, paint) {
myRow = { name: me.name, flag: me.flag || 'XX', ready: false, build: build, paint: paint };
writeRow();
}
function leave() { myRow = null; db.del('tourney/reg/' + me.uid); }
function setReady(on) { if (myRow) { myRow.ready = !!on; writeRow(); } }
// state machine - every client runs it, writes are guarded so the first one wins
function drive() {
const phase = meta.phase || 'open';
if (phase === 'open' && readyUids().length >= 2 && !wroteCount) {
wroteCount = true;
db.patch('tourney/meta', { phase: 'countdown', startAt: now() + COUNTDOWN, seed: (Math.random() * 1e9) | 0 });
}
if (phase === 'countdown') {
wroteCount = true;
if (meta.startAt && now() >= meta.startAt && !wroteRun) {
wroteRun = true;
db.patch('tourney/meta', { phase: 'running', frozen: readyUids().sort() });
}
}
if (phase === 'running') {
const fr = frozen(); if (!fr) return;
const ord = RC.LTourney.order(fr, meta.seed || 1);
const m = RC.LTourney.myMatch(ord, results, me.uid);
if (!m || m.done) { if (m && m.done && !meta.doneWrote) db.patch('tourney/meta', { phase: 'done' }); return; }
if (m.round !== lastRound) { lastRound = m.round; roundStart = now(); }
if (m.opp == null) return; // bye: bracket advances by itself
if (inMatch) return;
// opponent gone / never there -> walkover after the timer
const oppReg = reg[m.opp];
const oppGone = !oppReg || now() - (oppReg.ts || 0) > STALE;
if (oppGone && now() - roundStart > WALKOVER) { reportWin(m.round, m.pairIndex, me.uid); return; }
// both present -> the host kicks the match off once (guest joins the same match id)
if (!oppReg) return;
inMatch = true;
const id = [me.uid, m.opp].sort().join('_');
if (cb.startMatch) cb.startMatch({ id: id, host: m.host, seed: (meta.seed || 1) + m.round * 7,
round: m.round, pairIndex: m.pairIndex, oppUid: m.opp,
opp: { uid: m.opp, name: oppReg.name, build: oppReg.build, paint: oppReg.paint, flag: oppReg.flag } });
}
}
function reportWin(round, pair, uid) {
inMatch = false;
db.patch('tourney/results/' + round, { [pair]: uid });
}
function matchDone() { inMatch = false; }
return {
join, leave, setReady, reportWin, matchDone,
tick() { /* heartbeat + state progress */ writeRow(); drive(); },
view,
// host-only admin reset (clears everything for a fresh tournament)
reset() { db.del('tourney'); },
close() { subs.forEach(s => s && s.close()); },
};
};
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);

View File

@@ -8,7 +8,10 @@
'use strict'; 'use strict';
const RC = (root.RC = root.RC || {}); const RC = (root.RC = root.RC || {});
RC.WEIGHT_LIMIT = 100; // kg, single weight class in v1 // Weight classes. RC.WEIGHT_LIMIT follows the chosen class (see RC.setClass in ai.js);
// 'heavy' is as much as the catalogue can carry, so it is effectively "build what you like".
RC.CLASSES = [{ id: 'light', max: 60 }, { id: 'medium', max: 100 }, { id: 'heavy', max: 130 }];
RC.WEIGHT_LIMIT = 100; // medium is the default
RC.SLOTS = ['chassis', 'motor', 'wheels', 'battery', 'armour', 'weapon', 'tower', 'gadget']; RC.SLOTS = ['chassis', 'motor', 'wheels', 'battery', 'armour', 'weapon', 'tower', 'gadget'];
RC.REQUIRED = { chassis: true, motor: true, wheels: true, battery: true }; RC.REQUIRED = { chassis: true, motor: true, wheels: true, battery: true };
@@ -24,12 +27,18 @@
{ id: 'fang', slot: 'chassis', name: 'Fang', cost: 860, weight: 26, hp: 120, len: 1.55, wid: 1.0, h: 0.36, shape: 'arrow', lowProfile: true, frontArmour: 0.12 }, { id: 'fang', slot: 'chassis', name: 'Fang', cost: 860, weight: 26, hp: 120, len: 1.55, wid: 1.0, h: 0.36, shape: 'arrow', lowProfile: true, frontArmour: 0.12 },
{ id: 'plough', slot: 'chassis', name: 'Snowplough', cost: 980, weight: 36, hp: 150, len: 1.45, wid: 1.2, h: 0.42, shape: 'plow', frontArmour: 0.22 }, { id: 'plough', slot: 'chassis', name: 'Snowplough', cost: 980, weight: 36, hp: 150, len: 1.45, wid: 1.2, h: 0.42, shape: 'plow', frontArmour: 0.22 },
{ id: 'discus', slot: 'chassis', name: 'Discus', cost: 1350, weight: 32, hp: 155, len: 1.5, wid: 1.35, h: 0.3, shape: 'saucer', lowProfile: true }, { id: 'discus', slot: 'chassis', name: 'Discus', cost: 1350, weight: 32, hp: 155, len: 1.5, wid: 1.35, h: 0.3, shape: 'saucer', lowProfile: true },
{ id: 'orb', slot: 'chassis', name: 'Orb', cost: 700, weight: 28, hp: 140, len: 1.2, wid: 1.2, h: 0.62, shape: 'ball', frontArmour: 0.1 },
{ id: 'tower', slot: 'chassis', name: 'Tower', cost: 640, weight: 27, hp: 125, len: 1.1, wid: 1.0, h: 0.82, shape: 'tower' },
{ id: 'slab', slot: 'chassis', name: 'Slab', cost: 820, weight: 33, hp: 150, len: 1.55, wid: 1.4, h: 0.26, shape: 'slab', lowProfile: true },
// motor: force (N), top speed (m/s) // motor: force (N), top speed (m/s)
{ id: 'sparky', slot: 'motor', name: 'Sparky 2kW', cost: 100, weight: 8, power: 3, force: 650, speed: 4.0 }, { id: 'sparky', slot: 'motor', name: 'Sparky 2kW', cost: 100, weight: 8, power: 3, force: 650, speed: 4.0 },
{ id: 'hornet', slot: 'motor', name: 'Hornet 3kW', cost: 420, weight: 10, power: 5, force: 850, speed: 5.0 }, { id: 'hornet', slot: 'motor', name: 'Hornet 3kW', cost: 420, weight: 10, power: 5, force: 850, speed: 5.0 },
{ id: 'bulldog', slot: 'motor', name: 'Bulldog Torque', cost: 680, weight: 14, power: 6, force: 1250, speed: 4.3 }, { id: 'bulldog', slot: 'motor', name: 'Bulldog Torque', cost: 680, weight: 14, power: 6, force: 1250, speed: 4.3 },
{ id: 'comet', slot: 'motor', name: 'Comet 5kW', cost: 1250, weight: 12, power: 8, force: 1150, speed: 6.2 }, { id: 'comet', slot: 'motor', name: 'Comet 5kW', cost: 1250, weight: 12, power: 8, force: 1150, speed: 6.2 },
{ id: 'pico', slot: 'motor', name: 'Pico 1kW', cost: 60, weight: 5, power: 2, force: 440, speed: 3.4 },
{ id: 'turbine', slot: 'motor', name: 'Turbine 4kW', cost: 560, weight: 11, power: 6, force: 980, speed: 5.4 },
{ id: 'titandrive', slot: 'motor', name: 'Titan Drive', cost: 1100, weight: 18, power: 9, force: 1500, speed: 3.8 },
// wheels: speed factor, lateral grip, turn rate (rad/s), push factor; invertible = drives upside down // wheels: speed factor, lateral grip, turn rate (rad/s), push factor; invertible = drives upside down
{ id: 'rubber', slot: 'wheels', name: 'Rubber 4x', cost: 60, weight: 4, speedMul: 1.0, grip: 7, turn: 2.8, push: 1.0, kind: 'small' }, { id: 'rubber', slot: 'wheels', name: 'Rubber 4x', cost: 60, weight: 4, speedMul: 1.0, grip: 7, turn: 2.8, push: 1.0, kind: 'small' },

73
game/progress.js Normal file
View File

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

View File

@@ -313,6 +313,25 @@
const pan = sk(new T.BoxGeometry(L * 0.9, 0.09, Wd * 0.86), L * 0.9, 0.09, Wd * 0.86, -0.045); const pan = sk(new T.BoxGeometry(L * 0.9, 0.09, Wd * 0.86), L * 0.9, 0.09, Wd * 0.86, -0.045);
pan.position.y = c + 0.07; tilt.add(pan); pan.position.y = c + 0.07; tilt.add(pan);
top = c + H; top = c + H;
} else if (ch.shape === 'ball') {
const o = sk(new T.SphereGeometry(1, 24, 16), 2, 1, 2, 0);
o.scale.set(L / 2, H / 2 + 0.06, Wd / 2); o.position.y = c + H / 2; tilt.add(o);
const ring = new T.Mesh(new T.TorusGeometry(1, 0.045, 8, 28), accent);
ring.rotation.x = Math.PI / 2; ring.scale.set(L / 2 * 1.01, Wd / 2 * 1.01, 1); ring.position.y = c + H * 0.5; tilt.add(ring);
if (!drawn) { const st2 = box(0.05, H * 0.9, Wd * 0.5, m.stripe); st2.position.set(-L / 2 + 0.03, c + H * 0.5, 0); tilt.add(st2); }
top = c + H * 1.05;
} else if (ch.shape === 'tower') {
const o = sk(new T.BoxGeometry(L, H, Wd), L, H, Wd, -H / 2); o.position.y = c + H / 2; tilt.add(o);
const headH = H * 0.3, head = sk(new T.BoxGeometry(L * 0.7, headH, Wd * 0.7), L * 0.7, headH, Wd * 0.7, -headH / 2);
head.position.set(0, c + H + headH / 2, 0); tilt.add(head);
const vis = box(0.02, headH * 0.4, Wd * 0.5, m.glowW); vis.position.set(L * 0.35 + 0.005, c + H + headH * 0.6, 0); tilt.add(vis);
if (!drawn) for (const sy of [0.3, 0.7]) { const band = box(L * 1.004, 0.05, Wd * 1.004, m.stripe); band.position.set(0, c + H * sy, 0); tilt.add(band); }
top = c + H + headH;
} else if (ch.shape === 'slab') {
const o = sk(new T.BoxGeometry(L, H, Wd), L, H, Wd, -H / 2); o.position.y = c + H / 2; tilt.add(o);
const nose = box(0.4, H * 0.9, Wd * 1.02, m.steel); nose.position.set(L / 2 + 0.06, c + H * 0.4, 0); nose.rotation.z = -0.5; tilt.add(nose);
if (!drawn) { const edge = box(0.1, 0.07, Wd * 1.05, m.stripe); edge.position.set(L / 2 + 0.22, c * 0.5, 0); tilt.add(edge); }
top = c + H;
} else { } else {
const o = sk(new T.BoxGeometry(L, H, Wd), L, H, Wd, -H / 2); o.position.y = c + H / 2; tilt.add(o); const o = sk(new T.BoxGeometry(L, H, Wd), L, H, Wd, -H / 2); o.position.y = c + H / 2; tilt.add(o);
if (!drawn) { if (!drawn) {
@@ -327,6 +346,11 @@
const win = box(0.02, chh * 0.25, cd * 0.8, m.dark); win.position.set(-L * 0.16 + cw / 2 + 0.005, top + chh * 0.62, 0); tilt.add(win); 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; top += chh;
} }
if (look.hump) {
const hb = sk(new T.SphereGeometry(1, 18, 10, 0, Math.PI * 2, 0, Math.PI / 2), 2, 1, 2, 0);
hb.scale.set(L * 0.3, H * 0.9, Wd * 0.4); hb.position.set(-L * 0.22, top, 0); tilt.add(hb);
top += H * 0.6;
}
if (look.bumps) { if (look.bumps) {
for (const sz of [-1, 1]) { 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); const b = sk(new T.SphereGeometry(1, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2), 2, 1, 2, 0);
@@ -441,9 +465,12 @@
const WS = m.wsteel, ED = m.wedge, HZ = m.stripe; // weapon steel, edge, hazard stripe const WS = m.wsteel, ED = m.wedge, HZ = m.stripe; // weapon steel, edge, hazard stripe
if (w.type === 'wedge') { if (w.type === 'wedge') {
if (w.id === 'lance') { if (w.id === 'lance') {
// long spike lance // long spike lance on a sleeve - it thrusts forward when fired (poseRobot drives out.lance.position.x)
const shaft = cyl(0.05, 0.05, 0.85, m.dark, 8); shaft.rotation.z = Math.PI / 2; shaft.position.set(L / 2 + 0.42, c + H * 0.4, 0); tilt.add(shaft); const g = new T.Group(); g.position.set(L / 2, c + H * 0.4, 0); g.userData.baseX = L / 2; tilt.add(g);
const tip = cyl(0.001, 0.13, 0.42, HZ, 12); tip.rotation.z = -Math.PI / 2; tip.position.set(L / 2 + 0.95, c + H * 0.4, 0); tilt.add(tip); const sleeve = cyl(0.07, 0.08, 0.3, m.steel, 10); sleeve.rotation.z = Math.PI / 2; sleeve.position.x = -0.05; tilt.add(sleeve);
const shaft = cyl(0.05, 0.05, 0.85, m.dark, 8); shaft.rotation.z = Math.PI / 2; shaft.position.x = 0.42; g.add(shaft);
const tip = cyl(0.001, 0.13, 0.42, HZ, 12); tip.rotation.z = -Math.PI / 2; tip.position.x = 0.95; g.add(tip);
out.lance = g;
} else { } else {
// short ramp plate at the front (as before - stays close to the body so it does not poke through) // 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 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);
@@ -610,6 +637,11 @@
const sp = Math.hypot(r.vx, r.vz) * (Math.cos(r.a) * r.vx + Math.sin(r.a) * r.vz >= 0 ? 1 : -1); const sp = Math.hypot(r.vx, r.vz) * (Math.cos(r.a) * r.vx + Math.sin(r.a) * r.vz >= 0 ? 1 : -1);
for (const wl of R.wheels) wl.rotation.z -= sp * dt / (R.wheelR || 0.16); for (const wl of R.wheels) wl.rotation.z -= sp * dt / (R.wheelR || 0.16);
if (R.flipper) R.flipper.rotation.z = -0.32 + (r.flipAnim > 0 ? Math.sin((1 - r.flipAnim / 0.35) * Math.PI) * 1.5 : 0); if (R.flipper) R.flipper.rotation.z = -0.32 + (r.flipAnim > 0 ? Math.sin((1 - r.flipAnim / 0.35) * Math.PI) * 1.5 : 0);
if (R.lance) {
// boost is set for 0.8 s when the lance fires -> fast stab out and back
const k = r.boost > 0 ? r.boost / 0.8 : 0;
R.lance.position.x = R.lance.userData.baseX + Math.sin(Math.min(1, (1 - k) * 2.2) * Math.PI) * 0.55;
}
if (R.hammer) { if (R.hammer) {
let ang = 1.9; let ang = 1.9;
if (r.swing > 0) { const k = 1 - r.swing / 0.28; ang = lerp(1.9, -0.25, k * k); } if (r.swing > 0) { const k = 1 - r.swing / 0.28; ang = lerp(1.9, -0.25, k * k); }
@@ -794,6 +826,9 @@
scrap: new T.MeshStandardMaterial({ color: 0x5a5048, metalness: 0.6, roughness: 0.8 }), scrap: new T.MeshStandardMaterial({ color: 0x5a5048, metalness: 0.6, roughness: 0.8 }),
barrier: new T.MeshStandardMaterial({ color: 0x9aa0a8, metalness: 0.6, roughness: 0.5 }), barrier: new T.MeshStandardMaterial({ color: 0x9aa0a8, metalness: 0.6, roughness: 0.5 }),
}; };
const RUST = new T.MeshStandardMaterial({ color: 0x6e3e22, metalness: 0.45, roughness: 0.92 });
const PAINT = new T.MeshStandardMaterial({ color: 0x7a5230, metalness: 0.3, roughness: 0.85 });
const scrapMats = [BMAT.scrap, RUST, PAINT, m.steel, m.dark];
let bseed = 7; let bseed = 7;
const brnd = () => { bseed = (bseed * 16807) % 2147483647; return bseed / 2147483647; }; const brnd = () => { bseed = (bseed * 16807) % 2147483647; return bseed / 2147483647; };
for (const b of A.blocks) { for (const b of A.blocks) {
@@ -801,22 +836,43 @@
const mat = BMAT[b.kind] || BMAT.crate; const mat = BMAT[b.kind] || BMAT.crate;
if (b.kind === 'pillar') { if (b.kind === 'pillar') {
const rr = Math.min(b.hw, b.hd); const rr = Math.min(b.hw, b.hd);
const col = cyl(rr, rr * 1.12, b.h, mat, 14); col.position.y = b.h / 2; col.castShadow = true; g.add(col); const col = cyl(rr, rr * 1.12, b.h, mat, 16); col.position.y = b.h / 2; col.castShadow = true; g.add(col);
const cap = cyl(rr * 1.18, rr * 1.18, 0.12, m.dark, 14); cap.position.y = b.h; g.add(cap); const cap = cyl(rr * 1.18, rr * 1.18, 0.12, m.dark, 16); cap.position.y = b.h; g.add(cap);
const band = cyl(rr * 1.06, rr * 1.06, 0.18, m.stripe, 14); band.position.y = b.h * 0.42; g.add(band); const foot = cyl(rr * 1.25, rr * 1.35, 0.14, m.dark, 16); foot.position.y = 0.07; g.add(foot);
for (const sy of [0.28, 0.64]) { const band = cyl(rr * 1.05, rr * 1.05, 0.14, m.stripe, 16); band.position.y = b.h * sy; g.add(band); }
// warning light on top
const wl = new T.Mesh(new T.SphereGeometry(0.07, 8, 6), new T.MeshStandardMaterial({ color: 0x401000, emissive: 0xff5a10, emissiveIntensity: 0.9 }));
wl.position.y = b.h + 0.1; g.add(wl);
} else if (b.kind === 'scrap') { } else if (b.kind === 'scrap') {
for (let k = 0; k < 5; k++) { // tumbled junk pile: mixed rusty/steel/painted plates, each tilted, with a dark edge lip
const w2 = b.hw * (0.5 + brnd() * 0.75), h2 = b.h * (0.35 + brnd() * 0.65), d2 = b.hd * (0.5 + brnd() * 0.75); for (let k = 0; k < 6; k++) {
const p2 = box(w2, h2, d2, mat); const w2 = b.hw * (0.45 + brnd() * 0.8), h2 = b.h * (0.22 + brnd() * 0.5), d2 = b.hd * (0.45 + brnd() * 0.8);
p2.position.set((brnd() - 0.5) * b.hw, h2 / 2, (brnd() - 0.5) * b.hd); const pm = scrapMats[(brnd() * scrapMats.length) | 0];
p2.rotation.y = brnd() * 3; p2.castShadow = true; g.add(p2); const slab = new T.Group();
const p2 = box(w2, h2, d2, pm); p2.castShadow = true; slab.add(p2);
const lip = box(w2 + 0.04, 0.05, d2 + 0.04, m.dark); lip.position.y = h2 / 2; slab.add(lip); // crisp top edge
slab.position.set((brnd() - 0.5) * b.hw * 1.1, h2 / 2 + brnd() * b.h * 0.5, (brnd() - 0.5) * b.hd * 1.1);
slab.rotation.set((brnd() - 0.5) * 0.4, brnd() * 3, (brnd() - 0.5) * 0.4);
g.add(slab);
} }
// a rusty barrel wedged in, with a warning ring
const br = Math.min(b.hw, b.hd) * 0.42;
const barrel = cyl(br, br, b.h * 0.95, RUST, 14); barrel.position.set((brnd() - 0.5) * b.hw * 0.5, b.h * 0.48, (brnd() - 0.5) * b.hd * 0.5);
barrel.rotation.z = 0.12; barrel.castShadow = true; g.add(barrel);
const ring = cyl(br * 1.04, br * 1.04, 0.1, m.stripe, 14); ring.position.copy(barrel.position); ring.rotation.z = 0.12; g.add(ring);
// a leaning hazard-striped plank
const plank = box(0.1, b.h * 1.5, b.hd * 0.8, m.stripe); plank.position.set(b.hw * 0.7, b.h * 0.6, 0); plank.rotation.z = 0.5; plank.castShadow = true; g.add(plank);
} else if (b.kind === 'barrier') { } else if (b.kind === 'barrier') {
const bar = box(b.hw * 2, b.h, b.hd * 2, mat); bar.position.y = b.h / 2; bar.castShadow = true; g.add(bar); const bar = box(b.hw * 2, b.h, b.hd * 2, mat); bar.position.y = b.h / 2; bar.castShadow = true; g.add(bar);
const top = box(b.hw * 2, 0.1, b.hd * 2.1, m.stripe); top.position.y = b.h; g.add(top); const top = box(b.hw * 2 + 0.06, 0.12, b.hd * 2 + 0.06, m.stripe); top.position.y = b.h; g.add(top);
} else { const base = box(b.hw * 2 + 0.1, 0.1, b.hd * 2 + 0.1, m.dark); base.position.y = 0.05; g.add(base);
} else { // crate: steel box with hazard bands, corner bolts and a plated top
const bx = box(b.hw * 2, b.h, b.hd * 2, mat); bx.position.y = b.h / 2; bx.castShadow = true; g.add(bx); const bx = box(b.hw * 2, b.h, b.hd * 2, mat); bx.position.y = b.h / 2; bx.castShadow = true; g.add(bx);
for (const sy of [0.28, 0.74]) { const band = box(b.hw * 2.05, 0.06, b.hd * 2.05, m.dark); band.position.y = b.h * sy; g.add(band); } const lid = box(b.hw * 2 + 0.05, 0.08, b.hd * 2 + 0.05, m.dark); lid.position.y = b.h; g.add(lid);
for (const sy of [0.3, 0.72]) { const band = box(b.hw * 2.04, 0.08, b.hd * 2.04, m.stripe); band.position.y = b.h * sy; g.add(band); }
for (const sx of [-1, 1]) for (const sz of [-1, 1]) {
const bolt = cyl(0.03, 0.03, b.h * 0.9, m.dark, 6); bolt.position.set(sx * (b.hw - 0.05), b.h / 2, sz * (b.hd - 0.05)); g.add(bolt);
}
} }
} }
for (const b of A.belts) { for (const b of A.belts) {
@@ -887,11 +943,30 @@
const mr = cyl(0.43, 0.43, 0.06, m.stripe, 20); mr.position.y = 0.08; mag.add(mr); const mr = cyl(0.43, 0.43, 0.06, m.stripe, 20); mr.position.y = 0.08; mag.add(mr);
out.crane = { post: cpost, boom, cable, mag, px: C.x - 2.4, pz: C.z + 2.4 }; out.crane = { post: cpost, boom, cable, mag, px: C.x - 2.4, pz: C.z + 2.4 };
// pit doors + warning lights // pit: a real shaft you fall into, a hazard-striped rim and a steel grate
const pit = A.pit; const pit = A.pit;
const shaftMat = new T.MeshStandardMaterial({ color: 0x090a0d, metalness: 0.6, roughness: 0.9 });
const floorHole = box(pit.hw * 2, 0.02, pit.hd * 2, new T.MeshBasicMaterial({ color: 0x000000 }));
floorHole.position.set(pit.x, -0.01, pit.z); scene.add(floorHole);
for (const [nx, nz] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { // four shaft walls going down
const w = box(nz ? pit.hw * 2 : 0.08, 1.6, nz ? 0.08 : pit.hd * 2, shaftMat);
w.position.set(pit.x + nx * pit.hw, -0.8, pit.z + nz * pit.hd); scene.add(w);
}
for (const sx of [-1, 1]) for (const sz of [-1, 1]) { // striped rim around the edge
const bx = box(pit.hw * 2 + 0.2, 0.09, 0.14, m.stripe); bx.position.set(pit.x, 0.05, pit.z + sz * (pit.hd + 0.05)); scene.add(bx);
const bz = box(0.14, 0.09, pit.hd * 2 + 0.2, m.stripe); bz.position.set(pit.x + sx * (pit.hw + 0.05), 0.05, pit.z); scene.add(bz);
}
const grate = new T.Group(); out.pitGrate = grate; scene.add(grate); // retracts as the pit opens
const gbarMat = new T.MeshStandardMaterial({ color: 0x4a515c, metalness: 0.85, roughness: 0.35 });
const nb = Math.max(4, Math.round(pit.hw * 2 / 0.3));
for (let k = 0; k <= nb; k++) {
const t = -pit.hw + (k / nb) * pit.hw * 2;
const b1 = box(0.05, 0.08, pit.hd * 2, gbarMat); b1.position.set(pit.x + t, 0.06, pit.z); grate.add(b1);
const b2 = box(pit.hw * 2, 0.08, 0.05, gbarMat); b2.position.set(pit.x, 0.055, pit.z + t * (pit.hd / pit.hw)); grate.add(b2);
}
out.pitDoors = [-1, 1].map(sx => { out.pitDoors = [-1, 1].map(sx => {
const d = box(pit.hw, 0.05, pit.hd * 2, new T.MeshStandardMaterial({ color: 0x3d4148, metalness: 0.8, roughness: 0.4 })); const d = box(pit.hw, 0.05, pit.hd * 2, new T.MeshStandardMaterial({ color: 0x3d4148, metalness: 0.8, roughness: 0.4 }));
d.position.set(pit.x + sx * pit.hw / 2, 0.025, pit.z); d.userData.sx = sx; scene.add(d); return d; d.position.set(pit.x + sx * pit.hw / 2, 0.03, pit.z); d.userData.sx = sx; scene.add(d); return d;
}); });
out.pitLamps = [[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([sx, sz]) => { out.pitLamps = [[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([sx, sz]) => {
const l = new T.Mesh(new T.SphereGeometry(0.09, 10, 6), new T.MeshStandardMaterial({ color: 0x400000, emissive: 0xff1a1a, emissiveIntensity: 0 })); const l = new T.Mesh(new T.SphereGeometry(0.09, 10, 6), new T.MeshStandardMaterial({ color: 0x400000, emissive: 0xff1a1a, emissiveIntensity: 0 }));
@@ -1278,6 +1353,23 @@
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);
// long front weapons must stop at the enemy, not stab through it
if (R.lance) {
const e = s.robots[1 - i];
if (e && !e.out) {
const dx = e.x - r.x, dz = e.z - r.z, d = Math.hypot(dx, dz) || 1;
const fx = Math.cos(r.a), fz = Math.sin(r.a), facing = (dx * fx + dz * fz) / d;
if (facing > 0.55) {
const reach = d - e.st.rad * 0.85, base = R.st.len / 2 + 0.95;
const maxThrust = Math.max(0, reach - base), bx = R.lance.userData.baseX;
if (R.lance.position.x - bx > maxThrust) {
const hit = R.lance.position.x - bx - maxThrust > 0.04;
R.lance.position.x = bx + maxThrust;
if (hit && Math.random() < 0.6) burst(e.x - fx * e.st.rad, 0.4, e.z - fz * e.st.rad, 10, 5, [1, 0.8, 0.4]);
}
}
}
}
// damaged robots smoke, dead ones burn // damaged robots smoke, dead ones burn
const hp = r.hp / r.maxHp; const hp = r.hp / r.maxHp;
R.smokeT -= dt; R.smokeT -= dt;
@@ -1335,6 +1427,7 @@
// pit // pit
const o = s.pitOpen; const o = s.pitOpen;
for (const d of arena.pitDoors) { d.position.x = A.pit.x + d.userData.sx * (A.pit.hw / 2 + o * A.pit.hw * 1.02); d.position.y = 0.025 + o * 0.01; } for (const d of arena.pitDoors) { d.position.x = A.pit.x + d.userData.sx * (A.pit.hw / 2 + o * A.pit.hw * 1.02); d.position.y = 0.025 + o * 0.01; }
if (arena.pitGrate) { arena.pitGrate.position.y = -o * 1.5; arena.pitGrate.visible = o < 0.98; }
for (const l of arena.pitLamps) l.material.emissiveIntensity = s.pitAlarm ? (Math.sin(now / 150) > 0 ? 2.5 : 0.4) : 0; for (const l of arena.pitLamps) l.material.emissiveIntensity = s.pitAlarm ? (Math.sin(now / 150) > 0 ? 2.5 : 0.4) : 0;
// rockets // rockets
// mines lying on the floor: dark puck, the lamp blinks fast once it is armed // mines lying on the floor: dark puck, the lamp blinks fast once it is armed

View File

@@ -9,6 +9,13 @@
const RC = (root.RC = root.RC || (typeof require === 'function' ? require('./parts.js') : {})); const RC = (root.RC = root.RC || (typeof require === 'function' ? require('./parts.js') : {}));
const part = (b, slot) => (b && b[slot] ? RC.PARTS[b[slot]] || null : null); const part = (b, slot) => (b && b[slot] ? RC.PARTS[b[slot]] || null : null);
const clamp = (v, a, c) => (v < a ? a : v > c ? c : v);
// per-robot proportions: height / width / length factor (default 1). Bigger = heavier + tougher + slower.
RC.bodyOf = b => {
const d = (b && b.body) || {};
return { hx: clamp(+d.hx || 1, 0.7, 1.6), wx: clamp(+d.wx || 1, 0.8, 1.4), lx: clamp(+d.lx || 1, 0.8, 1.3) };
};
const sizeFactor = bo => bo.hx * bo.wx * bo.lx;
RC.HP_SCALE = 3; // catalogue hp x this = hit points in the arena RC.HP_SCALE = 3; // catalogue hp x this = hit points in the arena
@@ -19,7 +26,7 @@
const p = part(build, slot); const p = part(build, slot);
if (!p) { if (RC.REQUIRED[slot]) errors.push('need_' + slot); continue; } if (!p) { if (RC.REQUIRED[slot]) errors.push('need_' + slot); continue; }
if (p.slot !== slot) { errors.push('bad_' + slot); continue; } if (p.slot !== slot) { errors.push('bad_' + slot); continue; }
weight += p.weight; weight += slot === 'chassis' ? Math.round(p.weight * (0.4 + 0.6 * sizeFactor(RC.bodyOf(build)))) : p.weight;
if (slot === 'battery') supply += p.power; else power += p.power || 0; if (slot === 'battery') supply += p.power; else power += p.power || 0;
} }
if (weight > RC.WEIGHT_LIMIT) errors.push('overweight'); if (weight > RC.WEIGHT_LIMIT) errors.push('overweight');
@@ -34,9 +41,12 @@
const mass = Math.max(30, v.weight); const mass = Math.max(30, v.weight);
let value = 0; let value = 0;
for (const slot of RC.SLOTS) { const p = part(build, slot); if (p) value += p.cost; } for (const slot of RC.SLOTS) { const p = part(build, slot); if (p) value += p.cost; }
const len = ch ? ch.len : 1.3, wid = ch ? ch.wid : 1.0; const bo = RC.bodyOf(build), size = sizeFactor(bo);
const len = (ch ? ch.len : 1.3) * bo.lx, wid = (ch ? ch.wid : 1.0) * bo.wx;
return { return {
hp: ((ch ? ch.hp : 80) + (ar ? ar.hp : 0)) * RC.HP_SCALE, body: bo,
topHeavy: bo.hx / ((bo.wx + bo.lx) / 2), // tall + narrow = easier to tip over
hp: (Math.round((ch ? ch.hp : 80) * (0.6 + 0.4 * size)) + (ar ? ar.hp : 0)) * RC.HP_SCALE,
reduce: ar ? ar.reduce : 0, reduce: ar ? ar.reduce : 0,
mass, mass,
accel: (mo ? mo.force : 500) / mass * (wh ? Math.min(1.2, wh.grip / 8) : 1), accel: (mo ? mo.force : 500) / mass * (wh ? Math.min(1.2, wh.grip / 8) : 1),
@@ -44,8 +54,8 @@
turn: (wh ? wh.turn : 2.5) * (1.15 - mass / 650), turn: (wh ? wh.turn : 2.5) * (1.15 - mass / 650),
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) * bo.hx,
rad: Math.hypot(len, wid) / 2 * 0.9, // close to the body corners so robots do not clip through each other rad: Math.hypot(len, wid) / 2 * 0.95, // body corners - bigger = robots keep more distance, less clipping
weapon: we, tower: to, gadget: gd, armour: ar, weapon: we, tower: to, gadget: gd, armour: ar,
invertible: !!(wh && wh.invertible), invertible: !!(wh && wh.invertible),
lowProfile: !!(ch && ch.lowProfile), lowProfile: !!(ch && ch.lowProfile),

View File

@@ -25,7 +25,7 @@
RC.Shop = function (opt) { RC.Shop = function (opt) {
const t = opt.t; const t = opt.t;
let slot = 'weapon', sel = undefined, tipN = 0, topTab = 'build'; let slot = 'weapon', sel = undefined, tipN = 0, topTab = 'build', designerOpen = false;
function chipsFor(p) { function chipsFor(p) {
const s = []; const s = [];
@@ -68,7 +68,8 @@
$('tabs').querySelectorAll('.tab').forEach(el => { el.onclick = () => { slot = el.dataset.slot; sel = b[slot] || null; opt.sfx.click(); render(); }; }); $('tabs').querySelectorAll('.tab').forEach(el => { el.onclick = () => { slot = el.dataset.slot; sel = b[slot] || null; opt.sfx.click(); render(); }; });
// part cards // part cards
const items = (RC.REQUIRED[slot] ? [] : [null]).concat(RC.partsFor(slot).map(p => p.id)); const locked = opt.locked || (() => false); // event/unlock: hide parts not released yet
const items = (RC.REQUIRED[slot] ? [] : [null]).concat(RC.partsFor(slot).filter(p => !locked(p.id)).map(p => p.id));
$('cards').innerHTML = items.map(id => { $('cards').innerHTML = items.map(id => {
const p = id && RC.PARTS[id], eq = b[slot] === id, own = !id || save.owned.includes(id); const p = id && RC.PARTS[id], eq = b[slot] === id, own = !id || save.owned.includes(id);
const badge = eq ? `<span class="badge">${t('equipped')}</span>` : own && id ? `<span class="badge own">${t('owned')}</span>` : ''; const badge = eq ? `<span class="badge">${t('equipped')}</span>` : own && id ? `<span class="badge own">${t('owned')}</span>` : '';
@@ -126,11 +127,40 @@
const name = $('rname'); const name = $('rname');
if (document.activeElement !== name) name.value = save.robotName; if (document.activeElement !== name) name.value = save.robotName;
if (!$('mechTip').textContent) tip(); if (!$('mechTip').textContent) tip();
renderTopTabs(); renderFitted(); renderTopTabs(); renderFitted(); renderDesigner();
// live preview: show the selected part on the 3D robot (even parts you can't afford yet) // live preview: show the selected part on the 3D robot (even parts you can't afford yet)
if (opt.onPreview) opt.onPreview(topTab === 'build' && sel !== b[slot] ? Object.assign({}, b, { [slot]: sel }) : b); if (opt.onPreview) opt.onPreview(topTab === 'build' && sel !== b[slot] ? Object.assign({}, b, { [slot]: sel }) : b);
} }
// proportions designer (height / width / length) - only on the chassis slot
function renderDesigner() {
const el = $('designer');
if (!el) return;
if (slot !== 'chassis') { el.classList.add('hide'); return; }
el.classList.remove('hide');
el.classList.toggle('open', designerOpen);
el.classList.toggle('shut', !designerOpen);
const save = opt.getSave(), b = save.build;
if (!b.body) b.body = { hx: 1, wx: 1, lx: 1 };
const row = (key, label, lo, hi) => `<div class="drow"><span>${t('des_' + label)}</span>`
+ `<input type="range" data-k="${key}" min="${lo}" max="${hi}" step="0.05" value="${b.body[key] || 1}">`
+ `<span class="dv" id="dv_${key}">${Math.round((b.body[key] || 1) * 100)}%</span></div>`;
// collapsed by default: only the header; click the title to expand the three sliders
el.innerHTML = `<div class="dh"><span class="dtitle" id="dToggle"><span class="caret">${designerOpen ? '▾' : '▸'}</span>${t('s_body')}</span>${designerOpen ? `<button id="dReset">${t('des_reset')}</button>` : ''}</div>`
+ (designerOpen ? row('hx', 'height', 0.7, 1.6) + row('wx', 'width', 0.8, 1.4) + row('lx', 'length', 0.8, 1.3) : '');
$('dToggle').onclick = () => { designerOpen = !designerOpen; opt.sfx.click(); renderDesigner(); };
if (!designerOpen) return;
el.querySelectorAll('input[type=range]').forEach(inp => {
inp.oninput = () => {
b.body[inp.dataset.k] = +inp.value;
$('dv_' + inp.dataset.k).textContent = Math.round(inp.value * 100) + '%';
opt.onSave(); opt.onPreview(b); // live 3D while dragging
};
inp.onchange = () => render(); // on release: refresh weight bar + stats
});
$('dReset').onclick = () => { b.body = { hx: 1, wx: 1, lx: 1 }; opt.sfx.click(); opt.onSave(); opt.onPreview(b); render(); };
}
// top mode tabs: Parts / Paint / Hangar // top mode tabs: Parts / Paint / Hangar
function renderTopTabs() { function renderTopTabs() {
const tabs = [['build', '🔧 ' + t('tab_build')], ['paint', '🎨 ' + t('tab_paint')], ['hangar', '🚗 ' + t('tab_hangar')]]; const tabs = [['build', '🔧 ' + t('tab_build')], ['paint', '🎨 ' + t('tab_paint')], ['hangar', '🚗 ' + t('tab_hangar')]];

104
game/tourney.js Normal file
View File

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

View File

@@ -31,6 +31,9 @@ PROMPTS = [
f"hanging chains, shelves with motors and batteries, orange work lamps, empty floor in the middle, {_SCENE}"), f"hanging chains, shelves with motors and batteries, orange work lamps, empty floor in the middle, {_SCENE}"),
("bg_title", f"huge indoor robot combat arena seen from high above at an angle, steel floor plates, spiked walls, " ("bg_title", f"huge indoor robot combat arena seen from high above at an angle, steel floor plates, spiked walls, "
f"floodlights cutting through haze, dark crowded stands, a glowing pit in the floor, {_SCENE}"), f"floodlights cutting through haze, dark crowded stands, a glowing pit in the floor, {_SCENE}"),
("bg_start", f"dramatic hero shot of two chunky handmade combat robots facing off in a floodlit industrial "
f"night arena, sparks and haze, scratched painted steel with orange hazard stripes, low camera angle, "
f"empty dark sky above for a title, {_SCENE}"),
("bg_win", f"robot combat arena celebration, golden confetti and showers of sparks under floodlights, {_SCENE}"), ("bg_win", f"robot combat arena celebration, golden confetti and showers of sparks under floodlights, {_SCENE}"),
("bg_lose", f"smoking wrecked robot parts and scattered bolts on a steel arena floor, drifting smoke, dim red light, {_SCENE}"), ("bg_lose", f"smoking wrecked robot parts and scattered bolts on a steel arena floor, drifting smoke, dim red light, {_SCENE}"),
@@ -90,6 +93,25 @@ PROMPTS = [
("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 round dome shell robot like an upturned wok on hidden wheels, long horizontal spinning steel bar across the front at floor height, {_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}"),
# league opponents - lightweight (<=60 kg: small, quick)
("opp_tinflea", f"tiny grey open-frame robot with a small ramming wedge, yellow accents, {_ROBOT}"),
("opp_sparrow", f"small teal and white low robot with a long thin ramming spike on the front, {_ROBOT}"),
("opp_needle", f"small red and black robot with a spinning circular saw up front, wire mesh armour, {_ROBOT}"),
("opp_jackrabbit", f"green and yellow low robot with a wide front lifting scoop and big tyres, {_ROBOT}"),
("opp_switchblade", f"purple and white six-sided hexagon robot with an angled ramming wedge, {_ROBOT}"),
("opp_wasp", f"yellow and black arrow-shaped pointed robot with a long ramming spike, {_ROBOT}"),
("opp_firefly", f"orange low robot with a front saw and a small flame nozzle turret, {_ROBOT}"),
("opp_pinpoint", f"dark blue arrow-shaped robot with a heavy spiked mace on a swinging arm, {_ROBOT}"),
# league opponents - heavyweight (<=130 kg: big, armoured)
("opp_bulldozer", f"big yellow and black heavy robot on tank tracks with a wide ramming blade, thick steel armour, {_ROBOT}"),
("opp_anvil", f"heavy grey robot with a big angled plough blade on the nose and studded tyres, {_ROBOT}"),
("opp_boilerplate", f"heavy robot built from a rolled steel drum body with spiked armour and a hammer arm, {_ROBOT}"),
("opp_grinder", f"wide flat dark disc-shaped heavy robot with a horizontal spinning drum, green lights, {_ROBOT}"),
("opp_juggernaut", f"massive red and gold heavy robot on tank tracks with hydraulic crushing jaws, hardened armour, {_ROBOT}"),
("opp_warhound", f"purple heavy robot with a plough nose, spiked mace arm and a flame nozzle turret, {_ROBOT}"),
("opp_colossus", f"huge black and blue domed heavy robot on tracks with a big spinning bar and an electric arc turret, {_ROBOT}"),
("opp_doomsday", f"menacing black and red heavy robot with a big vertical spinning disc and a rocket pod, {_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, "
"grey stubble, grease on the cheek, dark overalls with an orange stripe, friendly grin, holding a wrench, " "grey stubble, grease on the cheek, dark overalls with an orange stripe, friendly grin, holding a wrench, "

View File

@@ -2,7 +2,7 @@
'use strict'; 'use strict';
const path = require('path'); const path = require('path');
const g = p => require(path.join(__dirname, '..', 'game', p)); const g = p => require(path.join(__dirname, '..', 'game', p));
g('parts.js'); g('robot.js'); g('combat.js'); g('ai.js'); g('parts.js'); g('robot.js'); g('combat.js'); g('ai.js'); g('progress.js'); g('tourney.js'); g('live.js'); g('ltourney.js');
const RC = globalThis.RC; const RC = globalThis.RC;
let fails = 0; let fails = 0;
const ok = (c, msg) => { if (!c) { fails++; console.log('FAIL', msg); } }; const ok = (c, msg) => { if (!c) { fails++; console.log('FAIL', msg); } };
@@ -13,7 +13,26 @@ ok(!RC.validate({ ...RC.STARTER, chassis: null }).ok, 'chassis required');
ok(RC.validate({ chassis: 'scarab', motor: 'comet', wheels: 'tracks', battery: 'lipo', armour: 'hardox', weapon: 'spinner', tower: 'rockets' }).errors.includes('overweight'), 'overweight detected'); ok(RC.validate({ chassis: 'scarab', motor: 'comet', wheels: 'tracks', battery: 'lipo', armour: 'hardox', weapon: 'spinner', tower: 'rockets' }).errors.includes('overweight'), 'overweight detected');
ok(RC.validate({ chassis: 'crate', motor: 'comet', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'spinner', tower: null }).errors.includes('no_power'), 'power detected'); ok(RC.validate({ chassis: 'crate', motor: 'comet', wheels: 'rubber', battery: 'lead', armour: null, weapon: 'spinner', tower: null }).errors.includes('no_power'), 'power detected');
ok(RC.validate({ ...RC.STARTER, motor: 'lead' }).errors.includes('bad_motor'), 'wrong slot detected'); ok(RC.validate({ ...RC.STARTER, motor: 'lead' }).errors.includes('bad_motor'), 'wrong slot detected');
for (const o of [...RC.LEAGUE, RC.DUMMY]) { const v = RC.validate(o.build); ok(v.ok, `league build ${o.id}: ${v.errors} (${v.weight} kg, ${v.power}/${v.supply})`); } // every weight class: all eight builds must fit the class limit and its own power budget
for (const c of RC.CLASSES) {
RC.setClass(c.id);
for (const o of RC.LEAGUE) {
const v = RC.validate(o.build);
ok(v.ok, `${c.id} build ${o.id}: ${v.errors} (${v.weight} kg, ${v.power}/${v.supply})`);
ok(v.weight <= c.max, `${c.id} build ${o.id} stays under ${c.max} kg (${v.weight})`);
}
const names = RC.LEAGUE.map(o => o.name);
ok(new Set(names).size === names.length, `${c.id}: no duplicate names`);
const rising = RC.LEAGUE.every((o, i) => i === 0 || o.prize > RC.LEAGUE[i - 1].prize);
ok(rising, `${c.id}: prize money goes up through the league`);
}
RC.setClass('medium');
ok(RC.WEIGHT_LIMIT === 100 && RC.LEAGUE === RC.LEAGUES.medium, 'setClass swaps limit and roster');
RC.setClass('light');
ok(RC.WEIGHT_LIMIT === 60, 'the light class really lowers the limit');
ok(!RC.validate({ ...RC.STARTER, chassis: 'plough', armour: 'hardox' }).ok, 'a heavy build is refused in the light class');
RC.setClass('medium');
{ const v = RC.validate(RC.DUMMY.build); ok(v.ok, `dummy build: ${v.errors}`); }
// fights: every league robot vs every other, AI on both sides // fights: every league robot vs every other, AI on both sides
function fight(a, b, seed) { function fight(a, b, seed) {
@@ -218,5 +237,152 @@ for (const id of ['crucible', 'colosseum', 'foundry', 'arena64']) {
ok(h0 - a2.hp > 10, 'once the grace time is over your own mine gets you too'); ok(h0 - a2.hp > 10, 'once the grace time is over your own mine gets you too');
} }
// ranks and achievements
{
const P = RC.Progress;
ok(P.rankOf(0).key === P.RANKS[0].key, 'no fame = lowest rank');
ok(P.rankOf(149).key === 'scrap' && P.rankOf(150).key === 'rookie', 'rank flips exactly at the threshold');
ok(P.rankOf(1e9).next === null && P.rankOf(1e9).pct === 1, 'top rank has nothing above it');
let last = -1, rising = true;
for (const r of P.RANKS) { if (r.at <= last) rising = false; last = r.at; }
ok(rising, 'rank thresholds go up');
const save = { money: 0, fame: 0, games: 0, owned: [], robots: [], paint: {}, ach: {} };
let got = P.check(save, { won: true, reason: 'ko', hpPct: 0.5, dealt: 100, lost: 1 });
const ids = got.map(a => a.id);
ok(ids.includes('first_win') && ids.includes('ko'), 'winning by knockout earns both the first win and the KO');
ok(!ids.includes('pit') && !ids.includes('flawless'), 'nothing is handed out that was not done');
ok(got.every(a => a.reward > 0), 'every achievement pays something');
got = P.check(save, { won: true, reason: 'ko', hpPct: 0.5, dealt: 100, lost: 1 });
ok(got.length === 0, 'the same achievement is never earned twice');
save.money = 5000;
ok(P.check(save, {}).map(a => a.id).includes('rich'), 'save-only achievements work without a fight');
ok(P.earned(save) === 3 && P.total === P.ACHIEVEMENTS.length, 'the counter matches what was earned');
const dup = P.ACHIEVEMENTS.map(a => a.id).filter((v, i, arr) => arr.indexOf(v) !== i);
ok(dup.length === 0, 'achievement ids are unique');
}
// knockout tournament
{
const T = RC.Tourney;
const me = () => ({ name: 'Me', build: RC.STARTER, paint: { body: 1, accent: 2 } });
let st = T.create({ me: me(), seed: 42 });
ok(st.field.length === T.SIZE, 'the bracket starts with eight robots');
ok(st.field.filter(e => e.player).length === 1, 'you are in it exactly once');
const names = st.field.map(e => e.name);
ok(new Set(names).size === names.length, 'no robot appears twice');
const p = T.pair(st);
ok(p && p[0].player && p[1] && !p[1].player, 'your first match is you against someone else');
// losing ends the run straight away
let lost = T.create({ me: me(), seed: 7 });
T.simOthers(lost);
T.advance(lost, false);
ok(lost.done && lost.out && !lost.won, 'a defeat knocks you out');
// winning everything takes three rounds and halves the field each time
st = T.create({ me: me(), seed: 42 });
const sizes = [];
let guard = 0;
while (!st.done && guard++ < 6) {
sizes.push(st.field.length);
T.simOthers(st);
T.advance(st, true);
}
ok(st.won && st.round === 3, 'three wins take the trophy');
ok(sizes.join() === '8,4,2', 'the field halves every round');
ok(st.prize === T.ROUND_PRIZE.reduce((a, b) => a + b, 0), 'every round prize is paid');
ok(st.log.filter(l => l.mine).length === 3, 'your three matches are in the log');
ok(st.log.filter(l => !l.mine).length === 4, 'the other matches were fought out too');
}
// live settings from the backend
{
const L = RC.Live, NOW = 1000000;
const ev = { id: 'e1', type: 'prize', prizeMul: 2, from: NOW - 100, to: NOW + 100 };
let r = L.parse(null, NOW, '20261115.1200');
ok(r.event === null && !r.onlineOff && !r.needsReload, 'no config = nothing special running');
ok(!r.locked('parts', 'wedge'), 'without a config every part stays available');
r = L.parse({ event: ev }, NOW, '');
ok(r.event && r.event.prizeMul === 2, 'an event inside its window is live');
ok(L.parse({ event: ev }, NOW + 500, '').event === null, 'after its end it is over');
ok(L.parse({ event: ev }, NOW - 500, '').event === null, 'before it starts it is not on yet');
ok(L.parse({ event: { id: 'x' } }, NOW, '').event !== null, 'an event without times runs all the time');
ok(L.parse({ event: { id: 'x', prizeMul: 99 } }, NOW, '').event.prizeMul === 5, 'a silly prize factor is capped');
r = L.parse({ unlock: { parts: ['wedge', 'saw'] } }, NOW, '');
ok(!r.locked('parts', 'wedge') && r.locked('parts', 'spinner'), 'only released parts are available');
ok(!r.locked('arenas', 'foundry'), 'a list that was not set locks nothing');
ok(!L.parse({ unlock: { parts: [] } }, NOW, '').locked('parts', 'spinner'), 'an empty list means everything is free');
ok(L.parse({ flags: { onlineOff: true } }, NOW, '').onlineOff, 'the kill switch comes through');
ok(L.parse({ flags: { tournament: true } }, NOW, '').tournament, 'the tournament switch opens the tournament');
ok(!L.parse({}, NOW, '').tournament, 'without the switch the tournament stays closed');
ok(L.parse({ event: { id: 't', tournament: true } }, NOW, '').tournament, 'an event can open the tournament too');
ok(L.parse({ build: { min: '20261115.1800' } }, NOW, '20261115.1200').needsReload, 'an older copy is asked to reload');
ok(!L.parse({ build: { min: '20261115.1800' } }, NOW, '20261115.1900').needsReload, 'a newer copy is left alone');
ok(!L.parse({ build: { min: '20261115.1800' } }, NOW, '').needsReload, 'without a build stamp we never nag');
for (const junk of ['nonsense', 42, [], { event: 'no object' }, { unlock: 5 }]) {
const p = L.parse(junk, NOW, '');
ok(p && p.event === null && typeof p.locked === 'function', 'broken config does not break the game: ' + JSON.stringify(junk));
}
}
// live multiplayer bracket
{
const LT = RC.LTourney;
ok(LT.order(['a','b'], 1).length === 2, '2 players = bracket of 2');
ok(LT.order(['a','b','c'], 1).length === 4, '3 players pad to 4 (one bye)');
ok(LT.order(['a','b','c','d','e'], 1).length === 8, '5 players pad to 8');
ok(LT.order(['a','b','c'], 1).filter(x => x === null).length === 1, 'exactly one bye for 3 players');
const o = LT.order(['bob','amy'], 1); // sorted-ish; host = lower uid
const m = LT.myMatch(o, {}, 'amy');
ok(m && m.round === 0 && m.opp === 'bob', 'first match is against the other player');
ok(LT.myMatch(o, {}, 'amy').host === ('amy' < 'bob'), 'lower uid hosts');
// a bye advances on its own, no match to play
const ob = LT.order(['x','y','z'], 2);
const bye = ob.indexOf(null) === 1 ? ob[0] : null; // the player paired with the null
// winner reported -> loser is out, winner is champion (2-player)
const win = o[0];
ok(LT.myMatch(o, { 0: { 0: win } }, win).done === true, 'the reported winner is done (champion)');
ok(LT.myMatch(o, { 0: { 0: win } }, o[1]) === null, 'the loser drops out');
// full 8: play it through, there is always one champion
const u = ['u0','u1','u2','u3','u4','u5','u6','u7'], O = LT.order(u, 9);
const R = {};
for (let r = 0; r < 3; r++) { const rows = LT.rounds(O, R)[r]; R[r] = {}; for (let i = 0; i < rows.length; i += 2) R[r][i/2] = rows[i] || rows[i+1]; }
const champ = LT.myMatch(O, R, O[0]);
ok(RC.LTourney.rounds(O, R).length === 4, 'an 8-player bracket has four columns');
ok(u.indexOf(champ.champion) >= 0, 'the champion is one of the players');
}
// body proportions designer
{
const base = { ...RC.STARTER };
const big = { ...base, body: { hx: 1.6, wx: 1.4, lx: 1.3 } };
const small = { ...base, body: { hx: 0.7, wx: 0.8, lx: 0.8 } };
const s0 = RC.stats(base), sb = RC.stats(big), ss = RC.stats(small);
ok(sb.h > s0.h && sb.len > s0.len && sb.wid > s0.wid, 'bigger body = bigger dimensions');
ok(ss.h < s0.h && ss.len < s0.len, 'smaller body = smaller dimensions');
ok(RC.validate(big).weight > RC.validate(base).weight, 'bigger body weighs more');
ok(sb.hp > s0.hp && ss.hp < s0.hp, 'size changes hit points');
ok(sb.top < s0.top, 'a heavy big build is slower');
ok(sb.topHeavy > 1 && RC.stats({ ...base, body: { hx: 0.8, wx: 1.4, lx: 1.3 } }).topHeavy < 1, 'tall = top-heavy, flat = stable');
ok(RC.bodyOf({ body: { hx: 9, wx: 9, lx: 9 } }).hx === 1.6, 'absurd values are clamped');
ok([sb.hp, sb.len, sb.mass, sb.top].every(Number.isFinite), 'no NaN at the extreme');
// a big heavy build can bust the class limit
RC.setClass('light');
ok(RC.validate({ ...RC.STARTER, body: { hx: 1.6, wx: 1.4, lx: 1.3 } }).weight > RC.validate(RC.STARTER).weight, 'body weight counts toward the limit');
RC.setClass('medium');
// builds without a body are unchanged
ok(RC.validate(RC.STARTER).weight === RC.validate({ ...RC.STARTER, body: { hx: 1, wx: 1, lx: 1 } }).weight, 'default body = no change');
}
console.log(fails ? `${fails} failure(s)` : 'all ok'); console.log(fails ? `${fails} failure(s)` : 'all ok');
process.exit(fails ? 1 : 0); process.exit(fails ? 1 : 0);