Files
Robot-Clash/game/game.js
2026-11-13 01:02:55 +01:00

660 lines
38 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 = 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 on the title screen, 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 store = Kit.store(ID);
const settings = Object.assign({ gfx: 'high', intro: true }, store.get('settings', {}));
const saveSettings = () => store.set('settings', settings);
const accounts = RC.Accounts(ID);
const newSave = () => ({
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', tutorialSeen: false,
});
let slot = null, save = null; // per account, set by enterAccount()
const persist = () => { if (slot && save) 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);
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 (mode === 'intro') { skipIntro(); return; }
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 (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 '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); }
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 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,
onBuild: () => view.showGarage(save.build, paintObj()),
onPaint: () => view.setPaint(paintObj()),
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 = ''; }
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 : '');
const playerName = () => (accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : '');
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 = accounts.current ? (accounts.current.guest ? '👤 ' + t('guest') : '👤 ' + accounts.current.name) : '👤 –';
$('bMute').textContent = audio.muted ? t('sound_off') : t('sound_on');
}
function setScreen(m) {
if (m !== 'garage' && painter.isOpen) painter.close();
mode = m;
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;
function startIntro() {
setScreen('intro');
hideOverlay();
if (!view) { showTitle(); return; }
const a = RC.LEAGUE[7], b = RC.LEAGUE[4];
view.showIntro([a.build, b.build], [a.paint, b.paint]);
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 [[1.2, SFX.clunk], [1.5, SFX.clunk], [1.62, SFX.clunk], [4.25, SFX.clunk], [4.6, 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 acc = accounts.current && !accounts.current.guest ? accounts.current : null;
const btns = acc
? `<button class="primary" id="bPlay">${t('play_as', { name: esc(acc.name) })}</button><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>`;
overlay.innerHTML = `<div class="title"><div class="big">ROBOT CLASH</div><div class="tag">${t('menu_text')}</div>
<div class="row">${btns}</div>
<div class="row"><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>`;
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('bSwitch', () => { accounts.logout(); hud(); showLogin(); });
on('bLogin', () => showLogin());
on('bReg', () => showRegister());
on('bGuest', () => { accounts.guest(); enterAccount(); });
on('bSet', () => showSettings(showTitle));
on('bHelp', () => showHelp(showTitle));
on('bLang', () => L.next());
on('bRank', () => showRanking(showTitle));
hud();
}
// ---------------------------------------------------------------- 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 enterAccount(fresh) {
slot = Kit.saveSlot(accounts.saveKey(), newSave);
save = slot.load();
repairSave();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (fresh && accounts.current && !accounts.current.guest) save.robotName = accounts.current.name.slice(0, 18);
persist();
hud();
shop.reset();
if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); showHelp(openGarage); } else openGarage();
}
// saves from older versions: missing parts, invalid ids
function repairSave() {
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);
}
function logout() { persist(); accounts.logout(); save = null; slot = null; F = null; hud(); startIntroOrTitle(); }
function startIntroOrTitle() { if (view) { const a = RC.LEAGUE[7], b = RC.LEAGUE[4]; view.showIntro([a.build, b.build], [a.paint, b.paint]); view.skipIntro(); } showTitle(); }
$('hUser').onclick = () => {
if (!accounts.current || mode === 'fight' || mode === 'pause') return;
SFX.click();
const back = currentBack();
card(`<h2>${t('account')}</h2><p>${accounts.current.guest ? t('guest_text') : t('logged_in_as', { name: esc(accounts.current.name) })}</p>
<div class="row"><button id="bOut">${accounts.current.guest ? t('to_title') : t('logout')}</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) {
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>`;
card(`<h2>${t('settings')}</h2><div class="set">
<span>${t('s_lang')}</span>${seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self]))}
<span>${t('s_music')}</span><input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">
<span>${t('s_sfx')}</span><input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">
<span>${t('s_mute')}</span>${seg('sMute', audio.muted ? '1' : '0', [['0', t('on')], ['1', t('off')]])}
<span>${t('s_gfx')}</span>${seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]])}
<span>${t('s_intro')}</span>${seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]])}
<span>${t('s_screen')}</span><div><button id="sFull">${t('win_full')}</button></div>
</div>
<h3>${t('s_controls')}</h3>${keysHtml()}
${save ? `<h3>${t('s_career')}</h3><div style="text-align:left"><button id="sReset">${t('reset')}</button></div>` : ''}
<div class="row"><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(); });
$('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)); };
$('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>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>`;
}
function showHelp(back) {
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) {
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();
}
$('bGMenu').onclick = () => { SFX.click(); persist(); startIntroOrTitle(); };
$('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>`,
{ 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]); }; });
$('bFight').onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); };
$('bBack').onclick = () => { SFX.click(); openGarage(); };
}
function showVs(opp) {
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`;
card(`<div class="vs"><div class="side">${RC.pic('icon', '🤖')}<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>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('fight_go_btn')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showLeague(); };
$('bGo').onclick = () => { SFX.click(); startFight(opp, false); };
}
// ---------------------------------------------------------------- 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], [paintObj(), 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);
introTick();
if (mode !== 'fight' || !F) return;
if (F.count > 0) {
F.count -= dt;
const n = Math.ceil(F.count);
if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } }
return;
}
const s = F.s, [me, en] = s.robots;
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()}`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('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: playerName(), 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 (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 (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 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') 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();
if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); }
});
// ---------------------------------------------------------------- start
accounts.resume();
hud();
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();
slot = Kit.saveSlot(accounts.saveKey(), newSave); save = slot.load(); repairSave(); hud();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true); else openGarage();
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('title')) startIntroOrTitle();
else startIntro();
})();