feat(net)!: client on server-run fights, websocket lobby, server economy (P1-5, P1-6, P1-7, P2-3, P2-4)

- net.js: REST + one WebSocket with reconnect; single-flight refresh shared across tabs; ?slot=N
- lobby.js / netfight.js: server owns presence, challenges and the fight; client shows snapshots
- game.js: every workshop change goes through RC.Eco via act() (server-checked online);
  results, rewards and achievements come from the server (match.end)
- ranking/live/cloudsave on the new REST endpoints; online tournament removed until P2-6

BREAKING CHANGE: needs the new server (protocol v1); old online saves are not migrated.
This commit is contained in:
Benjamin Oezcan
2026-11-19 02:09:07 +01:00
parent 4bd85f68bf
commit 85a19ba242
13 changed files with 494 additions and 798 deletions

View File

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