새 게임 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>
This commit is contained in:
101
packages/games/src/nonogram/bank.ts
Normal file
101
packages/games/src/nonogram/bank.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* 네모네모 로직 pictures (docs/games/nonogram.md §3). Hand-drawn, '#' filled, '.' empty. Every one has exactly one
|
||||
* answer that line logic alone reaches (nonogram.test.ts checks each with ./solver), and no empty row or column.
|
||||
* `color` paints the picture once it is solved.
|
||||
*/
|
||||
|
||||
export interface Picture {
|
||||
name: string;
|
||||
color: string;
|
||||
rows: string[];
|
||||
}
|
||||
|
||||
export const PICTURES: Record<5 | 10 | 15, Picture[]> = {
|
||||
5: [
|
||||
{ name: '하트', color: '#ef4444', rows: ['.#.#.', '#####', '#####', '.###.', '..#..'] },
|
||||
{ name: '집', color: '#c2410c', rows: ['..#..', '.###.', '#####', '.#.#.', '.###.'] },
|
||||
{ name: '나무', color: '#16a34a', rows: ['..#..', '.###.', '#####', '..#..', '.###.'] },
|
||||
{ name: '우산', color: '#7c3aed', rows: ['.###.', '#####', '..#..', '..#..', '.##..'] },
|
||||
{ name: '별', color: '#eab308', rows: ['..#..', '#####', '.###.', '.#.#.', '#...#'] },
|
||||
{ name: '화살표', color: '#2563eb', rows: ['..#..', '.###.', '#.#.#', '..#..', '..#..'] },
|
||||
{ name: '음표', color: '#4f46e5', rows: ['..##.', '..#.#', '..#..', '###..', '###..'] },
|
||||
{ name: '컵', color: '#a16207', rows: ['####.', '###.#', '###.#', '####.', '.##..'] },
|
||||
{ name: '버섯', color: '#dc2626', rows: ['.###.', '#####', '#.#.#', '..#..', '.###.'] },
|
||||
{ name: '고양이', color: '#f97316', rows: ['#...#', '#####', '#.#.#', '#####', '.###.'] },
|
||||
{ name: '해', color: '#f59e0b', rows: ['#.#.#', '.###.', '#####', '.###.', '#.#.#'] },
|
||||
],
|
||||
10: [
|
||||
{ name: '고양이', color: '#f97316', rows: ['.#......#.', '.##....##.', '.########.', '##########', '##.####.##', '##########', '###.##.###', '####..####', '.########.', '..######..'] },
|
||||
{ name: '사과', color: '#dc2626', rows: ['.....#....', '....#.....', '..##.###..', '.########.', '##########', '##########', '##########', '.########.', '.########.', '..##..##..'] },
|
||||
{ name: '물고기', color: '#0ea5e9', rows: ['....###...', '...#####..', '#.#######.', '##.####.##', '###.######', '###.######', '##.#######', '#.#######.', '...#####..', '....###...'] },
|
||||
{ name: '오리', color: '#eab308', rows: ['...###....', '..#####...', '..##.###..', '..########', '...####...', '#..#####..', '##########', '##########', '.########.', '..######..'] },
|
||||
{ name: '자동차', color: '#2563eb', rows: ['...#####..', '..##.#.##.', '.###.#.###', '##########', '##########', '##########', '##########', '.###..###.', '.###..###.', '..#....#..'] },
|
||||
{ name: '로켓', color: '#64748b', rows: ['....##....', '...####...', '...####...', '..##..##..', '..##..##..', '..######..', '..######..', '.########.', '##.####.##', '##..##..##'] },
|
||||
{ name: '꽃', color: '#ec4899', rows: ['..#.##.#..', '..######..', '..######..', '...####...', '....##....', '#...##...#', '##..##..##', '.##.##.##.', '..######..', '....##....'] },
|
||||
{ name: '우산', color: '#7c3aed', rows: ['....##....', '..######..', '.########.', '##########', '##..##..##', '....##....', '....##....', '....##....', '.#..##....', '.####.....'] },
|
||||
{ name: '집', color: '#c2410c', rows: ['....##....', '...####...', '..######..', '.########.', '##########', '.########.', '.#..##..#.', '.#..##..#.', '.#####..#.', '.#####..#.'] },
|
||||
{ name: '하트', color: '#ef4444', rows: ['.##....##.', '####..####', '#.########', '##########', '##########', '.########.', '..######..', '...####...', '....##....', '....##....'] },
|
||||
{ name: '컵', color: '#a16207', rows: ['..#..#....', '.#..#.....', '..#..#....', '#######...', '##########', '#######..#', '#######..#', '##########', '#######...', '.#####....'] },
|
||||
{ name: '버섯', color: '#dc2626', rows: ['...####...', '.########.', '##..##..##', '##..##..##', '##########', '.########.', '...####...', '...####...', '...####...', '..######..'] },
|
||||
{ name: '별', color: '#eab308', rows: ['....##....', '....##....', '...####...', '##########', '.########.', '..######..', '..######..', '.###..###.', '.##....##.', '##......##'] },
|
||||
{ name: '음표', color: '#4f46e5', rows: ['...#######', '...#######', '...#.....#', '...#.....#', '...#.....#', '...#.....#', '.###...###', '####..####', '####..####', '.##....##.'] },
|
||||
{ name: '나무', color: '#16a34a', rows: ['....##....', '...####...', '..######..', '...####...', '..######..', '.########.', '##########', '....##....', '....##....', '..######..'] },
|
||||
],
|
||||
15: [
|
||||
{
|
||||
name: '고양이',
|
||||
color: '#f97316',
|
||||
rows: ['.#...........#.', '.##.........##.', '.###.......###.', '.#############.', '###############', '###############', '###..#####..###', '###..#####..###', '###############', '######...######', '#######.#######', '#####.###.#####', '###############', '.#############.', '...#########...'],
|
||||
},
|
||||
{
|
||||
name: '로켓',
|
||||
color: '#64748b',
|
||||
rows: ['.......#.......', '......###......', '.....#####.....', '.....#####.....', '....###.###....', '....##...##....', '....###.###....', '....#######....', '....#######....', '....#######....', '...#########...', '..###########..', '#####.###.#####', '###...###...###', '......#.#......'],
|
||||
},
|
||||
{
|
||||
name: '자동차',
|
||||
color: '#2563eb',
|
||||
rows: ['.....#####.....', '....#..#..#....', '...##..#..##...', '..###..#..###..', '.#############.', '###############', '#.###########.#', '###############', '###############', '###...###...###', '..###.....###..', '.#####...#####.', '.#####...#####.', '..###.....###..', '###############'],
|
||||
},
|
||||
{
|
||||
name: '집',
|
||||
color: '#c2410c',
|
||||
rows: ['.......#.......', '......###.##...', '.....#######...', '....#######....', '...#########...', '..###########..', '.#############.', '###############', '..###########..', '..##..#######..', '..##..##...##..', '..######...##..', '..######...##..', '..######...##..', '..######...##..'],
|
||||
},
|
||||
{
|
||||
name: '나무',
|
||||
color: '#16a34a',
|
||||
rows: ['.......#.......', '......###......', '.....#####.....', '....#######....', '......###......', '.....#####.....', '...#########...', '..###########..', '.....#####.....', '...#########...', '.#############.', '###############', '......###......', '......###......', '....#######....'],
|
||||
},
|
||||
{
|
||||
name: '오리',
|
||||
color: '#eab308',
|
||||
rows: ['......####.....', '.....######....', '.....###.##....', '..#########....', '.##########....', '......#####....', '......####...#.', '....#######.##.', '.#############.', '###############', '###.....#######', '####...########', '###############', '.#############.', '...#########...'],
|
||||
},
|
||||
{
|
||||
name: '꽃',
|
||||
color: '#ec4899',
|
||||
rows: ['.....#####.....', '..##.#####.##..', '.####.###.####.', '.#####...#####.', '..###.....###..', '.#####...#####.', '.####.###.####.', '..##.#####.##..', '.....#####.....', '.......#.......', '.###...#...###.', '#####..#..#####', '.#####.#.#####.', '...#########...', '.......#.......'],
|
||||
},
|
||||
{
|
||||
name: '물고기',
|
||||
color: '#0ea5e9',
|
||||
rows: ['...........#...', '........#......', '.......###.....', '......######...', '.....########..', '#...##########.', '##.#######.####', '###############', '###############', '##.############', '#...##########.', '.....########..', '......######...', '.......###.....', '........#......'],
|
||||
},
|
||||
{
|
||||
name: '우산',
|
||||
color: '#7c3aed',
|
||||
rows: ['.......#.......', '....#######....', '..###########..', '.#############.', '###############', '###############', '##..#..#..#..##', '.......#.......', '.......#.......', '.......#.......', '.......#.......', '.......#.......', '..#....#.......', '..##..##.......', '...####........'],
|
||||
},
|
||||
{
|
||||
name: '컵',
|
||||
color: '#a16207',
|
||||
rows: ['...#...#...#...', '....#...#...#..', '...#...#...#...', '.###########...', '.##############', '.###########..#', '.###########..#', '.###########..#', '.##############', '.###########...', '.###########...', '..#########....', '...#######.....', '###############', '..###########..'],
|
||||
},
|
||||
{
|
||||
name: '별',
|
||||
color: '#eab308',
|
||||
rows: ['.......#.......', '......###......', '......###......', '.....#####.....', '###############', '.#############.', '..###########..', '...#########...', '....#######....', '...#########...', '...####.####...', '..####...####..', '..###.....###..', '.##.........##.', '.#...........#.'],
|
||||
},
|
||||
],
|
||||
};
|
||||
65
packages/games/src/nonogram/bot.test.ts
Normal file
65
packages/games/src/nonogram/bot.test.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
/** 네모네모 로직 computers (docs/games/nonogram.md §13): never refused, finish the race, stronger levels are faster. */
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { seedN } from '@bg/engine';
|
||||
import { liveBotPlayout } from '../bots/live-playout';
|
||||
import { deductions, nonogramBot } from './bot';
|
||||
import { makePicture, nonogram, type NonogramBoardView, type NonogramState } from './index';
|
||||
|
||||
const isBot = (p: string) => p.startsWith('bot:');
|
||||
|
||||
describe('nonogram · 한 판 전체', () => {
|
||||
test('사람(가만히) + 컴퓨터, 컴퓨터끼리만, 세 크기: 거절 0, 모두 끝까지, 빠른 판단', () => {
|
||||
for (const n of [2, 4]) {
|
||||
for (const humans of [1, 0]) {
|
||||
const players = Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i + 1}:n${n}${i}`));
|
||||
for (const size of [5, 10, 15] as const) {
|
||||
const r = liveBotPlayout(nonogram, nonogramBot, {
|
||||
players,
|
||||
options: nonogram.optionsSchema.parse({ size, timeLimitSec: humans ? 1200 : null }),
|
||||
seed: seedN(n * 10 + humans + size),
|
||||
isBot,
|
||||
levelOf: (p) => 1 + ((p.length * 7 + size) % 60),
|
||||
});
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.rejected).toEqual([]);
|
||||
expect(r.maxBotMs).toBeLessThan(50);
|
||||
const s = r.state as NonogramState;
|
||||
// Without a person and without a limit every computer solves it.
|
||||
if (!humans) for (const p of players) expect(s.status[p]).toBe('solved');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('강한 컴퓨터는 10×10을 기본 제한 시간 안에 풀고, 약한 컴퓨터보다 대체로 빨라요', () => {
|
||||
let strongFaster = 0;
|
||||
for (let k = 0; k < 8; k++) {
|
||||
const r = liveBotPlayout(nonogram, nonogramBot, {
|
||||
players: ['bot:1:easy', 'bot:2:hard'],
|
||||
options: nonogram.optionsSchema.parse({}),
|
||||
seed: seedN(700 + k),
|
||||
isBot,
|
||||
levelOf: (p) => (p.endsWith('easy') ? 3 : 58),
|
||||
});
|
||||
const s = r.state as NonogramState;
|
||||
expect(s.status['bot:2:hard']).toBe('solved');
|
||||
const hard = s.final!.ranking.find((x) => x.id === 'bot:2:hard')!;
|
||||
const easy = s.final!.ranking.find((x) => x.id === 'bot:1:easy')!;
|
||||
expect(hard.timeMs!).toBeLessThan(1_200_000);
|
||||
if (easy.status !== 'solved' || hard.timeMs! < easy.timeMs!) strongFaster++;
|
||||
}
|
||||
expect(strongFaster).toBeGreaterThanOrEqual(7);
|
||||
});
|
||||
});
|
||||
|
||||
describe('nonogram · 줄 논리로 찾는 칸', () => {
|
||||
test('겹치는 칸은 채우기, 다 채운 줄의 나머지는 X', () => {
|
||||
const p = makePicture(['#####', '#...#', '#...#', '#...#', '#####'], '테스트', '#000');
|
||||
const v: NonogramBoardView = { size: 5, rows: p.rows, cols: p.cols, marks: '0'.repeat(25), hints: 0, lastHint: null, answer: null };
|
||||
const d = deductions(v);
|
||||
expect(d).toContainEqual({ cells: [0, 1, 2, 3, 4], value: 1 });
|
||||
expect(d.every((x) => x.cells.every((i) => p.solution[i] === (x.value === 1 ? '#' : '.')))).toBe(true);
|
||||
v.marks = '11111' + '1000' + '1' + '0'.repeat(15);
|
||||
expect(deductions(v)).toContainEqual({ cells: [6, 7, 8], value: 2 });
|
||||
});
|
||||
});
|
||||
74
packages/games/src/nonogram/bot.ts
Normal file
74
packages/games/src/nonogram/bot.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* 네모네모 로직 computers (docs/games/nonogram.md §13). They only read their own screen (the clues and their marks).
|
||||
* - Line logic (./solver) on each row and column finds the cells it forces; one paint = one such run of cells in one
|
||||
* line (filled or X). A stronger computer takes the longest run of filled cells first, a weaker one any run.
|
||||
* - A weak computer now and then fills a cell it has not worked out (a slip) and clears it again a few moves later.
|
||||
* - Time per paint: about 6 s at level 1 … 1.2 s at level 60, a little longer on bigger pictures.
|
||||
*/
|
||||
import { raceBot } from '../race/bot';
|
||||
import type { MarkValue, NonogramBoardView, NonogramMove } from './index';
|
||||
import { lineCells, solveLine, type Known } from './solver';
|
||||
|
||||
type V = NonogramBoardView;
|
||||
|
||||
export interface Deduction {
|
||||
cells: number[];
|
||||
value: 1 | 2;
|
||||
}
|
||||
|
||||
/** Every run of not-yet-marked cells that one line forces. `ignore` is treated as not known (a cell I am unsure of). */
|
||||
export function deductions(v: V, ignore: number | null = null): Deduction[] {
|
||||
const n = v.size;
|
||||
const known: Known[] = Array.from(v.marks, (ch, i) => (i === ignore ? -1 : ch === '1' ? 1 : ch === '2' ? 0 : -1));
|
||||
const clues = [...v.rows, ...v.cols];
|
||||
const out: Deduction[] = [];
|
||||
for (let line = 0; line < 2 * n; line++) {
|
||||
const cells = lineCells(n, line);
|
||||
const solved = solveLine(clues[line]!, cells.map((i) => known[i]!));
|
||||
if (!solved) continue;
|
||||
let run: Deduction | null = null;
|
||||
for (let t = 0; t <= n; t++) {
|
||||
const i = cells[t];
|
||||
const value = t < n && known[i!] === -1 && solved[t] !== -1 ? (solved[t] === 1 ? 1 : 2) : null;
|
||||
if (run && value === run.value) run.cells.push(i!);
|
||||
else {
|
||||
if (run) out.push(run);
|
||||
run = value ? { cells: [i!], value } : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const nonogramBot = raceBot<V, NonogramMove>((v, skill, random, memory) => {
|
||||
const step = (6000 - 4800 * skill) * (0.6 + 0.04 * v.size) * (0.6 + 0.8 * random());
|
||||
const slip = typeof memory.slip === 'number' && v.marks[memory.slip] === '1' ? memory.slip : null;
|
||||
if (slip !== null && typeof memory.slipIn === 'number') {
|
||||
memory.slipIn -= 1;
|
||||
if (memory.slipIn <= 0) {
|
||||
memory.slip = null;
|
||||
return { move: { type: 'paint', cells: [slip], value: 0 }, ms: step * 0.6 };
|
||||
}
|
||||
}
|
||||
if (slip === null && random() < 0.15 * (1 - skill)) {
|
||||
const open: number[] = [];
|
||||
for (let i = 0; i < v.marks.length; i++) if (v.marks[i] === '0') open.push(i);
|
||||
if (open.length > 1) {
|
||||
memory.slip = open[Math.floor(random() * open.length)]!;
|
||||
memory.slipIn = 2 + Math.floor(random() * 3);
|
||||
return { move: { type: 'paint', cells: [memory.slip as number], value: 1 }, ms: step };
|
||||
}
|
||||
}
|
||||
const found = deductions(v, slip);
|
||||
if (!found.length) return { move: null, ms: 2000 };
|
||||
let pick = found[Math.floor(random() * found.length)]!;
|
||||
if (random() < 0.4 + 0.6 * skill) pick = found.reduce((a, b) => (b.value < a.value || (b.value === a.value && b.cells.length > a.cells.length) ? b : a));
|
||||
let cells = pick.cells;
|
||||
if (slip !== null && cells.includes(slip)) {
|
||||
// Line logic just settled the cell I slipped on: it was right after all (keep it) or gets its X now.
|
||||
memory.slip = null;
|
||||
if (pick.value === 1) cells = cells.filter((i) => i !== slip);
|
||||
if (!cells.length) return { move: null, ms: step * 0.3 };
|
||||
}
|
||||
return { move: { type: 'paint', cells, value: pick.value as MarkValue }, ms: step };
|
||||
});
|
||||
169
packages/games/src/nonogram/index.ts
Normal file
169
packages/games/src/nonogram/index.ts
Normal file
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* 네모네모 로직 (docs/games/nonogram.md). Everyone solves the same picture on their own copy (race frame, ../race).
|
||||
* Each row and column has number clues (the lengths of its filled runs, in order); fill the cells so every line
|
||||
* matches. Players only mark their own board (fill / X / clear); nothing tells them a cell is right or wrong.
|
||||
* Progress counts lines whose current filled cells match their clue, which anyone could check from the clues, so it
|
||||
* gives nothing of the answer away.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import type { GameEvent } from '@bg/engine';
|
||||
import { lit, makeRaceGame, timeLimitOption, type RaceState, type RaceView } from '../race';
|
||||
import { PICTURES } from './bank';
|
||||
import { clueOf, colCells, rowCells, sameClue } from './solver';
|
||||
|
||||
export { COUNTDOWN_MS, formatElapsed } from '../race';
|
||||
|
||||
export type NonogramSize = 5 | 10 | 15;
|
||||
export const SIZE_NAME: Record<NonogramSize, string> = { 5: '쉬움', 10: '보통', 15: '어려움' };
|
||||
|
||||
export const nonogramOptionsSchema = z.object({
|
||||
size: lit<NonogramSize>(5, 10, 15)
|
||||
.default(10)
|
||||
.meta({ title: '크기', labels: { 5: '5×5 쉬움', 10: '10×10 보통', 15: '15×15 어려움' } }),
|
||||
hints: z.boolean().default(true).meta({ title: '힌트 쓰기(틀렸거나 모르는 칸 하나를 알려 줌)' }),
|
||||
timeLimitSec: timeLimitOption([300, 600, 1200, 1800], 1200),
|
||||
});
|
||||
export type NonogramOptions = z.infer<typeof nonogramOptionsSchema>;
|
||||
|
||||
/** Mark values: 0 empty (not decided), 1 filled, 2 X (sure it is empty). */
|
||||
export type MarkValue = 0 | 1 | 2;
|
||||
|
||||
const cell = z.number().int().min(0).max(224);
|
||||
const moveSchemas = [
|
||||
z.object({ type: z.literal('paint'), cells: z.array(cell).min(1).max(15), value: lit<MarkValue>(0, 1, 2) }),
|
||||
z.object({ type: z.literal('hint') }),
|
||||
] as const;
|
||||
export type NonogramMove = { type: 'paint'; cells: number[]; value: MarkValue } | { type: 'hint' };
|
||||
|
||||
export interface NonogramPuzzle {
|
||||
size: NonogramSize;
|
||||
name: string;
|
||||
color: string;
|
||||
/** Per cell '#' filled or '.' empty, row-major. */
|
||||
solution: string;
|
||||
rows: number[][];
|
||||
cols: number[][];
|
||||
}
|
||||
|
||||
export interface NonogramBoard {
|
||||
/** Per cell '0' empty, '1' filled, '2' X. */
|
||||
marks: string;
|
||||
hints: number;
|
||||
/** The cell the last hint set, or null. */
|
||||
lastHint: number | null;
|
||||
}
|
||||
|
||||
export interface NonogramBoardView {
|
||||
size: NonogramSize;
|
||||
rows: number[][];
|
||||
cols: number[][];
|
||||
marks: string;
|
||||
hints: number;
|
||||
lastHint: number | null;
|
||||
/** Only once I am finished (or the game is over): the picture. */
|
||||
answer: { solution: string; name: string; color: string } | null;
|
||||
}
|
||||
|
||||
export type NonogramState = RaceState<NonogramPuzzle, NonogramBoard, NonogramOptions>;
|
||||
export type NonogramView = RaceView<NonogramBoardView, NonogramOptions>;
|
||||
|
||||
export function makePicture(rows: readonly string[], name: string, color: string): NonogramPuzzle {
|
||||
const size = rows.length as NonogramSize;
|
||||
const solution = rows.join('');
|
||||
return {
|
||||
size,
|
||||
name,
|
||||
color,
|
||||
solution,
|
||||
rows: rows.map((r) => clueOf(r)),
|
||||
cols: Array.from({ length: size }, (_, c) => clueOf(colCells(size, c).map((i) => solution[i]!))),
|
||||
};
|
||||
}
|
||||
|
||||
/** Lines (rows, then columns) whose filled cells right now match their clue. */
|
||||
export function matchedLines(size: number, rows: readonly number[][], cols: readonly number[][], marks: string): boolean[] {
|
||||
const filled = (cells: number[]) => cells.map((i) => marks[i]!);
|
||||
return [...rows.map((clue, r) => sameClue(clueOf(filled(rowCells(size, r))), clue)), ...cols.map((clue, c) => sameClue(clueOf(filled(colCells(size, c))), clue))];
|
||||
}
|
||||
|
||||
const isSolved = (p: NonogramPuzzle, marks: string) => [...p.solution].every((ch, i) => (ch === '#') === (marks[i] === '1'));
|
||||
const setCells = (marks: string, cells: readonly number[], ch: string) => {
|
||||
const m = marks.split('');
|
||||
for (const i of cells) m[i] = ch;
|
||||
return m.join('');
|
||||
};
|
||||
/** What a hint would set the cell to: filled, or X for an empty one. */
|
||||
const rightMark = (p: NonogramPuzzle, i: number) => (p.solution[i] === '#' ? '1' : '2');
|
||||
|
||||
export const nonogram = makeRaceGame<NonogramPuzzle, NonogramBoard, NonogramMove, NonogramBoardView, NonogramOptions>({
|
||||
id: 'nonogram',
|
||||
nameKo: '네모네모 로직',
|
||||
optionsSchema: nonogramOptionsSchema,
|
||||
moveSchemas: moveSchemas as never,
|
||||
|
||||
makePuzzle(rng, o) {
|
||||
const list = PICTURES[o.size];
|
||||
const pic = list[rng.int(list.length)]!;
|
||||
return makePicture(pic.rows, pic.name, pic.color);
|
||||
},
|
||||
|
||||
startBoard: (p) => ({ marks: '0'.repeat(p.size * p.size), hints: 0, lastHint: null }),
|
||||
|
||||
checkMove(p, b, m, o) {
|
||||
if (m.type === 'hint') return o.hints ? null : '이 방은 힌트를 쓰지 않아요.';
|
||||
const n = p.size;
|
||||
if (m.cells.some((i) => i >= n * n)) return '판 밖의 칸이에요.';
|
||||
if (new Set(m.cells).size !== m.cells.length) return '같은 칸이 두 번 들어 있어요.';
|
||||
const r0 = Math.floor(m.cells[0]! / n);
|
||||
const c0 = m.cells[0]! % n;
|
||||
if (!m.cells.every((i) => Math.floor(i / n) === r0) && !m.cells.every((i) => i % n === c0)) return '한 줄(가로 또는 세로)에 있는 칸만 한 번에 칠할 수 있어요.';
|
||||
if (m.cells.every((i) => b.marks[i] === String(m.value))) return '바뀌는 칸이 없어요.';
|
||||
return null;
|
||||
},
|
||||
|
||||
applyMove(p, b, m, { rng }) {
|
||||
let next: NonogramBoard;
|
||||
const events: GameEvent[] = [];
|
||||
if (m.type === 'hint') {
|
||||
const wrong: number[] = [];
|
||||
for (let i = 0; i < p.solution.length; i++) if (b.marks[i] !== rightMark(p, i)) wrong.push(i);
|
||||
if (!wrong.length) return { board: b };
|
||||
const i = wrong[rng.int(wrong.length)]!;
|
||||
next = { marks: setCells(b.marks, [i], rightMark(p, i)), hints: b.hints + 1, lastHint: i };
|
||||
events.push({ type: 'hint', i });
|
||||
} else next = { ...b, marks: setCells(b.marks, m.cells, String(m.value)) };
|
||||
return { board: next, outcome: isSolved(p, next.marks) ? 'solved' : undefined, events };
|
||||
},
|
||||
|
||||
boardView: (p, b, reveal) => ({
|
||||
size: p.size,
|
||||
rows: p.rows,
|
||||
cols: p.cols,
|
||||
marks: b.marks,
|
||||
hints: b.hints,
|
||||
lastHint: b.lastHint,
|
||||
answer: reveal ? { solution: p.solution, name: p.name, color: p.color } : null,
|
||||
}),
|
||||
|
||||
progress: (p, b) => matchedLines(p.size, p.rows, p.cols, b.marks).filter(Boolean).length,
|
||||
progressText: (p, b) => `맞는 줄 ${matchedLines(p.size, p.rows, p.cols, b.marks).filter(Boolean).length}/${p.size * 2}`,
|
||||
extraText: (b) => (b.hints ? ` · 힌트 ${b.hints}번` : ''),
|
||||
|
||||
/** Test helper: a few right cells, one wrong fill, one X, an X over a whole row, and a hint. */
|
||||
legalMoves(p, b, o) {
|
||||
const out: NonogramMove[] = [];
|
||||
for (let i = 0; i < p.solution.length && out.length < 3; i++) {
|
||||
const want = p.solution[i] === '#';
|
||||
if (want && b.marks[i] !== '1') out.push({ type: 'paint', cells: [i], value: 1 });
|
||||
else if (!want && b.marks[i] === '1') out.push({ type: 'paint', cells: [i], value: 0 });
|
||||
}
|
||||
const wrong = [...p.solution].findIndex((ch, i) => ch === '.' && b.marks[i] === '0');
|
||||
if (wrong >= 0) out.push({ type: 'paint', cells: [wrong], value: 1 }, { type: 'paint', cells: [wrong], value: 2 });
|
||||
const row = rowCells(p.size, Math.floor((b.hints * 7 + out.length) % p.size)).filter((i) => b.marks[i] !== '2');
|
||||
if (row.length) out.push({ type: 'paint', cells: row, value: 2 });
|
||||
if (o.hints) out.push({ type: 'hint' });
|
||||
return out;
|
||||
},
|
||||
|
||||
secrets: (p) => [p.solution, p.name],
|
||||
});
|
||||
317
packages/games/src/nonogram/nonogram.test.ts
Normal file
317
packages/games/src/nonogram/nonogram.test.ts
Normal file
@@ -0,0 +1,317 @@
|
||||
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);
|
||||
expect(JSON.stringify(nonogram.view(s, 'B'))).toContain(s.puzzle.name);
|
||||
hidden('A');
|
||||
hidden(null);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
121
packages/games/src/nonogram/solver.ts
Normal file
121
packages/games/src/nonogram/solver.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* 네모네모 로직 line logic (docs/games/nonogram.md §8, §13). A cell is 1 (filled), 0 (empty) or -1 (not known yet).
|
||||
* `solveLine` finds every cell one row/column forces from its clue and what is already known; `solveGrid` repeats
|
||||
* that over all rows and columns until nothing changes. Every bank picture must come out complete this way (so it has
|
||||
* exactly one answer and needs no guessing), and the computer players think with the same line logic.
|
||||
*/
|
||||
|
||||
export type Known = 1 | 0 | -1;
|
||||
|
||||
/** Run lengths of filled cells ('#' or 1); an empty line is []. */
|
||||
export function clueOf(line: ArrayLike<string | number>): number[] {
|
||||
const out: number[] = [];
|
||||
let run = 0;
|
||||
for (let i = 0; i < line.length; i++) {
|
||||
const on = line[i] === '#' || line[i] === 1 || line[i] === '1';
|
||||
if (on) run++;
|
||||
else if (run) {
|
||||
out.push(run);
|
||||
run = 0;
|
||||
}
|
||||
}
|
||||
if (run) out.push(run);
|
||||
return out;
|
||||
}
|
||||
|
||||
export const sameClue = (a: readonly number[], b: readonly number[]) => a.length === b.length && a.every((x, i) => x === b[i]);
|
||||
|
||||
/**
|
||||
* Every cell the clue forces, given what is known: the new line (known cells kept), or null when no arrangement fits.
|
||||
* Prefix / suffix DP over "cells so far, runs placed so far", split by whether the last cell is filled.
|
||||
*/
|
||||
export function solveLine(clue: readonly number[], line: readonly Known[]): Known[] | null {
|
||||
const n = line.length;
|
||||
const k = clue.length;
|
||||
const notOn = (i: number) => line[i] !== 1;
|
||||
// runFits[j][s]: run j can sit on cells s … s+len-1 (none known empty).
|
||||
const runFits = clue.map((len) => {
|
||||
const out: boolean[] = [];
|
||||
for (let s = 0; s + len <= n; s++) {
|
||||
let okRun = true;
|
||||
for (let t = s; t < s + len && okRun; t++) if (line[t] === 0) okRun = false;
|
||||
out[s] = okRun;
|
||||
}
|
||||
return out;
|
||||
});
|
||||
// Forward: E[i][j] = cells [0,i) hold runs 0..j-1 exactly and cell i-1 is empty (or i = 0); F[i][j] = … ends a run at i-1.
|
||||
const grid = () => Array.from({ length: n + 1 }, () => new Array<boolean>(k + 1).fill(false));
|
||||
const E = grid();
|
||||
const F = grid();
|
||||
E[0]![0] = true;
|
||||
for (let i = 0; i <= n; i++)
|
||||
for (let j = 0; j <= k; j++) {
|
||||
const e = E[i]![j]!;
|
||||
const f = F[i]![j]!;
|
||||
if (!e && !f) continue;
|
||||
if (i < n && notOn(i)) E[i + 1]![j] = true;
|
||||
if (e && j < k && runFits[j]![i]) F[i + clue[j]!]![j + 1] = true;
|
||||
}
|
||||
if (!E[n]![k] && !F[n]![k]) return null;
|
||||
// Backward: E2[i][j] = cells [i,n) hold runs j..k-1 exactly and cell i is empty (or i = n); F2[i][j] = run j starts at i.
|
||||
const E2 = grid();
|
||||
const F2 = grid();
|
||||
E2[n]![k] = true;
|
||||
for (let i = n; i >= 0; i--)
|
||||
for (let j = k; j >= 0; j--) {
|
||||
if (i < n && notOn(i) && (E2[i + 1]![j] || F2[i + 1]![j])) E2[i]![j] = true;
|
||||
if (j < k && runFits[j]![i]) {
|
||||
const end = i + clue[j]!;
|
||||
if (end === n ? j + 1 === k : E2[end]![j + 1]) F2[i]![j] = true;
|
||||
}
|
||||
}
|
||||
const canEmpty = new Array<boolean>(n).fill(false);
|
||||
const canFill = new Array<boolean>(n).fill(false);
|
||||
for (let x = 0; x < n; x++) {
|
||||
if (!notOn(x)) continue;
|
||||
for (let j = 0; j <= k && !canEmpty[x]; j++) if ((E[x]![j] || F[x]![j]) && (E2[x + 1]![j] || F2[x + 1]![j])) canEmpty[x] = true;
|
||||
}
|
||||
for (let j = 0; j < k; j++) {
|
||||
const len = clue[j]!;
|
||||
for (let s = 0; s + len <= n; s++) {
|
||||
if (!E[s]![j] || !F2[s]![j]) continue;
|
||||
for (let t = s; t < s + len; t++) canFill[t] = true;
|
||||
}
|
||||
}
|
||||
const out: Known[] = [];
|
||||
for (let x = 0; x < n; x++) {
|
||||
if (!canFill[x] && !canEmpty[x]) return null;
|
||||
out.push(line[x] !== -1 ? line[x]! : canFill[x] && !canEmpty[x] ? 1 : canEmpty[x] && !canFill[x] ? 0 : -1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const rowCells = (size: number, r: number) => Array.from({ length: size }, (_, c) => r * size + c);
|
||||
export const colCells = (size: number, c: number) => Array.from({ length: size }, (_, r) => r * size + c);
|
||||
/** Lines 0..size-1 are the rows, size..2·size-1 the columns. */
|
||||
export const lineCells = (size: number, line: number) => (line < size ? rowCells(size, line) : colCells(size, line - size));
|
||||
|
||||
/** Line logic to a fixed point. Returns the grid (row-major, -1 where unknown) or null on a contradiction. */
|
||||
export function solveGrid(size: number, rows: readonly number[][], cols: readonly number[][], start?: readonly Known[]): Known[] | null {
|
||||
const g: Known[] = start ? [...start] : new Array<Known>(size * size).fill(-1);
|
||||
const clues = [...rows, ...cols];
|
||||
let dirty = new Set(clues.map((_, i) => i));
|
||||
while (dirty.size) {
|
||||
const next = new Set<number>();
|
||||
for (const line of dirty) {
|
||||
const cells = lineCells(size, line);
|
||||
const solved = solveLine(clues[line]!, cells.map((i) => g[i]!));
|
||||
if (!solved) return null;
|
||||
cells.forEach((i, t) => {
|
||||
if (g[i] === -1 && solved[t] !== -1) {
|
||||
g[i] = solved[t]!;
|
||||
const r = Math.floor(i / size);
|
||||
const c = i % size;
|
||||
next.add(line < size ? size + c : r);
|
||||
}
|
||||
});
|
||||
}
|
||||
dirty = next;
|
||||
}
|
||||
return g;
|
||||
}
|
||||
Reference in New Issue
Block a user