Files
Robot-Clash/game/game.js
2026-11-13 00:41:54 +01:00

441 lines
24 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: menu, workshop, league ladder, fight, result, saving, audio, scores.
Logic lives in parts.js / robot.js / combat.js / ai.js (no DOM), the 3D view in render3d.js,
the workshop panel in garage.js. Texts: lang.js via t('key'). Credits line stays in the menu. */
(function () {
'use strict';
const $ = Kit.$;
const W = 960, H = 540; // design size of the stage
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 = '';
// Credits (standard for every game): shown in the menu, links open in the normal browser
const DISCORD = 'https://discord.gg/Ej4JPmCZva';
const CREDITS = `© 2026 Michael Media · <a href="${DISCORD}" target="_blank" rel="noopener">Discord</a>`;
// ---------------------------------------------------------------- services
const L = Kit.i18n(window.LANG, { prefix: ID });
const t = L.t;
const slot = Kit.saveSlot(ID + '.save', () => ({
money: 400, 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', name: '', tutorialSeen: false,
}));
let save = slot.load();
const persist = () => slot.save(save);
const audio = Kit.createAudio({
prefix: ID,
files: ['sfx_click', 'sfx_buy', 'sfx_hit', 'sfx_win', 'sfx_lose', 'music_garage', 'music_fight'],
});
const scores = Kit.scores({ url: DB_URL });
const DEV = new URLSearchParams(location.search);
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', p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok',
},
onPress(a) {
if (a === 'pause') togglePause();
else if (a === 'mute') toggleMute();
else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); }
},
});
// ---------------------------------------------------------------- sound (synth until ComfyGen clips exist)
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.05, 'square', 0.08); },
buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.1); },
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); },
win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09); },
lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.12); },
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.noise(0.2, 0.35, 1600); audio.tone(190, 0.15, 'sawtooth', 0.1, -90); } 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.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.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break;
case 'ko': 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.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 '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.tone(900 + Math.random() * 60, 0.1, 'sawtooth', 0.035);
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); } catch (err) { console.error(err); }
Kit.fit($('app'), { 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 garage = RC.Garage({
t, getSave: () => save, onSave: persist,
onBuild: () => { view.showGarage(save.build, save.paint); garageTitle(); },
onPaint: () => { view.showGarage(save.build, save.paint); garageTitle(); },
sfx: SFX,
});
// ---------------------------------------------------------------- state
let mode = 'menu'; // menu | 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) { overlay.innerHTML = `<div class="card">${html}</div>`; overlay.classList.remove('hide'); }
function hideOverlay() { overlay.classList.add('hide'); overlay.innerHTML = ''; }
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 : '');
function hud() {
$('hMoney').textContent = Kit.fmt(save.money);
$('hFame').textContent = Kit.fmt(save.fame);
$('hLeague').textContent = t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length });
$('bMute').textContent = audio.muted ? t('sound_off') : t('sound_on');
}
function garageTitle() {
$('gName').textContent = save.robotName;
$('gSub').textContent = weaponName(save.build);
}
function setScreen(m) {
mode = m;
document.body.classList.toggle('fighting', m === 'fight' || m === 'pause');
show('garage', m === 'garage');
show('gTitle', m === 'garage');
show('fightHud', m === 'fight' || m === 'pause' || m === 'result');
}
// ---------------------------------------------------------------- menu
function boardHtml() { return scores.enabled ? `<h2 style="margin-top:14px;font-size:18px">${t('ranking')}</h2><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>`; }
}
function showMenu() {
setScreen('menu');
F = null;
if (view) view.showGarage(save.build, save.paint);
audio.music('music_garage');
if (!view) { card(`<h1>Robot Clash</h1><p>${t('no_webgl')}</p><p class="credits">${CREDITS}</p>`); return; }
const nameField = scores.enabled ? `<div><input id="name" maxlength="20" placeholder="${esc(t('name_placeholder'))}" value="${esc(save.name)}"></div>` : '';
card(`<h1>ROBOT CLASH</h1><p>${t('menu_text')}</p>
${nameField}<button class="primary" id="bStart">${save.games ? t('continue_career') : t('play')}</button>
<div class="row"><button id="bHelp">${t('how_to')}</button><button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>
<button id="bReset">${t('reset')}</button></div>
${boardHtml()}<p class="credits">${CREDITS}</p>`);
$('bLang').onclick = () => { SFX.click(); L.next(); };
$('bHelp').onclick = () => { SFX.click(); showHelp(showMenu); };
$('bReset').onclick = () => { SFX.click(); confirmReset(); };
const name = $('name'), start = $('bStart');
if (name) {
const check = () => { const n = Kit.cleanName(name.value); start.disabled = !n || Kit.badName(n); };
name.addEventListener('input', check); check();
name.addEventListener('keydown', e => { if (e.key === 'Enter' && !start.disabled) start.click(); });
}
start.onclick = () => {
if (name) { save.name = Kit.cleanName(name.value); persist(); }
SFX.click();
if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); showHelp(openGarage); } else openGarage();
};
fillBoard();
}
function showHelp(back) {
card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>
<div class="keys"><b>W A S D / ↑ ← ↓ →</b><span>${t('key_drive')}</span><b>${t('key_space')}</b><span>${t('key_weapon')}</span>
<b>Shift / E</b><span>${t('key_tower')}</span><b>P / Esc</b><span>${t('pause')}</span><b>${t('key_pad')}</b><span>${t('key_pad_text')}</span></div>
<p style="margin-top:12px">${t('help_arena')}</p><button class="primary" id="bOk">${t('ok')}</button>`);
$('bOk').onclick = () => { SFX.click(); back(); };
}
function confirmReset() {
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(); showMenu(); };
$('bYes').onclick = () => { resetSave(); persist(); hud(); SFX.click(); showMenu(); };
}
function resetSave() {
save.money = 400; save.fame = 0; save.best = 0; save.season = 1; save.beaten = 0; save.wins = 0; save.losses = 0; save.games = 0;
save.owned = Object.values(RC.STARTER).filter(Boolean); save.build = Object.assign({}, RC.STARTER);
save.paint = { body: 0xff7a1a, accent: 0x15171b }; save.robotName = 'Clank'; save.tutorialSeen = false;
}
// ---------------------------------------------------------------- workshop + league
function openGarage() {
hideOverlay();
setScreen('garage');
view.showGarage(save.build, save.paint);
audio.music('music_garage');
garage.render(); garageTitle(); hud();
}
$('bGMenu').onclick = () => { SFX.click(); showMenu(); };
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
$('bLeague').onclick = () => { SFX.click(); showLeague(); };
function showLeague() {
setScreen('league');
const rows = RC.LEAGUE.map((o, i) => {
const cls = i < save.beaten ? 'done' : i === save.beaten ? 'next' : 'locked';
return `<li class="${cls}"><span>${i < save.beaten ? '✓' : i + 1}</span><span><span class="nm">${o.name}</span><br><span class="muted">${t('style_' + o.style)}</span></span>
<span class="muted">${weaponName(o.build)}</span><span class="pz">${Kit.fmt(Math.round(o.prize * seasonMul()))}</span></li>`;
}).join('');
card(`<h2>${t('league_title', { s: save.season })}</h2><p>${t('league_text')}</p><ol class="ladder">${rows}</ol>
<div class="row"><button class="primary" id="bFight">${t('fight_vs', { name: RC.LEAGUE[save.beaten].name })}</button><button id="bBack">${t('back')}</button></div>`);
$('bFight').onclick = () => { SFX.click(); startFight(RC.LEAGUE[save.beaten], false); };
$('bBack').onclick = () => { SFX.click(); openGarage(); };
}
// ---------------------------------------------------------------- fight
function startFight(opp, training) {
hideOverlay();
const stA = RC.stats(save.build), stB = RC.stats(opp.build);
const seed = (Date.now() & 0xffff) + save.games * 31;
const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name] });
const skill = Math.min(1, opp.skill + (save.season - 1) * 0.12);
F = { s, opp, training, brain: RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4,
acc: [0, 0], accT: 0, banner: null, ended: false };
// 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], [save.paint, opp.paint]);
$('fN0').textContent = save.robotName; $('fN1').textContent = opp.name;
$('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(opp.build);
$('fH0').style.background = hex(save.paint.body); $('fH1').style.background = hex(opp.paint.body);
fx.clear();
setScreen('fight');
audio.music('music_fight');
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) };
}
function playerInput() {
const k = {
throttle: (input.down('up') ? 1 : 0) - (input.down('down') ? 1 : 0),
turn: (input.down('right') ? 1 : 0) - (input.down('left') ? 1 : 0),
fire: input.down('fire'), fire2: input.down('fire2'),
};
const g = pad();
if (g) {
k.throttle = Kit.clamp(k.throttle + g.throttle, -1, 1); k.turn = Kit.clamp(k.turn + g.turn, -1, 1);
k.fire = k.fire || g.fire; k.fire2 = k.fire2 || g.fire2;
}
return k;
}
function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; }
function update(dt) {
fx.update(dt);
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;
RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]);
for (const e of s.events) {
SFX.event(e);
if (e.type === 'dmg') F.acc[e.who] += e.amount;
else if (e.type === 'pit_open') banner(t('pit_open'), '#ff4a3a', 2);
else if (e.type === 'pit') banner(t('into_pit'), '#ff4a3a', 2.2);
else if (e.type === 'ko') banner(t('knockout'), '#ff7a1a', 2.2);
}
view.events(s.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(); }
}
function fightHud() {
if (!F) return;
const s = F.s;
for (let i = 0; i < 2; i++) $('fH' + i).style.width = (s.robots[i].hp / s.robots[i].maxHp * 100).toFixed(1) + '%';
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 - RC.ARENA.pitOpensAt < 10 && s.left > RC.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];
const lines = [];
let money = 0, fame = 0, champion = false;
if (!F.training) {
const prize = Math.round(opp.prize * seasonMul());
save.games++;
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.2); money += ap; lines.push([t('r_appearance'), ap]);
save.losses++;
}
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.12 + (res.reason === 'pit' && !won ? me.st.value * 0.05 : 0));
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()}`);
$('bGarage').onclick = () => { SFX.click(); openGarage(); };
if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false); };
if (!F.training && save.fame > save.best) {
save.best = save.fame; persist();
scores.submit({ name: save.name || save.robotName, score: save.fame, level: save.season }).then(fillBoard);
} else fillBoard();
}
// ---------------------------------------------------------------- loop
let lastNow = 0;
function render(alpha, now) {
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 (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 (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('fight_hint'), W / 2, H - 16);
}
}
}
const loop = Kit.loop({ step: 1000 / 60, update, render }).start();
function togglePause() {
if (mode === 'fight') {
mode = 'pause'; loop.pause();
card(`<h2>${t('pause')}</h2><div class="row"><button class="primary" id="bGo">${t('continue')}</button><button id="bQuit">${t('give_up')}</button></div>`);
$('bGo').onclick = 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;
$('bLangTop').onclick = () => { SFX.click(); L.next(); };
addEventListener('blur', () => { if (mode === 'fight') togglePause(); });
// language switch: static texts update themselves (data-i18n), dynamic screens are drawn again
L.onChange(() => {
hud();
if (mode === 'menu') showMenu();
else if (mode === 'garage') { garage.render(); garageTitle(); }
else if (mode === 'league') showLeague();
if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); }
});
if (slot.failed()) console.warn('save failed');
// repair saves from older versions: missing parts, invalid ids
save.owned = (save.owned || []).filter(id => RC.PARTS[id]);
for (const sl of RC.SLOTS) { if (save.build[sl] && !RC.PARTS[save.build[sl]]) save.build[sl] = null; if (save.build[sl] && !save.owned.includes(save.build[sl])) save.owned.push(save.build[sl]); }
for (const sl of Object.keys(RC.REQUIRED)) if (!save.build[sl]) { save.build[sl] = RC.STARTER[sl]; if (!save.owned.includes(RC.STARTER[sl])) save.owned.push(RC.STARTER[sl]); }
save.beaten = Kit.clamp(save.beaten | 0, 0, RC.LEAGUE.length - 1);
hud();
// dev: index.html?play = straight into the workshop, ?fight = training fight
if (view && DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true);
else if (view && DEV.has('play')) openGarage(); else showMenu();
})();