Files
Robot-Clash/game/game.js
Michi 7a69651b6d Online-Lobby, Arenen, Lackiererei, ComfyGen-Grafik, Verschleierung
Grosse Erweiterung ueber die erste spielbare Version hinaus:

- Online (Firebase ueber REST, kein SDK): Konto per E-Mail, globale Lobby
  mit Laender-Raeumen, Herausfordern, Live-PvP (Host rechnet, Gast
  interpoliert, KI-Uebernahme bei Lag). Gast kann anonym beitreten.
  net.js / lobby.js / netfight.js, Regeln in docs/firebase.
- 3 Arenen in verschiedenen Groessen (RC.ARENAS, half 8/12/16), Kamera +
  Licht + Boden skalieren; Liga skaliert die Arena mit, Setting + online
  aus Seed. Harte Rams/Wandtreffer schleudern Roboter auf den Rucken.
- Intro (3D-Kamerafahrt), Titel, Einstellungen (Kamera, Schwierigkeit,
  Steuerung, Grafik, Arena), Lackiererei (painter.js, selbst bemalen).
- Shop mit ComfyGen-Sprites (aus den 3D-Teilen erzeugt), Liga-Gegner sehen
  aus wie ihre Portraits (looks.js), kraeftigere Waffen-Modelle.
- Oekonomie: Startgeld 800, Schadensbonus, Schaukaempfe, Online-Preisgeld.
- Verschleierung: build.ps1 -Obfuscate (terser), tablet-taugliche Touch-UI.
- Tests: tests/sim.test.js, balance.js, online.test.js. Dev-Tools in tools/.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-13 15:45:35 +01:00

953 lines
61 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 = 'https://robot-clash-aa37b-default-rtdb.firebaseio.com';
// Online lobby + live PvP: paste the Web API key (Firebase console -> Project settings -> Web API key).
// Empty key -> leaderboard still works, but no login/lobby (menu hides 'Online').
const NET_CFG = { apiKey: 'AIzaSyCE29VQnubM_9ok46nnosg07MpvhZH3O5w', dbUrl: DB_URL };
// dev/test: ?netkey=<API key> tries online without editing the file; ?online jumps to the lobby/login
if (new URLSearchParams(location.search).get('netkey')) NET_CFG.apiKey = new URLSearchParams(location.search).get('netkey');
// Credits (standard for every game): shown on the title screen, links open in the normal browser
const DISCORD = 'https://discord.gg/Ej4JPmCZva';
const 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);
// steer: 'simple' (keys = screen direction) | 'tank' · diff: 'easy' | 'normal' | 'hard' · autofire: weapon fires by itself in reach
const settings = Object.assign({ gfx: 'high', intro: true, steer: 'tank', diff: 'easy', autofire: true, cam: 'fpv', arena: 'random' }, store.get('settings', {}));
// v2: Michael found "simple" steering worse -> tank is the default again, old saved choice reset once
// v3: fights start in first person (cockpit) -> old saved camera reset once
if (!settings.v || settings.v < 2) settings.steer = 'tank';
if (!settings.v || settings.v < 3) { settings.cam = 'fpv'; settings.v = 3; store.set('settings', settings); }
// difficulty: player hit points x, AI skill +
const DIFF = { easy: { hp: 1.4, skill: -0.2 }, normal: { hp: 1.15, skill: -0.05 }, hard: { hp: 0.95, skill: 0.12 } };
const saveSettings = () => store.set('settings', settings);
const accounts = RC.Accounts(ID);
const newSave = () => ({
money: 800, fame: 0, best: 0, season: 1, beaten: 0, wins: 0, losses: 0, games: 0,
owned: Object.values(RC.STARTER).filter(Boolean), build: Object.assign({}, RC.STARTER),
paint: { body: 0xff7a1a, accent: 0x15171b }, robotName: 'Clank', flag: 'XX', tutorialSeen: false,
});
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 net = RC.Net(NET_CFG);
const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX'];
const flagHtml = c => `<span class="fl fl-${FLAGS.includes(c) ? c : 'XX'}"></span>`;
const lobby = net.enabled ? RC.Lobby({ net, getProfile: () => ({ name: playerName(), flag: save.flag || 'XX', build: save.build, paint: { body: save.paint.body, accent: save.paint.accent }, fame: save.fame | 0 }) }) : null;
const fx = Kit.fx();
const input = Kit.input({
keys: {
ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', ArrowRight: 'right', d: 'right',
' ': 'fire', Shift: 'fire2', e: 'fire2', p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok', c: 'cam',
},
onPress(a) {
if (mode === 'intro') { skipIntro(); return; }
if (a === 'pause') togglePause();
else if (a === 'mute') toggleMute();
else if (a === 'cam' && mode === 'fight') cycleCam();
else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); }
},
});
// ---------------------------------------------------------------- sound (ComfyGen clips + synth fallback)
const last = {};
const every = (k, ms) => { const n = performance.now(); if (last[k] && n - last[k] < ms) return false; last[k] = n; return true; };
const SFX = {
click() { audio.sfx('sfx_click'); audio.tone(660, 0.04, 'square', 0.05); },
buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.08); },
deny() { audio.tone(160, 0.15, 'square', 0.12, -40); },
beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); },
clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); },
win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); },
lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); },
event(e) {
switch (e.type) {
case 'bump': if (every('bump', 90)) audio.noise(0.12, Math.min(0.4, e.speed / 10), 700); break;
case 'wall': if (every('wall', 120)) { audio.sfx('sfx_hit'); audio.noise(0.2, 0.3, 1600); } break;
case 'flip': audio.tone(200, 0.2, 'square', 0.13, 500); audio.noise(0.12, 0.25, 3000); break;
case 'swing': audio.noise(0.15, 0.12, 900); break;
case 'smash': audio.sfx('sfx_hit'); audio.noise(0.25, 0.45, 650); audio.tone(95, 0.25, 'sine', 0.4, -45); break;
case 'spinhit': audio.sfx('sfx_hit'); audio.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); break;
case 'sparks': if (every('grind', 70)) audio.noise(0.06, 0.1, 5200); break;
case 'boom': audio.sfx('sfx_boom'); audio.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break;
case 'ko': audio.sfx('sfx_boom'); audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); break;
case 'launch': audio.noise(0.3, 0.18, 2200); audio.tone(300, 0.3, 'sawtooth', 0.07, 600); break;
case 'press_warn': for (let k = 0; k < 3; k++) audio.tone(880, 0.1, 'square', 0.1, 0, k * 0.2); break;
case 'press': audio.sfx('sfx_hit'); audio.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); break;
case 'crane': audio.tone(140, 0.6, 'sawtooth', 0.07, 140); break;
case 'drop': case 'land': audio.noise(0.22, 0.35, 500); break;
case '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(); hud(); }, // buy / sell -> credits in the header
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 : '');
// league robots dressed like their ComfyGen portraits (looks.js)
const oppPaint = o => (RC.LOOKS && RC.LOOKS[o.id] ? Object.assign({}, o.paint, { layer: RC.lookLayer(o.id, o.paint), drawn: true, look: RC.LOOKS[o.id] }) : o.paint);
const fbUser = () => (net && net.enabled ? net.auth.current : null);
const fbAcc = () => (fbUser() && !fbUser().guest ? fbUser() : null); // real (e-mail) account
const playerName = () => (fbUser() ? fbUser().name : accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : '');
// save slot: Firebase account -> robotclash.save.fb_<uid>, else local profile / guest
const saveKey = () => (fbAcc() ? ID + '.save.fb_' + fbAcc().uid : accounts.saveKey());
function hud() {
$('hMoney').textContent = save ? Kit.fmt(save.money) : '–';
$('hFame').textContent = save ? Kit.fmt(save.fame) : '–';
$('hLeague').textContent = save ? t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length }) : '–';
$('hUser').textContent = fbUser() ? '👤 ' + fbUser().name : accounts.current ? (accounts.current.guest ? '👤 ' + t('guest') : '👤 ' + accounts.current.name) : save ? '👤 ' + t('guest') : '👤 –';
$('bMute').textContent = audio.muted ? 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], [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 [[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 fb = net && net.enabled;
const acc = fb ? fbAcc() : (accounts.current && !accounts.current.guest ? accounts.current : null);
const online = fb ? `<button id="bOnline">🌍 ${t('online_play')}</button>` : '';
const btns = acc
? `<button class="primary" id="bPlay">${t('play_as', { name: esc(acc.name) })}</button>${online}<button id="bSwitch">${t('switch_account')}</button>`
: `<button class="primary" id="bLogin">${t('login')}</button><button id="bReg">${t('register')}</button><button id="bGuest">${t('play_guest')}</button>${online}`;
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('bOnline', () => startOnline());
on('bSwitch', () => { signOut(); fb ? showOnlineLogin(false, null, 'career') : showLogin(); });
on('bLogin', () => (fb ? showOnlineLogin(false, null, 'career') : showLogin()));
on('bReg', () => (fb ? showOnlineLogin(true, null, 'career') : showRegister()));
on('bGuest', () => { if (fbAcc()) net.auth.logout(); accounts.guest(); enterAccount(); });
on('bSet', () => showSettings(showTitle));
on('bHelp', () => showHelp(showTitle));
on('bLang', () => L.next());
on('bRank', () => showRanking(showTitle));
hud();
}
// ---------------------------------------------------------------- online lobby
let onlineReady = false, lobbyRows = [], pendingOut = null, lobbyRoom = null; // lobbyRoom = country code or null (room picker)
async function startOnline() {
if (!net.enabled) return;
if (!net.auth.current) {
if (save && !fbAcc()) return joinAnon(); // playing as guest -> straight in, anonymously
showOnlineLogin(false, null, 'online'); return;
}
if (!save || !slot) { if (!fbAcc()) accounts.guest(); loadSave(); }
if (!onlineReady) {
lobby.enter(); onlineReady = true;
lobby.onList(rows => { lobbyRows = rows; if (mode === 'lobby') renderLobby(); });
lobby.onIncoming(c => { if (mode === 'lobby' || mode === 'garage') showIncoming(c); });
lobby.onMatch(m => startFight({ name: m.opp.name, build: m.opp.build, paint: m.opp.paint || { body: 0x888888, accent: 0xff7a1a }, style: 'brawler', skill: 0.6, flag: m.opp.flag }, false, false, { id: m.id, host: m.host, seed: m.seed }));
lobby.onCancel(() => { pendingOut = null; if (mode === 'lobby') { renderLobby(); SFX.deny(); } });
}
showLobby();
}
async function joinAnon() {
if (!save) { accounts.guest(); loadSave(); }
const r = await net.auth.guest(playerName() || t('guest'));
if (!r.ok) { SFX.deny(); showOnlineLogin(false, r.error, 'online'); return; }
hud(); startOnline();
}
const errText = c => (window.LANG.en['e_' + c] ? t('e_' + c) : t('e_ERROR') + ' (' + esc(c) + ')');
function showOnlineLogin(reg, errKey, next) {
next = next || 'career';
setScreen('account');
const f = reg
? `<label>${t('f_name')}</label><input type="text" id="oName" maxlength="18" autocomplete="nickname">`
: '';
card(`<h2>${reg ? t('register') : t('login')}</h2><p>${t('online_login_text')}</p>
<div class="form">${f}<label>${t('f_email')}</label><input type="email" id="oMail" autocomplete="email" autocapitalize="off" autocorrect="off" spellcheck="false" inputmode="email">
<label>${t('f_pass')}</label><input type="password" id="oPass" autocomplete="${reg ? 'new-password' : 'current-password'}"></div>
<div class="err" id="oErr">${errKey ? errText(errKey) : ''}</div>
<div class="row"><button id="oBack">${t('back')}</button><button class="primary" id="oGo">${reg ? t('register_go') : t('login')}</button></div>
<p class="muted">${reg ? '' : t('no_account') + ' '}<button class="link" id="oToggle">${reg ? t('login') : t('register')}</button></p>
${next === 'online' ? `<div class="row"><button id="oAnon">👤 ${t('online_guest')}</button></div>` : ''}`, { bg: 'bg_title.jpg' });
if ($('oAnon')) $('oAnon').onclick = () => { SFX.click(); joinAnon(); };
$('oBack').onclick = () => { SFX.click(); showTitle(); };
$('oToggle').onclick = () => { SFX.click(); showOnlineLogin(!reg, null, next); };
$('oGo').onclick = async () => {
$('oGo').disabled = true;
const r = reg ? await net.auth.register($('oMail').value.trim(), $('oPass').value, $('oName') ? $('oName').value : '')
: await net.auth.login($('oMail').value.trim(), $('oPass').value);
if (!r.ok) { SFX.deny(); showOnlineLogin(reg, r.error, next); return; }
SFX.click(); hud();
if (next === 'online') startOnline(); else enterAccount(reg);
};
overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Enter') $('oGo').click(); }));
}
function showLobby() {
setScreen('lobby'); renderLobby();
}
function renderLobby() {
if (!lobbyRoom) return renderRooms();
const here = lobbyRows.filter(r => (FLAGS.includes(r.flag) ? r.flag : 'XX') === lobbyRoom);
const meRow = `<div class="prow me"><span class="pf">${flagHtml(lobbyRoom)}</span><span class="pn">${esc(playerName())} <span class="muted">(${t('you')})</span></span><span class="pfame">⭐ ${Kit.fmt(save.fame | 0)}</span><span class="pbusy"></span></div>`;
const list = here.map(r => `<div class="prow" data-uid="${r.uid}"><span class="pf">${flagHtml(r.flag)}</span><span class="pn">${esc(r.name)}</span><span class="pfame">⭐ ${Kit.fmt(r.fame | 0)}</span>${r.state === 'idle' ? `<button class="chal" data-uid="${r.uid}">${t('challenge')}</button>` : `<span class="pbusy">${t('busy')}</span>`}</div>`).join('');
card(`<h2>${flagHtml(lobbyRoom)} ${t('room_title', { room: t('cc_' + lobbyRoom) })}</h2>
<p class="muted">${t('room_count', { n: here.length + 1 })}</p>
<div class="plist">${meRow}${list || `<div class="muted" style="padding:14px">${t('lobby_empty')}</div>`}</div>
${pendingOut ? `<p class="muted">${t('waiting_accept')} <button class="link" id="lCancel">${t('cancel')}</button></p>` : ''}
<div class="row"><button id="lRooms">🌍 ${t('other_rooms')}</button><button id="lQuick">${t('quick_match')}</button><button id="lBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
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'); if (idle) { SFX.click(); pendingOut = idle.uid; lobby.challenge(idle.uid); renderLobby(); } else SFX.deny(); };
$('lRooms').onclick = () => { SFX.click(); lobbyRoom = null; renderLobby(); };
$('lBack').onclick = () => { SFX.click(); lobbyRoom = null; if (save) openGarage(); else showTitle(); };
}
// room picker: every country with how many players sit in it right now
function renderRooms() {
const count = f => lobbyRows.filter(r => (FLAGS.includes(r.flag) ? r.flag : 'XX') === f).length;
const rooms = FLAGS.map(f => { const n = count(f); return `<button class="room ${n ? 'live' : ''}" data-f="${f}">${flagHtml(f)}<span class="rn">${t('cc_' + f)}</span><span class="rc">${n ? '● ' + n : '0'}</span></button>`; }).join('');
card(`<h2>🌍 ${t('lobby')}</h2><p class="muted">${t('pick_room')}</p>
<div class="rooms">${rooms}</div>
<div class="row"><button id="lBack">${t('back')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
overlay.querySelectorAll('.room').forEach(b => { b.onclick = () => {
SFX.click(); lobbyRoom = b.dataset.f; save.flag = lobbyRoom; persist(); if (lobby) lobby.refresh(); renderLobby();
}; });
$('lBack').onclick = () => { SFX.click(); if (save) openGarage(); else showTitle(); };
}
function showIncoming(c) {
card(`<h2>${t('challenge_in')}</h2><p>${flagHtml(c.fromFlag)} <b>${esc(c.fromName)}</b> ${t('wants_fight')}</p>
<div class="row"><button id="cNo">${t('decline')}</button><button class="primary" id="cYes">${t('accept')}</button></div>`);
$('cYes').onclick = () => { SFX.click(); lobby.accept(c.from); };
$('cNo').onclick = () => { SFX.click(); lobby.decline(c.from); if (mode === 'lobby') renderLobby(); else hideOverlay(); };
}
// ---------------------------------------------------------------- accounts
function showLogin(errKey) {
setScreen('account');
const profs = accounts.list();
card(`<h2>${t('login')}</h2>
${profs.length ? `<p class="muted">${t('local_profiles')}</p><div class="profiles">${profs.map(p => `<button data-n="${esc(p.name)}">${esc(p.name)}</button>`).join('')}</div>` : ''}
<div class="form"><label>${t('f_name')}</label><input type="text" id="fName" maxlength="18" autocomplete="username">
<label>${t('f_pass')}</label><input type="password" id="fPass" autocomplete="current-password">
<label class="chk"><input type="checkbox" id="fRem" checked> ${t('f_remember')}</label></div>
<div class="err" id="fErr">${errKey ? t(errKey) : ''}</div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('login')}</button></div>
<p class="muted">${t('no_account')} <button class="link" id="bToReg">${t('register')}</button></p>
<p class="muted" style="font-size:11px">${t('local_note')}</p>`, { bg: 'bg_title.jpg' });
overlay.querySelectorAll('.profiles button').forEach(b => { b.onclick = () => { $('fName').value = b.dataset.n; $('fPass').focus(); }; });
$('bBack').onclick = () => { SFX.click(); showTitle(); };
$('bToReg').onclick = () => { SFX.click(); showRegister(); };
$('bGo').onclick = async () => {
const r = await accounts.login($('fName').value, $('fPass').value, $('fRem').checked);
if (!r.ok) { SFX.deny(); $('fErr').textContent = t('e_' + r.error); return; }
SFX.click(); enterAccount();
};
formKeys();
setTimeout(() => $(profs.length ? 'fPass' : 'fName').focus(), 50);
}
function showRegister() {
setScreen('account');
card(`<h2>${t('register')}</h2><p>${t('register_text')}</p>
<div class="form"><label>${t('f_name')}</label><input type="text" id="fName" maxlength="18" autocomplete="username">
<label>${t('f_pass')}</label><input type="password" id="fPass" autocomplete="new-password">
<label>${t('f_pass2')}</label><input type="password" id="fPass2" autocomplete="new-password"></div>
<div class="err" id="fErr"></div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('register_go')}</button></div>
<p class="muted" style="font-size:11px">${t('local_note')}</p>`, { bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showTitle(); };
$('bGo').onclick = async () => {
if ($('fPass').value !== $('fPass2').value) { SFX.deny(); $('fErr').textContent = t('e_pass_match'); return; }
const r = await accounts.register($('fName').value, $('fPass').value);
if (!r.ok) { SFX.deny(); $('fErr').textContent = t('e_' + r.error); return; }
SFX.buy(); enterAccount(true);
};
formKeys();
setTimeout(() => $('fName').focus(), 50);
}
// Enter in a form = primary button; typing never reaches the game keys
function formKeys() {
overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => {
e.stopPropagation();
if (e.key === 'Enter') { const b = overlay.querySelector('button.primary'); if (b) b.click(); }
}));
}
function loadSave() {
slot = Kit.saveSlot(saveKey(), newSave);
save = slot.load();
repairSave();
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
}
function enterAccount(fresh) {
loadSave();
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
if (fresh && who) save.robotName = who.name.slice(0, 18);
persist();
hud();
shop.reset();
if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); 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 signOut() {
persist();
if (lobby && onlineReady) { lobby.leave(); onlineReady = false; lobbyRows = []; pendingOut = null; }
if (net && net.enabled) net.auth.logout();
accounts.logout(); save = null; slot = null; F = null; hud();
}
function logout() { signOut(); startIntroOrTitle(); }
function startIntroOrTitle() { if (view) { const a = RC.LEAGUE[7], b = RC.LEAGUE[4]; view.showIntro([a.build, b.build], [oppPaint(a), oppPaint(b)]); view.skipIntro(); } showTitle(); }
$('hUser').onclick = () => {
if (!save || mode === 'fight' || mode === 'pause') return;
SFX.click();
const back = currentBack(), who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
card(`<h2>${t('account')}</h2><p>${who ? t('logged_in_as', { name: esc(who.name) }) + (who.email ? `<br><span class="muted">${esc(who.email)}</span>` : '') : t('guest_text')}</p>
<div class="row"><button id="bOut">${who ? t('logout') : t('to_title')}</button><button class="primary" id="bBack">${t('back')}</button></div>`);
$('bOut').onclick = () => { SFX.click(); logout(); };
$('bBack').onclick = () => { SFX.click(); back(); };
};
function currentBack() { return mode === 'garage' ? openGarage : mode === 'league' ? showLeague : mode === 'result' ? openGarage : mode === 'title' ? showTitle : save ? openGarage : showTitle; }
// ---------------------------------------------------------------- settings / help / ranking
function showSettings(back) {
const prev = mode;
const seg = (id, val, opts) => `<div class="seg" id="${id}">${opts.map(([v, label]) => `<button data-v="${v}" class="${v === val ? 'on' : ''}">${label}</button>`).join('')}</div>`;
const who = fbAcc() || (accounts.current && !accounts.current.guest ? accounts.current : null);
const item = (label, ctl) => `<span class="sl">${label}</span>${ctl}`;
card(`<h2>${t('settings')}</h2><div class="set2">
${item(t('s_lang'), seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self])))}
${item(t('s_mute'), seg('sMute', audio.muted ? '1' : '0', [['0', t('on')], ['1', t('off')]]))}
${item(t('s_music'), `<input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">`)}
${item(t('s_sfx'), `<input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">`)}
${item(t('s_gfx'), seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]]))}
${item(t('s_diff'), seg('sDiff', settings.diff, [['easy', t('diff_easy')], ['normal', t('diff_normal')], ['hard', t('diff_hard')]]))}
${item(t('s_cam'), seg('sCam', settings.cam, CAMS.map(c => [c, t('cam_' + c)])))}
${item(t('s_steer'), seg('sSteer', settings.steer, [['tank', t('steer_tank')], ['simple', t('steer_simple')]]))}
${item(t('s_autofire'), seg('sAuto', settings.autofire ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
${item(t('s_arena'), seg('sArena', settings.arena, [['random', t('arena_random')]].concat(RC.ARENAS.map(a => [a.id, t('arena_' + a.id)]))))}
${item(t('s_intro'), seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]]))}
</div>
<div class="setacc"><span class="sl">${t('s_account')}</span>
<span class="who">${who ? '👤 <b>' + esc(who.name) + '</b>' + (who.email ? ' <span class="muted">' + esc(who.email) + '</span>' : '') : '👤 ' + t('guest')}</span>
${save ? `<button id="sOut">${who ? t('logout') : t('to_title')}</button>` : ''}</div>
<div class="row"><button id="sFull">⛶ ${t('win_full')}</button><button id="sKeys">🎮 ${t('s_controls')}</button>
${save ? `<button id="sReset">${t('reset')}</button>` : ''}<button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, clear: prev === 'title' || prev === 'intro' });
const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; });
segOn('sLang', v => { L.set(v); showSettings(back); });
segOn('sMute', v => { if ((v === '1') !== audio.muted) audio.toggleMute(); hud(); });
segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (view) view.setQuality(v); });
segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); });
segOn('sDiff', v => { settings.diff = v; saveSettings(); });
segOn('sSteer', v => { settings.steer = v; saveSettings(); });
segOn('sCam', v => { settings.cam = v; saveSettings(); if (view) view.setCam(v); });
segOn('sAuto', v => { settings.autofire = v === '1'; saveSettings(); });
segOn('sArena', v => { settings.arena = v; saveSettings(); });
$('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol);
$('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value);
$('sSfx').onchange = () => SFX.click();
$('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); };
if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); };
if ($('sOut')) $('sOut').onclick = () => { SFX.click(); logout(); };
$('sKeys').onclick = () => { SFX.click(); showHelp(() => showSettings(back)); };
$('bBack').onclick = () => { SFX.click(); back(); };
}
function keysHtml() {
return `<div class="keys"><b>W A S D / ↑ ← ↓ →</b><span>${t('key_drive')}</span><b>${t('key_space')}</b><span>${t('key_weapon')}</span>
<b>Shift / E</b><span>${t('key_tower')}</span><b>C</b><span>${t('key_cam')}</span><b>P / Esc</b><span>${t('pause')}</span><b>M</b><span>${t('sound_on')} / ${t('sound_off')}</span>
<b>${t('key_pad')}</b><span>${t('key_pad_text')}</span></div>`;
}
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(); };
$('bGOnline').onclick = () => { SFX.click(); persist(); startOnline(); };
if (!(net && net.enabled)) $('bGOnline').style.display = 'none';
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
$('bLeague').onclick = () => { SFX.click(); showLeague(); };
function showLeague() {
setScreen('league');
const cards = RC.LEAGUE.map((o, i) => {
const cls = i < save.beaten ? 'done' : i === save.beaten ? 'next' : 'locked';
return `<div class="opp ${cls}" data-i="${i}">${RC.pic('opp_' + o.id, '🤖')}<div class="nm">${i + 1}. ${o.name}</div>
<div class="sm">${i <= save.beaten ? t('style_' + o.style) : '???'}</div>
<div class="pz">${RC.pic('ico_credits', '🪙')}${Kit.fmt(Math.round(o.prize * seasonMul()))}</div></div>`;
}).join('');
card(`<h2>${t('league_title', { s: save.season })}</h2><p>${t('league_text')}</p><div class="opps">${cards}</div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bFight">${t('fight_vs', { name: RC.LEAGUE[save.beaten].name })}</button></div>
${save.beaten ? `<p class="muted">${t('exhibition_hint')}</p>` : ''}`,
{ wide: true, bg: 'bg_title.jpg' });
overlay.querySelectorAll('.opp.next').forEach(el => { el.style.cursor = 'pointer'; el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); }; });
// beaten opponents: repeatable exhibition fights for half the prize (steady income)
overlay.querySelectorAll('.opp.done').forEach(el => { el.style.cursor = 'pointer'; el.title = t('exhibition_note'); el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[+el.dataset.i], true); }; });
$('bFight').onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); };
$('bBack').onclick = () => { SFX.click(); openGarage(); };
}
function showVs(opp, exhibition) {
const me = RC.stats(save.build), en = RC.stats(opp.build);
const line = s => `${Math.round(s.hp)} ${t('m_hp')} · ${Math.round(s.reduce * 100)}% ${t('m_armour')} · ${s.top.toFixed(1)} m/s`;
const mine = view.portrait(save.build, paintObj());
const myPic = mine ? `<span class="pic"><img src="${mine}" alt="" draggable="false"></span>` : RC.pic('icon', '🤖');
card(`<div class="vs"><div class="side">${myPic}<div class="nm">${esc(save.robotName)}</div><div class="muted">${weaponName(save.build)}</div><div class="muted">${line(me)}</div></div>
<div class="mid">VS</div>
<div class="side">${RC.pic('opp_' + opp.id, '🤖')}<div class="nm">${opp.name}</div><div class="muted">${weaponName(opp.build)}</div><div class="muted">${line(en)}</div></div></div>
<p>${t('style_' + opp.style)}</p>${exhibition ? `<p class="muted">${t('exhibition_note')}</p>` : ''}
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${exhibition ? t('exhibition_btn') : t('fight_go_btn')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showLeague(); };
$('bGo').onclick = () => { SFX.click(); startFight(opp, false, exhibition); };
}
// ---------------------------------------------------------------- fight
function startFight(opp, training, exhibition, online) {
hideOverlay();
const D = DIFF[settings.diff] || DIFF.easy;
const stA = RC.stats(save.build), stB = RC.stats(opp.build);
if (!online) stA.hp = Math.round(stA.hp * D.hp); // no handicap in live PvP
const seed = online ? online.seed : (Date.now() & 0xffff) + save.games * 31;
// arena: league scales with the opponent, online derives from the shared seed, training uses the setting
const ids = RC.ARENAS.map(a => a.id), idx = RC.LEAGUE.indexOf(opp);
const arenaId = DEV.get('arena') ? DEV.get('arena')
: online ? ids[seed % ids.length]
: idx >= 0 ? ids[Math.min(ids.length - 1, Math.floor(idx / 3))]
: settings.arena === 'random' || !settings.arena ? ids[(Math.random() * ids.length) | 0] : settings.arena;
const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name], arena: arenaId });
const skill = Kit.clamp(opp.skill + (save.season - 1) * 0.12 + D.skill, 0, 1);
F = { s, opp, training, exhibition: !!exhibition, online, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4,
acc: [0, 0], accT: 0, banner: null, ended: false };
if (online) {
F.nf = RC.NetFight({ net, id: online.id, host: online.host, oppStyle: 'brawler', oppSkill: 0.6, onPeerLost: () => banner(t('peer_lost'), '#ff4a3a', 2.5), onPeerBack: () => banner(t('peer_back'), '#6dff9e', 1.6) });
F.nf.start();
}
// dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing)
if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 });
if (DEV.has('ff')) {
F.count = 0; F.beat = 0;
const ai2 = F.auto || RC.AI.create({ style: 'brawler', skill: 0.5, seed });
for (let i = 0; i < (+DEV.get('ff') || 20) * 60 && !s.result; i++) {
RC.Combat.step(s, 1 / 60, [ai2.think(s, s.robots[0], s.robots[1], 1 / 60), F.brain.think(s, s.robots[1], s.robots[0], 1 / 60)]);
s.events.length = 0;
}
}
view.showArena(s, [save.build, opp.build], [paintObj(), oppPaint(opp)]);
view.setCam(DEV.get('cam') || settings.cam); // dev: &cam=chase|fpv
$('fN0').textContent = save.robotName; $('fN1').textContent = opp.name;
$('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(opp.build);
$('fH0').style.background = barCol(save.paint); $('fH1').style.background = barCol(opp.paint);
fx.clear();
setScreen('fight');
audio.music('music_fight');
banner('📍 ' + t('arena_' + s.arena.id), '#ff7a1a', 2.2);
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) };
}
// 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');
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; }
const s = F.s, me = s.robots[0], en = s.robots[1];
let k = { throttle: ky, turn: kx, fire, fire2 };
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 };
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 };
}
}
// 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') 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) k.fire2 = dist < tw.range * 0.95;
}
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 = RC.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;
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(); }
s.robots.forEach((r, i) => {
if (r.out) return;
const [px, py] = P(r.x, r.z), [qx, qy] = P(r.x + Math.cos(r.a), r.z + Math.sin(r.a)), ang = Math.atan2(qy - py, qx - px);
ctx.save(); ctx.translate(px, py); ctx.rotate(ang);
ctx.fillStyle = i === 0 ? hex(save.paint.body) : hex(F.opp.paint.body); ctx.strokeStyle = i === 0 ? '#fff' : '#000'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(7, 0); ctx.lineTo(-5, 5); ctx.lineTo(-5, -5); ctx.closePath(); ctx.fill(); ctx.stroke();
ctx.restore();
});
ctx.restore();
}
function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; }
function update(dt) {
fx.update(dt);
introTick();
if (mode !== 'fight' || !F) return;
if (F.count > 0) {
if (F.nf) F.nf.idle(dt);
F.count -= dt;
const n = Math.ceil(F.count);
if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } }
return;
}
const s = F.s, [me, en] = s.robots;
let events;
if (F.online) {
events = F.online.host ? F.nf.hostStep(s, playerInput(), dt) : F.nf.guestFrame(s, playerInput(), dt);
} else {
RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]);
events = s.events;
}
for (const e of events) {
SFX.event(e);
if (e.type === 'dmg') F.acc[e.who] += e.amount;
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(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];
if (F.online) { endOnlineFight(res, won, me); return; }
const lines = [];
let money = 0, fame = 0, champion = false;
if (!F.training) {
const prize = Math.round(opp.prize * seasonMul() * (F.exhibition ? 0.5 : 1));
save.games++;
if (won && F.exhibition) {
money += prize; lines.push([t('r_exhibition'), prize]);
fame = (idx + 1) * 10 * save.season;
save.wins++;
} else if (won) {
const bonus = res.reason === 'pit' ? 0.3 : res.reason === 'ko' ? 0.2 : 0;
money += prize; lines.push([t('r_prize'), prize]);
if (bonus) { const b = Math.round(prize * bonus); money += b; lines.push([t('r_bonus_' + res.reason), b]); }
fame = (idx + 1) * 50 * save.season + (res.reason === 'pit' ? 40 : res.reason === 'ko' ? 25 : 0);
save.wins++;
if (idx === save.beaten) save.beaten++;
if (save.beaten >= RC.LEAGUE.length) {
champion = true;
const cb = 1500 * save.season; money += cb; fame += 500 * save.season; lines.push([t('r_champion'), cb]);
save.season++; save.beaten = 0;
}
} else {
const ap = Math.round(prize * 0.35); money += ap; lines.push([t('r_appearance'), ap]);
save.losses++;
}
// every hit pays: damage bonus win or lose
const db = Math.round(me.dealt * 0.6 * (F.exhibition ? 0.5 : 1));
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06 + (res.reason === 'pit' && !won ? me.st.value * 0.03 : 0));
const paid = Math.min(repair, save.money + money);
if (paid) lines.push([t('r_repair'), -paid]);
money -= paid;
save.money += money; save.fame += fame;
persist();
}
hud();
(won ? SFX.win : SFX.lose)();
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
const why = t('why_' + res.reason + (res.winner === -1 ? '_draw' : won ? '_win' : '_lose'), { name: opp.name });
const rows = lines.map(([k, v]) => `<span>${k}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
const stats = `<span>${t('r_dealt')}</span><span>${Math.round(me.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(me.taken)}</span>`;
setScreen('result');
card(`<h1>${title}</h1><p>${why}</p>
${champion ? `<h2>${t('champion_title', { s: save.season - 1 })}</h2><p>${t('champion_text')}</p>` : ''}
<div class="res">${stats}${rows}${!F.training && fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div>
${F.training ? `<p class="muted">${t('training_note')}</p>` : ''}
<div class="row"><button class="primary" id="bGarage">${t('to_garage')}</button>${!F.training && !won ? `<button id="bRetry">${t('retry')}</button>` : ''}</div>${boardHtml()}`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bGarage').onclick = () => { SFX.click(); openGarage(); };
if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false, F.exhibition); };
if (!F.training && save.fame > save.best) {
save.best = save.fame; persist();
scores.submit({ name: playerName(), score: save.fame, level: save.season }).then(fillBoard);
} else fillBoard();
}
function endOnlineFight(res, won, me) {
if (F.nf) F.nf.stop();
if (lobby) lobby.endMatch();
(won ? SFX.win : SFX.lose)();
const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat');
// online rewards: prize (win) / half (draw) / appearance fee (loss) + damage bonus - repairs; fame on a win
const PVP = 600, lines = [];
let money = 0, fame = 0;
const draw = res.winner === -1;
if (won) { money += PVP; lines.push([t('r_prize'), PVP]); fame = 150 + (res.reason === 'ko' ? 40 : res.reason === 'pit' ? 60 : 0); }
else if (draw) { money += PVP / 2; lines.push([t('r_draw_prize'), PVP / 2]); fame = 40; }
else { const ap = Math.round(PVP * 0.35); money += ap; lines.push([t('r_appearance'), ap]); }
if (won && res.reason !== 'time') { const b = Math.round(PVP * (res.reason === 'pit' ? 0.3 : 0.2)); money += b; lines.push([t('r_bonus_' + res.reason), b]); }
const db = Math.round(me.dealt * 0.6);
if (db) { money += db; lines.push([t('r_dmg_bonus'), db]); }
const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.06);
const paid = Math.min(repair, save.money + money);
if (paid) { money -= paid; lines.push([t('r_repair'), -paid]); }
save.money += money; save.fame += fame; save.games++;
if (won) save.wins++; else if (!draw) save.losses++;
persist(); hud();
if (save.fame > save.best) { save.best = save.fame; persist(); scores.submit({ name: playerName(), score: save.fame, level: save.season }); }
const rows = lines.map(([k, v]) => `<span>${k}</span><span class="${v < 0 ? 'minus' : 'plus'}">${v < 0 ? '−' : '+'}${Kit.fmt(Math.abs(v))}</span>`).join('');
setScreen('result');
card(`<h1>${title}</h1><p>${esc(F.opp.name)} ${F.nf && !F.nf.peerAlive ? t('peer_left') : ''}</p>
<div class="res"><span>${t('r_dealt')}</span><span>${Math.round(me.dealt)}</span><span>${t('r_taken')}</span><span>${Math.round(me.taken)}</span>${rows}
${fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div>
<div class="row"><button class="primary" id="bLobby">${t('back_to_lobby')}</button><button id="bShopO">${t('to_garage')}</button></div>`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bLobby').onclick = () => { SFX.click(); showLobby(); };
$('bShopO').onclick = () => { SFX.click(); openGarage(); };
}
// ---------------------------------------------------------------- loop
let lastNow = 0;
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 (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() {
if (F && F.online && mode === 'fight') { banner(t('no_pause_online'), '#ffffff', 1.4); return; }
if (mode === 'fight') {
mode = 'pause'; loop.pause();
card(`<h2>${t('pause')}</h2><div class="row"><button id="bSet2">⚙ ${t('settings')}</button><button id="bQuit">${t('give_up')}</button><button class="primary" id="bGo">${t('continue')}</button></div>`);
$('bGo').onclick = togglePause;
$('bSet2').onclick = () => { SFX.click(); showSettings(() => { mode = 'fight'; togglePause(); }); };
$('bQuit').onclick = () => {
mode = 'fight'; loop.resume(); hideOverlay();
if (F && !F.s.result) { F.s.robots[0].hp = 0; F.s.robots[0].dead = true; F.s.result = { winner: 1, reason: 'ko' }; F.s.endIn = 0; }
};
} else if (mode === 'pause') { mode = 'fight'; hideOverlay(); loop.resume(); }
}
function toggleMute() { audio.toggleMute(); hud(); }
$('bMute').onclick = toggleMute;
$('bPause').onclick = togglePause;
addEventListener('blur', () => { if (mode === 'fight' && !(F && F.online)) togglePause(); });
// language switch: static texts update themselves (data-i18n), dynamic screens are drawn again
L.onChange(() => {
hud();
if (mode === 'title') showTitle();
else if (mode === 'garage') shop.render();
else if (mode === 'league') showLeague();
else if (mode === 'lobby') renderLobby();
if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); }
});
// ---------------------------------------------------------------- start
accounts.resume();
if (net && net.enabled) { net.auth.resume(); net.auth.onChange(() => { hud(); if (mode === 'title') showTitle(); }); }
hud();
if (!view) {
card(`<h1>Robot Clash</h1><p>${t('no_webgl')}</p><p class="credits">${CREDITS}</p>`);
} else if (DEV.has('fight') || DEV.has('play')) {
// dev: ?play = straight into the shop, ?fight=N = training fight against league robot N
if (!accounts.current) accounts.guest();
loadSave(); hud();
if (DEV.get('equip')) for (const id of DEV.get('equip').split(',')) { const p = RC.PARTS[id]; if (p) { if (!save.owned.includes(id)) save.owned.push(id); save.build[p.slot] = id; } }
if (DEV.get('arena')) settings.arena = DEV.get('arena');
RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); });
if (DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true); else openGarage();
// dev: ?play&screen=league|vs|settings|help|lobby|pause opens that screen (layout screenshots)
const scr = DEV.get('screen');
if (scr === 'league') { save.beaten = Math.max(save.beaten, 3); showLeague(); }
else if (scr === 'vs') showVs(RC.LEAGUE[4]);
else if (scr === 'settings') showSettings(openGarage);
else if (scr === 'help') showHelp(openGarage);
else if (scr === 'lobby') {
lobbyRows = [{ uid: 'a', name: 'BlechBrecher', flag: 'DE', fame: 1250, state: 'idle' }, { uid: 'b', name: 'SawQueen', flag: 'DE', fame: 430, state: 'inmatch' }, { uid: 'c', name: 'Rostlaube77', flag: 'AT', fame: 90, state: 'idle' }, { uid: 'd', name: 'Flipmaster', flag: 'GB', fame: 600, state: 'idle' }];
lobbyRoom = DEV.get('room') || null;
showLobby();
}
if (DEV.get('tab')) { const tb = document.querySelector(`.tab[data-slot="${DEV.get('tab')}"]`); if (tb) tb.click(); }
// dev: &buy=<part id> buys it through the real shop buttons (header check)
if (DEV.get('buy')) { const it = document.querySelector(`.item[data-id="${DEV.get('buy')}"]`); if (it) { it.click(); const b = document.querySelector('#detail button[data-act="buy"]'); if (b) b.click(); } }
// dev: &equip=wedge,flamer forces parts onto the robot (ignores cost), then shows the garage
if (DEV.get('equip') && !DEV.has('fight')) { for (const id of DEV.get('equip').split(',')) { const p = RC.PARTS[id]; if (p) { if (!save.owned.includes(id)) save.owned.push(id); save.build[p.slot] = id; } } persist(); view.showGarage(save.build, paintObj()); shop.render(); }
if (DEV.has('paint')) { // dev: open the paint booth with a test drawing
const c = layer.getContext('2d');
c.fillStyle = '#15171b'; c.fillRect(0, 100, 256, 56); c.fillStyle = '#f2c230'; c.font = 'bold 70px sans-serif'; c.fillText('★ 7', 300, 170);
c.strokeStyle = '#00e5ff'; c.lineWidth = 14; c.beginPath(); c.moveTo(270, 220); c.lineTo(500, 200); c.stroke();
painter.open(); view.showGarage(save.build, paintObj());
}
} else if (DEV.has('online') && net.enabled) { startIntroOrTitle(); startOnline(); }
else if (DEV.has('title')) startIntroOrTitle();
else startIntro();
})();