import { describe, expect, test } from 'bun:test'; import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine'; import { CELLS, COLS, COUNTDOWN_MS, ROWS, SELECTS_PER_SEC, apple, findMoves, hasMove, makeBoard, rankRows, rectSum, type AppleAction, type AppleOptions, type AppleState, type Rect, } from './index'; const T0 = 1_000_000; const START = T0 + COUNTDOWN_MS; const rng = () => SeededRng.fromSeed([7, 7, 7, 7]); function make(players = ['A', 'B'], opts: Partial = {}, seed = 1): AppleState { return apple.setup({ players, options: apple.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 }); } function act(s: AppleState, p: string, a: AppleAction, now: number): AppleState { const v = apple.validate(s, p, a, { now }); if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`); return apple.apply(s, p, a, { rng: rng(), now }).state; } const tick = (s: AppleState, now: number) => apple.apply(s, s.order[0]!, { type: 'tick' }, { rng: rng(), now }).state; const sel = (r: Rect): AppleAction => ({ type: 'select', ...r }); const reason = (s: AppleState, p: string, a: AppleAction, now?: number) => { const v = apple.validate(s, p, a, now === undefined ? undefined : { now }); return v.ok ? 'ok' : v.reason; }; /** A board from rows of text ('.' or '0' = empty), padded with empty cells. */ function board(rows: string[]): string { const out: string[] = []; for (let r = 0; r < ROWS; r++) out.push((rows[r] ?? '').replace(/\./g, '0').padEnd(COLS, '0').slice(0, COLS)); return out.join(''); } function rigged(cells: string, players = ['A', 'B']): AppleState { const s = tick(make(players), START); for (const p of players) s.boards[p] = cells; s.initial = cells; return s; } /** Brute force: every rectangle with sum 10, reduced to its apples' bounding box, deduplicated. */ function bruteMoves(cells: string): string[] { const keys = new Set(); for (let r0 = 0; r0 < ROWS; r0++) for (let r1 = r0; r1 < ROWS; r1++) for (let c0 = 0; c0 < COLS; c0++) for (let c1 = c0; c1 < COLS; c1++) { if (rectSum(cells, { r0, c0, r1, c1 }).sum !== 10) continue; let a = ROWS, b = COLS, c = -1, d = -1; for (let r = r0; r <= r1; r++) for (let k = c0; k <= c1; k++) if (cells[r * COLS + k] !== '0') { a = Math.min(a, r); b = Math.min(b, k); c = Math.max(c, r); d = Math.max(d, k); } keys.add(`${a},${b},${c},${d}`); } return [...keys].sort(); } describe('판 만들기', () => { test('17×10 칸에 1~9, 합은 10의 배수, 같은 시드면 같은 판, 모두 같은 판으로 시작', () => { for (let i = 1; i <= 30; i++) { const b = makeBoard(SeededRng.fromSeed(seedN(i))); expect(b).toHaveLength(CELLS); expect(b).toMatch(/^[1-9]+$/); expect([...b].reduce((a, c) => a + Number(c), 0) % 10).toBe(0); expect(makeBoard(SeededRng.fromSeed(seedN(i)))).toBe(b); } const s = make(['A', 'B', 'C']); expect(new Set(Object.values(s.boards))).toEqual(new Set([s.initial])); expect(s.endsAt!).toBe(START + 120_000); expect(make(['A'], { timeLimitSec: 60 }).endsAt).toBe(START + 60_000); }); test('findMoves = 손으로 센 모든 합 10 직사각형(가장 좁게), 빈 칸 너머도 포함', () => { for (let i = 1; i <= 6; i++) { const r = SeededRng.fromSeed(seedN(100 + i)); // Sparse boards so long rectangles across cleared cells show up too. const cells = [...makeBoard(r)].map((c) => (r.int(10) < 6 ? '0' : c)).join(''); const got = findMoves(cells).map((m) => `${m.r0},${m.c0},${m.r1},${m.c1}`).sort(); expect(got).toEqual(bruteMoves(cells)); } expect(findMoves(board(['19', '..', '.5', '.5']))).toEqual([ { r0: 0, c0: 0, r1: 0, c1: 1 }, { r0: 2, c0: 1, r1: 3, c1: 1 }, ]); expect(hasMove(board(['55']))).toBe(true); expect(hasMove(board(['54', '..', '9']))).toBe(false); }); test('한 수 계산은 1ms 안쪽(판 전체를 훑어도)', () => { const cells = makeBoard(SeededRng.fromSeed(seedN(3))); const t0 = performance.now(); for (let i = 0; i < 50; i++) findMoves(cells); expect((performance.now() - t0) / 50).toBeLessThan(5); }); }); describe('진행', () => { test('카운트다운 동안에는 판이 안 보이고 고를 수 없어요. 시간이 되면 바로 시작(타이머 전이라도)', () => { const s = make(); expect(apple.view(s, 'A').cells).toBeNull(); checkNoLeak(apple, s, 'A', s.order); const m = findMoves(s.initial)[0]!; expect(reason(s, 'A', sel(m), START - 1)).toBe('곧 시작해요. 잠시만 기다려 주세요.'); // The countdown is over but the room timer has not ticked yet: the select still counts. const s2 = act(s, 'A', sel(m), START + 5); expect(s2.phase).toBe('playing'); expect(s2.score.A).toBeGreaterThanOrEqual(2); expect(apple.view(s2, 'A').cells).toBe(s2.boards.A!); expect(apple.view(s2, null).cells).toBeNull(); // Others never get my board, only my score. expect(JSON.stringify(apple.view(s2, 'B'))).not.toContain(s2.boards.A!); expect(apple.view(s2, 'B').seats.find((x) => x.id === 'A')!.score).toBe(s2.score.A!); }); test('합이 딱 10이면 지워지고 지운 개수만큼 점수. 빈 칸은 합에 영향 없음, 모서리 순서 무관', () => { const s = rigged(board(['1.9', '...', '28.', '...', '55.'])); expect(reason(s, 'A', sel({ r0: 0, c0: 0, r1: 0, c1: 2 }), START + 10)).toBe('ok'); let t = act(s, 'A', sel({ r0: 0, c0: 2, r1: 0, c1: 0 }), START + 10); expect(t.score.A).toBe(2); expect(t.clears.A).toBe(1); expect(t.boards.A!.slice(0, 3)).toBe('000'); // B's copy is untouched. expect(t.boards.B).toBe(s.boards.B); // A rectangle over cleared cells: 2 + 8 (rows 0~2) still adds to 10. t = act(t, 'A', sel({ r0: 0, c0: 0, r1: 2, c1: 2 }), START + 600); expect(t.score.A).toBe(4); expect(reason(t, 'A', sel({ r0: 0, c0: 0, r1: 1, c1: 2 }), START + 1200)).toBe('고른 칸에 사과가 없어요.'); expect(reason(t, 'A', sel({ r0: 4, c0: 0, r1: 4, c1: 0 }), START + 1200)).toBe('합이 5이에요. 딱 10이 되게 골라 주세요.'); // The whole board (only 5 + 5 left) is a fine rectangle too. expect(reason(t, 'A', sel({ r0: 0, c0: 0, r1: 9, c1: 16 }), START + 1200)).toBe('ok'); }); test('너무 빨리 연달아 고르면 거절(1초에 5번까지)', () => { let s = rigged(board(['55555555555555555', '55555555555555555'])); let now = START + 100; for (let i = 0; i < SELECTS_PER_SEC; i++) s = act(s, 'A', sel({ r0: 0, c0: 2 * i, r1: 0, c1: 2 * i + 1 }), (now += 10)); expect(reason(s, 'A', sel({ r0: 1, c0: 0, r1: 1, c1: 1 }), now + 10)).toBe('조금 천천히 해 주세요.'); expect(reason(s, 'B', sel({ r0: 1, c0: 0, r1: 1, c1: 1 }), now + 10)).toBe('ok'); expect(reason(s, 'A', sel({ r0: 1, c0: 0, r1: 1, c1: 1 }), START + 100 + 10 + 1000)).toBe('ok'); }); test('서버 시계로 끝: 마감 뒤 고르기는 거절, 타이머 tick으로 끝나고 점수 순위(동점 같은 순위)', () => { let s = make(['A', 'B', 'C']); s = tick(s, START); const m1 = findMoves(s.initial)[0]; s = act(s, 'A', sel(m1!), START + 1000); s = act(s, 'B', sel(m1!), START + 1000); s = act(s, 'B', sel(findMoves(s.boards.B!)[0]!), START + 2000); expect(apple.deadline!(s)).toBe(s.endsAt!); expect(apple.timeoutNotBefore!(s)).toBe(s.endsAt!); expect(reason(s, 'C', sel(m1!), s.endsAt!)).toBe('시간이 다 됐어요.'); s = tick(s, s.endsAt!); expect(s.phase).toBe('ended'); const r = apple.result(s)!; expect(r.ranking).toEqual([['B'], ['A'], ['C']]); expect(r.scoreText!.C).toBe('사과 0개'); expect(r.summary).toContain('시간이 다 됐어요'); // Tie → shared rank. s.score.A = s.score.B!; expect(rankRows(s).map((x) => x.rank)).toEqual([1, 1, 3]); }); test('혼자 하기: 1명도 시작, 끝나면 내 점수 요약', () => { let s = make(['A']); s = tick(s, START); s = act(s, 'A', sel(findMoves(s.initial)[0]!), START + 500); s = tick(s, s.endsAt! + 5); const r = apple.result(s)!; expect(r.ranking).toEqual([['A']]); expect(r.summary).toBe(`시간이 다 됐어요. 사과 ${s.score.A}개를 지웠어요`); }); test('더 지울 게 없으면 "막힘", 모두 막히면 시간 전에 끝나요', () => { let s = rigged(board(['19', '..', '37', '..', '4'])); s = act(s, 'A', sel({ r0: 0, c0: 0, r1: 0, c1: 1 }), START + 100); expect(s.status.A).toBe('playing'); s = act(s, 'A', sel({ r0: 2, c0: 0, r1: 2, c1: 1 }), START + 700); expect(s.status.A).toBe('stuck'); expect(apple.activePlayers(s)).toEqual(['B']); expect(apple.timeoutPlayers!(s)).toEqual(['A', 'B']); expect(reason(s, 'A', sel({ r0: 4, c0: 0, r1: 4, c1: 0 }), START + 800)).toBe('더 지울 수 있는 사과가 없어요.'); s = act(s, 'B', sel({ r0: 2, c0: 0, r1: 2, c1: 1 }), START + 900); s = act(s, 'B', sel({ r0: 0, c0: 0, r1: 0, c1: 1 }), START + 1500); expect(s.phase).toBe('ended'); const r = apple.result(s)!; expect(r.ranking).toEqual([['A', 'B']]); expect(r.summary).toContain('모두 더 지울 사과가 없어요'); expect(r.summary).toContain('공동 1등 2명'); }); test('나가기: 남은 사람이 1명이면 끝, 나간 사람은 맨 뒤 순위', () => { let s = tick(make(['A', 'B', 'C']), START); s = act(s, 'A', sel(findMoves(s.initial)[0]!), START + 500); expect(apple.onLeave!(s, 'A')).toEqual({ type: 'leave' }); s = act(s, 'A', { type: 'leave' }, START + 600); expect(s.phase).toBe('playing'); expect(reason(s, 'A', sel(findMoves(s.boards.A!)[0]!), START + 700)).toBe('게임에서 빠졌어요.'); expect(apple.onLeave!(s, 'A')).toBeNull(); s = act(s, 'B', { type: 'leave' }, START + 800); expect(s.phase).toBe('ended'); const r = apple.result(s)!; expect(r.ranking).toEqual([['C'], ['A'], ['B']]); expect(r.summary).toBe('다른 사람이 모두 나가서 남은 사람이 이겼어요'); // Solo leaver: the game just ends. Leaving during the countdown works too. const solo = act(make(['A']), 'A', { type: 'leave' }, T0 + 100); expect(solo.phase).toBe('ended'); }); test('클라이언트 액션 스키마에는 select·stop만(tick/leave는 시스템 전용)', () => { expect(apple.actionSchema.safeParse({ type: 'stop' }).success).toBe(true); expect(apple.actionSchema.safeParse({ type: 'tick' }).success).toBe(false); expect(apple.actionSchema.safeParse({ type: 'leave' }).success).toBe(false); expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 9, c1: 16 }).success).toBe(true); expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 10, c1: 16 }).success).toBe(false); expect(apple.actionSchema.safeParse({ type: 'select', r0: 0, c0: 0, r1: 1, c1: 1.5 }).success).toBe(false); }); }); describe('제한 시간 무제한', () => { test('마감 없음: 모두 막히거나 「여기까지」하면 끝, 시간 제한 방에서는 여기까지 거절', () => { let s = make(['A', 'B'], { timeLimitSec: null }); expect(s.endsAt).toBeNull(); expect(apple.deadline!(s)).toBe(s.countdownEndsAt); expect(reason(s, 'A', { type: 'stop' }, T0 + 100)).toBe('곧 시작해요. 잠시만 기다려 주세요.'); s = tick(s, START); expect(s.phase).toBe('playing'); expect(s.status.A).toBe('playing'); // the start tick is not an away tick expect(apple.deadline!(s)).toBeNull(); expect(apple.timeoutNotBefore!(s)).toBeNull(); // Hours later the board still takes moves. const m = findMoves(s.initial)[0]!; s = act(s, 'A', sel(m), START + 3_600_000); expect(s.score.A).toBeGreaterThan(0); s = act(s, 'A', { type: 'stop' }, START + 3_600_100); expect(s.status.A).toBe('done'); expect(reason(s, 'A', { type: 'stop' }, START + 3_600_200)).toBe('이미 끝냈어요.'); expect(apple.activePlayers(s)).toEqual(['B']); expect(apple.timeoutPlayers!(s)).toEqual(['B']); s = act(s, 'B', { type: 'stop' }, START + 3_600_300); expect(s.phase).toBe('ended'); const r = apple.result(s)!; expect(r.ranking).toEqual([['A'], ['B']]); expect(r.summary).toContain('모두 끝냈어요'); expect(reason(tick(make(['A']), START), 'A', { type: 'stop' }, START + 10)).toBe('제한 시간이 있는 방에서는 끝날 때까지 해요.'); }); test('자리 비움: 방이 유예 뒤 tick을 보내면 그 사람은 여기까지(점수 유지), 혼자면 바로 끝', () => { let s = tick(make(['A', 'B'], { timeLimitSec: null }), START); s = act(s, 'B', sel(findMoves(s.initial)[0]!), START + 500); s = apple.apply(s, 'B', { type: 'tick' }, { rng: rng(), now: START + 60_000 }).state; expect(s.status.B).toBe('done'); expect(s.score.B).toBeGreaterThan(0); expect(s.phase).toBe('playing'); const solo = apple.apply(tick(make(['A'], { timeLimitSec: null }), START), 'A', { type: 'tick' }, { rng: rng(), now: START + 60_000 }).state; expect(solo.phase).toBe('ended'); expect(apple.result(solo)!.summary).toBe('여기까지 했어요. 사과 0개를 지웠어요'); }); }); describe('무작위 대국', () => { test.each([1, 2, 5, 8])('%i명: 엔진 randomPlayout(유출·JSON·결정성) 끝까지', (n) => { const players = Array.from({ length: n }, (_, i) => `p${i + 1}`); for (let i = 0; i < playoutSeeds(20); i++) { const a = randomPlayout(apple, { players, seed: seedN(700 + n * 10 + i), maxSteps: 1000, maxApplyMs: 20 }); expect(a.finished).toBe(true); const b = randomPlayout(apple, { players, seed: seedN(700 + n * 10 + i), maxSteps: 1000, maxApplyMs: 20 }); expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState)); const r = apple.result(a.finalState as AppleState)!; expect(r.ranking.flat().sort()).toEqual([...players].sort()); const s = a.finalState as AppleState; // Score = apples gone from the board. for (const p of players) expect(s.score[p]).toBe([...s.boards[p]!].filter((c) => c === '0').length); } }); test.each([1, 3])('무제한 %i명: 끝까지(여기까지·자리 비움 tick 포함)', (n) => { const players = Array.from({ length: n }, (_, i) => `p${i + 1}`); for (let i = 0; i < playoutSeeds(10); i++) { const a = randomPlayout(apple, { players, options: apple.optionsSchema.parse({ timeLimitSec: null }), seed: seedN(900 + n * 10 + i), maxSteps: 1000, maxApplyMs: 20 }); expect(a.finished).toBe(true); } }); });