/** 타자 대결 through a real Room: progress streams, a practice game against a computer, away players (docs/games/typing.md §8). */ import { afterEach, describe, expect, test } from 'bun:test'; import { GAMES } from '@bg/games'; import type { TypingState, TypingView } from '@bg/games/typing'; import { botProfile, isBotId, type ServerMessage } from '@bg/shared'; import { openDb } from '../db'; import { RoomManager } from './manager'; import { Room, type Conn } from './room'; import { RoomStore } from './store'; const rooms: Room[] = []; afterEach(() => { for (const r of rooms.splice(0)) r.clearTimer(); }); function harness() { const store = new RoomStore(openDb(':memory:')); let now = 1_000_000; const clock = { now: () => now, advance: (ms: number) => (now += ms) }; const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 }); const conn = (userId: string) => { const msgs: ServerMessage[] = []; const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; return c; }; return { clock, manager, conn }; } const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract).view as TypingView; function twoPlayers(options: Record) { const h = harness(); const r = h.manager.create('A', 'typing', 'private'); if (typeof r === 'string') throw new Error(r); const room = r as Room; rooms.push(room); const a = h.conn('A'); const b = h.conn('B'); room.join(a, 'player'); room.join(b, 'player'); room.ready('B', true); expect(room.configure('A', { options: { ...GAMES.typing!.defaultOptions, ...options } })).toBeNull(); expect(room.start('A')).toBeNull(); h.clock.advance(3000); room.onTimer(); return { h, room, a, b, s: () => room.game!.state as TypingState }; } describe('타자 대결 room flow', () => { test('연습: 먼저 다 친 사람이 방을 나가도 남은 사람은 끝까지 쳐요', () => { const { h, room, b, s } = twoPlayers({ mode: 'practice', category: 'word' }); const typeAll = (who: string) => { const n = s().items.length; for (let i = 0; i < n; i++) { h.clock.advance(3000); room.act(who, 100 + i, { type: 'submit', item: i, text: s().items[i]! }); } }; typeAll('A'); expect(s().rs.A!.finishedAt).not.toBeNull(); room.leave('A'); expect(s().phase).toBe('playing'); expect(lastView(b).upcoming[0]!.idx).toBe(0); typeAll('B'); expect(b.msgs.filter((m) => m.t === 'reject')).toEqual([]); expect(s().phase).toBe('ended'); expect(s().final!.ranking[0]).toMatchObject({ id: 'B', left: false }); }); test('진행은 stream으로만 가고(보기 다시 계산 없음), 먼저 정확하게 친 사람이 점수를 얻어요', () => { const { h, room, a, b, s } = twoPlayers({ rounds: 1 }); const v = lastView(b); expect(v.phase).toBe('playing'); const item = v.upcoming[0]!; // A paste the moment the text appears is refused. room.act('B', 1, { type: 'submit', item: item.idx, text: item.text }); expect((b.msgs.filter((m) => m.t === 'reject').at(-1) as { reason: string }).reason).toContain('너무 빨라요'); const states = b.msgs.filter((m) => m.t === 'state').length; h.clock.advance(1500); room.act('A', 1, { type: 'progress', item: item.idx, text: item.text.slice(0, 2) }); const stream = b.msgs.filter((m) => m.t === 'stream').at(-1) as Extract; expect(stream.events).toEqual([expect.objectContaining({ type: 'progress', player: 'A', item: item.idx })]); expect(b.msgs.filter((m) => m.t === 'state').length).toBe(states); h.clock.advance(3000); room.act('A', 2, { type: 'submit', item: item.idx, text: item.text }); expect(a.msgs.filter((m) => m.t === 'reject').map((m) => JSON.stringify(m))).toEqual([]); expect(s().totals.A!.points).toBe(1); expect(lastView(b).last).toMatchObject({ winner: 'A', text: item.text }); // The next item opens after the gap, from the server clock. expect(lastView(b).upcoming).toEqual([]); h.clock.advance(1500); room.onTimer(); expect(lastView(b).upcoming[0]!.idx).toBe(1); }); test('컴퓨터와 연습(타수 비교): 사람도 컴퓨터도 끝까지 치고, 거절 없이 끝나요', () => { const h = harness(); const room = h.manager.createPractice('A', 'typing') as Room; rooms.push(room); const a = h.conn('A'); room.join(a, 'player'); expect(room.configure('A', { options: { ...GAMES.typing!.defaultOptions, mode: 'speed', rounds: 1 } })).toBeNull(); expect(room.start('A')).toBeNull(); const bot = room.game!.players.find(isBotId)!; expect(bot).toBeDefined(); let cs = 0; for (let i = 0; i < 4 * 400 && !room.game!.finished; i++) { h.clock.advance(250); if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); const d = room.effectiveDeadline(); if (d !== null && d <= h.clock.now()) room.onTimer(); // The person sends a line every 6 seconds, read from their own screen. const v = lastView(a); const me = v.seats.find((x) => x.id === 'A')!; if (i % 24 === 23 && v.phase === 'playing' && !me.finished && v.upcoming[0]) room.act('A', ++cs, { type: 'submit', item: v.upcoming[0].idx, text: v.upcoming[0].text }); } expect(room.game!.finished).toBe(true); expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]); const s = room.game!.state as TypingState; expect(s.totals.A!.keys).toBeGreaterThan(0); expect(s.totals[bot]!.keys).toBeGreaterThan(0); expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort()); }); test('서바이벌 문장별(무제한은 자동 시간으로): 끊긴 사람을 기다리지 않고, 먼저 친 사람이 남아 이겨요', () => { const { h, room, a, b, s } = twoPlayers({ mode: 'survival', elimination: 'sentence', timeLimit: null, rounds: 1 }); // 서바이벌 always has a clock (무제한 plays as 자동). expect(s().curEndsAt).not.toBeNull(); room.disconnect(b); const item = lastView(a).upcoming[0]!; h.clock.advance(4000); room.act('A', 1, { type: 'submit', item: item.idx, text: item.text }); expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]); expect(room.game!.finished).toBe(true); expect(s().rs.B!.outReason).toBe('slowest'); expect(lastView(a).result!.ranking[0]!.id).toBe('A'); }); test('타수 비교 무제한: 끊긴 사람은 유예 뒤 친 데까지로 멈추고, 다음 타이머는 없어요', () => { const { h, room, a, b, s } = twoPlayers({ mode: 'speed', timeLimit: null, rounds: 1 }); expect(room.effectiveDeadline()).toBeNull(); room.disconnect(b); const d = room.effectiveDeadline()!; expect(d).toBeGreaterThan(h.clock.now()); h.clock.advance(d - h.clock.now()); room.onTimer(); expect(s().rs.B!.finishedAt).not.toBeNull(); expect(room.effectiveDeadline()).toBeNull(); let cs = 0; while (!room.game!.finished) { const v = lastView(a); h.clock.advance(5000); room.act('A', ++cs, { type: 'submit', item: v.upcoming[0]!.idx, text: v.upcoming[0]!.text }); } expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]); expect(lastView(a).result!.ranking[0]!.id).toBe('A'); }); });