Files
Robot-Clash/server/lobby.js

153 lines
7.2 KiB
JavaScript
Raw Normal View History

/* Lobby: who is online (= has an open, authenticated socket), challenges, match creation and results.
All state is in memory and uses server time only - no heartbeats, no client clocks.
const lobby = createLobby({ runner, economy, matches })
lobby.join({ uid, name, admin, send }) socket authenticated (a second socket replaces the first)
lobby.leave(uid, send) socket closed (only if it is still the current one)
lobby.handle(uid, msg) validated client message */
'use strict';
const crypto = require('crypto');
const CHALLENGE_TTL = 15000;
function createLobby({ runner, economy, matches, now = () => Date.now() }) {
const players = new Map(); // uid -> { uid, name, room, state, send, match: {id, seat} | null }
const pending = new Map(); // challenger uid -> { to, timer }
const inMatch = new Map(); // uid -> { id, seat } (survives a disconnect)
const row = p => {
const f = economy.fighter(p.uid, p.name);
return { uid: p.uid, name: p.name, flag: f.flag, fame: f.fame, room: p.room || f.flag, state: p.state };
};
const tell = (uid, msg) => { const p = players.get(uid); if (p) p.send(msg); };
const broadcast = (msg, except) => { for (const p of players.values()) if (p.uid !== except) p.send(msg); };
const setState = (p, state) => { p.state = state; broadcast({ t: 'lobby.state', player: row(p) }); };
function join(c) {
const old = players.get(c.uid);
const p = { uid: c.uid, name: c.name, admin: !!c.admin, room: old ? old.room : null, state: 'idle', send: c.send };
if (old && old.send !== c.send) old.send({ t: 'error', code: 'REPLACED' });
players.set(c.uid, p);
const m = inMatch.get(c.uid);
const room = m && runner.get(m.id);
if (room) { p.state = 'inmatch'; room.reconnect(m.seat); }
p.send({ t: 'lobby', players: [...players.values()].filter(x => x.uid !== c.uid).map(row), you: row(p) });
if (!old) broadcast({ t: 'lobby.join', player: row(p) }, c.uid);
if (room) p.send(room.startMsg(m.seat)); // reconnect: rebuild the running fight
}
function leave(uid, send) {
const p = players.get(uid);
if (!p || (send && p.send !== send)) return; // an old, already replaced socket
players.delete(uid);
dropChallenges(uid);
const m = inMatch.get(uid), room = m && runner.get(m.id);
if (room) room.disconnect(m.seat);
broadcast({ t: 'lobby.leave', uid });
}
function dropChallenges(uid) {
const out = pending.get(uid);
if (out) { clearTimeout(out.timer); pending.delete(uid); tell(out.to, { t: 'challenge.gone', from: uid }); }
for (const [from, c] of pending) if (c.to === uid) { clearTimeout(c.timer); pending.delete(from); const f = players.get(from); if (f) { setState(f, 'idle'); f.send({ t: 'challenge.gone', to: uid }); } }
}
function challenge(p, to) {
const q = players.get(to);
if (!q || to === p.uid) return p.send({ t: 'error', code: 'NOT_AVAILABLE' });
if (p.state !== 'idle' || q.state !== 'idle') return p.send({ t: 'error', code: 'BUSY' });
const f = economy.fighter(p.uid, p.name);
if (!f.ok) return p.send({ t: 'error', code: 'INVALID_ROBOT', errors: f.errors });
const timer = setTimeout(() => {
if (!pending.has(p.uid)) return;
pending.delete(p.uid); setState(p, 'idle');
p.send({ t: 'challenge.gone', to, reason: 'timeout' }); tell(to, { t: 'challenge.gone', from: p.uid, reason: 'timeout' });
}, CHALLENGE_TTL);
if (timer.unref) timer.unref();
pending.set(p.uid, { to, timer });
setState(p, 'challenging');
q.send({ t: 'challenge.in', from: p.uid, name: p.name, flag: f.flag, fame: f.fame });
}
function cancel(p) {
const c = pending.get(p.uid); if (!c) return;
clearTimeout(c.timer); pending.delete(p.uid); setState(p, 'idle');
tell(c.to, { t: 'challenge.gone', from: p.uid, reason: 'cancelled' });
}
function decline(p, from) {
const c = pending.get(from); if (!c || c.to !== p.uid) return;
clearTimeout(c.timer); pending.delete(from);
const f = players.get(from); if (f) { setState(f, 'idle'); f.send({ t: 'challenge.gone', to: p.uid, reason: 'declined' }); }
}
function accept(p, from) {
const c = pending.get(from), q = players.get(from);
if (!c || c.to !== p.uid || !q) return p.send({ t: 'error', code: 'NOT_AVAILABLE' });
clearTimeout(c.timer); pending.delete(from);
const fa = economy.fighter(q.uid, q.name), fb = economy.fighter(p.uid, p.name);
if (!fa.ok || !fb.ok) {
setState(q, 'idle');
const code = 'INVALID_ROBOT';
if (!fa.ok) q.send({ t: 'error', code, errors: fa.errors }); else p.send({ t: 'error', code: 'OPPONENT_INVALID' });
if (!fb.ok) p.send({ t: 'error', code, errors: fb.errors }); else q.send({ t: 'error', code: 'OPPONENT_INVALID' });
return;
}
startMatch(fa, fb);
}
function startMatch(fa, fb) {
const id = crypto.randomBytes(8).toString('hex');
const seed = crypto.randomInt(1, 1e9);
const seats = seed % 2 ? [fa, fb] : [fb, fa]; // fair: who gets which start position is random
const room = runner.create({
id, seed,
players: seats.map(f => ({ uid: f.uid, name: f.name, build: f.build, paint: f.paint, flag: f.flag })),
send: (seat, msg) => tell(seats[seat].uid, msg),
onEnd: finish,
});
if (matches) matches.start.run(id, seed, room.arena, seats[0].uid, seats[1].uid, now());
seats.forEach((f, seat) => {
inMatch.set(f.uid, { id, seat });
const pl = players.get(f.uid); if (pl) setState(pl, 'inmatch');
tell(f.uid, room.startMsg(seat));
});
return room;
}
function finish(room) {
const res = room.result;
if (matches) matches.end.run(res.winner, res.reason, now(), room.id);
room.players.forEach((pl, seat) => {
inMatch.delete(pl.uid);
const sm = room.summary(seat);
const won = res.winner === seat;
const r = economy.reward(pl.uid, Object.assign({ won, winner: res.winner === -1 ? -1 : won ? 0 : 1, reason: res.reason }, sm));
tell(pl.uid, { t: 'match.end', matchId: room.id, seat, result: res, summary: sm,
reward: { money: r.money, fame: r.fame, lines: r.lines, ach: r.ach }, save: r.save });
const p = players.get(pl.uid); if (p) setState(p, 'idle');
});
}
function handle(uid, msg) {
const p = players.get(uid); if (!p) return;
switch (msg.t) {
case 'ping': return p.send({ t: 'pong', t0: msg.t0, serverTime: now() });
case 'room': p.room = msg.room === 'all' ? null : msg.room; return setState(p, p.state);
case 'challenge': return challenge(p, msg.to);
case 'challenge.cancel': return cancel(p);
case 'challenge.accept': return accept(p, msg.from);
case 'challenge.decline': return decline(p, msg.from);
case 'input': { const m = inMatch.get(uid), room = m && runner.get(m.id); if (room) room.input(m.seat, msg); return; }
case 'match.leave': { const m = inMatch.get(uid), room = m && runner.get(m.id); if (room) room.forfeit(m.seat); return; }
}
}
// the profile changed (robot, flag, fame): show it to everyone
function refresh(uid) { const p = players.get(uid); if (p) setState(p, p.state); }
return { join, leave, handle, refresh, startMatch, players, pending, inMatch };
}
module.exports = { createLobby, CHALLENGE_TTL };