Files
joke-app/packages/games/src/nonogram/nonogram.test.ts

322 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import { PICTURES } from './bank';
import { COUNTDOWN_MS, makePicture, nonogram, type NonogramOptions, type NonogramState } from './index';
import { clueOf, solveGrid, solveLine, type Known } from './solver';
const T0 = 1_000_000;
const START = T0 + COUNTDOWN_MS;
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
type A = Parameters<typeof nonogram.apply>[2];
function make(players = ['A', 'B'], opts: Partial<NonogramOptions> = {}, seed = 1): NonogramState {
return nonogram.setup({ players, options: nonogram.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 });
}
function act(s: NonogramState, p: string, a: A, now = START + 1000): NonogramState {
const v = nonogram.validate(s, p, a, { now });
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
return nonogram.apply(s, p, a, { rng: rng(), now }).state;
}
const reason = (s: NonogramState, p: string, a: A, now = START + 1000) => {
const v = nonogram.validate(s, p, a, { now });
return v.ok ? 'ok' : v.reason;
};
const started = (players?: string[], opts?: Partial<NonogramOptions>, seed?: number) => nonogram.apply(make(players, opts, seed), 'A', { type: 'tick' }, { rng: rng(), now: START }).state;
/** The filled cells of row r in the answer. */
const rowFill = (s: NonogramState, r: number) => Array.from({ length: s.puzzle.size }, (_, c) => r * s.puzzle.size + c).filter((i) => s.puzzle.solution[i] === '#');
/** Fills the answer's cells of row r that are not filled yet (nothing to do → unchanged). */
function fillRow(s: NonogramState, p: string, r: number, now: number): NonogramState {
const cells = rowFill(s, r).filter((i) => s.boards[p]!.marks[i] !== '1');
return cells.length ? act(s, p, { type: 'paint', cells, value: 1 }, now) : s;
}
/** Fills every row's answer cells, one row per second; stops when I am finished. */
function solve(s: NonogramState, p: string, from = START + 1000): NonogramState {
for (let r = 0; r < s.puzzle.size && s.status[p] === 'playing'; r++) s = fillRow(s, p, r, from + r * 1000);
return s;
}
describe('nonogram · 그림', () => {
test('크기별 그림 수, 빈 줄 없음, 줄 논리만으로 답이 하나로 다 풀림', () => {
expect(PICTURES[5].length).toBeGreaterThanOrEqual(10);
expect(PICTURES[10].length).toBeGreaterThanOrEqual(14);
expect(PICTURES[15].length).toBeGreaterThanOrEqual(10);
for (const size of [5, 10, 15] as const) {
expect(new Set(PICTURES[size].map((p) => p.name)).size).toBe(PICTURES[size].length);
for (const pic of PICTURES[size]) {
expect(pic.rows, pic.name).toHaveLength(size);
for (const r of pic.rows) expect(r, pic.name).toMatch(new RegExp(`^[#.]{${size}}$`));
const p = makePicture(pic.rows, pic.name, pic.color);
expect([...p.rows, ...p.cols].every((c) => c.length > 0), `${size} ${pic.name}: empty line`).toBe(true);
const g = solveGrid(size, p.rows, p.cols)!;
expect(g, pic.name).not.toBeNull();
expect(g.map((x) => (x === 1 ? '#' : x === 0 ? '.' : '?')).join(''), `${size} ${pic.name}`).toBe(p.solution);
}
}
});
test('줄 풀기: 겹치는 칸, 다 채운 줄, 아는 칸에서 이어 풀기, 모순', () => {
const u = (n: number): Known[] => new Array<Known>(n).fill(-1);
expect(solveLine([3], u(4))).toEqual([-1, 1, 1, -1]);
expect(solveLine([2, 2], u(5))).toEqual([1, 1, 0, 1, 1]);
expect(solveLine([], u(3))).toEqual([0, 0, 0]);
expect(solveLine([1], [-1, -1, 1, -1])).toEqual([0, 0, 1, 0]);
expect(solveLine([2], [1, -1, -1, -1])).toEqual([1, 1, 0, 0]);
expect(solveLine([1, 1], [-1, 1, -1, -1, -1])).toEqual([0, 1, 0, -1, -1]);
expect(solveLine([3], [-1, 0, -1, -1])).toBeNull();
expect(solveLine([1], [1, -1, 1])).toBeNull();
expect(clueOf('.##.#..###')).toEqual([2, 1, 3]);
});
});
describe('nonogram · 판 만들기', () => {
test('크기 선택, 같은 시드 = 같은 그림, 모두 같은 빈 판으로 시작, 카운트다운에는 판을 안 보여 줌', () => {
for (const size of [5, 10, 15] as const) {
const s = make(['A', 'B', 'C'], { size });
expect(s.puzzle.size).toBe(size);
expect(PICTURES[size].map((p) => p.name)).toContain(s.puzzle.name);
expect(make(['A', 'B', 'C'], { size })).toEqual(s);
expect(new Set(Object.values(s.boards).map((b) => b.marks)).size).toBe(1);
expect(s.boards.A!.marks).toBe('0'.repeat(size * size));
expect(nonogram.view(s, 'A').board).toBeNull();
expect(reason(s, 'A', { type: 'paint', cells: [0], value: 1 }, T0 + 100)).toContain('곧 시작');
checkNoLeak(nonogram, s, 'A', s.order);
}
const names = new Set(Array.from({ length: 30 }, (_, k) => make(['A'], {}, k + 1).puzzle.name));
expect(names.size).toBeGreaterThan(5);
});
test('기본: 10×10, 힌트 켬, 제한 시간 20분', () => {
expect(nonogram.defaultOptions).toEqual({ size: 10, hints: true, timeLimitSec: 1200 });
expect(make().endsAt).toBe(START + 1_200_000);
});
});
describe('nonogram · 칠하기·힌트', () => {
test('한 줄의 칸들을 채우기·X·지우기, 내 판만 바뀜, 맞는지는 알려 주지 않음', () => {
let s = started();
s = act(s, 'A', { type: 'paint', cells: [0, 1, 2], value: 1 });
expect(s.boards.A!.marks.slice(0, 4)).toBe('1110');
expect(s.boards.B!.marks.slice(0, 4)).toBe('0000');
s = act(s, 'A', { type: 'paint', cells: [1], value: 2 });
expect(s.boards.A!.marks.slice(0, 3)).toBe('121');
s = act(s, 'A', { type: 'paint', cells: [0, 10, 20], value: 0 });
expect(s.boards.A!.marks.slice(0, 3)).toBe('021');
const v = nonogram.view(s, 'A').board!;
expect(v.marks.slice(0, 3)).toBe('021');
expect(v.answer).toBeNull();
expect(v.rows).toEqual(s.puzzle.rows);
expect(v.cols).toEqual(s.puzzle.cols);
});
test('거절: 판 밖, 같은 칸 두 번, 한 줄이 아님, 바뀌는 칸 없음, 15칸 넘게, 이상한 값', () => {
const s = started();
expect(reason(s, 'A', { type: 'paint', cells: [100], value: 1 })).toBe('판 밖의 칸이에요.');
expect(reason(s, 'A', { type: 'paint', cells: [3, 3], value: 1 })).toBe('같은 칸이 두 번 들어 있어요.');
expect(reason(s, 'A', { type: 'paint', cells: [0, 11], value: 1 })).toContain('한 줄');
expect(reason(s, 'A', { type: 'paint', cells: [9, 10], value: 1 })).toContain('한 줄');
expect(reason(s, 'A', { type: 'paint', cells: [5, 25, 95], value: 1 })).toBe('ok');
expect(reason(s, 'A', { type: 'paint', cells: [0, 1], value: 0 })).toBe('바뀌는 칸이 없어요.');
const parse = (a: unknown) => nonogram.actionSchema.safeParse(a).success;
expect(parse({ type: 'paint', cells: [0, 1], value: 2 })).toBe(true);
expect(parse({ type: 'paint', cells: Array.from({ length: 16 }, (_, i) => i), value: 1 })).toBe(false);
expect(parse({ type: 'paint', cells: [], value: 1 })).toBe(false);
expect(parse({ type: 'paint', cells: [0], value: 3 })).toBe(false);
expect(parse({ type: 'paint', cells: [225], value: 1 })).toBe(false);
const big = started(['A'], { size: 15 });
expect(reason(big, 'A', { type: 'paint', cells: Array.from({ length: 15 }, (_, c) => 14 * 15 + c), value: 2 })).toBe('ok');
});
test('힌트: 틀렸거나 모르는 칸 하나를 바른 상태로(채움 또는 X), 횟수가 결과에 붙음; 힌트 끈 방은 거절', () => {
let s = started(['A']);
// Fill every empty cell of row 0 by mistake, so a hint must fix a wrong cell or set an unknown one.
const wrong = Array.from({ length: 10 }, (_, c) => c).filter((i) => s.puzzle.solution[i] === '.');
if (wrong.length) s = act(s, 'A', { type: 'paint', cells: wrong, value: 1 });
for (let k = 1; k <= 5; k++) {
const before = s.boards.A!.marks;
s = act(s, 'A', { type: 'hint' }, START + 1000 + k * 200);
const i = s.boards.A!.lastHint!;
expect(before[i]).not.toBe(s.puzzle.solution[i] === '#' ? '1' : '2');
expect(s.boards.A!.marks[i]).toBe(s.puzzle.solution[i] === '#' ? '1' : '2');
expect([...s.boards.A!.marks].filter((ch, j) => ch !== before[j])).toHaveLength(1);
expect(s.boards.A!.hints).toBe(k);
}
expect(nonogram.view(s, 'A').board!.lastHint).toBe(s.boards.A!.lastHint);
expect(nonogram.view(s, 'A').seats[0]!.extra).toBe(' · 힌트 5번');
s = solve(s, 'A', START + 5000);
// Undo the wrong cells of row 0 if still there.
const left = wrong.filter((i) => s.boards.A!.marks[i] === '1');
if (s.status.A === 'playing' && left.length) s = act(s, 'A', { type: 'paint', cells: left, value: 0 }, START + 30_000);
expect(s.status.A).toBe('solved');
expect(nonogram.result(s)!.scoreText!.A).toMatch(/^다 풀었어요 · .* · 힌트 5번$/);
expect(s.final!.summary).toMatch(/힌트 5번$/);
const off = started(['A'], { hints: false });
expect(reason(off, 'A', { type: 'hint' })).toBe('이 방은 힌트를 쓰지 않아요.');
});
test('힌트만 계속 써도 언젠가 다 풀림', () => {
let s = started(['A'], { size: 5 });
for (let k = 0; k < 25 && s.status.A === 'playing'; k++) s = act(s, 'A', { type: 'hint' }, START + 1000 * (k + 1));
expect(s.status.A).toBe('solved');
});
});
describe('nonogram · 다 풀기·진행도', () => {
test('채운 칸이 답과 똑같으면 다 풂(X는 상관없음) → 혼자면 바로 끝, 그림과 이름 공개', () => {
let s = started(['A']);
const empties = Array.from({ length: 10 }, (_, c) => 90 + c).filter((i) => s.puzzle.solution[i] === '.');
if (empties.length) s = act(s, 'A', { type: 'paint', cells: empties, value: 2 });
s = solve(s, 'A', START + 2000);
expect(s.status.A).toBe('solved');
expect(s.phase).toBe('ended');
expect(s.final!.summary).toMatch(/^다 풀었어요! 걸린 시간 /);
const v = nonogram.view(s, 'A').board!;
expect(v.answer).toEqual({ solution: s.puzzle.solution, name: s.puzzle.name, color: s.puzzle.color });
expect(nonogram.view(s, 'A').seats[0]!.progressText).toBe('맞는 줄 20/20');
});
test('채운 칸이 하나라도 더 많으면 아직, 지우면 다 풂', () => {
let s = started(['A']);
const extra = [...s.puzzle.solution].findIndex((ch) => ch === '.');
s = act(s, 'A', { type: 'paint', cells: [extra], value: 1 }, START + 500);
s = solve(s, 'A');
expect(s.status.A).toBe('playing');
s = act(s, 'A', { type: 'paint', cells: [extra], value: 0 }, START + 20_000);
expect(s.status.A).toBe('solved');
});
test('진행도 = 지금 채운 칸이 숫자와 맞는 줄 수(답을 알려 주지 않음)', () => {
let s = started(['A', 'B']);
const seat = () => nonogram.view(s, 'B').seats.find((x) => x.id === 'A')!;
expect(seat().progress).toBe(0);
expect(seat().progressText).toBe('맞는 줄 0/20');
s = act(s, 'A', { type: 'paint', cells: rowFill(s, 0), value: 1 });
// Row 0 now matches; some columns may match too (their only run is in row 0 of length 1).
const p1 = seat().progress;
expect(p1).toBeGreaterThanOrEqual(1);
const colsOk = s.puzzle.cols.filter((c, col) => c.length === 1 && c[0] === 1 && s.puzzle.solution[col] === '#').length;
expect(p1).toBe(1 + colsOk);
// Matching by count only: the same run lengths in the wrong place still count for that row.
let t = started(['A'], { size: 5 });
const clue = t.puzzle.rows[0]!;
const cells: number[] = [];
let at = 5 - clue.reduce((a, b) => a + b, 0) - (clue.length - 1);
for (const len of clue) {
for (let k = 0; k < len; k++) cells.push(at + k);
at += len + 1;
}
t = act(t, 'A', { type: 'paint', cells, value: 1 });
expect(nonogram.view(t, 'A').seats[0]!.progress).toBeGreaterThanOrEqual(1);
});
});
describe('nonogram · 순위·끝', () => {
test('먼저 다 푼 사람 > 다 못 푼 사람(맞는 줄 많은 순), 같은 진행도 같은 순위, 나간 사람 맨 아래', () => {
let s = started(['A', 'B', 'C', 'D']);
s = act(s, 'B', { type: 'paint', cells: rowFill(s, 0), value: 1 });
s = act(s, 'C', { type: 'paint', cells: rowFill(s, 0), value: 1 });
s = act(s, 'D', { type: 'leave' } as A);
s = act(s, 'B', { type: 'stop' }, START + 2000);
s = act(s, 'C', { type: 'stop' }, START + 2000);
s = solve(s, 'A', START + 3000);
expect(s.phase).toBe('ended');
const r = s.final!.ranking;
expect(r.map((x) => x.id)).toEqual(['A', r[1]!.id, r[2]!.id, 'D']);
expect(r[0]!.status).toBe('solved');
expect(r[1]!.rank).toBe(2);
expect(r[2]!.rank).toBe(2);
expect(r[3]!.rank).toBe(4);
expect(s.final!.summary).toBe('가장 먼저 다 푼 사람이 이겼어요');
expect(nonogram.result(s)!.scoreText!.B).toMatch(/^맞는 줄 \d+\/20 · 포기$/);
expect(nonogram.result(s)!.scores!.A).toBe(20);
});
test('둘이 다 풀면 빠른 사람이 1등', () => {
let s = started(['A', 'B']);
s = solve(s, 'B', START + 500);
s = solve(s, 'A', START + 20_000);
expect(s.final!.ranking.map((r) => r.id)).toEqual(['B', 'A']);
expect(s.final!.ranking[0]!.timeMs).toBeLessThan(s.final!.ranking[1]!.timeMs!);
});
test('제한 시간: 마감 tick으로 끝, 마감 뒤 거절, 아무도 못 풀면 맞는 줄 많은 사람이 이김', () => {
let s = started(['A', 'B'], { timeLimitSec: 300 });
s = act(s, 'A', { type: 'paint', cells: rowFill(s, 0), value: 1 });
const end = START + 300_000;
expect(nonogram.deadline!(s)).toBe(end);
expect(nonogram.timeoutNotBefore!(s)).toBe(end);
expect(reason(s, 'B', { type: 'paint', cells: [0], value: 1 }, end)).toBe('시간이 다 됐어요.');
s = nonogram.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('시간이 다 됐어요. 아무도 다 풀지 못했어요. 가장 많이 푼 사람이 이겼어요');
// Game over: both now see the picture.
expect(nonogram.view(s, 'B').board!.answer!.name).toBe(s.puzzle.name);
});
test('무제한: 끊긴 사람은 tick 한 번으로 포기 처리, 모두 끝나면 끝', () => {
let s = started(['A', 'B'], { timeLimitSec: null });
expect(nonogram.deadline!(s)).toBeNull();
s = nonogram.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']);
for (let k = 0; k < 12; k++) s = act(s, 'A', { type: 'paint', cells: [k], value: (k % 2) + 1 as 1 | 2 }, START + 100 + k);
expect(reason(s, 'A', { type: 'paint', cells: [50], value: 2 }, START + 200)).toBe('조금 천천히 해 주세요.');
expect(reason(s, 'A', { type: 'paint', cells: [50], value: 2 }, START + 1200)).toBe('ok');
});
});
describe('nonogram · 숨긴 답', () => {
test('다 풀거나 게임이 끝나기 전에는 내 화면(과 관전 화면)에 답 문자열도 그림 이름도 없음, 포기해도 남이 푸는 동안은 안 보임', () => {
for (let seed = 1; seed <= 12; seed++) {
const size = ([5, 10, 15] as const)[seed % 3]!;
let s = started(['A', 'B'], { size }, seed);
const hidden = (p: string | null) => {
const j = JSON.stringify(nonogram.view(s, p));
expect(j).not.toContain(s.puzzle.solution);
expect(j).not.toContain(s.puzzle.name);
};
hidden('A');
hidden(null);
for (let r = 0; r < size - 1 && s.status.A === 'playing'; r++) {
s = fillRow(s, 'A', r, START + 1000 + r * 1000);
if (r === 1) s = act(s, 'A', { type: 'hint' }, START + 2500);
if (s.status.A !== 'playing') break;
hidden('A');
hidden('B');
hidden(null);
}
if (s.status.A !== 'playing') continue;
s = act(s, 'B', { type: 'stop' }, START + 60_000);
// B gave up but A is still solving: B must not get the answer to pass on.
hidden('B');
hidden('A');
hidden(null);
s = act(s, 'A', { type: 'stop' }, START + 61_000);
expect(s.phase).toBe('ended');
expect(JSON.stringify(nonogram.view(s, 'B'))).toContain(s.puzzle.name);
}
});
});
describe('nonogram · 무작위 대국', () => {
test('1·2·5·8명, 크기 셋: 유출·JSON·결정성', () => {
for (let k = 1; k <= playoutSeeds(60); k++) {
for (const n of [1, 2, 5, 8]) {
const size = ([5, 10, 15] as const)[k % 3]!;
const players = Array.from({ length: n }, (_, i) => `p${i}`);
const options = nonogram.optionsSchema.parse({ size, hints: k % 4 !== 0, timeLimitSec: k % 2 ? null : 300 });
const a = randomPlayout(nonogram, { players, options, seed: seedN(k * 10 + n), maxSteps: 4000 });
expect(a.finished).toBe(true);
const b = randomPlayout(nonogram, { players, options, seed: seedN(k * 10 + n), maxSteps: 4000 });
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
}
}
});
});