Files
Robot-Clash/game/lobby.js

139 lines
7.1 KiB
JavaScript
Raw Normal View History

/* 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.
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). */
(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 me = () => net.uid;
const prof = () => opt.getProfile();
async function beat(state) {
const p = prof();
await db.put(`lobby/${me()}`, { name: p.name, flag: 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();
2026-11-15 20:05:02 +01:00
// 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;
2026-11-15 20:05:02 +01:00
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}`);
2026-11-15 20:05:02 +01:00
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'); } }
2026-11-15 20:05:02 +01:00
// 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();
2026-11-15 20:05:02 +01:00
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');
}
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,
};
};
})(typeof window !== 'undefined' ? window : globalThis);