새 게임 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:
EJClaw
2026-11-24 14:29:01 +09:00
parent 35f2310f8d
commit 1b9acb9fc1
66 changed files with 8958 additions and 3 deletions

View File

@@ -44,6 +44,11 @@ import { hotStreakBot } from '../hot-streak/bot';
import { tichuBot } from '../tichu/bot';
import { cobBot } from '../castles-of-burgundy/bot';
import { typingBot } from '../typing/bot';
import { minesweeperBot } from '../minesweeper/bot';
import { shisenBot } from '../shisen/bot';
import { solitaireBot } from '../solitaire/bot';
import { sudokuBot } from '../sudoku/bot';
import { nonogramBot } from '../nonogram/bot';
export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
@@ -144,4 +149,9 @@ export const LIVE_BOT_STRATEGIES: Record<string, LiveBotStrategy> = {
apple: appleBot,
liar: liarBot,
typing: typingBot,
minesweeper: minesweeperBot,
shisen: shisenBot,
solitaire: solitaireBot,
sudoku: sudokuBot,
nonogram: nonogramBot,
};

View File

@@ -40,6 +40,11 @@ import { tichu } from './tichu';
import { caseFile } from './case-file';
import { castlesOfBurgundy } from './castles-of-burgundy';
import { typing } from './typing';
import { minesweeper } from './minesweeper';
import { shisen } from './shisen';
import { solitaire } from './solitaire';
import { sudoku } from './sudoku';
import { nonogram } from './nonogram';
export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -83,4 +88,9 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[caseFile.id]: caseFile,
[castlesOfBurgundy.id]: castlesOfBurgundy,
[typing.id]: typing,
[minesweeper.id]: minesweeper,
[shisen.id]: shisen,
[solitaire.id]: solitaire,
[sudoku.id]: sudoku,
[nonogram.id]: nonogram,
};

View File

@@ -0,0 +1,59 @@
/** 지뢰찾기 computers (docs/games/minesweeper.md §13): never refused, finish the race, stronger levels do better. */
import { describe, expect, test } from 'bun:test';
import { seedN } from '@bg/engine';
import { liveBotPlayout } from '../bots/live-playout';
import { minesweeperBot, sureMove } from './bot';
import { minesweeper, type MinesweeperState } from './index';
const isBot = (p: string) => p.startsWith('bot:');
describe('한 판 전체', () => {
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}:m${n}${i}`));
for (const level of ['beginner', 'intermediate'] as const) {
const r = liveBotPlayout(minesweeper, minesweeperBot, {
players,
options: minesweeper.optionsSchema.parse({ level, timeLimitSec: humans ? 600 : null }),
seed: seedN(n * 10 + humans),
isBot,
levelOf: (p) => 1 + ((p.length * 7) % 60),
});
expect(r.finished).toBe(true);
expect(r.rejected).toEqual([]);
expect(r.maxBotMs).toBeLessThan(50);
const s = r.state as MinesweeperState;
for (const p of players) if (isBot(p)) expect(['solved', 'failed']).toContain(s.status[p]!);
}
}
}
});
test('확실한 수만 있으면 틀리지 않아요: 어려움 컴퓨터는 초급을 대부분 풀고, 쉬움보다 자주 풀어요', () => {
const wins = { easy: 0, hard: 0 };
for (let k = 0; k < 20; k++) {
const r = liveBotPlayout(minesweeper, minesweeperBot, {
players: ['bot:1:easy', 'bot:2:hard'],
options: minesweeper.optionsSchema.parse({ level: 'beginner' }),
seed: seedN(500 + k),
isBot,
levelOf: (p) => (p.endsWith('easy') ? 3 : 58),
});
const s = r.state as MinesweeperState;
if (s.status['bot:1:easy'] === 'solved') wins.easy++;
if (s.status['bot:2:hard'] === 'solved') wins.hard++;
}
expect(wins.hard).toBeGreaterThanOrEqual(12);
expect(wins.hard).toBeGreaterThan(wins.easy);
});
test('확실한 수: 깃발 다 꽂힌 숫자는 주변 열기, 남은 칸 = 지뢰 수면 깃발', () => {
// 3×3: the centre shows 1 and only the corner is closed → flag it.
const v = { rows: 3, cols: 3, mines: 1, cells: '#000100000'.slice(1), flags: 0 };
v.cells = '#11' + '111' + '000';
expect(sureMove(v, false)).toEqual({ type: 'flag', i: 0 });
v.cells = 'F11' + '11#' + '000';
expect(sureMove(v, false)).toEqual({ type: 'chord', i: 1 });
});
});

View File

@@ -0,0 +1,79 @@
/**
* 지뢰찾기 computers (docs/games/minesweeper.md §13). They only read their own screen (opened numbers and their flags).
* - Sure moves first: a number with all its mines flagged opens the rest (chord), a number with exactly as many closed
* cells as mines left flags them. A stronger computer also compares two neighbouring numbers (subset rule).
* - With no sure move it guesses: a strong computer picks the cell least likely to be a mine, a weak one often any cell.
* - Time per move: about 3 s at level 1 … 0.8 s at level 60 (guesses take longer).
*/
import { raceBot } from '../race/bot';
import { around, type MinesweeperBoardView, type MinesweeperMove } from './index';
type V = MinesweeperBoardView;
const isNum = (ch: string) => ch >= '1' && ch <= '8';
const isClosed = (ch: string) => ch === '#';
interface Clue {
at: number;
/** Closed, unflagged neighbours. */
unknown: number[];
/** Mines still to find around it. */
left: number;
}
function clues(v: V): Clue[] {
const out: Clue[] = [];
for (let i = 0; i < v.cells.length; i++) {
if (!isNum(v.cells[i]!)) continue;
const nb = around(v.rows, v.cols, i);
const unknown = nb.filter((j) => isClosed(v.cells[j]!));
if (!unknown.length) continue;
const flags = nb.filter((j) => v.cells[j] === 'F').length;
out.push({ at: i, unknown, left: Number(v.cells[i]) - flags });
}
return out;
}
/** A sure move, or null. `deep` adds the subset rule between two numbers. */
export function sureMove(v: V, deep: boolean): MinesweeperMove | null {
const cs = clues(v);
for (const c of cs) if (c.left === 0) return { type: 'chord', i: c.at };
for (const c of cs) if (c.left === c.unknown.length && c.left > 0) return { type: 'flag', i: c.unknown[0]! };
if (!deep) return null;
for (const a of cs)
for (const b of cs) {
if (a === b || a.unknown.length >= b.unknown.length) continue;
if (!a.unknown.every((j) => b.unknown.includes(j))) continue;
const rest = b.unknown.filter((j) => !a.unknown.includes(j));
const mines = b.left - a.left;
if (mines === 0) return { type: 'open', i: rest[0]! };
if (mines === rest.length) return { type: 'flag', i: rest[0]! };
}
return null;
}
/** The closed cell least likely to hold a mine (a rough local estimate). */
export function bestGuess(v: V, random: () => number, careful: boolean): MinesweeperMove | null {
const closed: number[] = [];
for (let i = 0; i < v.cells.length; i++) if (isClosed(v.cells[i]!)) closed.push(i);
if (!closed.length) return null;
if (!careful) return { type: 'open', i: closed[Math.floor(random() * closed.length)]! };
const risk = new Map<number, number>();
for (const c of clues(v)) for (const j of c.unknown) risk.set(j, Math.max(risk.get(j) ?? 0, c.left / c.unknown.length));
const flags = [...v.cells].filter((ch) => ch === 'F').length;
const elsewhere = (v.mines - flags) / Math.max(1, closed.length);
let best = closed[0]!;
let low = Infinity;
for (const i of closed) {
const r = (risk.get(i) ?? elsewhere) + random() * 0.01;
if (r < low) [best, low] = [i, r];
}
return { type: 'open', i: best };
}
export const minesweeperBot = raceBot<V, MinesweeperMove>((v, skill, random) => {
const step = 3000 - 2200 * skill;
const sure = sureMove(v, random() < 0.3 + 0.7 * skill);
if (sure) return { move: sure, ms: step * (0.6 + 0.8 * random()) };
return { move: bestGuess(v, random, random() < 0.3 + 0.7 * skill), ms: step * (1.5 + random()) };
});

View File

@@ -0,0 +1,188 @@
/**
* 지뢰찾기 (docs/games/minesweeper.md). Everyone clears the same minefield on their own copy (race frame, ../race).
* The field is laid out around one starting cell with no mine next to it, and that cell is opened for everybody at
* the start, so nobody's first click decides the game and everyone starts from the same opening.
*/
import { z } from 'zod';
import type { Rng } from '@bg/engine';
import { lit, makeRaceGame, timeLimitOption, type RaceState, type RaceView } from '../race';
export { COUNTDOWN_MS, formatElapsed } from '../race';
export const LEVELS = {
beginner: { rows: 9, cols: 9, mines: 10, name: '초급' },
intermediate: { rows: 16, cols: 16, mines: 40, name: '중급' },
expert: { rows: 16, cols: 30, mines: 99, name: '고급' },
} as const;
export type Level = keyof typeof LEVELS;
export const minesweeperOptionsSchema = z.object({
level: lit<Level>('beginner', 'intermediate', 'expert')
.default('beginner')
.meta({ title: '난이도', labels: { beginner: '초급 9×9 · 지뢰 10', intermediate: '중급 16×16 · 지뢰 40', expert: '고급 16×30 · 지뢰 99' } }),
timeLimitSec: timeLimitOption([180, 300, 600, 1200], 600),
});
export type MinesweeperOptions = z.infer<typeof minesweeperOptionsSchema>;
const cell = z.number().int().min(0).max(479);
const moveSchemas = [
z.object({ type: z.literal('open'), i: cell }),
z.object({ type: z.literal('flag'), i: cell }),
z.object({ type: z.literal('chord'), i: cell }),
] as const;
export type MinesweeperMove = { type: 'open' | 'flag' | 'chord'; i: number };
export interface MinesweeperPuzzle {
rows: number;
cols: number;
mines: number;
/** Per cell: '*' mine, else '0'..'8' mines around it. Row-major. */
field: string;
/** The cell opened for everybody at the start. */
start: number;
}
export interface MinesweeperBoard {
/** Per cell '1' = opened. */
open: string;
/** Per cell '1' = flagged. */
flags: string;
/** Opened safe cells. */
opened: number;
/** The mine that went off, or null. */
boom: number | null;
}
/**
* What I see: per cell '#' closed, 'F' flag, '0'..'8' opened. Once I am finished (or the game is over): '*' mine,
* '!' the mine that went off, 'x' a flag on a safe cell.
*/
export interface MinesweeperBoardView {
rows: number;
cols: number;
mines: number;
cells: string;
flags: number;
}
export type MinesweeperState = RaceState<MinesweeperPuzzle, MinesweeperBoard, MinesweeperOptions>;
export type MinesweeperView = RaceView<MinesweeperBoardView, MinesweeperOptions>;
/** Cells around `i` (up to 8). */
export function around(rows: number, cols: number, i: number): number[] {
const r = Math.floor(i / cols);
const c = i % cols;
const out: number[] = [];
for (let dr = -1; dr <= 1; dr++)
for (let dc = -1; dc <= 1; dc++) {
if (!dr && !dc) continue;
const rr = r + dr;
const cc = c + dc;
if (rr >= 0 && rr < rows && cc >= 0 && cc < cols) out.push(rr * cols + cc);
}
return out;
}
/** Mines anywhere except in the 3×3 around the start cell (so it opens a patch). */
export function makeField(rng: Rng, level: Level): MinesweeperPuzzle {
const { rows, cols, mines } = LEVELS[level];
const n = rows * cols;
const start = rng.int(n);
const keep = new Set([start, ...around(rows, cols, start)]);
const free = rng.shuffle(Array.from({ length: n }, (_, i) => i).filter((i) => !keep.has(i)));
const mine = new Set(free.slice(0, mines));
let field = '';
for (let i = 0; i < n; i++) field += mine.has(i) ? '*' : String(around(rows, cols, i).filter((j) => mine.has(j)).length);
return { rows, cols, mines, field, start };
}
const setAt = (s: string, i: number, ch: string) => s.slice(0, i) + ch + s.slice(i + 1);
/** Opens `from` (a safe cell) and the zero area around it. */
function flood(p: MinesweeperPuzzle, b: MinesweeperBoard, from: number[]): MinesweeperBoard {
const open = b.open.split('');
const flags = b.flags;
let opened = b.opened;
const stack = [...from];
while (stack.length) {
const i = stack.pop()!;
if (open[i] === '1' || flags[i] === '1' || p.field[i] === '*') continue;
open[i] = '1';
opened++;
if (p.field[i] === '0') for (const j of around(p.rows, p.cols, i)) if (open[j] !== '1') stack.push(j);
}
return { ...b, open: open.join(''), opened };
}
const safeCells = (p: MinesweeperPuzzle) => p.rows * p.cols - p.mines;
const flagsAround = (p: MinesweeperPuzzle, b: MinesweeperBoard, i: number) => around(p.rows, p.cols, i).filter((j) => b.flags[j] === '1').length;
const closedAround = (p: MinesweeperPuzzle, b: MinesweeperBoard, i: number) => around(p.rows, p.cols, i).filter((j) => b.open[j] !== '1' && b.flags[j] !== '1');
export const minesweeper = makeRaceGame<MinesweeperPuzzle, MinesweeperBoard, MinesweeperMove, MinesweeperBoardView, MinesweeperOptions>({
id: 'minesweeper',
nameKo: '지뢰찾기',
optionsSchema: minesweeperOptionsSchema,
moveSchemas: moveSchemas as never,
movesPerSec: 15,
failText: '지뢰를 밟았어요',
makePuzzle: (rng, o) => makeField(rng, o.level),
startBoard(p) {
const n = p.rows * p.cols;
return flood(p, { open: '0'.repeat(n), flags: '0'.repeat(n), opened: 0, boom: null }, [p.start]);
},
checkMove(p, b, m) {
if (m.i >= p.rows * p.cols) return '판 밖의 칸이에요.';
const opened = b.open[m.i] === '1';
if (m.type === 'open') {
if (opened) return '이미 연 칸이에요.';
if (b.flags[m.i] === '1') return '깃발을 꽂은 칸이에요. 깃발을 먼저 치워 주세요.';
return null;
}
if (m.type === 'flag') return opened ? '이미 연 칸에는 깃발을 꽂을 수 없어요.' : null;
if (!opened || p.field[m.i] === '0') return '숫자가 있는 연 칸에서만 주변을 한꺼번에 열 수 있어요.';
if (flagsAround(p, b, m.i) !== Number(p.field[m.i])) return `주변 깃발이 숫자(${p.field[m.i]})와 같아야 한꺼번에 열 수 있어요.`;
if (!closedAround(p, b, m.i).length) return '주변에 더 열 칸이 없어요.';
return null;
},
applyMove(p, b, m) {
if (m.type === 'flag') return { board: { ...b, flags: setAt(b.flags, m.i, b.flags[m.i] === '1' ? '0' : '1') } };
const targets = m.type === 'open' ? [m.i] : closedAround(p, b, m.i);
const mine = targets.find((j) => p.field[j] === '*');
if (mine !== undefined) return { board: { ...b, boom: mine }, outcome: 'failed', events: [{ type: 'boom', i: mine }] };
const next = flood(p, b, targets);
return { board: next, outcome: next.opened === safeCells(p) ? 'solved' : undefined, events: [{ type: 'opened', n: next.opened - b.opened }] };
},
boardView(p, b, reveal) {
let cells = '';
let flags = 0;
for (let i = 0; i < p.rows * p.cols; i++) {
const f = b.flags[i] === '1';
if (f) flags++;
if (b.open[i] === '1') cells += p.field[i];
else if (reveal && b.boom === i) cells += '!';
else if (reveal && f) cells += p.field[i] === '*' ? 'F' : 'x';
else if (reveal && p.field[i] === '*') cells += '*';
else cells += f ? 'F' : '#';
}
return { rows: p.rows, cols: p.cols, mines: p.mines, cells, flags };
},
progress: (_p, b) => b.opened,
progressText: (p, b) => `연 칸 ${b.opened}/${safeCells(p)}`,
legalMoves(p, b) {
const out: MinesweeperMove[] = [];
for (let i = 0; i < p.rows * p.cols && out.length < 6; i++) {
if (b.open[i] === '1') continue;
out.push(b.flags[i] === '1' ? { type: 'flag', i } : { type: 'open', i });
}
return out;
},
secrets: (p) => [p.field],
});

View File

@@ -0,0 +1,210 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import { COUNTDOWN_MS, LEVELS, around, makeField, minesweeper, type MinesweeperOptions, type MinesweeperState } from './index';
const T0 = 1_000_000;
const START = T0 + COUNTDOWN_MS;
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
type A = Parameters<typeof minesweeper.apply>[2];
function make(players = ['A', 'B'], opts: Partial<MinesweeperOptions> = {}, seed = 1): MinesweeperState {
return minesweeper.setup({ players, options: minesweeper.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 });
}
function act(s: MinesweeperState, p: string, a: A, now = START + 1000): MinesweeperState {
const v = minesweeper.validate(s, p, a, { now });
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
return minesweeper.apply(s, p, a, { rng: rng(), now }).state;
}
const reason = (s: MinesweeperState, p: string, a: A, now = START + 1000) => {
const v = minesweeper.validate(s, p, a, { now });
return v.ok ? 'ok' : v.reason;
};
const started = (players?: string[], opts?: Partial<MinesweeperOptions>, seed?: number) => minesweeper.apply(make(players, opts, seed), 'A', { type: 'tick' }, { rng: rng(), now: START }).state;
const safe = (s: MinesweeperState) => [...s.puzzle.field].flatMap((ch, i) => (ch !== '*' && s.boards.A!.open[i] !== '1' ? [i] : []));
const mines = (s: MinesweeperState) => [...s.puzzle.field].flatMap((ch, i) => (ch === '*' ? [i] : []));
describe('판 만들기', () => {
test('난이도별 크기·지뢰 수, 시작 칸 주변 3×3에는 지뢰 없음, 숫자 = 주변 지뢰 수, 같은 시드 = 같은 판', () => {
for (const level of ['beginner', 'intermediate', 'expert'] as const) {
for (let k = 1; k <= 20; k++) {
const p = makeField(SeededRng.fromSeed(seedN(k)), level);
const L = LEVELS[level];
expect(p.field).toHaveLength(L.rows * L.cols);
expect([...p.field].filter((c) => c === '*')).toHaveLength(L.mines);
expect(p.field[p.start]).toBe('0');
for (const j of around(p.rows, p.cols, p.start)) expect(p.field[j]).not.toBe('*');
for (let i = 0; i < p.field.length; i++) {
if (p.field[i] === '*') continue;
expect(Number(p.field[i])).toBe(around(p.rows, p.cols, i).filter((j) => p.field[j] === '*').length);
}
expect(makeField(SeededRng.fromSeed(seedN(k)), level)).toEqual(p);
}
}
});
test('모두 같은 판, 시작 칸과 그 주변이 열린 채로 시작, 카운트다운에는 판을 안 보여 줌', () => {
const s = make(['A', 'B', 'C']);
expect(new Set(Object.values(s.boards).map((b) => b.open)).size).toBe(1);
expect(s.boards.A!.open[s.puzzle.start]).toBe('1');
expect(s.boards.A!.opened).toBeGreaterThan(1);
expect(minesweeper.view(s, 'A').board).toBeNull();
expect(reason(s, 'A', { type: 'open', i: 0 }, T0 + 100)).toContain('곧 시작');
checkNoLeak(minesweeper, s, 'A', s.order);
});
});
describe('열기·깃발·한꺼번에 열기', () => {
test('안전한 칸을 열면 열리고(0이면 이어서), 내 판만 바뀜', () => {
let s = started();
const i = safe(s)[0]!;
s = act(s, 'A', { type: 'open', i });
expect(s.boards.A!.open[i]).toBe('1');
expect(s.boards.B!.open[i]).toBe('0');
expect(reason(s, 'A', { type: 'open', i })).toBe('이미 연 칸이에요.');
});
test('깃발: 꽂고 치우기, 깃발 칸은 열 수 없음, 연 칸에는 못 꽂음', () => {
let s = started();
const m = mines(s)[0]!;
s = act(s, 'A', { type: 'flag', i: m });
expect(minesweeper.view(s, 'A').board!.cells[m]).toBe('F');
expect(minesweeper.view(s, 'A').board!.flags).toBe(1);
expect(reason(s, 'A', { type: 'open', i: m })).toContain('깃발');
s = act(s, 'A', { type: 'flag', i: m });
expect(minesweeper.view(s, 'A').board!.cells[m]).toBe('#');
expect(reason(s, 'A', { type: 'flag', i: s.puzzle.start })).toContain('이미 연 칸');
});
test('지뢰를 밟으면 실패(시간 멈춤), 내 화면에 지뢰가 모두 보이고 다른 사람은 계속', () => {
let s = started();
const m = mines(s)[0]!;
s = act(s, 'A', { type: 'open', i: m }, START + 5000);
expect(s.status.A).toBe('failed');
expect(s.status.B).toBe('playing');
const v = minesweeper.view(s, 'A');
expect(v.board!.cells[m]).toBe('!');
expect([...v.board!.cells].filter((c) => c === '*' || c === '!')).toHaveLength(s.puzzle.mines);
expect(v.seats.find((x) => x.id === 'A')!.timeMs).toBe(5000);
// B's screen still shows nothing of the mines.
expect(minesweeper.view(s, 'B').board!.cells).not.toContain('*');
expect(reason(s, 'A', { type: 'open', i: safe(s)[0]! })).toBe('이미 끝냈어요.');
});
test('한꺼번에 열기: 깃발 수가 숫자와 같을 때만, 틀린 깃발이면 지뢰가 터짐', () => {
let s = started();
const p = s.puzzle;
const num = [...p.field].findIndex((ch, i) => ch >= '1' && s.boards.A!.open[i] === '1');
expect(num).toBeGreaterThanOrEqual(0);
expect(reason(s, 'A', { type: 'chord', i: num })).toContain('깃발이 숫자');
const nb = around(p.rows, p.cols, num);
let t = s;
for (const j of nb) if (p.field[j] === '*') t = act(t, 'A', { type: 'flag', i: j });
const before = t.boards.A!.opened;
const closedSafe = nb.filter((j) => p.field[j] !== '*' && t.boards.A!.open[j] !== '1');
if (closedSafe.length) {
t = act(t, 'A', { type: 'chord', i: num });
expect(t.boards.A!.opened).toBeGreaterThan(before);
expect(t.status.A).toBe('playing');
}
// Wrong flags: flag safe neighbours instead, the real mine goes off.
const wrong = nb.filter((j) => p.field[j] !== '*' && s.boards.A!.open[j] !== '1');
const realMines = nb.filter((j) => p.field[j] === '*');
if (wrong.length >= realMines.length && realMines.length) {
let u = s;
for (const j of wrong.slice(0, realMines.length)) u = act(u, 'A', { type: 'flag', i: j });
u = act(u, 'A', { type: 'chord', i: num });
expect(u.status.A).toBe('failed');
}
});
test('안전한 칸을 모두 열면 다 풂 → 혼자면 바로 끝, 걸린 시간 요약', () => {
let s = started(['A']);
let now = START;
for (const i of safe(s)) {
if (s.boards.A!.open[i] === '1') continue;
now += 200;
s = act(s, 'A', { type: 'open', i }, now);
if (s.phase === 'ended') break;
}
expect(s.status.A).toBe('solved');
expect(s.final!.summary).toMatch(/^다 풀었어요! 걸린 시간 /);
expect(minesweeper.result(s)!.scoreText!.A).toMatch(/^다 풀었어요 · /);
});
});
describe('순위·끝', () => {
test('기본은 제한 시간 10분', () => {
expect(minesweeper.defaultOptions.timeLimitSec).toBe(600);
expect(make().endsAt).toBe(START + 600_000);
});
test('먼저 다 푼 사람 > 다 못 푼 사람(연 칸 많은 순), 지뢰 밟은 사람도 연 칸으로, 나간 사람 맨 아래', () => {
let s = started(['A', 'B', 'C', 'D']);
s = act(s, 'B', { type: 'open', i: mines(s)[0]! });
s = act(s, 'D', { type: 'leave' } as A);
s = act(s, 'C', { type: 'stop' });
let now = START;
for (const i of safe(s)) {
if (s.boards.A!.open[i] === '1') continue;
now += 100;
s = act(s, 'A', { type: 'open', i }, now);
if (s.phase === 'ended') break;
}
expect(s.phase).toBe('ended');
const r = s.final!.ranking;
expect(r.map((x) => x.id)).toEqual(['A', 'B', 'C', 'D'].slice(0, 1).concat(r.slice(1, 3).map((x) => x.id), ['D']));
expect(r[0]!.status).toBe('solved');
expect(r[1]!.rank).toBe(2);
expect(r[1]!.rank).toBe(r[2]!.rank); // B and C opened the same cells
expect(s.final!.summary).toBe('가장 먼저 다 푼 사람이 이겼어요');
expect(minesweeper.result(s)!.scoreText!.B).toContain('지뢰를 밟았어요');
expect(minesweeper.result(s)!.scoreText!.C).toContain('포기');
});
test('제한 시간: 마감 tick으로 끝, 마감 뒤 거절, 아무도 못 풀면 연 칸 많은 사람이 이김', () => {
let s = started(['A', 'B'], { timeLimitSec: 180 });
const i = safe(s).find((j) => s.puzzle.field[j] !== '0')!;
s = act(s, 'A', { type: 'open', i });
const end = START + 180_000;
expect(minesweeper.deadline!(s)).toBe(end);
expect(reason(s, 'B', { type: 'open', i }, end)).toBe('시간이 다 됐어요.');
s = minesweeper.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('시간이 다 됐어요. 아무도 다 풀지 못했어요. 가장 많이 푼 사람이 이겼어요');
});
test('무제한: 끊긴 사람은 tick 한 번으로 포기 처리, 모두 끝나면 끝', () => {
let s = started(['A', 'B'], { timeLimitSec: null });
expect(minesweeper.deadline!(s)).toBeNull();
s = minesweeper.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초에 15번까지', () => {
let s = started(['A']);
const cells = mines(s);
for (let k = 0; k < 15; k++) s = act(s, 'A', { type: 'flag', i: cells[k % cells.length]! }, START + 100 + k);
expect(reason(s, 'A', { type: 'flag', i: cells[0]! }, START + 200)).toBe('조금 천천히 해 주세요.');
expect(reason(s, 'A', { type: 'flag', i: cells[0]! }, START + 1200)).toBe('ok');
});
});
describe('무작위 대국', () => {
test('1·2·5·8명, 난이도 셋: 유출·JSON·결정성', () => {
for (let k = 1; k <= playoutSeeds(60); k++) {
for (const n of [1, 2, 5, 8]) {
const level = (['beginner', 'intermediate', 'expert'] as const)[k % 3]!;
const players = Array.from({ length: n }, (_, i) => `p${i}`);
const options = minesweeper.optionsSchema.parse({ level, timeLimitSec: k % 2 ? null : 180 });
const a = randomPlayout(minesweeper, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000 });
expect(a.finished).toBe(true);
const b = randomPlayout(minesweeper, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000 });
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
}
}
});
});

View 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: ['.......#.......', '......###......', '......###......', '.....#####.....', '###############', '.#############.', '..###########..', '...#########...', '....#######....', '...#########...', '...####.####...', '..####...####..', '..###.....###..', '.##.........##.', '.#...........#.'],
},
],
};

View 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 });
});
});

View 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 };
});

View 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],
});

View 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));
}
}
});
});

View 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;
}

View File

@@ -0,0 +1,40 @@
/**
* Live computers for race games (docs/games/race.md §5). Everybody solves their own copy, so a computer cannot get in
* anyone's way: the server asks it again and again on its own timer and it only looks at its own board (`view`).
* The game decides the next move and how long a person of that level would take to find it; this waits that long
* (scaled by the computer's own pace), then plays it.
*/
import type { LiveBotDecision, LiveBotInput, LiveBotStrategy } from '../bots/types';
import type { RaceView } from './index';
/** 0 (level 1) … 1 (level 60); level 30 when none is given. */
export const skillOf = (level: number | undefined): number => Math.max(0, Math.min(1, ((level ?? 30) - 1) / 59));
export interface RacePlan<M> {
/** null = nothing to do (wait and look again). */
move: M | null;
/** How long finding it takes (ms) before the pace factor. */
ms: number;
}
export function raceBot<BV, M>(plan: (board: BV, skill: number, random: () => number, memory: Record<string, unknown>) => RacePlan<M>): LiveBotStrategy<RaceView<BV, unknown>> {
return ({ me, view: v, now, random, persona, level, memory }: LiveBotInput<RaceView<BV, unknown>>): LiveBotDecision<M> => {
if (v.phase === 'ended') return { action: null, next: 10_000 };
if (v.phase === 'countdown' || !v.board) return { action: null, next: Math.max(200, v.countdownEndsAt - now + 50) };
const seat = v.seats.find((s) => s.id === me);
if (!seat || seat.status !== 'playing') return { action: null, next: 10_000 };
const at = typeof memory.at === 'number' ? memory.at : null;
if (at !== null && now < at) return { action: null, next: Math.max(50, at - now) };
if (at !== null && memory.move) {
const move = memory.move as M;
memory.at = null;
memory.move = null;
return { action: move, next: 60 };
}
const p = plan(v.board, skillOf(level), random, memory);
const ms = Math.max(60, Math.round(p.ms * (0.75 + 0.25 * persona.pace)));
memory.at = now + ms;
memory.move = p.move;
return { action: null, next: ms };
};
}

View File

@@ -0,0 +1,395 @@
/**
* Shared frame for "same puzzle, everyone on their own copy" games (지뢰찾기, 사천성, 솔리테어, 스도쿠, 네모네모 로직;
* docs/games/race.md). One seeded puzzle is dealt to everybody; each player solves their own board at the same time.
* The frame owns the clock (3-second countdown, optional time limit), give-up (`stop`), leaving, the stopwatch and the
* ranking (solved first by time, then the rest by progress). A game only supplies the puzzle and its moves.
* Pure and deterministic; state is JSON; time only via ctx.now.
*/
import { z } from 'zod';
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine';
export const COUNTDOWN_MS = 3000;
export const MAX_PLAYERS = 8;
/** `solved` = finished the puzzle, `failed` = a game-ending mistake (지뢰), `done` = gave up (포기). */
export type RaceStatus = 'playing' | 'solved' | 'failed' | 'done' | 'left';
export type RaceEndReason = 'finished' | 'time' | 'left';
/** A literal union schema (`lit(1, 2, null)`). */
export const lit = <T extends number | string | boolean | null>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
/** The time limit option every race game has: null = 무제한 (until everyone solves or gives up). */
export function timeLimitOption<T extends number>(choices: T[], def: T | null) {
const labels: Record<string, string> = { null: '무제한' };
for (const c of choices) labels[String(c)] = c % 60 === 0 ? `${c / 60}분` : `${c}초`;
return lit<T | null>(...choices, null)
.default(def as T | null)
.meta({ title: '제한 시간', labels });
}
export interface RaceRow {
rank: number;
id: PlayerId;
status: RaceStatus;
progress: number;
/** From the start until solved / failed / gave up; null while still playing (or left). */
timeMs: number | null;
/** Result line, e.g. "다 풀었어요 · 3분 05.4초" or "연 칸 40/71 · 지뢰". */
text: string;
}
export interface RaceFinal {
endReason: RaceEndReason;
ranking: RaceRow[];
summary: string;
}
export interface RaceState<P, B, O> {
options: O;
order: PlayerId[];
/** The shared puzzle (hidden during the countdown). */
puzzle: P;
boards: Record<PlayerId, B>;
status: Record<PlayerId, RaceStatus>;
/** Server time each player solved / failed / gave up. */
finishedAt: Record<PlayerId, number>;
/** Server times of each player's recent moves (rate limit). */
recent: Record<PlayerId, number[]>;
phase: 'countdown' | 'playing' | 'ended';
countdownEndsAt: number;
/** null = 무제한. */
endsAt: number | null;
final: RaceFinal | null;
}
export interface RaceSeat {
id: PlayerId;
status: RaceStatus;
progress: number;
/** Progress in words ("연 칸 40/71"). */
progressText: string;
timeMs: number | null;
/** Extra counts in words (" · 힌트 2번"), or ''. */
extra: string;
}
export interface RaceView<BV, O> {
options: O;
me: PlayerId | null;
phase: 'countdown' | 'playing' | 'ended';
countdownEndsAt: number;
endsAt: number | null;
/** My board as I may see it; null for spectators and during the countdown. */
board: BV | null;
seats: RaceSeat[];
result: RaceFinal | null;
}
export type StopAction = { type: 'stop' };
export type RaceAction<M> = M | StopAction | { type: 'tick' } | { type: 'leave' };
export interface MoveOutcome<B> {
board: B;
/** The move finished the puzzle, or ended it by a mistake (지뢰). */
outcome?: 'solved' | 'failed';
events?: GameEvent[];
}
export interface RaceSpec<P, B, M extends { type: string }, BV, O extends { timeLimitSec: number | null }> {
id: string;
nameKo: string;
optionsSchema: z.ZodType<O>;
/** The game's own moves (each a `z.object` with a literal `type`). */
moveSchemas: [z.ZodObject<{ type: z.ZodLiteral<string> } & z.ZodRawShape>, ...z.ZodObject<{ type: z.ZodLiteral<string> } & z.ZodRawShape>[]];
/** Moves per second a player may send (default 12). */
movesPerSec?: number;
makePuzzle(rng: Rng, options: O): P;
startBoard(puzzle: P, options: O): B;
/** Korean reason the move is refused, or null. Only called while the player is playing. */
checkMove(puzzle: P, board: B, move: M, options: O): string | null;
applyMove(puzzle: P, board: B, move: M, ctx: { rng: Rng; now: number; options: O }): MoveOutcome<B>;
/** What the player sees of their own board. `reveal` = they are finished or the game is over (show the answer). */
boardView(puzzle: P, board: B, reveal: boolean, options: O): BV;
/** Bigger is better; ranks players who did not solve. */
progress(puzzle: P, board: B): number;
progressText(puzzle: P, board: B): string;
/** " · 힌트 2번" etc., or ''. */
extraText?(board: B): string;
/** Word for a `failed` player in result lines ("지뢰를 밟음"). */
failText?: string;
/** Test helper: a few legal moves. */
legalMoves(puzzle: P, board: B, options: O): M[];
/** Strings that must not reach anybody before the countdown ends (the puzzle's hidden parts). */
secrets?(puzzle: P): string[];
}
/** "25.4초", "3분 05.4초" (tenths, rounded down). */
export function formatElapsed(ms: number): string {
const t = Math.floor(Math.max(0, ms) / 100);
const m = Math.floor(t / 600);
const sec = ((t % 600) / 10).toFixed(1);
return m > 0 ? `${m}분 ${sec.padStart(4, '0')}초` : `${sec}초`;
}
export function timeOf(s: Pick<RaceState<unknown, unknown, unknown>, 'finishedAt' | 'countdownEndsAt' | 'status'>, p: PlayerId): number | null {
const at = s.finishedAt[p];
return at === undefined || s.status[p] === 'left' ? null : Math.max(0, at - s.countdownEndsAt);
}
const GROUP: Record<RaceStatus, number> = { solved: 0, playing: 1, failed: 1, done: 1, left: 2 };
/**
* Ranking: who solved, fastest first; then everybody else still in by progress; players who left last.
* Equal time (solved) or equal progress (not solved) share a rank.
*/
export function rankSeats<T extends { id: PlayerId; status: RaceStatus; progress: number; timeMs: number | null }>(seats: T[]): (T & { rank: number })[] {
const key = (s: T) => (s.status === 'solved' ? (s.timeMs ?? 0) : -s.progress);
const sorted = [...seats].sort((a, b) => GROUP[a.status] - GROUP[b.status] || key(a) - key(b));
const out: (T & { rank: number })[] = [];
sorted.forEach((s, i) => {
const prev = out[i - 1];
const tie = prev && GROUP[prev.status] === GROUP[s.status] && key(prev) === key(s);
out.push({ ...s, rank: tie ? prev.rank : i + 1 });
});
return out;
}
export function makeRaceGame<P, B, M extends { type: string }, BV, O extends { timeLimitSec: number | null }>(
spec: RaceSpec<P, B, M, BV, O>,
): GameDefinition<RaceState<P, B, O>, RaceAction<M>, RaceView<BV, O>, O> {
type S = RaceState<P, B, O>;
type A = RaceAction<M>;
type Def = GameDefinition<S, A, RaceView<BV, O>, O>;
const perSec = spec.movesPerSec ?? 12;
const actionSchema = z.discriminatedUnion('type', [...spec.moveSchemas, z.object({ type: z.literal('stop') })] as never);
interface Ctx {
now: number;
events: GameEvent[];
}
const clone = (s: S): S => ({
...s,
order: [...s.order],
boards: { ...s.boards },
status: { ...s.status },
finishedAt: { ...s.finishedAt },
recent: { ...s.recent },
});
const inGame = (s: S, p: PlayerId) => s.status[p] !== 'left';
const started = (s: S, now: number | undefined) => s.phase === 'playing' || (s.phase === 'countdown' && now !== undefined && now >= s.countdownEndsAt);
const rateOk = (times: readonly number[] | undefined, now: number | undefined) =>
now === undefined || !times || times.length < perSec || now - times[times.length - perSec]! >= 1000;
const extra = (b: B) => spec.extraText?.(b) ?? '';
const seats = (s: S): RaceSeat[] =>
s.order.map((id) => ({
id,
status: s.status[id]!,
progress: spec.progress(s.puzzle, s.boards[id]!),
progressText: spec.progressText(s.puzzle, s.boards[id]!),
timeMs: timeOf(s, id),
extra: extra(s.boards[id]!),
}));
const rowText = (seat: RaceSeat): string => {
if (seat.status === 'solved') return `다 풀었어요 · ${formatElapsed(seat.timeMs ?? 0)}${seat.extra}`;
const why = seat.status === 'failed' ? ` · ${spec.failText ?? '실패'}` : seat.status === 'done' ? ' · 포기' : seat.status === 'left' ? ' · 나감' : '';
return `${seat.progressText}${why}${seat.extra}`;
};
function finish(s: S, reason: RaceEndReason, ctx: Ctx): void {
if (s.phase === 'ended') return;
s.phase = 'ended';
const ranking: RaceRow[] = rankSeats(seats(s)).map((r) => ({ rank: r.rank, id: r.id, status: r.status, progress: r.progress, timeMs: r.timeMs, text: rowText(r) }));
let summary: string;
if (s.order.length === 1) {
const r = ranking[0]!;
const p = s.order[0]!;
if (r.status === 'solved') summary = `다 풀었어요! 걸린 시간 ${formatElapsed(r.timeMs ?? 0)}${extra(s.boards[p]!)}`;
else {
const why = reason === 'time' ? '시간이 다 됐어요' : r.status === 'failed' ? (spec.failText ?? '실패했어요') : r.status === 'done' ? '포기했어요' : '게임이 끝났어요';
summary = `${why}. ${spec.progressText(s.puzzle, s.boards[p]!)}`;
}
} else {
const solved = ranking.filter((r) => r.status === 'solved');
const head = reason === 'time' ? '시간이 다 됐어요. ' : '';
summary = solved.length ? `${head}가장 먼저 다 푼 사람이 이겼어요` : `${head}아무도 다 풀지 못했어요. 가장 많이 푼 사람이 이겼어요`;
const top = ranking.filter((r) => r.rank === 1 && r.status !== 'left');
if (top.length > 1) summary += ` (공동 1등 ${top.length}명)`;
}
s.final = { endReason: reason, ranking, summary };
ctx.events.push({ type: 'gameEnd', reason });
}
const checkEnd = (s: S, ctx: Ctx) => {
if (s.order.every((q) => s.status[q] !== 'playing')) finish(s, s.order.some((q) => inGame(s, q)) ? 'finished' : 'left', ctx);
};
function catchUp(s: S, ctx: Ctx): void {
if (s.phase === 'countdown' && ctx.now >= s.countdownEndsAt) {
s.phase = 'playing';
ctx.events.push({ type: 'start' });
}
if (s.phase === 'playing' && s.endsAt !== null && ctx.now >= s.endsAt) finish(s, 'time', ctx);
}
function end(s: S, p: PlayerId, status: 'solved' | 'failed' | 'done', ctx: Ctx): void {
s.status[p] = status;
s.finishedAt[p] = ctx.now;
ctx.events.push({ type: status, player: p });
checkEnd(s, ctx);
}
const def: Def = {
id: spec.id,
nameKo: spec.nameKo,
realtime: true,
minPlayers: 1,
maxPlayers: MAX_PLAYERS,
stateVersion: 1,
defaultOptions: spec.optionsSchema.parse({}),
optionsSchema: spec.optionsSchema as unknown as Def['optionsSchema'],
actionSchema: actionSchema as unknown as Def['actionSchema'],
setup({ players, options, rng, now }) {
if (players.length < 1 || players.length > MAX_PLAYERS) throw new Error(`${spec.id}: ${players.length} players not allowed`);
const puzzle = spec.makePuzzle(rng, options);
const board = spec.startBoard(puzzle, options);
const per = <T>(v: () => T) => Object.fromEntries(players.map((p) => [p, v()])) as Record<PlayerId, T>;
const countdownEndsAt = now + COUNTDOWN_MS;
return {
options,
order: [...players],
puzzle,
boards: per(() => board),
status: per<RaceStatus>(() => 'playing'),
finishedAt: {},
recent: per<number[]>(() => []),
phase: 'countdown',
countdownEndsAt,
endsAt: options.timeLimitSec === null ? null : countdownEndsAt + options.timeLimitSec * 1000,
final: null,
};
},
validate(s, actor, a, vctx) {
if (!s.order.includes(actor)) return fail('이 게임의 플레이어가 아니에요.');
if (s.phase === 'ended') return fail('게임이 이미 끝났어요.');
const now = vctx?.now;
if (a.type === 'tick') return ok;
if (a.type === 'leave') return inGame(s, actor) ? ok : fail('이미 게임에서 빠졌어요.');
if (s.status[actor] === 'left') return fail('게임에서 빠졌어요.');
if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.');
if (now !== undefined && s.endsAt !== null && now >= s.endsAt) return fail('시간이 다 됐어요.');
if (s.status[actor] !== 'playing') return fail('이미 끝냈어요.');
if (a.type === 'stop') return ok;
if (!rateOk(s.recent[actor], now)) return fail('조금 천천히 해 주세요.');
const why = spec.checkMove(s.puzzle, s.boards[actor]!, a as M, s.options);
return why ? fail(why) : ok;
},
apply(prev, actor, a, { now, rng }) {
const s = clone(prev);
const ctx: Ctx = { now, events: [] };
const wasPlaying = prev.phase === 'playing';
catchUp(s, ctx);
if (s.phase === 'ended') return { state: s, events: ctx.events };
if (a.type === 'leave') {
s.status[actor] = 'left';
ctx.events.push({ type: 'left', player: actor });
checkEnd(s, ctx);
} else if (a.type === 'stop') {
if (s.phase === 'playing' && s.status[actor] === 'playing') end(s, actor, 'done', ctx);
} else if (a.type === 'tick') {
// 무제한: nothing is due during play, so a tick there means the room timed this player out while away.
if (wasPlaying && s.endsAt === null && s.status[actor] === 'playing') end(s, actor, 'done', ctx);
} else if (s.phase === 'playing' && s.status[actor] === 'playing') {
const r = spec.applyMove(s.puzzle, s.boards[actor]!, a as M, { rng, now, options: s.options });
s.boards[actor] = r.board;
s.recent[actor] = [...(s.recent[actor] ?? []).slice(-(perSec - 1)), now];
for (const e of r.events ?? []) ctx.events.push({ ...e, player: actor });
if (r.outcome) end(s, actor, r.outcome, ctx);
}
return { state: s, events: ctx.events };
},
view(s, viewer) {
const me = viewer && s.order.includes(viewer) ? viewer : null;
const reveal = !!me && (s.phase === 'ended' || s.status[me] !== 'playing');
return {
options: s.options,
me,
phase: s.phase,
countdownEndsAt: s.countdownEndsAt,
endsAt: s.endsAt,
board: me && s.phase !== 'countdown' ? spec.boardView(s.puzzle, s.boards[me]!, reveal, s.options) : null,
seats: seats(s),
result: s.final,
};
},
activePlayers(s) {
if (s.phase === 'ended') return [];
return s.order.filter((p) => s.status[p] === 'playing');
},
deadline(s) {
if (s.phase === 'ended') return null;
return s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt;
},
/** With a time limit everyone still in drives the clock; 무제한 after the start only those still playing (away → 포기 after the grace). */
timeoutPlayers(s) {
if (s.phase === 'ended') return [];
if (s.phase === 'playing' && s.endsAt === null) return s.order.filter((p) => s.status[p] === 'playing');
return s.order.filter((p) => inGame(s, p));
},
/** A disconnected player is never timed out early: their board simply waits for the clock. */
timeoutNotBefore(s) {
if (s.phase === 'ended') return null;
return s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt;
},
onTimeout() {
return { type: 'tick' };
},
onLeave(s, player) {
if (s.phase === 'ended' || !inGame(s, player)) return null;
return { type: 'leave' };
},
result(s): GameResult | null {
const f = s.final;
if (!f) return null;
const groups = new Map<number, PlayerId[]>();
for (const r of f.ranking) groups.set(r.rank, [...(groups.get(r.rank) ?? []), r.id]);
return {
ranking: [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ids]) => ids),
scores: Object.fromEntries(f.ranking.map((r) => [r.id, r.progress])),
scoreText: Object.fromEntries(f.ranking.map((r) => [r.id, r.text])),
summary: f.summary,
reason: 'normal',
};
},
/** Test helper: the clock tick, a few of the game's moves and 포기 (rarely, so random games get somewhere). */
legalActions(s, p) {
if (s.phase === 'ended' || !s.order.includes(p)) return [];
const out: A[] = [{ type: 'tick' }];
if (s.phase === 'playing' && s.status[p] === 'playing') {
const moves = spec.legalMoves(s.puzzle, s.boards[p]!, s.options);
out.push(...moves);
if (moves.length === 0 || s.recent[p]!.length >= perSec) out.push({ type: 'stop' });
}
return out.filter((x) => def.validate(s, p, x).ok);
},
secretsOf(s) {
return s.phase === 'countdown' ? (spec.secrets?.(s.puzzle) ?? []) : [];
},
};
return def;
}

View File

@@ -0,0 +1,63 @@
/** 사천성 computers (docs/games/shisen.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 { pairsNow, shisenBot } from './bot';
import { shisen, type ShisenState } from './index';
const isBot = (p: string) => p.startsWith('bot:');
describe('한 판 전체', () => {
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}:s${n}${i}`));
for (const size of ['small', 'normal'] as const) {
const r = liveBotPlayout(shisen, shisenBot, {
players,
options: shisen.optionsSchema.parse({ size, timeLimitSec: humans ? 900 : null }),
seed: seedN(n * 10 + humans),
isBot,
levelOf: (p) => 1 + ((p.length * 7) % 60),
});
expect(r.finished).toBe(true);
expect(r.rejected).toEqual([]);
expect(r.maxBotMs).toBeLessThan(50);
const s = r.state as ShisenState;
for (const p of players) if (isBot(p)) expect(s.status[p]).toBe('solved');
}
}
}
});
test('강한 컴퓨터가 약한 컴퓨터보다 대부분 빨리 다 풀어요', () => {
let faster = 0;
const times = { weak: 0, strong: 0 };
for (let k = 0; k < 10; k++) {
const r = liveBotPlayout(shisen, shisenBot, {
players: ['bot:1:weak', 'bot:2:strong'],
options: shisen.optionsSchema.parse({ size: 'small', timeLimitSec: null }),
seed: seedN(700 + k),
isBot,
levelOf: (p) => (p.endsWith('weak') ? 3 : 58),
});
const s = r.state as ShisenState;
expect(r.rejected).toEqual([]);
const t = (p: string) => s.finishedAt[p]! - s.countdownEndsAt;
times.weak += t('bot:1:weak');
times.strong += t('bot:2:strong');
if (t('bot:2:strong') < t('bot:1:weak')) faster++;
}
expect(faster).toBeGreaterThanOrEqual(9);
expect(times.strong * 2.5).toBeLessThan(times.weak);
});
test('보는 쌍: 곧은 줄·가까운 쌍은 쉬운 쌍', () => {
// 3×4: 1m 1m side by side (easy), 2p at both far corners joined over the margin (not easy).
const v = { rows: 3, cols: 4, cells: ['1m', '1m', null, '2p', null, null, null, null, '2p', null, null, null], hint: null, shuffles: 0, hints: 0 };
expect(pairsNow(v)).toEqual([
{ a: 0, b: 1, easy: true },
{ a: 3, b: 8, easy: false },
]);
});
});

View File

@@ -0,0 +1,45 @@
/**
* 사천성 computers (docs/games/shisen.md §13). They only read their own board.
* - They look for a pair that goes now (findPath). A weak computer mostly notices pairs that are close or joined by a
* straight line and spends long looking; a strong one sees any pair quickly.
* - Time per pair: about 7 s at level 1 … 1.5 s at level 60 (longer when only a far pair is left for a weak one).
*/
import { raceBot } from '../race/bot';
import { findPath, reachable, type ShisenBoardView, type ShisenMove } from './index';
type V = ShisenBoardView;
export interface SeenPair {
a: number;
b: number;
/** Easy to notice: a straight line, or close by with one turn. */
easy: boolean;
}
/** Every pair that goes now on the board. */
export function pairsNow(v: V): SeenPair[] {
const out: SeenPair[] = [];
for (let a = 0; a < v.cells.length; a++) {
if (v.cells[a] == null) continue;
for (const b of reachable(v.cells, v.rows, v.cols, a)) {
if (b <= a || v.cells[b] !== v.cells[a]) continue;
const path = findPath(v.cells, v.rows, v.cols, a, b)!;
const dist = Math.abs(Math.floor(a / v.cols) - Math.floor(b / v.cols)) + Math.abs((a % v.cols) - (b % v.cols));
out.push({ a, b, easy: path.length === 2 || (path.length === 3 && dist <= 4) });
}
}
return out;
}
export const shisenBot = raceBot<V, ShisenMove>((v, skill, random) => {
const step = 7000 - 5500 * skill;
const all = pairsNow(v);
if (!all.length) return { move: null, ms: 1000 };
const easy = all.filter((p) => p.easy);
const seesAll = random() < 0.25 + 0.75 * skill;
const pool = seesAll || !easy.length ? all : easy;
const p = pool[Math.floor(random() * pool.length)]!;
// A weak computer that finds only a far pair took a while to spot it.
const slow = !seesAll && !p.easy ? 1.8 : 1;
return { move: { type: 'pair', a: p.a, b: p.b }, ms: step * slow * (0.6 + 0.8 * random()) };
});

View File

@@ -0,0 +1,283 @@
/**
* 사천성 (docs/games/shisen.md). Everyone clears the same board of mahjong tiles on their own copy (race frame, ../race).
* Two tiles of the same kind go together when a line of at most three straight segments (two turns) joins them
* through empty cells; the line may run through the one-cell margin around the board.
* Every deal is solvable: the pairs are chosen by taking the board apart (two connectable cells at a time, the reverse
* of placing pairs one by one onto empty cells), and the kinds are put on afterwards. When a board has tiles left but
* no connectable pair, the engine reshuffles the remaining tiles over the same cells the same way.
*/
import { z } from 'zod';
import type { GameEvent, Rng } from '@bg/engine';
import { lit, makeRaceGame, timeLimitOption, type RaceState, type RaceView } from '../race';
export { COUNTDOWN_MS, formatElapsed } from '../race';
export const SIZES = {
small: { rows: 6, cols: 12, kinds: 18, name: '작게' },
normal: { rows: 8, cols: 14, kinds: 28, name: '보통' },
large: { rows: 8, cols: 17, kinds: 34, name: '크게' },
} as const;
export type Size = keyof typeof SIZES;
/** The 34 mahjong tile kinds (만수·통수·삭수 1~9, 자패 동남서북백발중). */
export const KINDS: string[] = [...['m', 'p', 's'].flatMap((s) => Array.from({ length: 9 }, (_, i) => `${i + 1}${s}`)), ...Array.from({ length: 7 }, (_, i) => `${i + 1}z`)];
export const shisenOptionsSchema = z.object({
size: lit<Size>('small', 'normal', 'large')
.default('normal')
.meta({ title: '판 크기', labels: { small: '작게 12×6 · 72패', normal: '보통 14×8 · 112패', large: '크게 17×8 · 136패' } }),
hints: z.boolean().default(true).meta({ title: '힌트 쓰기' }),
timeLimitSec: timeLimitOption([300, 600, 900, 1200], 900),
});
export type ShisenOptions = z.infer<typeof shisenOptionsSchema>;
const cell = z.number().int().min(0).max(135);
const moveSchemas = [z.object({ type: z.literal('pair'), a: cell, b: cell }), z.object({ type: z.literal('hint') })] as const;
export type ShisenMove = { type: 'pair'; a: number; b: number } | { type: 'hint' };
/** Per cell a kind code ('5m') or null (empty). Row-major. */
export type Cells = (string | null)[];
export interface ShisenPuzzle {
rows: number;
cols: number;
cells: Cells;
}
export interface ShisenBoard {
cells: Cells;
/** Pairs removed. */
removed: number;
/** The pair a hint shows, or null. */
hint: [number, number] | null;
hints: number;
shuffles: number;
}
export interface ShisenBoardView {
rows: number;
cols: number;
cells: Cells;
hint: [number, number] | null;
shuffles: number;
hints: number;
}
export type ShisenState = RaceState<ShisenPuzzle, ShisenBoard, ShisenOptions>;
export type ShisenView = RaceView<ShisenBoardView, ShisenOptions>;
/** A point of a connecting line: [row, col]; -1 / rows / cols are the margin outside the board. */
export type Point = [number, number];
const DIRS: Point[] = [
[-1, 0],
[1, 0],
[0, -1],
[0, 1],
];
/**
* The line joining cells `a` and `b` (both tiles) through empty cells and the margin with at most two turns:
* [a, corners…, b] as [row, col] points, the fewest turns first and then the shortest. null when there is none.
* Only the geometry is checked, not the kinds.
*/
export function findPath(cells: Cells, rows: number, cols: number, a: number, b: number): Point[] | null {
if (a === b) return null;
const A: Point = [Math.floor(a / cols), a % cols];
const B: Point = [Math.floor(b / cols), b % cols];
const inside = (r: number, c: number) => r >= -1 && r <= rows && c >= -1 && c <= cols;
const empty = (r: number, c: number) => inside(r, c) && (r < 0 || r >= rows || c < 0 || c >= cols || cells[r * cols + c] == null);
/** Cells strictly between p and q (same row or column) are all empty. */
const clear = (p: Point, q: Point) => {
const dr = Math.sign(q[0] - p[0]);
const dc = Math.sign(q[1] - p[1]);
for (let r = p[0] + dr, c = p[1] + dc; r !== q[0] || c !== q[1]; r += dr, c += dc) if (!empty(r, c)) return false;
return true;
};
if ((A[0] === B[0] || A[1] === B[1]) && clear(A, B)) return [A, B];
for (const C of [[A[0], B[1]] as Point, [B[0], A[1]] as Point]) if (empty(C[0], C[1]) && clear(A, C) && clear(C, B)) return [A, C, B];
let best: Point[] | null = null;
let bestLen = Infinity;
for (const [dr, dc] of DIRS) {
for (let k = 1; ; k++) {
const P: Point = [A[0] + dr * k, A[1] + dc * k];
if (!empty(P[0], P[1])) break;
// A → P, then across to the line of B, then along it to B.
const Q: Point = dr === 0 ? [B[0], P[1]] : [P[0], B[1]];
if ((Q[0] === P[0] && Q[1] === P[1]) || !empty(Q[0], Q[1]) || !clear(P, Q) || !clear(Q, B)) continue;
const len = k + Math.abs(Q[0] - P[0]) + Math.abs(Q[1] - P[1]) + Math.abs(B[0] - Q[0]) + Math.abs(B[1] - Q[1]);
if (len < bestLen) [best, bestLen] = [[A, P, Q, B], len];
}
}
return best;
}
/**
* Every tile (any kind) that a line with at most two turns joins to cell `a` through empty cells and the margin.
* A walk over (cell, direction) states, one layer per segment.
*/
export function reachable(cells: Cells, rows: number, cols: number, a: number): number[] {
const C = cols + 2;
const R = rows + 2;
const seen = new Uint8Array(R * C * 4);
const hit = new Set<number>();
let starts: { r: number; c: number; dirs: number[] }[] = [{ r: Math.floor(a / cols), c: a % cols, dirs: [0, 1, 2, 3] }];
for (let seg = 0; seg < 3; seg++) {
const next: typeof starts = [];
for (const s of starts)
for (const d of s.dirs) {
const [dr, dc] = DIRS[d]!;
for (let r = s.r + dr, c = s.c + dc; r >= -1 && r <= rows && c >= -1 && c <= cols; r += dr, c += dc) {
const onBoard = r >= 0 && r < rows && c >= 0 && c < cols;
if (onBoard && cells[r * cols + c] != null) {
if (r * cols + c !== a) hit.add(r * cols + c);
break;
}
const k = ((r + 1) * C + (c + 1)) * 4 + d;
if (seen[k]) break;
seen[k] = 1;
next.push({ r, c, dirs: d < 2 ? [2, 3] : [0, 1] });
}
}
starts = next;
}
return [...hit];
}
/** One pair that can go now (first in board order), or null. */
export function findPair(cells: Cells, rows: number, cols: number): [number, number] | null {
for (let a = 0; a < cells.length; a++) {
if (cells[a] == null) continue;
for (const b of reachable(cells, rows, cols, a)) if (b > a && cells[b] === cells[a]) return [a, b];
}
return null;
}
/**
* Puts the tile kinds of `pairs` (one kind code per pair) on the cells `fill` so that the board can always be cleared.
* The cells are taken apart two connectable ones at a time (a random cell and a random partner it reaches), which is
* placing pairs onto empty cells run backwards; that never dead-ends, because the top tiles of two columns (or the top
* two of a lone column) always connect over the top margin. Returns the cells and the removal order (a solution).
*/
export function deal(rng: Rng, rows: number, cols: number, fill: number[], pairs: string[]): { cells: Cells; solution: [number, number][] } {
if (fill.length !== pairs.length * 2) throw new Error('shisen: cells and tiles do not match');
const occ: Cells = Array(rows * cols).fill(null);
for (const i of fill) occ[i] = '#';
const left = new Set(fill);
const solution: [number, number][] = [];
while (left.size) {
let found: [number, number] | null = null;
for (const a of rng.shuffle([...left])) {
const r = reachable(occ, rows, cols, a);
if (r.length) {
found = [a, r[rng.int(r.length)]!];
break;
}
}
if (!found) throw new Error('shisen: no connectable cells'); // cannot happen (see above)
const [a, b] = found;
occ[a] = occ[b] = null;
left.delete(a);
left.delete(b);
solution.push(found);
}
const kinds = rng.shuffle(pairs);
const cells: Cells = Array(rows * cols).fill(null);
solution.forEach(([a, b], k) => (cells[a] = cells[b] = kinds[k]!));
return { cells, solution };
}
/** A new deal for the size: seeded kinds (all 34 for 크게), 4 tiles of each. */
export function makeDeal(rng: Rng, size: Size): ShisenPuzzle & { solution: [number, number][] } {
const { rows, cols, kinds } = SIZES[size];
const picked = kinds === KINDS.length ? KINDS : rng.shuffle(KINDS).slice(0, kinds);
const d = deal(
rng,
rows,
cols,
Array.from({ length: rows * cols }, (_, i) => i),
picked.flatMap((k) => [k, k]),
);
return { rows, cols, ...d };
}
/** The remaining tiles shuffled over the same cells, again clearable. */
export function reshuffle(rng: Rng, rows: number, cols: number, cells: Cells): Cells {
const fill: number[] = [];
const count = new Map<string, number>();
cells.forEach((k, i) => {
if (k == null) return;
fill.push(i);
count.set(k, (count.get(k) ?? 0) + 1);
});
const pairs = [...count.entries()].sort((x, y) => (x[0] < y[0] ? -1 : 1)).flatMap(([k, n]) => Array<string>(n / 2).fill(k));
return deal(rng, rows, cols, fill, pairs).cells;
}
const tilesOf = (p: ShisenPuzzle) => p.cells.filter((k) => k != null).length;
export const shisen = makeRaceGame<ShisenPuzzle, ShisenBoard, ShisenMove, ShisenBoardView, ShisenOptions>({
id: 'shisen',
nameKo: '사천성',
optionsSchema: shisenOptionsSchema,
moveSchemas: moveSchemas as never,
makePuzzle(rng, o) {
const { rows, cols, cells } = makeDeal(rng, o.size);
return { rows, cols, cells };
},
startBoard: (p) => ({ cells: [...p.cells], removed: 0, hint: null, hints: 0, shuffles: 0 }),
checkMove(p, b, m, o) {
if (m.type === 'hint') {
if (!o.hints) return '힌트를 쓰지 않는 방이에요.';
return b.hint ? '이미 힌트가 보여요.' : null;
}
const n = p.rows * p.cols;
if (m.a >= n || m.b >= n) return '판 밖의 칸이에요.';
if (m.a === m.b) return '서로 다른 두 패를 골라 주세요.';
const x = b.cells[m.a];
const y = b.cells[m.b];
if (x == null || y == null) return '빈 칸이에요.';
if (x !== y) return '같은 패가 아니에요.';
if (!findPath(b.cells, p.rows, p.cols, m.a, m.b)) return '두 번 넘게 꺾여야 이어져요.';
return null;
},
applyMove(p, b, m, { rng }) {
if (m.type === 'hint') return { board: { ...b, hint: findPair(b.cells, p.rows, p.cols), hints: b.hints + 1 }, events: [{ type: 'hint' }] };
let cells = [...b.cells];
cells[m.a] = cells[m.b] = null;
const removed = b.removed + 1;
let hint = b.hint && (b.hint.includes(m.a) || b.hint.includes(m.b)) ? null : b.hint;
let shuffles = b.shuffles;
const events: GameEvent[] = [{ type: 'pair', a: m.a, b: m.b }];
const solved = removed * 2 === tilesOf(p);
if (!solved && !findPair(cells, p.rows, p.cols)) {
cells = reshuffle(rng, p.rows, p.cols, cells);
shuffles++;
hint = null;
events.push({ type: 'shuffle' });
}
return { board: { cells, removed, hint, hints: b.hints, shuffles }, outcome: solved ? 'solved' : undefined, events };
},
boardView: (p, b) => ({ rows: p.rows, cols: p.cols, cells: b.cells, hint: b.hint, shuffles: b.shuffles, hints: b.hints }),
progress: (_p, b) => b.removed,
progressText: (p, b) => `없앤 쌍 ${b.removed}/${tilesOf(p) / 2}`,
extraText: (b) => `${b.shuffles ? ` · 섞기 ${b.shuffles}번` : ''}${b.hints ? ` · 힌트 ${b.hints}번` : ''}`,
legalMoves(p, b, o) {
const out: ShisenMove[] = [];
for (let a = 0; a < b.cells.length && out.length < 4; a++) {
if (b.cells[a] == null) continue;
for (const c of reachable(b.cells, p.rows, p.cols, a)) if (c > a && b.cells[c] === b.cells[a] && out.length < 4) out.push({ type: 'pair', a, b: c });
}
if (o.hints && !b.hint) out.push({ type: 'hint' });
return out;
},
secrets: (p) => [p.cells.join('')],
});

View File

@@ -0,0 +1,311 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import { COUNTDOWN_MS, KINDS, SIZES, findPair, findPath, makeDeal, reachable, reshuffle, shisen, type Cells, type ShisenOptions, type ShisenState } from './index';
const T0 = 1_000_000;
const START = T0 + COUNTDOWN_MS;
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
type A = Parameters<typeof shisen.apply>[2];
function make(players = ['A', 'B'], opts: Partial<ShisenOptions> = {}, seed = 1): ShisenState {
return shisen.setup({ players, options: shisen.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 });
}
function act(s: ShisenState, p: string, a: A, now = START + 1000): ShisenState {
const v = shisen.validate(s, p, a, { now });
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
return shisen.apply(s, p, a, { rng: rng(), now }).state;
}
const reason = (s: ShisenState, p: string, a: A, now = START + 1000) => {
const v = shisen.validate(s, p, a, { now });
return v.ok ? 'ok' : v.reason;
};
const started = (players?: string[], opts?: Partial<ShisenOptions>, seed?: number) => shisen.apply(make(players, opts, seed), 'A', { type: 'tick' }, { rng: rng(), now: START }).state;
const pairOf = (s: ShisenState, p = 'A') => {
const b = s.boards[p]!;
return findPair(b.cells, s.puzzle.rows, s.puzzle.cols)!;
};
/** Clears A's board pair by pair (any pair that goes now), 300 ms apart. */
function clearAll(s: ShisenState, p = 'A', from = START): ShisenState {
let now = from;
while (s.status[p] === 'playing' && s.phase !== 'ended') {
const [a, b] = pairOf(s, p);
now += 300;
s = act(s, p, { type: 'pair', a, b }, now);
}
return s;
}
/** A hand-made board (tests): puzzle and every board get these cells. */
function withCells(s: ShisenState, rows: number, cols: number, cells: Cells): ShisenState {
const puzzle = { rows, cols, cells };
const boards = Object.fromEntries(Object.keys(s.boards).map((p) => [p, { cells: [...cells], removed: 0, hint: null, hints: 0, shuffles: 0 }]));
return { ...s, puzzle, boards };
}
const grid = (rows: string[]): Cells => rows.flatMap((r) => r.match(/../g)!.map((x) => (x === '..' ? null : x)));
describe('판 만들기', () => {
test('크기별 칸·패 수, 한 종류에 4장, 같은 시드 = 같은 판, 모두 같은 판', () => {
for (const size of ['small', 'normal', 'large'] as const) {
for (let k = 1; k <= 10; k++) {
const p = makeDeal(SeededRng.fromSeed(seedN(k)), size);
const S = SIZES[size];
expect([p.rows, p.cols]).toEqual([S.rows, S.cols]);
expect(p.cells).toHaveLength(S.rows * S.cols);
const count = new Map<string, number>();
for (const c of p.cells) count.set(c!, (count.get(c!) ?? 0) + 1);
expect(count.size).toBe(S.kinds);
for (const [kind, n] of count) {
expect(KINDS).toContain(kind);
expect(n).toBe(4);
}
expect(makeDeal(SeededRng.fromSeed(seedN(k)), size)).toEqual(p);
}
}
expect(KINDS).toHaveLength(34);
const s = make(['A', 'B', 'C'], { size: 'small' });
expect(new Set(Object.values(s.boards).map((b) => JSON.stringify(b.cells))).size).toBe(1);
expect(make(['A'], { size: 'small' }, 2).puzzle.cells).not.toEqual(s.puzzle.cells);
});
test('언제나 풀리는 판: 크기마다 200판, 풀이 순서대로 없애면 모두 규칙대로 없어지고, 크게도 빨리 만들어요', () => {
for (const size of ['small', 'normal', 'large'] as const) {
let slowest = 0;
for (let k = 1; k <= 200; k++) {
const t0 = performance.now();
const d = makeDeal(SeededRng.fromSeed(seedN(1000 + k)), size);
slowest = Math.max(slowest, performance.now() - t0);
expect(d.solution).toHaveLength(d.cells.length / 2);
const cells = [...d.cells];
for (const [a, b] of d.solution) {
expect(cells[a]).not.toBeNull();
expect(cells[a]).toBe(cells[b]!);
expect(findPath(cells, d.rows, d.cols, a, b)).not.toBeNull();
cells[a] = cells[b] = null;
}
expect(cells.every((c) => c === null)).toBe(true);
}
expect(slowest).toBeLessThan(100);
}
});
test('카운트다운에는 판을 안 보여 주고, 수도 못 둬요', () => {
const s = make(['A', 'B']);
expect(shisen.view(s, 'A').board).toBeNull();
expect(shisen.view(s, null).board).toBeNull();
expect(reason(s, 'A', { type: 'hint' }, T0 + 100)).toContain('곧 시작');
checkNoLeak(shisen, s, 'A', s.order);
const v = shisen.view(started(), 'A').board!;
expect(v.cells).toEqual(started().puzzle.cells);
expect([v.rows, v.cols, v.hint, v.shuffles, v.hints]).toEqual([8, 14, null, 0, 0]);
});
});
describe('잇는 길(findPath)', () => {
// 4×5 board; '..' empty.
const rows = 4;
const cols = 5;
test('곧게·한 번·두 번 꺾기, 판 밖 테두리로 돌기, 세 번 꺾여야 하면 안 됨', () => {
let c = grid(['1m....1m..', '..2m......', '..........', '..........']);
expect(findPath(c, rows, cols, 0, 3)).toEqual([
[0, 0],
[0, 3],
]);
// Blocked straight line → over the top margin (two turns).
c = grid(['1m2m1m....', '..........', '..........', '..........']);
expect(findPath(c, rows, cols, 0, 2)).toEqual([
[0, 0],
[-1, 0],
[-1, 2],
[0, 2],
]);
// One turn.
c = grid(['1m........', '..........', '........1m', '..........']);
expect(findPath(c, rows, cols, 0, 14)!.length).toBe(3);
// Needs three turns: 1m at (1,1) boxed on three sides, the other 1m at (3,4) behind a wall.
c = grid(['..3m3m3m..', '3m1m..3m..', '..3m3m3m3m', '3m3m3m3m1m']);
expect(findPath(c, rows, cols, 6, 19)).toBeNull();
expect(findPath(c, rows, cols, 6, 6)).toBeNull();
});
test('reachable와 findPath가 늘 같은 답', () => {
let mismatch = 0;
for (let k = 1; k <= 20; k++) {
const r = SeededRng.fromSeed(seedN(k));
const d = makeDeal(r, 'normal');
const cells = d.cells.map((x) => (r.next() < 0.5 ? null : x));
for (let a = 0; a < cells.length; a++) {
if (cells[a] == null) continue;
const set = new Set(reachable(cells, d.rows, d.cols, a));
for (let b = 0; b < cells.length; b++) if (b !== a && cells[b] != null && set.has(b) !== (findPath(cells, d.rows, d.cols, a, b) !== null)) mismatch++;
}
}
expect(mismatch).toBe(0);
});
});
describe('패 없애기·힌트·섞기', () => {
test('이어지는 같은 패를 고르면 둘 다 없어지고 내 판만 바뀜, 진행 문구', () => {
let s = started();
const [a, b] = pairOf(s);
s = act(s, 'A', { type: 'pair', a, b });
expect([s.boards.A!.cells[a], s.boards.A!.cells[b]]).toEqual([null, null]);
expect(s.boards.B!.cells[a]).not.toBeNull();
expect(s.boards.A!.removed).toBe(1);
const seat = shisen.view(s, 'B').seats.find((x) => x.id === 'A')!;
expect(seat.progress).toBe(1);
expect(seat.progressText).toBe('없앤 쌍 1/56');
expect(reason(s, 'A', { type: 'pair', a, b })).toBe('빈 칸이에요.');
});
test('거절: 다른 패, 같은 칸, 두 번 넘게 꺾임, 판 밖', () => {
const s = started();
const c = s.boards.A!.cells;
const other = c.findIndex((k) => k !== c[0]);
expect(reason(s, 'A', { type: 'pair', a: 0, b: other })).toBe('같은 패가 아니에요.');
expect(reason(s, 'A', { type: 'pair', a: 0, b: 0 })).toBe('서로 다른 두 패를 골라 주세요.');
expect(reason(s, 'A', { type: 'pair', a: 0, b: 130 })).toBe('판 밖의 칸이에요.');
// A full board: two inner tiles of the same kind are boxed in.
const inner = c.findIndex((k, i) => i > 14 && i % 14 > 0 && i % 14 < 13 && i < 98 && c.some((x, j) => j !== i && x === k && j > 14 && j % 14 > 0 && j % 14 < 13 && j < 98 && Math.abs(j - i) > 14));
const mate = c.findIndex((x, j) => j !== inner && x === c[inner] && j > 14 && j % 14 > 0 && j % 14 < 13 && j < 98 && Math.abs(j - inner) > 14);
expect(reason(s, 'A', { type: 'pair', a: inner, b: mate })).toBe('두 번 넘게 꺾여야 이어져요.');
});
test('힌트: 이어지는 한 쌍을 보여 주고 횟수를 셈, 보이는 동안은 또 못 씀, 그 패를 없애면 사라짐, 끈 방에서는 못 씀', () => {
let s = started();
s = act(s, 'A', { type: 'hint' });
const h = s.boards.A!.hint!;
expect(h).not.toBeNull();
expect(s.boards.A!.cells[h[0]]).toBe(s.boards.A!.cells[h[1]]!);
expect(findPath(s.boards.A!.cells, 8, 14, h[0], h[1])).not.toBeNull();
expect(shisen.view(s, 'A').board!.hint).toEqual(h);
expect(shisen.view(s, 'A').board!.hints).toBe(1);
expect(reason(s, 'A', { type: 'hint' })).toBe('이미 힌트가 보여요.');
s = act(s, 'A', { type: 'pair', a: h[0], b: h[1] });
expect(s.boards.A!.hint).toBeNull();
expect(shisen.view(s, 'A').seats[0]!.extra).toBe(' · 힌트 1번');
expect(reason(started(['A'], { hints: false }), 'A', { type: 'hint' })).toBe('힌트를 쓰지 않는 방이에요.');
});
test('이을 쌍이 없어지면 남은 패를 같은 칸에 저절로 섞고(풀리게), 섞기 횟수를 셈', () => {
// 2×2 block X Y / Y X (no pair goes) and a Z pair in the corner.
let s = withCells(started(['A', 'B']), 4, 6, grid(['5z5z........', '....1m2p....', '....2p1m....', '............']));
expect(reason(s, 'A', { type: 'pair', a: 8, b: 15 })).toBe('두 번 넘게 꺾여야 이어져요.');
s = act(s, 'A', { type: 'hint' });
expect(s.boards.A!.hint).toEqual([0, 1]);
const r = shisen.apply(s, 'A', { type: 'pair', a: 0, b: 1 }, { rng: rng(), now: START + 2000 });
s = r.state;
const b = s.boards.A!;
expect(r.events.map((e) => e.type)).toContain('shuffle');
expect(b.shuffles).toBe(1);
expect(b.hint).toBeNull();
expect(b.cells.flatMap((k, i) => (k ? [i] : [])).sort((x, y) => x - y)).toEqual([8, 9, 14, 15]);
expect(b.cells.filter((k) => k === '1m')).toHaveLength(2);
expect(findPair(b.cells, 4, 6)).not.toBeNull();
// B's board is untouched.
expect(s.boards.B!.cells[0]).toBe('5z');
s = clearAll(s, 'A', START + 3000);
expect(s.status.A).toBe('solved');
expect(shisen.view(s, 'A').seats[0]!.extra).toBe(' · 섞기 1번 · 힌트 1번');
});
test('reshuffle: 같은 칸·같은 패, 언제나 풀림', () => {
for (let k = 1; k <= 50; k++) {
const r = SeededRng.fromSeed(seedN(k));
const d = makeDeal(r, 'large');
const cells = [...d.cells];
for (const [a, b] of d.solution.slice(0, k % 60)) cells[a] = cells[b] = null;
const next = reshuffle(r, d.rows, d.cols, cells);
expect(next.map((x) => x !== null)).toEqual(cells.map((x) => x !== null));
expect([...next].filter(Boolean).sort()).toEqual([...cells].filter(Boolean).sort());
// Clearable by construction, so at least one pair goes right away.
expect(findPair(next, d.rows, d.cols)).not.toBeNull();
}
});
test('다 없애면 다 풂 → 혼자면 바로 끝, 걸린 시간 요약', () => {
let s = started(['A'], { size: 'small' });
s = clearAll(s);
expect(s.status.A).toBe('solved');
expect(s.phase).toBe('ended');
expect(s.boards.A!.cells.every((c) => c === null)).toBe(true);
expect(s.final!.summary).toMatch(/^다 풀었어요! 걸린 시간 /);
expect(shisen.result(s)!.scoreText!.A).toMatch(/^다 풀었어요 · /);
expect(shisen.result(s)!.scores!.A).toBe(36);
});
});
describe('순위·끝', () => {
test('기본은 보통 14×8 · 힌트 켬 · 제한 시간 15분', () => {
expect(shisen.defaultOptions).toEqual({ size: 'normal', hints: true, timeLimitSec: 900 });
expect(make().endsAt).toBe(START + 900_000);
});
test('먼저 다 푼 사람 > 다 못 푼 사람(없앤 쌍 많은 순, 같으면 같은 순위), 나간 사람 맨 아래', () => {
let s = started(['A', 'B', 'C', 'D'], { size: 'small' });
for (const p of ['B', 'C']) {
const [a, b] = pairOf(s, p);
s = act(s, p, { type: 'pair', a, b });
}
s = act(s, 'B', { type: 'stop' });
s = act(s, 'D', { type: 'leave' } as A);
s = act(s, 'C', { type: 'stop' });
s = clearAll(s, 'A', START + 2000);
expect(s.phase).toBe('ended');
const r = s.final!.ranking;
expect(r.map((x) => x.id)).toEqual(['A', 'B', 'C', 'D']);
expect(r.map((x) => x.rank)).toEqual([1, 2, 2, 4]);
expect(s.final!.summary).toBe('가장 먼저 다 푼 사람이 이겼어요');
expect(shisen.result(s)!.scoreText!.B).toBe('없앤 쌍 1/36 · 포기');
});
test('제한 시간: 마감 tick으로 끝, 마감 뒤 거절, 아무도 못 풀면 많이 없앤 사람이 이김', () => {
let s = started(['A', 'B'], { timeLimitSec: 300 });
const [a, b] = pairOf(s);
s = act(s, 'A', { type: 'pair', a, b });
const end = START + 300_000;
expect(shisen.deadline!(s)).toBe(end);
expect(reason(s, 'B', { type: 'pair', a, b }, end)).toBe('시간이 다 됐어요.');
s = shisen.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('시간이 다 됐어요. 아무도 다 풀지 못했어요. 가장 많이 푼 사람이 이겼어요');
});
test('무제한: 끊긴 사람은 tick 한 번으로 포기 처리, 모두 끝나면 끝', () => {
let s = started(['A', 'B'], { timeLimitSec: null });
expect(shisen.deadline!(s)).toBeNull();
s = shisen.apply(s, 'B', { type: 'tick' }, { rng: rng(), now: START + 70_000 }).state;
expect(s.status.B).toBe('done');
s = shisen.apply(s, 'B', { type: 'tick' }, { rng: rng(), now: START + 71_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'], { size: 'large' });
for (let k = 0; k < 12; k++) {
const [a, b] = pairOf(s);
s = act(s, 'A', { type: 'pair', a, b }, START + 100 + k);
}
const [a, b] = pairOf(s);
expect(reason(s, 'A', { type: 'pair', a, b }, START + 200)).toBe('조금 천천히 해 주세요.');
expect(reason(s, 'A', { type: 'pair', a, b }, START + 1200)).toBe('ok');
});
});
describe('무작위 대국', () => {
test('1·2·5·8명, 세 크기: 유출·JSON·결정성', () => {
for (let k = 1; k <= playoutSeeds(60); k++) {
for (const n of [1, 2, 5, 8]) {
const size = (['small', 'normal', 'large'] as const)[k % 3]!;
const players = Array.from({ length: n }, (_, i) => `p${i}`);
const options = shisen.optionsSchema.parse({ size, hints: k % 2 === 0, timeLimitSec: k % 2 ? null : 300 });
const a = randomPlayout(shisen, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000 });
expect(a.finished).toBe(true);
const b = randomPlayout(shisen, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000 });
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
}
}
});
});

View File

@@ -0,0 +1,74 @@
/** 솔리테어 computers (docs/games/solitaire.md §13): never refused, always finish (no endless loops), stronger levels do better. */
import { describe, expect, test } from 'bun:test';
import { seedN } from '@bg/engine';
import { liveBotPlayout } from '../bots/live-playout';
import { chooseMove, scoreMove, solitaireBot } from './bot';
import { solitaire, type SolitaireBoardView, type SolitaireOptions, type SolitaireState } from './index';
const isBot = (p: string) => p.startsWith('bot:');
const MODES: Partial<SolitaireOptions>[] = [{ mode: 'klondike', draw: 1 }, { mode: 'klondike', draw: 3 }, { mode: 'freecell' }, { mode: 'spider', suits: 1 }, { mode: 'spider', suits: 4 }];
describe('solitaire · 한 판 전체', () => {
test('사람(가만히) + 컴퓨터, 컴퓨터끼리만(무제한): 거절 0, 모두 끝까지, 빠른 판단', () => {
for (const [k, o] of MODES.entries()) {
for (const humans of [1, 0]) {
const n = 2 + k % 2;
const players = Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i + 1}:s${k}${i}`));
const r = liveBotPlayout(solitaire, solitaireBot, {
players,
options: solitaire.optionsSchema.parse({ ...o, timeLimitSec: humans ? 900 : null }),
seed: seedN(k * 10 + humans),
isBot,
levelOf: (p) => 1 + ((p.length * 7 + k * 13) % 60),
});
expect(r.finished).toBe(true);
expect(r.rejected).toEqual([]);
expect(r.maxBotMs).toBeLessThan(50);
const s = r.state as SolitaireState;
if (!humans) for (const p of players) expect(['solved', 'done']).toContain(s.status[p]!);
}
}
});
test('강한 컴퓨터가 약한 컴퓨터보다 평균적으로 더 많이 올려요(같은 패)', () => {
const total = { easy: 0, hard: 0 };
for (let k = 0; k < 12; k++) {
const r = liveBotPlayout(solitaire, solitaireBot, {
players: ['bot:1:easy', 'bot:2:hard'],
options: solitaire.optionsSchema.parse(MODES[k % MODES.length]),
seed: seedN(700 + k),
isBot,
levelOf: (p) => (p.endsWith('easy') ? 3 : 58),
});
const s = r.state as SolitaireState;
const prog = (p: string) => solitaire.view(s, p).seats.find((x) => x.id === p)!.progress;
total.easy += prog('bot:1:easy');
total.hard += prog('bot:2:hard');
}
expect(total.hard).toBeGreaterThan(total.easy);
});
test('먼저 파운데이션, 다음 뒤집힌 카드를 여는 수; 같은 자리에서 같은 수는 두 번 하지 않아요', () => {
const v: SolitaireBoardView = {
mode: 'klondike',
draw: 1,
t: [[null, '9H'], ['TS'], ['AD'], [], [], [], []],
stock: 3,
waste: [],
cells: [],
f: ['', '', '', ''],
done: '',
canUndo: false,
undos: 0,
};
expect(scoreMove(v, { type: 'move', from: 't2', n: 1, to: 'f' })).toBeGreaterThan(scoreMove(v, { type: 'move', from: 't0', n: 1, to: 't1' }));
expect(scoreMove(v, { type: 'move', from: 't0', n: 1, to: 't1' })).toBeGreaterThan(scoreMove(v, { type: 'draw' }));
const mem = {};
expect(chooseMove(v, 0, () => 0, mem)).toEqual({ type: 'move', from: 't2', n: 1, to: 'f' });
expect(chooseMove(v, 0, () => 0, mem)).toEqual({ type: 'move', from: 't0', n: 1, to: 't1' });
expect(chooseMove(v, 0, () => 0, mem)).toEqual({ type: 'draw' });
// Nothing left to try on this screen → give up.
expect(chooseMove({ ...v, stock: 0 }, 0, () => 0, { tried: {} })).not.toEqual({ type: 'stop' });
expect(chooseMove({ ...v, t: [['KS'], [], [], [], [], [], []], stock: 0 }, 0, () => 0, {})).toEqual({ type: 'stop' });
});
});

View File

@@ -0,0 +1,179 @@
/**
* 솔리테어 computers (docs/games/solitaire.md §13). They only read their own screen (face-up cards, the stock count).
* Each turn they score every legal move: to a foundation first, then moves that turn up a face-down card, empty a
* column or build onto the same suit (Spider); Klondike draws and Spider deals when nothing better is left.
* They never try the same move twice from the same position, give up (`stop`) after two whole stock cycles without
* progress, when nothing is left to try, or after a move budget, so a game never loops.
* Time per move: about 4 s at level 1 … 1 s at level 60; a weak computer sometimes overlooks the best move.
*/
import { raceBot } from '../race/bot';
import { foundationSlot, isRun, legalOn, playMove, rankOf, suitOf, type SolitaireBoard, type SolitaireBoardView, type SolitaireMove } from './index';
type V = SolitaireBoardView;
export type SolitaireBotMove = SolitaireMove | { type: 'stop' };
/** Moves a computer makes before it gives up. */
export const MOVE_BUDGET = 1200;
function hash(s: string): string {
let h = 0x811c9dc5;
for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 0x01000193);
return (h >>> 0).toString(36);
}
const cols = (v: V) => v.t.map((c) => c.map((x) => x ?? '?').join('')).join(',');
const position = (v: V) => hash(`${cols(v)}|${v.stock}|${v.waste.join('')}|${v.cells.join('.')}|${v.f.join('.')}|${v.done}`);
const moveKey = (m: SolitaireMove) => (m.type === 'move' ? `${m.from}>${m.to}:${m.n}` : m.type);
/** How good a move looks (≤ 0 = not worth it). */
export function scoreMove(v: V, m: SolitaireMove): number {
if (m.type !== 'move') return m.type === 'draw' || m.type === 'deal' ? 1 : -1;
if (m.to[0] === 'f') return 100;
if (m.from[0] === 'f') return -1;
if (m.from === 'w') return 15;
if (m.from[0] === 'c') return 30;
const col = v.t[Number(m.from.slice(1))]!;
const s = col.length - m.n;
const card = col[s]!;
const below = s > 0 ? col[s - 1] : undefined;
const exposesF = !!below && foundationSlot(v.f, below) >= 0;
// A free cell is worth it when it frees a card for the foundation (a careful player also sees one move further).
if (m.to[0] === 'c') return exposesF ? 40 : rankOf(card) === 13 || below === undefined ? -1 : 0;
const dest = v.t[Number(m.to.slice(1))]!;
if (!dest.length && s === 0) return -1;
let sc: number;
if (below === null) sc = 60 + col.filter((x) => x === null).length;
else if (below === undefined) sc = v.mode !== 'klondike' ? 25 : kingWaiting(v) ? 20 : -1;
else if (exposesF) sc = 45;
else if (isRun(v.mode, [below, card])) return -1;
else sc = 8;
if (!dest.length && v.mode !== 'klondike') sc -= 15;
if (v.mode === 'spider' && dest.length && suitOf(dest.at(-1)!) === suitOf(card)) sc += 30;
if (v.mode === 'freecell' && dest.length) sc += m.n;
return sc;
}
/** Klondike: a king somewhere that an empty column would help (on the waste, or with cards under it). */
function kingWaiting(v: V): boolean {
if (v.waste.length && rankOf(v.waste.at(-1)!) === 13) return true;
return v.t.some((c) => c.some((x, k) => k > 0 && !!x && rankOf(x) === 13));
}
/** The screen after a move, worked out from what is visible ('??' stands for a card that is still face down). */
export function afterMove(v: V, m: SolitaireMove): V {
const b: SolitaireBoard = {
t: v.t.map((c) => c.map((x) => x ?? '??')),
down: v.t.map((c) => c.filter((x) => x === null).length),
stock: Array<string>(v.stock).fill('??'),
waste: [...v.waste],
cells: [...v.cells],
f: [...v.f],
done: v.done,
hist: [],
undos: 0,
};
const n = playMove({ mode: v.mode, deck: '' }, b, m, v.draw, false);
return { ...v, t: n.t.map((c) => c.map((x) => (x === '??' ? null : x))), stock: n.stock.length, waste: n.waste, cells: n.cells, f: n.f, done: n.done };
}
/** Score plus half of the best follow-up it opens up (a careful player looks one move ahead). */
function lookAhead(v: V, m: SolitaireMove, pos: string): number {
const base = scoreMove(v, m);
if (base < 0 || m.type !== 'move') return base;
const next = afterMove(v, m);
let best = 0;
for (const m2 of legalOn(next)) {
if (m2.type !== 'move') continue;
const s2 = scoreMove(next, m2);
if (s2 > best && position(afterMove(next, m2)) !== pos) best = s2;
}
return base === 0 ? (best >= 40 ? best / 2 : 0) : base + best / 2;
}
const fTotal = (f: string[]) => f.reduce((n, c) => n + (c ? rankOf(c) : 0), 0);
/**
* FreeCell shows every card, so the computer can dig: a short depth-first search (at most `nodes` positions) for moves
* that lead to one more card on a foundation. Returns that path, or null.
*/
export function digPlan(v: V, nodes: number): SolitaireMove[] | null {
const key = (x: V) => `${x.t.map((c) => c.join('')).sort().join(',')}|${[...x.cells].sort().join('')}|${x.f.join('')}`;
const goal = fTotal(v.f);
const seen = new Set<string>([key(v)]);
const stack: { v: V; path: SolitaireMove[] }[] = [{ v, path: [] }];
while (stack.length && seen.size < nodes) {
const { v: x, path } = stack.pop()!;
if (path.length >= 10) continue;
const next = legalOn(x)
.filter((m) => m.type === 'move' && scoreMove(x, m) >= 0)
.map((m) => ({ m, s: scoreMove(x, m) }))
.sort((a, b) => a.s - b.s);
for (const { m } of next) {
const y = afterMove(x, m);
if (fTotal(y.f) > goal) return [...path, m];
const k = key(y);
if (seen.has(k)) continue;
seen.add(k);
stack.push({ v: y, path: [...path, m] });
}
}
return null;
}
interface Memory {
plan?: SolitaireMove[];
tried?: Record<string, 1>;
n?: number;
idle?: number;
lastSig?: string;
}
/** The next move for this screen, or `stop`. `miss` = chance of overlooking the best move. */
export function chooseMove(v: V, miss: number, random: () => number, mem: Memory, careful = false): SolitaireBotMove {
const tried = (mem.tried ??= {});
mem.n = (mem.n ?? 0) + 1;
if (mem.n > MOVE_BUDGET) return { type: 'stop' };
const pos = position(v);
const legal = legalOn(v).filter((m) => !tried[`${pos}/${moveKey(m)}`]);
const scored = legal.map((m) => ({ m, s: (careful ? lookAhead(v, m, pos) : scoreMove(v, m)) + random() * 0.5 })).filter((x) => x.s > 0.5);
scored.sort((a, b) => b.s - a.s);
// Spider with an empty column: fill it with something so dealing becomes possible again.
if (!scored.length && v.mode === 'spider' && v.stock > 0) {
const fill = legal.find((m) => m.type === 'move' && v.t[Number(m.to.slice(1))]?.length === 0 && v.t[Number(m.from.slice(1))]!.length > m.n);
if (fill) scored.push({ m: fill, s: 1 });
}
// FreeCell: with nothing for the foundation right now, follow (or make) a short plan that digs one out.
if (v.mode === 'freecell' && !(scored[0]?.m.type === 'move' && (scored[0].m as { to: string }).to === 'f')) {
const next = mem.plan?.[0];
if (next && legal.some((m) => moveKey(m) === moveKey(next))) {
mem.plan = mem.plan!.slice(1);
tried[`${pos}/${moveKey(next)}`] = 1;
return next;
}
const plan = digPlan(v, careful ? 400 : 60);
if (plan) {
mem.plan = plan.slice(1);
tried[`${pos}/${moveKey(plan[0]!)}`] = 1;
return plan[0]!;
}
mem.plan = [];
}
if (!scored.length) return { type: 'stop' };
let pick = scored[0]!.m;
if (scored.length > 1 && scored[0]!.s > 2 && random() < miss) pick = scored[1]!.m;
if (pick.type === 'draw' && v.stock === 0) {
// Turning the waste over: two whole stock cycles without any change on the table → give up.
const sig = hash(`${cols(v)}|${v.f.join('.')}`);
mem.idle = sig === mem.lastSig ? (mem.idle ?? 0) + 1 : 0;
mem.lastSig = sig;
if (mem.idle >= 2) return { type: 'stop' };
}
tried[`${pos}/${moveKey(pick)}`] = 1;
return pick;
}
export const solitaireBot = raceBot<V, SolitaireBotMove>((v, skill, random, memory) => {
const step = 4000 - 3000 * skill;
const move = chooseMove(v, 0.4 * (1 - skill), random, memory as Memory, random() < skill);
const quick = move.type === 'draw' || move.type === 'deal' || move.type === 'stop';
return { move, ms: step * (quick ? 0.5 : 0.6 + 0.8 * random()) };
});

View File

@@ -0,0 +1,396 @@
/**
* 솔리테어 (docs/games/solitaire.md): Windows-style 클론다이크 / 프리셀 / 스파이더. Everyone gets the same deal and
* plays it on their own copy (race frame, ../race). Face-down tableau cards and the stock never reach the screen.
* The rule checks work on a `Table` (what a player can see), so the screen and the computer use the same rules.
*/
import { z } from 'zod';
import type { Rng } from '@bg/engine';
import { lit, makeRaceGame, timeLimitOption, type RaceState, type RaceView } from '../race';
export { COUNTDOWN_MS, formatElapsed } from '../race';
export type Mode = 'klondike' | 'freecell' | 'spider';
export const MODE_NAME: Record<Mode, string> = { klondike: '클론다이크', freecell: '프리셀', spider: '스파이더' };
export const TIME_CHOICES = [600, 900, 1200, 1800] as const;
/** Snapshots kept for 되돌리기. */
export const MAX_UNDO = 50;
export const solitaireOptionsSchema = z.object({
mode: lit<Mode>('klondike', 'freecell', 'spider').default('klondike').meta({ title: '종류', labels: MODE_NAME }),
draw: lit(1, 3).default(1).meta({ title: '한 번에 넘기는 카드(클론다이크)', labels: { 1: '1장', 3: '3장' } }),
suits: lit(1, 2, 4).default(1).meta({ title: '무늬 수(스파이더)', labels: { 1: '1가지', 2: '2가지', 4: '4가지' } }),
timeLimitSec: timeLimitOption([...TIME_CHOICES], 900),
});
export type SolitaireOptions = z.infer<typeof solitaireOptionsSchema>;
const FROM = /^(t[0-9]|w|c[0-3]|f[0-3])$/;
const TO = /^(t[0-9]|c[0-3]|f[0-3]?)$/;
const moveSchemas = [
z.object({ type: z.literal('move'), from: z.string().regex(FROM), n: z.number().int().min(1).max(13), to: z.string().regex(TO) }),
z.object({ type: z.literal('draw') }),
z.object({ type: z.literal('deal') }),
z.object({ type: z.literal('auto') }),
z.object({ type: z.literal('undo') }),
] as const;
export type SolitaireMove = { type: 'move'; from: string; n: number; to: string } | { type: 'draw' } | { type: 'deal' } | { type: 'auto' } | { type: 'undo' };
/** Cards are "AS", "TD", … (rank 'A23456789TJQK' + suit 'SHDC'), like the PlayingCard component. */
export const RANKS = 'A23456789TJQK';
export const rankOf = (c: string): number => RANKS.indexOf(c[0]!) + 1;
export const suitOf = (c: string): string => c[1]!;
export const isRed = (c: string): boolean => c[1] === 'H' || c[1] === 'D';
const SUIT_KO: Record<string, string> = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' };
export interface SolitairePuzzle {
mode: Mode;
/** The shuffled deck, 2 characters per card (Spider: 104 cards, duplicates allowed). */
deck: string;
}
export interface SolitaireBoard {
/** Tableau columns, bottom first. */
t: string[][];
/** Face-down cards at the bottom of each column. */
down: number[];
/** Klondike / Spider stock, top last. */
stock: string[];
/** Klondike waste, top last. */
waste: string[];
/** FreeCell free cells ('' empty); [] in the other modes. */
cells: string[];
/** Foundation tops ('' empty); [] in Spider. */
f: string[];
/** Spider: the suit of each completed K→A run removed so far. */
done: string;
/** Earlier boards (encoded), newest last, at most MAX_UNDO. */
hist: string[];
undos: number;
}
/** What a player can see of a board; the rules check moves on this. Face-down cards are null, the stock only a count. */
export interface Table {
mode: Mode;
draw: 1 | 3;
t: (string | null)[][];
stock: number;
waste: string[];
cells: string[];
f: string[];
done: string;
canUndo: boolean;
}
export interface SolitaireBoardView extends Table {
undos: number;
}
export type SolitaireState = RaceState<SolitairePuzzle, SolitaireBoard, SolitaireOptions>;
export type SolitaireView = RaceView<SolitaireBoardView, SolitaireOptions>;
const chunk2 = (s: string): string[] => Array.from({ length: s.length / 2 }, (_, i) => s.slice(i * 2, i * 2 + 2));
export function makeDeck(rng: Rng, o: Pick<SolitaireOptions, 'mode' | 'suits'>): SolitairePuzzle {
const suits = o.mode === 'spider' ? ({ 1: ['S'], 2: ['S', 'H'], 4: ['S', 'H', 'D', 'C'] } as const)[o.suits] : (['S', 'H', 'D', 'C'] as const);
const copies = o.mode === 'spider' ? 8 / suits.length : 1;
const cards: string[] = [];
for (let k = 0; k < copies; k++) for (const s of suits) for (const r of RANKS) cards.push(r + s);
return { mode: o.mode, deck: rng.shuffle(cards).join('') };
}
export function dealBoard(p: SolitairePuzzle): SolitaireBoard {
const cards = chunk2(p.deck);
const b: SolitaireBoard = { t: [], down: [], stock: [], waste: [], cells: [], f: [], done: '', hist: [], undos: 0 };
if (p.mode === 'klondike') {
let k = 0;
for (let i = 0; i < 7; i++) {
b.t.push(cards.slice(k, k + i + 1));
b.down.push(i);
k += i + 1;
}
b.stock = cards.slice(k);
b.f = ['', '', '', ''];
} else {
const cols = p.mode === 'freecell' ? 8 : 10;
const dealt = p.mode === 'freecell' ? 52 : 54;
b.t = Array.from({ length: cols }, () => []);
for (let k = 0; k < dealt; k++) b.t[k % cols]!.push(cards[k]!);
b.down = b.t.map((c) => (p.mode === 'spider' ? c.length - 1 : 0));
b.stock = cards.slice(dealt);
if (p.mode === 'freecell') {
b.cells = ['', '', '', ''];
b.f = ['', '', '', ''];
}
}
return b;
}
/** One board (without history) as a short string, for 되돌리기. */
export function encodeBoard(b: SolitaireBoard): string {
const slots = (xs: string[]) => xs.map((c) => c || '--').join('');
return [b.t.map((c) => c.join('')).join(','), b.down.join(','), b.stock.join(''), b.waste.join(''), slots(b.cells), slots(b.f), b.done].join('|');
}
function decodeBoard(s: string, hist: string[], undos: number): SolitaireBoard {
const [t, down, stock, waste, cells, f, done] = s.split('|') as [string, string, string, string, string, string, string];
const slots = (x: string) => chunk2(x).map((c) => (c === '--' ? '' : c));
return { t: t.split(',').map(chunk2), down: down.split(',').map(Number), stock: chunk2(stock), waste: chunk2(waste), cells: slots(cells), f: slots(f), done, hist, undos };
}
export function tableOf(p: SolitairePuzzle, b: SolitaireBoard, draw: 1 | 3): Table {
return {
mode: p.mode,
draw,
t: b.t.map((c, i) => c.map((x, k) => (k < b.down[i]! ? null : x))),
stock: b.stock.length,
waste: b.waste,
cells: b.cells,
f: b.f,
done: b.done,
canUndo: b.hist.length > 0,
};
}
type Pile = { kind: 't' | 'c' | 'f'; i: number } | { kind: 'w' } | { kind: 'f'; i: null };
function parsePile(id: string): Pile {
if (id === 'w') return { kind: 'w' };
if (id === 'f') return { kind: 'f', i: null };
return { kind: id[0] as 't' | 'c' | 'f', i: Number(id.slice(1)) };
}
function pileExists(tb: Table, p: Pile): boolean {
if (p.kind === 't') return p.i < tb.t.length;
if (p.kind === 'w') return tb.mode === 'klondike';
if (p.kind === 'c') return tb.mode === 'freecell';
return tb.mode !== 'spider';
}
/** The foundation slot a card goes to, or -1. */
export function foundationSlot(f: string[], card: string): number {
const r = rankOf(card);
if (r === 1) return f.indexOf('');
return f.findIndex((top) => top !== '' && suitOf(top) === suitOf(card) && rankOf(top) === r - 1);
}
/** Cards (bottom first) form a run that moves as a unit: Spider same suit, others alternating colours; each one lower. */
export function isRun(mode: Mode, cards: (string | null)[]): boolean {
for (let k = 1; k < cards.length; k++) {
const a = cards[k - 1];
const b = cards[k];
if (!a || !b || rankOf(a) !== rankOf(b) + 1) return false;
if (mode === 'spider' ? suitOf(a) !== suitOf(b) : isRed(a) === isRed(b)) return false;
}
return true;
}
/** How many cards FreeCell moves at once: (free cells + 1) × 2^(empty columns, not counting the target). */
export function freecellCapacity(tb: Table, toEmptyColumn: boolean): number {
const free = tb.cells.filter((c) => !c).length;
const empty = tb.t.filter((c) => c.length === 0).length - (toEmptyColumn ? 1 : 0);
return (free + 1) * 2 ** Math.max(0, empty);
}
/** Cards a move picks up, or a reason it cannot. */
function pickUp(tb: Table, from: Pile, n: number): string[] | string {
if (from.kind === 't') {
const col = tb.t[from.i]!;
if (!col.length) return '빈 줄이에요.';
if (n > col.length) return '옮길 카드가 없어요.';
const cards = col.slice(col.length - n);
if (cards.includes(null)) return '뒤집힌 카드는 옮길 수 없어요.';
if (!isRun(tb.mode, cards)) return tb.mode === 'spider' ? '같은 무늬로 이어진 카드만 한꺼번에 옮길 수 있어요.' : '색이 번갈아 하나씩 작아지게 이어진 카드만 한꺼번에 옮길 수 있어요.';
return cards as string[];
}
if (n !== 1) return '한 장씩만 옮길 수 있어요.';
if (from.kind === 'w') return tb.waste.length ? [tb.waste.at(-1)!] : '넘긴 카드가 없어요.';
if (from.kind === 'c') return tb.cells[from.i] ? [tb.cells[from.i]!] : '빈 칸이에요.';
if (tb.mode !== 'klondike') return '올린 카드는 내릴 수 없어요.';
return tb.f[from.i!] ? [tb.f[from.i!]!] : '빈 자리예요.';
}
/** Korean reason the move is refused on this table, or null. */
export function moveProblem(tb: Table, m: SolitaireMove): string | null {
if (m.type === 'draw') {
if (tb.mode !== 'klondike') return '클론다이크에서만 카드를 넘겨요.';
return tb.stock === 0 && tb.waste.length === 0 ? '넘길 카드가 없어요.' : null;
}
if (m.type === 'deal') {
if (tb.mode !== 'spider') return '스파이더에서만 카드를 나눠요.';
if (tb.stock === 0) return '더 나눌 카드가 없어요.';
const cards = tb.t.reduce((n, c) => n + c.length, 0);
if (cards >= tb.t.length && tb.t.some((c) => !c.length)) return '빈 줄이 있으면 나눌 수 없어요. 먼저 빈 줄을 채워 주세요.';
return null;
}
if (m.type === 'auto') {
if (tb.mode === 'spider') return '스파이더에는 자동 정리가 없어요.';
return canAuto(tb) ? null : '바로 올릴 수 있는 카드가 없어요.';
}
if (m.type === 'undo') return tb.canUndo ? null : '되돌릴 수가 없어요.';
const from = parsePile(m.from);
const to = parsePile(m.to);
if (!pileExists(tb, from) || !pileExists(tb, to)) return '그런 자리는 없어요.';
if (m.from === m.to) return '같은 자리예요.';
if (from.kind === 'f' && to.kind === 'f') return '이미 올린 카드예요.';
const got = pickUp(tb, from, m.n);
if (typeof got === 'string') return got;
const card = got[0]!;
if (to.kind === 'f') {
if (m.n !== 1) return '한 장씩 올려요.';
if (to.i === null) return foundationSlot(tb.f, card) >= 0 ? null : rankOf(card) === 1 ? '빈 자리가 없어요.' : '이 카드는 아직 올릴 수 없어요. 같은 무늬로 A부터 차례대로 올려요.';
const top = tb.f[to.i]!;
if (!top) return rankOf(card) === 1 ? null : '빈 자리에는 A부터 올려요.';
return suitOf(top) === suitOf(card) && rankOf(top) === rankOf(card) - 1 ? null : '같은 무늬로 A부터 차례대로 올려요.';
}
if (to.kind === 'c') {
if (m.n !== 1) return '빈 칸에는 한 장만 놓아요.';
return tb.cells[to.i] ? '빈 칸에만 놓을 수 있어요.' : null;
}
if (to.kind !== 't') return '그런 자리는 없어요.';
const dest = tb.t[to.i]!;
if (!dest.length) {
if (tb.mode === 'klondike' && rankOf(card) !== 13) return '빈 줄에는 K만 놓을 수 있어요.';
} else {
const top = dest.at(-1)!;
if (!top) return '뒤집힌 카드 위에는 놓을 수 없어요.';
if (rankOf(top) !== rankOf(card) + 1) return tb.mode === 'spider' ? '숫자가 하나 큰 카드 위에만 놓을 수 있어요.' : '색이 다르고 숫자가 하나 큰 카드 위에만 놓을 수 있어요.';
if (tb.mode !== 'spider' && isRed(top) === isRed(card)) return '색이 다르고 숫자가 하나 큰 카드 위에만 놓을 수 있어요.';
}
if (tb.mode === 'freecell' && m.n > 1) {
const cap = freecellCapacity(tb, !dest.length);
if (m.n > cap) return `빈 칸과 빈 줄로는 한 번에 ${cap}장까지 옮길 수 있어요.`;
}
return null;
}
/** Some visible top card (waste, free cell, column) can go to a foundation now (자동 정리). */
export function canAuto(tb: Table): boolean {
return [tb.waste.at(-1), ...tb.cells, ...tb.t.map((c) => c.at(-1))].some((c) => !!c && foundationSlot(tb.f, c) >= 0);
}
/** Turns up the top card of every column that ends face down. */
function flip(b: SolitaireBoard): void {
b.down = b.down.map((d, i) => (b.t[i]!.length > 0 && d >= b.t[i]!.length ? b.t[i]!.length - 1 : Math.min(d, b.t[i]!.length)));
}
/** Spider: removes every complete face-up K→A same-suit run lying on top of a column. */
function removeRuns(b: SolitaireBoard): number {
let n = 0;
b.t.forEach((col, i) => {
if (col.length - b.down[i]! < 13) return;
const top = col.slice(col.length - 13);
if (rankOf(top[0]!) === 13 && isRun('spider', top)) {
b.t[i] = col.slice(0, col.length - 13);
b.done += suitOf(top[0]!);
n++;
}
});
return n;
}
const fCount = (f: string[]) => f.reduce((n, c) => n + (c ? rankOf(c) : 0), 0);
export const isSolved = (mode: Mode, b: Pick<SolitaireBoard, 'f' | 'done'>): boolean => (mode === 'spider' ? b.done.length === 8 : fCount(b.f) === 52);
/** The board after a move already accepted by `moveProblem`. `remember` = keep the old board for 되돌리기. */
export function playMove(p: SolitairePuzzle, b0: SolitaireBoard, m: SolitaireMove, draw: 1 | 3, remember = true): SolitaireBoard {
if (m.type === 'undo') return decodeBoard(b0.hist.at(-1)!, b0.hist.slice(0, -1), b0.undos + 1);
const b: SolitaireBoard = { ...b0, t: b0.t.map((c) => [...c]), down: [...b0.down], stock: [...b0.stock], waste: [...b0.waste], cells: [...b0.cells], f: [...b0.f] };
if (remember) b.hist = [...b0.hist.slice(-(MAX_UNDO - 1)), encodeBoard(b0)];
if (m.type === 'draw') {
if (!b.stock.length) {
b.stock = b.waste.reverse();
b.waste = [];
} else for (let k = Math.min(draw, b.stock.length); k > 0; k--) b.waste.push(b.stock.pop()!);
} else if (m.type === 'deal') {
for (let i = 0; i < b.t.length && b.stock.length; i++) b.t[i]!.push(b.stock.pop()!);
} else if (m.type === 'auto') {
for (let moved = true; moved; ) {
moved = false;
const sources: [string, string | undefined][] = [['w', b.waste.at(-1)], ...b.cells.map((c, i) => [`c${i}`, c || undefined] as [string, string | undefined]), ...b.t.map((c, i) => [`t${i}`, c.length > b.down[i]! ? c.at(-1) : undefined] as [string, string | undefined])];
for (const [from, card] of sources) {
if (!card) continue;
const slot = foundationSlot(b.f, card);
if (slot < 0) continue;
b.f[slot] = card;
if (from === 'w') b.waste.pop();
else if (from[0] === 'c') b.cells[Number(from.slice(1))] = '';
else b.t[Number(from.slice(1))]!.pop();
flip(b);
moved = true;
break;
}
}
} else {
const from = parsePile(m.from);
const to = parsePile(m.to);
let cards: string[];
if (from.kind === 't') cards = b.t[from.i]!.splice(b.t[from.i]!.length - m.n, m.n);
else if (from.kind === 'w') cards = [b.waste.pop()!];
else if (from.kind === 'c') {
cards = [b.cells[from.i]!];
b.cells[from.i] = '';
} else {
const i = from.i!;
const c = b.f[i]!;
cards = [c];
b.f[i] = rankOf(c) === 1 ? '' : RANKS[rankOf(c) - 2]! + suitOf(c);
}
if (to.kind === 'f') b.f[to.i ?? foundationSlot(b.f, cards[0]!)] = cards[0]!;
else if (to.kind === 'c') b.cells[to.i] = cards[0]!;
else if (to.kind === 't') b.t[to.i]!.push(...cards);
}
flip(b);
if (p.mode === 'spider' && removeRuns(b)) flip(b);
return b;
}
/** Candidate moves on a table (not all legal): every movable tail, waste and cell cards to every pile, and the buttons. */
export function candidateMoves(tb: Table): SolitaireMove[] {
const out: SolitaireMove[] = [];
const dests = (from: string): string[] => [
...tb.t.map((_, j) => `t${j}`).filter((d) => d !== from),
...(tb.mode !== 'spider' ? ['f'] : []),
...(tb.mode === 'freecell' && tb.cells.includes('') ? [`c${tb.cells.indexOf('')}`] : []),
];
tb.t.forEach((col, i) => {
for (let n = 1; n <= col.length && col[col.length - n] && isRun(tb.mode, col.slice(col.length - n)); n++)
for (const to of dests(`t${i}`)) if (n === 1 || to[0] === 't') out.push({ type: 'move', from: `t${i}`, n, to });
});
if (tb.waste.length) for (const to of dests('w')) out.push({ type: 'move', from: 'w', n: 1, to });
tb.cells.forEach((c, i) => {
if (c) for (const to of dests(`c${i}`)) if (to[0] !== 'c') out.push({ type: 'move', from: `c${i}`, n: 1, to });
});
if (tb.mode === 'klondike') tb.f.forEach((c, i) => c && tb.t.forEach((_, j) => out.push({ type: 'move', from: `f${i}`, n: 1, to: `t${j}` })));
out.push({ type: 'draw' }, { type: 'deal' }, { type: 'auto' }, { type: 'undo' });
return out;
}
export const legalOn = (tb: Table): SolitaireMove[] => candidateMoves(tb).filter((m) => moveProblem(tb, m) === null);
export const cardWord = (c: string): string => `${SUIT_KO[suitOf(c)]} ${c[0] === 'T' ? '10' : c[0]}`;
export const solitaire = makeRaceGame<SolitairePuzzle, SolitaireBoard, SolitaireMove, SolitaireBoardView, SolitaireOptions>({
id: 'solitaire',
nameKo: '솔리테어',
optionsSchema: solitaireOptionsSchema,
moveSchemas: moveSchemas as never,
makePuzzle: (rng, o) => makeDeck(rng, o),
startBoard: (p) => dealBoard(p),
checkMove: (p, b, m, o) => moveProblem(tableOf(p, b, o.draw), m),
applyMove(p, b, m, { options }) {
const next = playMove(p, b, m, options.draw);
return { board: next, outcome: isSolved(p.mode, next) ? 'solved' : undefined };
},
boardView(p, b, _reveal, o) {
return { ...tableOf(p, b, o.draw), undos: b.undos };
},
progress: (p, b) => (p.mode === 'spider' ? b.done.length * 13 : fCount(b.f)),
progressText: (p, b) => (p.mode === 'spider' ? `완성 ${b.done.length}/8줄` : `올린 카드 ${fCount(b.f)}/52`),
extraText: (b) => (b.undos ? ` · 되돌리기 ${b.undos}번` : ''),
legalMoves: (p, b, o) => legalOn(tableOf(p, b, o.draw)),
secrets: (p) => [p.deck],
});

View File

@@ -0,0 +1,393 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import { scoreMove } from './bot';
import {
COUNTDOWN_MS,
MAX_UNDO,
dealBoard,
encodeBoard,
freecellCapacity,
isSolved,
legalOn,
makeDeck,
moveProblem,
playMove,
solitaire,
tableOf,
type SolitaireBoard,
type SolitaireMove,
type SolitaireOptions,
type SolitairePuzzle,
type SolitaireState,
} from './index';
const T0 = 1_000_000;
const START = T0 + COUNTDOWN_MS;
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
type A = Parameters<typeof solitaire.apply>[2];
function make(players = ['A', 'B'], opts: Partial<SolitaireOptions> = {}, seed = 1): SolitaireState {
return solitaire.setup({ players, options: solitaire.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 });
}
let clock = START + 1000;
function act(s: SolitaireState, p: string, a: A, now = (clock += 100)): SolitaireState {
const v = solitaire.validate(s, p, a, { now });
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
return solitaire.apply(s, p, a, { rng: rng(), now }).state;
}
const reason = (s: SolitaireState, p: string, a: A, now = (clock += 100)) => {
const v = solitaire.validate(s, p, a, { now });
return v.ok ? 'ok' : v.reason;
};
const started = (players?: string[], opts?: Partial<SolitaireOptions>, seed?: number) => solitaire.apply(make(players, opts, seed), 'A', { type: 'tick' }, { rng: rng(), now: START }).state;
const mv = (from: string, to: string, n = 1): SolitaireMove => ({ type: 'move', from, n, to });
/** A hand-made board: columns as space-separated cards, `^` marks the first face-up card (else only the top is up). */
function board(p: Partial<SolitaireBoard> & { cols: string[] }): SolitaireBoard {
const t: string[][] = [];
const down: number[] = [];
for (const c of p.cols) {
const parts = c.split(' ').filter(Boolean);
const up = parts.findIndex((x) => x.startsWith('^'));
const cards = parts.map((x) => x.replace('^', ''));
t.push(cards);
down.push(up >= 0 ? up : Math.max(0, cards.length - 1));
}
return { t, down, stock: p.stock ?? [], waste: p.waste ?? [], cells: p.cells ?? [], f: p.f ?? [], done: p.done ?? '', hist: [], undos: 0 };
}
/** A started one-player game of `mode` with my board replaced. */
function withBoard(mode: SolitaireOptions['mode'], b: SolitaireBoard, opts: Partial<SolitaireOptions> = {}): SolitaireState {
const s = started(['A', 'B'], { mode, ...opts });
return { ...s, boards: { ...s.boards, A: b } };
}
describe('solitaire · 패 돌리기', () => {
test('종류별 모양: 클론다이크 1~7장(맨 위만 앞면)+더미 24, 프리셀 7·7·7·7·6·6·6·6 모두 앞면, 스파이더 6×4·5×6+더미 50', () => {
for (let k = 1; k <= 10; k++) {
const kl = dealBoard(makeDeck(SeededRng.fromSeed(seedN(k)), { mode: 'klondike', suits: 1 }));
expect(kl.t.map((c) => c.length)).toEqual([1, 2, 3, 4, 5, 6, 7]);
expect(kl.down).toEqual([0, 1, 2, 3, 4, 5, 6]);
expect(kl.stock).toHaveLength(24);
expect(new Set([...kl.t.flat(), ...kl.stock]).size).toBe(52);
const fc = dealBoard(makeDeck(SeededRng.fromSeed(seedN(k)), { mode: 'freecell', suits: 1 }));
expect(fc.t.map((c) => c.length)).toEqual([7, 7, 7, 7, 6, 6, 6, 6]);
expect(fc.down.every((d) => d === 0)).toBe(true);
expect(fc.cells).toEqual(['', '', '', '']);
for (const suits of [1, 2, 4] as const) {
const sp = dealBoard(makeDeck(SeededRng.fromSeed(seedN(k)), { mode: 'spider', suits }));
expect(sp.t.map((c) => c.length)).toEqual([6, 6, 6, 6, 5, 5, 5, 5, 5, 5]);
expect(sp.down).toEqual([5, 5, 5, 5, 4, 4, 4, 4, 4, 4]);
expect(sp.stock).toHaveLength(50);
const all = [...sp.t.flat(), ...sp.stock];
expect(all).toHaveLength(104);
expect(new Set(all.map((c) => c[1])).size).toBe(suits);
for (const c of new Set(all)) expect(all.filter((x) => x === c)).toHaveLength(8 / suits);
}
}
});
test('같은 시드 = 같은 패, 모두 같은 판으로 시작, 카운트다운에는 판을 안 보여 줌', () => {
for (const mode of ['klondike', 'freecell', 'spider'] as const) {
const s = make(['A', 'B', 'C'], { mode });
expect(make(['A', 'B', 'C'], { mode })).toEqual(s);
expect(new Set(Object.values(s.boards).map((b) => encodeBoard(b))).size).toBe(1);
expect(solitaire.view(s, 'A').board).toBeNull();
expect(reason(s, 'A', { type: 'undo' }, T0 + 100)).toContain('곧 시작');
checkNoLeak(solitaire, s, 'A', s.order);
}
});
test('보기: 뒤집힌 카드는 null, 더미는 장수만, 다른 사람 판은 없음', () => {
const s = started(['A', 'B'], { mode: 'spider', suits: 4 });
const v = solitaire.view(s, 'A').board!;
expect(v.t.map((c) => c.filter((x) => x === null).length)).toEqual(s.boards.A!.down);
expect(v.stock).toBe(50);
expect(JSON.stringify(solitaire.view(s, 'A'))).not.toContain(s.boards.A!.stock.join(''));
expect(solitaire.view(s, null).board).toBeNull();
});
});
describe('solitaire · 클론다이크', () => {
test('카드 넘기기: 1장씩 / 3장씩, 더미가 비면 버린 카드를 다시 뒤집어 더미로', () => {
let s = started(['A'], { mode: 'klondike', draw: 1 });
const stock = [...s.boards.A!.stock];
s = act(s, 'A', { type: 'draw' });
expect(s.boards.A!.waste).toEqual([stock.at(-1)!]);
let t = started(['A'], { mode: 'klondike', draw: 3 });
t = act(t, 'A', { type: 'draw' });
expect(t.boards.A!.waste).toEqual(stock.slice(-3).reverse());
for (let k = 0; k < 7; k++) t = act(t, 'A', { type: 'draw' });
expect(t.boards.A!.stock).toHaveLength(0);
expect(t.boards.A!.waste).toHaveLength(24);
t = act(t, 'A', { type: 'draw' });
expect(t.boards.A!.stock).toEqual(stock);
expect(t.boards.A!.waste).toEqual([]);
const empty = withBoard('klondike', board({ cols: ['KS', '', '', '', '', '', ''], f: ['', '', '', ''] }));
expect(reason(empty, 'A', { type: 'draw' })).toBe('넘길 카드가 없어요.');
});
test('번갈아 색·하나 작은 수, 빈 줄엔 K만, 옮기면 아래 카드가 저절로 뒤집힘, 파운데이션은 A부터 같은 무늬', () => {
let s = withBoard(
'klondike',
board({ cols: ['3H 9H', '2D ^TS', '5C', 'KD', '', 'AS', '2S'], waste: ['QS'], f: ['', '', '', ''] }),
);
expect(reason(s, 'A', mv('t2', 't0'))).toBe('색이 다르고 숫자가 하나 큰 카드 위에만 놓을 수 있어요.');
expect(reason(s, 'A', mv('t2', 't4'))).toBe('빈 줄에는 K만 놓을 수 있어요.');
expect(reason(s, 'A', mv('t1', 't3', 2))).toBe('뒤집힌 카드는 옮길 수 없어요.');
expect(reason(s, 'A', mv('t6', 'f'))).toBe('이 카드는 아직 올릴 수 없어요. 같은 무늬로 A부터 차례대로 올려요.');
expect(reason(s, 'A', mv('t6', 'f0'))).toBe('빈 자리에는 A부터 올려요.');
expect(reason(s, 'A', mv('c0', 't0'))).toBe('그런 자리는 없어요.');
expect(reason(s, 'A', { type: 'deal' })).toBe('스파이더에서만 카드를 나눠요.');
s = act(s, 'A', mv('t0', 't1')); // 9H on TS, 3H turns up
expect(s.boards.A!.t[1]).toEqual(['2D', 'TS', '9H']);
expect(s.boards.A!.down[0]).toBe(0);
expect(solitaire.view(s, 'A').board!.t[0]).toEqual(['3H']);
s = act(s, 'A', mv('t3', 't4')); // K to the empty column
expect(s.boards.A!.t[4]).toEqual(['KD']);
s = act(s, 'A', mv('w', 't4')); // QS on KD
s = act(s, 'A', mv('t5', 'f'));
s = act(s, 'A', mv('t6', 'f'));
expect(s.boards.A!.f).toEqual(['2S', '', '', '']);
expect(solitaire.view(s, 'A').seats.find((x) => x.id === 'A')!.progressText).toBe('올린 카드 2/52');
// A card can come back down from a foundation (Klondike only).
expect(reason(s, 'A', mv('f0', 't0'))).toBe('ok');
s = act(s, 'A', mv('f0', 't0'));
expect(s.boards.A!.f[0]).toBe('AS');
expect(s.boards.A!.t[0]).toEqual(['3H', '2S']);
});
test('자동 정리: 올릴 수 있는 카드를 모두(뒤집히는 카드까지) 올리고, 없으면 거절', () => {
let s = withBoard('klondike', board({ cols: ['2H AS', 'AH', '', '', '', '', ''], waste: ['2S'], f: ['', '', '', ''] }));
s = act(s, 'A', { type: 'auto' });
expect(s.boards.A!.f.filter(Boolean).sort()).toEqual(['2H', '2S']);
expect(s.boards.A!.t[0]).toEqual([]);
expect(reason(s, 'A', { type: 'auto' })).toBe('바로 올릴 수 있는 카드가 없어요.');
});
test('다 올리면 다 풂: 혼자면 바로 끝, 걸린 시간 요약', () => {
const f = ['QS', 'QH', 'QD', 'QC'];
let s = withBoard('klondike', board({ cols: ['KS', 'KH', 'KD', '', '', '', ''], waste: ['KC'], f }));
s = { ...s, order: ['A'], status: { A: 'playing' }, boards: { A: s.boards.A! } };
s = act(s, 'A', { type: 'auto' });
expect(s.status.A).toBe('solved');
expect(s.final!.summary).toMatch(/^다 풀었어요! 걸린 시간 /);
expect(solitaire.result(s)!.scoreText!.A).toMatch(/^다 풀었어요 · /);
});
});
describe('solitaire · 프리셀', () => {
test('빈 칸 4개, 아무 카드나 빈 줄에, 올린 카드는 못 내림, 한 번에 옮기는 장수 = (빈 칸+1)×2^(빈 줄)', () => {
const cols = ['KS QH JC TD 9S 8H', '7C', 'AD', '', '5S', '6S', '4H', '3D'];
let s = withBoard('freecell', board({ cols: cols.map((c) => (c ? `^${c}` : '')), cells: ['', '', '', ''], f: ['', '', '', ''] }));
expect(reason(s, 'A', mv('t1', 't3'))).toBe('ok'); // any card into an empty column
expect(reason(s, 'A', mv('t0', 't1', 2))).toBe('색이 다르고 숫자가 하나 큰 카드 위에만 놓을 수 있어요.');
// 4 free cells, 1 empty column: 5 × 2 = 10 onto a card; into the empty column it does not count: 5.
expect(reason(s, 'A', mv('t0', 't3', 6))).toBe('빈 칸과 빈 줄로는 한 번에 5장까지 옮길 수 있어요.');
expect(reason(s, 'A', mv('t0', 't3', 5))).toBe('ok');
s = act(s, 'A', mv('t2', 'f'));
expect(reason(s, 'A', mv('f0', 't3'))).toBe('올린 카드는 내릴 수 없어요.');
for (const [i, from] of ['t4', 't5', 't6'].entries()) s = act(s, 'A', mv(from, `c${i}`));
expect(reason(s, 'A', mv('t7', 'c0'))).toBe('빈 칸에만 놓을 수 있어요.');
expect(reason(s, 'A', mv('t0', 'c3', 2))).toBe('빈 칸에는 한 장만 놓아요.');
// 1 free cell, 5 empty columns (t2…t6): 2 × 2^5 onto a card, 2 × 2^4 into an empty column.
const tb = tableOf(s.puzzle, s.boards.A!, 1);
expect(freecellCapacity(tb, false)).toBe(64);
expect(freecellCapacity(tb, true)).toBe(32);
expect(moveProblem(tb, mv('t0', 't3', 6))).toBeNull();
s = act(s, 'A', mv('c0', 't3'));
expect(s.boards.A!.cells[0]).toBe('');
expect(reason(s, 'A', { type: 'draw' })).toBe('클론다이크에서만 카드를 넘겨요.');
});
test('스크립트로 찾은 풀이를 실제로 두면 다 풂(solved)', () => {
let solvedOne = false;
for (let seed = 1; seed <= 6 && !solvedOne; seed++) {
const s0 = started(['A'], { mode: 'freecell', timeLimitSec: null }, seed);
const path = solveFreecell(s0.puzzle, s0.boards.A!, 60_000);
if (!path) continue;
let s = s0;
let now = START;
for (const m of path) s = act(s, 'A', m, (now += 200));
expect(s.status.A).toBe('solved');
expect(s.phase).toBe('ended');
solvedOne = true;
}
expect(solvedOne).toBe(true);
});
});
describe('solitaire · 스파이더', () => {
test('무늬 상관없이 하나 작은 수 위에, 같은 무늬 줄만 한꺼번에, 빈 줄 있으면 못 나눔, 나누면 10장', () => {
const cols = ['AS ^9S 8H', '9H', '', 'TS', 'JS', 'QS', 'KS', 'KH 2S', '3S', '4S'];
let s = withBoard('spider', board({ cols, stock: Array(10).fill('5H') }), { suits: 2 });
expect(reason(s, 'A', mv('t0', 't3', 2))).toBe('같은 무늬로 이어진 카드만 한꺼번에 옮길 수 있어요.');
expect(reason(s, 'A', mv('t1', 't3'))).toBe('ok'); // 9H on TS: any suit
expect(reason(s, 'A', mv('t7', 't1'))).toBe('숫자가 하나 큰 카드 위에만 놓을 수 있어요.');
expect(reason(s, 'A', { type: 'deal' })).toBe('빈 줄이 있으면 나눌 수 없어요. 먼저 빈 줄을 채워 주세요.');
expect(reason(s, 'A', mv('t0', 'f'))).toBe('그런 자리는 없어요.');
expect(reason(s, 'A', { type: 'auto' })).toBe('스파이더에는 자동 정리가 없어요.');
s = act(s, 'A', mv('t7', 't2'));
s = act(s, 'A', { type: 'deal' });
expect(s.boards.A!.t.every((c) => c.at(-1) === '5H')).toBe(true);
expect(s.boards.A!.stock).toHaveLength(0);
expect(reason(s, 'A', { type: 'deal' })).toBe('더 나눌 카드가 없어요.');
});
test('K부터 A까지 같은 무늬가 다 이어지면 저절로 빠지고 아래 카드가 뒤집힘, 8줄 다 빼면 다 풂', () => {
const run = 'KS QS JS TS 9S 8S 7S 6S 5S 4S 3S 2S'.split(' ');
const cols = [`4H ^${run.join(' ')}`, 'AS', '', '', '', '', '', '', '', ''];
let s = withBoard('spider', board({ cols, done: 'SSSSSSS' }));
s = { ...s, order: ['A'], status: { A: 'playing' }, boards: { A: s.boards.A! } };
const v0 = solitaire.view(s, 'A').board!;
expect(v0.t[0]![0]).toBeNull();
let t = act(s, 'A', mv('t1', 't0'));
expect(t.status.A).toBe('solved');
expect(t.boards.A!.done).toBe('SSSSSSSS');
expect(t.boards.A!.t[0]).toEqual(['4H']);
expect(t.boards.A!.down[0]).toBe(0);
// With other runs still left: the run goes, the progress text counts it.
t = act({ ...s, boards: { A: { ...s.boards.A!, done: 'SS' } } }, 'A', mv('t1', 't0'));
expect(t.status.A).toBe('playing');
expect(solitaire.view(t, 'A').seats[0]!.progressText).toBe('완성 3/8줄');
expect(solitaire.view(t, 'A').seats[0]!.progress).toBe(39);
});
});
describe('solitaire · 되돌리기', () => {
test('바로 앞 판으로 돌아가고 횟수를 셈, 50번까지, 처음엔 거절', () => {
let s = started(['A'], { mode: 'klondike' });
expect(reason(s, 'A', { type: 'undo' })).toBe('되돌릴 수가 없어요.');
const first = encodeBoard(s.boards.A!);
s = act(s, 'A', { type: 'draw' });
s = act(s, 'A', { type: 'undo' });
expect(encodeBoard(s.boards.A!)).toBe(first);
expect(s.boards.A!.undos).toBe(1);
expect(solitaire.view(s, 'A').board!.undos).toBe(1);
expect(solitaire.view(s, 'A').seats[0]!.extra).toBe(' · 되돌리기 1번');
let now = START + 10_000;
for (let k = 0; k < 60; k++) s = act(s, 'A', { type: 'draw' }, (now += 200));
expect(s.boards.A!.hist).toHaveLength(MAX_UNDO);
for (let k = 0; k < MAX_UNDO; k++) s = act(s, 'A', { type: 'undo' }, (now += 200));
expect(reason(s, 'A', { type: 'undo' }, (now += 200))).toBe('되돌릴 수가 없어요.');
expect(s.boards.A!.undos).toBe(1 + MAX_UNDO);
});
});
describe('solitaire · 순위·끝', () => {
test('기본은 클론다이크 1장, 스파이더 1가지, 제한 시간 15분', () => {
expect(solitaire.defaultOptions).toEqual({ mode: 'klondike', draw: 1, suits: 1, timeLimitSec: 900 });
expect(make().endsAt).toBe(START + 900_000);
});
test('먼저 다 푼 사람 > 올린 카드 많은 순(같으면 같은 순위), 포기한 사람도 올린 만큼, 나간 사람 맨 아래', () => {
const f = ['QS', 'QH', 'QD', 'QC'];
let s = started(['A', 'B', 'C', 'D'], { mode: 'klondike' });
const near = board({ cols: ['KS', 'KH', 'KD', 'KC', '', '', ''], f });
s = { ...s, boards: { ...s.boards, A: near, B: { ...near, f: ['AS', '', '', ''] }, C: { ...near, f: ['AS', '', '', ''] } } };
s = act(s, 'D', { type: 'leave' } as A);
s = act(s, 'B', { type: 'stop' });
s = act(s, 'C', { type: 'stop' });
expect(s.phase).toBe('playing');
s = act(s, 'A', { type: 'auto' });
expect(s.phase).toBe('ended');
const r = s.final!.ranking;
expect(r.map((x) => x.id)).toEqual(['A', 'B', 'C', 'D']);
expect(r.map((x) => x.rank)).toEqual([1, 2, 2, 4]);
expect(s.final!.summary).toBe('가장 먼저 다 푼 사람이 이겼어요');
expect(solitaire.result(s)!.scoreText!.B).toBe('올린 카드 1/52 · 포기');
expect(solitaire.result(s)!.scores!.A).toBe(52);
});
test('제한 시간: 마감 tick으로 끝, 마감 뒤 거절, 아무도 못 풀면 많이 올린 사람이 이김', () => {
let s = started(['A', 'B'], { mode: 'freecell', timeLimitSec: 600 });
s = { ...s, boards: { ...s.boards, A: { ...s.boards.A!, f: ['AS', '', '', ''] } } };
const end = START + 600_000;
expect(solitaire.deadline!(s)).toBe(end);
expect(reason(s, 'B', { type: 'auto' }, end)).toBe('시간이 다 됐어요.');
s = solitaire.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('시간이 다 됐어요. 아무도 다 풀지 못했어요. 가장 많이 푼 사람이 이겼어요');
});
test('무제한: 끊긴 사람은 tick 한 번으로 포기 처리, 모두 끝나면 끝', () => {
let s = started(['A', 'B'], { timeLimitSec: null });
expect(solitaire.deadline!(s)).toBeNull();
s = solitaire.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'], { mode: 'klondike' });
for (let k = 0; k < 12; k++) s = act(s, 'A', { type: 'draw' }, START + 100 + k);
expect(reason(s, 'A', { type: 'draw' }, START + 200)).toBe('조금 천천히 해 주세요.');
expect(reason(s, 'A', { type: 'draw' }, START + 1200)).toBe('ok');
});
});
describe('solitaire · 무작위 대국', () => {
test('1·2·5·8명, 세 종류: 유출·JSON·결정성, 끝나기 전 내 화면에 뒤집힌 카드·더미가 없음', () => {
const modes = [
{ mode: 'klondike', draw: 3 },
{ mode: 'freecell' },
{ mode: 'spider', suits: 2 },
{ mode: 'klondike', draw: 1 },
{ mode: 'spider', suits: 4 },
] as const;
for (let k = 1; k <= playoutSeeds(50); k++) {
for (const n of [1, 2, 5, 8]) {
const players = Array.from({ length: n }, (_, i) => `p${i}`);
const options = solitaire.optionsSchema.parse({ ...modes[(k + n) % modes.length], timeLimitSec: k % 2 ? null : 600 });
const invariant = (st: unknown) => {
const s = st as SolitaireState;
if (s.phase !== 'playing') return;
for (const p of players) {
if (s.status[p] !== 'playing') continue;
const v = solitaire.view(s, p).board!;
const b = s.boards[p]!;
expect(v.t.map((c) => c.filter((x) => x === null).length)).toEqual(b.down);
expect(typeof v.stock).toBe('number');
if (options.mode === 'klondike') {
// Every card is unique here, so none of the hidden ones may appear anywhere in my view.
const json = JSON.stringify(solitaire.view(s, p));
for (const c of [...b.stock, ...b.t.flatMap((col, i) => col.slice(0, b.down[i]))]) expect(json).not.toContain(`"${c}"`);
}
}
};
const a = randomPlayout(solitaire, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000, invariant });
expect(a.finished).toBe(true);
const b = randomPlayout(solitaire, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000 });
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
}
}
});
});
/** Test-only FreeCell solver (full information): depth-first, foundation moves and the computer's favourite moves first. */
function solveFreecell(p: SolitairePuzzle, start: SolitaireBoard, budget: number): SolitaireMove[] | null {
const seen = new Set<string>();
const key = (b: SolitaireBoard) => {
const cols = b.t.map((c) => c.join('')).sort().join(',');
return `${cols}|${[...b.cells].sort().join('')}|${b.f.join('')}`;
};
const stack: { b: SolitaireBoard; path: SolitaireMove[] }[] = [{ b: { ...start, hist: [] }, path: [] }];
while (stack.length && seen.size < budget) {
const { b, path } = stack.pop()!;
if (isSolved('freecell', b)) return path;
const k = key(b);
if (seen.has(k)) continue;
seen.add(k);
const tb = tableOf(p, b, 1);
const moves = legalOn(tb).filter((m) => m.type === 'move');
const ranked = moves.map((m) => ({ m, s: scoreMove(tb as never, m) + (m.type === 'move' && m.to[0] === 'c' ? -5 : 0) })).sort((x, y) => x.s - y.s);
for (const { m } of ranked) {
const next = playMove(p, b, m, 1);
next.hist = [];
if (!seen.has(key(next))) stack.push({ b: next, path: [...path, m] });
}
}
return null;
}

View File

@@ -0,0 +1,56 @@
/** 스도쿠 computers (docs/games/sudoku.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 { sudokuBot } from './bot';
import { sudoku, type SudokuState } from './index';
const isBot = (p: string) => p.startsWith('bot:');
describe('sudoku · 한 판 전체', () => {
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}:s${n}${i}`));
for (const difficulty of ['easy', 'normal', 'hard'] as const) {
const r = liveBotPlayout(sudoku, sudokuBot, {
players,
options: sudoku.optionsSchema.parse({ difficulty, timeLimitSec: humans ? 1800 : null }),
seed: seedN(n * 10 + humans),
isBot,
levelOf: (p) => 1 + ((p.length * 7) % 60),
});
expect(r.finished).toBe(true);
expect(r.rejected).toEqual([]);
expect(r.maxBotMs).toBeLessThan(50);
const s = r.state as SudokuState;
for (const p of players) if (isBot(p) && !humans) expect(s.status[p]).toBe('solved');
for (const p of players) if (isBot(p)) expect(s.boards[p]!.hints).toBe(0);
}
}
}
});
test('강한 컴퓨터는 쉬움을 기본 제한 시간(30분) 안에 풀고, 약한 컴퓨터보다 빨라요', () => {
let faster = 0;
const times = { weak: 0, strong: 0 };
for (let k = 0; k < 8; k++) {
const r = liveBotPlayout(sudoku, sudokuBot, {
players: ['bot:1:weak', 'bot:2:strong'],
options: sudoku.optionsSchema.parse({}),
seed: seedN(700 + k),
isBot,
levelOf: (p) => (p.endsWith('weak') ? 3 : 58),
});
const s = r.state as SudokuState;
expect(s.status['bot:2:strong']).toBe('solved');
const t = (p: string) => s.finishedAt[p]! - s.countdownEndsAt;
expect(t('bot:2:strong')).toBeLessThan(600_000);
times.weak += s.status['bot:1:weak'] === 'solved' ? t('bot:1:weak') : 1_800_000;
times.strong += t('bot:2:strong');
if (s.status['bot:1:weak'] !== 'solved' || t('bot:2:strong') < t('bot:1:weak')) faster++;
}
expect(faster).toBeGreaterThanOrEqual(7);
expect(times.strong * 2).toBeLessThan(times.weak);
});
});

View File

@@ -0,0 +1,62 @@
/**
* 스도쿠 computers (docs/games/sudoku.md §13). They only read their own screen; the givens there are public, so a
* computer solves the puzzle from them once and then fills one cell at a time, the easiest (fewest candidates) first.
* - Time per cell: level 1 about 15 s … level 60 about 4 s on 쉬움; 보통 ×1.5, 어려움 ×2.2.
* - Weak computers sometimes write a wrong number and fix it later (they never use hints).
*/
import { raceBot } from '../race/bot';
import { PEERS, solve, type Difficulty, type SudokuBoardView, type SudokuMove } from './index';
type V = SudokuBoardView;
const PACE: Record<Difficulty, number> = { easy: 1, normal: 1.5, hard: 2.2 };
/** The solution from the givens on screen (cached per puzzle). */
export function solutionOf(v: V, memory: Record<string, unknown>): string {
const key = [...v.values].map((ch, i) => (v.givens[i] === '1' ? ch : '0')).join('');
if (memory.key !== key) {
memory.key = key;
memory.sol = (solve([...key].map(Number)) ?? []).join('');
}
return memory.sol as string;
}
/** Digits still possible in `i`, looking only at the right numbers on the board. */
function candidates(v: V, sol: string, i: number): number[] {
const used = new Set<string>();
for (const j of PEERS[i]!) if (v.values[j] === sol[j]) used.add(sol[j]!);
return [1, 2, 3, 4, 5, 6, 7, 8, 9].filter((d) => !used.has(String(d)));
}
export const sudokuBot = raceBot<V, SudokuMove>((v, skill, random, memory) => {
const sol = solutionOf(v, memory);
const step = (15_000 - 11_000 * skill) * PACE[v.difficulty];
const empty: number[] = [];
const wrong: number[] = [];
for (let i = 0; i < 81; i++) {
if (v.values[i] === '0') empty.push(i);
else if (v.values[i] !== sol[i]) wrong.push(i);
}
// A wrong number gets noticed now and then, and always once the board is full.
if (wrong.length && (!empty.length || random() < 0.25)) {
const i = wrong[0]!;
return { move: { type: 'set', i, n: Number(sol[i]) }, ms: step * (0.8 + 0.6 * random()) };
}
if (!empty.length) return { move: null, ms: 1000 };
let best: number[] = [];
let low = 10;
for (const i of empty) {
const c = candidates(v, sol, i).length;
if (c < low) [best, low] = [[i], c];
else if (c === low) best.push(i);
}
const i = best[Math.floor(random() * best.length)]!;
const right = Number(sol[i]);
const ms = step * (0.7 + 0.6 * random()) * (1 + 0.2 * (low - 1));
if (random() < 0.15 * (1 - skill)) {
const others = candidates(v, sol, i).filter((d) => d !== right);
const pool = others.length ? others : [1, 2, 3, 4, 5, 6, 7, 8, 9].filter((d) => d !== right);
return { move: { type: 'set', i, n: pool[Math.floor(random() * pool.length)]! }, ms };
}
return { move: { type: 'set', i, n: right }, ms };
});

View File

@@ -0,0 +1,304 @@
/**
* 스도쿠 (docs/games/sudoku.md). Everyone solves the same 9×9 puzzle on their own copy (race frame, ../race).
* The seeded generator fills a whole grid, then removes cells while the solution stays unique; 쉬움 also has to be
* solvable with naked and hidden singles only. Like paper, nothing tells a player whether a number is right:
* progress counts filled cells and the board is solved when every cell matches the solution.
*/
import { z } from 'zod';
import type { Rng } from '@bg/engine';
import { lit, makeRaceGame, timeLimitOption, type RaceState, type RaceView } from '../race';
export { COUNTDOWN_MS, formatElapsed } from '../race';
export const DIFFICULTIES = {
easy: { name: '쉬움', givens: '숫자 38~40개' },
normal: { name: '보통', givens: '숫자 30~32개' },
hard: { name: '어려움', givens: '숫자 26개 안팎' },
} as const;
export type Difficulty = keyof typeof DIFFICULTIES;
export const sudokuOptionsSchema = z.object({
difficulty: lit<Difficulty>('easy', 'normal', 'hard')
.default('easy')
.meta({ title: '난이도', labels: { easy: '쉬움', normal: '보통', hard: '어려움' } }),
hints: z.boolean().default(true).meta({ title: '힌트' }),
timeLimitSec: timeLimitOption([600, 1200, 1800, 3600], 1800),
});
export type SudokuOptions = z.infer<typeof sudokuOptionsSchema>;
const cell = z.number().int().min(0).max(80);
const digit = z.number().int().min(1).max(9);
const moveSchemas = [
z.object({ type: z.literal('set'), i: cell, n: digit }),
z.object({ type: z.literal('clear'), i: cell }),
z.object({ type: z.literal('note'), i: cell, n: digit }),
z.object({ type: z.literal('hint') }),
] as const;
export type SudokuMove = { type: 'set'; i: number; n: number } | { type: 'clear'; i: number } | { type: 'note'; i: number; n: number } | { type: 'hint' };
export interface SudokuPuzzle {
difficulty: Difficulty;
/** 81 digits, '0' = empty. Row-major. */
givens: string;
/** 81 digits. */
solution: string;
}
export interface SudokuBoard {
/** 81 digits including the givens, '0' = empty. */
values: string;
/** Per cell, pencil marks as a bitmask (bit n = digit n). */
notes: number[];
hints: number;
/** The cell the last hint filled. */
hintAt: number | null;
}
export interface SudokuBoardView {
difficulty: Difficulty;
/** Per cell '1' = given. */
givens: string;
values: string;
notes: number[];
hints: number;
hintAt: number | null;
/** Only once I am finished (or the game is over). */
solution?: string;
}
export type SudokuState = RaceState<SudokuPuzzle, SudokuBoard, SudokuOptions>;
export type SudokuView = RaceView<SudokuBoardView, SudokuOptions>;
const rowOf = (i: number) => Math.floor(i / 9);
const colOf = (i: number) => i % 9;
const boxOf = (i: number) => Math.floor(rowOf(i) / 3) * 3 + Math.floor(colOf(i) / 3);
/** The 27 rows, columns and boxes. */
export const UNITS: number[][] = [
...Array.from({ length: 9 }, (_, r) => Array.from({ length: 9 }, (_, c) => r * 9 + c)),
...Array.from({ length: 9 }, (_, c) => Array.from({ length: 9 }, (_, r) => r * 9 + c)),
...Array.from({ length: 9 }, (_, b) => Array.from({ length: 9 }, (_, k) => (Math.floor(b / 3) * 3 + Math.floor(k / 3)) * 9 + (b % 3) * 3 + (k % 3))),
];
/** The 20 cells sharing a row, column or box with each cell. */
export const PEERS: number[][] = Array.from({ length: 81 }, (_, i) =>
Array.from({ length: 81 }, (_, j) => j).filter((j) => j !== i && (rowOf(j) === rowOf(i) || colOf(j) === colOf(i) || boxOf(j) === boxOf(i))),
);
const ALL = 0x3fe;
const bitCount = (m: number) => {
let n = 0;
for (let x = m; x; x &= x - 1) n++;
return n;
};
/**
* Depth-first search with bitmasks (fewest candidates first). Counts solutions up to `limit`; the first one found is
* written to `out`. With `rng` the candidates are tried in random order (used to make a full grid).
*/
function search(grid: number[], limit: number, out: number[] | null, rng: Rng | null): number {
const rows = new Array<number>(9).fill(0);
const cols = new Array<number>(9).fill(0);
const boxes = new Array<number>(9).fill(0);
for (let i = 0; i < 81; i++) {
const d = grid[i]!;
if (!d) continue;
const bit = 1 << d;
if (rows[rowOf(i)]! & bit || cols[colOf(i)]! & bit || boxes[boxOf(i)]! & bit) return 0;
rows[rowOf(i)]! |= bit;
cols[colOf(i)]! |= bit;
boxes[boxOf(i)]! |= bit;
}
const g = [...grid];
let found = 0;
const go = (): boolean => {
let best = -1;
let bestMask = 0;
let bestCount = 10;
for (let i = 0; i < 81; i++) {
if (g[i]) continue;
const m = ALL & ~(rows[rowOf(i)]! | cols[colOf(i)]! | boxes[boxOf(i)]!);
const c = bitCount(m);
if (c < bestCount) {
best = i;
bestMask = m;
bestCount = c;
if (c <= 1) break;
}
}
if (best < 0) {
if (found === 0 && out) for (let i = 0; i < 81; i++) out[i] = g[i]!;
found++;
return found >= limit;
}
if (!bestMask) return false;
let ds: number[] = [];
for (let d = 1; d <= 9; d++) if (bestMask & (1 << d)) ds.push(d);
if (rng) ds = rng.shuffle(ds);
const r = rowOf(best);
const c = colOf(best);
const b = boxOf(best);
for (const d of ds) {
const bit = 1 << d;
g[best] = d;
rows[r]! |= bit;
cols[c]! |= bit;
boxes[b]! |= bit;
const stop = go();
rows[r]! &= ~bit;
cols[c]! &= ~bit;
boxes[b]! &= ~bit;
g[best] = 0;
if (stop) return true;
}
return false;
};
go();
return found;
}
/** Number of solutions, counting at most `limit`. */
export const countSolutions = (grid: number[], limit = 2) => search(grid, limit, null, null);
/** The solution of a grid (the first one found), or null. */
export function solve(grid: number[]): number[] | null {
const out = new Array<number>(81).fill(0);
return search(grid, 1, out, null) ? out : null;
}
/** Fills the grid with naked and hidden singles only; true if that solves it. */
export function solvesWithSingles(grid: number[]): boolean {
const g = [...grid];
const cand = (i: number) => {
let m = ALL;
for (const j of PEERS[i]!) if (g[j]) m &= ~(1 << g[j]!);
return m;
};
for (let moved = true; moved; ) {
moved = false;
for (let i = 0; i < 81; i++) {
if (g[i]) continue;
const m = cand(i);
if (!m) return false;
if (bitCount(m) === 1) {
g[i] = 31 - Math.clz32(m);
moved = true;
}
}
for (const unit of UNITS) {
for (let d = 1; d <= 9; d++) {
if (unit.some((i) => g[i] === d)) continue;
const spots = unit.filter((i) => !g[i] && cand(i) & (1 << d));
if (spots.length === 0) return false;
if (spots.length === 1) {
g[spots[0]!] = d;
moved = true;
}
}
}
}
return g.every((d) => d > 0);
}
/** A seeded puzzle with exactly one solution (docs/games/sudoku.md §3~4). */
export function makePuzzle(rng: Rng, difficulty: Difficulty): SudokuPuzzle {
const full = new Array<number>(81).fill(0);
search(new Array<number>(81).fill(0), 1, full, rng);
const target = difficulty === 'easy' ? 38 + rng.int(3) : difficulty === 'normal' ? 30 + rng.int(3) : 0;
const grid = [...full];
let givens = 81;
for (const i of rng.shuffle(Array.from({ length: 81 }, (_, k) => k))) {
if (givens <= target) break;
const d = grid[i]!;
grid[i] = 0;
const keep = difficulty === 'easy' ? solvesWithSingles(grid) : countSolutions(grid) === 1;
if (keep) givens--;
else grid[i] = d;
}
return { difficulty, givens: grid.join(''), solution: full.join('') };
}
const setAt = (s: string, i: number, ch: string) => s.slice(0, i) + ch + s.slice(i + 1);
/** Puts `n` in cell `i`: the cell's own marks go, and `n` leaves the marks of its row, column and box. */
function place(b: SudokuBoard, i: number, n: number): SudokuBoard {
const notes = [...b.notes];
notes[i] = 0;
for (const j of PEERS[i]!) notes[j] = notes[j]! & ~(1 << n);
return { ...b, values: setAt(b.values, i, String(n)), notes };
}
export const blanksOf = (p: SudokuPuzzle) => [...p.givens].filter((ch) => ch === '0').length;
const filledOf = (p: SudokuPuzzle, b: SudokuBoard) => {
let n = 0;
for (let i = 0; i < 81; i++) if (p.givens[i] === '0' && b.values[i] !== '0') n++;
return n;
};
export const sudoku = makeRaceGame<SudokuPuzzle, SudokuBoard, SudokuMove, SudokuBoardView, SudokuOptions>({
id: 'sudoku',
nameKo: '스도쿠',
optionsSchema: sudokuOptionsSchema,
moveSchemas: moveSchemas as never,
makePuzzle: (rng, o) => makePuzzle(rng, o.difficulty),
startBoard: (p) => ({ values: p.givens, notes: new Array<number>(81).fill(0), hints: 0, hintAt: null }),
checkMove(p, b, m, o) {
if (m.type === 'hint') return o.hints ? null : '이 방은 힌트를 쓸 수 없어요.';
if (p.givens[m.i] !== '0') return '처음부터 있던 숫자는 바꿀 수 없어요.';
if (m.type === 'set') return b.values[m.i] === String(m.n) ? '이미 그 숫자예요.' : null;
if (m.type === 'clear') return b.values[m.i] === '0' && !b.notes[m.i] ? '지울 것이 없어요.' : null;
return b.values[m.i] !== '0' ? '숫자가 있는 칸에는 메모할 수 없어요.' : null;
},
applyMove(p, b, m, { rng }) {
let next: SudokuBoard;
if (m.type === 'set') next = place(b, m.i, m.n);
else if (m.type === 'clear') {
const notes = [...b.notes];
notes[m.i] = 0;
return { board: { ...b, values: b.values[m.i] === '0' ? b.values : setAt(b.values, m.i, '0'), notes } };
} else if (m.type === 'note') {
const notes = [...b.notes];
notes[m.i] = notes[m.i]! ^ (1 << m.n);
return { board: { ...b, notes } };
} else {
// A hint fixes one empty or wrong cell, picked at random.
const fix: number[] = [];
for (let i = 0; i < 81; i++) if (b.values[i] !== p.solution[i]) fix.push(i);
const i = fix[rng.int(fix.length)]!;
next = { ...place(b, i, Number(p.solution[i])), hints: b.hints + 1, hintAt: i };
}
return { board: next, outcome: next.values === p.solution ? 'solved' : undefined, events: m.type === 'hint' ? [{ type: 'hint', i: next.hintAt }] : undefined };
},
boardView(p, b, reveal) {
return {
difficulty: p.difficulty,
givens: [...p.givens].map((ch) => (ch === '0' ? '0' : '1')).join(''),
values: b.values,
notes: b.notes,
hints: b.hints,
hintAt: b.hintAt,
...(reveal ? { solution: p.solution } : {}),
};
},
progress: filledOf,
progressText: (p, b) => `채운 칸 ${filledOf(p, b)}/${blanksOf(p)}`,
extraText: (b) => (b.hints ? ` · 힌트 ${b.hints}번` : ''),
legalMoves(p, b, o) {
const out: SudokuMove[] = [];
for (let i = 0; i < 81 && out.length < 4; i++) {
if (p.givens[i] !== '0' || b.values[i] === p.solution[i]) continue;
out.push({ type: 'set', i, n: Number(p.solution[i]) });
if (out.length === 1) out.push(b.values[i] === '0' ? { type: 'note', i, n: 1 + (i % 9) } : { type: 'clear', i });
}
if (o.hints) out.push({ type: 'hint' });
return out;
},
secrets: (p) => [p.solution, p.givens],
});

View File

@@ -0,0 +1,230 @@
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));
}
}
});
});

View File

@@ -65,6 +65,11 @@ export const BOT_GAMES: readonly string[] = [
'tichu',
'castles-of-burgundy',
'typing',
'minesweeper',
'shisen',
'solitaire',
'sudoku',
'nonogram',
];
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */

View File

@@ -39,6 +39,11 @@ export const CATALOG: CatalogEntry[] = [
{ id: 'catchmind', nameKo: '그림 맞히기', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '한 사람이 그림을 그리면 나머지가 채팅으로 정답을 맞혀요!', available: true },
{ id: 'apple', nameKo: '사과 게임', minPlayers: 1, maxPlayers: 8, minutes: '1~3', level: '쉬움', blurb: '합이 10이 되게 사과를 드래그! 2분 동안 누가 더 많이 지울까 · 혼자서도 OK', available: true },
{ id: 'typing', nameKo: '타자 대결', minPlayers: 1, maxPlayers: 8, minutes: '3~10', level: '쉬움', blurb: '같은 글을 누가 더 빨리 정확하게 칠까! 가장 먼저 입력·서바이벌·타수 비교 · 단어·짧은글·긴글 · 한국어·영어', available: true },
{ id: 'minesweeper', nameKo: '지뢰찾기', minPlayers: 1, maxPlayers: 8, minutes: '1~10', level: '쉬움', blurb: '숫자를 보고 지뢰를 피해 모든 칸을 열어요! 초급·중급·고급 · 여럿이면 같은 판으로 누가 먼저 · 혼자서도 OK', available: true },
{ id: 'shisen', nameKo: '사천성', minPlayers: 1, maxPlayers: 8, minutes: '5~15', level: '쉬움', blurb: '같은 마작패 두 장을 두 번 이하로 꺾인 선으로 이어 없애요! 작게·보통·크게 · 여럿이면 같은 판으로 누가 먼저 · 혼자서도 OK', available: true },
{ id: 'solitaire', nameKo: '솔리테어', minPlayers: 1, maxPlayers: 8, minutes: '5~15', level: '쉬움', blurb: '윈도우 그 카드놀이! 클론다이크·프리셀·스파이더 · 여럿이면 같은 패로 누가 먼저 · 혼자서도 OK', available: true },
{ id: 'sudoku', nameKo: '스도쿠', minPlayers: 1, maxPlayers: 8, minutes: '5~30', level: '보통', blurb: '가로·세로·3×3 상자에 1~9를 한 번씩! 쉬움·보통·어려움 · 여럿이면 같은 판으로 누가 먼저 · 혼자서도 OK', available: true },
{ id: 'nonogram', nameKo: '네모네모 로직', minPlayers: 1, maxPlayers: 8, minutes: '3~20', level: '보통', blurb: '줄마다 적힌 숫자대로 칸을 칠하면 그림이 나와요! 5×5·10×10·15×15 · 여럿이면 같은 그림으로 누가 먼저 · 혼자서도 OK', available: true },
{ id: 'connect-four', nameKo: '커넥트 포', minPlayers: 2, maxPlayers: 2, minutes: '3~10', level: '쉬움', blurb: '열을 골라 돌을 떨어뜨려 네 개를 먼저 한 줄로! · 사목', available: true },
{ id: 'magical-athlete', nameKo: '야단법석 달리기', minPlayers: 2, maxPlayers: 6, minutes: '20~30', level: '쉬움', blurb: '엉뚱한 능력 선수를 뽑아 주사위 경주 4번! 1·2등만 점수', available: true },
{ id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },