135 lines
5.9 KiB
TypeScript
135 lines
5.9 KiB
TypeScript
/** 사과 게임 through a real Room: a practice race against a computer to the end, the server clock, away players (docs/games/apple.md §8.5, §13). */
|
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import { GAMES } from '@bg/games';
|
|
import { findMoves, type AppleState, type AppleView } from '@bg/games/apple';
|
|
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<ServerMessage, { t: 'state' }>).view as AppleView;
|
|
|
|
describe('사과 게임 room flow', () => {
|
|
test('컴퓨터와 연습: 사람은 화면에 보이는 판으로 합 10을 지우고, 컴퓨터도 자기 판을 풀고, 2분 뒤 서버 시계로 끝나요', () => {
|
|
const h = harness();
|
|
const room = h.manager.createPractice('A', 'apple') as Room;
|
|
rooms.push(room);
|
|
const a = h.conn('A');
|
|
room.join(a, 'player');
|
|
expect(room.start('A')).toBeNull();
|
|
const bot = room.game!.players.find(isBotId)!;
|
|
expect(bot).toBeDefined();
|
|
let cs = 0;
|
|
let rejects = 0;
|
|
for (let i = 0; i < 4 * 200 && !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 clears one rectangle every 2 seconds, read from their own screen.
|
|
const v = lastView(a);
|
|
if (i % 8 === 0 && v.phase === 'playing' && v.cells) {
|
|
const m = findMoves(v.cells, 1)[0];
|
|
if (m) room.act('A', ++cs, { type: 'select', ...m });
|
|
}
|
|
rejects = a.msgs.filter((m) => m.t === 'reject').length;
|
|
}
|
|
expect(room.game!.finished).toBe(true);
|
|
expect(rejects).toBe(0);
|
|
const s = room.game!.state as AppleState;
|
|
expect(s.final!.endReason === 'time' || s.final!.endReason === 'cleared').toBe(true);
|
|
expect(s.score.A).toBeGreaterThan(20);
|
|
expect(s.score[bot]).toBeGreaterThan(10);
|
|
// My view never carried the computer's board.
|
|
expect(JSON.stringify(lastView(a))).not.toContain(s.boards[bot]!);
|
|
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
|
|
});
|
|
|
|
test('합이 10이 아닌 직사각형은 거절(벌점 없음), 연결이 끊긴 사람은 일찍 시간 초과되지 않아요', () => {
|
|
const h = harness();
|
|
const r = h.manager.create('A', 'apple', '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.start('A')).toBeNull();
|
|
h.clock.advance(3000);
|
|
room.onTimer();
|
|
const s = () => room.game!.state as AppleState;
|
|
expect(s().phase).toBe('playing');
|
|
// Find a 2-cell rectangle that does not add up to 10.
|
|
const cells = s().boards.A!;
|
|
const c = [...Array(16).keys()].find((k) => Number(cells[k]) + Number(cells[k + 1]) !== 10)!;
|
|
room.act('A', 1, { type: 'select', r0: 0, c0: c, r1: 0, c1: c + 1 });
|
|
const rej = a.msgs.filter((m) => m.t === 'reject').at(-1) as { reason: string };
|
|
expect(rej.reason).toMatch(/^합이 \d+이에요/);
|
|
expect(s().score.A).toBe(0);
|
|
// B drops off: 70 s later (past the 60 s grace) nothing happened to B, the race goes on.
|
|
room.disconnect(b);
|
|
expect(room.effectiveDeadline()).toBe(s().endsAt);
|
|
h.clock.advance(70_000);
|
|
room.onTimer();
|
|
expect(s().phase).toBe('playing');
|
|
expect(s().status.B).toBe('playing');
|
|
h.clock.advance(s().endsAt! - h.clock.now());
|
|
room.onTimer();
|
|
expect(room.game!.finished).toBe(true);
|
|
});
|
|
test('제한 시간 무제한: 타이머가 돌지 않고, 끊긴 사람은 유예 뒤 한 번만 여기까지 처리(바쁜 루프 없음), 남은 사람이 여기까지 하면 끝', () => {
|
|
const h = harness();
|
|
const r = h.manager.create('A', 'apple', '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: { timeLimitSec: null } })).toBeNull();
|
|
expect(room.start('A')).toBeNull();
|
|
h.clock.advance(3000);
|
|
room.onTimer();
|
|
const s = () => room.game!.state as AppleState;
|
|
expect(s().phase).toBe('playing');
|
|
expect(s().endsAt).toBeNull();
|
|
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().status.B).toBe('done');
|
|
expect(s().status.A).toBe('playing');
|
|
// Nothing else is due: no timer fires again for B.
|
|
expect(room.effectiveDeadline()).toBeNull();
|
|
room.act('A', 1, { type: 'stop' });
|
|
expect(room.game!.finished).toBe(true);
|
|
expect(s().final!.summary).toContain('모두 끝냈어요');
|
|
});
|
|
});
|