Files
joke-app/packages/games/src/sudoku/sudoku.test.ts
EJClaw 1b9acb9fc1 새 게임 5개(같은 판 경주): 지뢰찾기, 사천성, 솔리테어, 스도쿠, 네모네모 로직
- 공통 틀 race: 같은 시드 판을 모두 각자 동시에, 3초 카운트다운, 제한 시간/무제한, 포기, 다 푼 시간 → 푼 만큼 순위, live 컴퓨터
- 지뢰찾기: 초급·중급·고급, 모두에게 같은 곳이 열린 채 시작, 깃발·한꺼번에 열기, 휴대폰 길게 누르기·깃발 모드
- 사천성: 마작패 72·112·136장, 두 번 이하로 꺾이는 선, 항상 풀리는 배치, 막히면 자동 섞기, 힌트
- 솔리테어: 클론다이크(1장·3장)·프리셀·스파이더(1·2·4무늬), 되돌리기, 자동 정리
- 스도쿠: 답이 하나인 문제 생성기(쉬움·보통·어려움), 메모, 겹침 표시, 힌트
- 네모네모 로직: 그림 37개(5×5·10×10·15×15, 모두 줄 논리만으로 풀림), 드래그 칠하기·X 표시, 풀면 그림과 이름
- 게임 46개, 컴퓨터 상대 42개, 게임 고르기에 혼자·퍼즐 탭
(아발론·모노레일은 아직 공개 전이라 이 배포에서 뺌; 작업 갈래 codex/owner/grp_discord_joke-app 2773f5c..에서 옮김)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:29:01 +09:00

231 lines
13 KiB
TypeScript

import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import { COUNTDOWN_MS, PEERS, UNITS, countSolutions, makePuzzle, solvesWithSingles, sudoku, type SudokuOptions, type SudokuState } from './index';
const T0 = 1_000_000;
const START = T0 + COUNTDOWN_MS;
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
type A = Parameters<typeof sudoku.apply>[2];
function make(players = ['A', 'B'], opts: Partial<SudokuOptions> = {}, seed = 1): SudokuState {
return sudoku.setup({ players, options: sudoku.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 });
}
function act(s: SudokuState, p: string, a: A, now = START + 1000): SudokuState {
const v = sudoku.validate(s, p, a, { now });
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
return sudoku.apply(s, p, a, { rng: rng(), now }).state;
}
const reason = (s: SudokuState, p: string, a: A, now = START + 1000) => {
const v = sudoku.validate(s, p, a, { now });
return v.ok ? 'ok' : v.reason;
};
const started = (players?: string[], opts?: Partial<SudokuOptions>, seed?: number) => sudoku.apply(make(players, opts, seed), 'A', { type: 'tick' }, { rng: rng(), now: START }).state;
const blanks = (s: SudokuState) => [...s.puzzle.givens].flatMap((ch, i) => (ch === '0' ? [i] : []));
const givenCell = (s: SudokuState) => [...s.puzzle.givens].findIndex((ch) => ch !== '0');
const right = (s: SudokuState, i: number) => Number(s.puzzle.solution[i]);
const wrongDigit = (s: SudokuState, i: number) => (right(s, i) % 9) + 1;
/** Fills every blank of `p` with the right number, one move each `gap` ms from `from`. */
function solveAll(s: SudokuState, p: string, from = START, gap = 200): SudokuState {
let now = from;
for (const i of blanks(s)) {
if (s.phase === 'ended' || s.status[p] !== 'playing') break;
if (s.boards[p]!.values[i] === s.puzzle.solution[i]) continue;
now += gap;
s = act(s, p, { type: 'set', i, n: right(s, i) }, now);
}
return s;
}
describe('sudoku · 퍼즐 만들기', () => {
test('난이도마다 30판: 해답이 딱 하나, 올바른 스도쿠, 숫자 개수, 쉬움은 싱글만으로 풀림, 300ms 안, 같은 시드 = 같은 판', () => {
const count = { easy: [38, 40], normal: [30, 32], hard: [17, 28] } as const;
for (const d of ['easy', 'normal', 'hard'] as const) {
let sum = 0;
for (let k = 1; k <= 30; k++) {
const t = performance.now();
const p = makePuzzle(SeededRng.fromSeed(seedN(k)), d);
expect(performance.now() - t).toBeLessThan(300);
const g = [...p.givens].map(Number);
expect(countSolutions(g)).toBe(1);
for (const unit of UNITS) expect(new Set(unit.map((i) => p.solution[i])).size).toBe(9);
for (let i = 0; i < 81; i++) if (g[i]) expect(p.solution[i]).toBe(p.givens[i]);
const n = g.filter(Boolean).length;
sum += n;
expect(n).toBeGreaterThanOrEqual(count[d][0]);
expect(n).toBeLessThanOrEqual(count[d][1]);
if (d === 'easy') expect(solvesWithSingles(g)).toBe(true);
expect(makePuzzle(SeededRng.fromSeed(seedN(k)), d)).toEqual(p);
}
if (d === 'hard') expect(sum / 30).toBeLessThanOrEqual(26);
}
});
test('모두 같은 판으로 시작, 카운트다운에는 판을 안 보여 줌, 기본은 쉬움·힌트 켬·30분', () => {
const s = make(['A', 'B', 'C']);
expect(new Set(Object.values(s.boards).map((b) => b.values)).size).toBe(1);
expect(s.boards.A!.values).toBe(s.puzzle.givens);
expect(sudoku.defaultOptions).toEqual({ difficulty: 'easy', hints: true, timeLimitSec: 1800 });
expect(s.endsAt).toBe(START + 1_800_000);
expect(sudoku.view(s, 'A').board).toBeNull();
expect(reason(s, 'A', { type: 'set', i: blanks(s)[0]!, n: 1 }, T0 + 100)).toContain('곧 시작');
checkNoLeak(sudoku, s, 'A', s.order);
});
});
describe('sudoku · 숫자·지우기·메모·힌트', () => {
test('숫자 넣기: 빈칸·내 숫자만 바꿈, 틀린 숫자도 넣을 수 있고 맞는지 알려 주지 않음, 내 판만 바뀜', () => {
let s = started();
const i = blanks(s)[0]!;
expect(reason(s, 'A', { type: 'set', i: givenCell(s), n: 1 })).toBe('처음부터 있던 숫자는 바꿀 수 없어요.');
s = act(s, 'A', { type: 'set', i, n: wrongDigit(s, i) });
expect(s.boards.A!.values[i]).toBe(String(wrongDigit(s, i)));
expect(s.boards.B!.values[i]).toBe('0');
expect(reason(s, 'A', { type: 'set', i, n: wrongDigit(s, i) })).toBe('이미 그 숫자예요.');
const v = sudoku.view(s, 'A');
expect(v.seats.find((x) => x.id === 'A')!.progressText).toBe(`채운 칸 1/${blanks(s).length}`);
s = act(s, 'A', { type: 'set', i, n: right(s, i) });
expect(sudoku.view(s, 'A').seats.find((x) => x.id === 'A')!.progress).toBe(1); // right or wrong, a filled cell counts the same
});
test('지우기: 숫자를 지우고, 숫자가 없으면 메모를 지움, 지울 게 없으면 거절', () => {
let s = started();
const i = blanks(s)[0]!;
expect(reason(s, 'A', { type: 'clear', i })).toBe('지울 것이 없어요.');
expect(reason(s, 'A', { type: 'clear', i: givenCell(s) })).toBe('처음부터 있던 숫자는 바꿀 수 없어요.');
s = act(s, 'A', { type: 'set', i, n: 5 });
s = act(s, 'A', { type: 'clear', i });
expect(s.boards.A!.values[i]).toBe('0');
s = act(s, 'A', { type: 'note', i, n: 3 });
s = act(s, 'A', { type: 'clear', i });
expect(s.boards.A!.notes[i]).toBe(0);
});
test('메모: 빈칸에만 켜고 끄기, 숫자를 넣으면 그 칸 메모와 같은 줄·칸·상자의 같은 숫자 메모가 지워짐', () => {
let s = started();
const [i, j] = blanks(s);
expect(reason(s, 'A', { type: 'note', i: givenCell(s), n: 1 })).toBe('처음부터 있던 숫자는 바꿀 수 없어요.');
s = act(s, 'A', { type: 'note', i: i!, n: 4 });
s = act(s, 'A', { type: 'note', i: i!, n: 7 });
expect(s.boards.A!.notes[i!]).toBe((1 << 4) | (1 << 7));
s = act(s, 'A', { type: 'note', i: i!, n: 7 });
expect(s.boards.A!.notes[i!]).toBe(1 << 4);
// Marks of 2 and 4 on every blank peer of j and on one cell far away.
const peer = PEERS[j!]!.filter((k) => s.puzzle.givens[k] === '0');
const far = blanks(s).find((k) => k !== j && !PEERS[j!]!.includes(k))!;
let now = START + 2000;
for (const k of [...peer, far, j!]) for (const n of [2, 4]) if (!(s.boards.A!.notes[k]! & (1 << n))) s = act(s, 'A', { type: 'note', i: k, n }, (now += 100));
s = act(s, 'A', { type: 'set', i: j!, n: 4 }, (now += 100));
expect(s.boards.A!.notes[j!]).toBe(0);
for (const k of peer) expect(s.boards.A!.notes[k]).toBe(1 << 2);
expect(s.boards.A!.notes[far]).toBe((1 << 2) | (1 << 4));
expect(reason(s, 'A', { type: 'note', i: j!, n: 1 }, now + 1000)).toBe('숫자가 있는 칸에는 메모할 수 없어요.');
});
test('힌트: 빈칸이나 틀린 칸 하나를 맞는 숫자로, 횟수는 결과에 · 힌트 N번, 힌트를 끈 방에서는 거절', () => {
let s = started(['A']);
const bl = blanks(s);
// Everything right except one wrong cell: the hint can only fix that one.
bl.slice(1).forEach((i, k) => (s = act(s, 'A', { type: 'set', i, n: right(s, i) }, START + 100 * (k + 1))));
s = act(s, 'A', { type: 'set', i: bl[0]!, n: wrongDigit(s, bl[0]!) }, START + 8000);
expect(s.status.A).toBe('playing');
s = act(s, 'A', { type: 'hint' }, START + 9000);
expect(s.boards.A!.values[bl[0]!]).toBe(s.puzzle.solution[bl[0]!]);
expect(s.boards.A!.hintAt).toBe(bl[0]!);
expect(s.status.A).toBe('solved');
expect(s.final!.summary).toBe('다 풀었어요! 걸린 시간 9.0초 · 힌트 1번');
expect(sudoku.result(s)!.scoreText!.A).toBe('다 풀었어요 · 9.0초 · 힌트 1번');
const off = started(['A'], { hints: false });
expect(reason(off, 'A', { type: 'hint' })).toBe('이 방은 힌트를 쓸 수 없어요.');
});
test('모두 맞게 채우면 다 풂 → 혼자면 바로 끝, 다 푼 뒤에야 내 화면에 정답이 보임', () => {
let s = started(['A', 'B']);
expect(JSON.stringify(sudoku.view(s, 'A'))).not.toContain(s.puzzle.solution);
s = solveAll(s, 'A');
expect(s.status.A).toBe('solved');
expect(sudoku.view(s, 'A').board!.solution).toBe(s.puzzle.solution);
expect(sudoku.view(s, 'B').board!.solution).toBeUndefined();
expect(JSON.stringify(sudoku.view(s, 'B'))).not.toContain(s.puzzle.solution);
expect(JSON.stringify(sudoku.view(s, null))).not.toContain(s.puzzle.solution);
expect(reason(s, 'A', { type: 'set', i: 0, n: 1 })).toBe('이미 끝냈어요.');
s = act(s, 'B', { type: 'stop' });
expect(s.phase).toBe('ended');
expect(sudoku.view(s, 'B').board!.solution).toBe(s.puzzle.solution);
});
});
describe('sudoku · 순위·끝', () => {
test('먼저 다 푼 사람 > 채운 칸 많은 순(같으면 같은 순위), 나간 사람 맨 아래', () => {
let s = started(['A', 'B', 'C', 'D', 'E']);
const bl = blanks(s);
s = act(s, 'B', { type: 'set', i: bl[0]!, n: wrongDigit(s, bl[0]!) });
s = act(s, 'B', { type: 'set', i: bl[1]!, n: right(s, bl[1]!) });
s = act(s, 'C', { type: 'set', i: bl[2]!, n: right(s, bl[2]!) });
s = act(s, 'D', { type: 'set', i: bl[3]!, n: right(s, bl[3]!) });
s = act(s, 'E', { type: 'leave' } as A);
s = act(s, 'B', { type: 'stop' });
s = act(s, 'C', { type: 'stop' });
s = act(s, 'D', { type: 'stop' });
s = solveAll(s, 'A');
expect(s.phase).toBe('ended');
const r = s.final!.ranking;
expect(r.map((x) => x.id)).toEqual(['A', 'B', r[2]!.id, r[3]!.id, 'E']);
expect(r.map((x) => x.rank)).toEqual([1, 2, 3, 3, 5]);
expect(s.final!.summary).toBe('가장 먼저 다 푼 사람이 이겼어요');
expect(sudoku.result(s)!.scoreText!.B).toBe(`채운 칸 2/${bl.length} · 포기`);
expect(sudoku.result(s)!.scores!.B).toBe(2);
});
test('제한 시간: 마감 tick으로 끝, 마감 뒤 거절, 아무도 못 풀면 많이 채운 사람이 이김', () => {
let s = started(['A', 'B'], { timeLimitSec: 600 });
const i = blanks(s)[0]!;
s = act(s, 'A', { type: 'set', i, n: 1 });
const end = START + 600_000;
expect(sudoku.deadline!(s)).toBe(end);
expect(reason(s, 'B', { type: 'set', i, n: 1 }, end)).toBe('시간이 다 됐어요.');
s = sudoku.apply(s, 'A', { type: 'tick' }, { rng: rng(), now: end }).state;
expect(s.final!.endReason).toBe('time');
expect(s.final!.ranking[0]!.id).toBe('A');
expect(s.final!.summary).toBe('시간이 다 됐어요. 아무도 다 풀지 못했어요. 가장 많이 푼 사람이 이겼어요');
expect(sudoku.view(s, 'A').board!.solution).toBe(s.puzzle.solution);
});
test('무제한: 끊긴 사람은 tick 한 번으로 포기 처리, 모두 끝나면 끝', () => {
let s = started(['A', 'B'], { timeLimitSec: null });
expect(sudoku.deadline!(s)).toBeNull();
s = sudoku.apply(s, 'B', { type: 'tick' }, { rng: rng(), now: START + 70_000 }).state;
expect(s.status.B).toBe('done');
s = act(s, 'A', { type: 'stop' }, START + 80_000);
expect(s.phase).toBe('ended');
expect(s.final!.summary).toContain('아무도 다 풀지 못했어요');
});
test('속도 제한: 1초에 12번까지', () => {
let s = started(['A']);
const i = blanks(s)[0]!;
for (let k = 0; k < 12; k++) s = act(s, 'A', { type: 'note', i, n: 1 + (k % 9) }, START + 100 + k);
expect(reason(s, 'A', { type: 'note', i, n: 1 }, START + 200)).toBe('조금 천천히 해 주세요.');
expect(reason(s, 'A', { type: 'note', i, n: 1 }, START + 1200)).toBe('ok');
});
});
describe('sudoku · 무작위 대국', () => {
test('1·2·5·8명, 난이도 셋: 유출·JSON·결정성, 다 풀기 전 내 화면에 정답 없음', () => {
for (let k = 1; k <= playoutSeeds(60); k++) {
for (const n of [1, 2, 5, 8]) {
const difficulty = (['easy', 'normal', 'hard'] as const)[k % 3]!;
const players = Array.from({ length: n }, (_, i) => `p${i}`);
const options = sudoku.optionsSchema.parse({ difficulty, hints: k % 2 === 0, timeLimitSec: k % 2 ? null : 600 });
const invariant = (st: unknown) => {
const s = st as SudokuState;
for (const p of players) if (s.phase !== 'ended' && s.status[p] === 'playing') expect(JSON.stringify(sudoku.view(s, p))).not.toContain(s.puzzle.solution);
};
const a = randomPlayout(sudoku, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000, invariant });
expect(a.finished).toBe(true);
const b = randomPlayout(sudoku, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000 });
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
}
}
});
});