Files
Robot-Clash/game/cloudsave.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

53 lines
2.2 KiB
JavaScript

/* Robot Clash - cloud copy of the offline CAMPAIGN for registered accounts (no DOM). Needs net.js.
The online game does not use this: its save lives on the server (server/economy.js).
The campaign still lives in localStorage (fast cache); with a real account it is mirrored to
/api/campaign so it survives a device change. Client-trusted - it is the offline game.
const cloud = RC.CloudSave(net);
cloud.pull() -> the cloud save object, or null (best effort, never throws)
cloud.push(save) -> debounced write (~2.5 s after the last change)
cloud.flush(save) -> write now (fight result, leaving garage, logout, unload)
RC.CloudSave.newer(cloud, local) -> true if the cloud copy should win (by ts) */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
// cloud wins when it is at least as new as local (shared copy is the source once it exists)
function newer(cloud, local) {
if (!cloud || typeof cloud !== 'object') return false;
const ct = +cloud.ts || 0, lt = (local && +local.ts) || 0;
return ct >= lt;
}
RC.CloudSave = function (net) {
let timer = null, sending = false, pending = null;
const clone = s => { try { return JSON.parse(JSON.stringify(s)); } catch (e) { return null; } };
async function write(save) {
sending = true;
try { await net.api('PUT', '/api/campaign', save); } catch (e) { /* best effort */ }
sending = false;
if (pending) { const s = pending; pending = null; write(s); }
}
function doPush(save) {
if (!net || !net.enabled || !save) return;
if (sending) { pending = save; return; } // one request at a time; keep only the latest
write(save);
}
return {
newer,
async pull() {
if (!net || !net.enabled) return null;
try { return await net.api('GET', '/api/campaign'); } catch (e) { return null; }
},
push(save) { clearTimeout(timer); const snap = clone(save); timer = setTimeout(() => doPush(snap), 2500); },
flush(save) { clearTimeout(timer); doPush(clone(save)); },
};
};
RC.CloudSave.newer = newer;
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);