feat(shop): shared economy rules for client and server (P2-2)
This commit is contained in:
207
game/eco.js
Normal file
207
game/eco.js
Normal file
@@ -0,0 +1,207 @@
|
||||
/* 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'];
|
||||
const COSMETIC = ['flag', 'flagSet', 'tutorialSeen', 'ach', '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);
|
||||
128
tests/eco.test.js
Normal file
128
tests/eco.test.js
Normal file
@@ -0,0 +1,128 @@
|
||||
'use strict';
|
||||
const { test } = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const path = require('path');
|
||||
for (const f of ['parts.js', 'robot.js', 'eco.js']) require(path.join(__dirname, '..', 'game', f));
|
||||
const RC = globalThis.RC;
|
||||
const E = RC.Eco;
|
||||
|
||||
const fresh = () => E.newOnlineSave();
|
||||
const anyPart = (slot, notIn = []) => Object.values(RC.PARTS).find(p => p.slot === slot && !notIn.includes(p.id) && !Object.values(RC.STARTER).includes(p.id));
|
||||
|
||||
test('fresh online save is a valid starter robot with 800 credits', () => {
|
||||
const s = fresh();
|
||||
assert.equal(s.money, 800);
|
||||
assert.ok(RC.validate(s.build).ok);
|
||||
assert.equal(s.build, s.robots[0].build, 'mirror points at the active robot');
|
||||
});
|
||||
|
||||
test('buy: deducts, owns, equips; refuses without money or twice', () => {
|
||||
const s = fresh(), p = anyPart('armour');
|
||||
s.money = p.cost;
|
||||
assert.ok(E.apply(s, { type: 'buy', part: p.id }).ok);
|
||||
assert.equal(s.money, 0);
|
||||
assert.ok(s.owned.includes(p.id));
|
||||
assert.equal(s.build.armour, p.id);
|
||||
assert.equal(E.apply(s, { type: 'buy', part: p.id }).error, 'OWNED');
|
||||
const q = anyPart('armour', [p.id]);
|
||||
assert.equal(E.apply(s, { type: 'buy', part: q.id }).error, 'NO_MONEY');
|
||||
assert.equal(E.apply(s, { type: 'buy', part: 'nope' }).error, 'BAD_PART');
|
||||
});
|
||||
|
||||
test('sell: 50 %, never while fitted on any robot, starter kit sells for 0', () => {
|
||||
const s = fresh(), p = anyPart('armour');
|
||||
s.money = 10000;
|
||||
E.apply(s, { type: 'buy', part: p.id });
|
||||
assert.equal(E.apply(s, { type: 'sell', part: p.id }).error, 'IN_USE');
|
||||
E.apply(s, { type: 'equip', slot: 'armour', part: null });
|
||||
const before = s.money;
|
||||
assert.ok(E.apply(s, { type: 'sell', part: p.id }).ok);
|
||||
assert.equal(s.money - before, Math.round(p.cost * 0.5));
|
||||
// fitted on a second robot only -> still in use
|
||||
E.apply(s, { type: 'buy', part: p.id });
|
||||
E.apply(s, { type: 'robotNew' });
|
||||
assert.equal(E.apply(s, { type: 'sell', part: p.id }).error, 'IN_USE', 'used by robot 0');
|
||||
assert.equal(E.sellValue(RC.STARTER.chassis), 0);
|
||||
});
|
||||
|
||||
test('exploit closed: new robot -> sell its starter weapon -> delete robot gains nothing', () => {
|
||||
const s = fresh();
|
||||
const start = s.money;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
E.apply(s, { type: 'robotNew' });
|
||||
while (s.build.weapons.length) E.apply(s, { type: 'weaponRemove', index: 0 });
|
||||
E.apply(s, { type: 'robotDelete', index: s.active });
|
||||
}
|
||||
assert.equal(s.money, start);
|
||||
});
|
||||
|
||||
test('equip: only owned parts of the right slot; required slots cannot be emptied', () => {
|
||||
const s = fresh(), p = anyPart('motor');
|
||||
assert.equal(E.apply(s, { type: 'equip', slot: 'motor', part: p.id }).error, 'NOT_OWNED');
|
||||
assert.equal(E.apply(s, { type: 'equip', slot: 'motor', part: null }).error, 'REQUIRED');
|
||||
assert.equal(E.apply(s, { type: 'equip', slot: 'armour', part: RC.STARTER.motor }).error, 'BAD_PART');
|
||||
assert.equal(E.apply(s, { type: 'equip', slot: 'weapon', part: null }).error, 'BAD_SLOT');
|
||||
});
|
||||
|
||||
test('weapons: add costs money, max 3, remove refunds, placement is clamped', () => {
|
||||
const s = fresh(), w = anyPart('weapon');
|
||||
s.money = 1e6;
|
||||
while (s.build.weapons.length < RC.MAX_WEAPONS) assert.ok(E.apply(s, { type: 'weaponAdd', part: w.id }).ok);
|
||||
assert.equal(E.apply(s, { type: 'weaponAdd', part: w.id }).error, 'MAX_WEAPONS');
|
||||
assert.ok(E.apply(s, { type: 'weaponPlace', index: 1, side: 'left', up: 5 }).ok);
|
||||
assert.equal(s.build.weapons[1].side, 'left');
|
||||
assert.equal(s.build.weapons[1].up, 0.6);
|
||||
assert.equal(E.apply(s, { type: 'weaponPlace', index: 1, side: 'top' }).error, 'BAD_SIDE');
|
||||
const m = s.money;
|
||||
assert.ok(E.apply(s, { type: 'weaponRemove', index: 1 }).ok);
|
||||
assert.equal(s.money - m, Math.round(w.cost * 0.5));
|
||||
assert.equal(E.apply(s, { type: 'weaponRemove', index: 9 }).error, 'BAD_INDEX');
|
||||
});
|
||||
|
||||
test('hangar: max 6 robots, keep at least one, active index follows deletes', () => {
|
||||
const s = fresh();
|
||||
for (let i = 1; i < E.MAX_ROBOTS; i++) assert.ok(E.apply(s, { type: 'robotNew', name: 'R' + i }).ok);
|
||||
assert.equal(E.apply(s, { type: 'robotNew' }).error, 'HANGAR_FULL');
|
||||
E.apply(s, { type: 'robotSwitch', index: 4 });
|
||||
E.apply(s, { type: 'robotDelete', index: 1 });
|
||||
assert.equal(s.active, 3);
|
||||
assert.equal(s.robotName, 'R4');
|
||||
assert.equal(s.build, s.robots[s.active].build);
|
||||
while (s.robots.length > 1) E.apply(s, { type: 'robotDelete', index: 0 });
|
||||
assert.equal(E.apply(s, { type: 'robotDelete', index: 0 }).error, 'LAST_ROBOT');
|
||||
});
|
||||
|
||||
test('unknown / malformed actions are refused without changes', () => {
|
||||
const s = fresh(), snap = JSON.stringify(s);
|
||||
assert.equal(E.apply(s, { type: 'toString' }).error, 'BAD_ACTION');
|
||||
assert.equal(E.apply(s, { type: '__proto__' }).error, 'BAD_ACTION');
|
||||
assert.equal(E.apply(s, null).error, 'BAD_ACTION');
|
||||
assert.equal(E.apply(s, { type: 'body', hx: 'x' }).error, 'BAD_BODY');
|
||||
assert.equal(JSON.stringify(s), snap);
|
||||
});
|
||||
|
||||
test('pvpReward: win/draw/loss, bonus, repair never below zero', () => {
|
||||
const win = E.pvpReward({ won: true, winner: 0, reason: 'ko', dealt: 100, hp: 50, maxHp: 100, value: 1000, money: 0 });
|
||||
assert.equal(win.fame, 190);
|
||||
assert.equal(win.money, 600 + 120 + 60 - 30);
|
||||
const loss = E.pvpReward({ won: false, winner: 1, reason: 'ko', dealt: 0, hp: 0, maxHp: 100, value: 1e6, money: 0 });
|
||||
assert.equal(loss.money, 0, 'repair capped at what you have');
|
||||
const draw = E.pvpReward({ won: false, winner: -1, reason: 'time', dealt: 0, hp: 100, maxHp: 100, value: 0 });
|
||||
assert.equal(draw.money, 300);
|
||||
assert.ok(draw.draw);
|
||||
const s = fresh(); E.applyReward(s, win);
|
||||
assert.equal(s.wins, 1); assert.equal(s.games, 1); assert.equal(s.best, 190);
|
||||
});
|
||||
|
||||
test('mergeCosmetics takes names/paint/flags but never economy or robot count', () => {
|
||||
const s = fresh();
|
||||
E.mergeCosmetics(s, { money: 1e9, owned: ['x'], flag: 'DE', robots: [{ name: 'Zed', paint: { body: 0x123456, accent: -5, decal: 'javascript:1' }, build: { chassis: 'x' } }, { name: 'ghost' }] });
|
||||
assert.equal(s.money, 800);
|
||||
assert.equal(s.flag, 'DE');
|
||||
assert.equal(s.robots.length, 1);
|
||||
assert.equal(s.robotName, 'Zed');
|
||||
assert.equal(s.paint.body, 0x123456);
|
||||
assert.equal(s.paint.accent, 0x15171b, 'bad colour ignored');
|
||||
assert.equal(s.paint.decal, null, 'non-PNG decal ignored');
|
||||
assert.equal(s.build.chassis, RC.STARTER.chassis);
|
||||
});
|
||||
Reference in New Issue
Block a user