Files
Robot-Clash/game/shop.js

219 lines
16 KiB
JavaScript
Raw Normal View History

2026-11-13 01:02:55 +01:00
/* 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.$;
2026-11-19 00:55:39 +01:00
RC.PAINTS = [0xd8452b, 0xff7a1a, 0xf2c230, 0x5fae3b, 0x2e9c8f, 0x2a6fd8, 0x6a3fb0, 0xd94f9a, 0xe6e6e6, 0x8c8c8c, 0x3a3d44, 0x15171b,
0x39ff14, 0xc0c0c0, 0xff1e8e, 0x7b2fff]; // last 4 are mission rewards (locked until earned)
RC.PAINT_REWARDS = [0x39ff14, 0xc0c0c0, 0xff1e8e, 0x7b2fff];
2026-11-15 17:08:11 +01:00
// ready-made [body, accent] combinations
RC.SCHEMES = [[0xff7a1a, 0x15171b], [0x15171b, 0xff7a1a], [0x2a6fd8, 0xe6e6e6], [0xd8452b, 0xf2c230],
[0x5fae3b, 0x15171b], [0x6a3fb0, 0xf2c230], [0xe6e6e6, 0xd8452b], [0x3a3d44, 0x2e9c8f]];
const HOTKEY = { weapon: 'hk_weapon', tower: 'hk_tower', gadget: 'hk_gadget' };
const GLYPH = { chassis: '🧱', motor: '⚙️', wheels: '🛞', battery: '🔋', armour: '🛡️', weapon: '🪓', tower: '🔥', gadget: '🧰' };
2026-11-13 01:02:55 +01:00
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 = '') =>
2026-11-19 00:55:39 +01:00
`<span class="pic ${cls}" data-f="${glyph}">${name ? `<img src="${Kit.asset('assets/Sprites/' + name + '.png')}" alt="" draggable="false" decoding="async" onerror="this.classList.add('missing')">` : ''}</span>`;
2026-11-13 01:02:55 +01:00
const ico = k => RC.pic(ICO[k][0], ICO[k][1]);
RC.Shop = function (opt) {
const t = opt.t;
2026-11-18 15:18:38 +01:00
let slot = 'chassis', sel = undefined, tipN = 0, topTab = 'build';
2026-11-13 01:02:55 +01:00
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>`);
2026-11-15 17:08:11 +01:00
// which button works this part in a fight
if (HOTKEY[p.slot]) s.push(`<span class="key">⌨ ${t(HOTKEY[p.slot])}</span>`);
2026-11-13 01:02:55 +01:00
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;
2026-11-18 15:18:38 +01:00
renderTopTabs(); // draw the 3 top tabs (Parts / Paint / Hangar)
if (topTab !== 'paint' && opt.onPaintLeave) opt.onPaintLeave(); // close the inline painter when leaving
const parts = topTab === 'build';
let editing = false;
// category tabs + detail + fitted belong to the Parts tab only
$('tabs').classList.toggle('hide', !parts);
$('fittedwrap').classList.toggle('hide', !parts);
{ const d = $('designer'); if (d) d.classList.add('hide'); }
2026-11-13 01:02:55 +01:00
2026-11-18 15:18:38 +01:00
if (parts) {
// category tiles; the weapon tab shows the build editor inside the cards area (tabs stay visible)
$('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(); }; });
editing = slot === 'weapon';
if (opt.onSlot) opt.onSlot(slot); // game.js: freeze the robot while on the weapon tab
$('cards').className = ''; // weapon catalog uses the same card grid as parts
$('detail').classList.remove('hide'); // weapon tab also shows the detail/preview panel
if (editing) {
if (opt.onWeaponTab) opt.onWeaponTab($('cards')); // game.js fills #cards + #detail with the weapon editor
} else {
const locked = opt.locked || (() => false); // event/unlock: hide parts not released yet
const items = (RC.REQUIRED[slot] ? [] : [null]).concat(RC.partsFor(slot).filter(p => !locked(p.id)).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(); }; });
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(RC.Eco.sellValue(sel)) })}</button>`;
2026-11-18 15:18:38 +01:00
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); });
}
} else if (topTab === 'paint') {
if (opt.onSlot) opt.onSlot(''); // leave weapon mode / unfreeze
$('detail').classList.add('hide');
$('cards').className = 'pcards';
if (opt.onPaintTab) opt.onPaintTab($('cards')); // game.js: slots + colours + inline painter
} else { // hangar
if (opt.onSlot) opt.onSlot('');
$('detail').classList.add('hide');
$('cards').className = 'hcards';
if (opt.onHangarView) opt.onHangarView($('cards'));
}
2026-11-13 01:02:55 +01:00
// robot stats (white ghost bar = value with the selected part)
2026-11-18 15:18:38 +01:00
const st = RC.stats(b), alt = (parts && !editing && sel !== b[slot]) ? RC.stats(Object.assign({}, b, { [slot]: sel })) : null;
2026-11-13 01:02:55 +01:00
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>`;
2026-11-18 15:18:38 +01:00
// warn about the build you are PREVIEWING (selected part card / picked weapon) before you commit it, else the current build
let shownB = b;
if (parts && !editing && sel && sel !== b[slot]) shownB = Object.assign({}, b, { [slot]: sel });
else if (editing && opt.weaponPreview) { const pb = opt.weaponPreview(); if (pb) shownB = pb; }
const vWarn = shownB === b ? v : RC.validate(shownB);
const overW = vWarn.weight > RC.WEIGHT_LIMIT, overP = vWarn.power > vWarn.supply;
2026-11-13 01:02:55 +01:00
$('meters').innerHTML = [
2026-11-18 15:18:38 +01:00
['weight', t('m_weight'), bar(v.weight, RC.WEIGHT_LIMIT, overW, valt && valt.weight), `${v.weight}/${RC.WEIGHT_LIMIT} kg`, overW],
['power', t('m_power'), bar(v.power, Math.max(1, v.supply), overP, valt && valt.power), `${v.power}/${v.supply}`, overP],
2026-11-13 01:02:55 +01:00
['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.6, false, alt && alt.turn), st.turn.toFixed(1)],
2026-11-18 15:18:38 +01:00
].map(r => `<span class="st ${r[5] ? 'warn' : ''}" title="${r[1]}">${ico(r[0])}${r[2]}<span>${r[3]}</span></span>`).join('');
2026-11-13 01:02:55 +01:00
2026-11-18 15:18:38 +01:00
// build problem -> a loud, blinking message naming exactly what is too weak (battery / weight / motor)
const gErr = $('gErr');
if (vWarn.errors.length) {
const msg = vWarn.errors.map(e => {
if (e === 'overweight') return t('err_overweight', { n: RC.WEIGHT_LIMIT });
if (e === 'no_power') return t('err_no_power');
if (e === 'too_many_weapons') return t('err_too_many_weapons');
return t('err_' + e.replace(/^(need|bad)_.*/, '$1'), { slot: t('slot_' + e.split('_')[1]) });
}).join(' · ');
gErr.innerHTML = '⚠ ' + msg;
gErr.classList.remove('alert'); void gErr.offsetWidth; gErr.classList.add('alert'); // restart the blink on every change/click
} else { gErr.textContent = ''; gErr.classList.remove('alert'); }
2026-11-13 01:02:55 +01:00
$('bLeague').disabled = !v.ok; $('bTrain').disabled = !v.ok;
const name = $('rname');
if (document.activeElement !== name) name.value = save.robotName;
if (!$('mechTip').textContent) tip();
2026-11-18 15:18:38 +01:00
renderFitted();
2026-11-15 17:08:11 +01:00
// live preview: show the selected part on the 3D robot (even parts you can't afford yet)
2026-11-18 15:18:38 +01:00
if (opt.onPreview) opt.onPreview(parts && !editing && sel !== b[slot] ? Object.assign({}, b, { [slot]: sel }) : b);
2026-11-15 17:08:11 +01:00
}
2026-11-18 15:18:38 +01:00
// proportions (height/width/length) now live in the build editor (game.js), not here
2026-11-17 14:17:50 +01:00
2026-11-18 15:18:38 +01:00
// top mode tabs: Parts / Paint / Hangar - all render into #cards (render() routes the content)
2026-11-15 17:08:11 +01:00
function renderTopTabs() {
const tabs = [['build', '🔧 ' + t('tab_build')], ['paint', '🎨 ' + t('tab_paint')], ['hangar', '🚗 ' + t('tab_hangar')]];
$('shopTabs').innerHTML = tabs.map(([k, label]) => `<button class="${k === topTab ? 'on' : ''}" data-tab="${k}">${label}</button>`).join('');
$('shopTabs').querySelectorAll('button').forEach(bt => { bt.onclick = () => { setTab(bt.dataset.tab); opt.sfx.click(); }; });
}
2026-11-18 15:18:38 +01:00
function setTab(k) { topTab = k; render(); }
2026-11-15 17:08:11 +01:00
// fitted parts summary (left column): every slot with the equipped part + quick remove/jump
function renderFitted() {
const save = opt.getSave(), b = save.build;
$('fitted').innerHTML = RC.SLOTS.map(sl => {
2026-11-18 15:18:38 +01:00
if (sl === 'weapon') { // weapons are a list -> open the editor
const ws = RC.weaponsOf(b), label = ws.length ? ws[0].part.name + (ws.length > 1 ? ' ×' + ws.length : '') : t('none');
return `<div class="frow" data-edit="1">${RC.pic('slot_weapon', GLYPH.weapon)}<span class="fn ${ws.length ? '' : 'empty'}">${label}</span><span class="frm">🔧</span></div>`;
}
2026-11-15 17:08:11 +01:00
const id = b[sl], p = id && RC.PARTS[id];
const rm = p && !RC.REQUIRED[sl] ? `<span class="frm" data-rm="${sl}">✕</span>` : '<span></span>';
return `<div class="frow" data-goto="${sl}">${RC.pic('slot_' + sl, GLYPH[sl])}<span class="fn ${p ? '' : 'empty'}">${p ? p.name : t('none')}</span>${rm}</div>`;
}).join('');
$('fitted').querySelectorAll('.frow').forEach(el => { el.onclick = e => {
2026-11-18 15:18:38 +01:00
if (el.dataset.edit) { slot = 'weapon'; opt.sfx.click(); render(); return; }
if (e.target.dataset.rm) { const s = e.target.dataset.rm; if (!opt.act({ type: 'equip', slot: s, part: null }).ok) { opt.sfx.deny(); return; } opt.sfx.click(); opt.onSave(); opt.onBuild(); render(); return; }
2026-11-15 17:08:11 +01:00
slot = el.dataset.goto; sel = opt.getSave().build[slot] || null; topTab = 'build'; opt.sfx.click(); render();
}; });
2026-11-13 01:02:55 +01:00
}
// every economy change goes through opt.act (RC.Eco rules; online the server checks the same action)
2026-11-13 01:02:55 +01:00
function act2(what) {
const p = sel ? RC.PARTS[sel] : null;
const a = what === 'buy' ? { type: 'buy', part: sel } : what === 'eq' ? { type: 'equip', slot, part: sel || null } : what === 'sell' ? { type: 'sell', part: sel } : null;
if (!a || !opt.act(a).ok) { opt.sfx.deny(); return; }
if (what === 'eq') opt.sfx.click(); else opt.sfx.buy();
if (what === 'buy' && p) say(t('tip_bought', { name: p.name }));
2026-11-13 01:02:55 +01:00
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')">`;
2026-11-18 15:18:38 +01:00
return { render, tip, setTab, weaponTab() { slot = 'weapon'; render(); }, reset() { sel = undefined; topTab = 'build'; } };
2026-11-13 01:02:55 +01:00
};
})(window);