, else local profile / guest
// Two completely separate games: the campaign (league, seasons) and online play (PvP).
// Money, parts and robots never cross over - they simply live in different saves.
// Opening the page always starts in online mode; the campaign keeps the old save key,
// so an existing game carries on as the campaign.
let gameMode = 'online';
const saveKey = () => (fbAcc() ? ID + '.save.fb_' + fbAcc().uid : accounts.saveKey())
+ (gameMode === 'online' ? '.online' : '');
function setMode(m) {
const onlineOk = net && net.enabled && !LIVE.onlineOff;
gameMode = onlineOk ? m : 'campaign'; // no Firebase or switched off: campaign only
document.body.dataset.gmode = gameMode;
}
function switchMode(m) {
if (m === gameMode) return;
persist(); // keep the mode we are leaving
setMode(m);
loadSave(); hud(); shop.reset();
openGarage();
// banner() only works during a fight (it writes to F) - the mechanic says it instead
$('mechTip').textContent = t(gameMode === 'online' ? 'mode_online' : 'mode_campaign') + ': ' + t('mode_switched');
}
function hud() {
$('hMoney').textContent = save ? Kit.fmt(save.money) : '–';
$('hFame').textContent = save ? Kit.fmt(save.fame) : '–';
$('hRank').textContent = save ? t('rank_' + RC.Progress.rankOf(save.fame).key) : '';
const ht = $('hTour');
if (ht) {
const running = save && save.tour && !save.tour.done;
const on = running || (typeof tourOpen === 'function' && tourOpen());
ht.classList.toggle('hide', !on);
if (on) ht.textContent = '🏆 ' + (running ? t('tour_continue') : t('tournament'));
}
const camp = gameMode === 'campaign';
$('hModeLbl').textContent = camp ? t('hud_league') : t('mode_online');
$('hLeague').textContent = !save ? '–' : camp ? t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length }) : t('mode_pvp');
$('hUser').textContent = fbUser() ? '👤 ' + fbUser().name : accounts.current ? (accounts.current.guest ? '👤 ' + t('guest') : '👤 ' + accounts.current.name) : save ? '👤 ' + t('guest') : '👤 –';
$('bMute').textContent = audio.muted ? '🔇' : '🔊';
$('bMute').title = (audio.muted ? t('sound_off') : t('sound_on')) + ' (M)';
}
function setScreen(m) {
if (m !== 'garage' && painter.isOpen) painter.close();
if (mode === 'garage' && m !== 'garage') cloudFlush(); // settle the cloud save when leaving the workshop
if (m !== 'garage' && editorOpen) { editorOpen = false; view.freeze(false); }
if (m !== 'title' && titleRankSub) { titleRankSub.close(); titleRankSub = null; } // stop the title's live ranking
if (m !== mode) overlayEnter();
mode = m;
document.body.dataset.mode = m; // CSS shows/places the HUD per screen
document.body.classList.toggle('fighting', m === 'fight' || m === 'pause');
if (m !== 'fight' && m !== 'pause') { const dv = $('dmgvig'); if (dv) dv.style.opacity = 0; } // clear the red damage glow when the fight is over
show('shop', m === 'garage');
show('fightHud', m === 'fight' || m === 'pause' || m === 'result');
backdrop(m === 'garage' ? 'bg_workshop.jpg' : null);
}
// ---------------------------------------------------------------- intro + title
let introCue = 0;
let gateDone = false;
function startGate(next) {
if (gateDone) { next(); return; }
gateDone = true;
setScreen('intro'); // defined UI state while the gate is up (HUD stays hidden)
const logo = `ROBOT CLASH
`;
overlay.innerHTML = `${logo}
${t('click_start')}
${CREDITS}
`;
overlay.classList.remove('hide'); overlay.classList.remove('clear');
overlay.style.backgroundImage = `url("${img('bg_start.jpg')}")`; // start screen backdrop (ComfyGen)
const go = e => {
if (e) { e.stopPropagation(); if (e.preventDefault) e.preventDefault(); } // must not also skip the intro
removeEventListener('pointerdown', go, true); removeEventListener('keydown', go, true);
if (audio.unlock) audio.unlock();
next();
};
addEventListener('pointerdown', go, true);
addEventListener('keydown', go, true);
}
function startIntro() {
setScreen('intro');
hideOverlay();
if (!view) { showTitle(); return; }
const a = RC.LEAGUE[7], b = RC.LEAGUE[4];
view.showIntro([a.build, b.build], [oppPaint(a), oppPaint(b)]);
introCue = 0;
audio.music('music_title');
if (!settings.intro) view.skipIntro();
}
function skipIntro() { if (view) view.skipIntro(); }
stageClick(() => { if (mode === 'intro') skipIntro(); });
function stageClick(fn) { $('stage').addEventListener('pointerdown', fn); }
function introTick() {
if (mode !== 'intro' || !view) return;
const it = view.introTime;
for (const [at, f] of [[0.4, SFX.clunk], [0.62, SFX.clunk], [2.2, SFX.clunk], [2.5, SFX.clunk], [3.4, SFX.clunk]]) {
if (introCue < at && it >= at) f();
}
introCue = it;
if (it >= RC.INTRO_END) showTitle();
}
function showTitle() {
setScreen('title');
audio.music('music_title');
const fb = net && net.enabled;
const acc = fb ? fbAcc() : (accounts.current && !accounts.current.guest ? accounts.current : null);
const online = fb ? `🌍 ${t('online_play')} ` : '';
const btns = acc
? `${t('play_as', { name: esc(acc.name) })} ${online}${t('switch_account')} `
: `${t('login')} ${t('register')} ${t('play_guest')} ${online}`;
// logo picture when ComfyGen made one, otherwise the lettering (never both, never nothing)
const logo = `ROBOT CLASH
`;
overlay.innerHTML = `
${logo}
${t('menu_text')}
${liveBanner()}
⚙ ${t('settings')} ${t('how_to')}
🌐 ${t('lang_self')} ${save ? `🏅 ${t('achievements')} ` : ''}${rank.enabled ? `🏆 ${t('ranking')} ` : ''}
${CREDITS}
${rank.enabled ? `
🏆 ${t('ranking')} ● ${t('rank_live')} ${t('loading')} ` : ''}
`;
overlay.classList.remove('hide'); overlay.classList.add('clear'); overlay.style.backgroundImage = '';
const on = (id, f) => { const el = $(id); if (el) el.onclick = () => { SFX.click(); f(); }; };
on('bPlay', () => enterAccount());
on('bOnline', () => startOnline());
on('bSwitch', () => { signOut(); fb ? showOnlineLogin(false, null, 'career') : showLogin(); });
on('bLogin', () => (fb ? showOnlineLogin(false, null, 'career') : showLogin()));
on('bReg', () => (fb ? showOnlineLogin(true, null, 'career') : showRegister()));
on('bGuest', () => { if (fbAcc()) net.auth.logout(); accounts.guest(); enterAccount(); });
on('bSet', () => showSettings(showTitle));
on('bHelp', () => showHelp(showTitle));
on('bLang', () => L.next());
on('bAch', () => showAchievements(showTitle));
on('bRank', () => showRanking(showTitle));
hud();
if (rank.enabled) startTitleRank();
}
// right-side live ranking on the title: names fade in from the bottom up, re-triggered on every live update
function startTitleRank() {
const el = $('trankList'); if (!el) return;
if (titleRankSub) titleRankSub.close();
titleRankSub = rank.watch(rows => {
if (mode !== 'title') return;
const list = $('trankList'); if (!list) return;
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
const r8 = rows.slice(0, 8), n = r8.length;
list.innerHTML = n ? r8.map((r, i) => ``
+ `${i + 1} ${flagHtml(r.flag || 'XX')} `
+ `${esc(r.name)} ⭐ ${Kit.fmt(r.fame)} `).join('')
: `${t('no_scores')} `;
});
}
// ---------------------------------------------------------------- online lobby
let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker)
let ntour = null, inNetTour = false; // live multiplayer tournament
async function startOnline(dest) { // dest 'lobby' -> player list, else the workshop (main page)
if (!net.enabled) return;
if (gameMode !== 'online') { setMode('online'); if (save) { loadSave(); hud(); } } // online uses its own save
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 => { const opp = { name: m.opp.name, build: m.opp.build, paint: m.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: m.opp.flag }; prepOpp(opp, () => startFight(opp, false, false, { id: m.id, host: m.host, seed: m.seed })); });
lobby.onCancel(() => { pendingOut = null; if (mode === 'lobby') { renderLobby(); SFX.deny(); } });
}
ensureFlag(() => { if (dest === 'lobby') showLobby(); else openGarage(); }); // country first, then main page / lobby
}
async function joinAnon() {
if (!save) { accounts.guest(); loadSave(); }
const r = await net.auth.guest(playerName() || t('guest'));
if (!r.ok) { SFX.deny(); showOnlineLogin(false, r.error, 'online'); return; }
hud(); startOnline();
}
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
? `${t('f_name')} `
: '';
card(`${reg ? t('register') : t('login')} ${t('online_login_text')}
${f}${t('f_email')}
${t('f_pass')}
${errKey ? errText(errKey) : ''}
${t('back')} ${reg ? t('register_go') : t('login')}
${reg ? '' : t('no_account') + ' '}${reg ? t('login') : t('register')}
${next === 'online' ? `👤 ${t('online_guest')}
` : ''}`, { 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 => `${t('cc_' + f)} `).join('');
const room = (f, label, flag) => `${flag ? flagHtml(f) : ''} ${label} ${f === 'all' ? total : cnt(f)} `;
const rooms = room('all', t('all_countries'), false) + FLAGS.map(f => room(f, t('cc_' + f), true)).join('');
const prow = (r, me) => `${flagHtml(me ? save.flag : r.flag)} ${esc(me ? playerName() : r.name)}${me ? ` (${t('you')}) ` : ''} \u2B50 ${Kit.fmt((me ? save.fame : r.fame) | 0)} ${me ? ' ' : (r.state === 'idle' ? `${t('challenge')} ` : `${t('busy')} `)}
`;
const list = here.map(r => prow(r, false)).join('');
const title = lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(lobbyRoom) + ' ' + t('cc_' + lobbyRoom);
overlay.innerHTML = `
${title} (${here.length + (showMe ? 1 : 0)})
${t('your_flag')} ${flagOpts}
${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `
${t('lobby_empty')}
`)}
${pendingOut ? `
${t('waiting_accept')} ${t('cancel')}
` : ''}
${t('back')} 🏆 ${t('ltour_title')} ${t('quick_match')}
`;
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(); };
$('lTour').onclick = () => { SFX.click(); openNetTourney(); };
}
// ---------------------------------------------------------------- live multiplayer tournament
function openNetTourney() {
if (!(net && net.enabled && net.auth.current)) { showOnlineLogin(false, null, 'online'); return; }
const u = net.auth.current;
if (!ntour) ntour = RC.NetTourney(net, { uid: u.uid, name: u.name || playerName(), flag: save.flag || 'XX' }, {
onView: v => { if (inNetTour) renderNetTourney(v); },
startMatch: info => startNetTourMatch(info),
});
inNetTour = true;
ntour.join(save.build, paintObj());
renderNetTourney(ntour.view());
}
function leaveNetTourney() {
inNetTour = false;
if (ntour) { ntour.leave(); }
}
function renderNetTourney(v) {
if (!inNetTour) return;
const pls = v.players.map(p => `${flagHtml(p.flag)} `
+ `${esc(p.name)}${p.me ? ` (${t('you')}) ` : ''} `
+ `${p.ready ? '✔ ' + t('ltour_ready') : t('ltour_waiting')}
`).join('')
|| `${t('ltour_empty')}
`;
let body, buttons = '';
if (v.phase === 'running' || v.phase === 'done') {
body = netBracketHtml(v);
if (v.me.match) buttons = `▶ ${t('tour_fight')} (${esc(v.me.match.opp || 'Bye')}) `;
else if (v.me.champion) body += `🏆 ${t('tour_won')}
`;
else if (v.me.out) body += `${t('tour_out')}
`;
else body += `${t('ltour_wait_round')}
`;
} else {
const me = v.players.find(p => p.me);
body = `${v.phase === 'countdown' ? t('ltour_countdown', { n: v.countdown }) : t('ltour_lobby', { n: v.readyCount })}
`
+ `${pls}
`;
buttons = me ? `${me.ready ? t('ltour_unready') : t('ltour_setready')} ` : '';
}
card(`🏆 ${t('ltour_title')} ${body}
${buttons}${t('back')}
`, { wide: true, bg: 'bg_title.jpg' });
if ($('ntReady')) $('ntReady').onclick = () => { SFX.click(); const me = v.players.find(p => p.me); ntour.setReady(!(me && me.ready)); };
if ($('ntFight')) $('ntFight').onclick = () => { SFX.click(); if (v.me.match && v.me.match.opp == null) return; /* bye */ };
$('ntBack').onclick = () => { SFX.click(); leaveNetTourney(); showLobby(); };
}
function netBracketHtml(v) {
if (!v.order) return '';
const rounds = RC.LTourney.rounds(v.order, v.results);
const name = u => (u ? (v.players.find(p => p.uid === u) || {}).name || u.slice(0, 5) : '—');
let cols = '';
for (let r = 0; r < rounds.length; r++) {
const col = rounds[r]; if (col.length < 2 && r) continue;
let rows = '';
for (let i = 0; i < col.length; i += 2) {
rows += `${[col[i], col[i + 1]].map(u => {
const mine = u === net.auth.current.uid;
return `
${esc(name(u))}
`; }).join('')}
`;
}
cols += `${t('tour_round_' + (RC.Tourney.ROUND_KEY[r] || 'final'))}
${rows}
`;
}
return `${cols}
`;
}
function startNetTourMatch(info) {
const opp = { name: info.opp.name || 'Rival', build: info.opp.build, paint: info.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: info.opp.flag };
prepOpp(opp, () => startFight(opp, false, false, { id: info.id, host: info.host, seed: info.seed, tourney: { round: info.round, pair: info.pairIndex, oppUid: info.oppUid } }));
}
function endNetTourFight(res, won, me) {
if (ntour) ntour.reportWin(F.online.tourney.round, F.online.tourney.pair, won ? net.auth.current.uid : F.online.tourney.oppUid);
save.games++; if (won) save.wins++; else save.losses++;
save.fame += won ? 120 : 30; persist(); hud();
(won ? SFX.win : SFX.lose)();
setScreen('result');
card(`${won ? t('victory') : t('defeat')} ${esc(F.opp.name)}
🏆 ${t('ltour_title')}
`, { bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('ntRes').onclick = () => { SFX.click(); inNetTour = true; renderNetTourney(ntour.view()); };
}
function showIncoming(c) {
card(`${t('challenge_in')} ${flagHtml(c.fromFlag)} ${esc(c.fromName)} ${t('wants_fight')}
${t('decline')} ${t('accept')}
`);
$('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(`${t('login')}
${profs.length ? `${t('local_profiles')}
${profs.map(p => `${esc(p.name)} `).join('')}
` : ''}
${t('f_name')}
${t('f_pass')}
${t('f_remember')}
${errKey ? t(errKey) : ''}
${t('back')} ${t('login')}
${t('no_account')} ${t('register')}
${t('local_note')}
`, { 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(`${t('register')} ${t('register_text')}
${t('f_name')}
${t('f_pass')}
${t('f_pass2')}
${t('back')} ${t('register_go')}
${t('local_note')}
`, { 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()); });
cloudPull();
}
// registered account: fetch the cloud save; take it if newer, else push the local copy up (first migration)
function cloudPull() {
const a = fbAcc(); if (!a) return;
const id = cloudId(), m = gameMode; // this mode's cloud slot
cloud.pull(id).then(cl => {
const cur = fbAcc();
if (!save || !cur || cur.uid !== a.uid || gameMode !== m) return; // account or mode changed while we waited
if (cl && RC.CloudSave.newer(cl, save)) {
save = cl; repairSave(); slot.save(save); hud(); shop.reset();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (mode === 'garage') { shop.render(); view.showGarage(save.build, paintObj()); }
} else {
cloud.flush(id, save);
}
});
}
function enterAccount(fresh) {
loadSave();
refreshDev();
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
if (fresh && who) save.robotName = who.name.slice(0, 18);
persist();
hud();
shop.reset();
ensureFlag(() => { // pick a country first, then tutorial / workshop
if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); startTutorial(openGarage); } else openGarage();
});
}
// saves from older versions: missing parts, invalid ids, hangar migration
function repairSave() {
save.owned = (save.owned || []).filter(id => RC.PARTS[id]);
if (save.flagSet === undefined) save.flagSet = !!(save.flag && save.flag !== 'XX'); // old saves that already picked a flag keep it
// weight classes: an older save has one league - that progress becomes the medium class
if (!save.leagues) {
save.leagues = { light: { beaten: 0, season: 1 },
medium: { beaten: save.beaten | 0, season: save.season || 1 },
heavy: { beaten: 0, season: 1 } };
}
for (const c of RC.CLASSES) if (!save.leagues[c.id]) save.leagues[c.id] = { beaten: 0, season: 1 };
if (!RC.CLASSES.some(c => c.id === save.cls)) save.cls = 'medium';
RC.setClass(save.cls);
save.beaten = save.leagues[save.cls].beaten; save.season = save.leagues[save.cls].season;
// hangar migration: older saves have only build/paint/robotName -> make it robot slot 0
if (!Array.isArray(save.robots) || !save.robots.length) {
save.robots = [{ name: save.robotName || 'Clank', build: save.build || Object.assign({}, RC.STARTER), paint: save.paint || { body: 0xff7a1a, accent: 0x15171b } }];
save.active = 0;
}
save.active = Kit.clamp(save.active | 0, 0, save.robots.length - 1);
const fixBuild = b => {
// migrate single weapon (+ Plan-10 mount) to the weapons list; then drop the old fields
if (!Array.isArray(b.weapons)) b.weapons = RC.weaponsOf(b).map(w => ({ id: w.id, side: w.side, up: w.up }));
delete b.weapon; delete b.mount;
b.weapons = b.weapons.filter(w => w && RC.PARTS[w.id] && RC.PARTS[w.id].slot === 'weapon').slice(0, RC.MAX_WEAPONS);
for (const w of b.weapons) { if (!RC.MOUNTS[w.side]) w.side = 'front'; w.up = Math.max(-0.3, Math.min(0.6, +w.up || 0)); }
for (const sl of RC.SLOTS) {
if (sl === 'weapon') continue;
if (b[sl] && !RC.PARTS[b[sl]]) b[sl] = null;
if (b[sl] && !save.owned.includes(b[sl])) save.owned.push(b[sl]);
}
for (const sl of Object.keys(RC.REQUIRED)) if (!b[sl]) { b[sl] = RC.STARTER[sl]; if (!save.owned.includes(RC.STARTER[sl])) save.owned.push(RC.STARTER[sl]); }
};
for (const r of save.robots) { r.build = r.build || Object.assign({}, RC.STARTER); r.paint = r.paint || { body: 0xff7a1a, accent: 0x15171b }; r.name = r.name || 'Robot'; fixBuild(r.build); }
// load the active robot into the live fields the rest of the game uses
const a = save.robots[save.active];
save.build = a.build; save.paint = a.paint; save.robotName = a.name;
save.beaten = Kit.clamp(save.beaten | 0, 0, RC.LEAGUE.length - 1);
// 3 paint save slots (account-wide presets); first slot seeds from the current paint
if (!Array.isArray(save.paintSlots) || save.paintSlots.length !== 3) {
const base = { body: save.paint.body, accent: save.paint.accent };
save.paintSlots = [{ ...base, decal: save.paint.decal || null, drawn: !!save.paint.drawn },
{ ...base, decal: null, drawn: false }, { ...base, decal: null, drawn: false }];
}
save.paintSlot = Kit.clamp(save.paintSlot | 0, 0, 2);
}
// 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 || $('cards'); if (!el) return;
const rows = save.robots.map((r, i) => `
${esc(r.name)}
${esc(weaponName(r.build))}
${i === save.active ? `
${t('active_robot')} ` : `
${t('use')} `}
${save.robots.length > 1 ? `
✕ ` : '
'}
`).join('');
el.innerHTML = `${rows}
${save.robots.length < MAX_ROBOTS ? `+ ${t('new_robot')} ` : `${t('hangar_full')}
`}`;
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();
cloudFlush(); // push now, while we still have the auth token
if (lobby && onlineReady) { lobby.leave(); onlineReady = false; lobbyRows = []; pendingOut = null; }
if (ntour) { ntour.leave(); inNetTour = false; }
if (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(`${t('account')} ${who ? t('logged_in_as', { name: esc(who.name) }) + (who.email ? `${esc(who.email)} ` : '') : t('guest_text')}
${who ? t('logout') : t('to_title')} ${t('back')}
`);
$('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) => `${opts.map(([v, label]) => `${label} `).join('')}
`;
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
const item = (label, ctl) => `${label} ${ctl}`;
card(`${t('settings')}
${item(t('s_lang'), seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self])))}
${save ? item(t('s_country'), `${FLAGS.map(f => `${t('cc_' + f)} `).join('')} `) : ''}
${item(t('s_music'), ` `)}
${item(t('s_sfx'), ` `)}
${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))}
${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_quiet'), seg('sQuiet', settings.quiet ? '1' : '0', [['0', t('off')], ['1', t('on')]]))}
${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')]]))}
${isDev ? `🛠 Dev · Coins
+10k +100k
+1M Reset 800
` : ''}
${t('s_account')}
${who ? '👤 ' + esc(who.name) + ' ' + (who.email ? ' ' + esc(who.email) + ' ' : '') : '👤 ' + t('guest')}
${save ? `${who ? t('logout') : t('to_title')} ` : ''}
⛶ ${t('win_full')} 🎮 ${t('s_controls')}
${save ? `${t('reset')} ` : ''}${t('back')}
`, { 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('sGfx', v => { settings.gfx = v; saveSettings(); if (view) view.setQuality(v); });
segOn('sIntro', v => { settings.intro = v === '1'; 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('sQuiet', v => { settings.quiet = v === '1'; saveSettings(); });
segOn('sArena', v => { settings.arena = v; saveSettings(); });
if ($('sCountry')) $('sCountry').onchange = e => { save.flag = e.target.value; save.flagSet = true; persist(); if (lobby) lobby.refresh(); hud(); };
$('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol);
$('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value);
$('sSfx').onchange = () => SFX.click();
$('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); };
if (isDev && save) overlay.querySelectorAll('[data-coin]').forEach(b => b.onclick = () => {
SFX.buy(); const v = b.dataset.coin;
save.money = v === 'set800' ? 800 : Math.min(1e9, (save.money | 0) + (+v || 0));
persist(); hud(); showSettings(back);
});
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 `W A S D / ↑ ← ↓ → ${t('key_drive')} ${t('key_space')} ${t('key_weapon')}
Shift / E ${t('key_tower')} C ${t('key_cam')} P / Esc ${t('pause')} M ${t('sound_on')} / ${t('sound_off')}
${t('key_pad')} ${t('key_pad_text')}
`;
}
// 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(`${t('tut_title')} ${n}/${TUT.length}
${t(TUT[i])}
${t('tut_skip')}
${n === TUT.length ? t('tut_go') : t('tut_next')}
`,
{ bg: 'bg_workshop.jpg' });
$('tNext').onclick = () => { SFX.click(); i++; step(); };
$('tSkip').onclick = () => { SFX.click(); done(); };
};
step();
}
// first start: pick the country whose flag shows on the ranking / in the lobby (changeable later in settings)
function chooseFlag(done) {
overlayEnter();
let pick = (save && FLAGS.includes(save.flag)) ? save.flag : 'XX';
card(`🌍 ${t('country_title')} ${t('country_text')}
${FLAGS.map(f => `${flagHtml(f)}${t('cc_' + f)} `).join('')}
${t('country_go')}
`, { bg: 'bg_title.jpg', wide: true });
overlay.querySelectorAll('.flagbtn').forEach(b => b.onclick = () => { pick = b.dataset.f; SFX.click(); overlay.querySelectorAll('.flagbtn').forEach(x => x.classList.toggle('on', x.dataset.f === pick)); });
$('cfGo').onclick = () => { if (save) { save.flag = pick; save.flagSet = true; persist(); } if (lobby) lobby.refresh(); SFX.click(); done(); };
}
const ensureFlag = done => { if (save && !save.flagSet) chooseFlag(done); else done(); };
// one line for the running event and one for the admin's message
function liveBanner() {
const out = [];
if (LIVE.event) {
const n = liveText(LIVE.event.name) || t('event_running');
const extra = LIVE.event.prizeMul !== 1 ? ` · ${t('event_prize', { n: LIVE.event.prizeMul })}` : '';
out.push(`${t('event')} ${esc(n)}${extra}
`);
}
const m = liveText(LIVE.motd);
if (m) out.push(`${esc(m)}
`);
return out.join('');
}
function showAchievements(back) {
overlayEnter();
const P = RC.Progress, r = P.rankOf(save.fame);
const pct = Math.round(r.pct * 100);
const nextLine = r.next
? t('rank_next', { n: t('rank_' + r.next.key), f: Kit.fmt(r.next.at - save.fame) })
: t('rank_top');
const rows = P.ACHIEVEMENTS.map(a => {
const done = !!(save.ach && save.ach[a.id]);
return `${done ? '🏅' : '🔒'}
${t('ach_' + a.id)} ${t('achd_' + a.id)}
${Kit.fmt(a.reward)}
`;
}).join('');
card(`🏅 ${t('achievements')}
${t('rank_' + r.key)} ${nextLine}
${t('ach_done', { n: P.earned(save), m: P.total })}
${rows}
${t('back')}
`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); back(); };
}
function showHelp(back) {
overlayEnter();
card(`${t('how_to')} ${t('help_text')}
${keysHtml()}
${t('help_arena')}
${t('ok')} `, { bg: 'bg_title.jpg' });
$('bOk').onclick = () => { SFX.click(); back(); };
}
let rankSub = null, titleRankSub = null, boardFame = {}, boardIdx = {};
const closeRank = () => { if (rankSub) { rankSub.close(); rankSub = null; } };
function showRanking(back) {
overlayEnter();
card(`🏆 ${t('ranking')} ${rank.enabled ? '● ' + t('rank_live') + ' ' : ''}
${t('loading')}
${t('back')}
`, { bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); closeRank(); back(); };
boardFame = {}; boardIdx = {};
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
closeRank();
if (rank.enabled) rankSub = rank.watch(rows => drawBoard($('board'), rows, myUid));
else drawBoard($('board'), [], myUid);
}
// animated live board: FLIP row reordering, fame bars, count-up numbers, rank ▲/▼
function animNum(el, from, to) {
if (!el) return; const t0 = performance.now(), dur = 520;
(function step(now) {
const k = Math.min(1, (now - t0) / dur), e = 1 - Math.pow(1 - k, 3);
el.textContent = Kit.fmt(Math.round(from + (to - from) * e));
if (k < 1 && el.isConnected) requestAnimationFrame(step);
})(t0);
}
function drawBoard(el, rows, myUid) {
if (!el) return;
if (!rows.length) { el.innerHTML = `${t('no_scores')} `; boardFame = {}; boardIdx = {}; return; }
const max = Math.max(1, rows[0].fame);
const prevTop = {};
el.querySelectorAll('.brow').forEach(li => { prevTop[li.dataset.key] = li.getBoundingClientRect().top; });
el.innerHTML = rows.map((r, i) => {
const me = r.key === myUid;
const was = boardIdx[r.key];
const arr = (was != null && was !== i) ? (i < was ? '▲ ' : '▼ ') : '';
return `
${i + 1} ${flagHtml(r.flag || 'XX')}
${esc(r.name)}${me ? ` (${t('you')}) ` : ''}${arr}
0 `;
}).join('');
el.querySelectorAll('.brow').forEach(li => {
const key = li.dataset.key, to = +li.dataset.fame, from = boardFame[key] != null ? boardFame[key] : to;
animNum(li.querySelector('.val b'), from, to); boardFame[key] = to;
if (prevTop[key] != null) {
const d = prevTop[key] - li.getBoundingClientRect().top;
if (d) { li.style.transform = `translateY(${d}px)`; li.style.transition = 'none';
requestAnimationFrame(() => { li.style.transition = 'transform .45s cubic-bezier(.2,.8,.2,1)'; li.style.transform = ''; }); }
}
});
boardIdx = {}; rows.forEach((r, i) => boardIdx[r.key] = i);
}
function confirmReset(back) {
card(`${t('reset')} ${t('reset_text')}
${t('reset_yes')} ${t('cancel')}
`);
$('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(); };
}
// the rank badge opens the achievements page
$('hTour').onclick = () => { SFX.click(); openNetTourney(); };
$('chipFame').onclick = () => {
if (!save || mode === 'intro' || mode === 'title') return;
if (mode === 'fight') togglePause();
SFX.click();
showAchievements(mode === 'pause' ? () => { mode = 'fight'; togglePause(); } : currentBack());
};
$('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 (rank.enabled && gameMode === 'online') ? `${t('ranking')} ${t('loading')} ` : ''; }
async function fillBoard() {
const el = $('board');
if (!el) return;
const myUid = (fbAcc() && fbAcc().uid) || net.uid;
try {
const rows = await rank.once(10);
el.innerHTML = rows.length
? rows.map((r, i) => `${i + 1}. ${esc(r.name)} ${Kit.fmt(r.fame)} `).join('')
: `${t('no_scores')} `;
} catch (e) { el.innerHTML = `${t('scores_offline')} `; }
}
// ---------------------------------------------------------------- shop + league
function openGarage() {
hideOverlay();
setScreen('garage');
view.showGarage(save.build, paintObj());
audio.music('music_garage');
shop.render(); hud(); updateShopBar();
$('zIn').onclick = () => { SFX.click(); view.zoomGarage(1.18); };
$('zOut').onclick = () => { SFX.click(); view.zoomGarage(1 / 1.18); };
}
$('bGMenu').onclick = () => { SFX.click(); persist(); startIntroOrTitle(); };
$('bGMode').onclick = () => { SFX.click(); switchMode(gameMode === 'online' ? 'campaign' : 'online'); };
const onlineUsable = () => !!(net && net.enabled && !LIVE.onlineOff);
if (!onlineUsable()) $('bGMode').style.display = 'none';
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
$('bLeague').onclick = () => { SFX.click(); if (gameMode === 'online') { persist(); startOnline('lobby'); } else showLeague(); };
if ($('bRankG')) $('bRankG').onclick = () => { SFX.click(); showRanking(openGarage); };
function updateShopBar() {
const on = gameMode === 'online';
$('bGMode').style.display = onlineUsable() ? '' : 'none';
$('bGMode').textContent = on ? '🏆 ' + t('to_campaign') : '🌍 ' + t('to_online');
$('bLeague').textContent = on ? t('to_lobby') : t('to_league');
const rg = $('bRankG'); if (rg) rg.style.display = (on && rank.enabled) ? '' : 'none'; // ranking is online-only
}
function applyClass(id) {
if (id === save.cls) return;
persist(); // write the ladder we are leaving
save.cls = id;
RC.setClass(id);
save.beaten = save.leagues[id].beaten; save.season = save.leagues[id].season;
save.tour = null; // a running bracket belongs to its class
persist(); hud(); shop.render();
}
// ---------------------------------------------------------------- tournament
function tourState() { return save.tour || null; }
const tourOpen = () => !!LIVE.tournament; // admin switch
const tourFee = () => (tourOpen() ? 0 : RC.Tourney.ENTRY_FEE);
function startTournament() {
if (save.money < tourFee()) { SFX.deny(); return; }
save.money -= tourFee();
save.tour = RC.Tourney.create({ me: { name: save.robotName, build: save.build, paint: paintObj() }, seed: (Date.now() & 0xffffff) || 1 });
persist(); hud();
showTournament();
}
function showTournament() {
const st = tourState();
if (!st) { showLeague(); return; }
overlayEnter();
const nameOf = e => (e.player ? save.robotName : e.name);
// a slot won its match if it shows up again in the next round's line-up (same object)
const advanced = (e, r) => st.rounds[r + 1] && st.rounds[r + 1].indexOf(e) >= 0;
const pr = RC.Tourney.pair(st); // the player's match this round (null if done)
const playerMatch = !st.done && pr ? pr : null;
// draw the bracket column by column: quarters -> semis -> final -> champion
let cols = '';
for (let r = 0; r < st.rounds.length; r++) {
const col = st.rounds[r];
if (col.length < 2) continue; // single entry = champion, shown separately
let rows = '';
for (let i = 0; i < col.length; i += 2) {
const pair = [col[i], col[i + 1]].filter(Boolean);
const isPlayerPair = !st.done && r === st.round && pair.indexOf(pr && pr[0]) >= 0;
const slots = pair.map(e => {
const you = e.player, win = advanced(e, r);
return `${esc(nameOf(e))}${you ? '' : ` ${t('ai_tag')} `}
`;
}).join('');
rows += `${slots}${isPlayerPair ? `
▶ ${t('tour_fight')}
` : ''}
`;
}
cols += `${t('tour_round_' + (RC.Tourney.ROUND_KEY[r] || 'final'))}
${rows}
`;
}
// champion column
const champ = st.done && st.won ? save.robotName : (st.rounds.length && st.rounds[st.rounds.length - 1].length === 1 ? nameOf(st.rounds[st.rounds.length - 1][0]) : '?');
cols += `🏆 ${t('tour_champion')}
${st.done ? esc(champ) : '…'}
`;
let head, buttons;
if (st.done) {
head = st.won
? `🏆 ${t('tour_won')} · ${t('tour_won_text', { n: Kit.fmt(st.prize) })}
`
: `${t('tour_out')} · ${t('tour_out_text', { n: Kit.fmt(st.prize) })}
`;
buttons = `${t('to_garage')} `;
} else {
head = `${t('tour_round_' + RC.Tourney.ROUND_KEY[st.round])} · ${playerMatch ? t('tour_your_match', { name: esc(playerMatch[1].name) }) : ''}
`;
buttons = `${t('back')} ${t('tour_fight')} `;
}
card(`🏆 ${t('tournament')} ${head}
${cols}
${buttons}
`, { wide: true, bg: 'bg_title.jpg' });
const go = () => { SFX.click(); const p = RC.Tourney.pair(st); RC.Tourney.simOthers(st); persist(); startFight(p[1], false, false, null, true); };
if ($('tGo')) $('tGo').onclick = go;
overlay.querySelectorAll('.tpair.now').forEach(el => { el.style.cursor = 'pointer'; el.onclick = go; });
if ($('tLater')) $('tLater').onclick = () => { SFX.click(); openGarage(); };
if ($('tDone')) $('tDone').onclick = () => { SFX.click(); save.tour = null; persist(); openGarage(); };
}
function showLeague() {
if (gameMode !== 'campaign') { switchMode('campaign'); return; } // league is campaign-only
setScreen('league');
const cards = RC.LEAGUE.map((o, i) => {
const cls = i < save.beaten ? 'done' : i === save.beaten ? 'next' : 'locked';
return `${RC.pic('opp_' + o.id, '🤖')}
${i + 1}. ${o.name}
${i <= save.beaten ? t('style_' + o.style) : '???'}
${RC.pic('ico_credits', '🪙')}${Kit.fmt(Math.round(o.prize * seasonMul()))}
`;
}).join('');
const tabs = RC.CLASSES.map(c => {
const pr = save.leagues[c.id] || { beaten: 0, season: 1 };
return `${t('cls_' + c.id)}
${c.max} kg · ${pr.beaten}/${RC.LEAGUES[c.id].length} `;
}).join('');
card(`${t('league_title', { s: save.season })}
${tabs}
${t('league_text')}
${cards}
${t('back')}
${t('fight_vs', { name: RC.LEAGUE[save.beaten].name })}
${save.beaten ? `${t('exhibition_hint')}
` : ''}`,
{ wide: true, bg: 'bg_title.jpg' });
$('clsTabs').querySelectorAll('button').forEach(b => {
b.onclick = () => { SFX.click(); applyClass(b.dataset.v); showLeague(); };
});
overlay.querySelectorAll('.opp.next').forEach(el => { el.style.cursor = 'pointer'; el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); }; });
// beaten opponents: repeatable exhibition fights for half the prize (steady income)
overlay.querySelectorAll('.opp.done').forEach(el => { el.style.cursor = 'pointer'; el.title = t('exhibition_note'); el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[+el.dataset.i], true); }; });
$('bFight').onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); };
$('bBack').onclick = () => { SFX.click(); openGarage(); };
}
function showVs(opp, exhibition) {
const me = RC.stats(save.build), en = RC.stats(opp.build);
const line = s => `${Math.round(s.hp)} ${t('m_hp')} · ${Math.round(s.reduce * 100)}% ${t('m_armour')} · ${s.top.toFixed(1)} m/s`;
const mine = view.portrait(save.build, paintObj());
const myPic = mine ? ` ` : RC.pic('icon', '🤖');
card(`${myPic}
${esc(save.robotName)}
${weaponName(save.build)}
${line(me)}
VS
${RC.pic('opp_' + opp.id, '🤖')}
${opp.name}
${weaponName(opp.build)}
${line(en)}
${t('style_' + opp.style)}
${exhibition ? `${t('exhibition_note')}
` : ''}
${t('back')} ${exhibition ? t('exhibition_btn') : t('fight_go_btn')}
`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showLeague(); };
$('bGo').onclick = () => { SFX.click(); startFight(opp, false, exhibition); };
}
// ---------------------------------------------------------------- fight
// spawn intro: the steel gate is shut over the arena, then splits open with a metal sound
function gateOpen() {
const g = $('gate'); if (!g) return;
g.classList.remove('open', 'hide');
void g.offsetWidth; // reflow so the transition runs from the shut state
SFX.gate();
requestAnimationFrame(() => g.classList.add('open'));
setTimeout(() => g.classList.add('hide'), 1150);
}
function startFight(opp, training, exhibition, online, tour) {
hideOverlay();
const D = BASE;
const 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')
: (LIVE.event && LIVE.event.arena && !online) ? LIVE.event.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, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4,
acc: [0, 0], accT: 0, banner: null, ended: false };
if (online) {
F.nf = RC.NetFight({ net, id: online.id, host: online.host, oppStyle: 'brawler', oppSkill: 0.6, onPeerLost: () => banner(t('peer_lost'), '#ff4a3a', 2.5), onPeerBack: () => banner(t('peer_back'), '#6dff9e', 1.6) });
F.nf.start();
}
// 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');
gateOpen();
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);
}
// the mine layer stays manual - you decide where a mine goes, the helper does not
if (me.st.gadget && me.st.gadget.type !== 'mines' && !k.fire3) k.fire3 = RC.Combat.wantGadget(s, me, en);
}
return k;
}
// health bar colour: paint, or the accent when the paint is too dark to read
const barCol = p => { const c = p.body >>> 0, l = ((c >> 16) & 255) * 0.3 + ((c >> 8) & 255) * 0.59 + (c & 255) * 0.11; return hex(l < 60 ? p.accent : p.body); };
const CAMS = ['iso', 'chase', 'fpv'];
function cycleCam() {
settings.cam = CAMS[(CAMS.indexOf(settings.cam) + 1) % CAMS.length];
saveSettings(); view.setCam(settings.cam); SFX.click();
banner(t('cam_' + settings.cam), '#ffffff', 1);
}
// minimap for chase / cockpit view: arena, traps, pit, both robots
function minimap() {
const touch = window.matchMedia && matchMedia('(pointer: coarse)').matches;
const s = F.s, A = s.arena, S = touch ? 104 : 128, X = W - S - 14, Y = touch ? 84 : H - S - 14, k = S / (A.half * 2);
// rotate 45° like the iso view, so "up" matches the arena camera
const P = (x, z) => [X + S / 2 + (x - z) * k * 0.7071, Y + S / 2 + (x + z) * k * 0.7071];
ctx.save();
ctx.fillStyle = 'rgba(10,12,16,.72)'; ctx.strokeStyle = 'rgba(255,255,255,.25)'; ctx.lineWidth = 1;
const poly = pts => { ctx.beginPath(); pts.forEach(([x, z], i) => { const [px, py] = P(x, z); if (i) ctx.lineTo(px, py); else ctx.moveTo(px, py); }); ctx.closePath(); };
const h = A.half;
if (A.shape === 'round') poly(Array.from({ length: 20 }, (_, i) => { const a = i / 20 * Math.PI * 2; return [Math.cos(a) * h, Math.sin(a) * h]; }));
else if (A.shape === 'octagon') { const d = h * 0.67; poly([[-d, -h], [d, -h], [h, -d], [h, d], [d, h], [-d, h], [-h, d], [-h, -d]]); }
else poly([[-h, -h], [h, -h], [h, h], [-h, h]]);
ctx.fill(); ctx.stroke();
const rect = (o, col) => { ctx.fillStyle = col; poly([[o.x - o.hw, o.z - o.hd], [o.x + o.hw, o.z - o.hd], [o.x + o.hw, o.z + o.hd], [o.x - o.hw, o.z + o.hd]]); ctx.fill(); };
rect(A.press, 'rgba(242,181,28,.35)'); rect(A.crane, 'rgba(242,181,28,.35)');
rect(A.pit, s.pitOpen >= 1 ? 'rgba(255,40,40,.85)' : 'rgba(255,255,255,.12)');
for (const f of A.flames) rect(f, RC.hazardOn(f, s.t) ? 'rgba(255,110,20,.85)' : 'rgba(255,110,20,.25)');
for (const sw of A.saws) { const [px, py] = P(sw.x, sw.z); ctx.fillStyle = RC.hazardOn(sw, s.t) ? 'rgba(255,60,60,.9)' : 'rgba(200,200,200,.3)'; ctx.beginPath(); ctx.arc(px, py, sw.r * k, 0, 7); ctx.fill(); }
for (const bl of A.belts) rect(bl, 'rgba(80,170,255,.35)');
for (const o of A.oil) { const [px, py] = P(o.x, o.z); ctx.fillStyle = 'rgba(12,12,20,.65)'; ctx.beginPath(); ctx.arc(px, py, o.r * k, 0, 7); ctx.fill(); }
for (const m of A.rams) rect(m, RC.hazardOn(m, s.t) ? 'rgba(255,60,60,.8)' : 'rgba(200,200,200,.25)');
for (const b of A.blocks) rect(b, 'rgba(150,160,175,.6)');
for (const mn of s.mines || []) {
const [px, py] = P(mn.x, mn.z);
ctx.fillStyle = mn.arm > 0 ? 'rgba(200,200,200,.45)' : 'rgba(255,70,40,.95)';
ctx.beginPath(); ctx.arc(px, py, Math.max(2, mn.r * k), 0, 7); ctx.fill();
}
s.robots.forEach((r, i) => {
if (r.out) return;
const [px, py] = P(r.x, r.z), [qx, qy] = P(r.x + Math.cos(r.a), r.z + Math.sin(r.a)), ang = Math.atan2(qy - py, qx - px);
ctx.save(); ctx.translate(px, py); ctx.rotate(ang);
ctx.fillStyle = i === 0 ? hex(save.paint.body) : hex(F.opp.paint.body); ctx.strokeStyle = i === 0 ? '#fff' : '#000'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(7, 0); ctx.lineTo(-5, 5); ctx.lineTo(-5, -5); ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.restore();
});
ctx.restore();
}
function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; }
let ntourT = 0;
function update(dt) {
if (ntour && inNetTour) { ntourT -= dt; if (ntourT <= 0) { ntourT = 2; ntour.tick(); } }
fx.update(dt);
introTick();
if (mode !== 'fight' || !F) return;
if (F.count > 0) {
if (F.nf) F.nf.idle(dt);
F.count -= dt;
const n = Math.ceil(F.count);
if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } }
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 =>
`${RC.pic('part_' + c.id, '🔧')}
` +
`
${CD_KEY[c.slot]} ${c.n === undefined ? '' : `
${c.n} `}
`).join('');
}
// condition panel: every part that can be torn off, shown per robot and greyed out when it is gone
const BREAKABLE = ['armour', 'wheels', 'tower'];
function buildDmg(i, build) {
const weps = (build.weapons || []).map((w, wi) =>
`${RC.pic('part_' + w.id, GLYPH_SLOT.weapon)} `).join('');
const icons = BREAKABLE.filter(k => build[k]).map(k =>
`${RC.pic('part_' + build[k], GLYPH_SLOT[k])} `).join('');
$('fD' + i).innerHTML = `${weps}${icons} `;
}
const GLYPH_SLOT = { armour: '🛡️', wheels: '🛞', weapon: '🪓', tower: '🔥' };
// short red flash on the box that just took a solid hit
let hitT = [0, 0];
function flashBox(who) {
const el = $(who === 0 ? 'fLeft' : 'fRight');
el.classList.add('hit');
clearTimeout(hitT[who]);
hitT[who] = setTimeout(() => el.classList.remove('hit'), 120);
}
function fightHud() {
if (!F) return;
const s = F.s;
for (let i = 0; i < 2; i++) {
const r = s.robots[i], pct = r.hp / r.maxHp;
$('fH' + i).style.width = (pct * 100).toFixed(1) + '%';
$('fG' + i).style.width = (pct * 100).toFixed(1) + '%'; // trails behind (CSS transition)
$(i === 0 ? 'fLeft' : 'fRight').classList.toggle('hurt', pct < 0.25 && !r.dead);
// readable damage: hit points left, and every torn-off part crossed out live
const el = $('fD' + i), hpn = el.querySelector('.hpn');
const txt = `${Math.ceil(r.hp)}/${Math.round(r.maxHp)}`;
if (hpn && hpn.textContent !== txt) hpn.textContent = txt;
for (const ps of el.querySelectorAll('.pt')) {
const p = ps.dataset.part, gone = /^weapon\d/.test(p) ? !!(r.lostW && r.lostW[+p.slice(6)]) : !!(r.lost && r.lost[p]);
ps.classList.toggle('gone', gone);
}
}
const own = s.robots[0].hp / s.robots[0].maxHp;
$('dmgvig').style.opacity = own < 0.3 && !s.robots[0].out ? ((0.3 - own) / 0.3 * 0.6).toFixed(2) : 0;
const cds = RC.Combat.cooldowns(s.robots[0]), chips = $('fCds').children;
for (let i = 0; i < chips.length && i < cds.length; i++) {
const ch = chips[i], c = cds[i];
ch.style.setProperty('--p', c.p.toFixed(2));
ch.classList.toggle('on', !!c.on);
ch.classList.toggle('spent', c.n === 0);
ch.classList.toggle('broke', !!c.broke);
const n = ch.querySelector('.n');
if (n && n.textContent !== String(c.n)) n.textContent = c.n;
if (c.slot === 'gadget') { const pg = $('padGadget'); if (pg) pg.style.setProperty('--p', c.p.toFixed(2)); }
}
const sec = Math.ceil(s.left);
$('fTime').textContent = `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`;
$('fTime').classList.toggle('low', sec <= 10);
const me = s.robots[0];
let st = '';
if (me.lifted) st = t('st_lifted'); else if (me.grabbedBy !== null) st = t('st_grabbed');
else if (me.flipped > 0 && !me.st.invertible) st = t('st_flipped'); else if (me.stun > 0) st = t('st_stunned');
else if (s.pitAlarm) st = t('pit_is_open'); else if (s.left - s.arena.pitOpensAt < 10 && s.left > s.arena.pitOpensAt) st = t('pit_soon');
$('fState').textContent = st;
}
// achievements are part of the save, so campaign and online each have their own
function awardAch(ctx) {
const got = RC.Progress.check(save, ctx);
if (!got.length) return got;
let pay = 0;
for (const a of got) pay += a.reward;
save.money += pay;
persist();
SFX.buy && SFX.buy();
return got;
}
const achHtml = got => (!got || !got.length ? '' :
`🏅 ${t('ach_new')} ` + got.map(a =>
`
${t('ach_' + a.id)} +${Kit.fmt(a.reward)}
`).join('') + '
');
function endFight() {
const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp);
const won = res.winner === 0, me = s.robots[0];
if (F.online && F.online.tourney) { endNetTourFight(res, won, me); return; }
if (F.online) { endOnlineFight(res, won, me); return; }
if (F.tour) { endTourFight(res, won, me); return; }
const lines = [];
let money = 0, fame = 0, champion = false;
if (!F.training) {
const prize = Math.round(opp.prize * seasonMul() * (F.exhibition ? 0.5 : 1));
save.games++;
if (won && F.exhibition) {
money += prize; lines.push([t('r_exhibition'), prize]);
fame = (idx + 1) * 10 * save.season;
save.wins++;
} else if (won) {
const bonus = res.reason === 'pit' ? 0.3 : res.reason === 'ko' ? 0.2 : 0;
money += prize; lines.push([t('r_prize'), prize]);
if (bonus) { const b = Math.round(prize * bonus); money += b; lines.push([t('r_bonus_' + res.reason), b]); }
fame = (idx + 1) * 50 * save.season + (res.reason === 'pit' ? 40 : res.reason === 'ko' ? 25 : 0);
save.wins++;
if (idx === save.beaten) save.beaten++;
if (save.beaten >= RC.LEAGUE.length) {
champion = true;
const cb = 1500 * save.season; money += cb; fame += 500 * save.season; lines.push([t('r_champion'), cb]);
save.season++; save.beaten = 0;
}
} else {
const ap = Math.round(prize * 0.35); money += ap; lines.push([t('r_appearance'), ap]);
save.losses++;
}
// every hit pays: damage bonus win or lose
const db = Math.round(me.dealt * 0.6 * (F.exhibition ? 0.5 : 1));
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06 + (res.reason === 'pit' && !won ? me.st.value * 0.03 : 0));
const paid = Math.min(repair, save.money + money);
if (paid) lines.push([t('r_repair'), -paid]);
money = applyEvent(money, lines);
money -= paid;
save.money += money; save.fame += fame;
persist();
}
const gotAch = awardAch({ won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt,
lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length,
training: F.training, exhibition: F.exhibition, champion });
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]) => `${k} ${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))} `).join('');
const stats = `${t('r_dealt')} ${Math.round(me.dealt)} ${t('r_taken')} ${Math.round(me.taken)} `;
setScreen('result');
card(`${title} ${why}
${champion ? `${t('champion_title', { s: save.season - 1 })} ${t('champion_text')}
` : ''}
${stats}${rows}${!F.training && fame ? `${t('hud_fame')} +${Kit.fmt(fame)} ` : ''}
${achHtml(gotAch)}
${F.training ? `${t('training_note')}
` : ''}
${t('to_garage')} ${!F.training && !won ? `${t('retry')} ` : ''}
${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();
if (gameMode === 'online') { rank.submit(rankRow()).then(fillBoard); return; } // global board = online fame only
}
fillBoard();
}
// a tournament round: the bracket moves on, the round prize is paid, then back to the bracket
function endTourFight(res, won, me) {
const st = save.tour, lines = [];
const before = st.prize;
RC.Tourney.advance(st, won);
const roundPay = st.prize - before;
save.games++;
if (won) save.wins++; else save.losses++;
let money = 0, fame = won ? 70 * st.round : 20;
if (roundPay) { money += roundPay; lines.push([t('tour_round_prize'), roundPay]); }
const db = Math.round(me.dealt * 0.6);
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
if (st.won) { money += 2000; fame += 400; lines.push([t('tour_trophy'), 2000]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06);
money = applyEvent(money, lines);
const paid = Math.min(repair, save.money + money);
if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); }
save.money += money; save.fame += fame;
persist();
const gotAch = awardAch({ won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt,
lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length, tourWon: st.won });
hud();
(won ? SFX.win : SFX.lose)();
const rows = lines.map(([k, v]) => `${k} ${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))} `).join('');
setScreen('result');
card(`${won ? t('victory') : t('defeat')} ${esc(F.opp.name)}
${t('r_dealt')} ${Math.round(me.dealt)} ${rows}
${t('hud_fame')} +${Kit.fmt(fame)}
${achHtml(gotAch)}
🏆 ${t('tournament')}
`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bTour').onclick = () => { SFX.click(); showTournament(); };
}
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);
money = applyEvent(money, lines);
const paid = Math.min(repair, save.money + money);
if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); }
save.money += money; save.fame += fame; save.games++;
if (won) save.wins++; else if (!draw) save.losses++;
persist();
const gotAch = awardAch({ won, reason: res.reason, hpPct: me.hp / me.maxHp, dealt: me.dealt,
lost: ['armour', 'wheels', 'weapon', 'tower'].filter(k => me.lost && me.lost[k]).length });
hud();
if (save.fame > save.best) { save.best = save.fame; persist(); rank.submit(rankRow()); }
const rows = lines.map(([k, v]) => `${k} ${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))} `).join('');
setScreen('result');
card(`${title} ${esc(F.opp.name)} ${F.nf && !F.nf.peerAlive ? t('peer_left') : ''}
${t('r_dealt')} ${Math.round(me.dealt)} ${t('r_taken')} ${Math.round(me.taken)} ${rows}
${fame ? `${t('hud_fame')} +${Kit.fmt(fame)} ` : ''}
${achHtml(gotAch)}
${t('back_to_lobby')} ${t('to_garage')}
`,
{ 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(`${t('pause')} ⚙ ${t('settings')} ${t('give_up')} ${t('continue')}
`);
$('bGo').onclick = togglePause;
$('bSet2').onclick = () => { SFX.click(); showSettings(() => { mode = 'fight'; togglePause(); }); };
$('bQuit').onclick = () => {
mode = 'fight'; loop.resume(); hideOverlay();
if (F && !F.s.result) { F.s.robots[0].hp = 0; F.s.robots[0].dead = true; F.s.result = { winner: 1, reason: 'ko' }; F.s.endIn = 0; }
};
} else if (mode === 'pause') { mode = 'fight'; hideOverlay(); loop.resume(); }
}
function toggleMute() { audio.toggleMute(); hud(); }
$('bMute').onclick = toggleMute;
$('bPause').onclick = togglePause;
addEventListener('blur', () => { if (mode === 'fight' && !(F && F.online)) togglePause(); });
// language switch: static texts update themselves (data-i18n), dynamic screens are drawn again
L.onChange(() => {
hud(); updateShopBar();
if (mode === 'title') showTitle();
else if (mode === 'garage') shop.render();
else if (mode === 'league') showLeague();
else if (mode === 'lobby') renderLobby();
if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); }
});
// ---------------------------------------------------------------- start
// backend settings; applied as soon as they arrive and whenever the admin changes them
RC.Live.load(net, v => {
LIVE = v;
if (LIVE.onlineOff && gameMode === 'online' && save) switchMode('campaign');
if (mode === 'title') showTitle(); else if (mode === 'lobby') renderLobby();
});
if (DEV.get('live')) { // dev: &live=event|off|old|lock (no Firebase needed)
const k = DEV.get('live'), now = Date.now();
const demo = {
event: { event: { id: 'demo', name: { de: 'Schwergewichts-Wochenende', en: 'Heavyweight weekend' }, type: 'prize', prizeMul: 2, from: now - 1000, to: now + 36e5 } },
off: { flags: { onlineOff: true, note: { de: 'Wartung', en: 'Maintenance' } } },
old: { build: { min: '99999999.9999' } }, // paired with a fake stamp below
lock: { unlock: { parts: ['crate', 'sparky', 'rubber', 'lead', 'wedge'] } },
motd: { motd: { de: 'Turnier am Samstag um 20 Uhr!', en: 'Tournament on Saturday, 8pm!' } },
}[k];
if (k === 'old' && !BUILD_ID()) window.RC_BUILD = '20000101.0000';
if (demo) LIVE = RC.Live.parse(demo, now, BUILD_ID());
}
setMode('online'); // every page load starts in online play
accounts.resume();
if (net && net.enabled) { net.auth.resume(); net.auth.onChange(() => { hud(); refreshDev(); if (mode === 'title') showTitle(); }); }
hud();
if (!hostOk()) {
card(`Robot Clash ${t('wrong_host')}
${CREDITS}
`);
} else if (LIVE.needsReload) {
// the admin published a newer build; browsers happily serve the cached old file
setScreen('intro'); // defined UI state while this card is up
card(`${t('reload_title')} ${t('reload_text')}
${t('reload_now')} ${t('reload_skip')}
`);
$('rNow').onclick = () => location.reload();
$('rSkip').onclick = () => { LIVE.needsReload = false; SFX.click(); startGate(startIntro); };
} else if (!view) {
card(`Robot Clash ${t('no_webgl')}
${CREDITS}
`);
} else if (DEV.has('fight') || DEV.has('play')) {
// dev: ?play = straight into the shop, ?fight=N = training fight against league robot N
if (!accounts.current) accounts.guest();
loadSave(); hud();
if (DEV.get('equip')) for (const id of DEV.get('equip').split(',')) { const p = RC.PARTS[id]; if (p) { if (!save.owned.includes(id)) save.owned.push(id); save.build[p.slot] = id; } }
if (DEV.get('arena')) settings.arena = DEV.get('arena');
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (DEV.get('hangar')) { const n = Math.min(MAX_ROBOTS, +DEV.get('hangar') || 3); while (save.robots.length < n) save.robots.push(newRobotDef(t('robot_n', { n: save.robots.length + 1 }))); }
if (DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true); else openGarage();
if (DEV.get('shoptab') && mode === 'garage') shop.setTab(DEV.get('shoptab'));
if (DEV.get('sel') && mode === 'garage') { const id = DEV.get('sel'), p = RC.PARTS[id]; if (p) { const tb = document.querySelector(`.tab[data-slot="${p.slot}"]`); if (tb) tb.click(); const it = document.querySelector(`.item[data-id="${id}"]`); if (it) it.click(); } }
// dev: ?play&screen=league|vs|settings|help|lobby|pause opens that screen (layout screenshots)
if (DEV.get('gmode')) switchMode(DEV.get('gmode')); // dev: &gmode=campaign|online
const scr = DEV.get('screen');
if (scr === 'league') { save.beaten = Math.max(save.beaten, 3); showLeague(); }
else if (scr === 'vs') showVs(RC.LEAGUE[4]);
else if (scr === 'settings') showSettings(openGarage);
else if (scr === 'help') showHelp(openGarage);
else if (scr === 'tour') { save.money = 3000; startTournament(); }
else if (scr === 'ach') { save.fame = 1200; save.ach = { first_win: true, ko: true, rich: true }; showAchievements(openGarage); }
else if (scr === '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= buys it through the real shop buttons (header check)
if (DEV.get('buy')) { const it = document.querySelector(`.item[data-id="${DEV.get('buy')}"]`); if (it) { it.click(); const b = document.querySelector('#detail button[data-act="buy"]'); if (b) b.click(); } }
// dev: &equip=wedge,flamer forces parts onto the robot (ignores cost), then shows the garage
if (DEV.get('equip') && !DEV.has('fight')) { for (const id of DEV.get('equip').split(',')) { const p = RC.PARTS[id]; if (p) { if (!save.owned.includes(id)) save.owned.push(id); save.build[p.slot] = id; } } persist(); view.showGarage(save.build, paintObj()); shop.render(); }
if (DEV.has('paint')) { // dev: open the paint booth with a test drawing
const c = layer.getContext('2d');
c.fillStyle = '#15171b'; c.fillRect(0, 100, 256, 56); c.fillStyle = '#f2c230'; c.font = 'bold 70px sans-serif'; c.fillText('★ 7', 300, 170);
c.strokeStyle = '#00e5ff'; c.lineWidth = 14; c.beginPath(); c.moveTo(270, 220); c.lineTo(500, 200); c.stroke();
painter.open(); view.showGarage(save.build, paintObj());
}
} else if (DEV.has('online') && net.enabled) { startIntroOrTitle(); startOnline(); }
else if (DEV.has('title')) startIntroOrTitle();
else startGate(startIntro);
if (DEV.has('tut')) startTutorial(openGarage); // dev: ?play&tut previews the first-start cards
if (DEV.has('uicheck') && RC.uiCheckRun) RC.uiCheckRun(); // dev: &uicheck prints layout faults as text
})();