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:
169
game/lobby.js
169
game/lobby.js
@@ -1,138 +1,65 @@
|
||||
/* Robot Clash - online lobby: presence, player list, challenges, match creation. No DOM.
|
||||
Needs net.js (RC.Net). Transport is Firebase RTDB (net.db). All cosmetic/casual, see docs/firebase.
|
||||
/* Robot Clash - online lobby over the server WebSocket (net.socket). No DOM. The server owns presence,
|
||||
challenges and matches; this just mirrors its state and forwards clicks.
|
||||
|
||||
const lobby = RC.Lobby({ net, getProfile: () => ({ name, flag, build, paint, fame }) });
|
||||
lobby.enter() announce presence, start heartbeat, watch list + incoming challenges
|
||||
lobby.leave() remove presence, stop everything
|
||||
lobby.onList(fn) fn([{ uid, name, flag, state, fame }]) - online players except me, newest first
|
||||
lobby.onIncoming(fn) fn({ from, fromName, fromFlag, build, paint, seed }) - someone challenges me
|
||||
lobby.onMatch(fn) fn({ id, host (bool), opp: { uid, name, flag, build, paint }, seed }) - fight on
|
||||
lobby.onCancel(fn) fn() - a pending challenge I sent/got fell through
|
||||
await lobby.challenge(uid) invite a player (writes to their inbox, waits for accept)
|
||||
await lobby.accept(from) accept an incoming challenge -> creates the match
|
||||
lobby.decline(from) reject an incoming challenge
|
||||
lobby.cancel() withdraw the challenge I sent
|
||||
|
||||
Presence TTL: entries older than STALE ms count as offline (no SDK onDisconnect). */
|
||||
const lobby = RC.Lobby({ net })
|
||||
lobby.enter() / leave()
|
||||
lobby.onList(fn) fn([{ uid, name, flag, fame, state, room }]) everyone online except me
|
||||
lobby.onIncoming(fn) fn({ from, fromName, fromFlag }) someone challenges me
|
||||
lobby.onCancel(fn) fn({ reason }) my challenge / an incoming one fell through
|
||||
lobby.onMatch(fn) fn(matchStartMsg) fight on (also after a reconnect)
|
||||
lobby.onEnd(fn) fn(matchEndMsg) server result + rewards + new save
|
||||
lobby.onError(fn) fn(code) BUSY | INVALID_ROBOT | ...
|
||||
lobby.challenge(uid) / accept(from) / decline(from) / cancel() / setRoom(code|'all')
|
||||
lobby.pending uid I challenged (or null) */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = (root.RC = root.RC || {});
|
||||
const HEARTBEAT = 4000, STALE = 12000;
|
||||
const now = () => Date.now();
|
||||
// match id = both uids sorted + join -> same id on both sides; lower uid hosts (authority)
|
||||
const matchId = (a, b) => [a, b].sort().join('_');
|
||||
const isHost = (a, b) => a < b;
|
||||
|
||||
RC.Lobby = (opt) => {
|
||||
const net = opt.net, db = net.db;
|
||||
const cbs = { list: [], incoming: [], match: [], cancel: [] };
|
||||
const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { /* ignore */ } });
|
||||
let hb = null, subList = null, subIn = null, subMatch = null;
|
||||
let outgoing = null; // uid I challenged
|
||||
let inMatch = null; // active match id
|
||||
const net = opt.net, sock = net.socket;
|
||||
const cbs = { list: [], incoming: [], cancel: [], match: [], end: [], error: [] };
|
||||
const emit = (k, v) => cbs[k].forEach(fn => { try { fn(v); } catch (e) { console.error(e); } });
|
||||
const players = new Map();
|
||||
let me = null, pending = null, offs = [], incomingFrom = null;
|
||||
|
||||
const me = () => net.uid;
|
||||
const prof = () => opt.getProfile();
|
||||
const list = () => emit('list', [...players.values()].sort((a, b) => (b.fame | 0) - (a.fame | 0) || String(a.name).localeCompare(b.name)));
|
||||
|
||||
async function beat(state) {
|
||||
const p = prof();
|
||||
await db.put(`lobby/${me()}`, { name: p.name, flag: p.flag || 'XX', room: p.room || p.flag || 'XX', fame: p.fame | 0, ver: 2, state: state || 'idle', ts: { '.sv': 'timestamp' } });
|
||||
}
|
||||
|
||||
function watchList() {
|
||||
subList = db.stream('lobby', data => {
|
||||
const t = now(), mine = me();
|
||||
const rows = Object.entries(data || {})
|
||||
.map(([uid, v]) => Object.assign({ uid }, v))
|
||||
.filter(v => v.uid !== mine && v.name && (t - (v.ts || 0)) < STALE)
|
||||
.sort((a, b) => (b.ts || 0) - (a.ts || 0));
|
||||
emit('list', rows);
|
||||
});
|
||||
}
|
||||
|
||||
// incoming challenges land under challenges/<me>/<fromUid>
|
||||
function watchIncoming() {
|
||||
subIn = db.stream(`challenges/${me()}`, data => {
|
||||
const entries = Object.entries(data || {}).filter(([, v]) => v && v.from && (now() - (v.ts || 0)) < STALE);
|
||||
if (!entries.length) return;
|
||||
const [, c] = entries[0];
|
||||
emit('incoming', { from: c.from, fromName: c.fromName, fromFlag: c.fromFlag, build: c.build, paint: c.paint, seed: c.seed });
|
||||
});
|
||||
}
|
||||
|
||||
// the match node appears for both players once created (host writes it on accept)
|
||||
function watchMatch(id, oppUid, host) {
|
||||
cleanupMatch();
|
||||
inMatch = id;
|
||||
subMatch = db.stream(`matches/${id}/meta`, meta => {
|
||||
// wait until BOTH players have written their robot (each side patches its own entry)
|
||||
if (!meta || inMatch !== id || meta.seed == null || !meta[oppUid] || !meta[me()]) return;
|
||||
emit('match', { id, host, opp: { uid: oppUid, name: meta[oppUid] && meta[oppUid].name, flag: meta[oppUid] && meta[oppUid].flag, build: meta[oppUid] && meta[oppUid].build, paint: meta[oppUid] && meta[oppUid].paint }, seed: meta.seed });
|
||||
if (subMatch) { subMatch.close(); subMatch = null; } // meta is fixed; stop watching
|
||||
});
|
||||
}
|
||||
function cleanupMatch() { if (subMatch) { subMatch.close(); subMatch = null; } }
|
||||
|
||||
async function challenge(uid) {
|
||||
if (outgoing) return;
|
||||
outgoing = uid;
|
||||
const p = prof();
|
||||
// a rematch reuses the match id, so clear whatever a crashed fight left behind -
|
||||
// otherwise the waiting side would pick up the old seed (and the old arena) at once
|
||||
await db.del(`matches/${matchId(me(), uid)}`);
|
||||
await beat('searching');
|
||||
await db.put(`challenges/${uid}/${me()}`, { from: me(), fromName: p.name, fromFlag: p.flag || 'XX', build: p.build, paint: p.paint, seed: (Math.random() * 1e9) | 0, ts: { '.sv': 'timestamp' } });
|
||||
// wait for the other side to create the match (they host if their uid < mine)
|
||||
const id = matchId(me(), uid), host = isHost(me(), uid);
|
||||
const give = setTimeout(() => { if (outgoing === uid) { emit('cancel'); cancel(); } }, STALE);
|
||||
const watch = db.stream(`matches/${id}/meta/seed`, seed => {
|
||||
if (seed == null) return;
|
||||
clearTimeout(give); watch.close(); outgoing = null;
|
||||
createMatch(uid, false); // add my own robot; the seed is already set by the other side
|
||||
watchMatch(id, uid, host);
|
||||
});
|
||||
}
|
||||
|
||||
async function accept(from) {
|
||||
const id = matchId(me(), from), host = isHost(me(), from);
|
||||
await db.del(`challenges/${me()}/${from}`);
|
||||
await createMatch(from, true); // whoever accepts rolls the seed (and with it the arena)
|
||||
watchMatch(id, from, host);
|
||||
}
|
||||
function decline(from) { db.del(`challenges/${me()}/${from}`); }
|
||||
function cancel() { if (outgoing) { db.del(`challenges/${outgoing}/${me()}`); outgoing = null; beat('idle'); } }
|
||||
|
||||
// setSeed: only the side that accepts writes the seed, so both read the exact same value.
|
||||
// It is rolled fresh for every match - a seed derived from the match id would hand the same
|
||||
// pair of players the same arena for ever.
|
||||
async function createMatch(oppUid, setSeed) {
|
||||
const id = matchId(me(), oppUid), p = prof();
|
||||
const meta = { [me()]: { name: p.name, flag: p.flag || 'XX', build: p.build, paint: p.paint } };
|
||||
if (setSeed) meta.seed = ((Math.random() * 1e9) | 0) || 1;
|
||||
await db.patch(`matches/${id}/meta`, meta);
|
||||
await beat('inmatch');
|
||||
function wire() {
|
||||
offs = [
|
||||
sock.on('lobby', m => { players.clear(); for (const p of m.players) players.set(p.uid, p); me = m.you; list(); }),
|
||||
sock.on('lobby.join', m => { players.set(m.player.uid, m.player); list(); }),
|
||||
sock.on('lobby.state', m => { if (m.player.uid === net.uid) { me = m.player; return; } players.set(m.player.uid, m.player); list(); }),
|
||||
sock.on('lobby.leave', m => { players.delete(m.uid); list(); }),
|
||||
sock.on('challenge.in', m => { incomingFrom = m.from; emit('incoming', { from: m.from, fromName: m.name, fromFlag: m.flag, fame: m.fame }); }),
|
||||
sock.on('challenge.gone', m => {
|
||||
if (m.to && m.to === pending) { pending = null; emit('cancel', { reason: m.reason || 'gone', outgoing: true }); }
|
||||
if (m.from && m.from === incomingFrom) { incomingFrom = null; emit('cancel', { reason: m.reason || 'gone', outgoing: false }); }
|
||||
}),
|
||||
sock.on('match.start', m => { pending = null; incomingFrom = null; emit('match', m); }),
|
||||
sock.on('match.end', m => emit('end', m)),
|
||||
sock.on('error', m => { if (['BUSY', 'NOT_AVAILABLE', 'INVALID_ROBOT', 'OPPONENT_INVALID'].includes(m.code)) pending = null; emit('error', m.code); }),
|
||||
sock.on('close', () => { players.clear(); pending = null; list(); }),
|
||||
];
|
||||
}
|
||||
|
||||
return {
|
||||
onList: fn => cbs.list.push(fn),
|
||||
onIncoming: fn => cbs.incoming.push(fn),
|
||||
onMatch: fn => cbs.match.push(fn),
|
||||
onCancel: fn => cbs.cancel.push(fn),
|
||||
challenge, accept, decline, cancel,
|
||||
async enter() {
|
||||
if (!net.enabled || !me()) return;
|
||||
await beat('idle');
|
||||
hb = setInterval(() => db.patch(`lobby/${me()}`, { ts: { '.sv': 'timestamp' }, state: outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle' }), HEARTBEAT);
|
||||
watchList(); watchIncoming();
|
||||
},
|
||||
refresh() { if (me()) beat(outgoing ? 'searching' : inMatch ? 'inmatch' : 'idle'); },
|
||||
endMatch() { const id = inMatch; inMatch = null; cleanupMatch(); if (id) db.del(`matches/${id}`); if (me()) beat('idle'); },
|
||||
leave() {
|
||||
clearInterval(hb); hb = null;
|
||||
if (subList) subList.close(); if (subIn) subIn.close(); cleanupMatch();
|
||||
if (me()) db.del(`lobby/${me()}`);
|
||||
},
|
||||
matchId, isHost,
|
||||
onMatch: fn => cbs.match.push(fn),
|
||||
onEnd: fn => cbs.end.push(fn),
|
||||
onError: fn => cbs.error.push(fn),
|
||||
get pending() { return pending; },
|
||||
get me() { return me; },
|
||||
get connected() { return sock.connected; },
|
||||
enter() { if (!net.enabled || !net.uid) return; if (!offs.length) wire(); sock.connect(); },
|
||||
leave() { offs.forEach(off => off()); offs = []; sock.close(); players.clear(); pending = null; },
|
||||
challenge(uid) { if (pending) return; pending = uid; if (!sock.send({ t: 'challenge', to: uid })) pending = null; },
|
||||
cancel() { if (!pending) return; sock.send({ t: 'challenge.cancel' }); pending = null; },
|
||||
accept(from) { incomingFrom = null; sock.send({ t: 'challenge.accept', from }); },
|
||||
decline(from) { incomingFrom = null; sock.send({ t: 'challenge.decline', from }); },
|
||||
setRoom(room) { sock.send({ t: 'room', room: room || 'all' }); },
|
||||
leaveMatch() { sock.send({ t: 'match.leave' }); },
|
||||
};
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
|
||||
Reference in New Issue
Block a user