update images and audio

This commit is contained in:
2026-11-13 01:02:55 +01:00
parent 9bc39faffb
commit 819ee0a5c3
78 changed files with 1301 additions and 336 deletions

View File

@@ -1,6 +1,7 @@
/* Robot Clash - game frame: menu, workshop, league ladder, fight, result, saving, audio, scores.
/* 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 workshop panel in garage.js. Texts: lang.js via t('key'). Credits line stays in the menu. */
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.$;
@@ -11,23 +12,28 @@
// (docs/firebase/README.md). Empty = offline.
const DB_URL = '';
// Credits (standard for every game): shown in the menu, links open in the normal browser
// Credits (standard for every game): shown on the title screen, links open in the normal browser
const DISCORD = 'https://discord.gg/Ej4JPmCZva';
const CREDITS = `© 2026 Michael Media · <a href="${DISCORD}" target="_blank" rel="noopener">Discord</a>`;
// ---------------------------------------------------------------- services
const L = Kit.i18n(window.LANG, { prefix: ID });
const t = L.t;
const slot = Kit.saveSlot(ID + '.save', () => ({
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', name: '', tutorialSeen: false,
}));
let save = slot.load();
const persist = () => slot.save(save);
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_win', 'sfx_lose', 'music_garage', 'music_fight'],
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);
@@ -39,36 +45,38 @@
' ': '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 (synth until ComfyGen clips exist)
// ---------------------------------------------------------------- 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.05, 'square', 0.08); },
buy() { audio.sfx('sfx_buy'); audio.arp([523, 784, 1046], 0.05, 'square', 0.1); },
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); },
win() { audio.sfx('sfx_win'); audio.arp([523, 659, 784, 1046, 1318], 0.09); },
lose() { audio.sfx('sfx_lose'); audio.arp([392, 330, 262, 196], 0.14, 'sawtooth', 0.12); },
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.noise(0.2, 0.35, 1600); audio.tone(190, 0.15, 'sawtooth', 0.1, -90); } 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.noise(0.3, 0.5, 2600); audio.tone(1200, 0.12, 'sawtooth', 0.1, -800); 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.noise(0.6, 0.5, 420); audio.tone(70, 0.5, 'sine', 0.5, -40); break;
case 'ko': audio.noise(1.0, 0.6, 350); audio.tone(55, 0.9, 'sine', 0.5, -25); 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.noise(0.5, 0.65, 300); audio.tone(55, 0.5, 'sine', 0.6, -20); 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;
@@ -79,7 +87,7 @@
},
loops(s) { // continuous weapons as short repeated bursts
for (const r of s.robots) {
if (r.sawOn && every('saw' + r.i, 110)) audio.tone(900 + Math.random() * 60, 0.1, 'sawtooth', 0.035);
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);
@@ -91,49 +99,268 @@
const cv = $('cv');
let ctx = cv.getContext('2d');
let view = null;
try { view = RC.Render($('gl'), W, H); } catch (err) { console.error(err); }
try { view = RC.Render($('gl'), W, H); view.setQuality(settings.gfx); } catch (err) { console.error(err); }
Kit.fit($('app'), { canvases: [[cv, W, H]], onFit(sc) { ctx = cv.getContext('2d'); if (view) view.resize(sc); } });
Kit.host.dragArea(document.body);
const hex = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
const img = name => Kit.asset('assets/Sprites/' + name);
function backdrop(name) { $('bgimg').style.backgroundImage = name ? `url("${img(name)}")` : 'none'; }
$('icoMoney').innerHTML = `<img src="${img('ico_credits.png')}" alt="" onerror="this.classList.add('missing')">`;
$('icoFame').innerHTML = `<img src="${img('ico_fame.png')}" alt="" onerror="this.classList.add('missing')">`;
const garage = RC.Garage({
const shop = RC.Shop({
t, getSave: () => save, onSave: persist,
onBuild: () => { view.showGarage(save.build, save.paint); garageTitle(); },
onPaint: () => { view.showGarage(save.build, save.paint); garageTitle(); },
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 = 'menu'; // menu | garage | league | fight | pause | result
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) { overlay.innerHTML = `<div class="card">${html}</div>`; overlay.classList.remove('hide'); }
function hideOverlay() { overlay.classList.add('hide'); overlay.innerHTML = ''; }
function card(html, opt = {}) {
overlay.innerHTML = `<div class="card" style="${opt.wide ? 'min-width:720px' : ''}">${html}</div>`;
overlay.classList.remove('hide'); overlay.classList.toggle('clear', !!opt.clear);
overlay.style.backgroundImage = opt.bg ? `linear-gradient(rgba(5,6,10,.55), rgba(5,6,10,.75)), url("${img(opt.bg)}")` : '';
}
function hideOverlay() { overlay.classList.add('hide'); overlay.innerHTML = ''; overlay.style.backgroundImage = ''; }
const esc = s => String(s).replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]));
const seasonMul = () => 1 + (save.season - 1) * 0.5;
const weaponName = b => (b.weapon ? RC.PARTS[b.weapon].name : t('unarmed')) + (b.tower ? ' + ' + RC.PARTS[b.tower].name : '');
const playerName = () => (accounts.current && !accounts.current.guest ? accounts.current.name : save ? save.robotName : '');
function hud() {
$('hMoney').textContent = Kit.fmt(save.money);
$('hFame').textContent = Kit.fmt(save.fame);
$('hLeague').textContent = t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length });
$('hMoney').textContent = save ? Kit.fmt(save.money) : '–';
$('hFame').textContent = save ? Kit.fmt(save.fame) : '–';
$('hLeague').textContent = save ? t('league_chip', { s: save.season, n: save.beaten, m: RC.LEAGUE.length }) : '–';
$('hUser').textContent = accounts.current ? (accounts.current.guest ? '👤 ' + t('guest') : '👤 ' + accounts.current.name) : '👤 –';
$('bMute').textContent = audio.muted ? t('sound_off') : t('sound_on');
}
function garageTitle() {
$('gName').textContent = save.robotName;
$('gSub').textContent = weaponName(save.build);
}
function setScreen(m) {
if (m !== 'garage' && painter.isOpen) painter.close();
mode = m;
document.body.classList.toggle('fighting', m === 'fight' || m === 'pause');
show('garage', m === 'garage');
show('gTitle', m === 'garage');
show('shop', m === 'garage');
show('fightHud', m === 'fight' || m === 'pause' || m === 'result');
backdrop(m === 'garage' ? 'bg_workshop.jpg' : null);
}
// ---------------------------------------------------------------- menu
function boardHtml() { return scores.enabled ? `<h2 style="margin-top:14px;font-size:18px">${t('ranking')}</h2><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
// ---------------------------------------------------------------- intro + title
let introCue = 0;
function startIntro() {
setScreen('intro');
hideOverlay();
if (!view) { showTitle(); return; }
const a = RC.LEAGUE[7], b = RC.LEAGUE[4];
view.showIntro([a.build, b.build], [a.paint, b.paint]);
introCue = 0;
audio.music('music_title');
if (!settings.intro) view.skipIntro();
}
function skipIntro() { if (view) view.skipIntro(); }
stageClick(() => { if (mode === 'intro') skipIntro(); });
function stageClick(fn) { $('stage').addEventListener('pointerdown', fn); }
function introTick() {
if (mode !== 'intro' || !view) return;
const it = view.introTime;
for (const [at, f] of [[1.2, SFX.clunk], [1.5, SFX.clunk], [1.62, SFX.clunk], [4.25, SFX.clunk], [4.6, SFX.clunk]]) {
if (introCue < at && it >= at) f();
}
introCue = it;
if (it >= RC.INTRO_END) showTitle();
}
function showTitle() {
setScreen('title');
audio.music('music_title');
const acc = accounts.current && !accounts.current.guest ? accounts.current : null;
const btns = acc
? `<button class="primary" id="bPlay">${t('play_as', { name: esc(acc.name) })}</button><button id="bSwitch">${t('switch_account')}</button>`
: `<button class="primary" id="bLogin">${t('login')}</button><button id="bReg">${t('register')}</button><button id="bGuest">${t('play_guest')}</button>`;
overlay.innerHTML = `<div class="title"><div class="big">ROBOT CLASH</div><div class="tag">${t('menu_text')}</div>
<div class="row">${btns}</div>
<div class="row"><button id="bSet">⚙ ${t('settings')}</button><button id="bHelp">${t('how_to')}</button>
<button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>${scores.enabled ? `<button id="bRank">🏆 ${t('ranking')}</button>` : ''}</div>
<p class="credits">${CREDITS}</p></div>`;
overlay.classList.remove('hide'); overlay.classList.add('clear'); overlay.style.backgroundImage = '';
const on = (id, f) => { const el = $(id); if (el) el.onclick = () => { SFX.click(); f(); }; };
on('bPlay', () => enterAccount());
on('bSwitch', () => { accounts.logout(); hud(); showLogin(); });
on('bLogin', () => showLogin());
on('bReg', () => showRegister());
on('bGuest', () => { accounts.guest(); enterAccount(); });
on('bSet', () => showSettings(showTitle));
on('bHelp', () => showHelp(showTitle));
on('bLang', () => L.next());
on('bRank', () => showRanking(showTitle));
hud();
}
// ---------------------------------------------------------------- accounts
function showLogin(errKey) {
setScreen('account');
const profs = accounts.list();
card(`<h2>${t('login')}</h2>
${profs.length ? `<p class="muted">${t('local_profiles')}</p><div class="profiles">${profs.map(p => `<button data-n="${esc(p.name)}">${esc(p.name)}</button>`).join('')}</div>` : ''}
<div class="form"><label>${t('f_name')}</label><input type="text" id="fName" maxlength="18" autocomplete="username">
<label>${t('f_pass')}</label><input type="password" id="fPass" autocomplete="current-password">
<label class="chk"><input type="checkbox" id="fRem" checked> ${t('f_remember')}</label></div>
<div class="err" id="fErr">${errKey ? t(errKey) : ''}</div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('login')}</button></div>
<p class="muted">${t('no_account')} <button class="link" id="bToReg">${t('register')}</button></p>
<p class="muted" style="font-size:11px">${t('local_note')}</p>`, { bg: 'bg_title.jpg' });
overlay.querySelectorAll('.profiles button').forEach(b => { b.onclick = () => { $('fName').value = b.dataset.n; $('fPass').focus(); }; });
$('bBack').onclick = () => { SFX.click(); showTitle(); };
$('bToReg').onclick = () => { SFX.click(); showRegister(); };
$('bGo').onclick = async () => {
const r = await accounts.login($('fName').value, $('fPass').value, $('fRem').checked);
if (!r.ok) { SFX.deny(); $('fErr').textContent = t('e_' + r.error); return; }
SFX.click(); enterAccount();
};
formKeys();
setTimeout(() => $(profs.length ? 'fPass' : 'fName').focus(), 50);
}
function showRegister() {
setScreen('account');
card(`<h2>${t('register')}</h2><p>${t('register_text')}</p>
<div class="form"><label>${t('f_name')}</label><input type="text" id="fName" maxlength="18" autocomplete="username">
<label>${t('f_pass')}</label><input type="password" id="fPass" autocomplete="new-password">
<label>${t('f_pass2')}</label><input type="password" id="fPass2" autocomplete="new-password"></div>
<div class="err" id="fErr"></div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('register_go')}</button></div>
<p class="muted" style="font-size:11px">${t('local_note')}</p>`, { bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showTitle(); };
$('bGo').onclick = async () => {
if ($('fPass').value !== $('fPass2').value) { SFX.deny(); $('fErr').textContent = t('e_pass_match'); return; }
const r = await accounts.register($('fName').value, $('fPass').value);
if (!r.ok) { SFX.deny(); $('fErr').textContent = t('e_' + r.error); return; }
SFX.buy(); enterAccount(true);
};
formKeys();
setTimeout(() => $('fName').focus(), 50);
}
// Enter in a form = primary button; typing never reaches the game keys
function formKeys() {
overlay.querySelectorAll('input').forEach(el => el.addEventListener('keydown', e => {
e.stopPropagation();
if (e.key === 'Enter') { const b = overlay.querySelector('button.primary'); if (b) b.click(); }
}));
}
function 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(`<h2>${t('account')}</h2><p>${accounts.current.guest ? t('guest_text') : t('logged_in_as', { name: esc(accounts.current.name) })}</p>
<div class="row"><button id="bOut">${accounts.current.guest ? t('to_title') : t('logout')}</button><button class="primary" id="bBack">${t('back')}</button></div>`);
$('bOut').onclick = () => { SFX.click(); logout(); };
$('bBack').onclick = () => { SFX.click(); back(); };
};
function currentBack() { return mode === 'garage' ? openGarage : mode === 'league' ? showLeague : mode === 'result' ? openGarage : mode === 'title' ? showTitle : save ? openGarage : showTitle; }
// ---------------------------------------------------------------- settings / help / ranking
function showSettings(back) {
const prev = mode;
const seg = (id, val, opts) => `<div class="seg" id="${id}">${opts.map(([v, label]) => `<button data-v="${v}" class="${v === val ? 'on' : ''}">${label}</button>`).join('')}</div>`;
card(`<h2>${t('settings')}</h2><div class="set">
<span>${t('s_lang')}</span>${seg('sLang', L.lang, L.langs.map(l => [l, window.LANG[l].lang_self]))}
<span>${t('s_music')}</span><input type="range" id="sMusic" min="0" max="1" step="0.05" value="${audio.musicVol}">
<span>${t('s_sfx')}</span><input type="range" id="sSfx" min="0" max="1" step="0.05" value="${audio.sfxVol}">
<span>${t('s_mute')}</span>${seg('sMute', audio.muted ? '1' : '0', [['0', t('on')], ['1', t('off')]])}
<span>${t('s_gfx')}</span>${seg('sGfx', settings.gfx, [['low', t('gfx_low')], ['medium', t('gfx_medium')], ['high', t('gfx_high')]])}
<span>${t('s_intro')}</span>${seg('sIntro', settings.intro ? '1' : '0', [['1', t('on')], ['0', t('off')]])}
<span>${t('s_screen')}</span><div><button id="sFull">${t('win_full')}</button></div>
</div>
<h3>${t('s_controls')}</h3>${keysHtml()}
${save ? `<h3>${t('s_career')}</h3><div style="text-align:left"><button id="sReset">${t('reset')}</button></div>` : ''}
<div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { wide: true, clear: prev === 'title' || prev === 'intro' });
const segOn = (id, f) => $(id).querySelectorAll('button').forEach(b => { b.onclick = () => { SFX.click(); f(b.dataset.v); $(id).querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); }; });
segOn('sLang', v => { L.set(v); showSettings(back); });
segOn('sMute', v => { if ((v === '1') !== audio.muted) audio.toggleMute(); hud(); });
segOn('sGfx', v => { settings.gfx = v; saveSettings(); if (view) view.setQuality(v); });
segOn('sIntro', v => { settings.intro = v === '1'; saveSettings(); });
$('sMusic').oninput = e => audio.setVolume(+e.target.value, audio.sfxVol);
$('sSfx').oninput = e => audio.setVolume(audio.musicVol, +e.target.value);
$('sSfx').onchange = () => SFX.click();
$('sFull').onclick = () => { SFX.click(); Kit.host.fullscreen(); };
if ($('sReset')) $('sReset').onclick = () => { SFX.click(); confirmReset(() => showSettings(back)); };
$('bBack').onclick = () => { SFX.click(); back(); };
}
function keysHtml() {
return `<div class="keys"><b>W A S D / ↑ ← ↓ →</b><span>${t('key_drive')}</span><b>${t('key_space')}</b><span>${t('key_weapon')}</span>
<b>Shift / E</b><span>${t('key_tower')}</span><b>P / Esc</b><span>${t('pause')}</span><b>M</b><span>${t('sound_on')} / ${t('sound_off')}</span>
<b>${t('key_pad')}</b><span>${t('key_pad_text')}</span></div>`;
}
function showHelp(back) {
card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>${keysHtml()}
<p style="margin-top:12px">${t('help_arena')}</p><button class="primary" id="bOk">${t('ok')}</button>`, { bg: 'bg_title.jpg' });
$('bOk').onclick = () => { SFX.click(); back(); };
}
function showRanking(back) {
card(`<h2>🏆 ${t('ranking')}</h2><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol><div class="row"><button class="primary" id="bBack">${t('back')}</button></div>`, { bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); back(); };
fillBoard();
}
function confirmReset(back) {
card(`<h2>${t('reset')}</h2><p>${t('reset_text')}</p><div class="row"><button id="bYes">${t('reset_yes')}</button><button class="primary" id="bNo">${t('cancel')}</button></div>`);
$('bNo').onclick = () => { SFX.click(); back(); };
$('bYes').onclick = () => { Object.assign(save, newSave()); RC.layerFromData(layer, null); save.tutorialSeen = true; persist(); hud(); shop.reset(); SFX.click(); openGarage(); };
}
$('bSettings').onclick = () => {
if (mode === 'fight') togglePause();
if (mode === 'intro') skipIntro();
SFX.click();
const back = mode === 'pause' ? () => { mode = 'fight'; togglePause(); } : currentBack();
showSettings(back);
};
function boardHtml() { return scores.enabled ? `<h3>${t('ranking')}</h3><ol class="board" id="board"><li class="muted">${t('loading')}</li></ol>` : ''; }
async function fillBoard(myKey) {
const el = $('board');
if (!el) return;
@@ -145,77 +372,44 @@
} catch (e) { el.innerHTML = `<li class="muted">${t('scores_offline')}</li>`; }
}
function showMenu() {
setScreen('menu');
F = null;
if (view) view.showGarage(save.build, save.paint);
audio.music('music_garage');
if (!view) { card(`<h1>Robot Clash</h1><p>${t('no_webgl')}</p><p class="credits">${CREDITS}</p>`); return; }
const nameField = scores.enabled ? `<div><input id="name" maxlength="20" placeholder="${esc(t('name_placeholder'))}" value="${esc(save.name)}"></div>` : '';
card(`<h1>ROBOT CLASH</h1><p>${t('menu_text')}</p>
${nameField}<button class="primary" id="bStart">${save.games ? t('continue_career') : t('play')}</button>
<div class="row"><button id="bHelp">${t('how_to')}</button><button id="bLang" title="English / Deutsch">🌐 ${t('lang_self')}</button>
<button id="bReset">${t('reset')}</button></div>
${boardHtml()}<p class="credits">${CREDITS}</p>`);
$('bLang').onclick = () => { SFX.click(); L.next(); };
$('bHelp').onclick = () => { SFX.click(); showHelp(showMenu); };
$('bReset').onclick = () => { SFX.click(); confirmReset(); };
const name = $('name'), start = $('bStart');
if (name) {
const check = () => { const n = Kit.cleanName(name.value); start.disabled = !n || Kit.badName(n); };
name.addEventListener('input', check); check();
name.addEventListener('keydown', e => { if (e.key === 'Enter' && !start.disabled) start.click(); });
}
start.onclick = () => {
if (name) { save.name = Kit.cleanName(name.value); persist(); }
SFX.click();
if (!save.tutorialSeen) { save.tutorialSeen = true; persist(); showHelp(openGarage); } else openGarage();
};
fillBoard();
}
function showHelp(back) {
card(`<h2>${t('how_to')}</h2><p>${t('help_text')}</p>
<div class="keys"><b>W A S D / ↑ ← ↓ →</b><span>${t('key_drive')}</span><b>${t('key_space')}</b><span>${t('key_weapon')}</span>
<b>Shift / E</b><span>${t('key_tower')}</span><b>P / Esc</b><span>${t('pause')}</span><b>${t('key_pad')}</b><span>${t('key_pad_text')}</span></div>
<p style="margin-top:12px">${t('help_arena')}</p><button class="primary" id="bOk">${t('ok')}</button>`);
$('bOk').onclick = () => { SFX.click(); back(); };
}
function confirmReset() {
card(`<h2>${t('reset')}</h2><p>${t('reset_text')}</p><div class="row"><button id="bYes">${t('reset_yes')}</button><button class="primary" id="bNo">${t('cancel')}</button></div>`);
$('bNo').onclick = () => { SFX.click(); showMenu(); };
$('bYes').onclick = () => { resetSave(); persist(); hud(); SFX.click(); showMenu(); };
}
function resetSave() {
save.money = 400; save.fame = 0; save.best = 0; save.season = 1; save.beaten = 0; save.wins = 0; save.losses = 0; save.games = 0;
save.owned = Object.values(RC.STARTER).filter(Boolean); save.build = Object.assign({}, RC.STARTER);
save.paint = { body: 0xff7a1a, accent: 0x15171b }; save.robotName = 'Clank'; save.tutorialSeen = false;
}
// ---------------------------------------------------------------- workshop + league
// ---------------------------------------------------------------- shop + league
function openGarage() {
hideOverlay();
setScreen('garage');
view.showGarage(save.build, save.paint);
view.showGarage(save.build, paintObj());
audio.music('music_garage');
garage.render(); garageTitle(); hud();
shop.render(); hud();
}
$('bGMenu').onclick = () => { SFX.click(); showMenu(); };
$('bGMenu').onclick = () => { SFX.click(); persist(); startIntroOrTitle(); };
$('bTrain').onclick = () => { SFX.click(); startFight(RC.DUMMY, true); };
$('bLeague').onclick = () => { SFX.click(); showLeague(); };
function showLeague() {
setScreen('league');
const rows = RC.LEAGUE.map((o, i) => {
const cards = RC.LEAGUE.map((o, i) => {
const cls = i < save.beaten ? 'done' : i === save.beaten ? 'next' : 'locked';
return `<li class="${cls}"><span>${i < save.beaten ? '✓' : i + 1}</span><span><span class="nm">${o.name}</span><br><span class="muted">${t('style_' + o.style)}</span></span>
<span class="muted">${weaponName(o.build)}</span><span class="pz">${Kit.fmt(Math.round(o.prize * seasonMul()))}</span></li>`;
return `<div class="opp ${cls}" data-i="${i}">${RC.pic('opp_' + o.id, '🤖')}<div class="nm">${i + 1}. ${o.name}</div>
<div class="sm">${i <= save.beaten ? t('style_' + o.style) : '???'}</div>
<div class="pz">${RC.pic('ico_credits', '🪙')}${Kit.fmt(Math.round(o.prize * seasonMul()))}</div></div>`;
}).join('');
card(`<h2>${t('league_title', { s: save.season })}</h2><p>${t('league_text')}</p><ol class="ladder">${rows}</ol>
<div class="row"><button class="primary" id="bFight">${t('fight_vs', { name: RC.LEAGUE[save.beaten].name })}</button><button id="bBack">${t('back')}</button></div>`);
$('bFight').onclick = () => { SFX.click(); startFight(RC.LEAGUE[save.beaten], false); };
card(`<h2>${t('league_title', { s: save.season })}</h2><p>${t('league_text')}</p><div class="opps">${cards}</div>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bFight">${t('fight_vs', { name: RC.LEAGUE[save.beaten].name })}</button></div>`,
{ wide: true, bg: 'bg_title.jpg' });
overlay.querySelectorAll('.opp.next').forEach(el => { el.style.cursor = 'pointer'; el.onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); }; });
$('bFight').onclick = () => { SFX.click(); showVs(RC.LEAGUE[save.beaten]); };
$('bBack').onclick = () => { SFX.click(); openGarage(); };
}
function showVs(opp) {
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`;
card(`<div class="vs"><div class="side">${RC.pic('icon', '🤖')}<div class="nm">${esc(save.robotName)}</div><div class="muted">${weaponName(save.build)}</div><div class="muted">${line(me)}</div></div>
<div class="mid">VS</div>
<div class="side">${RC.pic('opp_' + opp.id, '🤖')}<div class="nm">${opp.name}</div><div class="muted">${weaponName(opp.build)}</div><div class="muted">${line(en)}</div></div></div>
<p>${t('style_' + opp.style)}</p>
<div class="row"><button id="bBack">${t('back')}</button><button class="primary" id="bGo">${t('fight_go_btn')}</button></div>`, { wide: true, bg: 'bg_title.jpg' });
$('bBack').onclick = () => { SFX.click(); showLeague(); };
$('bGo').onclick = () => { SFX.click(); startFight(opp, false); };
}
// ---------------------------------------------------------------- fight
function startFight(opp, training) {
@@ -236,7 +430,7 @@
s.events.length = 0;
}
}
view.showArena(s, [save.build, opp.build], [save.paint, opp.paint]);
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);
@@ -273,6 +467,7 @@
function update(dt) {
fx.update(dt);
introTick();
if (mode !== 'fight' || !F) return;
if (F.count > 0) {
F.count -= dt;
@@ -363,12 +558,13 @@
${champion ? `<h2>${t('champion_title', { s: save.season - 1 })}</h2><p>${t('champion_text')}</p>` : ''}
<div class="res">${stats}${rows}${!F.training && fame ? `<span>${t('hud_fame')}</span><span class="plus">+${Kit.fmt(fame)}</span>` : ''}</div>
${F.training ? `<p class="muted">${t('training_note')}</p>` : ''}
<div class="row"><button class="primary" id="bGarage">${t('to_garage')}</button>${!F.training && !won ? `<button id="bRetry">${t('retry')}</button>` : ''}</div>${boardHtml()}`);
<div class="row"><button class="primary" id="bGarage">${t('to_garage')}</button>${!F.training && !won ? `<button id="bRetry">${t('retry')}</button>` : ''}</div>${boardHtml()}`,
{ bg: won ? 'bg_win.jpg' : 'bg_lose.jpg' });
$('bGarage').onclick = () => { SFX.click(); openGarage(); };
if ($('bRetry')) $('bRetry').onclick = () => { SFX.click(); startFight(opp, false); };
if (!F.training && save.fame > save.best) {
save.best = save.fame; persist();
scores.submit({ name: save.name || save.robotName, score: save.fame, level: save.season }).then(fillBoard);
scores.submit({ name: playerName(), score: save.fame, level: save.season }).then(fillBoard);
} else fillBoard();
}
@@ -378,6 +574,20 @@
const dt = Math.min(0.05, lastNow ? (now - lastNow) / 1000 : 0.016); lastNow = now;
if (view) view.frame(mode === 'pause' ? 0 : dt, now);
ctx.clearRect(0, 0, W, H);
if (mode === 'intro' && view) {
const it = view.introTime;
if (it > 5.6) {
const k = Math.min(1, (it - 5.6) / 0.8);
ctx.save(); ctx.globalAlpha = k; ctx.translate(W / 2, H * 0.4); ctx.scale(1.4 - 0.4 * k, 1.4 - 0.4 * k);
ctx.font = '84px "Russo One", "Segoe UI Black", "Arial Black", Impact, sans-serif';
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.lineWidth = 10; ctx.strokeStyle = '#000'; ctx.strokeText('ROBOT CLASH', 0, 0);
ctx.fillStyle = '#ff7a1a'; ctx.fillText('ROBOT CLASH', 0, 0);
ctx.restore();
}
ctx.font = '12px "Segoe UI", sans-serif'; ctx.textAlign = 'right'; ctx.fillStyle = 'rgba(255,255,255,.55)';
ctx.fillText(t('skip_intro'), W - 14, H - 12);
}
if (F && (mode === 'fight' || mode === 'pause' || mode === 'result')) {
fightHud();
fx.apply(ctx); fx.draw(ctx); ctx.restore();
@@ -405,8 +615,9 @@
function togglePause() {
if (mode === 'fight') {
mode = 'pause'; loop.pause();
card(`<h2>${t('pause')}</h2><div class="row"><button class="primary" id="bGo">${t('continue')}</button><button id="bQuit">${t('give_up')}</button></div>`);
card(`<h2>${t('pause')}</h2><div class="row"><button id="bSet2">⚙ ${t('settings')}</button><button id="bQuit">${t('give_up')}</button><button class="primary" id="bGo">${t('continue')}</button></div>`);
$('bGo').onclick = togglePause;
$('bSet2').onclick = () => { SFX.click(); showSettings(() => { mode = 'fight'; togglePause(); }); };
$('bQuit').onclick = () => {
mode = 'fight'; loop.resume(); hideOverlay();
if (F && !F.s.result) { F.s.robots[0].hp = 0; F.s.robots[0].dead = true; F.s.result = { winner: 1, reason: 'ko' }; F.s.endIn = 0; }
@@ -416,25 +627,33 @@
function toggleMute() { audio.toggleMute(); hud(); }
$('bMute').onclick = toggleMute;
$('bPause').onclick = togglePause;
$('bLangTop').onclick = () => { SFX.click(); L.next(); };
addEventListener('blur', () => { if (mode === 'fight') togglePause(); });
// language switch: static texts update themselves (data-i18n), dynamic screens are drawn again
L.onChange(() => {
hud();
if (mode === 'menu') showMenu();
else if (mode === 'garage') { garage.render(); garageTitle(); }
if (mode === 'title') showTitle();
else if (mode === 'garage') shop.render();
else if (mode === 'league') showLeague();
if (F) { $('fW0').textContent = weaponName(save.build); $('fW1').textContent = weaponName(F.opp.build); }
});
if (slot.failed()) console.warn('save failed');
// repair saves from older versions: missing parts, invalid ids
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);
// ---------------------------------------------------------------- start
accounts.resume();
hud();
// dev: index.html?play = straight into the workshop, ?fight = training fight
if (view && DEV.has('fight')) startFight(RC.LEAGUE[Kit.clamp(+DEV.get('fight') || 0, 0, 7)], true);
else if (view && DEV.has('play')) openGarage(); else showMenu();
if (!view) {
card(`<h1>Robot Clash</h1><p>${t('no_webgl')}</p><p class="credits">${CREDITS}</p>`);
} else if (DEV.has('fight') || DEV.has('play')) {
// dev: ?play = straight into the shop, ?fight=N = training fight against league robot N
if (!accounts.current) accounts.guest();
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();
})();