// 경기방 상태 기계 (리그 1:1 & 커스텀 N인 공용). 전송·저장과 분리된 순수 로직이라 node 로 테스트한다. // GameRoomDO(room.js)가 소켓 메시지를 handle() 로 넘기고, outbox/effects 를 비워 실제로 보낸다. import { AUTO_TARGET_MS, DEFAULT_RULES, MAX_ATTACK_PER_PIECE, MAX_PPS, RECONNECT_GRACE_MS, ROUND_COUNTDOWN_MS, ROUND_GAP_MS, overtimeMultiplier, sanitizeRules, } from "./rules.js"; const BOARD_W = 10; const BOARD_ROWS = 20; const BOARD_RE = /^[.IOTSZJLG]+$/; export class RoomLogic { /** * opts: { id, kind: "custom"|"league", code?, allowed?: [uid, uid], ft?, now?, rand? } */ constructor(opts) { this.id = opts.id; this.kind = opts.kind; this.code = opts.code ?? null; this.allowed = opts.allowed ?? null; this.rules = { ...DEFAULT_RULES, ...(opts.kind === "league" ? { ft: opts.ft ?? 3 } : {}) }; this.now = opts.now ?? (() => Date.now()); this.rand = opts.rand ?? Math.random; /** @type {Map} uid -> player */ this.players = new Map(); this.order = []; this.host = null; this.phase = "lobby"; // lobby | countdown | playing | between | match_end this.round = 0; this.roundStartAt = 0; this.nextRoundAt = 0; this.matchId = null; this.finished = false; this.lastEnd = null; // 끊겼다 돌아온 사람에게 다시 보낼 match_end ({uid|"*": msg}) // 리그 경기 종료 후 방 폐기 표시 this.outbox = []; // {to: uid|null, except?: uid, msg} this.effects = []; // {type, ...} } // ── 출력 ── send(to, msg) { this.outbox.push({ to, msg }); } broadcast(msg, except = null) { this.outbox.push({ to: null, except, msg }); } drain() { const o = this.outbox; const e = this.effects; this.outbox = []; this.effects = []; return { out: o, effects: e }; } // ── 직렬화 (DO 하이버네이션 대비) ── toJSON() { return { id: this.id, kind: this.kind, code: this.code, allowed: this.allowed, rules: this.rules, players: [...this.players.values()], order: this.order, host: this.host, phase: this.phase, round: this.round, roundStartAt: this.roundStartAt, nextRoundAt: this.nextRoundAt, matchId: this.matchId, finished: this.finished, lastEnd: this.lastEnd, }; } static fromJSON(j, deps = {}) { const r = new RoomLogic({ id: j.id, kind: j.kind, code: j.code, allowed: j.allowed, ...deps }); Object.assign(r, { rules: j.rules, order: j.order, host: j.host, phase: j.phase, round: j.round, roundStartAt: j.roundStartAt, nextRoundAt: j.nextRoundAt, matchId: j.matchId, finished: j.finished, lastEnd: j.lastEnd ?? null, }); for (const p of j.players) r.players.set(p.uid, p); return r; } // ── 조회 ── get connected() { return [...this.players.values()].filter((p) => p.connected); } get alive() { return [...this.players.values()].filter((p) => p.inRound && p.alive); } ftTarget() { return this.rules.ft; } lobbyMsg() { return { t: "lobby", room: this.id, code: this.code, kind: this.kind, host: this.host, rules: this.rules, phase: this.phase, round: this.round, players: this.order.map((uid) => { const p = this.players.get(uid); return { id: p.uid, nick: p.nick, guest: p.guest, wins: p.wins, alive: p.alive, inRound: p.inRound, connected: p.connected, rematch: p.rematch, tr: p.tr ?? null, rank: p.rank ?? null, }; }), }; } // ── 입장/퇴장 ── /** 반환: {ok:true} | {ok:false, reason} */ join(uid, info = {}) { if (this.finished) return { ok: false, reason: "이미 끝난 경기입니다" }; if (this.allowed && !this.allowed.includes(uid)) return { ok: false, reason: "이 경기의 참가자가 아닙니다" }; const existing = this.players.get(uid); if (existing) { existing.connected = true; existing.disconnectedAt = 0; Object.assign(existing, pickInfo(info)); this.send(uid, this.syncMsg(uid)); if (this.phase === "match_end" && this.lastEnd) { const end = this.lastEnd[uid] ?? this.lastEnd["*"]; if (end) this.send(uid, end); } if (existing.pendingGarbage?.length) { for (const g of existing.pendingGarbage) this.send(uid, g); existing.pendingGarbage = []; } this.broadcast(this.lobbyMsg()); return { ok: true, rejoined: true }; } const p = { uid, nick: info.nick ?? "?", guest: !!info.guest, tr: info.tr ?? null, rank: info.rank ?? null, connected: true, disconnectedAt: 0, wins: 0, inRound: false, alive: false, place: 0, target: null, autoTarget: null, autoTargetAt: 0, lastAttacker: null, carry: 0, pieces: 0, lastBoardAt: 0, grid: null, rematch: false, pendingGarbage: [], flagged: 0, }; this.players.set(uid, p); this.order.push(uid); if (!this.host) this.host = uid; this.send(uid, this.syncMsg(uid)); this.broadcast(this.lobbyMsg()); if (this.kind === "league" && this.phase === "lobby" && this.allowed.every((u) => this.players.get(u)?.connected)) { this.startRound(); } return { ok: true }; } syncMsg(uid) { const p = this.players.get(uid); return { ...this.lobbyMsg(), t: "sync", you: uid, inRound: p.inRound, alive: p.alive, boards: Object.fromEntries([...this.players.values()].filter((o) => o.grid && o.uid !== uid).map((o) => [o.uid, o.grid])), }; } /** 소켓 종료. 리그·라운드 중이면 15초 유예 후 톱아웃 처리. */ disconnect(uid) { const p = this.players.get(uid); if (!p) return; p.connected = false; p.disconnectedAt = this.now(); this.broadcast(this.lobbyMsg()); } leave(uid) { const p = this.players.get(uid); if (!p) return; if (this.kind === "league" && !this.finished) { this.forfeit(uid); return; } if (p.inRound && p.alive) this.topout(uid); this.players.delete(uid); this.order = this.order.filter((u) => u !== uid); if (this.host === uid) this.host = this.order.find((u) => this.players.get(u).connected) ?? this.order[0] ?? null; if (this.phase !== "lobby" && this.phase !== "match_end" && this.participants().length < 2 && this.alive.length <= 1) { // 남은 인원으로 라운드를 이어갈 수 없으면 로비로 if (this.phase === "between" || this.phase === "countdown") this.toLobby(); } this.broadcast(this.lobbyMsg()); } participants() { return this.connected; } // ── 라운드 ── startRound() { const ready = this.connected; if (ready.length < 2) return false; this.round += 1; this.phase = "countdown"; const now = this.now(); this.roundStartAt = now + ROUND_COUNTDOWN_MS; this.nextRoundAt = 0; const shared = this.randomSeed(); for (const p of this.players.values()) { const inRound = p.connected; Object.assign(p, { inRound, alive: inRound, place: 0, target: null, autoTarget: null, autoTargetAt: 0, lastAttacker: null, carry: 0, pieces: 0, grid: null, rematch: false, pendingGarbage: [], }); } for (const p of this.players.values()) { if (!p.inRound) continue; const seed = this.rules.sameBag ? shared : this.randomSeed(); this.send(p.uid, { t: "round_start", n: this.round, startIn: ROUND_COUNTDOWN_MS, seed, rules: this.rules }); } // 관전자에게도 라운드 시작 알림 (seed 없음) for (const p of this.players.values()) { if (!p.inRound) this.send(p.uid, { t: "round_start", n: this.round, startIn: ROUND_COUNTDOWN_MS, seed: null, rules: this.rules }); } this.broadcast(this.lobbyMsg()); return true; } randomSeed() { return 1 + Math.floor(this.rand() * 0x7ffffffe); } elapsed() { return Math.max(0, this.now() - this.roundStartAt); } /** 시간 경과 처리. DO 알람에서 호출. */ tick() { const now = this.now(); if (this.phase === "countdown" && now >= this.roundStartAt) this.phase = "playing"; if (this.phase === "between" && this.nextRoundAt && now >= this.nextRoundAt) { if (!this.startRound()) this.toLobby(); } for (const p of [...this.players.values()]) { if (!p.connected && p.disconnectedAt && now - p.disconnectedAt >= RECONNECT_GRACE_MS) { if (this.kind === "league" && !this.finished) { this.forfeit(p.uid); } else if (p.inRound && p.alive) { this.topout(p.uid); p.disconnectedAt = 0; } else if (this.phase === "lobby" || this.phase === "match_end") { this.leave(p.uid); } else { p.disconnectedAt = 0; } } } } /** 다음에 tick() 이 필요한 시각 (없으면 null). */ nextWake() { const t = []; if (this.phase === "countdown") t.push(this.roundStartAt); if (this.phase === "between" && this.nextRoundAt) t.push(this.nextRoundAt); for (const p of this.players.values()) if (!p.connected && p.disconnectedAt) t.push(p.disconnectedAt + RECONNECT_GRACE_MS); return t.length ? Math.min(...t) : null; } ensurePlaying() { if (this.phase === "countdown" && this.now() >= this.roundStartAt) this.phase = "playing"; return this.phase === "playing"; } // ── 메시지 처리 ── handle(uid, m) { const p = this.players.get(uid); if (!p || !m || typeof m.t !== "string") return; switch (m.t) { case "start": if (this.kind === "custom" && uid === this.host && (this.phase === "lobby" || this.phase === "match_end")) { if (this.phase === "match_end") this.resetWins(); if (!this.startRound()) this.send(uid, { t: "error", msg: "2명 이상 있어야 시작할 수 있습니다" }); } break; case "rules": if (this.kind === "custom" && uid === this.host && this.phase === "lobby") { this.rules = sanitizeRules(m.rules, this.rules); this.broadcast(this.lobbyMsg()); } break; case "stop": if (this.kind === "custom" && uid === this.host) this.toLobby(); break; case "attack": this.onAttack(p, m); break; case "board": this.onBoard(p, m); break; case "topout": if (p.inRound && p.alive && (this.phase === "playing" || this.ensurePlaying())) this.topout(uid); break; case "target": if (typeof m.id === "string" && m.id !== uid && this.players.has(m.id)) { p.target = m.id; this.send(uid, { t: "targeting", id: m.id, manual: true }); } else if (m.id === null) { p.target = null; } break; case "rematch": this.onRematch(p, !!m.vote); break; case "leave": this.leave(uid); break; case "ping": this.send(uid, { t: "pong", ts: m.ts ?? null }); break; } } onAttack(p, m) { if (!p.inRound || !p.alive || !this.ensurePlaying()) return; const lines = m.lines; const pieces = m.pieces; if (!Number.isInteger(lines) || lines < 0 || lines > MAX_ATTACK_PER_PIECE) { p.flagged++; return; } if (Number.isInteger(pieces)) { const sec = this.elapsed() / 1000; if (pieces > MAX_PPS * sec + 3) { p.flagged++; return; } p.pieces = pieces; } if (lines === 0) return; const mul = this.rules.garbageMul * overtimeMultiplier(this.elapsed(), this.rules.overtime); p.carry += lines * mul; const send = Math.floor(p.carry + 1e-9); p.carry -= send; if (send <= 0) return; const target = this.pickTarget(p); if (!target) return; target.lastAttacker = p.uid; const msg = { t: "garbage", from: p.uid, lines: send }; if (target.connected) this.send(target.uid, msg); else target.pendingGarbage.push(msg); this.broadcast({ t: "attack", from: p.uid, to: target.uid, lines: send }, target.uid); } pickTarget(p) { const others = this.alive.filter((o) => o.uid !== p.uid); if (!others.length) return null; if (others.length === 1) return others[0]; if (p.target) { const t = this.players.get(p.target); if (t && t.inRound && t.alive) return t; p.target = null; } const now = this.now(); let t = p.autoTarget && this.players.get(p.autoTarget); if (!t || !t.alive || !t.inRound || now - p.autoTargetAt >= AUTO_TARGET_MS) { t = others[Math.floor(this.rand() * others.length)]; p.autoTarget = t.uid; p.autoTargetAt = now; this.send(p.uid, { t: "targeting", id: t.uid, manual: false }); } return t; } onBoard(p, m) { if (!p.inRound) return; const grid = m.grid; if (typeof grid !== "string" || grid.length !== BOARD_W * BOARD_ROWS || !BOARD_RE.test(grid)) return; p.grid = grid; const now = this.now(); // 인원이 많을수록 브로드캐스트 주기를 늘린다 (§14.1). const minGap = 150 * Math.max(1, Math.ceil(this.connected.length / 6)); if (now - p.lastBoardAt < minGap && !m.lock) return; p.lastBoardAt = now; this.broadcast({ t: "board", id: p.uid, grid, pending: m.pending ?? 0 }, p.uid); } topout(uid) { const p = this.players.get(uid); if (!p || !p.alive) return; const aliveBefore = this.alive.length; p.alive = false; p.place = aliveBefore; this.broadcast({ t: "ko", who: uid, by: p.lastAttacker, place: p.place }); const left = this.alive; if (left.length <= 1) this.endRound(left[0] ?? null); else this.broadcast(this.lobbyMsg()); // 생존 인원·KO 표시 갱신 } endRound(winner) { if (winner) { winner.wins += 1; winner.place = 1; } const score = Object.fromEntries(this.order.map((u) => [u, this.players.get(u).wins])); this.broadcast({ t: "round_end", n: this.round, winner: winner?.uid ?? null, score }); const ft = this.ftTarget(); if (ft > 0 && winner && winner.wins >= ft) { this.endMatch(winner.uid); return; } this.phase = "between"; this.nextRoundAt = this.now() + ROUND_GAP_MS; this.broadcast(this.lobbyMsg()); } standings() { return [...this.players.values()] .filter((p) => p.wins > 0 || p.inRound) .sort((a, b) => b.wins - a.wins) .map((p, i) => ({ id: p.uid, nick: p.nick, wins: p.wins, rank: i + 1 })); } endMatch(winnerUid) { this.phase = "match_end"; this.nextRoundAt = 0; const standings = this.standings(); if (this.kind === "league") { this.finished = true; const [a, b] = this.allowed; const loser = winnerUid === a ? b : a; this.effects.push({ type: "league_end", winner: winnerUid, loser, score: { [a]: this.players.get(a)?.wins ?? 0, [b]: this.players.get(b)?.wins ?? 0 }, }); // match_end 메시지는 레이팅 반영 후 래퍼가 trDelta 를 붙여 보낸다. } else { this.effects.push({ type: "custom_end", standings, size: this.order.length }); const msg = { t: "match_end", result: standings, winner: winnerUid }; this.lastEnd = { "*": msg }; this.broadcast(msg); this.broadcastRematch(); } this.broadcast(this.lobbyMsg()); } forfeit(uid) { if (this.finished) return; const other = this.allowed.find((u) => u !== uid); const o = this.players.get(other); if (o) o.wins = Math.max(o.wins, this.rules.ft); const me = this.players.get(uid); if (me) me.alive = false; this.broadcast({ t: "ko", who: uid, by: null, place: 2, forfeit: true }); this.endMatch(other); } resetWins() { this.lastEnd = null; for (const p of this.players.values()) { p.wins = 0; p.rematch = false; } this.round = 0; } toLobby() { this.phase = "lobby"; this.nextRoundAt = 0; for (const p of this.players.values()) { p.inRound = false; p.alive = false; } this.broadcast(this.lobbyMsg()); } onRematch(p, vote) { if (this.kind !== "custom" || this.phase !== "match_end") return; p.rematch = vote; this.broadcastRematch(); const conn = this.connected; const votes = conn.filter((x) => x.rematch).length; if (votes * 2 > conn.length && conn.length >= 2) { this.resetWins(); this.startRound(); } } broadcastRematch() { const conn = this.connected; this.broadcast({ t: "rematch_state", votes: conn.filter((x) => x.rematch).map((x) => x.uid), needed: Math.floor(conn.length / 2) + 1, }); } } function pickInfo(info) { const o = {}; for (const k of ["nick", "guest", "tr", "rank"]) if (k in info) o[k] = info[k]; return o; }