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.
This commit is contained in:
Benjamin Oezcan
2026-11-19 02:09:07 +01:00
parent 4bd85f68bf
commit 85a19ba242
13 changed files with 494 additions and 798 deletions

View File

@@ -1,162 +1,64 @@
/* Robot Clash - live PvP sync over an existing deterministic fight. Needs net.js, combat.js, ai.js.
Robot 0 is always the local player, robot 1 the opponent (both clients see it that way, so the host
mirrors indices when it publishes). The lower-uid player is the host (authority): it runs the real
RC.Combat.step and publishes snapshots; the guest renders them and only sends its input.
/* Robot Clash - client side of a server-run live fight. No simulation here: the server steps RC.Combat;
this sends the local input and shows the server's snapshots (already mapped to "robot 0 = me").
const nf = RC.NetFight({ net, id, host, mySeat, oppStyle, oppSkill, onPeerLost(wasHost) });
nf.start()
HOST each tick, instead of the normal step:
nf.hostStep(s, localInput, dt) runs step with [local, remote|AI], publishes ~15 Hz, returns events
GUEST each frame, instead of step:
nf.guestFrame(s, localInput, dt) eases robots toward the last snapshot, returns events to play
nf.peerAlive false once the peer went silent > GRACE (AI takes over)
nf.stop()
mySeat: 0 if I am meta[myUid] rendered as robot 0 (always true locally). The host publishes with robots
ordered [host, guest]; each side maps so that *its* robot is index 0. */
const nf = RC.NetFight({ net, seat })
nf.frame(s, input, dt) send input (on change, max 30/s, at least every 0.25 s), ease the local state toward
the newest snapshot, return the events of snapshots not seen yet
nf.oppAway true while the opponent is disconnected (server tells us)
nf.silentFor seconds since the last snapshot (connection trouble)
nf.stop() */
(function (root) {
'use strict';
const RC = (root.RC = root.RC || {});
const PUB = 1 / 15, GRACE = 4000; // ms without news before the AI covers for the peer
// robot fields the view / HUD / sound read - kept small for the wire
const RF = ['x', 'z', 'a', 'y', 'hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'turretA', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'lost', 'dead', 'out'];
const rnd = v => (typeof v === 'number' ? Math.round(v * 1000) / 1000 : v);
const packRobot = r => { const o = {}; for (const k of RF) o[k] = rnd(r[k]); return o; };
const SEND_MIN = 1 / 30, SEND_KEEP = 0.25;
const EASE = ['x', 'z', 'y'], ANG = ['a', 'turretA'];
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
RC.NetFight = (opt) => {
const net = opt.net, db = net.db, id = opt.id, host = opt.host;
const base = `matches/${id}`;
let pubT = 0, seq = 0, sendT = 0, beatT = 0, lastInSeq = -1, evBuf = [];
let sending = false, slow = 0; // one write at a time; back off while the line is slow
let remoteInput = { throttle: 0, turn: 0, fire: false, fire2: false, fire3: false };
let started = false, lastPeer = Date.now(), peerAlive = true, ai = null, subIn = null, subState = null, subPing = null, lastState = null, stateApplied = -1;
const sock = opt.net.socket, seat = opt.seat;
let latest = null, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
const off = sock.on('snap', m => { latest = RC.Proto.toLocal(seat, m); lastSnap = Date.now(); });
function start() {
if (host) {
// host reads the guest's input stream
subIn = db.stream(`${base}/in`, v => { if (v && typeof v.seq === 'number') { remoteInput = v; lastPeer = Date.now(); } });
} else {
// guest reads the host's state stream
subState = db.stream(`${base}/state`, v => { if (v && typeof v.seq === 'number') { lastState = v; lastPeer = Date.now(); } });
subPing = db.stream(`${base}/ping`, v => { if (v) lastPeer = Date.now(); }); // host alive during the countdown
}
const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3;
function sendInput(inp, dt) {
sendT -= dt; keepT -= dt;
if (sendT > 0 || (!changed(inp) && keepT > 0)) return;
const i = RC.Proto.input(inp);
if (sock.send(Object.assign({ t: 'input', seq: ++seq }, i))) { prev = i; sendT = SEND_MIN; keepT = SEND_KEEP; }
}
function checkPeer() {
if (!started) { started = true; lastPeer = Math.max(lastPeer, Date.now()); } // countdown is over: start the clock
if (!peerAlive && Date.now() - lastPeer < GRACE) { peerAlive = true; if (opt.onPeerBack) opt.onPeerBack(host); }
if (peerAlive && Date.now() - lastPeer > GRACE) {
peerAlive = false;
if (host && !ai) ai = RC.AI.create({ style: opt.oppStyle || 'brawler', skill: opt.oppSkill != null ? opt.oppSkill : 0.5, seed: 7 });
if (opt.onPeerLost) opt.onPeerLost(host);
}
function applyRobot(r, d, k) {
for (const f of EASE) if (typeof d[f] === 'number') r[f] += (d[f] - r[f]) * k;
for (const f of ANG) if (typeof d[f] === 'number') r[f] += wrap(d[f] - r[f]) * k;
for (const f of RC.Proto.RF) if (!EASE.includes(f) && !ANG.includes(f) && d[f] !== undefined) r[f] = d[f];
if (d.lost) r.lost = Object.assign(r.lost || {}, d.lost);
if (d.lostW) r.lostW = d.lostW.slice();
if (d.W && r.W) d.W.forEach((w, i) => { if (r.W[i]) Object.assign(r.W[i], w); });
}
const syncList = (dst, src, def) => { dst.length = src.length; for (let i = 0; i < src.length; i++) dst[i] = Object.assign(dst[i] || Object.assign({}, def), src[i]); };
// HOST: step with [local, guest-or-AI], publish robots as [host, guest] but return a state where
// index 0 is the LOCAL player (so game.js renders identically on both sides).
function hostStep(s, localInput, dt) {
checkPeer();
const guestInput = peerAlive ? remoteInput : ai.think(s, s.robots[1], s.robots[0], dt);
RC.Combat.step(s, dt, [localInput, guestInput]);
if (s.events.length) evBuf.push.apply(evBuf, s.events); // batch events between publishes for the guest
pubT -= dt;
// publish only when the previous write came back - otherwise slow uploads queue up and the host stutters
if (pubT <= 0 && !sending) {
pubT = PUB + slow;
sending = true;
const t0 = Date.now();
const payload = {
seq: ++seq, t: rnd(s.t), left: rnd(s.left), pitOpen: rnd(s.pitOpen), pitAlarm: s.pitAlarm,
press: { st: s.press.st, y: rnd(s.press.y) }, crane: { st: s.crane.st, x: rnd(s.crane.x), z: rnd(s.crane.z), who: s.crane.who },
rockets: s.rockets.map(k => ({ x: rnd(k.x), z: rnd(k.z), y: rnd(k.y), a: rnd(k.a) })),
mines: s.mines.map(k => ({ x: rnd(k.x), z: rnd(k.z), arm: rnd(k.arm) })),
r: [packRobot(s.robots[0]), packRobot(s.robots[1])],
ev: evBuf.slice(-24), result: s.result, endIn: rnd(s.endIn),
};
evBuf.length = 0;
const done = () => {
sending = false;
const ms = Date.now() - t0; // slow line: send less often instead of piling up
slow = ms > 400 ? 0.2 : ms > 180 ? 0.08 : 0;
};
try { Promise.resolve(db.put(`${base}/state`, payload)).then(done, done); } catch (e) { done(); }
}
return s.events;
function frame(s, inp, dt) {
sendInput(inp, dt);
if (!latest) return [];
const n = latest, k = Math.min(1, dt * 14);
s.t = n.time; s.left = n.left; s.pitOpen = n.pitOpen; s.pitAlarm = n.pitAlarm; s.endIn = n.endIn;
s.press.st = n.press.st; s.press.y = n.press.y;
Object.assign(s.crane, n.crane);
syncList(s.rockets, n.rockets, { sp: 6, t: 3 });
syncList(s.mines, n.mines, { r: 0.85 });
applyRobot(s.robots[0], n.robots[0], k);
applyRobot(s.robots[1], n.robots[1], k);
if (n.result) s.result = n.result;
if (n.tick === seenTick) return [];
seenTick = n.tick;
return n.ev || [];
}
// GUEST: no simulation. Ease local robots toward the latest snapshot; snap flags/hp; play its events once.
function guestFrame(s, localInput, dt) {
checkPeer();
// send my input (I am robot 0 locally = guest = snapshot index 1)
sendT -= dt;
beatT -= dt;
// send on change, and at least every 0.5 s as a heartbeat (otherwise the host thinks I am gone)
if (sendT <= 0 && !sending && (changed(localInput) || beatT <= 0)) {
sendT = PUB; beatT = 0.5; lastInSeq++;
sending = true;
const fin = () => { sending = false; };
try {
Promise.resolve(db.put(`${base}/in`, { seq: lastInSeq, throttle: rnd(localInput.throttle || 0), turn: rnd(localInput.turn || 0),
fire: !!localInput.fire, fire2: !!localInput.fire2, fire3: !!localInput.fire3 })).then(fin, fin);
} catch (e) { fin(); }
prevInput = localInput;
}
const ev = [];
if (lastState) {
const snap = lastState;
s.t = snap.t; s.left = snap.left; s.pitOpen = snap.pitOpen; s.pitAlarm = snap.pitAlarm;
s.press.st = snap.press.st; s.press.y = snap.press.y;
s.crane.st = snap.crane.st; s.crane.x = snap.crane.x; s.crane.z = snap.crane.z; s.crane.who = snap.crane.who;
syncRockets(s, snap.rockets);
syncMines(s, snap.mines);
s.result = snap.result; s.endIn = snap.endIn;
// snapshot order [host, guest]; locally guest must be index 0 -> swap
applyRobot(s.robots[0], snap.r[1], dt); // me (guest)
applyRobot(s.robots[1], snap.r[0], dt); // host
if (snap.seq !== stateApplied) {
stateApplied = snap.seq;
for (const e of snap.ev || []) { const c = Object.assign({}, e); if (c.who === 0) c.who = 1; else if (c.who === 1) c.who = 0; ev.push(c); }
}
}
return ev;
}
function applyRobot(r, d, dt) {
if (!d) return;
const k = Math.min(1, dt * 14); // ease position/angle, snap the rest
r.x += (d.x - r.x) * k; r.z += (d.z - r.z) * k; r.y += (d.y - r.y) * k;
r.a += wrap(d.a - r.a) * k;
r.turretA += wrap(d.turretA - r.turretA) * k;
for (const f of ['hp', 'maxHp', 'flipped', 'stun', 'lifted', 'grabbedBy', 'grab', 'spin', 'sawOn', 'flameOn', 'gunOn', 'swing', 'cd', 'cd2', 'boost', 'gcd', 'gUses', 'shield', 'lost', 'dead', 'out']) if (d[f] !== undefined) r[f] = d[f];
}
function syncRockets(s, list) {
list = list || [];
s.rockets.length = list.length;
for (let i = 0; i < list.length; i++) s.rockets[i] = Object.assign(s.rockets[i] || { owner: 1, sp: 6, t: 3 }, list[i]);
}
function syncMines(s, list) {
list = list || [];
s.mines.length = list.length;
for (let i = 0; i < list.length; i++) s.mines[i] = Object.assign(s.mines[i] || { owner: 0, r: 0.85 }, list[i]);
}
let prevInput = null;
function changed(inp) { return !prevInput || inp.throttle !== prevInput.throttle || inp.turn !== prevInput.turn || inp.fire !== prevInput.fire || inp.fire2 !== prevInput.fire2 || inp.fire3 !== prevInput.fire3; }
return {
start, hostStep, guestFrame,
// during the countdown: keep the line alive (guest sends a neutral input, host an empty state ping)
idle(dt) {
sendT -= dt;
if (sendT > 0) return;
sendT = 0.5;
if (host) db.patch(`${base}/ping`, { h: Date.now() });
else { lastInSeq++; db.put(`${base}/in`, { seq: lastInSeq, throttle: 0, turn: 0, fire: false, fire2: false, fire3: false }); }
},
get peerAlive() { return peerAlive; },
stop() { if (subIn) subIn.close(); if (subState) subState.close(); if (subPing) subPing.close(); },
frame,
get oppAway() { return !!(latest && latest.away && latest.away[1]); },
get silentFor() { return (Date.now() - lastSnap) / 1000; },
stop() { off(); },
};
};
})(typeof window !== 'undefined' ? window : globalThis);