/* Robot Clash - game frame: intro, title, accounts, settings, shop, league, fight, result, audio, scores. Logic lives in parts.js / robot.js / combat.js / ai.js (no DOM), the 3D view in render3d.js, the shop panel in shop.js, accounts in profiles.js. Texts: lang.js via t('key'). Credits line stays on the title screen. */ (function () { 'use strict'; const $ = Kit.$; const W = 1280, H = 720; // design size of the stage (16:9, higher res = denser UI) const ID = 'robotclash'; // localStorage prefix // Own backend (server/): auth + saves + ranks + lobby + live PvP. Empty serverUrl = same origin as the page, // so when the game is served by the Node server it just works. file:// (double-click) stays offline. const NET_CFG = { serverUrl: '' }; // dev/test: ?server=http://localhost:8080 points at a server on another origin; ?online jumps to login/lobby { const s = new URLSearchParams(location.search).get('server'); if (s) NET_CFG.serverUrl = s; } const DB_URL = (NET_CFG.serverUrl || '') + '/db'; // ranking (Kit.scores) via the same server // Credits (standard for every game): shown on the title screen, links open in the normal browser const DISCORD = 'https://discord.gg/Ej4JPmCZva'; // live settings from the backend (/live): news, events, unlocks, kill switch. // Always usable - without a backend or network this is simply "nothing special running". let LIVE = RC.Live.parse(null, Date.now(), BUILD_ID()); const liveText = o => (o && (o[L.lang] || o.en || o.de)) || ''; const evMul = () => (LIVE.event ? LIVE.event.prizeMul : 1); // extra earnings from a running event, shown as its own result line function applyEvent(money, lines) { const m = evMul(); if (m === 1 || money <= 0) return money; const bonus = Math.round(money * m) - money; if (bonus) lines.push([t('event_bonus'), bonus]); return money + bonus; } function BUILD_ID() { return (typeof window !== 'undefined' && window.RC_BUILD) || ''; } const SITE = 'https://michael-media.de'; // build stamp comes from build-web.mjs; identifies the exact release in a leaked copy const BUILD = (typeof window !== 'undefined' && window.RC_BUILD) || ''; const CREDITS = `© 2026 Michael Media` + ` · Discord` + (BUILD ? ` · ${BUILD}` : ''); // Soft domain lock: the published build only runs on our own site. Local file, localhost and the // exe always run. This stops a lazy re-upload, nothing more - the file itself can always be copied. const HOSTS = ['localhost', '127.0.0.1', '']; // own hosts: any subdomain of michael-media.de (roboclash.michael-media.de) plus the Hetzner IP const hostOk = () => location.protocol === 'file:' || HOSTS.includes(location.hostname) || /(^|\.)michael-media\.de$/.test(location.hostname) || location.hostname === '91.99.166.238' || (Kit.host && Kit.host.exe) || document.documentElement.classList.contains('exe'); // ---------------------------------------------------------------- services const L = Kit.i18n(window.LANG, { prefix: ID }); // first start (no saved choice yet): default to English, not the browser language if (Kit.store(ID).get('lang', null) === null) L.set('en'); const t = L.t; const store = Kit.store(ID); // steer: 'simple' (keys = screen direction) | 'tank' · diff: 'easy' | 'normal' | 'hard' · autofire: weapon fires by itself in reach const settings = Object.assign({ gfx: 'medium', intro: true, steer: 'tank', autofire: true, cam: 'fpv', arena: 'random', quiet: false, comfort: true }, 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 + // fixed balance baseline (used to be the "easy" setting, which was the default anyway). // The weight class is meant to be the dial from here on, not a difficulty menu. const BASE = { hp: 1.4, skill: -0.2 }; 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', flagSet: false, tutorialSeen: false, ach: {}, tour: null, cls: 'medium', leagues: null, robots: [], active: 0, // hangar: saved robot builds; the active one mirrors build/paint/robotName }); const MAX_ROBOTS = 6; const newRobotDef = n => ({ name: n || 'Robot', build: Object.assign({}, RC.STARTER), paint: { body: 0xff7a1a, accent: 0x15171b, decal: null, drawn: false } }); // keep the active hangar slot in sync with the live build/paint/robotName before saving function syncActive() { if (!save || !save.robots || !save.robots[save.active]) return; const r = save.robots[save.active]; r.name = save.robotName; r.build = save.build; r.paint = save.paint; } let slot = null, save = null; // per account, set by enterAccount() // the active class's league progress lives in save.beaten/season while you play, // and is written back to its own slot on every save (same idea as the active robot) const syncClass = () => { if (save && save.leagues && save.cls) save.leagues[save.cls] = { beaten: save.beaten | 0, season: save.season || 1 }; }; const persist = () => { if (slot && save) { syncActive(); syncClass(); save.ts = Date.now(); slot.save(save); if (fbAcc()) cloud.push(cloudId(), 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 }, }); // first start (nothing saved yet): start very quiet; gain is squared, so these are low if (Kit.store(ID).get('music', null) === null) audio.setVolume(0.1, 0.35); const scores = Kit.scores({ url: DB_URL }); // legacy (Firebase-only, disabled on the own server) const DEV = new URLSearchParams(location.search); if (DEV.has('touch')) document.body.classList.add('forcetouch'); // dev: &touch shows the touch pad on desktop const net = RC.Net(NET_CFG); const rank = RC.Ranking(net); // live ranking over the own server (ranks/ + SSE) const rankRow = () => ({ uid: (fbAcc() && fbAcc().uid) || net.uid, name: playerName(), fame: save.fame, flag: save.flag, cls: save.cls, season: save.season }); const cloud = RC.CloudSave(net); // mirrors a registered account's save to the server (best effort) // cloud path per mode: saves// - keeps the two games fully separate in the cloud too // (server rule canWrite('saves/$uid/...') still holds: segment[1] stays the uid) const cloudId = () => { const a = fbAcc(); return a ? a.uid + '/' + (gameMode === 'online' ? 'online' : 'campaign') : null; }; const cloudFlush = () => { if (fbAcc() && save) cloud.flush(cloudId(), save); }; // dev menu: only the admin account (ADMIN_UID on the server) sees it. The server tells us via /api/me. let isDev = false; function refreshDev() { if (!net.enabled || !fbAcc()) { isDev = false; return; } net.token().then(tk => { if (!tk) return; fetch((NET_CFG.serverUrl || '') + '/api/me?auth=' + tk).then(r => r.json()).then(d => { isDev = !!(d && d.admin); }).catch(() => {}); }); } const FLAGS = ['DE', 'AT', 'CH', 'GB', 'US', 'FR', 'ES', 'IT', 'NL', 'PL', 'TR', 'RU', 'BR', 'JP', 'KR', 'XX']; const flagHtml = c => ``; 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, decal: save.paint.decal || null, drawn: !!save.paint.drawn }, fame: save.fame | 0 }) }) : null; const fx = Kit.fx(); const input = Kit.input({ keys: { ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', ArrowRight: 'right', d: 'right', ' ': 'fire', Shift: 'fire2', e: 'fire2', g: 'fire3', p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok', c: 'cam', }, onPress(a) { if (mode === 'intro') { skipIntro(); return; } if (a === 'pause') togglePause(); else if (a === 'mute') toggleMute(); else if (a === 'cam' && mode === 'fight') cycleCam(); else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); } }, }); // ---------------------------------------------------------------- sound (ComfyGen clips + synth fallback) const last = {}; const every = (k, ms) => { const n = performance.now(); if (last[k] && n - last[k] < ms) return false; last[k] = n; return true; }; const SFX = { click() { audio.sfx('sfx_click'); audio.tone(660, 0.04, 'square', 0.05); }, buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.08); }, deny() { audio.tone(160, 0.15, 'square', 0.12, -40); }, beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); }, clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); }, gate() { // metal garage door rolling open audio.noise(1.0, 0.4, 1500); audio.noise(0.9, 0.3, 500, 0.05); // metal roll rumble audio.tone(110, 0.9, 'sawtooth', 0.1, 70); // servo whir rising for (let k = 0; k < 6; k++) audio.tone(170 + k * 28, 0.05, 'square', 0.07, 0, k * 0.11); // chain clanks audio.noise(0.25, 0.55, 300, 0.9); audio.tone(58, 0.4, 'sine', 0.5, -22, 0.9); // heavy end clunk }, win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); }, lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); }, event(e) { switch (e.type) { case 'bump': if (every('bump', 90)) audio.noise(0.12, Math.min(0.4, e.speed / 10), 700); break; case 'wall': if (every('wall', 120)) { audio.sfx('sfx_hit'); audio.noise(0.2, 0.3, 1600); } break; case 'flip': audio.tone(200, 0.2, 'square', 0.13, 500); audio.noise(0.12, 0.25, 3000); break; case 'swing': audio.noise(0.15, 0.12, 900); break; case 'smash': audio.sfx('sfx_hit'); audio.noise(0.25, 0.45, 650); audio.tone(95, 0.25, 'sine', 0.4, -45); break; case 'spinhit': audio.sfx('sfx_hit'); audio.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); break; case 'sparks': if (every('grind', 70)) audio.noise(0.06, 0.1, 5200); break; case 'boom': audio.sfx('sfx_boom'); audio.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break; case 'ko': audio.sfx('sfx_boom'); audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); break; case 'launch': audio.noise(0.3, 0.18, 2200); audio.tone(300, 0.3, 'sawtooth', 0.07, 600); break; case 'press_warn': for (let k = 0; k < 3; k++) audio.tone(880, 0.1, 'square', 0.1, 0, k * 0.2); break; case 'press': audio.sfx('sfx_hit'); audio.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); break; case 'crane': audio.tone(140, 0.6, 'sawtooth', 0.07, 140); break; case 'drop': case 'land': audio.noise(0.22, 0.35, 500); break; case 'broke': audio.sfx('sfx_hit'); audio.noise(0.45, 0.5, 900); audio.tone(240, 0.35, 'sawtooth', 0.22, -190); break; case 'mine_drop': audio.tone(520, 0.08, 'square', 0.12, -160); audio.noise(0.06, 0.12, 2200); break; case 'pit_open': for (let k = 0; k < 3; k++) audio.tone(700, 0.3, 'square', 0.12, -250, k * 0.4); break; case 'pit': audio.tone(420, 1.2, 'sawtooth', 0.14, -360); break; case 'grab': audio.tone(150, 0.25, 'square', 0.12, -60); break; case 'boost': audio.noise(0.4, 0.25, 1800); break; } }, loops(s) { // continuous weapons as short repeated bursts for (const r of s.robots) { const q = settings.quiet ? 0.3 : 1, slow = settings.quiet ? 1.7 : 1; // quiet mode: softer + less often if (r.sawOn && every('saw' + r.i, 200 * slow)) { if (!settings.quiet) audio.sfx('sfx_saw', 0.35); audio.tone(360 + Math.random() * 40, 0.12, 'triangle', 0.02 * q); } if (r.flameOn && every('fl' + r.i, 120 * slow)) audio.noise(0.14, 0.12 * q, 900); if (r.gunOn && every('gun' + r.i, 70 * slow)) audio.noise(0.04, 0.16 * q, 3500); if (r.spin > 0.2 && every('spin' + r.i, 100 * slow)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin * q); } }, }; // ---------------------------------------------------------------- view const cv = $('cv'); let ctx = cv.getContext('2d'); let view = null; try { view = RC.Render($('gl'), W, H); view.setQuality(settings.gfx); } catch (err) { console.error(err); } // cap upscaling so the UI does not get huge on big / high-DPI screens (960x540 stage, max ~2x) Kit.fit($('app'), { max: 2.0, margin: document.documentElement.classList.contains('exe') ? 1 : 0.98, canvases: [[cv, W, H]], onFit(sc) { ctx = cv.getContext('2d'); if (view) view.resize(sc); } }); Kit.host.dragArea(document.body); const hex = n => '#' + (n >>> 0).toString(16).padStart(6, '0'); const img = name => Kit.asset('assets/Sprites/' + name); function backdrop(name) { $('bgimg').style.backgroundImage = name ? `url("${img(name)}")` : 'none'; } $('icoMoney').innerHTML = ``; $('icoFame').innerHTML = ``; const shop = RC.Shop({ t, getSave: () => save, onSave: () => { persist(); hud(); }, // buy/sell/rename -> header onBuild: () => view.showGarage(save.build, paintObj()), onPaint: () => view.setPaint(paintObj()), onPreview: b => { if (mode === 'garage') view.showGarage(b, paintObj()); }, // show the selected part on the robot onHangarView: el => renderHangar(el), // Hangar tab content onSlot: slot => { const on = slot === 'weapon'; if (on !== editorOpen) { editorOpen = on; view.freeze(on); } if (on) view.setEditWeapon(editSel); else { const wp = $('wplace'); if (wp) wp.classList.add('hide'); } }, onWeaponTab: () => renderWeaponEditor(), // weapon tab fills #cards with the catalog + #wplace with placement weaponPreview: () => { // build with the PICKED weapon added, so the warning shows before buying if (!save) return null; const weps = save.build.weapons || []; if (!wPrev || weps.length >= RC.MAX_WEAPONS) return null; // picking = intent to mount -> preview the added cost return Object.assign({}, save.build, { weapons: weps.concat([{ id: wPrev, side: 'front', up: 0 }]) }); }, onPaintTab: el => paintTab(el), // paint tab: 3 slots + colours + the inline painter onPaintLeave: () => paintLeave(), locked: id => LIVE.locked('parts', id), // event/unlock: part not released yet 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()), }); if ($('bPaint')) $('bPaint').onclick = () => { SFX.click(); painter.open(); view.showGarage(save.build, paintObj()); }; // drag on the robot turns it; in the build editor, grab a weapon to place it instead let drag = null, wdrag = false, editorOpen = false, editSel = 0, wPrev = null; $('gl').addEventListener('pointerdown', e => { if (mode !== 'garage') return; if (editorOpen && save) { const hit = view.pickWeaponAt(e.clientX, e.clientY); if (hit >= 0) { editSel = hit; wPrev = save.build.weapons[hit] && save.build.weapons[hit].id; view.setEditWeapon(editSel); wdrag = true; $('gl').setPointerCapture(e.pointerId); renderWeaponEditor(); return; } } drag = e.clientX; $('gl').setPointerCapture(e.pointerId); }); $('gl').addEventListener('pointermove', e => { if (wdrag) { const mnt = view.dragWeapon(e.clientX, e.clientY); if (mnt && save && save.build.weapons[editSel]) { save.build.weapons[editSel].side = mnt.side; save.build.weapons[editSel].up = mnt.up; } return; } if (drag != null) { view.turn(e.clientX - drag); drag = e.clientX; } }); $('gl').addEventListener('pointerup', () => { if (wdrag) { wdrag = false; persist(); refreshEditorRobot(); renderWeaponEditor(); } drag = null; }); addEventListener('beforeunload', () => { try { cloudFlush(); } catch (e) { /* closing anyway */ } }); // ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ---- function refreshEditorRobot() { view.showGarage(save.build, paintObj()); view.freeze(true); view.setEditWeapon(editSel); } function reDrawEditor() { persist(); hud(); refreshEditorRobot(); shop.render(); } // after a change: 3D + tabs + meters + editor // weapon detail chips (mirrors the shop's part chips, weapon stats only) function wChips(p) { const s = []; if (p.dmg) s.push(`${t('st_dmg', { n: p.dmg })}`); if (p.dps) s.push(`${t('st_dps', { n: p.dps })}`); if (p.range) s.push(`${t('st_range', { n: p.range })}`); s.push(`⌨ ${t('hk_weapon')}`); s.push(`⚖️ ${p.weight} kg`); if (p.power) s.push(`⚡ ${p.power}`); return s.join(''); } // show the clicked weapon live on the robot (a mounted one, else a temporary front preview) function previewWeapon(id) { const weps = save.build.weapons || []; const idx = weps.findIndex(w => w.id === id); if (idx >= 0) { editSel = idx; refreshEditorRobot(); } else { const pv = Object.assign({}, save.build, { weapons: weps.concat([{ id, side: 'front', up: 0 }]) }); view.showGarage(pv, paintObj()); view.freeze(true); view.setEditWeapon(weps.length); } } function renderWeaponEditor() { const cards = $('cards'), wp = $('wplace'); if (!save || !cards) return; const b = save.build, weps = b.weapons || []; editSel = Math.min(editSel, Math.max(0, weps.length - 1)); const cat = RC.partsFor('weapon'); const canAdd = weps.length < RC.MAX_WEAPONS; if (!wPrev || !RC.PARTS[wPrev]) wPrev = (weps[editSel] && weps[editSel].id) || cat[0].id; // right (#cards): the weapon catalog, same card grid as the other slots — click = preview cards.className = ''; cards.innerHTML = cat.map(p => { const mounted = weps.filter(w => w.id === p.id).length; const badge = mounted ? `×${mounted}` : ''; const price = `
🪙 ${Kit.fmt(p.cost)}
`; return `
${badge}${RC.pic('part_' + p.id, GLYPH_SLOT.weapon)}
${p.name}
${price}
`; }).join(''); cards.querySelectorAll('[data-prev]').forEach(x => x.onclick = () => { wPrev = x.dataset.prev; SFX.click(); previewWeapon(wPrev); renderWeaponEditor(); }); // detail panel: previewed weapon + Montieren / Entfernen (like the other slots) const dp = $('detail'), pv = RC.PARTS[wPrev]; if (dp && pv) { const mounted = weps.filter(w => w.id === wPrev).length, poor = save.money < pv.cost; let act = ``; if (mounted) act += ``; if (!canAdd) act += `${t('ed_max', { n: RC.MAX_WEAPONS })}`; dp.innerHTML = `${RC.pic('part_' + wPrev, GLYPH_SLOT.weapon)}
${pv.name}${mounted ? ` ×${mounted}` : ''}
${t('pd_' + wPrev)}
${wChips(pv)}
${act}
`; dp.querySelectorAll('button[data-wact]').forEach(x => x.onclick = () => { if (x.dataset.wact === 'add') addWeapon(wPrev); else { const i = weps.map(w => w.id).lastIndexOf(wPrev); if (i >= 0) removeWeapon(i); } }); } // left (#wplace): placement of the active mounted weapon + shape (no sell list) if (wp) { const sel = weps[editSel]; const sides = [['front', t('mt_front')], ['back', t('mt_back')], ['left', t('mt_left')], ['right', t('mt_right')]]; const srow = (key, label, lo, hi) => { const val = (b.body && b.body[key]) || 1; return `
${t('des_' + label)}${Math.round(val * 100)}%
`; }; wp.classList.remove('hide'); wp.innerHTML = `
${t('ed_weapons')} ${weps.length}/${RC.MAX_WEAPONS}
` + (sel ? `
${t('ed_place')} — ${RC.PARTS[sel.id].name}
` + `
${sides.map(([k, lb]) => ``).join('')}
` + `
${t('des_height')}${Math.round(((sel.up || 0) + 0.3) / 0.9 * 100)}%
` : `${t('ed_noweapons')}`) + `
${t('s_body')}
${srow('hx', 'height', 0.7, 1.6)}${srow('wx', 'width', 0.8, 1.4)}${srow('lx', 'length', 0.8, 1.3)}`; wp.querySelectorAll('[data-side]').forEach(x => x.onclick = () => { if (!sel) return; sel.side = x.dataset.side; SFX.click(); reDrawEditor(); }); if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } }; if ($('edUp')) $('edUp').onchange = () => reDrawEditor(); wp.querySelectorAll('[data-body]').forEach(x => { x.oninput = e => { b.body = b.body || { hx: 1, wx: 1, lx: 1 }; b.body[e.target.dataset.body] = +e.target.value; refreshEditorRobot(); }; x.onchange = () => reDrawEditor(); }); } if (weps[editSel] && weps[editSel].id === wPrev) view.setEditWeapon(editSel); } function addWeapon(id) { const p = RC.PARTS[id]; if (!p || save.build.weapons.length >= RC.MAX_WEAPONS || save.money < p.cost) { SFX.deny(); return; } save.money -= p.cost; save.build.weapons.push({ id, side: 'front', up: 0 }); editSel = save.build.weapons.length - 1; wPrev = id; view.setEditWeapon(editSel); SFX.buy(); reDrawEditor(); } function removeWeapon(i) { const w = save.build.weapons[i]; if (!w) return; const p = RC.PARTS[w.id]; if (p) save.money += Math.round(p.cost * 0.5); save.build.weapons.splice(i, 1); if (editSel >= save.build.weapons.length) editSel = Math.max(0, save.build.weapons.length - 1); view.setEditWeapon(editSel); SFX.buy(); reDrawEditor(); } // ---- paint tab: 3 save slots + quick colours + the inline painter (all inside #cards) ---- const phex = c => '#' + (c >>> 0).toString(16).padStart(6, '0'); function paintTab(el) { let hdr = $('paintHdr'); if (!hdr) { el.innerHTML = ''; hdr = document.createElement('div'); hdr.id = 'paintHdr'; hdr.className = 'phdr'; el.appendChild(hdr); } $('shop').classList.add('paintmode'); // hide category tabs / detail / fitted bar while painting renderPaintHeader(hdr); if (!painter.isOpen) painter.open(el); // mount the painter inline, below the header } function paintLeave() { $('shop').classList.remove('paintmode'); if (!painter.isOpen) return; const art = painter.hasArt(); save.paint.decal = art ? layer.toDataURL('image/png') : null; save.paint.drawn = art; painter.close(); persist(); const hdr = $('paintHdr'); if (hdr) hdr.remove(); } function renderPaintHeader(hdr) { const slots = save.paintSlots || []; hdr.innerHTML = `
${slots.map((s, i) => `
${s.decal ? '🖌' : ''}
`).join('')}
` + `

${t('paint_body')}

` + `

${t('paint_accent')}

` + `

${t('paint_schemes')}

`; for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) { $(id).innerHTML = RC.PAINTS.map(c => ``).join(''); $(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { save.paint[key] = +sw.dataset.c; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); }); } $('paintSchemes').innerHTML = RC.SCHEMES.map(([b2, a2]) => { const on = save.paint.body === b2 && save.paint.accent === a2; return ``; }).join(''); $('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { save.paint.body = +sw.dataset.b; save.paint.accent = +sw.dataset.a; SFX.click(); persist(); view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); }); hdr.querySelectorAll('[data-load]').forEach(x => x.onclick = e => { if (e.target.dataset.save) return; loadPaintSlot(+x.dataset.load); }); hdr.querySelectorAll('[data-save]').forEach(x => x.onclick = e => { e.stopPropagation(); savePaintSlot(+x.dataset.save); }); } function loadPaintSlot(i) { const s = save.paintSlots[i]; if (!s) return; save.paintSlot = i; save.paint.body = s.body; save.paint.accent = s.accent; save.paint.decal = s.decal || null; save.paint.drawn = !!s.drawn; SFX.click(); persist(); RC.layerFromData(layer, save.paint.decal, () => { view.showGarage(save.build, paintObj()); if (painter.sync) painter.sync(); }); const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr); } function savePaintSlot(i) { const art = painter.hasArt(); save.paintSlots[i] = { body: save.paint.body, accent: save.paint.accent, decal: art ? layer.toDataURL('image/png') : (save.paint.decal || null), drawn: art || !!save.paint.drawn }; save.paintSlot = i; SFX.buy(); persist(); const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr); } // ---------------------------------------------------------------- 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 = `
${html}
`; overlay.classList.remove('hide'); overlay.classList.toggle('clear', !!opt.clear); overlay.style.backgroundImage = opt.bg ? `linear-gradient(rgba(5,6,10,.55), rgba(5,6,10,.75)), url("${img(opt.bg)}")` : ''; } function hideOverlay() { overlay.classList.add('hide'); overlay.innerHTML = ''; overlay.style.backgroundImage = ''; } // fade a menu in once; the class is dropped again so live lists (lobby) do not flicker on every refresh let enterT = 0; function overlayEnter() { overlay.classList.add('enter'); clearTimeout(enterT); enterT = setTimeout(() => overlay.classList.remove('enter'), 220); } const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); const seasonMul = () => 1 + (save.season - 1) * 0.5; const weaponName = b => { const ws = RC.weaponsOf(b); const main = ws.length ? ws[0].part.name + (ws.length > 1 ? ' ×' + ws.length : '') : t('unarmed'); return main + (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); // decode an online opponent's own drawing (data URL) into a canvas before the arena is built, so it shows on their robot const oppDecalCv = (() => { const c = document.createElement('canvas'); c.width = 512; c.height = 256; return c; })(); function prepOpp(opp, done) { const d = opp && opp.paint && opp.paint.decal; if (!d) { done(); return; } RC.layerFromData(oppDecalCv, d, () => { opp.paint.layer = oppDecalCv; opp.paint.drawn = true; done(); }); } 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_, 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
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 ? `` : ''; const btns = acc ? `${online}` : `${online}`; // logo picture when ComfyGen made one, otherwise the lettering (never both, never nothing) const logo = `ROBOT CLASH
ROBOT CLASH
`; overlay.innerHTML = `
${logo}
${t('menu_text')}
${liveBanner()}
${btns}
${save ? `` : ''}${rank.enabled ? `` : ''}

${CREDITS}

${rank.enabled ? `

🏆 ${t('ranking')} ● ${t('rank_live')}

  1. ${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 ? `` : ''; card(`

    ${reg ? t('register') : t('login')}

    ${t('online_login_text')}

    ${f}
    ${errKey ? errText(errKey) : ''}

    ${reg ? '' : t('no_account') + ' '}

    ${next === 'online' ? `
    ` : ''}`, { 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 => ``).join(''); const room = (f, label, flag) => ``; 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('busy')}`)}
    `; const list = here.map(r => prow(r, false)).join(''); const title = lobbyRoom === 'all' ? '🌍 ' + t('all_countries') : flagHtml(lobbyRoom) + ' ' + t('cc_' + lobbyRoom); overlay.innerHTML = `
    🌍 ${t('lobby')}
    ${rooms}
    ${title} (${here.length + (showMe ? 1 : 0)})
    ${showMe ? prow(null, true) : ''}${list || (showMe ? '' : `
    ${t('lobby_empty')}
    `)}
    ${pendingOut ? `

    ${t('waiting_accept')}

    ` : ''}
    `; 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 = ``; 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 ? `` : ''; } card(`

    🏆 ${t('ltour_title')}

    ${body}
    ${buttons}
    `, { 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)}

    `, { 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')}

    `); $('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 => ``).join('')}
    ` : ''}
    ${errKey ? t(errKey) : ''}

    ${t('no_account')}

    ${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('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')}` : ``} ${save.robots.length > 1 ? `` : ''}
    `).join(''); el.innerHTML = `
    ${rows}
    ${save.robots.length < MAX_ROBOTS ? `` : `

    ${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')}

    `); $('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]) => ``).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'), ``) : ''} ${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
    ` : ''}
    ${t('s_account')} ${who ? '👤 ' + esc(who.name) + '' + (who.email ? ' ' + esc(who.email) + '' : '') : '👤 ' + t('guest')} ${save ? `` : ''}
    ${save ? `` : ''}
    `, { 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])}

    `, { 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 => ``).join('')}
    `, { 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}
    `, { 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')}

    `, { 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') + '' : ''}

    1. ${t('loading')}
    `, { 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')}

    `); $('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')}

    1. ${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 = ``; } else { head = `

    ${t('tour_round_' + RC.Tourney.ROUND_KEY[st.round])} · ${playerMatch ? t('tour_your_match', { name: esc(playerMatch[1].name) }) : ''}

    `; buttons = ``; } 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 ``; }).join(''); card(`

    ${t('league_title', { s: save.season })}

    ${tabs}

    ${t('league_text')}

    ${cards}
    ${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')}

    ` : ''}
    `, { 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')}

    ` : ''}
    ${!F.training && !won ? `` : ''}
    ${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)}
    `, { 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)}
    `, { 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')}

    `); $('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')}

    `); $('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 })();