Files
Robot-Clash/server/economy.js

65 lines
2.7 KiB
JavaScript
Raw Normal View History

/* Server-authoritative online economy. The online save of every player lives here; money, fame, parts and
robots change ONLY through RC.Eco (game/eco.js - the same rules the client runs) or fight rewards. */
2026-11-18 15:18:38 +01:00
'use strict';
const RC = require('../game/robot.js'); // pulls in parts.js, sets globalThis.RC
require('../game/eco.js');
require('../game/progress.js');
const { OnlineSaves, KV } = require('./db');
const Eco = RC.Eco;
function load(uid) {
let s = OnlineSaves.get(uid);
if (!s || !Array.isArray(s.robots) || !s.robots.length) { s = Eco.newOnlineSave(); OnlineSaves.put(uid, s); }
s.active = Math.max(0, Math.min(s.active | 0, s.robots.length - 1));
Eco.mirror(s); // build/paint/robotName point at robots[active] again after JSON
return s;
}
const store = (uid, s) => OnlineSaves.put(uid, s);
// what the client gets: the whole online save (it caches it locally)
const view = s => JSON.parse(JSON.stringify(s));
function action(user, a) {
if (a && a.type === 'devCoins' && !user.admin) return { ok: false, error: 'DENIED' };
const s = load(user.uid);
const r = Eco.apply(s, a);
if (r.ok) store(user.uid, s);
return Object.assign(r, { save: view(s) }); // on error the client resyncs to this
2026-11-18 15:18:38 +01:00
}
function putCosmetics(uid, incoming) {
const s = load(uid);
Eco.mergeCosmetics(s, incoming);
store(uid, s);
return view(s);
2026-11-18 15:18:38 +01:00
}
// the robot a player fights with (validated) + what the lobby shows
function fighter(uid, name) {
const s = load(uid);
const v = RC.validate(s.build);
return {
ok: v.ok, errors: v.errors, uid, name, flag: s.flag || 'XX', fame: s.fame | 0,
build: JSON.parse(JSON.stringify(s.build)), paint: JSON.parse(JSON.stringify(s.paint)), robotName: s.robotName,
};
}
// book a finished live fight; returns { money, fame, lines, save }
function reward(uid, o) {
const s = load(uid);
const live = KV.get('live') || {};
const ev = live.event && live.event.prizeMul && Date.now() >= (live.event.from || 0) && Date.now() <= (live.event.to || Infinity) ? live.event.prizeMul : 1;
const r = Eco.pvpReward(Object.assign({}, o, { money: s.money, prizeMul: ev }));
Eco.applyReward(s, r);
// achievements pay credits -> decided here, never on the client (same rules: game/progress.js)
const ach = RC.Progress.check(s, { won: r.won, reason: o.reason, hpPct: (o.hp || 0) / (o.maxHp || 1), dealt: o.dealt || 0, lost: (o.lost || []).length });
for (const a of ach) s.money = Math.min(1e9, s.money + (a.reward | 0));
store(uid, s);
return Object.assign(r, { ach: ach.map(a => ({ id: a.id, reward: a.reward })), save: view(s) });
}
function ranks(n = 20) { return OnlineSaves.top(Math.max(1, Math.min(100, n | 0))); }
module.exports = { load, action, putCosmetics, fighter, reward, ranks };