Files
Robot-Clash/game/workshop.js
Benjamin Oezcan 4535ac7d8a refactor(game): split game.js into sfx, pages, online and workshop modules (P4-5)
Modules are classic-script factories RC.Game<Part>(G); G gives live access to the shared state.
Guarded by new browser tests for every moved page and workshop tool (tests/e2e/screens.spec.js).
2026-11-19 09:58:53 +01:00

197 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Robot Clash - workshop extras: weapon/shape editor, paint tab with paint slots, hangar (several robots).
Part of game.js (split for size): created once by game.js with the shared context G.
Live state (save, mode, F, ...) is read as G.<name>; services/helpers are taken from G at creation. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
RC.GameWorkshop = function (G) {
const {
$, GLYPH_SLOT, MAX_ROBOTS, SFX, act, esc, hud, layer, paintObj, painter, persist, shop, syncActive, t,
weaponName
} = G;
// ---- weapon/shape editor: rendered inside the shop's #cards (tabs stay visible), robot held still ----
function refreshEditorRobot() { G.view.showGarage(G.save.build, paintObj()); G.view.freeze(true); G.view.setEditWeapon(G.editSel); }
function reDrawEditor() { persist(); hud(); refreshEditorRobot(); shop.render(); } // after a change: 3D + tabs + meters + editor
// weapon detail chips (mirrors the shop's part chips, weapon stats only)
function wChips(p) {
const s = [];
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 class="key">⌨ ${t('hk_weapon')}</span>`);
s.push(`<span>⚖️ ${p.weight} kg</span>`);
if (p.power) s.push(`<span>⚡ ${p.power}</span>`);
return s.join('');
}
// show the clicked weapon live on the robot (a mounted one, else a temporary front preview)
function previewWeapon(id) {
const weps = G.save.build.weapons || [];
const idx = weps.findIndex(w => w.id === id);
if (idx >= 0) { G.editSel = idx; refreshEditorRobot(); }
else {
const pv = Object.assign({}, G.save.build, { weapons: weps.concat([{ id, side: 'front', up: 0 }]) });
G.view.showGarage(pv, paintObj()); G.view.freeze(true); G.view.setEditWeapon(weps.length);
}
}
function renderWeaponEditor() {
const cards = $('cards'), wp = $('wplace'); if (!G.save || !cards) return;
const b = G.save.build, weps = b.weapons || [];
G.editSel = Math.min(G.editSel, Math.max(0, weps.length - 1));
const cat = RC.partsFor('weapon');
const canAdd = weps.length < RC.MAX_WEAPONS;
if (!G.wPrev || !RC.PARTS[G.wPrev]) G.wPrev = (weps[G.editSel] && weps[G.editSel].id) || cat[0].id;
// right (#cards): the weapon catalog, same card grid as the other slots — click = preview
cards.className = '';
cards.innerHTML = cat.map(p => {
const mounted = weps.filter(w => w.id === p.id).length;
const badge = mounted ? `<span class="badge own">×${mounted}</span>` : '';
const price = `<div class="pr ${G.save.money < p.cost ? 'no' : ''}">🪙 ${Kit.fmt(p.cost)}</div>`;
return `<div class="item ${p.id === G.wPrev ? 'sel' : ''}" data-prev="${p.id}">${badge}${RC.pic('part_' + p.id, GLYPH_SLOT.weapon)}<div class="nm">${p.name}</div>${price}</div>`;
}).join('');
cards.querySelectorAll('[data-prev]').forEach(x => x.onclick = () => { G.wPrev = x.dataset.prev; SFX.click(); previewWeapon(G.wPrev); renderWeaponEditor(); });
// detail panel: previewed weapon + Montieren / Entfernen (like the other slots)
const dp = $('detail'), pv = RC.PARTS[G.wPrev];
if (dp && pv) {
const mounted = weps.filter(w => w.id === G.wPrev).length, poor = G.save.money < pv.cost;
let act = `<button class="primary" data-wact="add" ${(!canAdd || poor) ? 'disabled' : ''}>${t('buy', { n: Kit.fmt(pv.cost) })}</button>`;
if (mounted) act += `<button data-wact="rem">${t('sell', { n: Kit.fmt(RC.Eco.sellValue(G.wPrev)) })}</button>`;
if (!canAdd) act += `<span class="muted">${t('ed_max', { n: RC.MAX_WEAPONS })}</span>`;
dp.innerHTML = `${RC.pic('part_' + G.wPrev, GLYPH_SLOT.weapon)}
<div><div class="nm">${pv.name}${mounted ? ` <span class="badge own">×${mounted}</span>` : ''}</div>
<div class="ds">${t('pd_' + G.wPrev)}</div><div class="chips">${wChips(pv)}</div></div>
<div class="act">${act}</div>`;
dp.querySelectorAll('button[data-wact]').forEach(x => x.onclick = () => {
if (x.dataset.wact === 'add') addWeapon(G.wPrev);
else { const i = weps.map(w => w.id).lastIndexOf(G.wPrev); if (i >= 0) removeWeapon(i); }
});
}
// left (#wplace): placement of the active mounted weapon + shape (no sell list)
if (wp) {
const sel = weps[G.editSel];
const sides = [['front', t('mt_front')], ['back', t('mt_back')], ['left', t('mt_left')], ['right', t('mt_right')]];
const srow = (key, label, lo, hi) => { const val = (b.body && b.body[key]) || 1; return `<div class="wprow"><span>${t('des_' + label)}</span><input type="range" data-body="${key}" min="${lo}" max="${hi}" step="0.05" value="${val}"><span class="dv">${Math.round(val * 100)}%</span></div>`; };
wp.classList.remove('hide');
wp.innerHTML =
`<div class="wphead">${t('ed_weapons')} ${weps.length}/${RC.MAX_WEAPONS}</div>`
+ (sel ? `<div class="wphead">${t('ed_place')} — ${RC.PARTS[sel.id].name}</div>`
+ `<div class="wpsides">${sides.map(([k, lb]) => `<button data-side="${k}" class="${sel.side === k ? 'on' : ''}">${lb}</button>`).join('')}</div>`
+ `<div class="wprow"><span>${t('des_height')}</span><input type="range" id="edUp" min="-0.3" max="0.6" step="0.05" value="${sel.up || 0}"><span class="dv">${Math.round(((sel.up || 0) + 0.3) / 0.9 * 100)}%</span></div>`
: `<span class="edhint">${t('ed_noweapons')}</span>`)
+ `<div class="wphead">${t('s_body')}</div>${srow('hx', 'height', 0.7, 1.6)}${srow('wx', 'width', 0.8, 1.4)}${srow('lx', 'length', 0.8, 1.3)}`;
wp.querySelectorAll('[data-side]').forEach(x => x.onclick = () => { if (!sel) return; act({ type: 'weaponPlace', index: G.editSel, side: x.dataset.side }); SFX.click(); reDrawEditor(); });
if ($('edUp')) $('edUp').oninput = e => { if (sel) { sel.up = +e.target.value; refreshEditorRobot(); } }; // live preview while dragging
if ($('edUp')) $('edUp').onchange = e => { if (sel) act({ type: 'weaponPlace', index: G.editSel, up: +e.target.value }); reDrawEditor(); };
wp.querySelectorAll('[data-body]').forEach(x => {
x.oninput = e => { b.body = b.body || { hx: 1, wx: 1, lx: 1 }; b.body[e.target.dataset.body] = +e.target.value; refreshEditorRobot(); };
x.onchange = e => { act({ type: 'body', [e.target.dataset.body]: +e.target.value }); reDrawEditor(); };
});
}
if (weps[G.editSel] && weps[G.editSel].id === G.wPrev) G.view.setEditWeapon(G.editSel);
}
function addWeapon(id) {
if (!act({ type: 'weaponAdd', part: id }).ok) { SFX.deny(); return; }
G.editSel = G.save.build.weapons.length - 1; G.wPrev = id; G.view.setEditWeapon(G.editSel);
SFX.buy(); reDrawEditor();
}
function removeWeapon(i) {
if (!act({ type: 'weaponRemove', index: i }).ok) { SFX.deny(); return; }
if (G.editSel >= G.save.build.weapons.length) G.editSel = Math.max(0, G.save.build.weapons.length - 1);
G.view.setEditWeapon(G.editSel);
SFX.buy(); reDrawEditor();
}
// ---- paint tab: 3 save slots + quick colours + the inline painter (all inside #cards) ----
const phex = c => '#' + (c >>> 0).toString(16).padStart(6, '0');
function paintTab(el) {
let hdr = $('paintHdr');
if (!hdr) { el.innerHTML = ''; hdr = document.createElement('div'); hdr.id = 'paintHdr'; hdr.className = 'phdr'; el.appendChild(hdr); }
$('shop').classList.add('paintmode'); // hide category tabs / detail / fitted bar while painting
renderPaintHeader(hdr);
if (!painter.isOpen) painter.open(el); // mount the painter inline, below the header
}
function paintLeave() {
$('shop').classList.remove('paintmode');
if (!painter.isOpen) return;
const art = painter.hasArt();
G.save.paint.decal = art ? layer.toDataURL('image/png') : null; G.save.paint.drawn = art;
painter.close(); persist();
const hdr = $('paintHdr'); if (hdr) hdr.remove();
}
function renderPaintHeader(hdr) {
const slots = G.save.paintSlots || [];
hdr.innerHTML =
`<div class="pslots">${slots.map((s, i) => `<div class="pslot ${i === G.save.paintSlot ? 'on' : ''}" data-load="${i}" style="background:${phex(s.body)}"><i class="acc" style="background:${phex(s.accent)}"></i>${s.decal ? '<span class="dmark">🖌</span>' : ''}<button class="sv" data-save="${i}">💾</button></div>`).join('')}</div>`
+ `<div class="psec"><h4>${t('paint_body')}</h4><div class="pgrid" id="paintBody"></div></div>`
+ `<div class="psec"><h4>${t('paint_accent')}</h4><div class="pgrid" id="paintAccent"></div></div>`
+ `<div class="psec"><h4>${t('paint_schemes')}</h4><div class="pgrid wide" id="paintSchemes"></div></div>`;
const lockP = c => (RC.PAINT_REWARDS || []).includes(c) && !(G.save.unlockedPaints || []).includes(c); // reward colour, not earned yet
for (const [id, key] of [['paintBody', 'body'], ['paintAccent', 'accent']]) {
$(id).innerHTML = RC.PAINTS.map(c => `<span class="sw ${G.save.paint[key] === c ? 'on' : ''} ${lockP(c) ? 'locked' : ''}" data-c="${c}" style="background:${phex(c)}" title="${lockP(c) ? t('paint_locked') : ''}">${lockP(c) ? '<span class="lk">🔒</span>' : ''}</span>`).join('');
$(id).querySelectorAll('.sw').forEach(sw => sw.onclick = () => { if (sw.classList.contains('locked')) { SFX.deny && SFX.deny(); return; } G.save.paint[key] = +sw.dataset.c; SFX.click(); persist(); G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
}
$('paintSchemes').innerHTML = RC.SCHEMES.map(([b2, a2]) => { const on = G.save.paint.body === b2 && G.save.paint.accent === a2; return `<span class="sw duo ${on ? 'on' : ''}" data-b="${b2}" data-a="${a2}"><i style="background:${phex(b2)}"></i><i style="background:${phex(a2)}"></i></span>`; }).join('');
$('paintSchemes').querySelectorAll('.sw').forEach(sw => sw.onclick = () => { G.save.paint.body = +sw.dataset.b; G.save.paint.accent = +sw.dataset.a; SFX.click(); persist(); G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); renderPaintHeader(hdr); });
hdr.querySelectorAll('[data-load]').forEach(x => x.onclick = e => { if (e.target.dataset.save) return; loadPaintSlot(+x.dataset.load); });
hdr.querySelectorAll('[data-save]').forEach(x => x.onclick = e => { e.stopPropagation(); savePaintSlot(+x.dataset.save); });
}
function loadPaintSlot(i) {
const s = G.save.paintSlots[i]; if (!s) return;
G.save.paintSlot = i;
G.save.paint.body = s.body; G.save.paint.accent = s.accent; G.save.paint.decal = s.decal || null; G.save.paint.drawn = !!s.drawn;
SFX.click(); persist();
RC.layerFromData(layer, G.save.paint.decal, () => { G.view.showGarage(G.save.build, paintObj()); if (painter.sync) painter.sync(); });
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
}
function savePaintSlot(i) {
const art = painter.hasArt();
G.save.paintSlots[i] = { body: G.save.paint.body, accent: G.save.paint.accent, decal: art ? layer.toDataURL('image/png') : (G.save.paint.decal || null), drawn: art || !!G.save.paint.drawn };
G.save.paintSlot = i; SFX.buy(); persist();
const hdr = $('paintHdr'); if (hdr) renderPaintHeader(hdr);
}
// hangar: switch / add / delete robot slots (owned parts are shared)
function switchRobot(i) {
if (i === G.save.active || !G.save.robots[i]) return;
syncActive();
if (!act({ type: 'robotSwitch', index: i }).ok) return;
persist();
RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); });
shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar();
}
function addRobot() {
syncActive();
if (!act({ type: 'robotNew', name: t('robot_n', { n: G.save.robots.length + 1 }) }).ok) { SFX.deny(); return; }
persist();
RC.layerFromData(layer, G.save.paint.decal, () => { if (G.mode === 'garage') G.view.showGarage(G.save.build, paintObj()); });
shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar();
SFX.buy();
}
function delRobot(i) {
syncActive();
if (!act({ type: 'robotDelete', index: i }).ok) { SFX.deny(); return; }
persist(); RC.layerFromData(layer, G.save.paint.decal, () => {}); shop.reset(); shop.render(); G.view.showGarage(G.save.build, paintObj()); renderHangar();
}
// hangar management (shop top-tab): list of robots with weapon, switch / delete + add button
function renderHangar(el) {
el = el || $('cards'); if (!el) return;
const rows = G.save.robots.map((r, i) => `<div class="hmrow ${i === G.save.active ? 'on' : ''}" data-i="${i}">
<div><div class="hmn">${esc(r.name)}</div><div class="hmw">${esc(weaponName(r.build))}</div></div>
${i === G.save.active ? `<span class="muted" style="font-size:12px">${t('active_robot')}</span>` : `<button data-use="${i}">${t('use')}</button>`}
${G.save.robots.length > 1 ? `<button data-del="${i}" title="${t('delete')}">✕</button>` : '<span></span>'}</div>`).join('');
el.innerHTML = `<div class="hmgr">${rows}</div>
${G.save.robots.length < MAX_ROBOTS ? `<button class="primary" id="hAdd" style="margin-top:8px">+ ${t('new_robot')}</button>` : `<p class="muted" style="margin-top:8px">${t('hangar_full')}</p>`}`;
el.querySelectorAll('[data-use]').forEach(b => { b.onclick = () => { SFX.click(); switchRobot(+b.dataset.use); shop.setTab('build'); } ; });
el.querySelectorAll('[data-del]').forEach(b => { b.onclick = () => { SFX.click(); delRobot(+b.dataset.del); renderHangar(); } ; });
if ($('hAdd')) $('hAdd').onclick = () => { addRobot(); shop.setTab('build'); };
}
return {
refreshEditorRobot, reDrawEditor, wChips, previewWeapon, renderWeaponEditor, addWeapon, removeWeapon,
phex, paintTab, paintLeave, renderPaintHeader, loadPaintSlot, savePaintSlot, switchRobot, addRobot,
delRobot, renderHangar
};
};
})(window);