/* 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/): accounts, online save + shop (server-authoritative), ranking, lobby + live fights over
// WebSocket. Empty serverUrl = same origin as the page, so when the Node server serves the game it just works.
// file:// (double-click) stays offline = campaign only.
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; }
// 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 GM = {}; // feature modules, created at the end (see 'feature modules')
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,
missions: null, mseed: (Math.random() * 1e9) | 0, unlockedPaints: null, unlockedSchemes: 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 }; };
// local cache always; online: cosmetics go to the server (economy only via act()); campaign: cloud copy for accounts
const persist = () => {
if (!slot || !save) return;
syncActive(); syncClass(); save.ts = Date.now(); slot.save(save);
if (gameMode === 'online') onlinePush(); else if (fbAcc()) cloud.push(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 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); // online ranking, computed by the server
const cloud = RC.CloudSave(net); // campaign copy for registered accounts (online saves live on the server)
const cloudFlush = () => { if (!save) return; if (gameMode === 'online') onlineFlush(); else if (fbAcc()) cloud.flush(save); };
// dev menu (coins): local guests always; server accounts only if admin (the server checks again)
let isDev = false;
function refreshDev() { isDev = !fbUser() ? true : !!fbUser().admin; }
// ---------------------------------------------------------------- online (game/online.js)
function act(...a) { return GM.online.act(...a); }
function endOnlineFight(...a) { return GM.online.endOnlineFight(...a); }
function onlineFightLost(...a) { return GM.online.onlineFightLost(...a); }
function onlineFlush(...a) { return GM.online.onlineFlush(...a); }
function onlinePull(...a) { return GM.online.onlinePull(...a); }
function onlinePush(...a) { return GM.online.onlinePush(...a); }
function renderLobby(...a) { return GM.online.renderLobby(...a); }
function showLobby(...a) { return GM.online.showLobby(...a); }
function showOnlineLogin(...a) { return GM.online.showOnlineLogin(...a); }
function startOnline(...a) { return GM.online.startOnline(...a); }
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 }) : null;
// F3 (or ?net): network overlay - ping graph + where lag comes from (netstats.js / netoverlay.js)
const netStats = RC.NetStats();
const netOverlay = net.enabled ? RC.NetOverlay({ stats: netStats, net, t, mount: $('stage') }) : null;
if (netOverlay && DEV.has('net')) netOverlay.toggle(true);
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 (game/sfx.js)
const SFX = RC.GameSfx(audio, settings);
// rate limit for repeating inputs (gamepad start button)
const lastT = {};
const every = (k, ms) => { const n = performance.now(); if (lastT[k] && n - lastT[k] < ms) return false; lastT[k] = n; return true; };
// ---------------------------------------------------------------- view
const cv = $('cv');
let ctx = cv.getContext('2d');
let view = null;
try { view = RC.Render($('gl'), W, H); view.setQuality(settings.gfx); if (view.setComfort) view.setComfort(settings.comfort); } 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
act: a => act(a), // economy changes (buy/sell/equip) - server-checked online
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; const w = save.build.weapons[editSel]; if (w) act({ type: 'weaponPlace', index: editSel, side: w.side, up: w.up }); persist(); refreshEditorRobot(); renderWeaponEditor(); }
drag = null;
});
addEventListener('beforeunload', () => { try { cloudFlush(); } catch (e) { /* closing anyway */ } });
// ---------------------------------------------------------------- workshop (game/workshop.js)
function paintLeave(...a) { return GM.workshop.paintLeave(...a); }
function paintTab(...a) { return GM.workshop.paintTab(...a); }
function refreshEditorRobot(...a) { return GM.workshop.refreshEditorRobot(...a); }
function renderHangar(...a) { return GM.workshop.renderHangar(...a); }
function renderWeaponEditor(...a) { return GM.workshop.renderWeaponEditor(...a); }
// ---------------------------------------------------------------- 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 = `
${t('click_start')}
${CREDITS}
${CREDITS}
${t('local_profiles')}
${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_text')}
${t('local_note')}
`, { bg: 'bg_title.jpg' }); $('bBack').onclick = () => { SFX.click(); showTitle(); }; $('fPriv').onclick = () => { SFX.click(); showLegal(showRegister, 'privacy'); }; $('bGo').onclick = async () => { if (!$('fConsent').checked) { SFX.deny(); $('fErr').textContent = t('consent_required'); return; } 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()); }); if (gameMode === 'online') onlinePull(); else cloudPull(); } // campaign + registered account: fetch the cloud copy; take it if newer, else push the local copy up function cloudPull() { const a = fbAcc(); if (!a || gameMode !== 'campaign') return; const m = gameMode; cloud.pull().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(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 if (save.mseed == null) save.mseed = (Math.random() * 1e9) | 0; // stable per-save mission seed const rewardPaint = c => (RC.PAINT_REWARDS || []).includes(c); if (!Array.isArray(save.unlockedPaints)) save.unlockedPaints = RC.PAINTS.filter(c => !rewardPaint(c)); // all but the reward colours if (!Array.isArray(save.unlockedSchemes)) save.unlockedSchemes = RC.SCHEMES.map((_, i) => i); // all schemes free // 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); } function signOut() { persist(); cloudFlush(); // push now, while we still have the auth token if (lobby) { lobby.leave(); lobbyRows = []; } 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(`${who ? t('logged_in_as', { name: esc(who.name) }) + (who.email ? `
${esc(who.email)}` : '') : t('guest_text')}
🏆 ${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('league_text')}
${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 ? `${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 myBuild = online ? online.myBuild : save.build; // live: exactly the robot the server fights with const stA = RC.stats(myBuild), 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 ? online.arena : 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); const count = online ? Math.max(0, +online.countdown || 0) : 3.5; F = { s, opp, training, exhibition: !!exhibition, online, tour: !!tour, brain: online ? null : RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count, beat: Math.ceil(count) + 1, acc: [0, 0], accT: 0, banner: null, ended: false, oppAway: false }; if (online) { netStats.reset(); F.nf = RC.NetFight({ net, seat: online.seat, stats: netStats }); } // the server runs the fight, we show it // 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, [myBuild, opp.build], [paintObj(), oppPaint(opp)]); if (view.setComfort) view.setComfort(settings.comfort); 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(); 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 }; } function update(dt) { fx.update(dt); introTick(); if (mode !== 'fight' || !F) return; if (F.count > 0) { F.count -= dt; const n = Math.ceil(F.count); if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } } return; } const s = F.s, [me, en] = s.robots; let events; if (F.online) { events = F.nf.frame(s, playerInput(), dt); if (F.nf.oppAway !== F.oppAway) { F.oppAway = F.nf.oppAway; banner(t(F.oppAway ? 'peer_lost' : 'peer_back'), F.oppAway ? '#ff4a3a' : '#6dff9e', 2.2); } // no word from the server for 20 s (and no result yet - a hidden tab may simply have slept through the end) if (!F.serverEnd && F.nf.silentFor > 20 && !F.ended) { F.ended = true; onlineFightLost(); return; } } 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); } // live: the fight is over when the server says so (match.end carries the booked rewards) if (s.result && s.endIn <= 0 && !F.ended && (!F.online || F.serverEnd)) { 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 => `${why}
${champion ? `${t('champion_text')}
` : ''}${t('training_note')}
` : ''}${esc(F.opp.name)}
${t('no_pause_online')}
`); $('bGo').onclick = () => { SFX.click(); hideOverlay(); }; $('bGiveUp').onclick = () => { SFX.click(); hideOverlay(); if (lobby) lobby.leaveMatch(); }; return; } if (mode === 'fight') { mode = 'pause'; loop.pause(); card(`${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_text')}
`); $('rNow').onclick = () => location.reload(); $('rSkip').onclick = () => { LIVE.needsReload = false; SFX.click(); startGate(startIntro); }; } else if (!view) { card(`${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 === 'missions') { if (gameMode !== 'campaign') switchMode('campaign'); if (DEV.has('mreset')) save.missions = null; showMissions(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=