M9: 컴퓨터 상대 — 게임 22종 컴퓨터 전략, 서버 구동(BotDriver), 연습 방

- packages/shared/src/bots.ts: 컴퓨터 id(bot:<n>:<ulid>)·프로필(컴퓨터 n)·BOT_GAMES
  (도블·할리갈리·그림 맞히기·마피아 제외)
- packages/games/src/bots: 전략 계약(자기 view + 합법 수만), decideBotAction(validate 재검사),
  게임별 <게임>/bot.ts 22개 + 행동 테스트, 전 게임 판 끝까지 돌리는 공통 테스트
- 서버: Room.addBot/removeBot(방장·대기실만, 방은 친구만), RoomManager.createPractice
  (POST /api/rooms {practice:true}), BotDriver(사람 같은 지연, 사람과 같은 창이면 더 천천히,
  재시작 후 다시 예약), 연습 게임은 전적 제외(result_json.practice), 사람이 모두 나가면 무효
- 프로토콜 addBot/removeBot, 문서 03·06 §12·08·09 §8

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-06 13:32:28 +09:00
parent c27cb0a11a
commit a3f81ded37
67 changed files with 5113 additions and 18 deletions

View File

@@ -0,0 +1,286 @@
/** Computer players in rooms (docs/06-lobby-rooms.md §12): seating rules, practice rooms, driving, records, restore. */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import { BOT_STRATEGIES } from '@bg/games/bots';
import { BOT_GAMES, ClientMessage, botProfile, isBotId, type ServerMessage } from '@bg/shared';
import { openDb } from '../db';
import { defaultBotDelay } from './bots';
import { RoomManager } from './manager';
import { Room, type Conn, type RoomSnapshot } from './room';
import { RoomStore } from './store';
const rooms: Room[] = [];
afterEach(() => {
for (const r of rooms.splice(0)) r.clearTimer();
});
function harness(log?: (level: 'info' | 'warn' | 'error', msg: string) => void) {
const db = openDb(':memory:');
const store = new RoomStore(db);
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, log });
const conn = (userId: string) => {
const msgs: ServerMessage[] = [];
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
return c;
};
const create = (host: string, gameId = 'omok', visibility: 'private' | 'public' = 'private') => {
const r = manager.create(host, gameId, visibility);
if (typeof r === 'string') throw new Error(r);
rooms.push(r);
return r;
};
return { db, store, clock, manager, conn, create, users };
}
/** Plays every planned bot move (the delay is 0 in these tests) until the game waits on a human. */
function drive(room: Room, max = 500): number {
let n = 0;
while (room.bots.dueAt !== null && n < max) {
room.bots.fire();
n++;
}
return n;
}
const bots = (room: Room) => room.seatedIds().filter(isBotId);
describe('bot list', () => {
test('BOT_GAMES matches the strategies and leaves out real-time / talk games', () => {
expect([...BOT_GAMES].sort()).toEqual(Object.keys(BOT_STRATEGIES).sort());
for (const id of BOT_GAMES) expect(GAMES[id]).toBeDefined();
for (const id of ['dobble', 'halli-galli', 'catchmind', 'mafia']) expect(BOT_GAMES).not.toContain(id);
});
test('thinking time: short for forced moves, longer for choices, longest when people act in the same window', () => {
const r = () => 0.5;
expect(defaultBotDelay(1, false, r)).toBe(550);
expect(defaultBotDelay(5, false, r)).toBe(1100);
expect(defaultBotDelay(5, true, r)).toBe(2600);
});
test('protocol accepts addBot / removeBot', () => {
expect(ClientMessage.safeParse({ t: 'addBot' }).success).toBe(true);
expect(ClientMessage.safeParse({ t: 'addBot', seat: 1 }).success).toBe(true);
expect(ClientMessage.safeParse({ t: 'addBot', seat: -1 }).success).toBe(false);
expect(ClientMessage.safeParse({ t: 'removeBot', userId: 'bot:1:01J0000000000000000000000' }).success).toBe(true);
expect(ClientMessage.safeParse({ t: 'removeBot' }).success).toBe(false);
});
});
describe('addBot / removeBot', () => {
test('host only, lobby only, empty seats only; the room turns private and drops out of the public list', () => {
const { create, conn, manager } = harness();
const room = create('A', 'omok', 'public');
room.join(conn('A'), 'player');
room.join(conn('S'), 'spectator');
expect(manager.publicRooms('omok')).toHaveLength(1);
expect(room.addBot('S')).toBe('방장만 컴퓨터를 넣을 수 있어요.');
expect(room.addBot('A', 0)).toBe('이미 다른 사람이 앉은 자리예요.');
expect(room.addBot('A')).toBeNull();
const [bot] = bots(room);
expect(bot).toMatch(/^bot:1:/);
expect(room.addBot('A')).toBe('빈자리가 없어요.');
expect(room.config.visibility).toBe('private');
expect(manager.publicRooms('omok')).toHaveLength(0);
expect(room.configure('A', { visibility: 'public' })).toBe('컴퓨터가 있는 방은 공개할 수 없어요.');
expect(room.configure('A', { gameId: 'dobble' })).toContain('컴퓨터');
const seat = room.roomView().seats[1]!;
expect(seat).toMatchObject({ ready: true, connected: true, away: false });
expect(seat.user).toMatchObject({ nickname: '컴퓨터 1', kind: 'bot' });
expect(room.removeBot('S', bot!)).toBe('방장만 컴퓨터를 뺄 수 있어요.');
expect(room.removeBot('A', 'B')).toBe('없는 컴퓨터예요.');
expect(room.removeBot('A', bot!)).toBeNull();
expect(bots(room)).toHaveLength(0);
// Without computers the host may make it public again.
expect(room.configure('A', { visibility: 'public' })).toBeNull();
});
test('games without computer players refuse them', () => {
const { create, conn } = harness();
const room = create('A', 'dobble');
room.join(conn('A'), 'player');
expect(room.addBot('A')).toBe('이 게임은 컴퓨터와 할 수 없어요.');
});
test('bots get the lowest free number; kick removes a bot; the host is never passed to a bot', () => {
const { create, conn } = harness();
const room = create('A', 'one-card');
room.join(conn('A'), 'player');
room.addBot('A');
room.addBot('A');
room.addBot('A');
const [b1, b2] = bots(room);
expect(room.kick('A', b2!)).toBeNull();
room.addBot('A');
expect(bots(room).map((b) => botProfile(b)!.nickname).sort()).toEqual(['컴퓨터 1', '컴퓨터 2', '컴퓨터 3']);
expect(room.transferHost('A', b1!)).toBe('컴퓨터에게는 방장을 넘길 수 없어요.');
// A spectator joins, then the host leaves: the spectator becomes host, not a computer.
room.join(conn('S'), 'spectator');
room.leave('A');
expect(room.hostId).toBe('S');
});
test('a room needs a seated person to start', () => {
const { create, conn } = harness();
const room = create('A', 'omok');
room.join(conn('A'), 'spectator');
room.addBot('A');
room.addBot('A');
expect(room.start('A')).toBe('사람이 한 명은 앉아야 해요.');
});
test('bots cannot be added or removed during a game', () => {
const { create, conn } = harness();
const room = create('A', 'one-card');
room.join(conn('A'), 'player');
room.addBot('A');
expect(room.start('A')).toBeNull();
expect(room.addBot('A')).toBe('게임 중에는 바꿀 수 없어요.');
expect(room.removeBot('A', bots(room)[0]!)).toBe('게임 중에는 바꿀 수 없어요.');
});
});
describe('createPractice', () => {
test('a private room with just enough computers to start; never offered by quick play', () => {
const { manager, conn } = harness();
const expected: Record<string, number> = { omok: 1, mahjong: 2, bang: 3, dalmuti: 3, quoridor: 1, yacht: 1 };
for (const [gameId, n] of Object.entries(expected)) {
const room = manager.createPractice(`host-${gameId}`, gameId);
if (typeof room === 'string') throw new Error(room);
rooms.push(room);
expect(room.config.visibility).toBe('private');
expect(bots(room)).toHaveLength(n);
room.join(conn(`host-${gameId}`), 'player');
expect(room.start(`host-${gameId}`)).toBeNull();
expect(room.game!.players).toContain(`host-${gameId}`);
}
expect(manager.createPractice('X', 'mafia')).toBe('이 게임은 컴퓨터와 할 수 없어요.');
// Quick play never lands in a practice room.
const qp = manager.quickPlay('Q', 'omok');
if (typeof qp === 'string') throw new Error(qp);
rooms.push(qp);
expect(qp.hasBots()).toBe(false);
});
});
describe('playing with bots', () => {
function omokVsBot() {
const h = harness();
const room = h.manager.createPractice('A', 'omok') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
expect(room.start('A')).toBeNull();
return { ...h, room, a };
}
test('the bot answers each human move through the normal action path', () => {
const { room, a, store } = omokVsBot();
const moves = () => (room.game!.state as { moves: unknown[] }).moves.length;
expect(room.bots.dueAt).toBeNull(); // black (human) to move
room.act('A', 1, { type: 'place', x: 7, y: 7 });
expect(room.bots.dueAt).not.toBeNull();
expect(drive(room)).toBe(1);
expect(moves()).toBe(2);
expect(a.msgs.filter((m) => m.t === 'state').length).toBeGreaterThanOrEqual(3);
// Logged like any action, with the bot as actor.
const log = store.log(room.id);
expect(log.some((e) => e.kind === 'act' && e.actorId !== null && isBotId(e.actorId))).toBe(true);
});
test('a bot move planned before a state change re-reads the state when it fires', () => {
const { room } = omokVsBot();
room.act('A', 1, { type: 'place', x: 7, y: 7 });
const due = room.bots.dueAt;
room.scheduleTimer(); // e.g. a reconnect re-arms timers: the plan stays
expect(room.bots.dueAt).toBe(due);
drive(room);
expect((room.game!.state as { moves: unknown[] }).moves).toHaveLength(2);
expect(room.bots.dueAt).toBeNull();
});
test('a practice game is kept but not counted; rematch only needs the people', () => {
const { room, db } = omokVsBot();
// Human resigns; the game is recorded as practice.
room.act('A', 1, { type: 'resign' });
expect(room.status).toBe('finished');
const row = db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
expect(JSON.parse(row.result_json).practice).toBe(true);
expect(db.query<{ n: number }, []>('SELECT COUNT(*) AS n FROM user_stats').get()!.n).toBe(0);
expect(db.query<{ n: number }, []>('SELECT COUNT(*) AS n FROM game_players').get()!.n).toBe(2);
expect(room.rematch('A')).toBeNull();
expect(room.status).toBe('playing');
expect(room.gameNo).toBe(2);
});
test('when every person leaves mid-game, the game ends uncounted', () => {
const { room, db } = omokVsBot();
room.act('A', 1, { type: 'place', x: 7, y: 7 });
room.leave('A');
expect(room.game!.finished).toBe(true);
expect(room.bots.dueAt).toBeNull();
expect(db.query<{ n: number }, []>('SELECT COUNT(*) AS n FROM user_stats').get()!.n).toBe(0);
});
// The real driver + room timers for every bot game: the bots act on their own (reaction windows, simultaneous
// choices, "ready" between hands) and the only person just lets the clock run out each time.
test.each([...BOT_GAMES])('%s: a whole practice game with a person who only times out finishes', (gameId) => {
const logs: string[] = [];
const h = harness((level, msg) => level !== 'info' && logs.push(msg));
const room = h.manager.createPractice('A', gameId) as Room;
rooms.push(room);
room.join(h.conn('A'), 'player');
expect(room.start('A')).toBeNull();
for (let i = 0; i < 5000 && !room.game!.finished; i++) {
drive(room);
if (room.game!.finished) break;
const at = room.effectiveDeadline();
expect(at).not.toBeNull();
h.clock.advance(Math.max(0, at! - h.clock.now()));
room.onTimer();
}
expect(room.game!.finished).toBe(true);
expect(logs).toEqual([]);
});
});
describe('restore after restart', () => {
test('bots stay seated, have no reconnect grace, and the driver re-plans their move', () => {
const { manager, conn, store, clock, users } = harness();
const room = manager.createPractice('A', 'omok') as Room;
rooms.push(room);
room.join(conn('A'), 'player');
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
room.start('A');
room.act('A', 1, { type: 'place', x: 7, y: 7 });
// Crash before the bot answers.
room.clearTimer();
const { seq, stateJson } = store.openRooms()[0]!;
clock.advance(60_000);
const restored = Room.restore(room.id, room.code, seq, JSON.parse(stateJson) as RoomSnapshot, {
store,
games: GAMES,
users,
now: clock.now,
botDelay: () => 0,
});
rooms.push(restored);
expect(restored.hasBots()).toBe(true);
expect(restored.presence.has(bots(restored)[0]!)).toBe(false);
expect(restored.roomView().seats[1]).toMatchObject({ connected: true, ready: true });
expect(restored.bots.dueAt).not.toBeNull();
drive(restored);
expect((restored.game!.state as { moves: unknown[] }).moves).toHaveLength(2);
// The manager path too: restoreAll keeps bots out of the seat index (no "active room" for a bot).
const m2 = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
m2.restoreAll();
for (const r of m2.all()) rooms.push(r);
expect(m2.activeRoomFor('A')).toBe(room.code);
expect(m2.activeRoomFor(bots(restored)[0]!)).toBeNull();
});
});