Files
Robot-Clash/game/cloudsave.js

53 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

/* 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).
2026-11-18 15:18:38 +01:00
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.
2026-11-18 15:18:38 +01:00
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)
2026-11-18 15:18:38 +01:00
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;
2026-11-18 15:18:38 +01:00
const clone = s => { try { return JSON.parse(JSON.stringify(s)); } catch (e) { return null; } };
async function write(save) {
2026-11-18 15:18:38 +01:00
sending = true;
try { await net.api('PUT', '/api/campaign', save); } catch (e) { /* best effort */ }
2026-11-18 15:18:38 +01:00
sending = false;
if (pending) { const s = pending; pending = null; write(s); }
2026-11-18 15:18:38 +01:00
}
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);
2026-11-18 15:18:38 +01:00
}
return {
newer,
async pull() {
if (!net || !net.enabled) return null;
try { return await net.api('GET', '/api/campaign'); } catch (e) { return null; }
2026-11-18 15:18:38 +01:00
},
push(save) { clearTimeout(timer); const snap = clone(save); timer = setTimeout(() => doPush(snap), 2500); },
flush(save) { clearTimeout(timer); doPush(clone(save)); },
2026-11-18 15:18:38 +01:00
};
};
RC.CloudSave.newer = newer;
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
})(typeof window !== 'undefined' ? window : globalThis);