222 lines
15 KiB
JavaScript
222 lines
15 KiB
JavaScript
/* 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];
|
|
// ready-made [body, accent] combinations
|
|
RC.SCHEMES = [[0xff7a1a, 0x15171b], [0x15171b, 0xff7a1a], [0x2a6fd8, 0xe6e6e6], [0xd8452b, 0xf2c230],
|
|
[0x5fae3b, 0x15171b], [0x6a3fb0, 0xf2c230], [0xe6e6e6, 0xd8452b], [0x3a3d44, 0x2e9c8f]];
|
|
const hex = n => '#' + (n >>> 0).toString(16).padStart(6, '0');
|
|
const SELL = 0.5;
|
|
const HOTKEY = { weapon: 'hk_weapon', tower: 'hk_tower', gadget: 'hk_gadget' };
|
|
const GLYPH = { chassis: '🧱', motor: '⚙️', wheels: '🛞', battery: '🔋', armour: '🛡️', weapon: '🪓', tower: '🔥', gadget: '🧰' };
|
|
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, topTab = 'build', designerOpen = false;
|
|
|
|
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>`);
|
|
// which button works this part in a fight
|
|
if (HOTKEY[p.slot]) s.push(`<span class="key">⌨ ${t(HOTKEY[p.slot])}</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 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"> </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)],
|
|
].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 = 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(); }; });
|
|
}
|
|
// ready-made two-colour schemes
|
|
const sc = $('paintSchemes');
|
|
if (sc) {
|
|
sc.innerHTML = RC.SCHEMES.map(([b2, a2]) => {
|
|
const on = save.paint.body === b2 && save.paint.accent === a2;
|
|
return `<span class="sw duo ${on ? 'on' : ''}" data-b="${b2}" data-a="${a2}"><i style="background:${hex(b2)}"></i><i style="background:${hex(a2)}"></i></span>`;
|
|
}).join('');
|
|
sc.querySelectorAll('.sw').forEach(el => {
|
|
el.onclick = () => { save.paint.body = +el.dataset.b; save.paint.accent = +el.dataset.a; 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();
|
|
renderTopTabs(); renderFitted(); renderDesigner();
|
|
// live preview: show the selected part on the 3D robot (even parts you can't afford yet)
|
|
if (opt.onPreview) opt.onPreview(topTab === 'build' && sel !== b[slot] ? Object.assign({}, b, { [slot]: sel }) : b);
|
|
}
|
|
|
|
// proportions designer (height / width / length) - only on the chassis slot
|
|
function renderDesigner() {
|
|
const el = $('designer');
|
|
if (!el) return;
|
|
if (slot !== 'chassis') { el.classList.add('hide'); return; }
|
|
el.classList.remove('hide');
|
|
el.classList.toggle('open', designerOpen);
|
|
el.classList.toggle('shut', !designerOpen);
|
|
const save = opt.getSave(), b = save.build;
|
|
if (!b.body) b.body = { hx: 1, wx: 1, lx: 1 };
|
|
const row = (key, label, lo, hi) => `<div class="drow"><span>${t('des_' + label)}</span>`
|
|
+ `<input type="range" data-k="${key}" min="${lo}" max="${hi}" step="0.05" value="${b.body[key] || 1}">`
|
|
+ `<span class="dv" id="dv_${key}">${Math.round((b.body[key] || 1) * 100)}%</span></div>`;
|
|
// collapsed by default: only the header; click the title to expand the three sliders
|
|
el.innerHTML = `<div class="dh"><span class="dtitle" id="dToggle"><span class="caret">${designerOpen ? '▾' : '▸'}</span>${t('s_body')}</span>${designerOpen ? `<button id="dReset">${t('des_reset')}</button>` : ''}</div>`
|
|
+ (designerOpen ? row('hx', 'height', 0.7, 1.6) + row('wx', 'width', 0.8, 1.4) + row('lx', 'length', 0.8, 1.3) : '');
|
|
$('dToggle').onclick = () => { designerOpen = !designerOpen; opt.sfx.click(); renderDesigner(); };
|
|
if (!designerOpen) return;
|
|
el.querySelectorAll('input[type=range]').forEach(inp => {
|
|
inp.oninput = () => {
|
|
b.body[inp.dataset.k] = +inp.value;
|
|
$('dv_' + inp.dataset.k).textContent = Math.round(inp.value * 100) + '%';
|
|
opt.onSave(); opt.onPreview(b); // live 3D while dragging
|
|
};
|
|
inp.onchange = () => render(); // on release: refresh weight bar + stats
|
|
});
|
|
$('dReset').onclick = () => { b.body = { hx: 1, wx: 1, lx: 1 }; opt.sfx.click(); opt.onSave(); opt.onPreview(b); render(); };
|
|
}
|
|
|
|
// top mode tabs: Parts / Paint / Hangar
|
|
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(); }; });
|
|
$('buildView').classList.toggle('hide', topTab !== 'build');
|
|
$('paintView').classList.toggle('hide', topTab !== 'paint');
|
|
$('hangarView').classList.toggle('hide', topTab !== 'hangar');
|
|
if (topTab === 'hangar' && opt.onHangarView) opt.onHangarView($('hangarView'));
|
|
}
|
|
function setTab(k) { topTab = k; renderTopTabs(); }
|
|
|
|
// 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 => {
|
|
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 => {
|
|
if (e.target.dataset.rm) { const s = e.target.dataset.rm; opt.getSave().build[s] = null; opt.sfx.click(); opt.onSave(); opt.onBuild(); render(); return; }
|
|
slot = el.dataset.goto; sel = opt.getSave().build[slot] || null; topTab = 'build'; opt.sfx.click(); render();
|
|
}; });
|
|
}
|
|
|
|
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, setTab, reset() { sel = undefined; topTab = 'build'; } };
|
|
};
|
|
})(window);
|