- 서버: SiteSettings.gameSpeed, /api/config에 노출, 컴퓨터 생각 시간(defaultBotDelay)과 마피아·라이어 컴퓨터가 살펴보는 간격에 BOT_SLOWDOWN(1.5)/배율. 게임이 정한 반응 시각(원카드 외치기)은 그대로 - 웹: lib/motion.ts — .game-layout 안 CSS 애니메이션·트랜지션은 useMotionScope가 playbackRate로, Web Animations는 fxAnim, 연출 타이머(배너 유지·다음 단계·복사본 정리·숫자 세기·다시 보기 한 칸)는 fxMs. 채팅·role="timer"·규칙 시간·꾹 눌러 보기는 제외 - 관리자 사이트 탭에 배율 버튼(1/16~16)과 직접 입력 - 테스트: 배율 검증(API 400/200, 열린 방 즉시 반영), 컴퓨터 생각 시간 배율, motion 단위 테스트, e2e/speed.e2e.ts(돌 애니메이션 재생 배율·컴퓨터 응답 시간), 관리자 e2e에 배율 저장 - 문서: 14-admin §5, 07-ui-ux, 06-lobby-rooms, 13-decisions, README Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
679 lines
30 KiB
TypeScript
679 lines
30 KiB
TypeScript
/** 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, LIVE_BOT_STRATEGIES, botReactionAt } from '@bg/games/bots';
|
||
import { classicDeck, type OneCardState } from '@bg/games/one-card';
|
||
import { BOT_GAMES, ClientMessage, botProfile, isBotId, type ServerMessage } from '@bg/shared';
|
||
import { openDb } from '../db';
|
||
import { SiteSettingsSchema, type SettingsStore } from '../admin/settings';
|
||
import { botPace, defaultBotDelay, type BotDelayInput } 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, offlineSince?: (userId: string) => number | null, botDelay: (input: BotDelayInput) => number = () => 0) {
|
||
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, log, offlineSince });
|
||
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 (turn-based + live) and leaves out real-time / drawing games', () => {
|
||
expect([...BOT_GAMES].sort()).toEqual([...Object.keys(BOT_STRATEGIES), ...Object.keys(LIVE_BOT_STRATEGIES)].sort());
|
||
for (const id of BOT_GAMES) expect(GAMES[id]).toBeDefined();
|
||
for (const id of ['dobble', 'halli-galli', 'catchmind']) expect(BOT_GAMES).not.toContain(id);
|
||
expect(BOT_GAMES).toContain('mafia');
|
||
});
|
||
|
||
test('each computer has its own fixed pace between quick and careful', () => {
|
||
const ids = Array.from({ length: 200 }, (_, i) => `bot:${(i % 9) + 1}:01J${String(i).padStart(23, '0')}`);
|
||
const paces = ids.map(botPace);
|
||
for (const p of paces) expect(p >= 0.7 && p < 1.5).toBe(true);
|
||
expect(botPace(ids[0]!)).toBe(paces[0]!);
|
||
expect(Math.min(...paces)).toBeLessThan(0.85);
|
||
expect(Math.max(...paces)).toBeGreaterThan(1.35);
|
||
});
|
||
|
||
test('thinking time: a beat for forced moves, longer for choices, quicker follow-ups, longest when people act too', () => {
|
||
const bot = 'bot:1:01J0000000000000000000000';
|
||
const pace = botPace(bot);
|
||
const r = () => 0.5; // middle of every range, no hesitation (0.5 >= 0.12)
|
||
const d = (choices: number, withPeople = false, followUp = false, random = r) => defaultBotDelay({ choices, withPeople, bot, followUp }, random);
|
||
expect(d(1)).toBe(Math.round(1000 * pace));
|
||
expect(d(4)).toBe(Math.round(2600 * pace));
|
||
expect(d(225)).toBe(Math.round(3200 * pace)); // many choices: capped (log2 → 4)
|
||
expect(d(4, false, true)).toBe(Math.round(1300 * pace));
|
||
expect(d(4, true)).toBe(Math.round(2600 * pace + 1500));
|
||
// Sometimes it hesitates on a real choice.
|
||
expect(d(4, false, false, () => 0.05)).toBe(Math.round((1300 + 600 + 70 + 1000 + 100) * pace));
|
||
// Never instant, never absurdly slow.
|
||
for (let i = 0; i < 500; i++) {
|
||
const id = `bot:${i}:x`;
|
||
const forced = defaultBotDelay({ choices: 1, withPeople: false, bot: id, followUp: false });
|
||
const choice = defaultBotDelay({ choices: 30, withPeople: false, bot: id, followUp: false });
|
||
expect(forced).toBeGreaterThanOrEqual(480);
|
||
expect(forced).toBeLessThanOrEqual(1960);
|
||
expect(choice).toBeGreaterThanOrEqual(1000);
|
||
expect(choice).toBeLessThanOrEqual(10_400);
|
||
}
|
||
});
|
||
|
||
test('game speed scales the thinking time, but not a reaction the game timed itself', () => {
|
||
const bot = 'bot:1:01J0000000000000000000000';
|
||
const r = () => 0.5;
|
||
const input = { choices: 4, withPeople: true, bot, followUp: false };
|
||
expect(defaultBotDelay(input, r, 3)).toBe(Math.round((2600 * botPace(bot) + 1500) * 3));
|
||
expect(defaultBotDelay(input, r, 0.25)).toBe(Math.round((2600 * botPace(bot) + 1500) * 0.25));
|
||
expect(defaultBotDelay({ ...input, reactMs: 800 }, r, 3)).toBe(800);
|
||
});
|
||
|
||
test('the admin game speed reaches the computers (×1.5 slower base) and the room view', () => {
|
||
let speed = 1 / 16;
|
||
const db = openDb(':memory:');
|
||
let now = 1_000_000;
|
||
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
|
||
const settings = { game: () => null, getSite: () => SiteSettingsSchema.parse({ gameSpeed: speed }) } as unknown as SettingsStore;
|
||
const manager = new RoomManager({ store: new RoomStore(db), games: GAMES, users, now: () => now, settings });
|
||
const play = () => {
|
||
const room = manager.createPractice('A', 'omok') as Room;
|
||
rooms.push(room);
|
||
room.join({ userId: 'A', send: () => {}, close: () => {} }, 'player');
|
||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
|
||
expect(room.start('A')).toBeNull();
|
||
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
||
expect(room.roomView().gameSpeed).toBe(speed);
|
||
return room.bots.dueAt! - now;
|
||
};
|
||
// 1/16: at least the shortest thought (0.49 s) × 1.5 × 16, though never past half the 30 s turn timer.
|
||
const slow = play();
|
||
expect(slow).toBeGreaterThanOrEqual(11_000);
|
||
expect(slow).toBeLessThanOrEqual(15_000);
|
||
speed = 16;
|
||
// ×16: at most the longest thought (10.4 s) × 1.5 / 16.
|
||
expect(play()).toBeLessThanOrEqual(1000);
|
||
});
|
||
|
||
test('thinking never takes more than half of the time left on the turn timer', () => {
|
||
const h = harness(undefined, undefined, () => 60 * 60_000);
|
||
const room = h.manager.createPractice('A', 'omok') as Room;
|
||
rooms.push(room);
|
||
room.join(h.conn('A'), 'player');
|
||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
|
||
expect(room.start('A')).toBeNull();
|
||
room.act('A', 1, { type: 'place', x: 7, y: 7 });
|
||
const deadline = room.effectiveDeadline();
|
||
expect(deadline).not.toBeNull();
|
||
const now = h.clock.now();
|
||
expect(room.bots.dueAt).toBe(now + (deadline! - now) / 2);
|
||
});
|
||
|
||
test('a bot that is still on after its own move gets a quicker follow-up', () => {
|
||
const inputs: BotDelayInput[] = [];
|
||
const h = harness(undefined, undefined, (i) => (inputs.push(i), 0));
|
||
const room = h.manager.createPractice('A', 'yacht') as Room;
|
||
rooms.push(room);
|
||
room.join(h.conn('A'), 'player');
|
||
expect(room.start('A')).toBeNull();
|
||
// Let the person time out until the bots have played a few turns.
|
||
for (let i = 0; i < 40 && inputs.length < 12; i++) {
|
||
drive(room);
|
||
const at = room.effectiveDeadline();
|
||
if (at === null) break;
|
||
h.clock.advance(at - h.clock.now());
|
||
room.onTimer();
|
||
}
|
||
expect(inputs.some((i) => i.followUp)).toBe(true);
|
||
expect(inputs.some((i) => !i.followUp)).toBe(true);
|
||
});
|
||
|
||
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, mafia: 5 };
|
||
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', 'dobble')).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('마피아: talking computers (live bots)', () => {
|
||
test('each computer looks at the game on its own clock: they greet, talk, vote at different moments and the game goes on', () => {
|
||
const h = harness();
|
||
const room = h.manager.createPractice('A', 'mafia') as Room;
|
||
rooms.push(room);
|
||
room.join(h.conn('A'), 'player');
|
||
expect(room.start('A')).toBeNull();
|
||
const ids = room.game!.players.filter(isBotId);
|
||
expect(room.bots.dueAt).not.toBeNull(); // computers are watching from the start
|
||
const voteTimes = new Map<string, number>();
|
||
for (let i = 0; i < 10 * 60 * 4 && !room.game!.finished; i++) {
|
||
h.clock.advance(250);
|
||
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
|
||
const ph = (room.game!.state as { phase: { kind: string; votes?: Record<string, string> } }).phase;
|
||
if (ph.kind === 'vote') for (const v of Object.keys(ph.votes ?? {})) if (!voteTimes.has(v)) voteTimes.set(v, h.clock.now());
|
||
const d = room.effectiveDeadline();
|
||
if (d !== null && d <= h.clock.now()) room.onTimer();
|
||
}
|
||
const s = room.game!.state as { chat: { from: string; channel: string; text: string }[]; events: { t: string }[] };
|
||
const talkers = new Set(s.chat.filter((m) => m.channel === 'day' && isBotId(m.from)).map((m) => m.from));
|
||
expect(talkers.size).toBeGreaterThanOrEqual(3);
|
||
expect(s.events.some((e) => e.t === 'vote')).toBe(true);
|
||
// Votes came in one by one, not all at the same instant.
|
||
expect(new Set(voteTimes.values()).size).toBeGreaterThan(1);
|
||
expect(ids.length).toBe(5);
|
||
// Names in chat are the players' display names ("컴퓨터 n" / "n번"), never raw ids.
|
||
expect(s.chat.some((m) => m.text.includes('bot:'))).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('원카드: computers call and catch on their own reaction clock', () => {
|
||
test('a computer that played down to one card calls at its reaction time; a person can catch only after 2 s', () => {
|
||
const h = harness(undefined, undefined, (input) => defaultBotDelay(input, () => 0.5));
|
||
const room = h.manager.createPractice('A', 'one-card') as Room;
|
||
rooms.push(room);
|
||
const a = h.conn('A');
|
||
room.join(a, 'player');
|
||
expect(room.start('A')).toBeNull();
|
||
const bot = bots(room)[0]!;
|
||
// Rig: the computer's turn with [♥9, ♣3] on ♥5; the person is next.
|
||
const s = room.game!.state as OneCardState;
|
||
const deck = classicDeck(1);
|
||
const take = (ids: string[]) => ids.map((id) => deck.find((c) => c.id === id)!);
|
||
s.hands = { A: take(['S4', 'S6', 'D8']), [bot]: take(['H9', 'C3']) };
|
||
s.discard = take(['H5']);
|
||
s.drawPile = deck.filter((c) => !['S4', 'S6', 'D8', 'H9', 'C3', 'H5'].includes(c.id));
|
||
s.current = bot;
|
||
s.phase = { kind: 'turn' };
|
||
s.pendingAttack = 0;
|
||
s.declaredSuit = null;
|
||
s.oneCardWindow = null;
|
||
room.bots.cancel();
|
||
room.scheduleTimer();
|
||
for (let k = 0; k < 5 && !(room.game!.state as OneCardState).oneCardWindow; k++) {
|
||
h.clock.advance(Math.max(0, (room.bots.dueAt ?? h.clock.now()) - h.clock.now()));
|
||
room.bots.fire();
|
||
}
|
||
let st = room.game!.state as OneCardState;
|
||
expect(st.oneCardWindow).toMatchObject({ player: bot, declared: false });
|
||
expect(st.current).toBe('A');
|
||
const opened = st.oneCardWindow!.openedAt!;
|
||
// Planned exactly at its reaction time (not squeezed by the turn clock, no thinking chat).
|
||
const at = botReactionAt(room.def, st, bot, room.profile(bot).level) as number;
|
||
expect(at).toBeGreaterThanOrEqual(opened + 500);
|
||
expect(room.bots.dueAt).toBe(at);
|
||
const rejects = () => a.msgs.filter((m) => m.t === 'reject').length;
|
||
const before = rejects();
|
||
room.act('A', 101, { type: 'declareOneCard' });
|
||
expect(rejects()).toBe(before + 1);
|
||
if (at > opened + 2000) {
|
||
// Slow this time: the person catches it first and the planned call is dropped.
|
||
h.clock.advance(opened + 2000 - h.clock.now());
|
||
room.act('A', 102, { type: 'declareOneCard' });
|
||
st = room.game!.state as OneCardState;
|
||
expect(st.oneCardWindow).toBeNull();
|
||
expect(st.hands[bot]).toHaveLength(2);
|
||
expect(room.bots.dueAt).toBeNull();
|
||
} else {
|
||
h.clock.advance(at - h.clock.now());
|
||
room.bots.fire();
|
||
st = room.game!.state as OneCardState;
|
||
expect(st.oneCardWindow).toMatchObject({ player: bot, declared: true });
|
||
expect(st.hands[bot]).toHaveLength(1);
|
||
}
|
||
});
|
||
});
|
||
|
||
describe('practice rooms close once nobody is there', () => {
|
||
function finishedPractice() {
|
||
const h = harness();
|
||
const room = h.manager.createPractice('A', 'omok') as Room;
|
||
rooms.push(room);
|
||
const a = h.conn('A');
|
||
room.join(a, 'player');
|
||
expect(room.start('A')).toBeNull();
|
||
room.act('A', 1, { type: 'resign' });
|
||
expect(room.status).toBe('finished');
|
||
return { ...h, room, a };
|
||
}
|
||
|
||
test('leaving on purpose (only computers left) closes the room right away', () => {
|
||
const { room, manager, store } = finishedPractice();
|
||
room.leave('A');
|
||
expect(manager.get(room.code)).toBeUndefined();
|
||
expect(store.openRooms()).toHaveLength(0);
|
||
expect(manager.activeRoomFor('A')).toBeNull();
|
||
});
|
||
|
||
test('leaving mid-game also closes it', () => {
|
||
const h = harness();
|
||
const room = h.manager.createPractice('A', 'omok') as Room;
|
||
rooms.push(room);
|
||
room.join(h.conn('A'), 'player');
|
||
room.start('A');
|
||
room.leave('A');
|
||
expect(h.manager.get(room.code)).toBeUndefined();
|
||
});
|
||
|
||
test('going to another page (seat kept) or closing the site: closed a minute later by the sweep', () => {
|
||
const { room, a, manager, clock, conn } = finishedPractice();
|
||
room.disconnect(a);
|
||
manager.sweep();
|
||
expect(manager.get(room.code)).toBe(room); // a refresh reconnects within seconds
|
||
clock.advance(30_000);
|
||
room.join(conn('A'), 'player');
|
||
room.disconnect(room.conns.get('A')!);
|
||
clock.advance(59_000);
|
||
manager.sweep();
|
||
expect(manager.get(room.code)).toBe(room); // the minute counts from the last disconnect
|
||
clock.advance(1_000);
|
||
manager.sweep();
|
||
expect(manager.get(room.code)).toBeUndefined();
|
||
});
|
||
|
||
test('a running practice game left for another page (site still open) waits 30 minutes', () => {
|
||
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' } });
|
||
room.start('A');
|
||
room.detach(a);
|
||
h.clock.advance(29 * 60_000);
|
||
h.manager.sweep();
|
||
expect(h.manager.get(room.code)).toBe(room);
|
||
h.clock.advance(60_000);
|
||
h.manager.sweep();
|
||
expect(h.manager.get(room.code)).toBeUndefined();
|
||
});
|
||
|
||
test('a room nobody joined closes as soon as the host leaves it', () => {
|
||
const h = harness();
|
||
const room = h.create('A', 'omok', 'public');
|
||
room.join(h.conn('A'), 'player');
|
||
expect(h.manager.publicRooms('omok')).toHaveLength(1);
|
||
room.leave('A');
|
||
expect(h.manager.get(room.code)).toBeUndefined();
|
||
expect(h.store.openRooms()).toHaveLength(0);
|
||
expect(h.manager.publicRooms('omok')).toHaveLength(0);
|
||
// Taking a seat in another room frees the lobby seat: same thing.
|
||
const first = h.create('B');
|
||
const b = h.conn('B');
|
||
first.join(b, 'player');
|
||
first.disconnect(b);
|
||
h.manager.releaseOtherLobbySeats('B', 'other');
|
||
expect(h.manager.get(first.code)).toBeUndefined();
|
||
});
|
||
|
||
test('the last person leaving a game on purpose closes it; a spectator still watching keeps it', () => {
|
||
const h = harness();
|
||
const room = h.create('A');
|
||
room.join(h.conn('A'), 'player');
|
||
room.join(h.conn('B'), 'player');
|
||
room.join(h.conn('S'), 'spectator');
|
||
expect(room.start('A')).toBeNull();
|
||
room.leave('A');
|
||
room.leave('B');
|
||
expect(h.manager.get(room.code)).toBe(room); // S is still connected
|
||
room.leave('S');
|
||
expect(h.manager.get(room.code)).toBeUndefined();
|
||
});
|
||
|
||
test('rooms without computers keep the old timeouts; someone still connected keeps any room', () => {
|
||
const h = harness();
|
||
const room = h.create('A');
|
||
const a = h.conn('A');
|
||
room.join(a, 'player');
|
||
room.join(h.conn('B'), 'player');
|
||
room.leave('B');
|
||
expect(h.manager.get(room.code)).toBe(room);
|
||
const practice = h.manager.createPractice('C', 'omok') as Room;
|
||
rooms.push(practice);
|
||
practice.join(h.conn('C'), 'player');
|
||
h.clock.advance(5 * 60_000);
|
||
h.manager.sweep();
|
||
expect(h.manager.get(practice.code)).toBe(practice);
|
||
room.disconnect(a);
|
||
h.clock.advance(5 * 60_000);
|
||
h.manager.sweep();
|
||
expect(h.manager.get(room.code)).toBe(room); // empty lobby: 10 minutes
|
||
});
|
||
});
|
||
|
||
describe('every player closed the site', () => {
|
||
/** A running human omok game (A black) with spectator S watching; `online` = who still has the site open. */
|
||
function humanGame() {
|
||
const online = new Set<string>(['A', 'B', 'S']);
|
||
const offAt = new Map<string, number>();
|
||
const h = harness(undefined, (u) => (online.has(u) ? null : (offAt.get(u) ?? 0)));
|
||
const room = h.create('A');
|
||
room.configure('A', { options: { ...(room.config.options as object), colorAssignment: 'hostBlack' } });
|
||
const a = h.conn('A');
|
||
const b = h.conn('B');
|
||
const sp = h.conn('S');
|
||
room.join(a, 'player');
|
||
room.join(b, 'player');
|
||
expect(room.start('A')).toBeNull();
|
||
room.join(sp, 'spectator');
|
||
/** The socket closed and the user has no other page of the site open. */
|
||
const closeSite = (u: string, c: Conn) => {
|
||
room.disconnect(c);
|
||
online.delete(u);
|
||
offAt.set(u, h.clock.now());
|
||
};
|
||
return { ...h, room, a, b, sp, online, offAt, closeSite };
|
||
}
|
||
|
||
test('a running game closes a minute after the last player left the site, spectators or not', () => {
|
||
const { room, a, b, sp, manager, clock, store, closeSite } = humanGame();
|
||
closeSite('A', a);
|
||
clock.advance(30_000);
|
||
closeSite('B', b);
|
||
clock.advance(59_000);
|
||
manager.sweep();
|
||
expect(manager.get(room.code)).toBe(room); // a refresh comes back within seconds
|
||
clock.advance(1_000);
|
||
manager.sweep();
|
||
expect(manager.get(room.code)).toBeUndefined();
|
||
expect(store.openRooms()).toHaveLength(0);
|
||
expect(sp.msgs.some((m) => m.t === 'bye' && m.reason === 'closed')).toBe(true);
|
||
expect(manager.activeRoomFor('A')).toBeNull();
|
||
expect(manager.activeRoomFor('B')).toBeNull();
|
||
});
|
||
|
||
test('a player still on the site (other page, or reconnected after a drop) keeps the game', () => {
|
||
const { room, a, b, manager, clock, online, closeSite } = humanGame();
|
||
closeSite('B', b);
|
||
room.detach(a); // A went to the home page
|
||
clock.advance(60 * 60_000);
|
||
manager.sweep();
|
||
expect(manager.get(room.code)).toBe(room);
|
||
// A's socket dropped and came back on the home page: not in the room any more, but still on the site.
|
||
room.disconnect(a);
|
||
online.add('A');
|
||
clock.advance(60 * 60_000);
|
||
manager.sweep();
|
||
expect(manager.get(room.code)).toBe(room);
|
||
});
|
||
|
||
test('a finished game closes too; a lobby waits for invited people (10 minutes)', () => {
|
||
const { room, a, b, manager, clock, closeSite } = humanGame();
|
||
room.act('A', 1, { type: 'resign' });
|
||
expect(room.status).toBe('finished');
|
||
closeSite('A', a);
|
||
closeSite('B', b);
|
||
clock.advance(60_000);
|
||
manager.sweep();
|
||
expect(manager.get(room.code)).toBeUndefined();
|
||
|
||
const h = harness(undefined, () => 0);
|
||
const lobby = h.create('C');
|
||
const c = h.conn('C');
|
||
lobby.join(c, 'player');
|
||
lobby.disconnect(c);
|
||
h.clock.advance(5 * 60_000);
|
||
h.manager.sweep();
|
||
expect(h.manager.get(lobby.code)).toBe(lobby);
|
||
});
|
||
|
||
test('a practice game closes a minute after the site is closed', () => {
|
||
const h = harness(undefined, () => 0);
|
||
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' } });
|
||
room.start('A');
|
||
room.disconnect(a);
|
||
h.clock.advance(60_000);
|
||
h.manager.sweep();
|
||
expect(h.manager.get(room.code)).toBeUndefined();
|
||
});
|
||
});
|
||
|
||
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();
|
||
});
|
||
});
|