/* Robot Clash - game frame: intro, title, accounts, settings, shop, league, fight, result, audio, scores.
Logic lives in parts.js / robot.js / combat.js / ai.js (no DOM), the 3D view in render3d.js,
the shop panel in shop.js, accounts in profiles.js. Texts: lang.js via t('key').
Credits line stays on the title screen. */
(function () {
'use strict';
const $ = Kit.$;
const W = 960, H = 540; // design size of the stage
const ID = 'robotclash'; // localStorage prefix
// Paste the Firebase Realtime Database URL here to switch the online fame ranking on
// (docs/firebase/README.md). Empty = offline.
const DB_URL = '';
// Credits (standard for every game): shown on the title screen, links open in the normal browser
const DISCORD = 'https://discord.gg/Ej4JPmCZva';
const CREDITS = `© 2026 Michael Media · Discord`;
// ---------------------------------------------------------------- services
const L = Kit.i18n(window.LANG, { prefix: ID });
const t = L.t;
const store = Kit.store(ID);
const settings = Object.assign({ gfx: 'high', intro: true }, store.get('settings', {}));
const saveSettings = () => store.set('settings', settings);
const accounts = RC.Accounts(ID);
const newSave = () => ({
money: 400, fame: 0, best: 0, season: 1, beaten: 0, wins: 0, losses: 0, games: 0,
owned: Object.values(RC.STARTER).filter(Boolean), build: Object.assign({}, RC.STARTER),
paint: { body: 0xff7a1a, accent: 0x15171b }, robotName: 'Clank', tutorialSeen: false,
});
let slot = null, save = null; // per account, set by enterAccount()
const persist = () => { if (slot && save) slot.save(save); };
const audio = Kit.createAudio({
prefix: ID,
files: ['sfx_click', 'sfx_buy', 'sfx_hit', 'sfx_saw', 'sfx_boom', 'sfx_win', 'sfx_lose', 'music_title', 'music_garage', 'music_fight'],
throttle: { sfx_hit: 80, sfx_saw: 120, sfx_boom: 100 },
});
const scores = Kit.scores({ url: DB_URL });
const DEV = new URLSearchParams(location.search);
const fx = Kit.fx();
const input = Kit.input({
keys: {
ArrowUp: 'up', w: 'up', ArrowDown: 'down', s: 'down', ArrowLeft: 'left', a: 'left', ArrowRight: 'right', d: 'right',
' ': 'fire', Shift: 'fire2', e: 'fire2', p: 'pause', Escape: 'pause', m: 'mute', Enter: 'ok',
},
onPress(a) {
if (mode === 'intro') { skipIntro(); return; }
if (a === 'pause') togglePause();
else if (a === 'mute') toggleMute();
else if (a === 'ok') { const b = overlay.querySelector('button.primary'); if (b && !b.disabled) b.click(); }
},
});
// ---------------------------------------------------------------- sound (ComfyGen clips + synth fallback)
const last = {};
const every = (k, ms) => { const n = performance.now(); if (last[k] && n - last[k] < ms) return false; last[k] = n; return true; };
const SFX = {
click() { audio.sfx('sfx_click'); audio.tone(660, 0.04, 'square', 0.05); },
buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.08); },
deny() { audio.tone(160, 0.15, 'square', 0.12, -40); },
beep(hi) { audio.tone(hi ? 1046 : 523, hi ? 0.4 : 0.15, 'square', 0.14); },
clunk() { audio.noise(0.25, 0.5, 260); audio.tone(70, 0.3, 'sine', 0.4, -20); },
win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09, 'square', 0.1); },
lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.1); },
event(e) {
switch (e.type) {
case 'bump': if (every('bump', 90)) audio.noise(0.12, Math.min(0.4, e.speed / 10), 700); break;
case 'wall': if (every('wall', 120)) { audio.sfx('sfx_hit'); audio.noise(0.2, 0.3, 1600); } break;
case 'flip': audio.tone(200, 0.2, 'square', 0.13, 500); audio.noise(0.12, 0.25, 3000); break;
case 'swing': audio.noise(0.15, 0.12, 900); break;
case 'smash': audio.sfx('sfx_hit'); audio.noise(0.25, 0.45, 650); audio.tone(95, 0.25, 'sine', 0.4, -45); break;
case 'spinhit': audio.sfx('sfx_hit'); audio.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); break;
case 'sparks': if (every('grind', 70)) audio.noise(0.06, 0.1, 5200); break;
case 'boom': audio.sfx('sfx_boom'); audio.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break;
case 'ko': audio.sfx('sfx_boom'); audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); break;
case 'launch': audio.noise(0.3, 0.18, 2200); audio.tone(300, 0.3, 'sawtooth', 0.07, 600); break;
case 'press_warn': for (let k = 0; k < 3; k++) audio.tone(880, 0.1, 'square', 0.1, 0, k * 0.2); break;
case 'press': audio.sfx('sfx_hit'); audio.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); break;
case 'crane': audio.tone(140, 0.6, 'sawtooth', 0.07, 140); break;
case 'drop': case 'land': audio.noise(0.22, 0.35, 500); break;
case 'pit_open': for (let k = 0; k < 3; k++) audio.tone(700, 0.3, 'square', 0.12, -250, k * 0.4); break;
case 'pit': audio.tone(420, 1.2, 'sawtooth', 0.14, -360); break;
case 'grab': audio.tone(150, 0.25, 'square', 0.12, -60); break;
case 'boost': audio.noise(0.4, 0.25, 1800); break;
}
},
loops(s) { // continuous weapons as short repeated bursts
for (const r of s.robots) {
if (r.sawOn && every('saw' + r.i, 110)) { audio.sfx('sfx_saw'); audio.tone(900 + Math.random() * 60, 0.1, 'sawtooth', 0.03); }
if (r.flameOn && every('fl' + r.i, 120)) audio.noise(0.14, 0.12, 900);
if (r.gunOn && every('gun' + r.i, 70)) audio.noise(0.04, 0.16, 3500);
if (r.spin > 0.2 && every('spin' + r.i, 100)) audio.tone(120 + r.spin * 260, 0.1, 'sawtooth', 0.03 * r.spin);
}
},
};
// ---------------------------------------------------------------- view
const cv = $('cv');
let ctx = cv.getContext('2d');
let view = null;
try { view = RC.Render($('gl'), W, H); view.setQuality(settings.gfx); } catch (err) { console.error(err); }
Kit.fit($('app'), { canvases: [[cv, W, H]], onFit(sc) { ctx = cv.getContext('2d'); if (view) view.resize(sc); } });
Kit.host.dragArea(document.body);
const hex = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
const img = name => Kit.asset('assets/Sprites/' + name);
function backdrop(name) { $('bgimg').style.backgroundImage = name ? `url("${img(name)}")` : 'none'; }
$('icoMoney').innerHTML = `
`;
$('icoFame').innerHTML = `
`;
const shop = RC.Shop({
t, getSave: () => save, onSave: persist,
onBuild: () => view.showGarage(save.build, paintObj()),
onPaint: () => view.setPaint(paintObj()),
sfx: SFX,
});
// own artwork on the robot (painter.js): transparent 512x256 layer, saved per account as PNG data
const layer = document.createElement('canvas');
layer.width = 512; layer.height = 256;
const paintObj = () => ({ body: save.paint.body, accent: save.paint.accent, layer, drawn: painter.isOpen || !!save.paint.drawn });
const painter = RC.Painter({
t, layer, view, sfx: SFX, getPaint: paintObj,
onLive: () => view.setPaint(paintObj()),
onDone: () => {
const art = painter.hasArt();
save.paint.decal = art ? layer.toDataURL('image/png') : null; save.paint.drawn = art;
persist(); view.showGarage(save.build, paintObj());
},
onCancel: () => view.showGarage(save.build, paintObj()),
});
$('bPaint').onclick = () => { SFX.click(); painter.open(); view.showGarage(save.build, paintObj()); };
// drag on the robot turns it
let drag = null;
$('gl').addEventListener('pointerdown', e => { if (mode === 'garage') { drag = e.clientX; $('gl').setPointerCapture(e.pointerId); } });
$('gl').addEventListener('pointermove', e => { if (drag != null) { view.turn(e.clientX - drag); drag = e.clientX; } });
$('gl').addEventListener('pointerup', () => { drag = null; });
// ---------------------------------------------------------------- state
let mode = 'intro'; // intro | title | account | garage | league | fight | pause | result
let F = null; // current fight
const show = (id, on) => $(id).classList.toggle('hide', !on);
const overlay = $('overlay');
function card(html, opt = {}) {
overlay.innerHTML = `
${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(); }; $('bGo').onclick = async () => { if ($('fPass').value !== $('fPass2').value) { SFX.deny(); $('fErr').textContent = t('e_pass_match'); return; } const r = await accounts.register($('fName').value, $('fPass').value); if (!r.ok) { SFX.deny(); $('fErr').textContent = t('e_' + r.error); return; } SFX.buy(); enterAccount(true); }; formKeys(); setTimeout(() => $('fName').focus(), 50); } // Enter in a form = primary button; typing never reaches the game keys function formKeys() { overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Enter') { const b = overlay.querySelector('button.primary'); if (b) b.click(); } })); } function enterAccount(fresh) { slot = Kit.saveSlot(accounts.saveKey(), newSave); save = slot.load(); repairSave(); RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); if (fresh && accounts.current && !accounts.current.guest) save.robotName = accounts.current.name.slice(0, 18); persist(); hud(); shop.reset(); if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); showHelp(openGarage); } else openGarage(); } // saves from older versions: missing parts, invalid ids function repairSave() { save.owned = (save.owned || []).filter(id => RC.PARTS[id]); for (const sl of RC.SLOTS) { if (save.build[sl] && !RC.PARTS[save.build[sl]]) save.build[sl] = null; if (save.build[sl] && !save.owned.includes(save.build[sl])) save.owned.push(save.build[sl]); } for (const sl of Object.keys(RC.REQUIRED)) if (!save.build[sl]) { save.build[sl] = RC.STARTER[sl]; if (!save.owned.includes(RC.STARTER[sl])) save.owned.push(RC.STARTER[sl]); } save.beaten = Kit.clamp(save.beaten | 0, 0, RC.LEAGUE.length - 1); } function logout() { persist(); accounts.logout(); save = null; slot = null; F = null; hud(); startIntroOrTitle(); } function startIntroOrTitle() { if (view) { const a = RC.LEAGUE[7], b = RC.LEAGUE[4]; view.showIntro([a.build, b.build], [a.paint, b.paint]); view.skipIntro(); } showTitle(); } $('hUser').onclick = () => { if (!accounts.current || mode === 'fight' || mode === 'pause') return; SFX.click(); const back = currentBack(); card(`${accounts.current.guest ? t('guest_text') : t('logged_in_as', { name: esc(accounts.current.name) })}
`); $('bOut').onclick = () => { SFX.click(); logout(); }; $('bBack').onclick = () => { SFX.click(); back(); }; }; function currentBack() { return mode === 'garage' ? openGarage : mode === 'league' ? showLeague : mode === 'result' ? openGarage : mode === 'title' ? showTitle : save ? openGarage : showTitle; } // ---------------------------------------------------------------- settings / help / ranking function showSettings(back) { const prev = mode; const seg = (id, val, opts) => `${t('help_text')}
${keysHtml()}${t('help_arena')}
`, { bg: 'bg_title.jpg' }); $('bOk').onclick = () => { SFX.click(); back(); }; } function showRanking(back) { card(`${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(); }; } $('bSettings').onclick = () => { if (mode === 'fight') togglePause(); if (mode === 'intro') skipIntro(); SFX.click(); const back = mode === 'pause' ? () => { mode = 'fight'; togglePause(); } : currentBack(); showSettings(back); }; function boardHtml() { return scores.enabled ? `${t('league_text')}
${t('style_' + opp.style)}
`, { wide: true, bg: 'bg_title.jpg' }); $('bBack').onclick = () => { SFX.click(); showLeague(); }; $('bGo').onclick = () => { SFX.click(); startFight(opp, false); }; } // ---------------------------------------------------------------- fight function startFight(opp, training) { hideOverlay(); const stA = RC.stats(save.build), stB = RC.stats(opp.build); const seed = (Date.now() & 0xffff) + save.games * 31; const s = RC.Combat.create({ robots: [stA, stB], seed, names: [save.robotName, opp.name] }); const skill = Math.min(1, opp.skill + (save.season - 1) * 0.12); F = { s, opp, training, brain: RC.AI.create({ style: opp.style, skill, seed: seed + 5 }), count: 3.5, beat: 4, acc: [0, 0], accT: 0, banner: null, ended: false }; // dev: ?auto = AI drives the player too, ?ff=30 = fast-forward 30 s (screenshots, balancing) if (DEV.has('auto')) F.auto = RC.AI.create({ style: 'brawler', skill: 0.7, seed: seed + 11 }); if (DEV.has('ff')) { F.count = 0; F.beat = 0; const ai2 = F.auto || RC.AI.create({ style: 'brawler', skill: 0.5, seed }); for (let i = 0; i < (+DEV.get('ff') || 20) * 60 && !s.result; i++) { RC.Combat.step(s, 1 / 60, [ai2.think(s, s.robots[0], s.robots[1], 1 / 60), F.brain.think(s, s.robots[1], s.robots[0], 1 / 60)]); s.events.length = 0; } } view.showArena(s, [save.build, opp.build], [paintObj(), opp.paint]); $('fN0').textContent = save.robotName; $('fN1').textContent = opp.name; $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(opp.build); $('fH0').style.background = hex(save.paint.body); $('fH1').style.background = hex(opp.paint.body); fx.clear(); setScreen('fight'); audio.music('music_fight'); fightHud(); } function pad() { const gp = navigator.getGamepads ? Array.from(navigator.getGamepads()).find(Boolean) : null; if (!gp) return null; const dz = v => (Math.abs(v) < 0.18 ? 0 : v); const b = i => !!(gp.buttons[i] && gp.buttons[i].pressed); if (b(9) && every('gpStart', 400)) togglePause(); return { throttle: -dz(gp.axes[1] || 0) + (b(12) ? 1 : 0) - (b(13) ? 1 : 0), turn: dz(gp.axes[0] || 0) + (b(15) ? 1 : 0) - (b(14) ? 1 : 0), fire: b(0) || b(7), fire2: b(1) || b(2) || b(6) }; } function playerInput() { const k = { throttle: (input.down('up') ? 1 : 0) - (input.down('down') ? 1 : 0), turn: (input.down('right') ? 1 : 0) - (input.down('left') ? 1 : 0), fire: input.down('fire'), fire2: input.down('fire2'), }; const g = pad(); if (g) { k.throttle = Kit.clamp(k.throttle + g.throttle, -1, 1); k.turn = Kit.clamp(k.turn + g.turn, -1, 1); k.fire = k.fire || g.fire; k.fire2 = k.fire2 || g.fire2; } return k; } function banner(text, color, time = 1.4) { F.banner = { text, color: color || '#ff7a1a', t: time, max: time }; } function update(dt) { fx.update(dt); introTick(); if (mode !== 'fight' || !F) return; if (F.count > 0) { F.count -= dt; const n = Math.ceil(F.count); if (n < F.beat) { F.beat = n; if (n > 0) { SFX.beep(false); banner(String(n), '#fff', 0.9); } else { SFX.beep(true); banner(t('fight_go'), '#ff7a1a', 1.1); } } return; } const s = F.s, [me, en] = s.robots; RC.Combat.step(s, dt, [F.auto ? F.auto.think(s, me, en, dt) : playerInput(), F.brain.think(s, en, me, dt)]); for (const e of s.events) { SFX.event(e); if (e.type === 'dmg') F.acc[e.who] += e.amount; else if (e.type === 'pit_open') banner(t('pit_open'), '#ff4a3a', 2); else if (e.type === 'pit') banner(t('into_pit'), '#ff4a3a', 2.2); else if (e.type === 'ko') banner(t('knockout'), '#ff7a1a', 2.2); } view.events(s.events); s.events.length = 0; SFX.loops(s); // damage numbers, grouped F.accT -= dt; if (F.accT <= 0) { F.accT = 0.3; for (let i = 0; i < 2; i++) if (F.acc[i] >= 1) { const r = s.robots[i], p = view.project(r.x, r.y + 1.1, r.z); fx.float(p.x, p.y, '-' + Math.round(F.acc[i]), i === 0 ? '#ff6a5a' : '#ffd060', 16 + Math.min(14, F.acc[i] / 3)); F.acc[i] = 0; } } if (s.left <= 10 && !s.result && Math.ceil(s.left) !== F.tick) { F.tick = Math.ceil(s.left); audio.tone(1200, 0.05, 'square', 0.06); } if (s.result && s.endIn <= 0 && !F.ended) { F.ended = true; endFight(); } } function fightHud() { if (!F) return; const s = F.s; for (let i = 0; i < 2; i++) $('fH' + i).style.width = (s.robots[i].hp / s.robots[i].maxHp * 100).toFixed(1) + '%'; const sec = Math.ceil(s.left); $('fTime').textContent = `${Math.floor(sec / 60)}:${String(sec % 60).padStart(2, '0')}`; $('fTime').classList.toggle('low', sec <= 10); const me = s.robots[0]; let st = ''; if (me.lifted) st = t('st_lifted'); else if (me.grabbedBy !== null) st = t('st_grabbed'); else if (me.flipped > 0 && !me.st.invertible) st = t('st_flipped'); else if (me.stun > 0) st = t('st_stunned'); else if (s.pitAlarm) st = t('pit_is_open'); else if (s.left - RC.ARENA.pitOpensAt < 10 && s.left > RC.ARENA.pitOpensAt) st = t('pit_soon'); $('fState').textContent = st; } function endFight() { const s = F.s, res = s.result, opp = F.opp, idx = RC.LEAGUE.indexOf(opp); const won = res.winner === 0, me = s.robots[0]; const lines = []; let money = 0, fame = 0, champion = false; if (!F.training) { const prize = Math.round(opp.prize * seasonMul()); save.games++; if (won) { const bonus = res.reason === 'pit' ? 0.3 : res.reason === 'ko' ? 0.2 : 0; money += prize; lines.push([t('r_prize'), prize]); if (bonus) { const b = Math.round(prize * bonus); money += b; lines.push([t('r_bonus_' + res.reason), b]); } fame = (idx + 1) * 50 * save.season + (res.reason === 'pit' ? 40 : res.reason === 'ko' ? 25 : 0); save.wins++; if (idx === save.beaten) save.beaten++; if (save.beaten >= RC.LEAGUE.length) { champion = true; const cb = 1500 * save.season; money += cb; fame += 500 * save.season; lines.push([t('r_champion'), cb]); save.season++; save.beaten = 0; } } else { const ap = Math.round(prize * 0.2); money += ap; lines.push([t('r_appearance'), ap]); save.losses++; } const repair = Math.round((1 - me.hp / me.maxHp) * me.st.value * 0.12 + (res.reason === 'pit' && !won ? me.st.value * 0.05 : 0)); const paid = Math.min(repair, save.money + money); if (paid) lines.push([t('r_repair'), -paid]); money -= paid; save.money += money; save.fame += fame; persist(); } hud(); (won ? SFX.win : SFX.lose)(); const title = res.winner === -1 ? t('draw') : won ? t('victory') : t('defeat'); const why = t('why_' + res.reason + (res.winner === -1 ? '_draw' : won ? '_win' : '_lose'), { name: opp.name }); const rows = lines.map(([k, v]) => `${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(`${why}
${champion ? `${t('champion_text')}
` : ''}${t('training_note')}
` : ''}${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(); slot = Kit.saveSlot(accounts.saveKey(), newSave); save = slot.load(); repairSave(); hud(); RC.layerFromData(layer, save.paint.decal, () => { if (mode === 'garage') view.showGarage(save.build, paintObj()); }); if (DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true); else openGarage(); if (DEV.has('paint')) { // dev: open the paint booth with a test drawing const c = layer.getContext('2d'); c.fillStyle = '#15171b'; c.fillRect(0, 100, 256, 56); c.fillStyle = '#f2c230'; c.font = 'bold 70px sans-serif'; c.fillText('★ 7', 300, 170); c.strokeStyle = '#00e5ff'; c.lineWidth = 14; c.beginPath(); c.moveTo(270, 220); c.lineTo(500, 200); c.stroke(); painter.open(); view.showGarage(save.build, paintObj()); } } else if (DEV.has('title')) startIntroOrTitle(); else startIntro(); })();