Files
Robot-Clash/game/eco.js
Benjamin Oezcan 85a19ba242 feat(net)!: client on server-run fights, websocket lobby, server economy (P1-5, P1-6, P1-7, P2-3, P2-4)
- net.js: REST + one WebSocket with reconnect; single-flight refresh shared across tabs; ?slot=N
- lobby.js / netfight.js: server owns presence, challenges and the fight; client shows snapshots
- game.js: every workshop change goes through RC.Eco via act() (server-checked online);
  results, rewards and achievements come from the server (match.end)
- ranking/live/cloudsave on the new REST endpoints; online tournament removed until P2-6

BREAKING CHANGE: needs the new server (protocol v1); old online saves are not migrated.
2026-11-19 02:09:07 +01:00

208 lines
11 KiB
JavaScript

/* Robot Clash - workshop economy rules, shared by client and server. No DOM.
The client applies an action at once (snappy UI); in online play the server applies the SAME action
to its own copy of the save and is the authority (its result replaces the client's economy fields).
RC.Eco.apply(save, action) -> { ok, error } mutates save only when ok
action.type: buy | sell | equip | weaponAdd | weaponRemove | weaponPlace | body |
robotNew | robotDelete | robotSwitch | rename | devCoins (server: admins only)
RC.Eco.sellValue(partId) -> credits back when selling (starter kit = 0, else 50 %)
RC.Eco.pvpReward(o) -> { money, fame, lines:[[key, amount]] } for a live PvP fight
RC.Eco.applyReward(save, r, o)
RC.Eco.newOnlineSave() -> the economy part of a fresh online save
RC.Eco.ECONOMY / COSMETIC which save fields belong to whom (server keeps economy, merges cosmetics)
save shape (same as game.js): { money, fame, owned:[partId], robots:[{ name, build, paint }], active,
build/paint/robotName mirror robots[active] (same objects) }. */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const SELL = 0.5;
const MAX_ROBOTS = 6;
const BODY = { hx: [0.7, 1.6], wx: [0.8, 1.4], lx: [0.8, 1.3] };
const MAX_DECAL = 400 * 1024; // chars of the PNG data URL
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
const num = v => typeof v === 'number' && Number.isFinite(v);
const err = e => ({ ok: false, error: e });
const OK = { ok: true };
const starterIds = () => Object.values(RC.STARTER).filter(Boolean);
// the free starter kit sells for nothing - otherwise "new robot -> sell its starter parts" prints money
const sellValue = id => {
const p = RC.PARTS[id]; if (!p) return 0;
return starterIds().includes(id) ? 0 : Math.round(p.cost * SELL);
};
const starterBuild = () => {
const b = Object.assign({}, RC.STARTER);
b.weapons = RC.weaponsOf(b).map(w => ({ id: w.id, side: w.side || 'front', up: w.up || 0 }));
delete b.weapon; delete b.mount;
return b;
};
const newRobot = name => ({ name: name || 'Robot', build: starterBuild(), paint: { body: 0xff7a1a, accent: 0x15171b, decal: null, drawn: false } });
function newOnlineSave() {
const r = newRobot('Clank');
return { money: 800, fame: 0, best: 0, games: 0, wins: 0, losses: 0, owned: starterIds(), robots: [r], active: 0,
build: r.build, paint: r.paint, robotName: r.name };
}
// keep the live mirror fields pointing at the active robot
function mirror(save) {
const a = save.robots[save.active];
save.build = a.build; save.paint = a.paint; save.robotName = a.name;
}
const cur = save => save.robots[save.active].build;
const usedAnywhere = (save, id) => save.robots.some(r => RC.SLOTS.some(sl => sl !== 'weapon' && r.build[sl] === id));
const cleanName = n => Array.from(String(n || '')).filter(c => c.charCodeAt(0) >= 32 && c !== '<' && c !== '>').join('').trim().slice(0, 18);
const ACTIONS = {
buy(save, a) {
const p = RC.PARTS[a.part];
if (!p || p.slot === 'weapon') return err('BAD_PART');
if (save.owned.includes(a.part)) return err('OWNED');
if (save.money < p.cost) return err('NO_MONEY');
save.money -= p.cost; save.owned.push(a.part); cur(save)[p.slot] = a.part;
return OK;
},
sell(save, a) {
const p = RC.PARTS[a.part];
if (!p || p.slot === 'weapon' || !save.owned.includes(a.part)) return err('NOT_OWNED');
if (usedAnywhere(save, a.part)) return err('IN_USE');
save.owned = save.owned.filter(x => x !== a.part); save.money += sellValue(a.part);
return OK;
},
equip(save, a) {
if (!RC.SLOTS.includes(a.slot) || a.slot === 'weapon') return err('BAD_SLOT');
if (a.part == null) { if (RC.REQUIRED[a.slot]) return err('REQUIRED'); cur(save)[a.slot] = null; return OK; }
const p = RC.PARTS[a.part];
if (!p || p.slot !== a.slot) return err('BAD_PART');
if (!save.owned.includes(a.part)) return err('NOT_OWNED');
cur(save)[a.slot] = a.part;
return OK;
},
weaponAdd(save, a) {
const p = RC.PARTS[a.part], b = cur(save);
if (!p || p.slot !== 'weapon') return err('BAD_PART');
b.weapons = b.weapons || [];
if (b.weapons.length >= RC.MAX_WEAPONS) return err('MAX_WEAPONS');
if (save.money < p.cost) return err('NO_MONEY');
save.money -= p.cost; b.weapons.push({ id: a.part, side: 'front', up: 0 });
return OK;
},
weaponRemove(save, a) {
const b = cur(save), w = b.weapons && b.weapons[a.index];
if (!Number.isInteger(a.index) || !w) return err('BAD_INDEX');
b.weapons.splice(a.index, 1); save.money += sellValue(w.id);
return OK;
},
weaponPlace(save, a) {
const w = cur(save).weapons && cur(save).weapons[a.index];
if (!Number.isInteger(a.index) || !w) return err('BAD_INDEX');
if (a.side !== undefined) { if (!RC.MOUNTS[a.side]) return err('BAD_SIDE'); w.side = a.side; }
if (a.up !== undefined) { if (!num(a.up)) return err('BAD_UP'); w.up = clamp(a.up, -0.3, 0.6); }
return OK;
},
body(save, a) {
const keys = Object.keys(BODY).filter(k => a[k] !== undefined);
if (keys.some(k => !num(a[k]))) return err('BAD_BODY'); // validate everything before changing anything
const b = cur(save); b.body = Object.assign({ hx: 1, wx: 1, lx: 1 }, b.body);
for (const k of keys) b.body[k] = clamp(a[k], BODY[k][0], BODY[k][1]);
return OK;
},
robotNew(save, a) {
if (save.robots.length >= MAX_ROBOTS) return err('HANGAR_FULL');
for (const id of starterIds()) if (!save.owned.includes(id)) save.owned.push(id); // the kit comes with the frame
save.robots.push(newRobot(cleanName(a.name) || 'Robot ' + (save.robots.length + 1)));
save.active = save.robots.length - 1; mirror(save);
return OK;
},
robotDelete(save, a) {
if (save.robots.length <= 1) return err('LAST_ROBOT');
if (!Number.isInteger(a.index) || !save.robots[a.index]) return err('BAD_INDEX');
const i = a.index;
save.robots.splice(i, 1);
// robots after the deleted one move up; deleting the active one keeps the slot number (next robot)
save.active = clamp(save.active > i ? save.active - 1 : save.active, 0, save.robots.length - 1); mirror(save);
return OK;
},
robotSwitch(save, a) {
if (!Number.isInteger(a.index) || !save.robots[a.index]) return err('BAD_INDEX');
save.active = a.index; mirror(save);
return OK;
},
rename(save, a) {
const n = cleanName(a.name);
if (!n) return err('BAD_NAME');
save.robots[save.active].name = n; save.robotName = n;
return OK;
},
devCoins(save, a) {
if (!num(a.money)) return err('BAD_MONEY');
save.money = clamp(Math.round(a.money), 0, 1e9);
return OK;
},
};
function apply(save, action) {
if (!action || typeof action !== 'object' || !Object.prototype.hasOwnProperty.call(ACTIONS, action.type)) return err('BAD_ACTION');
if (!save || !Array.isArray(save.robots) || !save.robots[save.active]) return err('BAD_SAVE');
return ACTIONS[action.type](save, action);
}
// ---- live PvP rewards: prize (win) / half (draw) / appearance fee (loss) + KO/pit bonus + damage bonus
// - repairs (can never take you below 0); fame on a win/draw. Lines carry i18n keys for the client.
const PVP = 600;
function pvpReward(o) {
const lines = [];
let money = 0, fame = 0;
const draw = o.winner === -1, won = o.won;
if (won) { money += PVP; lines.push(['r_prize', PVP]); fame = 150 + (o.reason === 'ko' ? 40 : o.reason === 'pit' ? 60 : 0); }
else if (draw) { money += PVP / 2; lines.push(['r_draw_prize', PVP / 2]); fame = 40; }
else { const ap = Math.round(PVP * 0.35); money += ap; lines.push(['r_appearance', ap]); }
if (won && o.reason !== 'time') { const b = Math.round(PVP * (o.reason === 'pit' ? 0.3 : 0.2)); money += b; lines.push(['r_bonus_' + o.reason, b]); }
const db = Math.round((o.dealt || 0) * 0.6);
if (db) { money += db; lines.push(['r_dmg_bonus', db]); }
const mul = num(o.prizeMul) && o.prizeMul > 0 ? o.prizeMul : 1;
if (mul !== 1 && money > 0) { const bonus = Math.round(money * mul) - money; if (bonus) { money += bonus; lines.push(['event_bonus', bonus]); } }
const repair = Math.round((1 - (o.hp || 0) / (o.maxHp || 1)) * (o.value || 0) * 0.06);
const paid = Math.max(0, Math.min(repair, (o.money || 0) + money));
if (paid) { money -= paid; lines.push(['r_repair', -paid]); }
return { money, fame, lines, won: !!won, draw };
}
function applyReward(save, r) {
save.money = clamp(Math.round(save.money + r.money), 0, 1e9);
save.fame = clamp(Math.round(save.fame + r.fame), 0, 1e9);
save.games = (save.games | 0) + 1;
if (r.won) save.wins = (save.wins | 0) + 1; else if (!r.draw) save.losses = (save.losses | 0) + 1;
if (save.fame > (save.best | 0)) save.best = save.fame;
}
// which fields of a save the server owns (economy) vs. takes from the client as they are (cosmetics)
const ECONOMY = ['money', 'fame', 'best', 'games', 'wins', 'losses', 'owned', 'robots', 'active', 'build', 'paint', 'robotName', 'ach'];
const COSMETIC = ['ts', 'flag', 'flagSet', 'tutorialSeen', 'paintSlots', 'paintSlot', 'unlockedPaints', 'unlockedSchemes', 'cls'];
const isColor = v => Number.isInteger(v) && v >= 0 && v <= 0xffffff;
// robot name / paint are cosmetic too, but live inside robots[] -> merged per robot, never adds or removes robots
function mergeCosmetics(save, incoming) {
if (!incoming || typeof incoming !== 'object') return;
for (const k of COSMETIC) if (incoming[k] !== undefined && JSON.stringify(incoming[k]).length < 64 * 1024) save[k] = incoming[k];
const rs = Array.isArray(incoming.robots) ? incoming.robots : [];
rs.forEach((r, i) => {
const mine = save.robots[i]; if (!mine || !r) return;
const n = cleanName(r.name); if (n) mine.name = n;
const p = r.paint;
if (p && typeof p === 'object') {
if (isColor(p.body)) mine.paint.body = p.body;
if (isColor(p.accent)) mine.paint.accent = p.accent;
if (p.decal === null || (typeof p.decal === 'string' && p.decal.startsWith('data:image/png;base64,') && p.decal.length <= MAX_DECAL)) mine.paint.decal = p.decal;
mine.paint.drawn = !!p.drawn;
}
});
mirror(save);
}
RC.Eco = { apply, sellValue, pvpReward, applyReward, newOnlineSave, newRobot, starterBuild, mergeCosmetics, mirror,
ECONOMY, COSMETIC, MAX_ROBOTS, SELL, PVP };
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);