/* Drives all live rooms at a fixed 60 Hz. One timer for the whole server; catches up after a hitch (max 10 ticks per wake-up), logs when a tick takes too long. */ 'use strict'; const { Room, DT } = require('./room'); function createRunner(opt = {}) { const rooms = new Map(); const STEP = DT * 1000; let next = 0, timer = null, slowLogged = 0; function loop() { const now = performance.now(); if (!next) next = now; let n = 0; while (now >= next && n < 10) { const t0 = performance.now(); for (const room of rooms.values()) { // one broken fight must never stop the others (or the server): end it as a draw and log it try { room.tick(); } catch (e) { console.error('[match] room', room.id, 'crashed', e); try { room.finish({ winner: -1, reason: 'time' }); } catch (e2) { rooms.delete(room.id); } } } const ms = performance.now() - t0; if (ms > 8 && Date.now() - slowLogged > 10000) { slowLogged = Date.now(); console.warn(`[match] slow tick ${ms.toFixed(1)} ms for ${rooms.size} rooms`); } next += STEP; n++; } if (now - next > 250) next = now; // fell far behind (sleeping laptop, debugger): don't replay it timer = setTimeout(loop, Math.max(0, next - performance.now())); } return { rooms, create(o) { const room = new Room(Object.assign({}, o, { onEnd: r => { rooms.delete(r.id); if (o.onEnd) o.onEnd(r); }, })); rooms.set(room.id, room); if (!timer && opt.autoStart !== false) loop(); return room; }, get: id => rooms.get(id), stop() { clearTimeout(timer); timer = null; next = 0; }, }; } module.exports = { createRunner };