Files
Robot-Clash/game/game.js
Michi a494290548 fix(net): interpolate between snapshots to absorb jitter (P1-6)
netfight eased to the newest snapshot with no buffer, so a jittery
client's robot stalled then jumped. Render ~120 ms in the past between
the two bracketing snapshots instead. Dev params ?netlag/?interp/
?netprobe reproduce it; unit test for the interp math + a Playwright
lag test (tests/e2e/netlag.spec.js).
2026-11-19 19:46:54 +01:00

1388 lines
87 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Robot Clash - game frame: intro, title, accounts, settings, shop, league, fight, result, audio, scores.
Logic lives in parts.js / robot.js / combat.js / ai.js (no DOM), the 3D view in render3d.js,
the shop panel in shop.js, accounts in profiles.js. Texts: lang.js via t('key').
Credits line stays on the title screen. */
(function () {
'use strict';
const $ = Kit.$;
const W = 1280, H = 720; // design size of the stage (16:9, higher res = denser UI)
const ID = 'robotclash'; // localStorage prefix
// 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; }
// Credits (standard for every game): shown on the title screen, links open in the normal browser
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';
// build stamp comes from build-web.mjs; identifies the exact release in a leaked copy
const BUILD = (typeof window !== 'undefined' && window.RC_BUILD) || '';
const CREDITS = `© 2026 <a href="${SITE}" target="_blank" rel="noopener">Michael Media</a>`
+ ` · <a href="${DISCORD}" target="_blank" rel="noopener">Discord</a>`
+ (BUILD ? ` · <span class="build">${BUILD}</span>` : '');
// Soft domain lock: the published build only runs on our own site. Local file, localhost and the
// exe always run. This stops a lazy re-upload, nothing more - the file itself can always be copied.
const HOSTS = ['localhost', '127.0.0.1', ''];
// own hosts: any subdomain of michael-media.de (roboclash.michael-media.de) plus the Hetzner IP
const hostOk = () => location.protocol === 'file:' || HOSTS.includes(location.hostname)
|| /(^|\.)michael-media\.de$/.test(location.hostname) || location.hostname === '91.99.166.238'
|| (Kit.host && Kit.host.exe) || document.documentElement.classList.contains('exe');
// ---------------------------------------------------------------- services
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 GM = {}; // feature modules, created at the end (see 'feature modules')
const store = Kit.store(ID);
// steer: 'simple' (keys = screen direction) | 'tank' · diff: 'easy' | 'normal' | 'hard' · autofire: weapon fires by itself in reach
const settings = Object.assign({ gfx: 'medium', intro: true, steer: 'tank', autofire: true, cam: 'fpv', arena: 'random', quiet: false, comfort: true }, store.get('settings', {}));
// v2: Michael found "simple" steering worse -> tank is the default again, old saved choice reset once
// v3: fights start in first person (cockpit) -> old saved camera reset once
if (!settings.v || settings.v < 2) settings.steer = 'tank';
if (!settings.v || settings.v < 3) { settings.cam = 'fpv'; settings.v = 3; store.set('settings', settings); }
// difficulty: player hit points x, AI skill +
// 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 accounts = RC.Accounts(ID);
const newSave = () => ({
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),
paint: { body: 0xff7a1a, accent: 0x15171b }, robotName: 'Clank', flag: 'XX', flagSet: false, tutorialSeen: false, ach: {}, tour: null, cls: 'medium', leagues: null,
missions: null, mseed: (Math.random() * 1e9) | 0, unlockedPaints: null, unlockedSchemes: null,
robots: [], active: 0, // hangar: saved robot builds; the active one mirrors build/paint/robotName
});
const MAX_ROBOTS = 6;
const newRobotDef = n => ({ name: n || 'Robot', build: Object.assign({}, RC.STARTER), paint: { body: 0xff7a1a, accent: 0x15171b, decal: null, drawn: false } });
// keep the active hangar slot in sync with the live build/paint/robotName before saving
function syncActive() {
if (!save || !save.robots || !save.robots[save.active]) return;
const r = save.robots[save.active];
r.name = save.robotName; r.build = save.build; r.paint = save.paint;
}
let slot = null, save = null; // per account, set by enterAccount()
// 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 }; };
// 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'],
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 DEV = new URLSearchParams(location.search);
if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop
const netProbe = DEV.has('netprobe') ? (window.__probe = []) : null; // dev: records opponent robot pos for the lag test
const net = RC.Net(NET_CFG);
const rank = RC.Ranking(net); // online ranking, computed by the server
const cloud = RC.CloudSave(net); // campaign copy for registered accounts (online saves live on the server)
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() { isDev = !fbUser() ? true : !!fbUser().admin; }
// ---------------------------------------------------------------- online (game/online.js)
function act(...a) { return GM.online.act(...a); }
function endOnlineFight(...a) { return GM.online.endOnlineFight(...a); }
function onlineFightLost(...a) { return GM.online.onlineFightLost(...a); }
function onlineFlush(...a) { return GM.online.onlineFlush(...a); }
function onlinePull(...a) { return GM.online.onlinePull(...a); }
function onlinePush(...a) { return GM.online.onlinePush(...a); }
function renderLobby(...a) { return GM.online.renderLobby(...a); }
function showLobby(...a) { return GM.online.showLobby(...a); }
function showOnlineLogin(...a) { return GM.online.showOnlineLogin(...a); }
function startOnline(...a) { return GM.online.startOnline(...a); }
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`;
const lobby = net.enabled ? RC.Lobby({ net }) : null;
// F3 (or ?net): network overlay - ping graph + where lag comes from (netstats.js / netoverlay.js)
const netStats = RC.NetStats();
const netOverlay = net.enabled ? RC.NetOverlay({ stats: netStats, net, t, mount: $('stage') }) : null;
if (netOverlay && DEV.has('net')) netOverlay.toggle(true);
const fx = Kit.fx();
const input = Kit.input({
keys: {
ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', ArrowRight: 'right', d: 'right',
' ': 'fire', Shift: 'fire2', e: 'fire2', g: 'fire3', p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok', c: 'cam',
},
onPress(a) {
if (mode === 'intro') { skipIntro(); return; }
if (a === 'pause') togglePause();
else if (a === 'mute') toggleMute();
else if (a === 'cam' && mode === 'fight') cycleCam();
else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); }
},
});
// ---------------------------------------------------------------- sound (game/sfx.js)
const SFX = RC.GameSfx(audio, settings);
// rate limit for repeating inputs (gamepad start button)
const lastT = {};
const every = (k, ms) => { const n = performance.now(); if (lastT[k] && n - lastT[k] < ms) return false; lastT[k] = n; return true; };
// ---------------------------------------------------------------- view
const cv = $('cv');
let ctx = cv.getContext('2d');
let view = null;
try { view = RC.Render($('gl'), W, H); view.setQuality(settings.gfx); if (view.setComfort) view.setComfort(settings.comfort); } catch (err) { console.error(err); }
// cap upscaling so the UI does not get huge on big / high-DPI screens (960x540 stage, max ~2x)
Kit.fit($('app'), { max: 2.0, margin: document.documentElement.classList.contains('exe') ? 1 : 0.98,
canvases: [[cv, W, H]], onFit(sc) { ctx = cv.getContext('2d'); if (view) view.resize(sc); } });
Kit.host.dragArea(document.body);
const hex = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
const img = name => Kit.asset('assets/Sprites/' + name);
function backdrop(name) { $('bgimg').style.backgroundImage = name ? `url("${img(name)}")` : 'none'; }
$('icoMoney').innerHTML = `<img src="${img('ico_credits.png')}" alt="" onerror="this.classList.add('missing')">`;
$('icoFame').innerHTML = `<img src="${img('ico_fame.png')}" alt="" onerror="this.classList.add('missing')">`;
const shop = RC.Shop({
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
onHangarView: el => renderHangar(el), // Hangar tab content
onSlot: slot => { const on = slot === 'weapon'; if (on !== editorOpen) { editorOpen = on; view.freeze(on); } if (on) view.setEditWeapon(editSel); else { const wp = $('wplace'); if (wp) wp.classList.add('hide'); } },
onWeaponTab: () => renderWeaponEditor(), // weapon tab fills #cards with the catalog + #wplace with placement
weaponPreview: () => { // build with the PICKED weapon added, so the warning shows before buying
if (!save) return null;
const weps = save.build.weapons || [];
if (!wPrev || weps.length >= RC.MAX_WEAPONS) return null; // picking = intent to mount -> preview the added cost
return Object.assign({}, save.build, { weapons: weps.concat([{ id: wPrev, side: 'front', up: 0 }]) });
},
onPaintTab: el => paintTab(el), // paint tab: 3 slots + colours + the inline painter
onPaintLeave: () => paintLeave(),
locked: id => LIVE.locked('parts', id), // event/unlock: part not released yet
sfx: SFX,
});
// own artwork on the robot (painter.js): transparent 512x256 layer, saved per account as PNG data
const layer = document.createElement('canvas');
layer.width = 512; layer.height = 256;
const paintObj = () => ({ body: save.paint.body, accent: save.paint.accent, layer, drawn: painter.isOpen || !!save.paint.drawn });
const painter = RC.Painter({
t, layer, view, sfx: SFX, getPaint: paintObj,
onLive: () => view.setPaint(paintObj()),
onDone: () => {
const art = painter.hasArt();
save.paint.decal = art ? layer.toDataURL('image/png') : null; save.paint.drawn = art;
persist(); view.showGarage(save.build, paintObj());
},
onCancel: () => view.showGarage(save.build, paintObj()),
});
if ($('bPaint')) $('bPaint').onclick = () => { SFX.click(); painter.open(); view.showGarage(save.build, paintObj()); };
// drag on the robot turns it; in the build editor, grab a weapon to place it instead
let drag = null, wdrag = false, editorOpen = false, editSel = 0, wPrev = null;
$('gl').addEventListener('pointerdown', e => {
if (mode !== 'garage') return;
if (editorOpen && save) {
const hit = view.pickWeaponAt(e.clientX, e.clientY);
if (hit >= 0) { editSel = hit; wPrev = save.build.weapons[hit] && save.build.weapons[hit].id; view.setEditWeapon(editSel); wdrag = true; $('gl').setPointerCapture(e.pointerId); renderWeaponEditor(); return; }
}
drag = e.clientX; $('gl').setPointerCapture(e.pointerId);
});
$('gl').addEventListener('pointermove', e => {
if (wdrag) {
const mnt = view.dragWeapon(e.clientX, e.clientY);
if (mnt && save && save.build.weapons[editSel]) { save.build.weapons[editSel].side = mnt.side; save.build.weapons[editSel].up = mnt.up; }
return;
}
if (drag != null) { view.turn(e.clientX - drag); drag = e.clientX; }
});
$('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 */ } });
// ---------------------------------------------------------------- workshop (game/workshop.js)
function paintLeave(...a) { return GM.workshop.paintLeave(...a); }
function paintTab(...a) { return GM.workshop.paintTab(...a); }
function refreshEditorRobot(...a) { return GM.workshop.refreshEditorRobot(...a); }
function renderHangar(...a) { return GM.workshop.renderHangar(...a); }
function renderWeaponEditor(...a) { return GM.workshop.renderWeaponEditor(...a); }
// ---------------------------------------------------------------- state
let mode = 'intro'; // intro | title | account | garage | league | fight | pause | result
let F = null; // current fight
const show = (id, on) => $(id).classList.toggle('hide', !on);
const overlay = $('overlay');
function card(html, opt = {}) {
overlay.innerHTML = `<div class="card" style="${opt.wide ? 'min-width:720px' : ''}">${html}</div>`;
overlay.classList.remove('hide'); overlay.classList.toggle('clear', !!opt.clear);
overlay.style.backgroundImage = opt.bg ? `linear-gradient(rgba(5,6,10,.55), rgba(5,6,10,.75)), url("${img(opt.bg)}")` : '';
}
function hideOverlay() { overlay.classList.add('hide'); overlay.innerHTML = ''; overlay.style.backgroundImage = ''; }
// fade a menu in once; the class is dropped again so live lists (lobby) do not flicker on every refresh
let enterT = 0;
function overlayEnter() { overlay.classList.add('enter'); clearTimeout(enterT); enterT = setTimeout(() => overlay.classList.remove('enter'), 220); }
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const seasonMul = () => 1 + (save.season - 1) * 0.5;
const weaponName = b => { const ws = RC.weaponsOf(b); const main = ws.length ? ws[0].part.name + (ws.length > 1 ? ' ×' + ws.length : '') : t('unarmed'); return main + (b.tower ? ' + ' + RC.PARTS[b.tower].name : ''); };
// league robots dressed like their ComfyGen portraits (looks.js)
const oppPaint = o => (RC.LOOKS && RC.LOOKS[o.id] ? Object.assign({}, o.paint, { layer: RC.lookLayer(o.id, o.paint), drawn: true, look: RC.LOOKS[o.id] }) : o.paint);
// decode an online opponent's own drawing (data URL) into a canvas before the arena is built, so it shows on their robot
const oppDecalCv = (() => { const c = document.createElement('canvas'); c.width = 512; c.height = 256; return c; })();
function prepOpp(opp, done) {
const d = opp && opp.paint && opp.paint.decal;
if (!d) { done(); return; }
RC.layerFromData(oppDecalCv, d, () => { opp.paint.layer = oppDecalCv; opp.paint.drawn = true; done(); });
}
const fbUser = () => (net && net.enabled ? net.auth.current : null);
const fbAcc = () => (fbUser() && !fbUser().guest ? fbUser() : null); // real (e-mail) account
const playerName = () => (fbUser() ? fbUser().name : accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : '');
// save slot: server account -> robotclash.save.fb_<uid>, else local profile / guest
// 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 server 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() {
$('hMoney').textContent = save ? Kit.fmt(save.money) : '–';
$('hFame').textContent = save ? Kit.fmt(save.fame) : '–';
$('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') : '👤 –';
$('bMute').textContent = audio.muted ? '🔇' : '🔊';
$('bMute').title = (audio.muted ? t('sound_off') : t('sound_on')) + ' (M)';
}
function setScreen(m) {
if (m !== 'garage' && painter.isOpen) painter.close();
if (mode === 'garage' && m !== 'garage') cloudFlush(); // settle the cloud save when leaving the workshop
if (m !== 'garage' && editorOpen) { editorOpen = false; view.freeze(false); }
if (m !== 'title' && titleRankSub) { titleRankSub.close(); titleRankSub = null; } // stop the title's live ranking
if (m !== mode) overlayEnter();
mode = m;
document.body.dataset.mode = m; // CSS shows/places the HUD per screen
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('fightHud', m === 'fight' || m === 'pause' || m === 'result');
backdrop(m === 'garage' ? 'bg_workshop.jpg' : null);
}
// ---------------------------------------------------------------- intro + title
let introCue = 0;
let gateDone = false;
function startGate(next) {
if (gateDone) { next(); return; }
gateDone = true;
setScreen('intro'); // defined UI state while the gate is up (HUD stays hidden)
const logo = `<img class="tlogoimg" src="${Kit.asset('assets/Sprites/logo.png')}" alt="ROBOT CLASH"
onerror="this.remove()" onload="this.nextElementSibling.style.display='none'"><div class="big">ROBOT CLASH</div>`;
overlay.innerHTML = `<div class="title"><div class="tpanel">${logo}
<div class="hazbar"></div><p class="tag">${t('click_start')}</p>
<p class="credits">${CREDITS}</p></div></div>`;
overlay.classList.remove('hide'); overlay.classList.remove('clear');
overlay.style.backgroundImage = `url("${img('bg_start.jpg')}")`; // start screen backdrop (ComfyGen)
const go = e => {
if (e) { e.stopPropagation(); if (e.preventDefault) e.preventDefault(); } // must not also skip the intro
removeEventListener('pointerdown', go, true); removeEventListener('keydown', go, true);
if (audio.unlock) audio.unlock();
next();
};
addEventListener('pointerdown', go, true);
addEventListener('keydown', go, true);
}
function startIntro() {
setScreen('intro');
hideOverlay();
if (!view) { showTitle(); return; }
const a = RC.LEAGUE[7], b = RC.LEAGUE[4];
view.showIntro([a.build, b.build], [oppPaint(a), oppPaint(b)]);
introCue = 0;
audio.music('music_title');
if (!settings.intro) view.skipIntro();
}
function skipIntro() { if (view) view.skipIntro(); }
stageClick(() => { if (mode === 'intro') skipIntro(); });
function stageClick(fn) { $('stage').addEventListener('pointerdown', fn); }
function introTick() {
if (mode !== 'intro' || !view) return;
const it = view.introTime;
for (const [at, f] of [[0.4, SFX.clunk], [0.62, SFX.clunk], [2.2, SFX.clunk], [2.5, SFX.clunk], [3.4, SFX.clunk]]) {
if (introCue < at && it >= at) f();
}
introCue = it;
if (it >= RC.INTRO_END) showTitle();
}
function showTitle() {
setScreen('title');
audio.music('music_title');
const fb = net && net.enabled;
const acc = fb ? fbAcc() : (accounts.current && !accounts.current.guest ? accounts.current : null);
const online = fb ? `<button id="bOnline">🌍 ${t('online_play')}</button>` : '';
const btns = acc
? `<button class="primary" id="bPlay">${t('play_as', { name: esc(acc.name) })}</button>${online}<button id="bSwitch">${t('switch_account')}</button>`
: `<button class="primary" id="bLogin">${t('login')}</button><button id="bReg">${t('register')}</button><button id="bGuest">${t('play_guest')}</button>${online}`;
// logo picture when ComfyGen made one, otherwise the lettering (never both, never nothing)
const logo = `<img class="tlogoimg" src="${Kit.asset('assets/Sprites/logo.png')}" alt="ROBOT CLASH"
onerror="this.remove()" onload="this.nextElementSibling.style.display='none'"><div class="big">ROBOT CLASH</div>`;
overlay.innerHTML = `<div class="title"><div class="tpanel">
${logo}
<div class="tag">${t('menu_text')}</div>
${liveBanner()}
<div class="hazbar"></div>
<div class="tmenu">${btns}</div>
<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>${save ? `<button id="bAch">🏅 ${t('achievements')}</button>` : ''}${rank.enabled ? `<button id="bRank">🏆 ${t('ranking')}</button>` : ''}<button id="bLegal">§ ${t('legal')}</button></div>
<p class="credits">${CREDITS}</p></div>${rank.enabled ? `<div class="trank"><h3>🏆 ${t('ranking')} <span class="livedot">● ${t('rank_live')}</span></h3><ol id="trankList"><li class="trmuted">${t('loading')}</li></ol></div>` : ''}</div>`;
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(); }; };
on('bPlay', () => enterAccount());
on('bOnline', () => startOnline());
on('bSwitch', () => { signOut(); fb ? showOnlineLogin(false, null, 'career') : showLogin(); });
on('bLogin', () => (fb ? showOnlineLogin(false, null, 'career') : showLogin()));
on('bReg', () => (fb ? showOnlineLogin(true, null, 'career') : showRegister()));
on('bGuest', () => { if (fbAcc()) net.auth.logout(); accounts.guest(); enterAccount(); });
on('bSet', () => showSettings(showTitle));
on('bHelp', () => showHelp(showTitle));
on('bLang', () => L.next());
on('bAch', () => showAchievements(showTitle));
on('bRank', () => showRanking(showTitle));
on('bLegal', () => showLegal(showTitle));
hud();
if (rank.enabled) startTitleRank();
}
// right-side live ranking on the title: names fade in from the bottom up, re-triggered on every live update
function startTitleRank() {
const el = $('trankList'); if (!el) return;
if (titleRankSub) titleRankSub.close();
titleRankSub = rank.watch(rows => {
if (mode !== 'title') return;
const list = $('trankList'); if (!list) return;
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
const r8 = rows.slice(0, 8), n = r8.length;
list.innerHTML = n ? r8.map((r, i) => `<li class="trow ${r.key === myUid ? 'me' : ''}" style="animation-delay:${((n - 1 - i) * 0.08).toFixed(2)}s">`
+ `<span class="trk">${i + 1}</span><span class="trf">${flagHtml(r.flag || 'XX')}</span>`
+ `<span class="trn">${esc(r.name)}</span><span class="trv">⭐ ${Kit.fmt(r.fame)}</span></li>`).join('')
: `<li class="trmuted">${t('no_scores')}</li>`;
});
}
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
// ---------------------------------------------------------------- accounts
function showLogin(errKey) {
setScreen('account');
const profs = accounts.list();
card(`<h2>${t('login')}</h2>
${profs.length ? `<p class="muted">${t('local_profiles')}</p><div class="profiles">${profs.map(p => `<button data-n="${esc(p.name)}">${esc(p.name)}</button>`).join('')}</div>` : ''}
<div class="form"><label>${t('f_name')}</label><input type="text" id="fName" maxlength="18" autocomplete="username">
<label>${t('f_pass')}</label><input type="password" id="fPass" autocomplete="current-password">
<label class="chk"><input type="checkbox" id="fRem" checked> ${t('f_remember')}</label></div>
<div class="err" id="fErr">${errKey ? t(errKey) : ''}</div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('login')}</button></div>
<p class="muted">${t('no_account')} <button class="link" id="bToReg">${t('register')}</button></p>
<p class="muted" style="font-size:11px">${t('local_note')}</p>`, { bg: 'bg_title.jpg' });
overlay.querySelectorAll('.profiles button').forEach(b => { b.onclick = () => { $('fName').value = b.dataset.n; $('fPass').focus(); }; });
$('bBack').onclick = () => { SFX.click(); showTitle(); };
$('bToReg').onclick = () => { SFX.click(); showRegister(); };
$('bGo').onclick = async () => {
const r = await accounts.login($('fName').value, $('fPass').value, $('fRem').checked);
if (!r.ok) { SFX.deny(); $('fErr').textContent = t('e_' + r.error); return; }
SFX.click(); enterAccount();
};
formKeys();
setTimeout(() => $(profs.length ? 'fPass' : 'fName').focus(), 50);
}
function showRegister() {
setScreen('account');
card(`<h2>${t('register')}</h2><p>${t('register_text')}</p>
<div class="form"><label>${t('f_name')}</label><input type="text" id="fName" maxlength="18" autocomplete="username">
<label>${t('f_pass')}</label><input type="password" id="fPass" autocomplete="new-password">
<label>${t('f_pass2')}</label><input type="password" id="fPass2" autocomplete="new-password"></div>
<label class="chk"><input type="checkbox" id="fConsent"> ${t('consent_pre')} <button type="button" class="link" id="fPriv">${t('legal_privacy')}</button></label>
<div class="err" id="fErr"></div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('register_go')}</button></div>
<p class="muted" style="font-size:11px">${t('local_note')}</p>`, { bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showTitle(); };
$('fPriv').onclick = () => { SFX.click(); showLegal(showRegister, 'privacy'); };
$('bGo').onclick = async () => {
if (!$('fConsent').checked) { SFX.deny(); $('fErr').textContent = t('consent_required'); return; }
if ($('fPass').value !== $('fPass2').value) { SFX.deny(); $('fErr').textContent = t('e_pass_match'); return; }
const r = await accounts.register($('fName').value, $('fPass').value);
if (!r.ok) { SFX.deny(); $('fErr').textContent = t('e_' + r.error); return; }
SFX.buy(); enterAccount(true);
};
formKeys();
setTimeout(() => $('fName').focus(), 50);
}
// Enter in a form = primary button; typing never reaches the game keys
function formKeys() {
overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => {
e.stopPropagation();
if (e.key === 'Enter') { const b = overlay.querySelector('button.primary'); if (b) b.click(); }
}));
}
function loadSave() {
slot = Kit.saveSlot(saveKey(), newSave);
save = slot.load();
repairSave();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (gameMode === 'online') onlinePull(); else cloudPull();
}
// campaign + registered account: fetch the cloud copy; take it if newer, else push the local copy up
function cloudPull() {
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)) {
save = cl; repairSave(); slot.save(save); hud(); shop.reset();
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(save);
}
});
}
function enterAccount(fresh) {
loadSave();
refreshDev();
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
if (fresh && who) save.robotName = who.name.slice(0, 18);
persist();
hud();
shop.reset();
ensureFlag(() => { // pick a country first, then tutorial / workshop
if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); startTutorial(openGarage); } else openGarage();
});
}
// saves from older versions: missing parts, invalid ids, hangar migration
function repairSave() {
save.owned = (save.owned || []).filter(id => RC.PARTS[id]);
if (save.flagSet === undefined) save.flagSet = !!(save.flag && save.flag !== 'XX'); // old saves that already picked a flag keep it
if (save.mseed == null) save.mseed = (Math.random() * 1e9) | 0; // stable per-save mission seed
const rewardPaint = c => (RC.PAINT_REWARDS || []).includes(c);
if (!Array.isArray(save.unlockedPaints)) save.unlockedPaints = RC.PAINTS.filter(c => !rewardPaint(c)); // all but the reward colours
if (!Array.isArray(save.unlockedSchemes)) save.unlockedSchemes = RC.SCHEMES.map((_, i) => i); // all schemes free
// 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
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.active = 0;
}
save.active = Kit.clamp(save.active | 0, 0, save.robots.length - 1);
const fixBuild = b => {
// migrate single weapon (+ Plan-10 mount) to the weapons list; then drop the old fields
if (!Array.isArray(b.weapons)) b.weapons = RC.weaponsOf(b).map(w => ({ id: w.id, side: w.side, up: w.up }));
delete b.weapon; delete b.mount;
b.weapons = b.weapons.filter(w => w && RC.PARTS[w.id] && RC.PARTS[w.id].slot === 'weapon').slice(0, RC.MAX_WEAPONS);
for (const w of b.weapons) { if (!RC.MOUNTS[w.side]) w.side = 'front'; w.up = Math.max(-0.3, Math.min(0.6, +w.up || 0)); }
for (const sl of RC.SLOTS) {
if (sl === 'weapon') continue;
if (b[sl] && !RC.PARTS[b[sl]]) b[sl] = null;
if (b[sl] && !save.owned.includes(b[sl])) save.owned.push(b[sl]);
}
for (const sl of Object.keys(RC.REQUIRED)) if (!b[sl]) { b[sl] = RC.STARTER[sl]; if (!save.owned.includes(RC.STARTER[sl])) save.owned.push(RC.STARTER[sl]); }
};
for (const r of save.robots) { r.build = r.build || Object.assign({}, RC.STARTER); r.paint = r.paint || { body: 0xff7a1a, accent: 0x15171b }; r.name = r.name || 'Robot'; fixBuild(r.build); }
// load the active robot into the live fields the rest of the game uses
const a = save.robots[save.active];
save.build = a.build; save.paint = a.paint; save.robotName = a.name;
save.beaten = Kit.clamp(save.beaten | 0, 0, RC.LEAGUE.length - 1);
// 3 paint save slots (account-wide presets); first slot seeds from the current paint
if (!Array.isArray(save.paintSlots) || save.paintSlots.length !== 3) {
const base = { body: save.paint.body, accent: save.paint.accent };
save.paintSlots = [{ ...base, decal: save.paint.decal || null, drawn: !!save.paint.drawn },
{ ...base, decal: null, drawn: false }, { ...base, decal: null, drawn: false }];
}
save.paintSlot = Kit.clamp(save.paintSlot | 0, 0, 2);
}
function signOut() {
persist();
cloudFlush(); // push now, while we still have the auth token
if (lobby) { lobby.leave(); lobbyRows = []; }
if (net && net.enabled) net.auth.logout();
accounts.logout(); save = null; slot = null; F = null; hud();
}
function logout() { signOut(); startIntroOrTitle(); }
function startIntroOrTitle() { if (view) { const a = RC.LEAGUE[7], b = RC.LEAGUE[4]; view.showIntro([a.build, b.build], [oppPaint(a), oppPaint(b)]); view.skipIntro(); } showTitle(); }
$('hUser').onclick = () => {
if (!save || mode === 'fight' || mode === 'pause') return;
SFX.click();
const back = currentBack(), who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
card(`<h2>${t('account')}</h2><p>${who ? t('logged_in_as', { name: esc(who.name) }) + (who.email ? `<br><span class="muted">${esc(who.email)}</span>` : '') : t('guest_text')}</p>
<div class="row"><button id="bOut">${who ? t('logout') : t('to_title')}</button><button class="primary" id="bBack">${t('back')}</button></div>`);
$('bOut').onclick = () => { SFX.click(); logout(); };
$('bBack').onclick = () => { SFX.click(); back(); };
};
function currentBack() { return mode === 'garage' ? openGarage : mode === 'league' ? showLeague : mode === 'result' ? openGarage : mode === 'title' ? showTitle : save ? openGarage : showTitle; }
// ---------------------------------------------------------------- pages (game/pages.js)
function ensureFlag(...a) { return GM.pages.ensureFlag(...a); }
function boardHtml(...a) { return GM.pages.boardHtml(...a); }
function fillBoard(...a) { return GM.pages.fillBoard(...a); }
function liveBanner(...a) { return GM.pages.liveBanner(...a); }
function showAchievements(...a) { return GM.pages.showAchievements(...a); }
function showHelp(...a) { return GM.pages.showHelp(...a); }
function showLegal(...a) { return GM.pages.showLegal(...a); }
function showMissions(...a) { return GM.pages.showMissions(...a); }
function showRanking(...a) { return GM.pages.showRanking(...a); }
function showSettings(...a) { return GM.pages.showSettings(...a); }
function startTutorial(...a) { return GM.pages.startTutorial(...a); }
let rankSub = null, titleRankSub = null, boardFame = {}, boardIdx = {};
// ---------------------------------------------------------------- shop + league
function openGarage() {
hideOverlay();
setScreen('garage');
view.showGarage(save.build, paintObj());
audio.music('music_garage');
shop.render(); hud(); updateShopBar();
$('zIn').onclick = () => { SFX.click(); view.zoomGarage(1.18); };
$('zOut').onclick = () => { SFX.click(); view.zoomGarage(1 / 1.18); };
}
$('bGMenu').onclick = () => { SFX.click(); persist(); startIntroOrTitle(); };
$('bGMode').onclick = () => { SFX.click(); switchMode(gameMode === 'online' ? 'campaign' : 'online'); };
const onlineUsable = () => !!(net && net.enabled && !LIVE.onlineOff);
if (!onlineUsable()) $('bGMode').style.display = 'none';
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
$('bLeague').onclick = () => { SFX.click(); if (gameMode === 'online') { persist(); startOnline('lobby'); } else showLeague(); };
if ($('bRankG')) $('bRankG').onclick = () => { SFX.click(); showRanking(openGarage); };
if ($('bMissions')) $('bMissions').onclick = () => { SFX.click(); showMissions(openGarage); };
function updateShopBar() {
const on = gameMode === 'online';
$('bGMode').style.display = onlineUsable() ? '' : 'none';
$('bGMode').textContent = on ? '🏆 ' + t('to_campaign') : '🌍 ' + t('to_online');
$('bLeague').textContent = on ? t('to_lobby') : t('to_league');
const rg = $('bRankG'); if (rg) rg.style.display = (on && rank.enabled) ? '' : 'none'; // ranking is online-only
const mb = $('bMissions'); // missions are campaign-only
if (mb) { ensureMissions(); mb.style.display = on ? 'none' : ''; mb.classList.toggle('alert', !on && RC.Missions.active(save).some(m => m.done)); }
}
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() {
if (gameMode !== 'campaign') { switchMode('campaign'); return; } // league is campaign-only
setScreen('league');
const cards = RC.LEAGUE.map((o, i) => {
const cls = i < save.beaten ? 'done' : i === save.beaten ? 'next' : 'locked';
return `<div class="opp ${cls}" data-i="${i}">${RC.pic('opp_' + o.id, '🤖')}<div class="nm">${i + 1}. ${o.name}</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>`;
}).join('');
const tabs = RC.CLASSES.map(c => {
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>` : ''}`,
{ 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]); }; });
// beaten opponents: repeatable exhibition fights for half the prize (steady income)
overlay.querySelectorAll('.opp.done').forEach(el => { el.style.cursor = 'pointer'; el.title = t('exhibition_note'); el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[+el.dataset.i], true); }; });
$('bFight').onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); };
$('bBack').onclick = () => { SFX.click(); openGarage(); };
}
function showVs(opp, exhibition) {
const me = RC.stats(save.build), en = RC.stats(opp.build);
const line = s => `${Math.round(s.hp)} ${t('m_hp')} · ${Math.round(s.reduce * 100)}% ${t('m_armour')} · ${s.top.toFixed(1)} m/s`;
const mine = view.portrait(save.build, paintObj());
const myPic = mine ? `<span class="pic"><img src="${mine}" alt="" draggable="false"></span>` : RC.pic('icon', '🤖');
card(`<div class="vs"><div class="side">${myPic}<div class="nm">${esc(save.robotName)}</div><div class="muted">${weaponName(save.build)}</div><div class="muted">${line(me)}</div></div>
<div class="mid">VS</div>
<div class="side">${RC.pic('opp_' + opp.id, '🤖')}<div class="nm">${opp.name}</div><div class="muted">${weaponName(opp.build)}</div><div class="muted">${line(en)}</div></div></div>
<p>${t('style_' + opp.style)}</p>${exhibition ? `<p class="muted">${t('exhibition_note')}</p>` : ''}
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${exhibition ? t('exhibition_btn') : t('fight_go_btn')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showLeague(); };
$('bGo').onclick = () => { SFX.click(); startFight(opp, false, exhibition); };
}
// ---------------------------------------------------------------- fight
// 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();
const D = BASE;
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
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 arenaId = DEV.get('arena') ? DEV.get('arena')
: (LIVE.event && LIVE.event.arena && !online) ? LIVE.event.arena
: 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);
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) { // the server runs the fight, we show it (interpolated); dev: ?netlag=base,jit[,seed], ?interp=ms
netStats.reset();
let lag = null; const nl = DEV.get('netlag');
if (nl) { const [b, j, sd] = nl.split(',').map(Number); lag = { base: b || 0, jit: j || 0, seed: sd || 1 }; }
F.nf = RC.NetFight({ net, seat: online.seat, stats: netStats, interp: +DEV.get('interp') || 0, lag });
}
// dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing)
if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 });
if (DEV.has('ff')) {
F.count = 0; F.beat = 0;
const ai2 = F.auto || RC.AI.create({ style: 'brawler', skill: 0.5, seed });
for (let i = 0; i < (+DEV.get('ff') || 20) * 60 && !s.result; i++) {
RC.Combat.step(s, 1 / 60, [ai2.think(s, s.robots[0], s.robots[1], 1 / 60), F.brain.think(s, s.robots[1], s.robots[0], 1 / 60)]);
s.events.length = 0;
}
}
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;
$('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(opp.build);
$('fH0').style.background = barCol(save.paint); $('fH1').style.background = barCol(opp.paint);
fx.clear();
setScreen('fight');
audio.music('music_fight');
gateOpen();
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';
buildCds();
buildDmg(0, save.build); buildDmg(1, opp.build);
fightHud();
}
function pad() {
const gp = navigator.getGamepads ? Array.from(navigator.getGamepads()).find(Boolean) : null;
if (!gp) return null;
const dz = v => (Math.abs(v) < 0.18 ? 0 : v);
const b = i => !!(gp.buttons[i] && gp.buttons[i].pressed);
if (b(9) && every('gpStart', 400)) togglePause();
return { throttle: -dz(gp.axes[1] || 0) + (b(12) ? 1 : 0) - (b(13) ? 1 : 0), turn: dz(gp.axes[0] || 0) + (b(15) ? 1 : 0) - (b(14) ? 1 : 0),
fire: b(0) || b(7), fire2: b(1) || b(2) || b(6), fire3: b(3) || b(5) };
}
// up/down + left/right from keys, touch pad and gamepad
function playerInput() {
let ky = (input.down('up') ? 1 : 0) - (input.down('down') ? 1 : 0);
let kx = (input.down('right') ? 1 : 0) - (input.down('left') ? 1 : 0);
let fire = input.down('fire'), fire2 = input.down('fire2'), fire3 = input.down('fire3');
const g = pad();
if (g) { ky = Kit.clamp(ky + g.throttle, -1, 1); kx = Kit.clamp(kx + g.turn, -1, 1); fire = fire || g.fire; fire2 = fire2 || g.fire2; fire3 = fire3 || g.fire3; }
const s = F.s, me = s.robots[0], en = s.robots[1];
let k = { throttle: ky, turn: kx, fire, fire2, fire3 };
if (settings.steer === 'simple' && view.camMode === 'iso') {
// keys = direction on screen; the robot turns towards it and drives
// (iso camera: screen up = world (-1,-1), screen right = world (1,-1))
const dx = (kx - ky) / Math.SQRT2, dz = (-kx - ky) / Math.SQRT2;
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
if (Math.hypot(dx, dz) < 0.2) k = { throttle: 0, turn: 0, fire, fire2, fire3 };
else {
let diff = wrap(Math.atan2(dz, dx) - me.a);
// target behind: drive backwards there instead of a slow 180° turn on the spot
// (with a little hysteresis so it does not flip between forward and reverse)
const back = F.revDir ? Math.abs(diff) > 1.2 : Math.abs(diff) > 2.1;
F.revDir = back;
if (back) diff = wrap(diff + Math.PI);
const ad = Math.abs(diff);
const thr = ad < 0.9 ? 1 : ad < 1.6 ? 0.6 : 0.2; // keep rolling while turning
k = { throttle: back ? -thr : thr, turn: Kit.clamp(diff * 3.5, -1, 1), fire, fire2, fire3 };
}
}
// weapon helper: fires the main weapon in reach, the tower when in range
if (settings.autofire) {
const w = me.st.weapon, tw = me.st.tower, dist = Math.hypot(en.x - me.x, en.z - me.z);
if (w && !k.fire) {
if (w.type === 'spinner' || w.type === 'vspinner') k.fire = dist < 5;
else if (w.type === 'saw') k.fire = dist < 2.4;
else if (w.type !== 'wedge') k.fire = RC.Combat.inZone(s, me, en);
}
if (tw && !k.fire2) {
// the turret fires forward now, so only help when the enemy is actually in front
const d = Math.atan2(en.z - me.z, en.x - me.x) - me.a;
const ahead = Math.abs(Math.atan2(Math.sin(d), Math.cos(d)));
const near = tw.type === 'flamer' || tw.type === 'zapper';
k.fire2 = dist < tw.range * 0.95 && ahead < (near ? 0.5 : 0.3);
}
// 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;
}
// health bar colour: paint, or the accent when the paint is too dark to read
const barCol = p => { const c = p.body >>> 0, l = ((c >> 16) & 255) * 0.3 + ((c >> 8) & 255) * 0.59 + (c & 255) * 0.11; return hex(l < 60 ? p.accent : p.body); };
const CAMS = ['iso', 'chase', 'fpv'];
function cycleCam() {
settings.cam = CAMS[(CAMS.indexOf(settings.cam) + 1) % CAMS.length];
saveSettings(); view.setCam(settings.cam); SFX.click();
banner(t('cam_' + settings.cam), '#ffffff', 1);
}
// minimap for chase / cockpit view: arena, traps, pit, both robots
function minimap() {
const touch = window.matchMedia && matchMedia('(pointer: coarse)').matches;
const s = F.s, A = s.arena, S = touch ? 104 : 128, X = W - S - 14, Y = touch ? 84 : H - S - 14, k = S / (A.half * 2);
// rotate 45° like the iso view, so "up" matches the arena camera
const P = (x, z) => [X + S / 2 + (x - z) * k * 0.7071, Y + S / 2 + (x + z) * k * 0.7071];
ctx.save();
ctx.fillStyle = 'rgba(10,12,16,.72)'; ctx.strokeStyle = 'rgba(255,255,255,.25)'; ctx.lineWidth = 1;
const poly = pts => { ctx.beginPath(); pts.forEach(([x, z], i) => { const [px, py] = P(x, z); if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py); }); ctx.closePath(); };
const h = A.half;
if (A.shape === 'round') poly(Array.from({ length: 20 }, (_, i) => { const a = i / 20 * Math.PI * 2; return [Math.cos(a) * h, Math.sin(a) * h]; }));
else if (A.shape === 'octagon') { const d = h * 0.67; poly([[-d, -h], [d, -h], [h, -d], [h, d], [d, h], [-d, h], [-h, d], [-h, -d]]); }
else poly([[-h, -h], [h, -h], [h, h], [-h, h]]);
ctx.fill(); ctx.stroke();
const rect = (o, col) => { ctx.fillStyle = col; poly([[o.x - o.hw, o.z - o.hd], [o.x + o.hw, o.z - o.hd], [o.x + o.hw, o.z + o.hd], [o.x - o.hw, o.z + o.hd]]); ctx.fill(); };
rect(A.press, 'rgba(242,181,28,.35)'); rect(A.crane, 'rgba(242,181,28,.35)');
rect(A.pit, s.pitOpen >= 1 ? 'rgba(255,40,40,.85)' : 'rgba(255,255,255,.12)');
for (const f of A.flames) rect(f, RC.hazardOn(f, s.t) ? 'rgba(255,110,20,.85)' : 'rgba(255,110,20,.25)');
for (const sw of A.saws) { const [px, py] = P(sw.x, sw.z); ctx.fillStyle = RC.hazardOn(sw, s.t) ? 'rgba(255,60,60,.9)' : 'rgba(200,200,200,.3)'; ctx.beginPath(); ctx.arc(px, py, sw.r * k, 0, 7); ctx.fill(); }
for (const bl of A.belts) rect(bl, 'rgba(80,170,255,.35)');
for (const o of A.oil) { const [px, py] = P(o.x, o.z); ctx.fillStyle = 'rgba(12,12,20,.65)'; ctx.beginPath(); ctx.arc(px, py, o.r * k, 0, 7); ctx.fill(); }
for (const m of A.rams) rect(m, RC.hazardOn(m, s.t) ? 'rgba(255,60,60,.8)' : 'rgba(200,200,200,.25)');
for (const b of A.blocks) rect(b, 'rgba(150,160,175,.6)');
for (const mn of s.mines || []) {
const [px, py] = P(mn.x, mn.z);
ctx.fillStyle = mn.arm > 0 ? 'rgba(200,200,200,.45)' : 'rgba(255,70,40,.95)';
ctx.beginPath(); ctx.arc(px, py, Math.max(2, mn.r * k), 0, 7); ctx.fill();
}
s.robots.forEach((r, i) => {
if (r.out) return;
const [px, py] = P(r.x, r.z), [qx, qy] = P(r.x + Math.cos(r.a), r.z + Math.sin(r.a)), ang = Math.atan2(qy - py, qx - px);
ctx.save(); ctx.translate(px, py); ctx.rotate(ang);
ctx.fillStyle = i === 0 ? hex(save.paint.body) : hex(F.opp.paint.body); ctx.strokeStyle = i === 0 ? '#fff' : '#000'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(7, 0); ctx.lineTo(-5, 5); ctx.lineTo(-5, -5); ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.restore();
});
ctx.restore();
}
function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; }
function update(dt) {
fx.update(dt);
introTick();
if (mode !== 'fight' || !F) return;
if (F.count > 0) {
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); } }
return;
}
const s = F.s, [me, en] = s.robots;
let events;
if (F.online) {
events = F.nf.frame(s, playerInput(), dt);
if (netProbe) { netProbe.push({ t: performance.now(), x: s.robots[1].x, z: s.robots[1].z }); if (netProbe.length > 2000) netProbe.shift(); }
if (F.nf.oppAway !== F.oppAway) { F.oppAway = F.nf.oppAway; banner(t(F.oppAway ? 'peer_lost' : 'peer_back'), F.oppAway ? '#ff4a3a' : '#6dff9e', 2.2); }
// no word from the server for 20 s (and no result yet - a hidden tab may simply have slept through the end)
if (!F.serverEnd && F.nf.silentFor > 20 && !F.ended) { F.ended = true; onlineFightLost(); return; }
} else {
RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]);
events = s.events;
}
for (const e of events) {
SFX.event(e);
if (e.type === 'dmg') { F.acc[e.who] += e.amount; if (e.amount >= 3) flashBox(e.who); }
else if (e.type === 'pit_open') banner(t('pit_open'), '#ff4a3a', 2);
else if (e.type === 'pit') banner(t('into_pit'), '#ff4a3a', 2.2);
else if (e.type === 'ko') banner(t('knockout'), '#ff7a1a', 2.2);
else if (e.type === 'broke') banner(t(e.who === 0 ? 'broke_you' : 'broke_enemy', { p: t('slot_' + e.part) }), e.who === 0 ? '#ff5a4a' : '#ffc940', 1.8);
}
view.events(events);
s.events.length = 0;
SFX.loops(s);
// damage numbers, grouped
F.accT -= dt;
if (F.accT <= 0) {
F.accT = 0.3;
for (let i = 0; i < 2; i++) if (F.acc[i] >= 1) {
const r = s.robots[i], p = view.project(r.x, r.y + 1.1, r.z);
fx.float(p.x, p.y, '-' + Math.round(F.acc[i]), i === 0 ? '#ff6a5a' : '#ffd060', 16 + Math.min(14, F.acc[i] / 3));
F.acc[i] = 0;
}
}
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); }
// 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)
const CD_KEY = { weapon: '␣', tower: '⇧', gadget: 'G' };
function buildCds() {
const el = $('fCds');
el.innerHTML = RC.Combat.cooldowns(F.s.robots[0]).map(c =>
`<div class="cdchip" data-slot="${c.slot}" style="--p:0"><div class="in">${RC.pic('part_' + c.id, '🔧')}</div>` +
`<b class="k">${CD_KEY[c.slot]}</b>${c.n === undefined ? '' : `<b class="n">${c.n}</b>`}</div>`).join('');
}
// condition panel: every part that can be torn off, shown per robot and greyed out when it is gone
const BREAKABLE = ['armour', 'wheels', 'tower'];
function buildDmg(i, build) {
const weps = (build.weapons || []).map((w, wi) =>
`<span class="pt" data-part="weapon${wi}" title="${t('slot_weapon')}">${RC.pic('part_' + w.id, GLYPH_SLOT.weapon)}</span>`).join('');
const icons = BREAKABLE.filter(k => build[k]).map(k =>
`<span class="pt" data-part="${k}" title="${t('slot_' + k)}">${RC.pic('part_' + build[k], GLYPH_SLOT[k])}</span>`).join('');
$('fD' + i).innerHTML = `<span class="hpn"></span><span class="pts">${weps}${icons}</span>`;
}
const GLYPH_SLOT = { armour: '🛡️', wheels: '🛞', weapon: '🪓', tower: '🔥' };
// short red flash on the box that just took a solid hit
let hitT = [0, 0];
function flashBox(who) {
const el = $(who === 0 ? 'fLeft' : 'fRight');
el.classList.add('hit');
clearTimeout(hitT[who]);
hitT[who] = setTimeout(() => el.classList.remove('hit'), 120);
}
function fightHud() {
if (!F) return;
const s = F.s;
for (let i = 0; i < 2; i++) {
const r = s.robots[i], pct = r.hp / r.maxHp;
$('fH' + i).style.width = (pct * 100).toFixed(1) + '%';
$('fG' + i).style.width = (pct * 100).toFixed(1) + '%'; // trails behind (CSS transition)
$(i === 0 ? 'fLeft' : 'fRight').classList.toggle('hurt', pct < 0.25 && !r.dead);
// readable damage: hit points left, and every torn-off part crossed out live
const el = $('fD' + i), hpn = el.querySelector('.hpn');
const txt = `${Math.ceil(r.hp)}/${Math.round(r.maxHp)}`;
if (hpn && hpn.textContent !== txt) hpn.textContent = txt;
for (const ps of el.querySelectorAll('.pt')) {
const p = ps.dataset.part, gone = /^weapon\d/.test(p) ? !!(r.lostW && r.lostW[+p.slice(6)]) : !!(r.lost && r.lost[p]);
ps.classList.toggle('gone', gone);
}
}
const own = s.robots[0].hp / s.robots[0].maxHp;
$('dmgvig').style.opacity = own < 0.3 && !s.robots[0].out ? ((0.3 - own) / 0.3 * (settings.comfort ? 0.32 : 0.6)).toFixed(2) : 0;
const cds = RC.Combat.cooldowns(s.robots[0]), chips = $('fCds').children;
for (let i = 0; i < chips.length && i < cds.length; i++) {
const ch = chips[i], c = cds[i];
ch.style.setProperty('--p', c.p.toFixed(2));
ch.classList.toggle('on', !!c.on);
ch.classList.toggle('spent', c.n === 0);
ch.classList.toggle('broke', !!c.broke);
const n = ch.querySelector('.n');
if (n && n.textContent !== String(c.n)) n.textContent = c.n;
if (c.slot === 'gadget') { const pg = $('padGadget'); if (pg) pg.style.setProperty('--p', c.p.toFixed(2)); }
}
const sec = Math.ceil(s.left);
$('fTime').textContent = `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
$('fTime').classList.toggle('low', sec <= 10);
const me = s.robots[0];
let st = '';
if (me.lifted) st = t('st_lifted'); else if (me.grabbedBy !== null) st = t('st_grabbed');
else if (me.flipped > 0 && !me.st.invertible) st = t('st_flipped'); else if (me.stun > 0) st = t('st_stunned');
else if (s.pitAlarm) st = t('pit_is_open'); else if (s.left - s.arena.pitOpensAt < 10 && s.left > s.arena.pitOpensAt) st = t('pit_soon');
$('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>');
// campaign missions: roll/reset for the current day/week
function ensureMissions() { return (save && gameMode === 'campaign') ? RC.Missions.ensure(save, Date.now(), save.mseed || 1) : null; }
// advance missions from a finished campaign fight, auto-pay credits/fame + unlock paints
function updateMissions(base) {
if (!save || gameMode !== 'campaign' || (F && F.training)) return [];
ensureMissions();
const ctx = Object.assign({}, base);
if (F && F.s && F.s.arena) ctx.arenaId = F.s.arena.id;
const w0 = (save.build.weapons || [])[0];
ctx.weaponType = w0 && RC.PARTS[w0.id] ? RC.PARTS[w0.id].type : null;
const done = [];
for (const m of RC.Missions.active(save)) {
if (RC.Missions.apply(m, ctx)) {
save.money += m.reward | 0; save.fame += m.fame | 0;
if (typeof m.unlock === 'number' && !save.unlockedPaints.includes(m.unlock)) save.unlockedPaints.push(m.unlock);
done.push(m);
}
}
if (done.length) { persist(); SFX.buy && SFX.buy(); }
return done;
}
const missHtml = done => (!done || !done.length ? '' :
`<div class="achwon"><b>🎯 ${t('miss_complete')}</b>` + done.map(m =>
`<div><span>${t('mission_' + m.id)}</span><span class="plus">+${Kit.fmt(m.reward)}${m.fame ? ' ⭐' + m.fame : ''}</span></div>`).join('') + '</div>');
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) { endOnlineFight(res, won, me); return; }
if (F.tour) { endTourFight(res, won, me); return; }
const lines = [];
let money = 0, fame = 0, champion = false;
if (!F.training) {
const prize = Math.round(opp.prize * seasonMul() * (F.exhibition ? 0.5 : 1));
save.games++;
if (won && F.exhibition) {
money += prize; lines.push([t('r_exhibition'), prize]);
fame = (idx + 1) * 10 * save.season;
save.wins++;
} else if (won) {
const bonus = res.reason === 'pit' ? 0.3 : res.reason === 'ko' ? 0.2 : 0;
money += prize; lines.push([t('r_prize'), prize]);
if (bonus) { const b = Math.round(prize * bonus); money += b; lines.push([t('r_bonus_' + res.reason), b]); }
fame = (idx + 1) * 50 * save.season + (res.reason === 'pit' ? 40 : res.reason === 'ko' ? 25 : 0);
save.wins++;
if (idx === save.beaten) save.beaten++;
if (save.beaten >= RC.LEAGUE.length) {
champion = true;
const cb = 1500 * save.season; money += cb; fame += 500 * save.season; lines.push([t('r_champion'), cb]);
save.season++; save.beaten = 0;
}
} else {
const ap = Math.round(prize * 0.35); money += ap; lines.push([t('r_appearance'), ap]);
save.losses++;
}
// every hit pays: damage bonus win or lose
const db = Math.round(me.dealt * 0.6 * (F.exhibition ? 0.5 : 1));
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06 + (res.reason === 'pit' && !won ? me.st.value * 0.03 : 0));
const paid = Math.min(repair, save.money + money);
if (paid) lines.push([t('r_repair'), -paid]);
money = applyEvent(money, lines);
money -= paid;
save.money += money; save.fame += fame;
persist();
}
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 = 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)();
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
const why = t('why_' + res.reason + (res.winner === -1 ? '_draw' : won ? '_win' : '_lose'), { name: opp.name });
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 stats = `<span>${t('r_dealt')}</span><span>${Math.round(me.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(me.taken)}</span>`;
setScreen('result');
card(`<h1>${title}</h1><p>${why}</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>
${achHtml(gotAch)}${missHtml(gotMiss)}
${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()}`,
{ 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(); }
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(); };
}
// ---------------------------------------------------------------- loop
let lastNow = 0, fpsN = 0, fpsT = 0, fpsVal = 0;
function render(alpha, now) {
// cap rendering: ~60 fps during action, ~16 fps when a static menu covers the arena (saves CPU/GPU on
// high-refresh monitors and in menus). update() stays fixed 60 Hz via the loop, so physics is unaffected.
const active = mode === 'fight' || mode === 'pause' || mode === 'intro' || mode === 'garage';
const minGap = active ? 15.5 : (mode === 'title' ? 33 : 60); // title ~30 fps so the background robots animate smoothly
if (lastNow && now - lastNow < minGap) return;
const dt = Math.min(0.05, lastNow ? (now - lastNow) / 1000 : 0.016); lastNow = now;
if (view) view.frame(mode === 'pause' ? 0 : dt, now);
ctx.clearRect(0, 0, W, H);
if (DEV.has('fps')) { // dev: ?fps shows the effective render rate
fpsN++; if (now - fpsT > 500) { fpsVal = Math.round(fpsN * 1000 / (now - fpsT)); fpsN = 0; fpsT = now; }
ctx.fillStyle = '#6dff9e'; ctx.font = '14px monospace'; ctx.textAlign = 'left'; ctx.textBaseline = 'top';
ctx.fillText(fpsVal + ' fps · ' + settings.gfx, 10, 10);
}
if (mode === 'intro' && view) {
const it = view.introTime;
if (it > 5.6) {
const k = Math.min(1, (it - 5.6) / 0.8);
ctx.save(); ctx.globalAlpha = k; ctx.translate(W / 2, H * 0.4); ctx.scale(1.4 - 0.4 * k, 1.4 - 0.4 * k);
ctx.font = '84px "Russo One", "Segoe UI Black", "Arial Black", Impact, sans-serif';
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.lineWidth = 10; ctx.strokeStyle = '#000'; ctx.strokeText('ROBOT CLASH', 0, 0);
ctx.fillStyle = '#ff7a1a'; ctx.fillText('ROBOT CLASH', 0, 0);
ctx.restore();
}
ctx.font = '12px "Segoe UI", sans-serif'; ctx.textAlign = 'right'; ctx.fillStyle = 'rgba(255,255,255,.55)';
ctx.fillText(t('skip_intro'), W - 14, H - 12);
}
if (F && (mode === 'fight' || mode === 'pause' || mode === 'result')) {
fightHud();
fx.apply(ctx); fx.draw(ctx); ctx.restore();
const b = F.banner;
if (b && b.t > 0) {
if (mode !== 'pause') b.t -= dt;
const k = b.t / b.max, sc = 1 + Math.max(0, k - 0.75) * 2;
ctx.save();
ctx.globalAlpha = Math.min(1, k * 3);
ctx.translate(W / 2, H * 0.42); ctx.scale(sc, sc);
ctx.font = '64px "Russo One", "Segoe UI Black", "Arial Black", Impact, sans-serif';
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.lineWidth = 8; ctx.strokeStyle = '#000'; ctx.strokeText(b.text, 0, 0);
ctx.fillStyle = b.color; ctx.fillText(b.text, 0, 0);
ctx.restore();
}
if (view.camMode !== 'iso') minimap();
if (mode === 'fight' && F.s.t < 7 && F.count <= 0) {
ctx.font = '13px "Segoe UI", sans-serif'; ctx.textAlign = 'center'; ctx.fillStyle = 'rgba(232,235,242,.75)';
ctx.fillText(t(settings.steer === 'simple' && view.camMode === 'iso' ? 'fight_hint_simple' : 'fight_hint'), W / 2, H - 16);
}
}
}
const loop = Kit.loop({ step: 1000 / 60, update, render }).start();
function togglePause() {
overlayEnter();
// live fight: no pause (the server keeps running) - but you can give up; the fight goes on behind the card
if (F && F.online && mode === 'fight') {
if ($('bGiveUp')) { hideOverlay(); return; } // second press closes the card again
card(`<h2>${t('pause')}</h2><p>${t('no_pause_online')}</p><div class="row"><button id="bGiveUp">${t('give_up')}</button><button class="primary" id="bGo">${t('continue')}</button></div>`);
$('bGo').onclick = () => { SFX.click(); hideOverlay(); };
$('bGiveUp').onclick = () => { SFX.click(); hideOverlay(); if (lobby) lobby.leaveMatch(); };
return;
}
if (mode === 'fight') {
mode = 'pause'; loop.pause();
card(`<h2>${t('pause')}</h2><div class="row"><button id="bSet2">⚙ ${t('settings')}</button><button id="bQuit">${t('give_up')}</button><button class="primary" id="bGo">${t('continue')}</button></div>`);
$('bGo').onclick = togglePause;
$('bSet2').onclick = () => { SFX.click(); showSettings(() => { mode = 'fight'; togglePause(); }); };
$('bQuit').onclick = () => {
mode = 'fight'; loop.resume(); hideOverlay();
if (F && !F.s.result) { F.s.robots[0].hp = 0; F.s.robots[0].dead = true; F.s.result = { winner: 1, reason: 'ko' }; F.s.endIn = 0; }
};
} else if (mode === 'pause') { mode = 'fight'; hideOverlay(); loop.resume(); }
}
function toggleMute() { audio.toggleMute(); hud(); }
$('bMute').onclick = toggleMute;
$('bPause').onclick = togglePause;
addEventListener('blur', () => { if (mode === 'fight' && !(F && F.online)) togglePause(); });
// language switch: static texts update themselves (data-i18n), dynamic screens are drawn again
L.onChange(() => {
hud(); updateShopBar();
if (mode === 'title') showTitle();
else if (mode === 'garage') shop.render();
else if (mode === 'league') showLeague();
else if (mode === 'lobby') renderLobby();
if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); }
});
// ---------------------------------------------------------------- feature modules
// game.js was split by topic (pages.js, online.js, workshop.js). They share this context: getters always
// return the CURRENT value (save, mode, F change all the time), setters write back into game.js.
const G = {
get $() { return $; }, get CAMS() { return CAMS; }, get FLAGS() { return FLAGS; },
get GLYPH_SLOT() { return GLYPH_SLOT; }, get L() { return L; }, get MAX_ROBOTS() { return MAX_ROBOTS; },
get SFX() { return SFX; }, get accounts() { return accounts; }, get achHtml() { return achHtml; },
get act() { return act; }, get audio() { return audio; }, get card() { return card; },
get currentBack() { return currentBack; }, get ensureFlag() { return ensureFlag; },
get ensureMissions() { return ensureMissions; }, get enterAccount() { return enterAccount; },
get esc() { return esc; }, get fbAcc() { return fbAcc; }, get flagHtml() { return flagHtml; },
get hideOverlay() { return hideOverlay; }, get hud() { return hud; }, get img() { return img; },
get layer() { return layer; }, get liveText() { return liveText; }, get loadSave() { return loadSave; },
get lobby() { return lobby; }, get logout() { return logout; }, get net() { return net; },
get newSave() { return newSave; }, get openGarage() { return openGarage; }, get overlay() { return overlay; },
get overlayEnter() { return overlayEnter; }, get paintObj() { return paintObj; },
get painter() { return painter; }, get persist() { return persist; }, get playerName() { return playerName; },
get prepOpp() { return prepOpp; }, get rank() { return rank; }, get refreshDev() { return refreshDev; },
get renderWeaponEditor() { return renderWeaponEditor; }, get repairSave() { return repairSave; },
get saveSettings() { return saveSettings; }, get setMode() { return setMode; },
get setScreen() { return setScreen; }, get settings() { return settings; }, get shop() { return shop; },
get showLeague() { return showLeague; }, get showLegal() { return showLegal; },
get showTitle() { return showTitle; }, get showTournament() { return showTournament; },
get skipIntro() { return skipIntro; }, get startFight() { return startFight; },
get syncActive() { return syncActive; }, get t() { return t; }, get togglePause() { return togglePause; },
get tourState() { return tourState; }, get weaponName() { return weaponName; }, get F() { return F; },
get LIVE() { return LIVE; }, get boardFame() { return boardFame; }, set boardFame(v) { boardFame = v; },
get boardIdx() { return boardIdx; }, set boardIdx(v) { boardIdx = v; }, get editSel() { return editSel; },
set editSel(v) { editSel = v; }, get editorOpen() { return editorOpen; }, get gameMode() { return gameMode; },
get isDev() { return isDev; }, get joinedRoom() { return joinedRoom; }, set joinedRoom(v) { joinedRoom = v; },
get lobbyRoom() { return lobbyRoom; }, set lobbyRoom(v) { lobbyRoom = v; },
get lobbyRows() { return lobbyRows; }, set lobbyRows(v) { lobbyRows = v; }, get mode() { return mode; },
set mode(v) { mode = v; }, get onlineReady() { return onlineReady; }, set onlineReady(v) { onlineReady = v; },
get rankSub() { return rankSub; }, set rankSub(v) { rankSub = v; }, get save() { return save; },
get slot() { return slot; }, get view() { return view; }, get wPrev() { return wPrev; },
set wPrev(v) { wPrev = v; },
};
GM.pages = RC.GamePages(G);
GM.online = RC.GameOnline(G);
GM.workshop = RC.GameWorkshop(G);
// ---------------------------------------------------------------- start
// backend settings; applied as soon as they arrive and whenever the admin changes them
RC.Live.load(net, v => {
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 server 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();
if (net && net.enabled) {
let lastUid = null;
net.auth.onChange(cur => {
hud(); refreshDev();
// session gone while playing online (expired / server reset / logged out elsewhere): ask to log in again
if (lastUid && !cur && gameMode === 'online' && save && ['garage', 'lobby', 'result'].includes(mode)) {
if (lobby) lobby.leave();
showOnlineLogin(false, 'SESSION_EXPIRED', 'online');
} else if (mode === 'title') showTitle();
lastUid = cur ? cur.uid : null;
});
if (net.auth.resume()) lastUid = net.uid;
}
hud();
if (!hostOk()) {
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) {
card(`<h1>Robot Clash</h1><p>${t('no_webgl')}</p><p class="credits">${CREDITS}</p>`);
} else if (DEV.has('fight') || DEV.has('play')) {
// dev: ?play = straight into the shop, ?fight=N = training fight against league robot N
if (!accounts.current) accounts.guest();
loadSave(); hud();
if (DEV.get('equip')) for (const id of DEV.get('equip').split(',')) { const p = RC.PARTS[id]; if (p) { if (!save.owned.includes(id)) save.owned.push(id); save.build[p.slot] = id; } }
if (DEV.get('arena')) settings.arena = DEV.get('arena');
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (DEV.get('hangar')) { const n = Math.min(MAX_ROBOTS, +DEV.get('hangar') || 3); while (save.robots.length < n) save.robots.push(newRobotDef(t('robot_n', { n: save.robots.length + 1 }))); }
if (DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true); else openGarage();
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(); } }
// 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');
if (scr === 'league') { save.beaten = Math.max(save.beaten, 3); showLeague(); }
else if (scr === 'vs') showVs(RC.LEAGUE[4]);
else if (scr === 'settings') showSettings(openGarage);
else if (scr === 'help') showHelp(openGarage);
else if (scr === '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 === 'missions') { if (gameMode !== 'campaign') switchMode('campaign'); if (DEV.has('mreset')) save.missions = null; showMissions(openGarage); }
else if (scr === 'lobby') {
lobbyRows = [{ uid: 'a', name: 'BlechBrecher', flag: 'DE', fame: 1250, state: 'idle' }, { uid: 'b', name: 'SawQueen', flag: 'DE', fame: 430, state: 'inmatch' }, { uid: 'c', name: 'Rostlaube77', flag: 'AT', fame: 90, state: 'idle' }, { uid: 'd', name: 'Flipmaster', flag: 'GB', fame: 600, state: 'idle' }];
lobbyRoom = DEV.get('room') || null;
showLobby();
}
if (DEV.get('tab')) { const tb = document.querySelector(`.tab[data-slot="${DEV.get('tab')}"]`); if (tb) tb.click(); }
// dev: &buy=<part id> buys it through the real shop buttons (header check)
if (DEV.get('buy')) { const it = document.querySelector(`.item[data-id="${DEV.get('buy')}"]`); if (it) { it.click(); const b = document.querySelector('#detail button[data-act="buy"]'); if (b) b.click(); } }
// dev: &equip=wedge,flamer forces parts onto the robot (ignores cost), then shows the garage
if (DEV.get('equip') && !DEV.has('fight')) { for (const id of DEV.get('equip').split(',')) { const p = RC.PARTS[id]; if (p) { if (!save.owned.includes(id)) save.owned.push(id); save.build[p.slot] = id; } } persist(); view.showGarage(save.build, paintObj()); shop.render(); }
if (DEV.has('paint')) { // dev: open the paint booth with a test drawing
const c = layer.getContext('2d');
c.fillStyle = '#15171b'; c.fillRect(0, 100, 256, 56); c.fillStyle = '#f2c230'; c.font = 'bold 70px sans-serif'; c.fillText('★ 7', 300, 170);
c.strokeStyle = '#00e5ff'; c.lineWidth = 14; c.beginPath(); c.moveTo(270, 220); c.lineTo(500, 200); c.stroke();
painter.open(); view.showGarage(save.build, paintObj());
}
} else if (DEV.has('online') && net.enabled) { startIntroOrTitle(); startOnline(); }
else if (DEV.has('title')) startIntroOrTitle();
else startGate(startIntro);
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
})();