Files
Robot-Clash/game/game.js
2026-11-15 20:05:02 +01:00

1186 lines
76 KiB
JavaScript
Raw 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
// Paste the Firebase Realtime Database URL here to switch the online fame ranking on
// (docs/firebase/README.md). Empty = offline.
const DB_URL = 'https://robot-clash-aa37b-default-rtdb.firebaseio.com';
// Online lobby + live PvP: paste the Web API key (Firebase console -> Project settings -> Web API key).
// Empty key -> leaderboard still works, but no login/lobby (menu hides 'Online').
const NET_CFG = { apiKey: 'AIzaSyCE29VQnubM_9ok46nnosg07MpvhZH3O5w', dbUrl: DB_URL };
// dev/test: ?netkey=<API key> tries online without editing the file; ?online jumps to the lobby/login
if (new URLSearchParams(location.search).get('netkey')) NET_CFG.apiKey = new URLSearchParams(location.search).get('netkey');
// Credits (standard for every game): shown on the title screen, links open in the normal browser
const DISCORD = 'https://discord.gg/Ej4JPmCZva';
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 = ['michael-media.de', 'www.michael-media.de', 'localhost', '127.0.0.1', ''];
const hostOk = () => location.protocol === 'file:' || HOSTS.includes(location.hostname)
|| (Kit.host && Kit.host.exe) || document.documentElement.classList.contains('exe');
// ---------------------------------------------------------------- services
const L = Kit.i18n(window.LANG, { prefix: ID });
const t = L.t;
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', diff: 'easy', autofire: true, cam: 'fpv', arena: 'random' }, store.get('settings', {}));
// v2: Michael found "simple" steering worse -> tank is the default again, old saved choice reset once
// v3: fights start in first person (cockpit) -> old saved camera reset once
if (!settings.v || settings.v < 2) settings.steer = 'tank';
if (!settings.v || settings.v < 3) { settings.cam = 'fpv'; settings.v = 3; store.set('settings', settings); }
// difficulty: player hit points x, AI skill +
const DIFF = { easy: { hp: 1.4, skill: -0.2 }, normal: { hp: 1.15, skill: -0.05 }, hard: { hp: 0.95, skill: 0.12 } };
const saveSettings = () => store.set('settings', settings);
const 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', tutorialSeen: false,
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()
const persist = () => { if (slot && save) { syncActive(); slot.save(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 },
});
const scores = Kit.scores({ url: DB_URL });
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 FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`;
const lobby = net.enabled ? RC.Lobby({ net, getProfile: () => ({ name: playerName(), flag: save.flag || 'XX', build: save.build, paint: { body: save.paint.body, accent: save.paint.accent }, fame: save.fame | 0 }) }) : null;
const fx = Kit.fx();
const 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 (ComfyGen clips + synth fallback)
const last = {};
const every = (k, ms) => { const n = performance.now(); if (last[k] && n - last[k] < ms) return false; last[k] = n; return true; };
const SFX = {
click() { audio.sfx('sfx_click'); audio.tone(660, 0.04, 'square', 0.05); },
buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.08); },
deny() { audio.tone(160, 0.15, 'square', 0.12, -40); },
beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); },
clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); },
win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); },
lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); },
event(e) {
switch (e.type) {
case 'bump': if (every('bump', 90)) audio.noise(0.12, Math.min(0.4, e.speed / 10), 700); break;
case 'wall': if (every('wall', 120)) { audio.sfx('sfx_hit'); audio.noise(0.2, 0.3, 1600); } break;
case 'flip': audio.tone(200, 0.2, 'square', 0.13, 500); audio.noise(0.12, 0.25, 3000); break;
case 'swing': audio.noise(0.15, 0.12, 900); break;
case 'smash': audio.sfx('sfx_hit'); audio.noise(0.25, 0.45, 650); audio.tone(95, 0.25, 'sine', 0.4, -45); break;
case 'spinhit': audio.sfx('sfx_hit'); audio.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); break;
case 'sparks': if (every('grind', 70)) audio.noise(0.06, 0.1, 5200); break;
case 'boom': audio.sfx('sfx_boom'); audio.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break;
case 'ko': audio.sfx('sfx_boom'); audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); break;
case 'launch': audio.noise(0.3, 0.18, 2200); audio.tone(300, 0.3, 'sawtooth', 0.07, 600); break;
case 'press_warn': for (let k = 0; k < 3; k++) audio.tone(880, 0.1, 'square', 0.1, 0, k * 0.2); break;
case 'press': audio.sfx('sfx_hit'); audio.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); break;
case 'crane': audio.tone(140, 0.6, 'sawtooth', 0.07, 140); break;
case 'drop': case 'land': audio.noise(0.22, 0.35, 500); break;
case 'broke': audio.sfx('sfx_hit'); audio.noise(0.45, 0.5, 900); audio.tone(240, 0.35, 'sawtooth', 0.22, -190); break;
case 'mine_drop': audio.tone(520, 0.08, 'square', 0.12, -160); audio.noise(0.06, 0.12, 2200); break;
case 'pit_open': for (let k = 0; k < 3; k++) audio.tone(700, 0.3, 'square', 0.12, -250, k * 0.4); break;
case 'pit': audio.tone(420, 1.2, 'sawtooth', 0.14, -360); break;
case 'grab': audio.tone(150, 0.25, 'square', 0.12, -60); break;
case 'boost': audio.noise(0.4, 0.25, 1800); break;
}
},
loops(s) { // continuous weapons as short repeated bursts
for (const r of s.robots) {
if (r.sawOn && every('saw' + r.i, 110)) { audio.sfx('sfx_saw'); audio.tone(900 + Math.random() * 60, 0.1, 'sawtooth', 0.03); }
if (r.flameOn && every('fl' + r.i, 120)) audio.noise(0.14, 0.12, 900);
if (r.gunOn && every('gun' + r.i, 70)) audio.noise(0.04, 0.16, 3500);
if (r.spin > 0.2 && every('spin' + r.i, 100)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin);
}
},
};
// ---------------------------------------------------------------- view
const cv = $('cv');
let ctx = cv.getContext('2d');
let view = null;
try { view = RC.Render($('gl'), W, H); view.setQuality(settings.gfx); } 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
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
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()),
});
$('bPaint').onclick = () => { SFX.click(); painter.open(); view.showGarage(save.build, paintObj()); };
// drag on the robot turns it
let drag = null;
$('gl').addEventListener('pointerdown', e => { if (mode === 'garage') { drag = e.clientX; $('gl').setPointerCapture(e.pointerId); } });
$('gl').addEventListener('pointermove', e => { if (drag != null) { view.turn(e.clientX - drag); drag = e.clientX; } });
$('gl').addEventListener('pointerup', () => { drag = null; });
// ---------------------------------------------------------------- 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 => (b.weapon ? RC.PARTS[b.weapon].name : t('unarmed')) + (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);
const fbUser = () => (net && net.enabled ? net.auth.current : null);
const fbAcc = () => (fbUser() && !fbUser().guest ? fbUser() : null); // real (e-mail) account
const playerName = () => (fbUser() ? fbUser().name : accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : '');
// save slot: Firebase account -> robotclash.save.fb_<uid>, else local profile / guest
const saveKey = () => (fbAcc() ? ID + '.save.fb_' + fbAcc().uid : accounts.saveKey());
function hud() {
$('hMoney').textContent = save ? Kit.fmt(save.money) : '–';
$('hFame').textContent = save ? Kit.fmt(save.fame) : '–';
$('hLeague').textContent = save ? t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length }) : '–';
$('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 (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');
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.add('clear'); overlay.style.backgroundImage = '';
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>
<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>${scores.enabled ? `<button id="bRank">🏆 ${t('ranking')}</button>` : ''}</div>
<p class="credits">${CREDITS}</p></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('bRank', () => showRanking(showTitle));
hud();
}
// ---------------------------------------------------------------- online lobby
let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker)
async function startOnline() {
if (!net.enabled) return;
if (!net.auth.current) {
if (save && !fbAcc()) return joinAnon(); // playing as guest -> straight in, anonymously
showOnlineLogin(false, null, 'online'); return;
}
if (!save || !slot) { if (!fbAcc()) accounts.guest(); loadSave(); }
if (!onlineReady) {
lobby.enter(); onlineReady = true;
lobby.onList(rows => { lobbyRows = rows; if (mode === 'lobby') renderLobby(); });
lobby.onIncoming(c => { if (mode === 'lobby' || mode === 'garage') showIncoming(c); });
lobby.onMatch(m => startFight({ name: m.opp.name, build: m.opp.build, paint: m.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: m.opp.flag }, false, false, { id: m.id, host: m.host, seed: m.seed }));
lobby.onCancel(() => { pendingOut = null; if (mode === 'lobby') { renderLobby(); SFX.deny(); } });
}
showLobby();
}
async function joinAnon() {
if (!save) { accounts.guest(); loadSave(); }
const r = await net.auth.guest(playerName() || t('guest'));
if (!r.ok) { SFX.deny(); showOnlineLogin(false, r.error, 'online'); return; }
hud(); startOnline();
}
const errText = c => (window.LANG.en['e_' + c] ? t('e_' + c) : t('e_ERROR') + ' (' + esc(c) + ')');
function showOnlineLogin(reg, errKey, next) {
next = next || 'career';
setScreen('account');
const f = reg
? `<label>${t('f_name')}</label><input type="text" id="oName" maxlength="18" autocomplete="nickname">`
: '';
card(`<h2>${reg ? t('register') : t('login')}</h2><p>${t('online_login_text')}</p>
<div class="form">${f}<label>${t('f_email')}</label><input type="email" id="oMail" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" inputmode="email">
<label>${t('f_pass')}</label><input type="password" id="oPass" autocomplete="${reg ? 'new-password' : 'current-password'}"></div>
<div class="err" id="oErr">${errKey ? errText(errKey) : ''}</div>
<div class="row"><button id="oBack">${t('back')}</button><button class="primary" id="oGo">${reg ? t('register_go') : t('login')}</button></div>
<p class="muted">${reg ? '' : t('no_account') + ' '}<button class="link" id="oToggle">${reg ? t('login') : t('register')}</button></p>
${next === 'online' ? `<div class="row"><button id="oAnon">👤 ${t('online_guest')}</button></div>` : ''}`, { bg: 'bg_title.jpg' });
if ($('oAnon')) $('oAnon').onclick = () => { SFX.click(); joinAnon(); };
$('oBack').onclick = () => { SFX.click(); showTitle(); };
$('oToggle').onclick = () => { SFX.click(); showOnlineLogin(!reg, null, next); };
$('oGo').onclick = async () => {
$('oGo').disabled = true;
const r = reg ? await net.auth.register($('oMail').value.trim(), $('oPass').value, $('oName') ? $('oName').value : '')
: await net.auth.login($('oMail').value.trim(), $('oPass').value);
if (!r.ok) { SFX.deny(); showOnlineLogin(reg, r.error, next); return; }
SFX.click(); hud();
if (next === 'online') startOnline(); else enterAccount(reg);
};
overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Enter') $('oGo').click(); }));
}
function showLobby() {
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 => (FLAGS.includes(r.flag) ? r.flag : 'XX');
const all = lobbyRows;
const myFlag = FLAGS.includes(save.flag) ? save.flag : 'XX';
// I am in the lobby too: count myself in my own country (and in "all"), and only list me there
const total = all.length + 1;
const cnt = f => all.filter(r => code(r) === f).length + (f === myFlag ? 1 : 0);
const here = lobbyRoom === 'all' ? all : all.filter(r => code(r) === lobbyRoom);
const showMe = lobbyRoom === 'all' || lobbyRoom === myFlag;
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' : ''}" data-f="${f}"><span class="rfl">${flag ? flagHtml(f) : ''}</span><span class="rn">${label}</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 list = here.map(r => prow(r, false)).join('');
const title = lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(lobbyRoom) + ' ' + t('cc_' + lobbyRoom);
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 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; 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(); };
$('lBack').onclick = () => { SFX.click(); if (save) openGarage(); else showTitle(); };
}
function showIncoming(c) {
card(`<h2>${t('challenge_in')}</h2><p>${flagHtml(c.fromFlag)} <b>${esc(c.fromName)}</b> ${t('wants_fight')}</p>
<div class="row"><button id="cNo">${t('decline')}</button><button class="primary" id="cYes">${t('accept')}</button></div>`);
$('cYes').onclick = () => { SFX.click(); lobby.accept(c.from); };
$('cNo').onclick = () => { SFX.click(); lobby.decline(c.from); if (mode === 'lobby') renderLobby(); else hideOverlay(); };
}
// ---------------------------------------------------------------- accounts
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>
<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(); };
$('bGo').onclick = async () => {
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()); });
}
function enterAccount(fresh) {
loadSave();
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
if (fresh && who) save.robotName = who.name.slice(0, 18);
persist();
hud();
shop.reset();
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]);
// 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 => {
for (const sl of RC.SLOTS) {
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);
}
// hangar: switch / add / delete robot slots (owned parts are shared)
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;
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);
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;
persist(); RC.layerFromData(layer, save.paint.decal, () => {}); shop.reset(); shop.render(); view.showGarage(save.build, paintObj()); renderHangar();
}
// hangar management (shop top-tab): list of robots with weapon, switch / delete + add button
function renderHangar(el) {
el = el || $('hangarView'); if (!el) return;
const rows = save.robots.map((r, i) => `<div class="hmrow ${i === save.active ? 'on' : ''}" data-i="${i}">
<div><div class="hmn">${esc(r.name)}</div><div class="hmw">${esc(weaponName(r.build))}</div></div>
${i === save.active ? `<span class="muted" style="font-size:12px">${t('active_robot')}</span>` : `<button data-use="${i}">${t('use')}</button>`}
${save.robots.length > 1 ? `<button data-del="${i}" title="${t('delete')}">✕</button>` : '<span></span>'}</div>`).join('');
el.innerHTML = `<div class="hmgr">${rows}</div>
${save.robots.length < MAX_ROBOTS ? `<button class="primary" id="hAdd" style="margin-top:8px">+ ${t('new_robot')}</button>` : `<p class="muted" style="margin-top:8px">${t('hangar_full')}</p>`}`;
el.querySelectorAll('[data-use]').forEach(b => { b.onclick = () => { SFX.click(); switchRobot(+b.dataset.use); shop.setTab('build'); } ; });
el.querySelectorAll('[data-del]').forEach(b => { b.onclick = () => { SFX.click(); delRobot(+b.dataset.del); renderHangar(); } ; });
if ($('hAdd')) $('hAdd').onclick = () => { addRobot(); shop.setTab('build'); };
}
function signOut() {
persist();
if (lobby && onlineReady) { lobby.leave(); onlineReady = false; lobbyRows = []; pendingOut = null; }
if (net && net.enabled) net.auth.logout();
accounts.logout(); save = null; slot = null; F = null; hud();
}
function logout() { signOut(); startIntroOrTitle(); }
function startIntroOrTitle() { if (view) { const a = RC.LEAGUE[7], b = RC.LEAGUE[4]; view.showIntro([a.build, b.build], [oppPaint(a), oppPaint(b)]); view.skipIntro(); } showTitle(); }
$('hUser').onclick = () => {
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; }
// ---------------------------------------------------------------- settings / help / ranking
function showSettings(back) {
overlayEnter();
const prev = mode;
const seg = (id, val, opts) => `<div class="seg" id="${id}">${opts.map(([v, label]) => `<button data-v="${v}" class="${v === val ? 'on' : ''}">${label}</button>`).join('')}</div>`;
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
const item = (label, ctl) => `<span class="sl">${label}</span>${ctl}`;
card(`<h2>${t('settings')}</h2><div class="set2">
${item(t('s_lang'), seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self])))}
${item(t('s_mute'), seg('sMute', audio.muted ? '1' : '0', [['0', t('on')], ['1', t('off')]]))}
${item(t('s_music'), `<input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">`)}
${item(t('s_sfx'), `<input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">`)}
${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))}
${item(t('s_diff'), seg('sDiff', settings.diff, [['easy', t('diff_easy')], ['normal', t('diff_normal')], ['hard', t('diff_hard')]]))}
${item(t('s_cam'), seg('sCam', settings.cam, CAMS.map(c => [c, t('cam_' + c)])))}
${item(t('s_steer'), seg('sSteer', settings.steer, [['tank', t('steer_tank')], ['simple', t('steer_simple')]]))}
${item(t('s_autofire'), seg('sAuto', settings.autofire ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))}
${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
</div>
<div class="setacc"><span class="sl">${t('s_account')}</span>
<span class="who">${who ? '👤 <b>' + esc(who.name) + '</b>' + (who.email ? ' <span class="muted">' + esc(who.email) + '</span>' : '') : '👤 ' + t('guest')}</span>
${save ? `<button id="sOut">${who ? t('logout') : t('to_title')}</button>` : ''}</div>
<div class="row"><button id="sFull">⛶ ${t('win_full')}</button><button id="sKeys">🎮 ${t('s_controls')}</button>
${save ? `<button id="sReset">${t('reset')}</button>` : ''}<button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, clear: prev === 'title' || prev === 'intro' });
const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; });
segOn('sLang', v => { L.set(v); showSettings(back); });
segOn('sMute', v => { if ((v === '1') !== audio.muted) audio.toggleMute(); hud(); });
segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (view) view.setQuality(v); });
segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); });
segOn('sDiff', v => { settings.diff = v; saveSettings(); });
segOn('sSteer', v => { settings.steer = v; saveSettings(); });
segOn('sCam', v => { settings.cam = v; saveSettings(); if (view) view.setCam(v); });
segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); });
segOn('sArena', v => { settings.arena = v; saveSettings(); });
$('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol);
$('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value);
$('sSfx').onchange = () => SFX.click();
$('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); };
if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); };
if ($('sOut')) $('sOut').onclick = () => { SFX.click(); logout(); };
$('sKeys').onclick = () => { SFX.click(); showHelp(() => showSettings(back)); };
$('bBack').onclick = () => { SFX.click(); back(); };
}
function keysHtml() {
return `<div class="keys"><b>W A S D / ↑ ← ↓ →</b><span>${t('key_drive')}</span><b>${t('key_space')}</b><span>${t('key_weapon')}</span>
<b>Shift / E</b><span>${t('key_tower')}</span><b>C</b><span>${t('key_cam')}</span><b>P / Esc</b><span>${t('pause')}</span><b>M</b><span>${t('sound_on')} / ${t('sound_off')}</span>
<b>${t('key_pad')}</b><span>${t('key_pad_text')}</span></div>`;
}
// first start: four short cards instead of the full help page
const TUT = ['tut_1', 'tut_2', 'tut_3', 'tut_4'];
function startTutorial(done) {
let i = 0;
const step = () => {
if (i >= TUT.length) { done(); return; }
const n = i + 1;
overlayEnter();
card(`<h2>${t('tut_title')} <span class="muted">${n}/${TUT.length}</span></h2>
<p>${t(TUT[i])}</p>
<div class="row"><button id="tSkip">${t('tut_skip')}</button>
<button class="primary" id="tNext">${n === TUT.length ? t('tut_go') : t('tut_next')}</button></div>`,
{ bg: 'bg_workshop.jpg' });
$('tNext').onclick = () => { SFX.click(); i++; step(); };
$('tSkip').onclick = () => { SFX.click(); done(); };
};
step();
}
function showHelp(back) {
overlayEnter();
card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>${keysHtml()}
<p style="margin-top:12px">${t('help_arena')}</p><button class="primary" id="bOk">${t('ok')}</button>`, { bg: 'bg_title.jpg' });
$('bOk').onclick = () => { SFX.click(); back(); };
}
function showRanking(back) {
overlayEnter();
card(`<h2>🏆 ${t('ranking')}</h2><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol><div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); back(); };
fillBoard();
}
function confirmReset(back) {
card(`<h2>${t('reset')}</h2><p>${t('reset_text')}</p><div class="row"><button id="bYes">${t('reset_yes')}</button><button class="primary" id="bNo">${t('cancel')}</button></div>`);
$('bNo').onclick = () => { SFX.click(); back(); };
$('bYes').onclick = () => { Object.assign(save, newSave()); RC.layerFromData(layer, null); save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); };
}
$('bSettings').onclick = () => {
if (mode === 'fight') togglePause();
if (mode === 'intro') skipIntro();
SFX.click();
const back = mode === 'pause' ? () => { mode = 'fight'; togglePause(); } : currentBack();
showSettings(back);
};
function boardHtml() { return scores.enabled ? `<h3>${t('ranking')}</h3><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
async function fillBoard(myKey) {
const el = $('board');
if (!el) return;
try {
const rows = (await scores.top(10)).filter(r => !Kit.badName(r.name));
el.innerHTML = rows.length
? rows.map((r, i) => `<li class="${r.key === myKey ? 'me' : ''}"><span>${i + 1}.</span><span class="nm">${esc(r.name)}</span><span>${Kit.fmt(r.score)}</span></li>`).join('')
: `<li class="muted">${t('no_scores')}</li>`;
} catch (e) { el.innerHTML = `<li class="muted">${t('scores_offline')}</li>`; }
}
// ---------------------------------------------------------------- shop + league
function openGarage() {
hideOverlay();
setScreen('garage');
view.showGarage(save.build, paintObj());
audio.music('music_garage');
shop.render(); hud();
$('zIn').onclick = () => { SFX.click(); view.zoomGarage(1.18); };
$('zOut').onclick = () => { SFX.click(); view.zoomGarage(1 / 1.18); };
}
$('bGMenu').onclick = () => { SFX.click(); persist(); startIntroOrTitle(); };
$('bGOnline').onclick = () => { SFX.click(); persist(); startOnline(); };
if (!(net && net.enabled)) $('bGOnline').style.display = 'none';
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
$('bLeague').onclick = () => { SFX.click(); showLeague(); };
function showLeague() {
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('');
card(`<h2>${t('league_title', { s: save.season })}</h2><p>${t('league_text')}</p><div class="opps">${cards}</div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bFight">${t('fight_vs', { name: RC.LEAGUE[save.beaten].name })}</button></div>
${save.beaten ? `<p class="muted">${t('exhibition_hint')}</p>` : ''}`,
{ wide: true, bg: 'bg_title.jpg' });
overlay.querySelectorAll('.opp.next').forEach(el => { el.style.cursor = 'pointer'; el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); }; });
// 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
function startFight(opp, training, exhibition, online) {
hideOverlay();
const D = DIFF[settings.diff] || DIFF.easy;
const stA = RC.stats(save.build), stB = RC.stats(opp.build);
if (!online) stA.hp = Math.round(stA.hp * D.hp); // no handicap in live PvP
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')
: online ? ids[seed % ids.length]
: idx >= 0 ? bySize[Math.min(bySize.length - 1, Math.floor(idx * bySize.length / RC.LEAGUE.length))]
: settings.arena === 'random' || !settings.arena ? ids[(Math.random() * ids.length) | 0] : settings.arena;
const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name], arena: arenaId });
const skill = Kit.clamp(opp.skill + (save.season - 1) * 0.12 + D.skill, 0, 1);
F = { s, opp, training, exhibition: !!exhibition, online, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4,
acc: [0, 0], accT: 0, banner: null, ended: false };
if (online) {
F.nf = RC.NetFight({ net, id: online.id, host: online.host, oppStyle: 'brawler', oppSkill: 0.6, onPeerLost: () => banner(t('peer_lost'), '#ff4a3a', 2.5), onPeerBack: () => banner(t('peer_back'), '#6dff9e', 1.6) });
F.nf.start();
}
// dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing)
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, [save.build, opp.build], [paintObj(), oppPaint(opp)]);
view.setCam(DEV.get('cam') || settings.cam); // dev: &cam=chase|fpv
$('fN0').textContent = save.robotName; $('fN1').textContent = opp.name;
$('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');
banner('📍 ' + t('arena_' + s.arena.id), '#ff7a1a', 2.2);
if (save.games === 0 && !F.online) setTimeout(() => { if (mode === 'fight') banner(t('tut_controls'), '#ffffff', 5); }, 2400);
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);
}
if (me.st.gadget && !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) {
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); } }
return;
}
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);
} 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); }
if (s.result && s.endIn <= 0 && !F.ended) { 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', 'weapon', 'tower'];
function buildDmg(i, build) {
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">${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')) ps.classList.toggle('gone', !!(r.lost && r.lost[ps.dataset.part]));
}
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 * 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;
}
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; }
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 -= paid;
save.money += money; save.fame += fame;
persist();
}
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>
${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();
scores.submit({ name: playerName(), score: save.fame, level: save.season }).then(fillBoard);
} else fillBoard();
}
function endOnlineFight(res, won, me) {
if (F.nf) F.nf.stop();
if (lobby) lobby.endMatch();
(won ? SFX.win : SFX.lose)();
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
// online rewards: prize (win) / half (draw) / appearance fee (loss) + damage bonus - repairs; fame on a win
const PVP = 600, lines = [];
let money = 0, fame = 0;
const draw = res.winner === -1;
if (won) { money += PVP; lines.push([t('r_prize'), PVP]); fame = 150 + (res.reason === 'ko' ? 40 : res.reason === 'pit' ? 60 : 0); }
else if (draw) { money += PVP / 2; lines.push([t('r_draw_prize'), PVP / 2]); fame = 40; }
else { const ap = Math.round(PVP * 0.35); money += ap; lines.push([t('r_appearance'), ap]); }
if (won && res.reason !== 'time') { const b = Math.round(PVP * (res.reason === 'pit' ? 0.3 : 0.2)); money += b; lines.push([t('r_bonus_' + res.reason), b]); }
const db = Math.round(me.dealt * 0.6);
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06);
const paid = Math.min(repair, save.money + money);
if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); }
save.money += money; save.fame += fame; save.games++;
if (won) save.wins++; else if (!draw) save.losses++;
persist(); hud();
if (save.fame > save.best) { save.best = save.fame; persist(); scores.submit({ name: playerName(), score: save.fame, level: save.season }); }
const rows = lines.map(([k, v]) => `<span>${k}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
setScreen('result');
card(`<h1>${title}</h1><p>${esc(F.opp.name)} ${F.nf && !F.nf.peerAlive ? t('peer_left') : ''}</p>
<div class="res"><span>${t('r_dealt')}</span><span>${Math.round(me.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(me.taken)}</span>${rows}
${fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div>
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button><button id="bShopO">${t('to_garage')}</button></div>`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bLobby').onclick = () => { SFX.click(); showLobby(); };
$('bShopO').onclick = () => { SFX.click(); openGarage(); };
}
// ---------------------------------------------------------------- loop
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 : 60;
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();
if (F && F.online && mode === 'fight') { banner(t('no_pause_online'), '#ffffff', 1.4); 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();
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); }
});
// ---------------------------------------------------------------- start
accounts.resume();
if (net && net.enabled) { net.auth.resume(); net.auth.onChange(() => { hud(); if (mode === 'title') showTitle(); }); }
hud();
if (!hostOk()) {
card(`<h1>Robot Clash</h1><p>${t('wrong_host')}</p><p class="credits">${CREDITS}</p>`);
} 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)
const scr = DEV.get('screen');
if (scr === 'league') { save.beaten = Math.max(save.beaten, 3); showLeague(); }
else if (scr === 'vs') showVs(RC.LEAGUE[4]);
else if (scr === 'settings') showSettings(openGarage);
else if (scr === 'help') showHelp(openGarage);
else if (scr === 'lobby') {
lobbyRows = [{ uid: 'a', name: 'BlechBrecher', flag: 'DE', fame: 1250, state: 'idle' }, { uid: 'b', name: 'SawQueen', flag: 'DE', fame: 430, state: 'inmatch' }, { uid: 'c', name: 'Rostlaube77', flag: 'AT', fame: 90, state: 'idle' }, { uid: 'd', name: 'Flipmaster', flag: 'GB', fame: 600, state: 'idle' }];
lobbyRoom = DEV.get('room') || null;
showLobby();
}
if (DEV.get('tab')) { const tb = document.querySelector(`.tab[data-slot="${DEV.get('tab')}"]`); if (tb) tb.click(); }
// dev: &buy=<part id> buys it through the real shop buttons (header check)
if (DEV.get('buy')) { const it = document.querySelector(`.item[data-id="${DEV.get('buy')}"]`); if (it) { it.click(); const b = document.querySelector('#detail button[data-act="buy"]'); if (b) b.click(); } }
// dev: &equip=wedge,flamer forces parts onto the robot (ignores cost), then shows the garage
if (DEV.get('equip') && !DEV.has('fight')) { for (const id of DEV.get('equip').split(',')) { const p = RC.PARTS[id]; if (p) { if (!save.owned.includes(id)) save.owned.push(id); save.build[p.slot] = id; } } persist(); view.showGarage(save.build, paintObj()); shop.render(); }
if (DEV.has('paint')) { // dev: open the paint booth with a test drawing
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')) startGate(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
})();