Files
Robot-Clash/server/economy.js
Benjamin Oezcan dca1032ac4 feat(server)!: websocket lobby, server-run matches, server economy, new schema (P1-2, P1-4, P2-1, P2-1b, P2-5)
Replaces the Firebase-style /db facade (rtdb, rules, nodes tree) with explicit REST endpoints and a
WebSocket hub. Login by name or optional e-mail, seed accounts via npm run db:reset.

BREAKING CHANGE: old clients (lobby/netfight over /db) no longer work against this server; database is new.
2026-11-19 01:52:30 +01:00

61 lines
2.3 KiB
JavaScript

/* 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 };