/* 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. */ 'use strict'; const RC = require('../game/robot.js'); // pulls in parts.js, sets globalThis.RC require('../game/eco.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 } function putCosmetics(uid, incoming) { const s = load(uid); Eco.mergeCosmetics(s, incoming); store(uid, s); return view(s); } // 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); store(uid, s); return Object.assign(r, { 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 };