Files
Robot-Clash/game/shop.js

146 lines
10 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.$;
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.6, false, alt && alt.turn), st.turn.toFixed(1)],
2026-11-13 01:02:55 +01:00
].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);