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

@@ -84,8 +84,13 @@
const rammer = !w || w.type === 'wedge';
const pushing = style === 'pusher' && s.pitOpen >= 1;
contact = rammer && !pushing && dist < me.st.rad + e.st.rad + 0.3 ? contact + react : 0;
if (contact > 0.45 && retreat <= 0 && rand() < 0.25 + skill * 0.7) { retreat = 0.35 + rand() * 0.3; contact = 0; }
if (retreat > 0) { retreat -= react; cmd = { throttle: -1, turn: cmd.turn * 0.3 }; }
// only back off with room behind (no spike wall, no trap)
const half = A().half - me.st.rad - 0.4;
const bx = me.x - fx * 1.4, bz = me.z - fz * 1.4;
const roomBehind = Math.abs(bx) < half && Math.abs(bz) < half && !danger(s, bx, bz, me);
if (contact > 0.45 && retreat <= 0 && roomBehind && rand() < 0.25 + skill * 0.7) { retreat = 0.35 + rand() * 0.3; contact = 0; }
if (retreat > 0 && !roomBehind) retreat = 0;
if (retreat > 0) { retreat -= react; cmd = { throttle: -0.85, turn: cmd.turn * 0.3 }; }
hold = { throttle: cmd.throttle, turn: cmd.turn, fire: false, fire2: false };
return withWeapons(hold, s, me, e, dist, inZ);

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 252 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 281 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

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

View File

@@ -1,95 +0,0 @@
/* Robot Clash - workshop panel (#garage in index.html): slot tabs, buy / equip / sell parts,
weight + power meters, paint. Needs parts.js, robot.js, kit-core.js.
const gar = RC.Garage({ t, getSave, onBuild(), onPaint(), onSave(), sfx: { click, buy, deny } });
gar.render() redraw everything (after language switch, money change)
save fields used: money, owned [ids], build {slot: id|null}, paint {body, accent}, robotName */
(function (root) {
'use strict';
const RC = root.RC, $ = Kit.$;
RC.PAINTS = [0xd8452b, 0xff7a1a, 0xf2c230, 0x5fae3b, 0x2e9c8f, 0x2a6fd8, 0x6a3fb0, 0xd94f9a, 0xe6e6e6, 0x8c8c8c, 0x3a3d44, 0x15171b];
const hex = n => '#' + n.toString(16).padStart(6, '0');
const SELL = 0.5;
RC.Garage = function (opt) {
const t = opt.t;
let slot = 'weapon';
function statLine(p) {
const s = [];
if (p.hp) s.push(t('st_hp', { n: p.hp * RC.HP_SCALE }));
if (p.slot === 'motor') s.push(t('st_speed', { n: p.speed.toFixed(1) }), t('st_force', { n: p.force }));
if (p.slot === 'wheels') s.push(t('st_grip', { n: p.grip }), t('st_turn', { n: p.turn }), p.invertible ? t('st_invert') : '');
if (p.slot === 'armour') s.push(t('st_reduce', { n: Math.round(p.reduce * 100) }));
if (p.dmg) s.push(t('st_dmg', { n: p.dmg }));
if (p.dps) s.push(t('st_dps', { n: p.dps }));
if (p.range) s.push(t('st_range', { n: p.range }));
s.push(t('st_weight', { n: p.weight }));
if (p.slot === 'battery') s.push(t('st_supply', { n: p.power }));
else if (p.power) s.push(t('st_power', { n: p.power }));
return s.filter(Boolean).join(' · ');
}
function render() {
const save = opt.getSave(), b = save.build, v = RC.validate(b);
// tabs
$('tabs').innerHTML = RC.SLOTS.map(sl => `<button data-slot="${sl}" class="${sl === slot ? 'on' : ''} ${RC.REQUIRED[sl] && !b[sl] ? 'miss' : ''}">${t('slot_' + sl)}</button>`).join('');
$('tabs').querySelectorAll('button').forEach(el => { el.onclick = () => { slot = el.dataset.slot; opt.sfx.click(); render(); }; });
// parts of this slot
const rows = [];
if (!RC.REQUIRED[slot]) rows.push(`<div class="part ${b[slot] ? '' : 'eq'}"><span class="pn">${t('none')}</span><span class="pb">${b[slot] ? `<button data-act="eq" data-id="">${t('equip')}</button>` : `<span class="muted">${t('equipped')}</span>`}</span><span class="pd">${t('none_' + slot)}</span></div>`);
for (const p of RC.partsFor(slot)) {
const own = save.owned.includes(p.id), eq = b[slot] === p.id;
let btns;
if (eq) btns = `<span class="muted">${t('equipped')}</span>`;
else if (own) btns = `<button data-act="eq" data-id="${p.id}">${t('equip')}</button><button data-act="sell" data-id="${p.id}">${t('sell', { n: Kit.fmt(Math.round(p.cost * SELL)) })}</button>`;
else btns = `<button class="buy" data-act="buy" data-id="${p.id}" ${save.money < p.cost ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(p.cost) })}</button>`;
rows.push(`<div class="part ${eq ? 'eq' : ''}"><span class="pn">${p.name}</span><span class="pb">${btns}</span><span class="pd">${t('pd_' + p.id)}</span><span class="ps">${statLine(p)}</span></div>`);
}
$('parts').innerHTML = rows.join('');
$('parts').querySelectorAll('button[data-act]').forEach(el => { el.onclick = () => act(el.dataset.act, el.dataset.id || null); });
// meters
const st = RC.stats(b);
const bar = (val, max, over) => `<div class="bar"><i class="${over ? 'over' : ''}" style="width:${Math.min(100, val / max * 100)}%"></i></div>`;
$('meters').innerHTML = [
[t('m_weight'), bar(v.weight, RC.WEIGHT_LIMIT, v.weight > RC.WEIGHT_LIMIT), `${v.weight}/${RC.WEIGHT_LIMIT} kg`],
[t('m_power'), bar(v.power, Math.max(1, v.supply), v.power > v.supply), `${v.power}/${v.supply}`],
[t('m_hp'), bar(st.hp, 175 * RC.HP_SCALE), Math.round(st.hp)],
[t('m_armour'), bar(st.reduce, 0.4), Math.round(st.reduce * 100) + '%'],
[t('m_speed'), bar(st.top, 7), st.top.toFixed(1) + ' m/s'],
[t('m_accel'), bar(st.accel, 30), st.accel.toFixed(1)],
[t('m_turn'), bar(st.turn, 3), st.turn.toFixed(1)],
].map(r => `<span>${r[0]}</span>${r[1]}<span>${r[2]}</span>`).join('');
// paint
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
$(id).innerHTML = `<span style="width:58px">${t('paint_' + key)}</span>` + RC.PAINTS.map(c => `<span class="sw ${save.paint[key] === c ? 'on' : ''}" data-c="${c}" style="background:${hex(c)}"></span>`).join('');
$(id).querySelectorAll('.sw').forEach(el => { el.onclick = () => { save.paint[key] = +el.dataset.c; opt.sfx.click(); opt.onSave(); opt.onPaint(); render(); }; });
}
$('gErr').textContent = v.errors.map(e => t('err_' + e.replace(/^(need|bad)_.*/, '$1'), { slot: t('slot_' + e.split('_')[1]) })).join(' · ');
$('bLeague').disabled = !v.ok; $('bTrain').disabled = !v.ok;
const name = $('rname');
if (document.activeElement !== name) name.value = save.robotName;
}
function act(what, id) {
const save = opt.getSave(), p = id ? RC.PARTS[id] : null;
if (what === 'buy' && p && save.money >= p.cost && !save.owned.includes(id)) {
save.money -= p.cost; save.owned.push(id); save.build[slot] = id; opt.sfx.buy();
} else if (what === 'eq') {
save.build[slot] = id; opt.sfx.click();
} else if (what === 'sell' && p && save.build[slot] !== id) {
save.owned = save.owned.filter(x => x !== id); save.money += Math.round(p.cost * SELL); opt.sfx.buy();
} else { opt.sfx.deny(); return; }
opt.onSave(); opt.onBuild(); render();
}
$('rname').addEventListener('input', () => {
const s = opt.getSave(), n = Kit.cleanName($('rname').value).slice(0, 18);
if (n && !Kit.badName(n)) { s.robotName = n; opt.onSave(); opt.onPaint(); }
});
$('rname').addEventListener('keydown', e => { if (e.key === 'Enter') $('rname').blur(); e.stopPropagation(); });
return { render, get slot() { return slot; } };
};
})(window);

View File

@@ -8,7 +8,7 @@
<style>
:root {
--bg: #090b10; --panel: #151920; --panel2: #1c212b; --line: #2d3442; --text: #e8ebf2; --dim: #8d95a8;
--accent: #ff7a1a; --good: #6dff9e; --warn: #ff5a4a; --blue: #4fa8ff;
--accent: #ff7a1a; --good: #6dff9e; --warn: #ff5a4a; --blue: #4fa8ff; --gold: #ffc940;
--head: "Russo One", "Segoe UI Black", "Arial Black", Impact, sans-serif;
}
* { box-sizing: border-box; }
@@ -19,94 +19,186 @@
/* fixed design size, scaled to the window by Kit.fit */
#app { position: relative; width: 960px; display: flex; flex-direction: column; gap: 8px; }
#hud { display: flex; gap: 8px; align-items: center; }
.chip { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 5px 11px; }
#hud { display: flex; gap: 8px; align-items: center; height: 38px; }
.chip { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; padding: 4px 10px; display: flex; align-items: center; gap: 6px; }
.chip b { color: var(--accent); font-variant-numeric: tabular-nums; }
.chip .pic { width: 22px; height: 22px; }
.grow { flex: 1; }
.logo { font-family: var(--head); letter-spacing: .06em; color: var(--accent); font-size: 20px; padding: 0 6px; }
#stage { position: relative; width: 960px; height: 540px; border: 2px solid var(--line); border-radius: 10px; overflow: hidden; background: #000; }
#stage canvas { position: absolute; left: 0; top: 0; display: block; }
#cv { pointer-events: none; }
#stage > canvas { position: absolute; left: 0; top: 0; display: block; }
#cv { pointer-events: none; z-index: 2; }
#gl { z-index: 1; }
#bgimg { position: absolute; inset: 0; background: #0b0d12 center / cover no-repeat; z-index: 0; }
#bgimg::after { content: ''; position: absolute; inset: 0; background: linear-gradient(90deg, rgba(5,6,9,.15) 0%, rgba(5,6,9,.55) 45%, rgba(5,6,9,.8) 100%); }
/* sprite with fallback glyph (shown while the ComfyGen image is missing) */
.pic { position: relative; display: inline-flex; align-items: center; justify-content: center; flex: none; }
.pic::before { content: attr(data-f); position: absolute; font-size: 60%; opacity: .7; }
.pic img { position: relative; width: 100%; height: 100%; object-fit: contain; }
.pic img.missing { visibility: hidden; }
button { font: inherit; color: var(--text); background: var(--panel2); border: 1px solid var(--line);
border-radius: 8px; padding: 6px 12px; cursor: pointer; }
button:hover { border-color: var(--accent); }
button.primary { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; padding: 10px 24px; font-family: var(--head); letter-spacing: .04em; }
button.primary { background: linear-gradient(#ff8f3a, #e8650a); color: #1a0c02; border-color: #ffa25a; font-weight: 700; padding: 10px 24px; font-family: var(--head); letter-spacing: .04em; box-shadow: 0 3px 0 #7a3000; }
button.primary:active { transform: translateY(2px); box-shadow: 0 1px 0 #7a3000; }
button:disabled { opacity: .4; cursor: default; }
button:disabled:hover { border-color: var(--line); }
button.link { background: none; border: none; color: var(--accent); padding: 2px 4px; text-decoration: underline; }
input[type=text], input[type=password] { font: inherit; width: 100%; padding: 9px 11px; border-radius: 8px; border: 1px solid var(--line);
background: #0b0e14; color: var(--text); }
input:focus { outline: none; border-color: var(--accent); }
/* overlays (menus) */
#overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
background: rgba(5, 6, 10, .62); backdrop-filter: blur(2px); z-index: 5; }
background: rgba(5, 6, 10, .62) center / cover no-repeat; z-index: 6; }
#overlay.hide { display: none; }
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 14px; padding: 22px 30px;
min-width: 380px; max-width: 640px; text-align: center; box-shadow: 0 20px 60px #000a; }
#overlay.clear { background-color: transparent; }
.card { background: rgba(21, 25, 32, .94); border: 1px solid var(--line); border-radius: 14px; padding: 22px 30px;
min-width: 380px; max-width: 760px; text-align: center; box-shadow: 0 20px 60px #000a; }
.card h1 { margin: 0 0 6px; font: 44px var(--head); letter-spacing: .05em; color: var(--accent); text-shadow: 0 3px 0 #5a2600; }
.card h2 { margin: 0 0 8px; font: 26px var(--head); letter-spacing: .04em; color: var(--accent); }
.card h3 { margin: 12px 0 6px; font: 14px var(--head); letter-spacing: .06em; color: var(--dim); text-align: left; }
.card p { color: var(--dim); margin: 6px 0 14px; }
.card input { font: inherit; width: 220px; padding: 8px 10px; border-radius: 8px; border: 1px solid var(--line);
background: #0b0e14; color: var(--text); text-align: center; margin-bottom: 12px; }
.board { list-style: none; padding: 0; margin: 14px 0 0; text-align: left; font-variant-numeric: tabular-nums; max-height: 150px; overflow: auto; }
.board li { display: flex; gap: 10px; padding: 2px 0; }
.board li .nm { flex: 1; } .board li.me { color: var(--good); }
.muted { color: var(--dim); font-size: 13px; }
.card .row { display: flex; gap: 8px; justify-content: center; margin-top: 12px; flex-wrap: wrap; }
.credits { margin: 16px 0 0; font-size: 12px; color: var(--dim); }
.row { display: flex; gap: 8px; justify-content: center; margin-top: 12px; flex-wrap: wrap; }
.credits { margin: 14px 0 0; font-size: 12px; color: var(--dim); }
.credits a { color: var(--accent); text-decoration: none; }
.credits a:hover { text-decoration: underline; }
.keys { display: grid; grid-template-columns: auto auto; gap: 3px 14px; text-align: left; margin: 10px auto 0; width: max-content; font-size: 13px; color: var(--dim); }
.keys b { color: var(--text); }
.err { color: var(--warn); font-size: 13px; min-height: 18px; margin: 6px 0; }
/* league ladder */
.ladder { list-style: none; padding: 0; margin: 10px 0; text-align: left; }
.ladder li { display: grid; grid-template-columns: 26px 1fr 150px 80px; gap: 8px; align-items: center; padding: 5px 10px; border-radius: 8px; }
.ladder li.done { color: var(--dim); }
.ladder li.next { background: #ff7a1a22; border: 1px solid var(--accent); }
.ladder li.locked { opacity: .45; }
.ladder .nm { font-family: var(--head); letter-spacing: .03em; }
.ladder .pz { text-align: right; color: var(--accent); font-variant-numeric: tabular-nums; }
/* title screen */
.title { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: flex-end; padding-bottom: 38px;
background: linear-gradient(180deg, rgba(4,5,8,0) 30%, rgba(4,5,8,.85) 100%); }
.title .big { font: 76px var(--head); letter-spacing: .06em; color: var(--accent); text-shadow: 0 5px 0 #5a2600, 0 0 40px rgba(255,122,26,.5); line-height: 1; }
.title .tag { color: #c9cfdc; margin: 6px 0 18px; text-shadow: 0 2px 4px #000; }
.title .row { margin-top: 8px; }
.title .credits { margin-top: 18px; }
.skip { position: absolute; right: 16px; bottom: 12px; font-size: 12px; color: rgba(255,255,255,.55); }
.form { width: 320px; margin: 0 auto; text-align: left; display: flex; flex-direction: column; gap: 8px; }
.form label { font-size: 13px; color: var(--dim); }
.form .chk { display: flex; gap: 6px; align-items: center; font-size: 13px; color: var(--dim); }
.profiles { display: flex; gap: 6px; flex-wrap: wrap; justify-content: center; margin-bottom: 10px; }
.profiles button { padding: 4px 10px; font-size: 13px; }
/* settings */
.set { display: grid; grid-template-columns: 150px 1fr; gap: 10px 14px; align-items: center; text-align: left; min-width: 460px; }
.set input[type=range] { width: 100%; accent-color: var(--accent); }
.seg { display: flex; gap: 4px; }
.seg button { flex: 1; padding: 5px 8px; font-size: 13px; }
.seg button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
/* league */
.opps { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; margin: 10px 0; }
.opp { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 6px; text-align: center; position: relative; }
.opp > .pic { width: 100%; height: 92px; font-size: 56px; }
.opp .nm { font: 14px var(--head); letter-spacing: .03em; }
.opp .sm { font-size: 11px; color: var(--dim); min-height: 28px; }
.opp .pz { color: var(--gold); font-size: 13px; display: flex; gap: 4px; justify-content: center; align-items: center; }
.opp .pz .pic { width: 16px; height: 16px; }
.opp.done { opacity: .6; } .opp.done::after { content: '✓'; position: absolute; top: 4px; right: 8px; color: var(--good); font: 22px var(--head); }
.opp.next { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,122,26,.35), 0 0 24px rgba(255,122,26,.25); }
.opp.locked .pic { filter: brightness(.15) grayscale(1); }
.vs { display: grid; grid-template-columns: 1fr 70px 1fr; align-items: center; gap: 10px; margin: 6px 0 10px; }
.vs .side { text-align: center; }
.vs .side > .pic { width: 210px; height: 170px; font-size: 90px; }
.vs .mid { font: 46px var(--head); color: var(--accent); text-shadow: 0 3px 0 #5a2600; }
.vs .nm { font: 20px var(--head); }
.res { display: grid; grid-template-columns: 1fr auto; gap: 4px 20px; text-align: left; margin: 10px auto; width: 300px; font-variant-numeric: tabular-nums; }
.res .plus { color: var(--good); } .res .minus { color: var(--warn); }
/* workshop panel */
#garage { position: absolute; right: 0; top: 0; bottom: 0; width: 392px; background: rgba(15, 18, 24, .94);
border-left: 1px solid var(--line); padding: 12px 14px; display: flex; flex-direction: column; gap: 8px; z-index: 3; }
#garage.hide, #fightHud.hide, #gTitle.hide { display: none; }
#garage h3 { margin: 0; font: 15px var(--head); letter-spacing: .05em; color: var(--accent); }
.tabs { display: grid; grid-template-columns: repeat(4, 1fr); gap: 4px; }
.tabs button { padding: 5px 2px; font-size: 12px; }
.tabs button.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
.tabs button.miss { border-color: var(--warn); }
#parts { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 5px; padding-right: 2px; }
.part { background: var(--panel2); border: 1px solid var(--line); border-radius: 8px; padding: 7px 9px; display: grid;
grid-template-columns: 1fr auto; gap: 2px 8px; align-items: center; }
.part.eq { border-color: var(--accent); background: #2a1c10; }
.part .pn { font-weight: 700; }
.part .pd { grid-column: 1 / 2; font-size: 12px; color: var(--dim); }
.part .ps { grid-column: 1 / 3; font-size: 11.5px; color: #b6bdcc; font-variant-numeric: tabular-nums; }
.part .pb { grid-row: 1 / 3; grid-column: 2; display: flex; flex-direction: column; gap: 3px; align-items: stretch; }
.part .pb button { padding: 3px 9px; font-size: 12px; }
.part .pb .buy { border-color: var(--accent); color: var(--accent); }
.meters { display: grid; grid-template-columns: 70px 1fr 64px; gap: 3px 8px; font-size: 12px; align-items: center; font-variant-numeric: tabular-nums; }
.bar { height: 8px; background: #0b0e14; border-radius: 4px; overflow: hidden; border: 1px solid var(--line); }
.bar i { display: block; height: 100%; background: var(--accent); }
/* shop */
#shop { position: absolute; inset: 0; display: grid; grid-template-columns: 340px 1fr; z-index: 3; pointer-events: none; }
#shop.hide, #fightHud.hide { display: none; }
#shop > * { pointer-events: auto; }
#sLeft { display: flex; flex-direction: column; padding: 12px; gap: 8px; pointer-events: none; }
#sLeft > * { pointer-events: auto; }
#rname { width: 100%; font: 24px var(--head); letter-spacing: .04em; background: transparent; border: 1px solid transparent;
border-radius: 6px; color: var(--text); padding: 2px 6px; text-shadow: 0 2px 6px #000; }
#rname:hover, #rname:focus { border-color: var(--line); outline: none; background: rgba(11,14,20,.8); }
.mech { display: flex; gap: 8px; align-items: flex-end; }
.mech .pic { width: 50px; height: 60px; font-size: 34px; border-radius: 8px; overflow: hidden; background: rgba(0,0,0,.35); border: 1px solid var(--line); }
.mech .bubble { background: rgba(250,246,238,.95); color: #1b1d22; border-radius: 10px 10px 10px 2px; padding: 5px 8px; font-size: 12px; max-width: 262px; box-shadow: 0 4px 14px #0008; }
.spacer { flex: 1; pointer-events: none !important; }
.stats { background: rgba(12,14,19,.8); border: 1px solid var(--line); border-radius: 10px; padding: 6px 8px; display: grid; grid-template-columns: 1fr 1fr; gap: 3px 10px; font-size: 11px; font-variant-numeric: tabular-nums; }
.stats .st { display: grid; grid-template-columns: 18px 1fr 54px; gap: 5px; align-items: center; }
.stats .st > span:last-child { text-align: right; }
#shop.painting .mech, #shop.painting .stats { display: none; }
.stats .pic { width: 18px; height: 18px; font-size: 16px; }
.bar { height: 8px; background: #0b0e14; border-radius: 4px; overflow: hidden; border: 1px solid var(--line); position: relative; }
.bar i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--accent); }
.bar i.ghost { background: rgba(255,255,255,.35); }
.bar i.over { background: var(--warn); }
.paint { display: flex; gap: 4px; align-items: center; font-size: 12px; color: var(--dim); }
.paint span.sw { width: 20px; height: 20px; border-radius: 5px; border: 2px solid transparent; cursor: pointer; }
.paint { display: flex; gap: 3px; align-items: center; font-size: 11px; color: var(--dim); }
.paint span.sw { width: 15px; height: 15px; border-radius: 4px; border: 2px solid transparent; cursor: pointer; }
.paint span.sw.on { border-color: #fff; }
.gbtns { display: flex; gap: 6px; }
.gbtns .primary { flex: 1; padding: 9px 8px; }
.err { color: var(--warn); font-size: 12px; min-height: 16px; }
#rname { width: 100%; font: 18px var(--head); letter-spacing: .04em; background: transparent; border: 1px solid transparent;
border-radius: 6px; color: var(--text); padding: 2px 6px; }
#rname:hover, #rname:focus { border-color: var(--line); outline: none; background: #0b0e14; }
#gTitle { position: absolute; left: 18px; bottom: 16px; z-index: 2; pointer-events: none; text-shadow: 0 2px 6px #000; }
#gTitle .big { font: 30px var(--head); letter-spacing: .05em; }
#gTitle .sub { color: var(--dim); }
.paint .lb { width: 46px; }
#sRight { background: rgba(14,16,22,.9); border-left: 1px solid var(--line); display: flex; flex-direction: column; padding: 10px 12px; gap: 8px; min-height: 0; }
.tabs { display: grid; grid-template-columns: repeat(7, 1fr); gap: 5px; }
.tab { background: var(--panel2); border: 1px solid var(--line); border-radius: 9px; padding: 4px 2px 3px; display: flex; flex-direction: column; align-items: center; gap: 1px; font-size: 11px; cursor: pointer; }
.tab .pic { width: 34px; height: 34px; font-size: 26px; }
.tab:hover { border-color: var(--accent); }
.tab.on { background: linear-gradient(#3a2414, #241710); border-color: var(--accent); color: var(--accent); font-weight: 700; }
.tab.miss { border-color: var(--warn); }
#cards { flex: 1; min-height: 0; overflow-y: auto; display: grid; grid-template-columns: repeat(4, 1fr); gap: 7px; align-content: start; padding: 2px; }
.item { background: linear-gradient(#20252f, #181c24); border: 1px solid var(--line); border-radius: 10px; padding: 6px 6px 5px; cursor: pointer; text-align: center; position: relative; }
.item:hover { border-color: #5a6478; }
.item.sel { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(255,122,26,.3); }
.item > .pic { width: 100%; height: 62px; font-size: 42px; }
.item .nm { font-size: 12px; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.item .pr { font-size: 12px; color: var(--gold); display: flex; gap: 3px; justify-content: center; align-items: center; font-variant-numeric: tabular-nums; }
.item .pr .pic { width: 14px; height: 14px; }
.item .pr.no { color: var(--warn); }
.item .badge { position: absolute; top: 5px; left: 5px; font-size: 10px; font-weight: 700; padding: 1px 6px; border-radius: 6px; background: var(--accent); color: #1a0c02; }
.item .badge.own { background: #3c4556; color: var(--text); }
#detail { background: var(--panel2); border: 1px solid var(--line); border-radius: 10px; padding: 8px 10px; display: grid; grid-template-columns: 92px 1fr auto; gap: 10px; align-items: center; min-height: 110px; }
#detail > .pic { width: 92px; height: 92px; font-size: 60px; }
#detail .nm { font: 17px var(--head); letter-spacing: .03em; }
#detail .ds { font-size: 12.5px; color: var(--dim); margin: 2px 0 5px; }
.chips { display: flex; flex-wrap: wrap; gap: 4px; }
.chips span { background: #0f1218; border: 1px solid var(--line); border-radius: 6px; padding: 1px 6px; font-size: 11.5px; display: inline-flex; gap: 3px; align-items: center; font-variant-numeric: tabular-nums; }
.chips span .pic { width: 13px; height: 13px; font-size: 11px; }
.chips span.up { color: var(--good); border-color: #2e5a3e; } .chips span.down { color: var(--warn); border-color: #5a2e2e; }
#detail .act { display: flex; flex-direction: column; gap: 6px; min-width: 120px; }
#detail .act button { padding: 8px 10px; }
.gbar { display: flex; gap: 6px; align-items: center; }
.gbar .err { flex: 1; margin: 0; font-size: 12px; text-align: left; }
.gbar .primary { padding: 9px 26px; }
/* paint booth (painter.js) */
#painter { grid-column: 2; grid-row: 1; background: rgba(14,16,22,.94); border-left: 1px solid var(--line); display: flex; flex-direction: column; padding: 10px 12px; gap: 7px; }
.pt-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.pt-head h3 { margin: 0; font: 16px var(--head); color: var(--accent); letter-spacing: .05em; }
.pt-head .seg button { padding: 3px 7px; font-size: 11.5px; }
.pt-canvas { position: relative; }
.pt-canvas canvas { position: static; display: block; width: 594px; height: 297px; border-radius: 8px; border: 1px solid var(--line); cursor: crosshair; touch-action: none;
background-image: linear-gradient(90deg, transparent 49.8%, rgba(0,0,0,.7) 49.8%, rgba(0,0,0,.7) 50.2%, transparent 50.2%), linear-gradient(0deg, transparent 49.7%, rgba(255,255,255,.12) 49.7%, rgba(255,255,255,.12) 50.3%, transparent 50.3%); }
.pt-lab { position: absolute; top: 4px; font-size: 11px; font-weight: 700; color: rgba(255,255,255,.75); background: rgba(0,0,0,.45); padding: 1px 6px; border-radius: 5px; pointer-events: none; }
.pt-lab.l { left: 6px; } .pt-lab.r { left: 303px; }
.pt-tools { display: flex; gap: 4px; flex-wrap: wrap; align-items: center; }
.pt-tools button { padding: 4px 8px; font-size: 12px; }
.pt-tools button.on, .pt-st.on { background: var(--accent); color: #1a0c02; border-color: var(--accent); font-weight: 700; }
.pt-chk { font-size: 12px; color: var(--dim); display: flex; gap: 4px; align-items: center; margin-left: auto; }
.pt-row { display: flex; gap: 8px; align-items: center; font-size: 12px; color: var(--dim); min-height: 30px; }
.pt-row input[type=range] { width: 120px; accent-color: var(--accent); }
.pt-row #ptExtra { display: flex; gap: 3px; flex-wrap: wrap; flex: 1; }
.pt-row #ptExtra input { padding: 4px 8px; }
.pt-st { padding: 1px 6px; font-size: 15px; min-width: 28px; }
.pt-colors { display: flex; gap: 4px; align-items: center; }
.pt-colors .sw { width: 22px; height: 22px; border-radius: 5px; border: 2px solid rgba(255,255,255,.15); cursor: pointer; }
.pt-colors .sw.on { border-color: #fff; box-shadow: 0 0 0 2px var(--accent); }
.pt-colors input[type=color] { width: 34px; height: 26px; border: none; background: none; padding: 0; cursor: pointer; }
#bPaint { align-self: flex-start; }
/* fight HUD */
#fightHud { position: absolute; left: 0; right: 0; top: 0; padding: 10px 14px; display: grid; grid-template-columns: 1fr 150px 1fr;
gap: 12px; pointer-events: none; z-index: 2; }
gap: 12px; pointer-events: none; z-index: 4; }
.fbox { background: rgba(10, 12, 16, .78); border: 1px solid var(--line); border-radius: 10px; padding: 6px 10px; }
.fbox .fn { font: 16px var(--head); letter-spacing: .04em; display: flex; justify-content: space-between; }
.fbox .fn small { font: 12px "Segoe UI", sans-serif; color: var(--dim); }
@@ -119,7 +211,7 @@
#fState { font-size: 12px; color: var(--accent); min-height: 16px; font-weight: 700; letter-spacing: .05em; }
/* touch pad: only on touch screens */
#pad { position: absolute; left: 14px; right: 14px; bottom: 14px; display: none; justify-content: space-between; pointer-events: none; z-index: 4; }
#pad { position: absolute; left: 14px; right: 14px; bottom: 14px; display: none; justify-content: space-between; pointer-events: none; z-index: 5; }
#pad > div { display: grid; grid-template-columns: repeat(3, 60px); gap: 6px; pointer-events: auto; }
#pad button { height: 60px; font-size: 20px; opacity: .7; padding: 0; }
#pad .fire { grid-template-columns: repeat(2, 74px); }
@@ -142,32 +234,40 @@
<div id="app">
<div id="hud">
<div class="logo">ROBOT CLASH</div>
<div class="chip"><span data-i18n="hud_money">Credits</span> <b id="hMoney">0</b></div>
<div class="chip"><span data-i18n="hud_fame">Fame</span> <b id="hFame">0</b></div>
<div class="chip" data-i18n-title="hud_money"><span class="pic" data-f="🪙" id="icoMoney"></span><b id="hMoney">0</b></div>
<div class="chip" data-i18n-title="hud_fame"><span class="pic" data-f="⭐" id="icoFame"></span><b id="hFame">0</b></div>
<div class="chip"><span data-i18n="hud_league">League</span> <b id="hLeague">-</b></div>
<div class="grow"></div>
<button id="bLangTop" title="English / Deutsch">🌐</button>
<div class="chip" id="hUser" data-i18n-title="account"></div>
<button id="bSettings" data-i18n-title="settings">⚙</button>
<button id="bMute" title="M">Sound</button>
<button id="bPause" title="P / Esc" data-i18n="pause">Pause</button>
</div>
<div id="stage">
<div id="bgimg"></div>
<canvas id="gl"></canvas>
<canvas id="cv"></canvas>
<div id="gTitle" class="hide"><div class="big" id="gName"></div><div class="sub" id="gSub"></div></div>
<div id="garage" class="hide">
<input id="rname" maxlength="18" spellcheck="false">
<div class="tabs" id="tabs"></div>
<div id="parts"></div>
<div class="meters" id="meters"></div>
<div class="paint" id="paintBody"></div>
<div class="paint" id="paintAccent"></div>
<div class="err" id="gErr"></div>
<div class="gbtns">
<button class="primary" id="bLeague" data-i18n="to_league">League</button>
<button id="bTrain" data-i18n="training">Training</button>
<button id="bGMenu" data-i18n="menu">Menu</button>
<div id="shop" class="hide">
<div id="sLeft">
<input id="rname" maxlength="18" spellcheck="false">
<div class="mech"><span class="pic" data-f="🧔" id="mechPic"></span><div class="bubble" id="mechTip"></div></div>
<div class="spacer"></div>
<div class="stats" id="meters"></div>
<div class="paint" id="paintBody"></div>
<div class="paint" id="paintAccent"></div>
<button id="bPaint" data-i18n="pt_open">🎨 Paint it yourself</button>
</div>
<div id="sRight">
<div class="tabs" id="tabs"></div>
<div id="cards"></div>
<div id="detail"></div>
<div class="gbar">
<div class="err" id="gErr"></div>
<button id="bGMenu" data-i18n="menu">Menu</button>
<button id="bTrain" data-i18n="training">Training</button>
<button class="primary" id="bLeague" data-i18n="to_league">League</button>
</div>
</div>
</div>
@@ -204,8 +304,10 @@
<script src="robot.js"></script>
<script src="combat.js"></script>
<script src="ai.js"></script>
<script src="profiles.js"></script>
<script src="render3d.js"></script>
<script src="garage.js"></script>
<script src="shop.js"></script>
<script src="painter.js"></script>
<script src="game.js"></script>
</body>
</html>

View File

@@ -83,6 +83,43 @@ window.LANG = {
champion_text: 'The league starts again - harder opponents, higher prizes.',
training_note: 'Training: no prize money, free repairs.',
to_garage: 'Workshop', retry: 'Rematch',
// title + accounts
skip_intro: 'Any key: skip', settings: 'Settings',
login: 'Log in', register: 'Register', play_guest: 'Play as guest', play_as: 'Play as {name}', switch_account: 'Switch account',
guest: 'Guest', account: 'Account', logout: 'Log out', to_title: 'Back to title',
guest_text: 'You are playing as a guest. Your progress is saved on this device.',
logged_in_as: 'Logged in as <b>{name}</b>.',
local_profiles: 'Profiles on this device:',
f_name: 'Name', f_pass: 'Password', f_pass2: 'Repeat password', f_remember: 'Stay logged in',
no_account: 'No account yet?', register_go: 'Create account',
register_text: 'Each account has its own robot, credits and league progress.',
local_note: 'Accounts are stored on this device for now. Online accounts follow later.',
e_name_short: 'Name needs at least 3 characters.', e_name_bad: 'Please pick another name.', e_name_taken: 'This name is taken.',
e_pass_short: 'Password needs at least 4 characters.', e_pass_match: 'Passwords do not match.',
e_unknown: 'No account with this name.', e_wrong_pass: 'Wrong password.',
// settings
s_lang: 'Language', s_music: 'Music', s_sfx: 'Effects', s_mute: 'Sound', s_gfx: 'Graphics', s_intro: 'Intro at start',
s_screen: 'Display', s_controls: 'Controls', s_career: 'Career', on: 'On', off: 'Off',
gfx_low: 'Low', gfx_medium: 'Medium', gfx_high: 'High',
// paint booth
pt_open: '🎨 Paint it yourself', pt_title: 'Paint booth', pt_top: 'TOP VIEW · front', pt_side: 'SIDE · front',
pt_view_top: 'Top', pt_view_right: 'Right', pt_view_left: 'Left', pt_view_front: 'Front', pt_view_free: 'Turn',
pt_brush: 'Brush', pt_spray: 'Spray', pt_erase: 'Eraser', pt_stamp: 'Stamp', pt_text: 'Text', pt_fill: 'Fill',
pt_mirror: 'Mirror both sides', pt_size: 'Size', pt_undo: 'Undo', pt_clear: 'Clear all', pt_done: 'Done', pt_text_ph: 'Text or number',
// shop
owned: 'owned', need_money: '{n} credits missing', fight_go_btn: 'Into the arena!',
tip_bought: '{name}? Good choice. Let me bolt that on.',
tip_overweight: 'Too heavy! The judges weigh every robot - drop a part or pick lighter armour.',
tip_power: 'Your battery can\'t feed all that. Buy a stronger battery or a weapon that needs less power.',
tip_0: 'Welcome to the workshop! Pick a category on top and click a part to see what it does.',
tip_1: 'The white bar in the stats shows how your robot changes with the selected part.',
tip_2: 'A wedge plus a strong motor is cheap and nasty - shove them into the saws!',
tip_3: 'Big tyres keep you driving when a flipper turns you over.',
tip_4: 'The pit opens at half time. Pushers love it - so should you.',
tip_5: 'Stay out of the corners: the forge press and the magnet crane don\'t care whose robot it is.',
tip_6: 'Tracks win every shoving match, but they are slow.',
tip_7: 'Hammers ignore half of the armour. Great against heavy plates.',
tip_8: 'Lost a fight? You still get an appearance fee - repairs come off your winnings.',
},
de: {
lang_self: 'Deutsch',
@@ -164,5 +201,42 @@ window.LANG = {
champion_text: 'Die Liga beginnt von vorn – härtere Gegner, höhere Preise.',
training_note: 'Training: kein Preisgeld, Reparatur gratis.',
to_garage: 'Werkstatt', retry: 'Revanche',
// title + accounts
skip_intro: 'Beliebige Taste: überspringen', settings: 'Einstellungen',
login: 'Einloggen', register: 'Registrieren', play_guest: 'Als Gast spielen', play_as: 'Spielen als {name}', switch_account: 'Konto wechseln',
guest: 'Gast', account: 'Konto', logout: 'Ausloggen', to_title: 'Zum Titel',
guest_text: 'Du spielst als Gast. Dein Fortschritt wird auf diesem Gerät gespeichert.',
logged_in_as: 'Eingeloggt als <b>{name}</b>.',
local_profiles: 'Profile auf diesem Gerät:',
f_name: 'Name', f_pass: 'Passwort', f_pass2: 'Passwort wiederholen', f_remember: 'Eingeloggt bleiben',
no_account: 'Noch kein Konto?', register_go: 'Konto anlegen',
register_text: 'Jedes Konto hat seinen eigenen Roboter, Credits und Liga-Fortschritt.',
local_note: 'Konten werden vorerst auf diesem Gerät gespeichert. Online-Konten folgen später.',
e_name_short: 'Der Name braucht mindestens 3 Zeichen.', e_name_bad: 'Bitte wähle einen anderen Namen.', e_name_taken: 'Dieser Name ist schon vergeben.',
e_pass_short: 'Das Passwort braucht mindestens 4 Zeichen.', e_pass_match: 'Die Passwörter stimmen nicht überein.',
e_unknown: 'Kein Konto mit diesem Namen.', e_wrong_pass: 'Falsches Passwort.',
// settings
s_lang: 'Sprache', s_music: 'Musik', s_sfx: 'Effekte', s_mute: 'Ton', s_gfx: 'Grafik', s_intro: 'Intro beim Start',
s_screen: 'Anzeige', s_controls: 'Steuerung', s_career: 'Karriere', on: 'An', off: 'Aus',
gfx_low: 'Niedrig', gfx_medium: 'Mittel', gfx_high: 'Hoch',
// paint booth
pt_open: '🎨 Selbst bemalen', pt_title: 'Lackiererei', pt_top: 'OBEN · vorne', pt_side: 'SEITE · vorne',
pt_view_top: 'Oben', pt_view_right: 'Rechts', pt_view_left: 'Links', pt_view_front: 'Vorne', pt_view_free: 'Drehen',
pt_brush: 'Pinsel', pt_spray: 'Spray', pt_erase: 'Radierer', pt_stamp: 'Stempel', pt_text: 'Text', pt_fill: 'Füllen',
pt_mirror: 'Beide Seiten spiegeln', pt_size: 'Größe', pt_undo: 'Zurück', pt_clear: 'Alles löschen', pt_done: 'Fertig', pt_text_ph: 'Text oder Nummer',
// shop
owned: 'im Besitz', need_money: 'Es fehlen {n} Credits', fight_go_btn: 'Ab in die Arena!',
tip_bought: '{name}? Gute Wahl. Ich schraub das gleich dran.',
tip_overweight: 'Zu schwer! Jeder Roboter wird gewogen – lass ein Teil weg oder nimm leichtere Panzerung.',
tip_power: 'Deine Batterie schafft das nicht. Kauf eine stärkere oder nimm eine Waffe mit weniger Strombedarf.',
tip_0: 'Willkommen in der Werkstatt! Wähl oben eine Kategorie und klick ein Teil an, um zu sehen, was es kann.',
tip_1: 'Der weiße Balken bei den Werten zeigt, wie sich dein Roboter mit dem gewählten Teil ändert.',
tip_2: 'Keil plus starker Motor: billig und gemein – schieb sie in die Sägen!',
tip_3: 'Große Reifen fahren weiter, wenn dich ein Flipper umdreht.',
tip_4: 'Zur Halbzeit geht die Grube auf. Schieber lieben sie – du solltest es auch.',
tip_5: 'Bleib aus den Ecken: Schmiedepresse und Magnetkran ist egal, wessen Roboter da steht.',
tip_6: 'Ketten gewinnen jedes Schiebeduell, sind aber langsam.',
tip_7: 'Hämmer ignorieren die halbe Panzerung. Ideal gegen dicke Platten.',
tip_8: 'Kampf verloren? Antrittsgeld gibt es trotzdem – die Reparatur geht davon ab.',
},
};

183
game/painter.js Normal file
View File

@@ -0,0 +1,183 @@
/* Robot Clash - paint booth: draw your own artwork onto the robot, the 3D robot updates live.
The drawing is a transparent 512x256 layer: left half = top view, right half = side view
(front of the robot to the right in both). render3d.js puts it over the paint colour.
const painter = RC.Painter({ t, layer, getPaint(), onLive(), onDone(), onCancel(), sfx, view });
painter.open() / painter.close()
RC.layerFromData(canvas, dataURL, done) restore a saved drawing
Needs kit-core.js. Panel is built into #shop (replaces the parts column while open). */
(function (root) {
'use strict';
const RC = root.RC, $ = Kit.$;
const LW = 512, LH = 256;
const COLORS = ['#ffffff', '#c8ccd4', '#6b7280', '#15171b', '#d8452b', '#ff7a1a', '#f2c230', '#5fae3b',
'#2e9c8f', '#2a6fd8', '#6a3fb0', '#d94f9a', '#8a5a3a', '#ffd9a0', '#00e5ff', '#b6ff3a'];
const STAMPS = ['★', '⚡', '⚙', '✚', '●', '▲', '♛', '☢', '🔥', '💀', '👁', '🎯'];
RC.layerFromData = (cv, data, done) => {
const c = cv.getContext('2d');
c.clearRect(0, 0, LW, LH);
if (!data) { if (done) done(); return; }
const im = new Image();
im.onload = () => { c.drawImage(im, 0, 0, LW, LH); if (done) done(); };
im.onerror = () => { if (done) done(); };
im.src = data;
};
RC.Painter = function (opt) {
const t = opt.t, layer = opt.layer, lc = layer.getContext('2d');
let tool = 'brush', color = '#ffffff', size = 14, stamp = '★', text = '', mirror = true;
let undo = [], drawing = null, panel = null, before = null, pending = false;
function build() {
panel = document.createElement('div');
panel.id = 'painter';
panel.innerHTML = `
<div class="pt-head"><h3>🎨 ${t('pt_title')}</h3><div class="seg" id="ptView">
${['top', 'right', 'left', 'front', 'free'].map(v => `<button data-v="${v}" class="${v === 'free' ? 'on' : ''}">${t('pt_view_' + v)}</button>`).join('')}</div></div>
<div class="pt-canvas"><span class="pt-lab l">${t('pt_top')} ▸</span><span class="pt-lab r">${t('pt_side')} ▸</span><canvas id="ptCv" width="${LW}" height="${LH}"></canvas></div>
<div class="pt-tools" id="ptTools">
${[['brush', '🖌️'], ['spray', '💨'], ['erase', '🧽'], ['stamp', '⭐'], ['text', '🔤'], ['fill', '🪣']].map(([k, g]) => `<button data-tool="${k}" title="${t('pt_' + k)}">${g} ${t('pt_' + k)}</button>`).join('')}
<label class="pt-chk"><input type="checkbox" id="ptMirror" ${mirror ? 'checked' : ''}> ${t('pt_mirror')}</label>
</div>
<div class="pt-row"><span>${t('pt_size')}</span><input type="range" id="ptSize" min="2" max="60" value="${size}">
<span id="ptExtra"></span></div>
<div class="pt-colors" id="ptColors">${COLORS.map(c => `<span class="sw" data-c="${c}" style="background:${c}"></span>`).join('')}<input type="color" id="ptPick" value="${color}"></div>
<div class="gbar"><button id="ptUndo">↶ ${t('pt_undo')}</button><button id="ptClear">${t('pt_clear')}</button><div class="grow"></div>
<button id="ptCancel">${t('cancel')}</button><button class="primary" id="ptDone">✓ ${t('pt_done')}</button></div>`;
$('shop').appendChild(panel);
const cv = $('ptCv');
cv.addEventListener('pointerdown', down);
cv.addEventListener('pointermove', move);
cv.addEventListener('pointerup', up);
cv.addEventListener('pointercancel', up);
panel.querySelectorAll('[data-tool]').forEach(b => { b.onclick = () => { tool = b.dataset.tool; opt.sfx.click(); refresh(); }; });
panel.querySelectorAll('#ptColors .sw').forEach(s => { s.onclick = () => { color = s.dataset.c; $('ptPick').value = color; opt.sfx.click(); refresh(); }; });
$('ptPick').oninput = e => { color = e.target.value; refresh(); };
$('ptSize').oninput = e => { size = +e.target.value; };
$('ptMirror').onchange = e => { mirror = e.target.checked; };
$('ptUndo').onclick = () => { if (undo.length) { lc.putImageData(undo.pop(), 0, 0); live(); opt.sfx.click(); } };
$('ptClear').onclick = () => { snap(); lc.clearRect(0, 0, LW, LH); live(); opt.sfx.click(); };
$('ptDone').onclick = () => { opt.sfx.buy(); close(); opt.onDone(); };
$('ptCancel').onclick = () => { lc.putImageData(before, 0, 0); opt.sfx.click(); close(); opt.onCancel(); };
panel.querySelectorAll('#ptView button').forEach(b => { b.onclick = () => {
panel.querySelectorAll('#ptView button').forEach(x => x.classList.toggle('on', x === b));
opt.view.face(b.dataset.v === 'free' ? null : b.dataset.v); opt.sfx.click();
}; });
// typing in the text field must not drive the robot / open menus
panel.addEventListener('keydown', e => e.stopPropagation());
}
function refresh() {
panel.querySelectorAll('[data-tool]').forEach(b => b.classList.toggle('on', b.dataset.tool === tool));
panel.querySelectorAll('#ptColors .sw').forEach(s => s.classList.toggle('on', s.dataset.c === color));
const ex = $('ptExtra');
if (tool === 'stamp') {
ex.innerHTML = STAMPS.map(s => `<button class="pt-st ${s === stamp ? 'on' : ''}" data-s="${s}">${s}</button>`).join('');
ex.querySelectorAll('button').forEach(b => { b.onclick = () => { stamp = b.dataset.s; refresh(); }; });
} else if (tool === 'text') {
ex.innerHTML = `<input type="text" id="ptText" maxlength="14" placeholder="${t('pt_text_ph')}" value="${text.replace(/"/g, '&quot;')}">`;
$('ptText').oninput = e => { text = e.target.value; };
} else ex.innerHTML = '';
const p = opt.getPaint();
$('ptCv').style.backgroundColor = '#' + (p.body >>> 0).toString(16).padStart(6, '0');
}
function pos(e) {
const r = e.target.getBoundingClientRect();
return { x: (e.clientX - r.left) / r.width * LW, y: (e.clientY - r.top) / r.height * LH };
}
const halfOf = x => (x < LW / 2 ? 0 : 1);
function snap() { undo.push(lc.getImageData(0, 0, LW, LH)); if (undo.length > 25) undo.shift(); }
// every mark is clipped to the half it started in; in the top view "mirror" copies it to the other robot side
function withClip(half, fn) {
lc.save(); lc.beginPath(); lc.rect(half * LW / 2, 0, LW / 2, LH); lc.clip();
fn(false);
if (mirror && half === 0) { lc.translate(0, LH); lc.scale(1, -1); fn(true); }
lc.restore();
}
function down(e) {
e.preventDefault();
e.target.setPointerCapture(e.pointerId);
const p = pos(e), half = halfOf(p.x);
snap();
if (tool === 'stamp' || tool === 'text') {
const s = tool === 'stamp' ? stamp : text.trim();
if (s) withClip(half, flip => {
lc.save(); lc.translate(p.x, p.y); if (flip) lc.scale(1, -1);
lc.fillStyle = color; lc.font = `${tool === 'text' ? 'bold ' : ''}${size * (tool === 'text' ? 1.2 : 2)}px "Russo One", "Segoe UI Black", "Segoe UI Emoji", sans-serif`;
lc.textAlign = 'center'; lc.textBaseline = 'middle';
if (tool === 'text') { lc.lineWidth = Math.max(2, size / 6); lc.strokeStyle = 'rgba(0,0,0,.6)'; lc.strokeText(s, 0, 0); }
lc.fillText(s, 0, 0); lc.restore();
});
opt.sfx.click(); live(); return;
}
if (tool === 'fill') { // fill the whole half (top or side) with the colour
lc.save(); lc.fillStyle = color; lc.fillRect(half * LW / 2, 0, LW / 2, LH); lc.restore();
opt.sfx.click(); live(); return;
}
drawing = { half, last: p };
paint(p, p);
}
function move(e) {
if (!drawing) return;
const p = pos(e);
paint(drawing.last, p);
drawing.last = p;
}
function up() { drawing = null; }
function paint(a, b) {
withClip(drawing.half, () => {
lc.globalCompositeOperation = tool === 'erase' ? 'destination-out' : 'source-over';
if (tool === 'spray') {
lc.fillStyle = color;
const n = Math.ceil(size * 1.5);
for (let i = 0; i < n; i++) {
const ang = Math.random() * Math.PI * 2, r = Math.random() * size;
lc.globalAlpha = 0.35; lc.fillRect(b.x + Math.cos(ang) * r, b.y + Math.sin(ang) * r, 1.6, 1.6);
}
lc.globalAlpha = 1;
} else {
lc.strokeStyle = color; lc.lineWidth = size; lc.lineCap = 'round'; lc.lineJoin = 'round';
lc.beginPath(); lc.moveTo(a.x, a.y); lc.lineTo(b.x + 0.01, b.y); lc.stroke();
}
lc.globalCompositeOperation = 'source-over';
});
live();
}
// preview canvas + 3D robot, at most once per frame
function live() {
if (pending) return;
pending = true;
requestAnimationFrame(() => {
pending = false;
const v = $('ptCv').getContext('2d');
v.clearRect(0, 0, LW, LH); v.drawImage(layer, 0, 0);
opt.onLive();
});
}
function open() {
if (!panel) build();
before = lc.getImageData(0, 0, LW, LH);
undo = [];
panel.style.display = '';
$('sRight').style.display = 'none'; $('shop').classList.add('painting');
opt.view.paintCam(true);
refresh(); live();
}
function close() {
if (!panel) return;
panel.style.display = 'none';
$('sRight').style.display = ''; $('shop').classList.remove('painting');
opt.view.paintCam(false); opt.view.face(null);
}
// anything drawn at all? (decides stock stripes vs. own artwork on the model)
function hasArt() {
const d = lc.getImageData(0, 0, LW, LH).data;
for (let i = 3; i < d.length; i += 16) if (d[i] > 8) return true;
return false;
}
return { open, close, hasArt, get isOpen() { return !!panel && panel.style.display !== 'none'; } };
};
})(window);

80
game/profiles.js Normal file
View File

@@ -0,0 +1,80 @@
/* Robot Clash - player accounts. v1: local profiles on this device (name + password, stored as a
salted hash in localStorage - keeps siblings apart, no real security). Later the same interface
gets a Firebase Auth backend (docs/firebase) without changing game.js.
const acc = RC.Accounts('robotclash');
acc.list() -> [{ id, name }]
await acc.register(name, pass) -> { ok, error: 'name_short' | 'name_bad' | 'name_taken' | 'pass_short' }
await acc.login(name, pass, remember) -> { ok, error: 'unknown' | 'wrong_pass' }
acc.guest() play without an account (own save slot)
acc.current { id, name, guest } or null
acc.resume() remembered login from the last session (true/false)
acc.logout() / acc.remove(id)
acc.saveKey() localStorage key of the current player's save
Needs kit-core.js (Kit.store, Kit.cleanName, Kit.badName). */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
// SHA-256 where available (secure contexts incl. file://), FNV-1a fallback
async function hash(text) {
try {
if (root.crypto && root.crypto.subtle) {
const buf = await root.crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, '0')).join('');
}
} catch (e) { /* fall through */ }
let h = 0x811c9dc5;
for (let i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 0x01000193) >>> 0; }
return 'f' + h.toString(16);
}
const rid = () => Math.random().toString(36).slice(2, 10);
RC.Accounts = function (prefix) {
const st = Kit.store(prefix);
const all = () => st.get('profiles', []) || [];
const put = list => st.set('profiles', list);
const find = name => all().find(p => p.name.toLowerCase() === String(name).trim().toLowerCase());
const api = {
current: null,
list: () => all().map(p => ({ id: p.id, name: p.name })),
async register(name, pass) {
name = Kit.cleanName(name).slice(0, 18);
if (name.length < 3) return { ok: false, error: 'name_short' };
if (Kit.badName(name)) return { ok: false, error: 'name_bad' };
if (find(name)) return { ok: false, error: 'name_taken' };
if (String(pass || '').length < 4) return { ok: false, error: 'pass_short' };
const salt = rid() + rid();
const p = { id: 'p' + rid(), name, salt, hash: await hash(salt + pass), created: Date.now() };
put(all().concat(p));
api.current = { id: p.id, name: p.name, guest: false };
st.set('session', p.id);
return { ok: true };
},
async login(name, pass, remember) {
const p = find(name);
if (!p) return { ok: false, error: 'unknown' };
if (await hash(p.salt + pass) !== p.hash) return { ok: false, error: 'wrong_pass' };
api.current = { id: p.id, name: p.name, guest: false };
st.set('session', remember ? p.id : null);
return { ok: true };
},
guest() { api.current = { id: 'guest', name: '', guest: true }; st.set('session', null); },
resume() {
const id = st.get('session', null), p = id && all().find(q => q.id === id);
if (!p) return false;
api.current = { id: p.id, name: p.name, guest: false };
return true;
},
logout() { api.current = null; st.set('session', null); },
remove(id) {
put(all().filter(p => p.id !== id));
try { localStorage.removeItem(prefix + '.save.' + id); localStorage.removeItem(prefix + '.save.' + id + '.bak'); } catch (e) { /* ignore */ }
if (api.current && api.current.id === id) api.logout();
},
// the guest keeps the save of versions before accounts existed
saveKey: () => (!api.current || api.current.guest ? prefix + '.save' : prefix + '.save.' + api.current.id),
};
return api;
};
})(window);

View File

@@ -44,7 +44,29 @@
function floorTex() {
const A = RC.ARENA, S = 64, N = A.half * 2 * S; // 64 px per metre
const P = (x, z) => [(x + A.half) * S, (z + A.half) * S];
return canvasTex(N, N, (c) => {
let plate = null; // tex_floor.jpg from ComfyGen (make_tileable)
const tex = canvasTex(N, N, draw);
const im = new Image();
im.onload = () => {
// under file:// Chrome taints the canvas with a disk image and WebGL refuses it -> keep the drawn plates
// (the release HTML embeds images as data: URIs, there it works)
const probe = document.createElement('canvas').getContext('2d');
probe.drawImage(im, 0, 0, 1, 1);
try { probe.getImageData(0, 0, 1, 1); } catch (e) { return; }
plate = im; draw(tex.image.getContext('2d')); tex.needsUpdate = true;
};
im.src = Kit.asset('assets/Sprites/tex_floor.jpg');
return tex;
function draw(c) {
if (plate) { // 4 m per texture tile, slightly darkened
for (let x = 0; x < N; x += 256) for (let y = 0; y < N; y += 256) c.drawImage(plate, x, y, 256, 256);
c.fillStyle = 'rgba(10,12,16,.35)'; c.fillRect(0, 0, N, N);
c.strokeStyle = 'rgba(0,0,0,.55)'; c.lineWidth = 3;
for (let k = 0; k <= N; k += 128) { c.beginPath(); c.moveTo(k, 0); c.lineTo(k, N); c.moveTo(0, k); c.lineTo(N, k); c.stroke(); }
} else drawPlates(c);
drawMarks(c);
}
function drawPlates(c) {
// steel plates 2 m
for (let i = 0; i < A.half; i++) for (let j = 0; j < A.half; j++) {
const v = 52 + ((i * 7 + j * 13) % 5) * 4;
@@ -54,6 +76,8 @@
c.fillStyle = '#25272c';
for (const [rx, ry] of [[10, 10], [118, 10], [10, 118], [118, 118]]) { c.beginPath(); c.arc(i * 128 + rx, j * 128 + ry, 3, 0, 7); c.fill(); }
}
}
function drawMarks(c) {
// scratches + oil
let seed = 5; const r = () => { seed = (seed * 16807) % 2147483647; return seed / 2147483647; };
for (let k = 0; k < 340; k++) {
@@ -78,7 +102,7 @@
// centre mark
const [cx, cy] = P(0, 0);
c.strokeStyle = 'rgba(255,122,26,.35)'; c.lineWidth = 5; c.beginPath(); c.arc(cx, cy, 1.4 * S, 0, 7); c.stroke();
});
}
}
// ---------------------------------------------------------------- particles
@@ -132,6 +156,7 @@
M.rubber = new T.MeshStandardMaterial({ color: 0x15161a, metalness: 0, roughness: 0.92 });
M.hub = new T.MeshStandardMaterial({ color: 0x9aa1aa, metalness: 0.8, roughness: 0.35 });
M.glowW = new T.MeshStandardMaterial({ color: 0xffffff, emissive: 0xfff2c0, emissiveIntensity: 1.5 });
M.lamp = new T.MeshStandardMaterial({ color: 0xffffff, emissive: 0xfff2c0, emissiveIntensity: 1.5 }); // floodlights (intro switches them on)
M.stripe = new T.MeshStandardMaterial({ map: stripeTex(), metalness: 0.3, roughness: 0.6 });
M.flame = new T.MeshBasicMaterial({ color: 0xff3a08, transparent: true, opacity: 0.42, blending: T.AdditiveBlending, depthWrite: false, side: T.DoubleSide });
M.trackTex = canvasTex(64, 16, (c, w, h) => { c.fillStyle = '#17181b'; c.fillRect(0, 0, w, h); c.fillStyle = '#2c2e33'; for (let x = 0; x < w; x += 8) c.fillRect(x, 0, 4, h); }, [6, 1]);
@@ -141,16 +166,56 @@
const box = (w, h, d, m) => { const o = new T.Mesh(new T.BoxGeometry(w, h, d), m); o.castShadow = true; o.receiveShadow = true; return o; };
const cyl = (r1, r2, h, m, seg = 20) => { const o = new T.Mesh(new T.CylinderGeometry(r1, r2, h, seg), m); o.castShadow = true; return o; };
// ---- skin: paint colour + the player's own drawing (paint.layer, 512x256 canvas:
// left half = top view, front to the right; right half = side view, front to the right)
const css = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
function makeSkin(paint) {
const cv = document.createElement('canvas'); cv.width = 512; cv.height = 256;
const tex = new T.CanvasTexture(cv);
tex.encoding = T.sRGBEncoding; tex.anisotropy = 4;
const mat = new T.MeshStandardMaterial({ map: tex, metalness: 0.4, roughness: 0.45 });
function redraw(p = paint) {
paint = p;
const c = cv.getContext('2d');
c.fillStyle = css(p.body); c.fillRect(0, 0, 512, 256);
c.strokeStyle = 'rgba(0,0,0,.2)'; c.lineWidth = 3; c.strokeRect(5, 5, 246, 246); c.strokeRect(261, 5, 246, 246);
if (p.layer) c.drawImage(p.layer, 0, 0, 512, 256);
tex.needsUpdate = true;
}
redraw();
return { mat, redraw };
}
// planar UVs by face direction: up/down faces -> top half, sides -> side half (readable on both sides)
function skinUV(geo, L, Wd, H, y0) {
geo = geo.index ? geo.toNonIndexed() : geo;
geo.computeVertexNormals();
const p = geo.attributes.position, n = geo.attributes.normal, uv = new Float32Array(p.count * 2);
const cl = (v, a, b) => Math.min(b, Math.max(a, v));
for (let i = 0; i < p.count; i++) {
const fx = cl((p.getX(i) + L / 2) / L, 0, 1), fz = cl((p.getZ(i) + Wd / 2) / Wd, 0, 1), fy = cl((p.getY(i) - y0) / H, 0, 1);
const ax = Math.abs(n.getX(i)), ay = Math.abs(n.getY(i)), az = Math.abs(n.getZ(i));
let u, v;
if (ay >= ax && ay >= az) { u = 0.004 + 0.492 * fx; v = 1 - fz; }
else if (az >= ax) { u = 0.504 + 0.492 * (n.getZ(i) > 0 ? fx : 1 - fx); v = fy; }
else { u = 0.504 + 0.492 * (n.getX(i) > 0 ? 1 - fz : fz); v = fy; }
uv[i * 2] = u; uv[i * 2 + 1] = v;
}
geo.setAttribute('uv', new T.BufferAttribute(uv, 2));
return geo;
}
function buildRobot(build, paint) {
const m = mats(), st = RC.stats(build), P = RC.PARTS;
const ch = P[build.chassis], wh = P[build.wheels], ar = build.armour ? P[build.armour] : null;
const L = st.len, Wd = st.wid, H = st.h;
const body = new T.MeshStandardMaterial({ color: paint.body, metalness: 0.45, roughness: 0.42 });
const skin = makeSkin(paint), body = skin.mat;
const drawn = !!(paint.layer && paint.drawn); // own artwork: no stock stripes, painted armour
const accent = new T.MeshStandardMaterial({ color: paint.accent, metalness: 0.3, roughness: 0.45 });
const armour = ar ? new T.MeshStandardMaterial({ color: ar.tint, metalness: 0.9, roughness: 0.28 }) : null;
const armour = ar ? (drawn ? body : new T.MeshStandardMaterial({ color: ar.tint, metalness: 0.9, roughness: 0.28 })) : null;
const root = new T.Group(), tilt = new T.Group();
root.add(tilt);
const out = { root, tilt, body, st, build, roll: 0, flash: 0, spinA: 0, sawA: 0, gunA: 0, smokeT: 0 };
const out = { root, tilt, body, skin, st, build, roll: 0, flash: 0, spinA: 0, sawA: 0, gunA: 0, smokeT: 0 };
const sk = (geo, w, h, d, y0) => { const o = new T.Mesh(skinUV(geo, w, d, h, y0), body); o.castShadow = o.receiveShadow = true; return o; };
const big = wh && wh.kind === 'big';
const c = big ? 0.12 : 0.1; // ground clearance
out.c = c;
@@ -162,26 +227,29 @@
s.moveTo(-L / 2, 0); s.lineTo(L / 2, 0); s.lineTo(L / 2, H * 0.22); s.lineTo(-L / 2 + L * 0.38, H); s.lineTo(-L / 2, H); s.closePath();
const g = new T.ExtrudeGeometry(s, { depth: Wd, bevelEnabled: true, bevelSize: 0.015, bevelThickness: 0.015, bevelSegments: 1 });
g.translate(0, 0, -Wd / 2);
const o = new T.Mesh(g, body); o.position.y = c; o.castShadow = o.receiveShadow = true; tilt.add(o);
const st1 = box(L * 0.32, 0.02, Wd * 0.8, m.stripe); st1.position.set(-L / 2 + L * 0.19, top + 0.012, 0); tilt.add(st1);
const o = sk(g, L, H, Wd, 0); o.position.y = c; tilt.add(o);
if (!drawn) { const st1 = box(L * 0.32, 0.02, Wd * 0.8, m.stripe); st1.position.set(-L / 2 + L * 0.19, top + 0.012, 0); tilt.add(st1); }
} else if (ch.shape === 'dome') {
const o = box(L, H * 0.5, Wd, body); o.position.y = c + H * 0.25; tilt.add(o);
const d = new T.Mesh(new T.SphereGeometry(1, 28, 12, 0, Math.PI * 2, 0, Math.PI / 2), body);
d.scale.set(L * 0.5, H * 0.75, Wd * 0.5); d.position.y = c + H * 0.5; d.castShadow = true; tilt.add(d);
const o = sk(new T.BoxGeometry(L, H * 0.5, Wd), L, H * 0.5, Wd, -H * 0.25); o.position.y = c + H * 0.25; tilt.add(o);
const d = sk(new T.SphereGeometry(1, 28, 12, 0, Math.PI * 2, 0, Math.PI / 2), 2, 1, 2, 0);
d.scale.set(L * 0.5, H * 0.75, Wd * 0.5); d.position.y = c + H * 0.5; tilt.add(d);
const ring = new T.Mesh(new T.TorusGeometry(1, 0.035, 8, 32), accent);
ring.rotation.x = Math.PI / 2; ring.scale.set(L * 0.5, Wd * 0.5, 1); ring.position.y = c + H * 0.5; tilt.add(ring);
top = c + H * 1.2;
} else {
const o = box(L, H, Wd, body); o.position.y = c + H / 2; tilt.add(o);
const s1 = box(L * 0.86, 0.02, Wd * 0.22, accent); s1.position.set(0, top + 0.01, 0); tilt.add(s1);
const s2 = box(0.06, H * 0.6, Wd * 1.002, m.stripe); s2.position.set(-L / 2 + 0.08, c + H / 2, 0); tilt.add(s2);
const o = sk(new T.BoxGeometry(L, H, Wd), L, H, Wd, -H / 2); o.position.y = c + H / 2; tilt.add(o);
if (!drawn) {
const s1 = box(L * 0.86, 0.02, Wd * 0.22, accent); s1.position.set(0, top + 0.01, 0); tilt.add(s1);
const s2 = box(0.06, H * 0.6, Wd * 1.002, m.stripe); s2.position.set(-L / 2 + 0.08, c + H / 2, 0); tilt.add(s2);
}
}
out.top = top;
// armour plates (sides + rear), bolts
if (armour) {
for (const sz of [-1, 1]) {
const p = box(L * 0.9, H * 0.78, 0.05, armour); p.position.set(0, c + H * 0.42, sz * (Wd / 2 + 0.028)); tilt.add(p);
const p = drawn ? sk(new T.BoxGeometry(L * 0.9, H * 0.78, 0.05), L * 0.9, H * 0.78, 0.05, -H * 0.39) : box(L * 0.9, H * 0.78, 0.05, armour);
p.position.set(0, c + H * 0.42, sz * (Wd / 2 + 0.028)); tilt.add(p);
for (const bx of [-0.36, 0, 0.36]) { const b = cyl(0.025, 0.025, 0.03, m.dark, 8); b.rotation.x = Math.PI / 2; b.position.set(bx * L, c + H * 0.55, sz * (Wd / 2 + 0.06)); tilt.add(b); }
}
const r = box(0.05, H * 0.78, Wd * 0.95, armour); r.position.set(-L / 2 - 0.028, c + H * 0.42, 0); tilt.add(r);
@@ -340,6 +408,7 @@
scene.add(key);
const rimA = new T.PointLight(0xff7a1a, 1.1, 22); rimA.position.set(-9, 5, 9); scene.add(rimA);
const rimB = new T.PointLight(0x4fa8ff, 0.9, 22); rimB.position.set(9, 5, -9); scene.add(rimB);
out.lights = { key, rimA, rimB, hemi: scene.children.find(o => o.isHemisphereLight) };
out.flashLight = new T.PointLight(0xffaa55, 0, 9); scene.add(out.flashLight);
// floor
@@ -376,7 +445,7 @@
}
for (const [px, pz] of [[-1, -1], [1, -1], [-1, 1]]) {
const post = box(0.22, 3.4, 0.22, wallMat); post.position.set(px * (half + 0.35), 1.7, pz * (half + 0.35)); scene.add(post);
const lamp = box(0.5, 0.3, 0.3, m.glowW); lamp.position.set(px * (half + 0.2), 3.5, pz * (half + 0.2)); scene.add(lamp);
const lamp = box(0.5, 0.3, 0.3, m.lamp); lamp.position.set(px * (half + 0.2), 3.5, pz * (half + 0.2)); scene.add(lamp);
}
// audience stands behind the back walls
const seats = new T.InstancedMesh(new T.BoxGeometry(0.32, 0.5, 0.32), new T.MeshStandardMaterial({ roughness: 0.9 }), 900);
@@ -461,37 +530,29 @@
}
// ---------------------------------------------------------------- garage
// transparent: the painted workshop (bg_workshop.jpg, CSS) shows through; only a shadow catcher
function buildGarage(scene) {
scene.background = new T.Color(0x0c0f15);
scene.background = null;
scene.add(new T.HemisphereLight(0x9fb4d8, 0x1c160f, 0.6));
const spot = new T.SpotLight(0xfff0d8, 2.2, 14, 0.62, 0.45);
spot.position.set(1.6, 5, 2.6); spot.target.position.set(0, 0, 0); spot.castShadow = true; spot.shadow.mapSize.set(1024, 1024);
scene.add(spot); scene.add(spot.target);
const rim = new T.PointLight(0xff7a1a, 1.2, 8); rim.position.set(-2.5, 1.2, -1.5); scene.add(rim);
const rim2 = new T.PointLight(0x4fa8ff, 0.8, 8); rim2.position.set(2.5, 1.0, -2); scene.add(rim2);
const floor = new T.Mesh(new T.PlaneGeometry(30, 30), new T.MeshStandardMaterial({ color: 0x1a1d23, metalness: 0.3, roughness: 0.8 }));
const floor = new T.Mesh(new T.PlaneGeometry(30, 30), new T.ShadowMaterial({ opacity: 0.55 }));
floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);
const turntable = new T.Group(); scene.add(turntable);
const disc = cyl(1.5, 1.6, 0.12, new T.MeshStandardMaterial({ color: 0x3a3e46, metalness: 0.8, roughness: 0.35 }), 48);
disc.position.y = 0.06; disc.receiveShadow = true; turntable.add(disc);
const ring = new T.Mesh(new T.TorusGeometry(1.56, 0.03, 8, 64), new T.MeshStandardMaterial({ color: 0xff7a1a, emissive: 0xff7a1a, emissiveIntensity: 0.6 }));
ring.rotation.x = Math.PI / 2; ring.position.y = 0.12; scene.add(ring);
const wallMat = new T.MeshStandardMaterial({ map: canvasTex(256, 128, (c, w, h) => {
c.fillStyle = '#171a20'; c.fillRect(0, 0, w, h); c.fillStyle = '#0d0f13';
for (let x = 8; x < w; x += 16) for (let y = 8; y < h; y += 16) { c.beginPath(); c.arc(x, y, 2.5, 0, 7); c.fill(); }
}, [6, 2]), roughness: 0.9 });
const wall = new T.Mesh(new T.PlaneGeometry(24, 8), wallMat); wall.position.set(0, 4, -4); wall.receiveShadow = true; scene.add(wall);
const st = box(24, 0.3, 0.05, mats().stripe); st.position.set(0, 0.4, -3.97); scene.add(st);
// a few crates
for (const [x, z, s] of [[-3.2, -3.2, 0.7], [-2.5, -3.4, 0.5], [3.4, -3.1, 0.8]]) {
const b = box(s, s, s, new T.MeshStandardMaterial({ color: 0x4b3a26, roughness: 0.9 })); b.position.set(x, s / 2, z); scene.add(b);
}
return { turntable };
return { turntable, spot };
}
// ---------------------------------------------------------------- view
RC.Render = function (canvas, W, H) {
const renderer = new T.WebGLRenderer({ canvas, antialias: true });
const renderer = new T.WebGLRenderer({ canvas, antialias: true, alpha: true });
renderer.setClearColor(0x000000, 0);
renderer.outputEncoding = T.sRGBEncoding;
renderer.toneMapping = T.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
@@ -511,17 +572,40 @@
const camBase = new T.Vector3(15.2, 15.5, 15.2), camLook = new T.Vector3(-1.25, 0, -1.25);
cam.position.copy(camBase); cam.lookAt(camLook);
const gcam = new T.PerspectiveCamera(34, asp, 0.1, 60);
gcam.position.set(2.9, 1.8, 3.4); gcam.lookAt(0, 0.35, 0);
gcam.setViewOffset(W, H, 170, 20, W, H);
gcam.position.set(3.7, 2.5, 4.4); gcam.lookAt(0, 0.3, 0);
gcam.setViewOffset(W, H, 300, 40, W, H); // robot sits in the left part of the shop
// intro / title: perspective camera flying over the arena
const pcam = new T.PerspectiveCamera(40, asp, 0.1, 120);
let mode = 'garage', gRobot = null, robots = [], state = null, shake = 0, flashT = 0;
let mode = 'garage', gRobot = null, robots = [], state = null, shake = 0, flashT = 0, introT = 0, scale = 1, hold = 0;
let quality = 'high', fxMul = 1;
const PX = [6, 34, 18], WORLD = [0.07, 0.7, 0.32]; // particle sizes: ortho px / perspective m
const pointMode = persp => [sparks, smoke, fire].forEach((p, i) => { p.pts.material.size = persp ? WORLD[i] : PX[i]; });
const api = {
get mode() { return mode; },
resize(scale) {
renderer.setPixelRatio(Math.min(3, scale * (root.devicePixelRatio || 1)));
get introTime() { return introT; },
resize(sc) {
scale = sc;
const cap = quality === 'low' ? 1 : quality === 'medium' ? 1.5 : 3;
renderer.setPixelRatio(Math.min(cap, sc * (root.devicePixelRatio || 1)));
renderer.setSize(W, H);
},
// 'low' | 'medium' | 'high': shadows, resolution, particle amount
setQuality(q) {
quality = q; fxMul = q === 'low' ? 0.35 : q === 'medium' ? 0.7 : 1;
const sh = q !== 'low';
renderer.shadowMap.enabled = sh;
renderer.shadowMap.type = q === 'high' ? T.PCFSoftShadowMap : T.PCFShadowMap;
for (const sc of [arenaScene, garageScene]) sc.traverse(o => { if (o.material) [].concat(o.material).forEach(m => { m.needsUpdate = true; }); });
api.resize(scale);
},
// intro fly-over, then a slow orbit behind the title screen; skip() jumps to the orbit
showIntro(builds, paints) {
api.showArena(RC.Combat.create({ robots: builds.map(b => RC.stats(b)), seed: 3 }), builds, paints);
mode = 'intro'; introT = 0; pointMode(true);
},
skipIntro() { if (mode === 'intro' && introT < INTRO_END) introT = INTRO_END; },
showGarage(build, paint) {
mode = 'garage';
if (gRobot) garage.turntable.remove(gRobot.root);
@@ -529,9 +613,21 @@
gRobot.root.position.y = 0.12;
garage.turntable.add(gRobot.root);
},
setPaint(paint) { if (gRobot) { gRobot.body.color.setHex(paint.body); } },
// live update while painting (colour or drawing changed, no rebuild)
setPaint(paint) { if (gRobot) gRobot.skin.redraw(paint); },
// camera for the paint booth: closer, robot centred in the left part
// drag to turn the robot on the turntable (auto-rotation pauses for a moment)
turn(dx) { garage.turntable.rotation.y += dx * 0.012; hold = 2.5; },
// view a side straight on: 'top' | 'left' | 'right' | 'front' | null (free)
face(side) {
const a = { right: 0, front: -Math.PI / 2, left: Math.PI, top: 0 }[side];
if (a == null) { hold = 0; return; }
// turntable angle that points the robot's side (+z = right) at the camera
garage.turntable.rotation.y = Math.atan2(gcam.position.x, gcam.position.z) + a; hold = 1e9;
},
paintCam(on) { gcam.position.set(on ? 2.6 : 3.7, on ? 2.2 : 2.5, on ? 3.1 : 4.4); gcam.lookAt(0, 0.3, 0); },
showArena(s, builds, paints) {
mode = 'arena'; state = s;
mode = 'arena'; state = s; pointMode(false); lightsOn(1);
for (const R of robots) arenaScene.remove(R.root);
robots = builds.map((b, i) => { const R = buildRobot(b, paints[i]); arenaScene.add(R.root); return R; });
sparks.clear(); smoke.clear(); fire.clear(); shake = 0;
@@ -567,10 +663,18 @@
},
frame(dt, now) {
if (mode === 'garage') {
garage.turntable.rotation.y += dt * 0.45;
if (hold > 0) hold -= dt; else garage.turntable.rotation.y += dt * 0.45;
renderer.render(garageScene, gcam);
return;
}
if (mode === 'intro') {
introT += dt;
introScript(dt, now);
animateArena(dt, now);
sparks.update(dt, 9, 1.2); smoke.update(dt, -0.6, 1.4); fire.update(dt, -2.5, 2);
renderer.render(arenaScene, pcam);
return;
}
animateArena(dt, now);
sparks.update(dt, 9, 1.2); smoke.update(dt, -0.6, 1.4); fire.update(dt, -2.5, 2);
shake = Math.max(0, shake - dt * 1.2);
@@ -583,7 +687,46 @@
},
};
// ---- intro: dark arena -> floodlights flicker on -> camera sweeps up -> two robots are lowered in
const INTRO_END = RC.INTRO_END = 7.5;
const ease = u => (u < 0.5 ? 2 * u * u : 1 - Math.pow(-2 * u + 2, 2) / 2);
function lightsOn(k) {
const L = arena.lights;
L.key.intensity = 1.25 * k; L.rimA.intensity = 1.1 * k; L.rimB.intensity = 0.9 * k;
if (L.hemi) L.hemi.intensity = 0.55 * (0.12 + 0.88 * k);
M.lamp.emissiveIntensity = 1.5 * k;
}
function introScript(dt) {
const t = introT, s = state;
// floodlights: off, flicker, on
lightsOn(t < 1.2 ? 0 : t < 1.32 ? 1 : t < 1.5 ? 0.08 : t < 1.62 ? 0.8 : t < 1.85 ? 0.25 : 1);
// camera path, then a slow orbit
let ang, r, h, lx, lz;
if (t < INTRO_END) {
const e = ease(Math.min(1, t / INTRO_END));
ang = lerp(-2.4, Math.PI / 4, e); r = lerp(5, 20.5, e); h = lerp(0.8, 13.5, Math.pow(e, 1.4));
lx = lerp(RC.ARENA.pit.x, -0.6, e); lz = lerp(RC.ARENA.pit.z, -0.6, e);
} else {
ang = Math.PI / 4 + (t - INTRO_END) * 0.05; r = 20.5; h = 13.5; lx = lz = 0;
}
pcam.position.set(Math.cos(ang) * r, h, Math.sin(ang) * r);
pcam.lookAt(lx, 0.3, lz);
// robots lowered in from above, landing with sparks
s.t = t + 2; // trap timing: flames ignite once the lights are on
s.robots.forEach((rb, i) => {
const k = clamp((t - 2.6 - i * 0.35) / 1.6, 0, 1);
const was = rb.y;
rb.y = 7 * Math.pow(1 - k, 2); rb.vx = rb.vz = 0; rb.lifted = rb.y > 0 ? 1 : 0; // lifted: no tumbling
if (was > 0 && rb.y === 0) { burst(rb.x, 0.2, rb.z, Math.round(40 * fxMul), 5, [1, 0.8, 0.4]); puff(rb.x, rb.z, 10); }
rb.spin = t > 5.4 ? Math.min(1, (t - 5.4) * 0.8) : 0; // spinners rev up
rb.sawOn = t > 5.6;
rb.flameOn = t > 5.8 && t < 6.6 || (t > INTRO_END && Math.sin(t * 0.9 + i * 2) > 0.97);
rb.turretA = rb.a + Math.sin(t * 0.7 + i) * 0.4;
});
}
function burst(x, y, z, n, sp, c) {
n = Math.max(1, Math.round(n * fxMul));
for (let k = 0; k < n; k++) {
const a = Math.random() * Math.PI * 2, v = sp * (0.3 + Math.random());
sparks.spawn(x, y, z, Math.cos(a) * v, 1 + Math.random() * sp, Math.sin(a) * v, 0.25 + Math.random() * 0.45, c[0], c[1], c[2]);

145
game/shop.js Normal file
View File

@@ -0,0 +1,145 @@
/* Robot Clash - workshop shop (#shop in index.html): category tiles, part cards with sprites,
detail panel with buy / fit / sell and stat comparison, robot stats, paint, mechanic tips.
Needs parts.js, robot.js, kit-core.js. Sprites from ComfyGen (assets/Sprites/<name>.png) with
fallback glyphs while they are missing.
RC.pic(name, glyph, cls) -> '<span class="pic">' with the sprite (shared helper)
const shop = RC.Shop({ t, getSave, onBuild(), onPaint(), onSave(), sfx: { click, buy, deny } });
shop.render() / shop.tip() redraw / next mechanic tip */
(function (root) {
'use strict';
const RC = root.RC, $ = Kit.$;
RC.PAINTS = [0xd8452b, 0xff7a1a, 0xf2c230, 0x5fae3b, 0x2e9c8f, 0x2a6fd8, 0x6a3fb0, 0xd94f9a, 0xe6e6e6, 0x8c8c8c, 0x3a3d44, 0x15171b];
const hex = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
const SELL = 0.5;
const GLYPH = { chassis: '🧱', motor: '⚙️', wheels: '🛞', battery: '🔋', armour: '🛡️', weapon: '🪓', tower: '🔥' };
const ICO = { hp: ['ico_hp', '❤️'], armour: ['ico_armour', '🛡️'], speed: ['ico_speed', '⏱️'], weight: ['ico_weight', '⚖️'],
power: ['ico_power', '⚡'], money: ['ico_credits', '🪙'], fame: ['ico_fame', '⭐'], accel: [null, '🚀'], turn: [null, '↻'] };
RC.pic = (name, glyph = '', cls = '') =>
`<span class="pic ${cls}" data-f="${glyph}">${name ? `<img src="${Kit.asset('assets/Sprites/' + name + '.png')}" alt="" draggable="false" onerror="this.classList.add('missing')">` : ''}</span>`;
const ico = k => RC.pic(ICO[k][0], ICO[k][1]);
RC.Shop = function (opt) {
const t = opt.t;
let slot = 'weapon', sel = undefined, tipN = 0;
function chipsFor(p) {
const s = [];
if (p.hp) s.push(`<span>${ico('hp')}${p.hp * RC.HP_SCALE}</span>`);
if (p.slot === 'motor') s.push(`<span>${ico('speed')}${p.speed.toFixed(1)} m/s</span>`, `<span>${ico('accel')}${p.force} N</span>`);
if (p.slot === 'wheels') s.push(`<span>${t('st_grip', { n: p.grip })}</span>`, `<span>${ico('turn')}${p.turn}</span>`, p.invertible ? `<span>${t('st_invert')}</span>` : '');
if (p.slot === 'armour') s.push(`<span>${ico('armour')}-${Math.round(p.reduce * 100)}%</span>`);
if (p.dmg) s.push(`<span>${t('st_dmg', { n: p.dmg })}</span>`);
if (p.dps) s.push(`<span>${t('st_dps', { n: p.dps })}</span>`);
if (p.range) s.push(`<span>${t('st_range', { n: p.range })}</span>`);
s.push(`<span>${ico('weight')}${p.weight} kg</span>`);
if (p.slot === 'battery') s.push(`<span>${ico('power')}+${p.power}</span>`);
else if (p.power) s.push(`<span>${ico('power')}${p.power}</span>`);
return s.filter(Boolean).join('');
}
// stat changes if this part (id or null) went into the current slot
function deltas(build, id) {
if (build[slot] === id) return '';
const a = RC.stats(build), b = RC.stats(Object.assign({}, build, { [slot]: id }));
const va = RC.validate(build), vb = RC.validate(Object.assign({}, build, { [slot]: id }));
const rows = [
['hp', b.hp - a.hp, 0], ['armour', (b.reduce - a.reduce) * 100, 0, '%'], ['speed', b.top - a.top, 1],
['accel', b.accel - a.accel, 1], ['turn', b.turn - a.turn, 1], ['weight', vb.weight - va.weight, 0, ' kg', true],
['power', (vb.supply - vb.power) - (va.supply - va.power), 0],
];
return rows.filter(r => Math.abs(r[1]) >= (r[2] ? 0.05 : 0.5)).map(([k, v, d, unit = '', inv]) => {
const good = inv ? v < 0 : v > 0;
return `<span class="${good ? 'up' : 'down'}">${ico(k)}${v > 0 ? '+' : ''}${v.toFixed(d)}${unit}</span>`;
}).join('');
}
function render() {
const save = opt.getSave(), b = save.build, v = RC.validate(b);
if (sel === undefined || (sel && RC.PARTS[sel].slot !== slot)) sel = b[slot] || null;
// category tiles
$('tabs').innerHTML = RC.SLOTS.map(sl => `<div class="tab ${sl === slot ? 'on' : ''} ${RC.REQUIRED[sl] && !b[sl] ? 'miss' : ''}" data-slot="${sl}">${RC.pic('slot_' + sl, GLYPH[sl])}<span>${t('slot_' + sl)}</span></div>`).join('');
$('tabs').querySelectorAll('.tab').forEach(el => { el.onclick = () => { slot = el.dataset.slot; sel = b[slot] || null; opt.sfx.click(); render(); }; });
// part cards
const items = (RC.REQUIRED[slot] ? [] : [null]).concat(RC.partsFor(slot).map(p => p.id));
$('cards').innerHTML = items.map(id => {
const p = id && RC.PARTS[id], eq = b[slot] === id, own = !id || save.owned.includes(id);
const badge = eq ? `<span class="badge">${t('equipped')}</span>` : own && id ? `<span class="badge own">${t('owned')}</span>` : '';
const price = !p || own ? `<div class="pr">&nbsp;</div>` : `<div class="pr ${save.money < p.cost ? 'no' : ''}">${ico('money')}${Kit.fmt(p.cost)}</div>`;
return `<div class="item ${id === sel ? 'sel' : ''}" data-id="${id || ''}">${badge}${RC.pic(p ? 'part_' + id : null, p ? GLYPH[slot] : '✖')}<div class="nm">${p ? p.name : t('none')}</div>${price}</div>`;
}).join('');
$('cards').querySelectorAll('.item').forEach(el => { el.onclick = () => { sel = el.dataset.id || null; opt.sfx.click(); render(); }; });
// detail of the selected card
const p = sel && RC.PARTS[sel], eq = b[slot] === sel, own = !sel || save.owned.includes(sel);
let act;
if (eq) act = `<button disabled>${t('equipped')}</button>`;
else if (own) act = `<button class="primary" data-act="eq">${t('equip')}</button>`;
else act = `<button class="primary" data-act="buy" ${save.money < p.cost ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(p.cost) })}</button>`;
if (p && own && !eq) act += `<button data-act="sell">${t('sell', { n: Kit.fmt(Math.round(p.cost * SELL)) })}</button>`;
if (p && !own && save.money < p.cost) act += `<span class="muted">${t('need_money', { n: Kit.fmt(p.cost - save.money) })}</span>`;
$('detail').innerHTML = `${RC.pic(p ? 'part_' + sel : null, p ? GLYPH[slot] : '✖')}
<div><div class="nm">${p ? p.name : t('none')}</div><div class="ds">${p ? t('pd_' + sel) : t('none_' + slot)}</div>
<div class="chips">${p ? chipsFor(p) : ''}</div><div class="chips" style="margin-top:4px">${deltas(b, sel)}</div></div>
<div class="act">${act}</div>`;
$('detail').querySelectorAll('button[data-act]').forEach(el => { el.onclick = () => act2(el.dataset.act); });
// robot stats (white ghost bar = value with the selected part)
const st = RC.stats(b), alt = sel !== b[slot] ? RC.stats(Object.assign({}, b, { [slot]: sel })) : null;
const valt = alt ? RC.validate(Object.assign({}, b, { [slot]: sel })) : null;
const bar = (val, max, over, ghost) => `<div class="bar">${ghost != null ? `<i class="ghost" style="width:${Math.min(100, ghost / max * 100)}%"></i>` : ''}<i class="${over ? 'over' : ''}" style="width:${Math.min(100, val / max * 100)}%;${ghost != null && ghost < val ? 'opacity:.55' : ''}"></i></div>`;
$('meters').innerHTML = [
['weight', t('m_weight'), bar(v.weight, RC.WEIGHT_LIMIT, v.weight > RC.WEIGHT_LIMIT, valt && valt.weight), `${v.weight}/${RC.WEIGHT_LIMIT} kg`],
['power', t('m_power'), bar(v.power, Math.max(1, v.supply), v.power > v.supply, valt && valt.power), `${v.power}/${v.supply}`],
['hp', t('m_hp'), bar(st.hp, 175 * RC.HP_SCALE, false, alt && alt.hp), Math.round(st.hp)],
['armour', t('m_armour'), bar(st.reduce, 0.4, false, alt && alt.reduce), Math.round(st.reduce * 100) + '%'],
['speed', t('m_speed'), bar(st.top, 7, false, alt && alt.top), st.top.toFixed(1) + ' m/s'],
['accel', t('m_accel'), bar(st.accel, 30, false, alt && alt.accel), st.accel.toFixed(1)],
['turn', t('m_turn'), bar(st.turn, 3, false, alt && alt.turn), st.turn.toFixed(1)],
].map(r => `<span class="st" title="${r[1]}">${ico(r[0])}${r[2]}<span>${r[3]}</span></span>`).join('');
// paint
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
$(id).innerHTML = `<span class="lb">${t('paint_' + key)}</span>` + RC.PAINTS.map(c => `<span class="sw ${save.paint[key] === c ? 'on' : ''}" data-c="${c}" style="background:${hex(c)}"></span>`).join('');
$(id).querySelectorAll('.sw').forEach(el => { el.onclick = () => { save.paint[key] = +el.dataset.c; opt.sfx.click(); opt.onSave(); opt.onPaint(); render(); }; });
}
$('gErr').textContent = v.errors.map(e => t('err_' + e.replace(/^(need|bad)_.*/, '$1'), { slot: t('slot_' + e.split('_')[1]) })).join(' · ');
$('bLeague').disabled = !v.ok; $('bTrain').disabled = !v.ok;
const name = $('rname');
if (document.activeElement !== name) name.value = save.robotName;
if (!$('mechTip').textContent) tip();
}
function act2(what) {
const save = opt.getSave(), p = sel ? RC.PARTS[sel] : null;
if (what === 'buy' && p && save.money >= p.cost && !save.owned.includes(sel)) {
save.money -= p.cost; save.owned.push(sel); save.build[slot] = sel; opt.sfx.buy();
say(t('tip_bought', { name: p.name }));
} else if (what === 'eq') {
save.build[slot] = sel; opt.sfx.click();
} else if (what === 'sell' && p && save.build[slot] !== sel) {
save.owned = save.owned.filter(x => x !== sel); save.money += Math.round(p.cost * SELL); opt.sfx.buy();
} else { opt.sfx.deny(); return; }
opt.onSave(); opt.onBuild(); render();
}
function say(text) { $('mechTip').textContent = text; }
function tip() {
const save = opt.getSave(), v = RC.validate(save.build);
if (v.errors.includes('overweight')) return say(t('tip_overweight'));
if (v.errors.includes('no_power')) return say(t('tip_power'));
const n = Object.keys(window.LANG.en).filter(k => /^tip_\d+$/.test(k)).length;
say(t('tip_' + (tipN++ % n)));
}
setInterval(() => { if (!$('shop').classList.contains('hide')) tip(); }, 14000);
$('rname').addEventListener('input', () => {
const s = opt.getSave(), n = Kit.cleanName($('rname').value).slice(0, 18);
if (n && !Kit.badName(n)) { s.robotName = n; opt.onSave(); opt.onPaint(); }
});
$('rname').addEventListener('keydown', e => { if (e.key === 'Enter') $('rname').blur(); e.stopPropagation(); });
$('mechPic').innerHTML = `<img src="${Kit.asset('assets/Sprites/npc_mechanic.png')}" alt="" onerror="this.classList.add('missing')">`;
return { render, tip, reset() { sel = undefined; } };
};
})(window);