diff --git a/README.md b/README.md index 35ffa17..83d13aa 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,13 @@ 운영 중: https://game.tkrmagid.kr -## 게임 (41개) +## 게임 (46개) | 종류 | 게임 | |---|---| | 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) | | 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 티츄, 젝스님트, 구십구, 바퀴벌레 포커, 뱅! | | 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택, 증강 윷놀이), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 | +| 혼자·퍼즐(같은 판 경주) | 지뢰찾기, 사천성, 솔리테어(클론다이크·프리셀·스파이더), 스도쿠, 네모네모 로직 | | 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 타자 대결, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) | 칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음). @@ -19,7 +20,7 @@ - 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다. - 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다. - 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다. -- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 37개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만. +- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 42개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만. - 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드. - 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드. - 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 라이어 게임 주제·제시어 추가/수정/삭제, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록. diff --git a/apps/server/src/rooms/minesweeper.room.test.ts b/apps/server/src/rooms/minesweeper.room.test.ts new file mode 100644 index 0000000..d001e35 --- /dev/null +++ b/apps/server/src/rooms/minesweeper.room.test.ts @@ -0,0 +1,120 @@ +/** 지뢰찾기 through a real Room: a practice race against a computer, mines never reach my screen, away players (docs/games/minesweeper.md §8.5). */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import type { MinesweeperState, MinesweeperView } from '@bg/games/minesweeper'; +import { botProfile, isBotId, type ServerMessage } from '@bg/shared'; +import { openDb } from '../db'; +import { RoomManager } from './manager'; +import { Room, type Conn } from './room'; +import { RoomStore } from './store'; + +const rooms: Room[] = []; +afterEach(() => { + for (const r of rooms.splice(0)) r.clearTimer(); +}); + +function harness() { + const store = new RoomStore(openDb(':memory:')); + let now = 1_000_000; + const clock = { now: () => now, advance: (ms: number) => (now += ms) }; + const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; + const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 }); + const conn = (userId: string) => { + const msgs: ServerMessage[] = []; + const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; + return c; + }; + return { clock, manager, conn }; +} + +const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract).view as MinesweeperView; + +describe('지뢰찾기 room flow', () => { + test('컴퓨터와 연습: 사람은 안전한 칸을 하나씩 열고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 내 화면에는 지뢰 위치가 없어요', () => { + const h = harness(); + const room = h.manager.createPractice('A', 'minesweeper') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + const bot = room.game!.players.find(isBotId)!; + expect(bot).toBeDefined(); + let cs = 0; + const s = () => room.game!.state as MinesweeperState; + for (let i = 0; i < 4 * 900 && !room.game!.finished; i++) { + h.clock.advance(250); + if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); + const d = room.effectiveDeadline(); + if (d !== null && d <= h.clock.now()) room.onTimer(); + const v = lastView(a); + if (v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing') expect(v.board.cells).not.toMatch(/[*!x]/); + // The person opens the first closed cell next to an opened 0-region every 2 s… or gives up after 60 s. + if (i % 8 === 0 && v.phase === 'playing' && v.board && v.seats.find((x) => x.id === 'A')!.status === 'playing') { + if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' }); + else { + const k = [...v.board.cells].findIndex((ch, j) => ch === '#' && s().puzzle.field[j] !== '*'); + if (k >= 0) room.act('A', ++cs, { type: 'open', i: k }); + } + } + } + expect(room.game!.finished).toBe(true); + expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0); + expect(['solved', 'failed']).toContain(s().status[bot]!); + expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort()); + }); + + test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => { + const h = harness(); + const r = h.manager.create('A', 'minesweeper', 'private'); + if (typeof r === 'string') throw new Error(r); + const room = r as Room; + rooms.push(room); + const a = h.conn('A'); + const b = h.conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.ready('B', true); + expect(room.configure('A', { options: { level: 'beginner', timeLimitSec: 180 } })).toBeNull(); + expect(room.start('A')).toBeNull(); + h.clock.advance(3000); + room.onTimer(); + const s = () => room.game!.state as MinesweeperState; + expect(s().phase).toBe('playing'); + room.disconnect(b); + expect(room.effectiveDeadline()).toBe(s().endsAt); + h.clock.advance(70_000); + room.onTimer(); + expect(s().status.B).toBe('playing'); + h.clock.advance(s().endsAt! - h.clock.now()); + room.onTimer(); + expect(room.game!.finished).toBe(true); + expect(s().final!.endReason).toBe('time'); + }); + + test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => { + const h = harness(); + const r = h.manager.create('A', 'minesweeper', 'private'); + if (typeof r === 'string') throw new Error(r); + const room = r as Room; + rooms.push(room); + const a = h.conn('A'); + const b = h.conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.ready('B', true); + expect(room.configure('A', { options: { level: 'beginner', timeLimitSec: null } })).toBeNull(); + expect(room.start('A')).toBeNull(); + h.clock.advance(3000); + room.onTimer(); + const s = () => room.game!.state as MinesweeperState; + expect(room.effectiveDeadline()).toBeNull(); + room.disconnect(b); + const d = room.effectiveDeadline()!; + h.clock.advance(d - h.clock.now()); + room.onTimer(); + expect(s().status.B).toBe('done'); + expect(room.effectiveDeadline()).toBeNull(); + room.act('A', 1, { type: 'stop' }); + expect(room.game!.finished).toBe(true); + }); +}); diff --git a/apps/server/src/rooms/nonogram.room.test.ts b/apps/server/src/rooms/nonogram.room.test.ts new file mode 100644 index 0000000..35562fb --- /dev/null +++ b/apps/server/src/rooms/nonogram.room.test.ts @@ -0,0 +1,118 @@ +/** 네모네모 로직 through a real Room: a practice race against a computer, the answer never reaches my screen, away players (docs/games/nonogram.md §8). */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import type { NonogramState, NonogramView } from '@bg/games/nonogram'; +import { botProfile, isBotId, type ServerMessage } from '@bg/shared'; +import { openDb } from '../db'; +import { RoomManager } from './manager'; +import { Room, type Conn } from './room'; +import { RoomStore } from './store'; + +const rooms: Room[] = []; +afterEach(() => { + for (const r of rooms.splice(0)) r.clearTimer(); +}); + +function harness() { + const store = new RoomStore(openDb(':memory:')); + let now = 1_000_000; + const clock = { now: () => now, advance: (ms: number) => (now += ms) }; + const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; + const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 }); + const conn = (userId: string) => { + const msgs: ServerMessage[] = []; + const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; + return c; + }; + return { clock, manager, conn }; +} + +const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract).view as NonogramView; + +function twoPlayerRoom(h: ReturnType, timeLimitSec: number | null) { + const r = h.manager.create('A', 'nonogram', 'private'); + if (typeof r === 'string') throw new Error(r); + const room = r as Room; + rooms.push(room); + const a = h.conn('A'); + const b = h.conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.ready('B', true); + expect(room.configure('A', { options: { size: 5, hints: true, timeLimitSec } })).toBeNull(); + expect(room.start('A')).toBeNull(); + h.clock.advance(3000); + room.onTimer(); + return { room, a, b, s: () => room.game!.state as NonogramState }; +} + +describe('nonogram · 네모네모 로직 room flow', () => { + test('컴퓨터와 연습: 사람은 한 줄씩 칠하고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 끝내기 전 내 화면에는 답이 없어요', () => { + const h = harness(); + const room = h.manager.createPractice('A', 'nonogram') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + const bot = room.game!.players.find(isBotId)!; + expect(bot).toBeDefined(); + let cs = 0; + let row = 0; + const s = () => room.game!.state as NonogramState; + for (let i = 0; i < 4 * 1500 && !room.game!.finished; i++) { + h.clock.advance(250); + if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); + const d = room.effectiveDeadline(); + if (d !== null && d <= h.clock.now()) room.onTimer(); + const v = lastView(a); + const mine = v.seats.find((x) => x.id === 'A')!; + if (v.board && mine.status === 'playing') { + expect(v.board.answer).toBeNull(); + expect(JSON.stringify(v)).not.toContain(s().puzzle.solution); + } + // The person fills one row of the answer every 20 s. + if (i % 80 === 0 && v.phase === 'playing' && v.board && mine.status === 'playing' && row < v.board.size) { + const n = v.board.size; + const cells = Array.from({ length: n }, (_, c) => row * n + c).filter((k) => s().puzzle.solution[k] === '#'); + room.act('A', ++cs, { type: 'paint', cells, value: 1 }); + row++; + } + } + expect(room.game!.finished).toBe(true); + expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0); + expect(s().status.A).toBe('solved'); + expect(s().status[bot]).toBe('solved'); + const v = lastView(a); + expect(v.result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort()); + expect(v.board!.answer!.name).toBe(s().puzzle.name); + }); + + test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => { + const h = harness(); + const { room, b, s } = twoPlayerRoom(h, 300); + expect(s().phase).toBe('playing'); + room.disconnect(b); + expect(room.effectiveDeadline()).toBe(s().endsAt); + h.clock.advance(70_000); + room.onTimer(); + expect(s().status.B).toBe('playing'); + h.clock.advance(s().endsAt! - h.clock.now()); + room.onTimer(); + expect(room.game!.finished).toBe(true); + expect(s().final!.endReason).toBe('time'); + }); + + test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => { + const h = harness(); + const { room, b, s } = twoPlayerRoom(h, null); + expect(room.effectiveDeadline()).toBeNull(); + room.disconnect(b); + const d = room.effectiveDeadline()!; + h.clock.advance(d - h.clock.now()); + room.onTimer(); + expect(s().status.B).toBe('done'); + expect(room.effectiveDeadline()).toBeNull(); + room.act('A', 1, { type: 'stop' }); + expect(room.game!.finished).toBe(true); + }); +}); diff --git a/apps/server/src/rooms/shisen.room.test.ts b/apps/server/src/rooms/shisen.room.test.ts new file mode 100644 index 0000000..addc621 --- /dev/null +++ b/apps/server/src/rooms/shisen.room.test.ts @@ -0,0 +1,115 @@ +/** 사천성 through a real Room: a practice race against a computer to the end, away players (docs/games/shisen.md §8). */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import { findPair, type ShisenState, type ShisenView } from '@bg/games/shisen'; +import { botProfile, isBotId, type ServerMessage } from '@bg/shared'; +import { openDb } from '../db'; +import { RoomManager } from './manager'; +import { Room, type Conn } from './room'; +import { RoomStore } from './store'; + +const rooms: Room[] = []; +afterEach(() => { + for (const r of rooms.splice(0)) r.clearTimer(); +}); + +function harness() { + const store = new RoomStore(openDb(':memory:')); + let now = 1_000_000; + const clock = { now: () => now, advance: (ms: number) => (now += ms) }; + const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; + const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 }); + const conn = (userId: string) => { + const msgs: ServerMessage[] = []; + const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; + return c; + }; + return { clock, manager, conn }; +} + +const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract).view as ShisenView; + +function twoPlayers(timeLimitSec: number | null) { + const h = harness(); + const r = h.manager.create('A', 'shisen', 'private'); + if (typeof r === 'string') throw new Error(r); + const room = r as Room; + rooms.push(room); + const a = h.conn('A'); + const b = h.conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.ready('B', true); + expect(room.configure('A', { options: { size: 'small', hints: true, timeLimitSec } })).toBeNull(); + expect(room.start('A')).toBeNull(); + h.clock.advance(3000); + room.onTimer(); + return { h, room, a, b, s: () => room.game!.state as ShisenState }; +} + +describe('사천성 room flow', () => { + test('컴퓨터와 연습: 사람은 2초마다 한 쌍씩 없애다 1분 뒤 포기하고, 컴퓨터는 자기 판을 끝까지 풀어요', () => { + const h = harness(); + const room = h.manager.createPractice('A', 'shisen') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + const bot = room.game!.players.find(isBotId)!; + expect(bot).toBeDefined(); + let cs = 0; + let removed = 0; + const s = () => room.game!.state as ShisenState; + for (let i = 0; i < 4 * 1000 && !room.game!.finished; i++) { + h.clock.advance(250); + if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); + const d = room.effectiveDeadline(); + if (d !== null && d <= h.clock.now()) room.onTimer(); + const v = lastView(a); + if (i % 8 === 0 && v.phase === 'playing' && v.board && v.seats.find((x) => x.id === 'A')!.status === 'playing') { + if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' }); + else { + const p = findPair(v.board.cells, v.board.rows, v.board.cols); + if (p) { + room.act('A', ++cs, { type: 'pair', a: p[0], b: p[1] }); + removed++; + } + } + } + } + expect(room.game!.finished).toBe(true); + expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0); + expect(s().boards.A!.removed).toBe(removed); + expect(removed).toBeGreaterThan(20); + expect(s().status[bot]).toBe('solved'); + expect(lastView(a).result!.ranking.map((r) => r.id)).toEqual([bot, 'A']); + }); + + test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => { + const { h, room, b, s } = twoPlayers(300); + expect(s().phase).toBe('playing'); + room.disconnect(b); + expect(room.effectiveDeadline()).toBe(s().endsAt); + h.clock.advance(70_000); + room.onTimer(); + expect(s().status.B).toBe('playing'); + h.clock.advance(s().endsAt! - h.clock.now()); + room.onTimer(); + expect(room.game!.finished).toBe(true); + expect(s().final!.endReason).toBe('time'); + }); + + test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => { + const { h, room, b, s } = twoPlayers(null); + expect(room.effectiveDeadline()).toBeNull(); + room.disconnect(b); + const d = room.effectiveDeadline()!; + h.clock.advance(d - h.clock.now()); + room.onTimer(); + expect(s().status.B).toBe('done'); + expect(room.effectiveDeadline()).toBeNull(); + room.act('A', 1, { type: 'stop' }); + expect(room.game!.finished).toBe(true); + expect(s().final!.ranking.map((r) => r.status)).toEqual(['done', 'done']); + }); +}); diff --git a/apps/server/src/rooms/solitaire.room.test.ts b/apps/server/src/rooms/solitaire.room.test.ts new file mode 100644 index 0000000..d9c6511 --- /dev/null +++ b/apps/server/src/rooms/solitaire.room.test.ts @@ -0,0 +1,121 @@ +/** 솔리테어 through a real Room: a practice race against a computer, hidden cards never reach my screen, away players (docs/games/solitaire.md §8). */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import { legalOn, type SolitaireState, type SolitaireView } from '@bg/games/solitaire'; +import { botProfile, isBotId, type ServerMessage } from '@bg/shared'; +import { openDb } from '../db'; +import { RoomManager } from './manager'; +import { Room, type Conn } from './room'; +import { RoomStore } from './store'; + +const rooms: Room[] = []; +afterEach(() => { + for (const r of rooms.splice(0)) r.clearTimer(); +}); + +function harness() { + const store = new RoomStore(openDb(':memory:')); + let now = 1_000_000; + const clock = { now: () => now, advance: (ms: number) => (now += ms) }; + const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; + const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 }); + const conn = (userId: string) => { + const msgs: ServerMessage[] = []; + const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; + return c; + }; + return { clock, manager, conn }; +} + +const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract).view as SolitaireView; + +function twoPlayers(h: ReturnType, options: Record) { + const r = h.manager.create('A', 'solitaire', 'private'); + if (typeof r === 'string') throw new Error(r); + const room = r as Room; + rooms.push(room); + const a = h.conn('A'); + const b = h.conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.ready('B', true); + expect(room.configure('A', { options })).toBeNull(); + expect(room.start('A')).toBeNull(); + h.clock.advance(3000); + room.onTimer(); + return { room, a, b, s: () => room.game!.state as SolitaireState }; +} + +describe('solitaire · 솔리테어 room flow', () => { + test('컴퓨터와 연습: 사람은 2초마다 한 수, 1분 뒤 포기하고 컴퓨터는 끝까지 가요. 내 화면에는 뒤집힌 카드와 더미가 없어요', () => { + const h = harness(); + const room = h.manager.createPractice('A', 'solitaire') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + const bot = room.game!.players.find(isBotId)!; + expect(bot).toBeDefined(); + let cs = 0; + let moves = 0; + const s = () => room.game!.state as SolitaireState; + for (let i = 0; i < 4 * 1000 && !room.game!.finished; i++) { + h.clock.advance(250); + if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); + const d = room.effectiveDeadline(); + if (d !== null && d <= h.clock.now()) room.onTimer(); + const v = lastView(a); + const playing = v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing'; + if (playing) { + const b = s().boards.A!; + const json = JSON.stringify(v); + for (const c of [...b.stock, ...b.t.flatMap((col, k) => col.slice(0, b.down[k]))]) expect(json).not.toContain(`"${c}"`); + } + if (i % 8 === 0 && playing) { + if (h.clock.now() - v.countdownEndsAt > 60_000) room.act('A', ++cs, { type: 'stop' }); + else { + const legal = legalOn(v.board!).filter((m) => m.type !== 'undo' && m.type !== 'auto'); + const m = legal.find((x) => x.type === 'move' && x.to === 'f') ?? legal.find((x) => x.type === 'draw') ?? legal[0]; + if (m) { + room.act('A', ++cs, m); + moves++; + } + } + } + } + expect(room.game!.finished).toBe(true); + expect(moves).toBeGreaterThan(10); + expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0); + expect(s().boards[bot]!.hist.length).toBeGreaterThan(0); + expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort()); + }); + + test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => { + const h = harness(); + const { room, b, s } = twoPlayers(h, { mode: 'spider', draw: 1, suits: 2, timeLimitSec: 600 }); + expect(s().phase).toBe('playing'); + room.disconnect(b); + expect(room.effectiveDeadline()).toBe(s().endsAt); + h.clock.advance(70_000); + room.onTimer(); + expect(s().status.B).toBe('playing'); + h.clock.advance(s().endsAt! - h.clock.now()); + room.onTimer(); + expect(room.game!.finished).toBe(true); + expect(s().final!.endReason).toBe('time'); + }); + + test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => { + const h = harness(); + const { room, b, s } = twoPlayers(h, { mode: 'freecell', draw: 1, suits: 1, timeLimitSec: null }); + expect(room.effectiveDeadline()).toBeNull(); + room.disconnect(b); + const d = room.effectiveDeadline()!; + h.clock.advance(d - h.clock.now()); + room.onTimer(); + expect(s().status.B).toBe('done'); + expect(room.effectiveDeadline()).toBeNull(); + room.act('A', 1, { type: 'stop' }); + expect(room.game!.finished).toBe(true); + }); +}); diff --git a/apps/server/src/rooms/sudoku.room.test.ts b/apps/server/src/rooms/sudoku.room.test.ts new file mode 100644 index 0000000..3eb0277 --- /dev/null +++ b/apps/server/src/rooms/sudoku.room.test.ts @@ -0,0 +1,126 @@ +/** 스도쿠 through a real Room: a practice race against a computer, the solution never reaches my screen, away players (docs/games/sudoku.md §8). */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import type { SudokuState, SudokuView } from '@bg/games/sudoku'; +import { botProfile, isBotId, type ServerMessage } from '@bg/shared'; +import { openDb } from '../db'; +import { RoomManager } from './manager'; +import { Room, type Conn } from './room'; +import { RoomStore } from './store'; + +const rooms: Room[] = []; +afterEach(() => { + for (const r of rooms.splice(0)) r.clearTimer(); +}); + +function harness() { + const store = new RoomStore(openDb(':memory:')); + let now = 1_000_000; + const clock = { now: () => now, advance: (ms: number) => (now += ms) }; + const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; + const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 }); + const conn = (userId: string) => { + const msgs: ServerMessage[] = []; + const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; + return c; + }; + return { clock, manager, conn }; +} + +const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m) => m.t === 'state').at(-1) as Extract).view as SudokuView; + +describe('sudoku room flow', () => { + test('컴퓨터와 연습: 사람은 맞는 숫자를 하나씩 넣고, 컴퓨터도 자기 판을 풀어 끝까지 가요. 다 풀기 전 내 화면에는 정답이 없어요', () => { + const h = harness(); + const room = h.manager.createPractice('A', 'sudoku') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + const bot = room.game!.players.find(isBotId)!; + expect(bot).toBeDefined(); + let cs = 0; + const s = () => room.game!.state as SudokuState; + for (let i = 0; i < 4 * 1900 && !room.game!.finished; i++) { + h.clock.advance(250); + if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); + const d = room.effectiveDeadline(); + if (d !== null && d <= h.clock.now()) room.onTimer(); + const v = lastView(a); + const playing = v.board && v.phase === 'playing' && v.seats.find((x) => x.id === 'A')!.status === 'playing'; + if (playing) { + expect(v.board!.solution).toBeUndefined(); + expect(JSON.stringify(v)).not.toContain(s().puzzle.solution); + } + // The person fills the first empty cell with the right number every 2 s. + if (i % 8 === 0 && playing) { + const k = v.board!.values.indexOf('0'); + if (k >= 0) room.act('A', ++cs, { type: 'set', i: k, n: Number(s().puzzle.solution[k]) }); + } + } + expect(room.game!.finished).toBe(true); + expect(a.msgs.filter((m) => m.t === 'reject')).toHaveLength(0); + expect(s().status.A).toBe('solved'); + expect(s().status[bot]).toBe('solved'); + expect(lastView(a).board!.solution).toBe(s().puzzle.solution); + expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort()); + }); + + test('제한 시간: 연결이 끊긴 사람은 일찍 시간 초과되지 않고, 마감에 서버 시계로 끝나요', () => { + const h = harness(); + const r = h.manager.create('A', 'sudoku', 'private'); + if (typeof r === 'string') throw new Error(r); + const room = r as Room; + rooms.push(room); + const a = h.conn('A'); + const b = h.conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.ready('B', true); + expect(room.configure('A', { options: { difficulty: 'easy', hints: true, timeLimitSec: 600 } })).toBeNull(); + expect(room.start('A')).toBeNull(); + h.clock.advance(3000); + room.onTimer(); + const s = () => room.game!.state as SudokuState; + expect(s().phase).toBe('playing'); + room.disconnect(b); + expect(room.effectiveDeadline()).toBe(s().endsAt); + h.clock.advance(70_000); + room.onTimer(); + expect(s().status.B).toBe('playing'); + h.clock.advance(s().endsAt! - h.clock.now()); + room.onTimer(); + expect(room.game!.finished).toBe(true); + expect(s().final!.endReason).toBe('time'); + }); + + test('무제한: 끊긴 사람은 유예 뒤 한 번만 포기 처리, 남은 사람이 포기하면 끝', () => { + const h = harness(); + const r = h.manager.create('A', 'sudoku', 'private'); + if (typeof r === 'string') throw new Error(r); + const room = r as Room; + rooms.push(room); + const a = h.conn('A'); + const b = h.conn('B'); + room.join(a, 'player'); + room.join(b, 'player'); + room.ready('B', true); + expect(room.configure('A', { options: { difficulty: 'normal', hints: false, timeLimitSec: null } })).toBeNull(); + expect(room.start('A')).toBeNull(); + h.clock.advance(3000); + room.onTimer(); + const s = () => room.game!.state as SudokuState; + expect(room.effectiveDeadline()).toBeNull(); + room.disconnect(b); + const d = room.effectiveDeadline()!; + h.clock.advance(d - h.clock.now()); + room.onTimer(); + expect(s().status.B).toBe('done'); + expect(room.effectiveDeadline()).toBeNull(); + h.clock.advance(60_000); + room.onTimer(); + expect(s().status.A).toBe('playing'); + room.act('A', 1, { type: 'stop' }); + expect(room.game!.finished).toBe(true); + }); +}); diff --git a/apps/web/src/games/help.test.ts b/apps/web/src/games/help.test.ts index 8d7852a..0da3209 100644 --- a/apps/web/src/games/help.test.ts +++ b/apps/web/src/games/help.test.ts @@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti const IDS = Object.keys(GAME_UI); test('모든 게임에 도움말이 있어요', () => { - expect(IDS).toHaveLength(41); + expect(IDS).toHaveLength(46); for (const id of IDS) { const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8'); expect(src, id).toMatch(/\bquickStart,/); diff --git a/apps/web/src/games/minesweeper/art.tsx b/apps/web/src/games/minesweeper/art.tsx new file mode 100644 index 0000000..7a33070 --- /dev/null +++ b/apps/web/src/games/minesweeper/art.tsx @@ -0,0 +1,60 @@ +/** 지뢰찾기 cell pictures (SVG, no image files). */ + +/** SVG units per cell. */ +export const S = 32; +const NUM_COLOR = ['', '#1d4ed8', '#15803d', '#dc2626', '#1e3a8a', '#7f1d1d', '#0f766e', '#111827', '#6b7280']; + +function Flag({ x, y, wrong }: { x: number; y: number; wrong?: boolean }) { + return ( + + + + + {wrong && } + + ); +} + +function Mine({ x, y }: { x: number; y: number }) { + return ( + + + + + + ); +} + +/** Small stand-alone pictures for rules and help cards. */ +export function MiniCell({ ch, size = 30 }: { ch: string; size?: number }) { + return ( + + + + ); +} + +export function CellArt({ ch, x, y, cls, i }: { ch: string; x: number; y: number; cls?: string; i?: number }) { + const closed = ch === '#' || ch === 'F' || ch === 'x'; + return ( + + {closed ? ( + <> + + + + + ) : ( + + )} + {(ch === 'F' || ch === 'x') && } + {(ch === '*' || ch === '!') && } + {ch >= '1' && ch <= '8' && ( + + {ch} + + )} + + ); +} + diff --git a/apps/web/src/games/minesweeper/help.ts b/apps/web/src/games/minesweeper/help.ts new file mode 100644 index 0000000..c3fd9a0 --- /dev/null +++ b/apps/web/src/games/minesweeper/help.ts @@ -0,0 +1,17 @@ +/** 지뢰찾기 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { MinesweeperView } from '@bg/games/minesweeper'; +import type { PublicUser } from '@bg/shared/lite'; +import { raceHelp } from '../race/text'; + +const HOW = [ + '연 칸의 숫자는 그 칸을 둘러싼 8칸에 있는 지뢰 수예요. 지뢰가 없는 칸을 모두 열면 다 푼 거예요.', + '지뢰가 확실한 칸에는 깃발을 꽂아요(PC 오른쪽 클릭, 휴대폰 길게 누르기). 깃발 수가 숫자와 같아진 숫자 칸을 누르면 주변을 한꺼번에 열어요.', + '지뢰를 밟으면 그 판은 끝이에요.', + '키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 열기, F로 깃발이에요.', +]; + +export function helpNow(v: MinesweeperView, me: string | null, players: Record): string { + const lines = raceHelp(v, me, players, HOW, '지뢰를 밟았어요.'); + if (v.board && v.phase === 'playing') return `${lines}\n남은 지뢰(전체 지뢰 − 내 깃발)는 ${v.board.mines - v.board.flags}개예요.`; + return lines; +} diff --git a/apps/web/src/games/minesweeper/index.tsx b/apps/web/src/games/minesweeper/index.tsx new file mode 100644 index 0000000..00ad33b --- /dev/null +++ b/apps/web/src/games/minesweeper/index.tsx @@ -0,0 +1,321 @@ +/** 지뢰찾기 화면 (docs/games/minesweeper.md §9). */ +import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'; +import { LEVELS, type Level, type MinesweeperOptions, type MinesweeperView } from '@bg/games/minesweeper'; +import type { PublicUser } from '@bg/shared/lite'; +import { haptic, noise, sfx, tone } from '../../lib/feedback'; +import { fxMs } from '../../lib/motion'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit'; +import { helpNow } from './help'; +import { quickStart } from './quick'; +import { CellArt, MiniCell, S } from './art'; + +const FAIL = '지뢰를 밟았어요!'; +const LONG_PRESS_MS = 420; + +type Cell = [number, number]; +const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x)); + +const CSS = ` +.ms-board { display: block; width: 100%; height: auto; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation; + border-radius: 10px; background: #9ca3af; box-shadow: var(--shadow); outline: none; cursor: pointer; } +.ms-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); } +.ms-board[data-off='true'] { cursor: default; } +.ms-new { animation: ms-in .28s ease-out both; transform-box: fill-box; transform-origin: center; } +.ms-boom { animation: ms-boom .6s ease-out both; transform-box: fill-box; transform-origin: center; } +@keyframes ms-in { from { opacity: 0; transform: scale(.6); } } +@keyframes ms-boom { 0% { transform: scale(.4); } 40% { transform: scale(1.3); } 100% { transform: scale(1); } } +@media (prefers-reduced-motion: reduce) { .ms-new, .ms-boom { animation: none; } } +`; + +const describeCh = (ch: string) => + ch === '#' ? '닫힌 칸' : ch === 'F' ? '깃발' : ch === '0' ? '빈 칸' : ch === '*' ? '지뢰' : ch === '!' ? '터진 지뢰' : ch === 'x' ? '잘못 꽂은 깃발' : `숫자 ${ch}`; + +function MinesBoard({ view: v, me, players, act }: BoardProps) { + const { now, left, elapsed, countdown, mine } = useRaceClock(v, me); + const phone = useNarrow(); + const b = v.board; + const [flagMode, setFlagMode] = useState(false); + const [cursor, setCursor] = useState(0); + const [focused, setFocused] = useState(false); + const [fresh, setFresh] = useState>(new Set()); + const [announce, setAnnounce] = useState(''); + const svgRef = useRef(null); + const press = useRef<{ i: number; x: number; y: number; timer: ReturnType | null; long: boolean; button: number } | null>(null); + const prev = useRef(null); + const playing = canPlayNow(v, me, now); + + // Newly opened cells pop in; sounds for what changed. + useEffect(() => { + const cur = b?.cells ?? null; + const was = prev.current; + prev.current = cur; + if (!cur || !was || was.length !== cur.length) return; + const added = new Set(); + let flagged = 0; + for (let i = 0; i < cur.length; i++) { + if (was[i] === '#' && cur[i]! >= '0' && cur[i]! <= '8') added.add(i); + if (was[i] !== cur[i] && (cur[i] === 'F' || was[i] === 'F') && cur[i] !== '*') flagged++; + } + if (cur.includes('!') && !was.includes('!')) { + noise(500, 0.2, 0, 'lowpass', 400, 0.7); + haptic([30, 40, 60]); + } else if (added.size > 8) sfx.whoosh(); + else if (added.size) tone(900, 40, 'triangle', 0.1); + else if (flagged === 1) tone(640, 50, 'square', 0.05); + if (added.size) { + setFresh(added); + const t = setTimeout(() => setFresh(new Set()), fxMs(320)); + return () => clearTimeout(t); + } + }, [b?.cells]); + + if (!b) { + return ( +
+ + + +
+ + +
+
+ ); + } + + const turn = phone && b.cols > b.rows; + const dR = turn ? b.cols : b.rows; + const dC = turn ? b.rows : b.cols; + const toDisp = (i: number): Cell => { + const r = Math.floor(i / b.cols); + const c = i % b.cols; + return turn ? [c, b.rows - 1 - r] : [r, c]; + }; + const toIndex = (dr: number, dc: number) => (turn ? (b.rows - 1 - dc) * b.cols + dr : dr * b.cols + dc); + const cellAt = (e: { clientX: number; clientY: number }) => { + const box = svgRef.current!.getBoundingClientRect(); + const dc = clamp(Math.floor(((e.clientX - box.left) / box.width) * dC), 0, dC - 1); + const dr = clamp(Math.floor(((e.clientY - box.top) / box.height) * dR), 0, dR - 1); + return toIndex(dr, dc); + }; + + const describe = (i: number) => { + const [dr, dc] = toDisp(i); + return `${dr + 1}줄 ${dc + 1}칸, ${describeCh(b.cells[i]!)}`; + }; + /** Primary action on a cell: open a closed one, open around a number, or flag (깃발 mode / right click / long press). */ + const hit = (i: number, flag: boolean) => { + if (!playing) return; + const ch = b.cells[i]!; + if (flag) { + if (ch === '#' || ch === 'F') { + act({ type: 'flag', i }); + haptic(10); + setAnnounce(ch === 'F' ? '깃발을 치웠어요.' : '깃발을 꽂았어요.'); + } + return; + } + if (ch === '#') act({ type: 'open', i }); + else if (ch >= '1' && ch <= '8') { + // A number opens the cells around it once its flags match. + let flags = 0; + let closed = 0; + const r = Math.floor(i / b.cols); + const c = i % b.cols; + for (let y = r - 1; y <= r + 1; y++) + for (let x = c - 1; x <= c + 1; x++) { + if (y < 0 || x < 0 || y >= b.rows || x >= b.cols || (y === r && x === c)) continue; + const k = b.cells[y * b.cols + x]; + if (k === 'F') flags++; + else if (k === '#') closed++; + } + if (closed && flags === Number(ch)) act({ type: 'chord', i }); + else if (closed) setAnnounce(`주변 깃발이 ${flags}개예요. ${ch}개를 꽂아야 한꺼번에 열 수 있어요.`); + } else if (ch === 'F') setAnnounce('깃발을 꽂은 칸이에요. 깃발 모드나 오른쪽 클릭으로 치워요.'); + }; + + const onDown = (e: ReactPointerEvent) => { + if (!playing) return; + const i = cellAt(e); + setCursor(i); + const p = { i, x: e.clientX, y: e.clientY, timer: null as ReturnType | null, long: false, button: e.button }; + if (e.pointerType !== 'mouse') + p.timer = setTimeout(() => { + p.long = true; + hit(p.i, !flagMode); + }, LONG_PRESS_MS); + press.current = p; + }; + const onMove = (e: ReactPointerEvent) => { + const p = press.current; + if (p && Math.hypot(e.clientX - p.x, e.clientY - p.y) > 10) { + if (p.timer) clearTimeout(p.timer); + press.current = null; // scrolling, not a tap + } + }; + const onUp = (e: ReactPointerEvent) => { + const p = press.current; + press.current = null; + if (!p) return; + if (p.timer) clearTimeout(p.timer); + if (p.long) return; + if (cellAt(e) !== p.i) return; + hit(p.i, p.button === 2 || flagMode); + }; + + const onKey = (e: ReactKeyboardEvent) => { + const step: Record = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] }; + const m = step[e.key]; + if (m) { + e.preventDefault(); + const [dr, dc] = toDisp(cursor); + const next = toIndex(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1)); + setCursor(next); + setAnnounce(describe(next)); + return; + } + if (e.key === ' ' || e.key === 'Enter') { + e.preventDefault(); + if (!e.repeat) hit(cursor, flagMode); + } else if (e.key === 'f' || e.key === 'F' || e.key === 'ㄹ') { + e.preventDefault(); + hit(cursor, true); + } + }; + + const [cr, cc] = toDisp(cursor); + const wrapStyle: CSSProperties = phone + ? { width: '100%' } + : { width: `min(100%, ${dC * 56}px, calc((var(--play-h, 100vh) - 170px) * ${dC / dR}))`, minWidth: Math.min(280, dC * 22) }; + + return ( +
+ + + + 💣 {b.mines - b.flags} + + {mine && v.phase === 'playing' && ( + + )} + + +
+ { + if (press.current?.timer) clearTimeout(press.current.timer); + press.current = null; + }} + onKeyDown={onKey} + onFocus={() => setFocused(true)} + onBlur={() => setFocused(false)} + onContextMenu={(e) => e.preventDefault()} + > + {Array.from(b.cells, (ch, i) => { + const [dr, dc] = toDisp(i); + return ; + })} + {focused && playing && } + + +
+ {mine && playing && ( +
+ +
+ )} + {!phone && mine && v.phase !== 'ended' &&

왼쪽 클릭: 열기(숫자는 주변 한꺼번에) · 오른쪽 클릭: 깃발 · 키보드: 화살표 + 스페이스, F 깃발

} + {phone && mine && playing &&

누르기: {flagMode ? '깃발' : '열기'} · 길게 누르기: {flagMode ? '열기' : '깃발'} · 숫자를 누르면 주변을 한꺼번에 열어요

} +

+ {announce} +

+
+ ); +} + +const levelInfo = (l: Level) => `${LEVELS[l].name} ${LEVELS[l].rows}×${LEVELS[l].cols} · 지뢰 ${LEVELS[l].mines}`; + +function MinesSide(props: BoardProps) { + return ; +} + +function statusText(v: MinesweeperView, me: string | null, players: Record): string { + return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자를 보고 지뢰를 피해 칸을 열어요', playing: '숫자는 주변 8칸의 지뢰 수예요 · 지뢰 없는 칸을 모두 열어요', failed: FAIL }); +} + +function Options({ value: o, onChange }: OptionsProps) { + return ( +
+
+ 난이도 + [l, LEVELS[l].name])} + onChange={(level) => onChange({ ...o, level })} + /> + {levelInfo(o.level)} +
+ onChange({ ...o, timeLimitSec: timeLimitSec as MinesweeperOptions['timeLimitSec'] })} /> +
+ ); +} + +function optionsSummary(o: MinesweeperOptions): string { + return `${levelInfo(o.level)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`; +} + +function Rules({ options }: { options?: MinesweeperOptions }) { + const level = options?.level ?? 'beginner'; + return ( +
+

+ 판 아래에 지뢰가 숨어 있어요. 지뢰가 없는 칸을 모두 열면 이겨요. 모두 똑같은 판을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요. +

+
+ + + + 연 칸의 숫자 = 그 칸을 둘러싼 8칸에 있는 지뢰 수 +
+

+ 시작할 때 지뢰가 없는 한 곳이 모두에게 똑같이 열려 있어요. 숫자를 보고 지뢰가 확실한 칸에는 깃발을 꽂고, 안전한 칸을 열어요. 주변이 비어 있는 칸(0)을 열면 이어진 칸이 + 한꺼번에 열려요. 깃발 수가 숫자와 같아진 숫자 칸을 누르면 남은 주변 칸을 한꺼번에 열어요(깃발이 틀렸으면 지뢰가 터져요). +

+

+ 지뢰를 밟으면 그 판은 끝이에요. 여럿이면 가장 먼저 다 연 사람이 이기고, 아무도 못 열면 연 칸이 많은 사람이 이겨요(지뢰를 밟은 사람도 그때까지 연 칸으로 셈). 제한 시간은{' '} + {limitLabel(options ? options.timeLimitSec : 600)}이고, 지금 난이도는 {levelInfo(level)}이에요. +

+

PC: 왼쪽 클릭 열기, 오른쪽 클릭 깃발. 휴대폰: 누르면 열기, 길게 누르면 깃발(위의 [⛏ 칸 열기] 버튼으로 바꿀 수 있어요). 키보드: 화살표로 옮기고 스페이스로 열기, F로 깃발.

+
+ ); +} + +const ui: GameUI = { + Board: MinesBoard, + Side: MinesSide, + statusText, + liveStatus: true, + isMyTurn: raceIsMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/minesweeper/quick.tsx b/apps/web/src/games/minesweeper/quick.tsx new file mode 100644 index 0000000..186f44d --- /dev/null +++ b/apps/web/src/games/minesweeper/quick.tsx @@ -0,0 +1,38 @@ +/** 지뢰찾기 30초 규칙 요약 (docs/07 §5). Small boards drawn with the game's own cells. */ +import type { QuickCard } from '../types'; +import { MiniCell } from './art'; + +function Grid({ rows }: { rows: string[] }) { + return ( + + {rows.flatMap((row, r) => + [...row].map((ch, c) => ( + + + + )), + )} + + ); +} + +export const quickStart: QuickCard[] = [ + { + pic: , + alt: '닫힌 칸 사이에 숫자 1이 적힌 연 칸들이 있어요', + title: '숫자 = 주변 지뢰 수', + text: '연 칸의 숫자는 둘러싼 8칸에 있는 지뢰 수예요. 모두 똑같은 판을 각자 풀어요.', + }, + { + pic: , + alt: '지뢰가 확실한 칸에 빨간 깃발을 꽂은 모습이에요', + title: '지뢰에는 깃발', + text: '지뢰가 확실한 칸에 깃발을 꽂아요(오른쪽 클릭, 휴대폰은 길게 누르기). 지뢰를 밟으면 끝이에요.', + }, + { + pic: , + alt: '지뢰 칸만 남기고 모든 칸이 열렸어요', + title: '모든 칸을 열면 승리', + text: '지뢰 없는 칸을 모두 열면 다 푼 거예요. 여럿이면 가장 먼저 다 연 사람이 이겨요.', + }, +]; diff --git a/apps/web/src/games/nonogram/art.tsx b/apps/web/src/games/nonogram/art.tsx new file mode 100644 index 0000000..037a62e --- /dev/null +++ b/apps/web/src/games/nonogram/art.tsx @@ -0,0 +1,53 @@ +/** 네모네모 로직 small pictures for the rules and the 30-second cards (SVG, no image files). */ + +/** Run lengths of the '#' cells; an empty line is [0]. */ +export function runsOf(line: string): number[] { + const out = line.split(/[^#]+/).filter(Boolean).map((s) => s.length); + return out.length ? out : [0]; +} + +/** + * A small puzzle: clues from `answer`, cells from `marks` ('#' filled, 'x' X, '.' empty; default = the answer). + * `color` paints the filled cells (a solved picture). + */ +export function MiniNono({ answer, marks = answer, color, cell = 22 }: { answer: string[]; marks?: string[]; color?: string; cell?: number }) { + const n = answer.length; + const S = 20; + const rows = answer.map(runsOf); + const cols = Array.from({ length: n }, (_, c) => runsOf(answer.map((r) => r[c]).join(''))); + const left = Math.max(...rows.map((r) => r.length)) * 12 + 6; + const top = Math.max(...cols.map((c) => c.length)) * 13 + 4; + const w = left + n * S; + const h = top + n * S; + return ( + + {cols.map((clue, c) => + clue.map((x, j) => ( + + {x} + + )), + )} + {rows.map((clue, r) => + clue.map((x, j) => ( + + {x} + + )), + )} + {marks.flatMap((row, r) => + [...row].map((ch, c) => { + const x = left + c * S; + const y = top + r * S; + return ( + + + {ch === 'x' && } + + ); + }), + )} + + + ); +} diff --git a/apps/web/src/games/nonogram/help.ts b/apps/web/src/games/nonogram/help.ts new file mode 100644 index 0000000..a8c5b6b --- /dev/null +++ b/apps/web/src/games/nonogram/help.ts @@ -0,0 +1,18 @@ +/** 네모네모 로직 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { NonogramView } from '@bg/games/nonogram'; +import type { PublicUser } from '@bg/shared/lite'; +import { raceHelp } from '../race/text'; + +const HOW = [ + '줄 옆의 숫자는 그 줄에서 이어서 칠할 칸 수예요. 숫자가 여러 개면 그 순서대로, 덩어리 사이는 한 칸 이상 띄어요.', + '모든 가로줄과 세로줄이 숫자와 맞게 칠하면 그림이 나오고 다 푼 거예요. 칠한 칸이 맞는지는 알려 주지 않아요.', + '비어야 할 칸에는 ✕를 해 두면 헷갈리지 않아요(PC 오른쪽 클릭, 휴대폰은 [✕ 표시]로 바꿔서). 끌면 한 줄을 한 번에 칠해요.', + '키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 칠하기, X로 ✕ 표시예요.', +]; + +export function helpNow(v: NonogramView, me: string | null, players: Record): string { + const lines = raceHelp(v, me, players, HOW, ''); + if (v.board && v.phase === 'playing' && v.options.hints && v.seats.some((s) => s.id === me && s.status === 'playing')) + return `${lines}\n막히면 [💡 힌트]로 틀렸거나 모르는 칸 하나를 바르게 고칠 수 있어요(쓴 횟수는 결과에 나와요). 지금까지 ${v.board.hints}번 썼어요.`; + return lines; +} diff --git a/apps/web/src/games/nonogram/index.tsx b/apps/web/src/games/nonogram/index.tsx new file mode 100644 index 0000000..74e04f9 --- /dev/null +++ b/apps/web/src/games/nonogram/index.tsx @@ -0,0 +1,412 @@ +/** 네모네모 로직 화면 (docs/games/nonogram.md §9). */ +import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'; +import type { MarkValue, NonogramOptions, NonogramSize, NonogramView } from '@bg/games/nonogram'; +import type { PublicUser } from '@bg/shared/lite'; +import { haptic, sfx, tone } from '../../lib/feedback'; +import { fxMs } from '../../lib/motion'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit'; +import { helpNow } from './help'; +import { quickStart } from './quick'; +import { MiniNono, runsOf } from './art'; + +/** SVG units per cell. */ +const S = 20; +const SIZE_NAME: Record = { 5: '쉬움', 10: '보통', 15: '어려움' }; +const sizeInfo = (n: NonogramSize) => `${n}×${n} ${SIZE_NAME[n]}`; +const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x)); +const MARK_WORD: Record = { '0': '빈 칸', '1': '칠한 칸', '2': '✕ 표시' }; + +const CSS = ` +.ng-board { display: block; width: 100%; height: auto; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: none; + border-radius: 10px; background: var(--surface); box-shadow: var(--shadow); outline: none; cursor: crosshair; } +.ng-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); } +.ng-board[data-off='true'] { cursor: default; } +.ng-clue { font-weight: 800; fill: var(--text); transition: opacity .3s; } +.ng-clue[data-ok='true'] { opacity: .3; } +.ng-new { animation: ng-in .22s ease-out both; transform-box: fill-box; transform-origin: center; } +.ng-color { animation: ng-color .7s ease-out both; transform-box: fill-box; transform-origin: center; } +.ng-hint { animation: ng-hint 1.2s ease-out 2 both; transform-box: fill-box; transform-origin: center; } +.ng-title { font-weight: 900; font-size: 1.15rem; color: var(--success); margin: 0; text-align: center; } +.ng-title.ans { color: var(--text-sub); font-size: 1rem; } +@keyframes ng-in { from { transform: scale(.4); } } +@keyframes ng-color { 0% { fill: var(--text); transform: scale(1); } 40% { transform: scale(1.12); } 100% { transform: scale(1); } } +@keyframes ng-hint { 0% { opacity: 1; stroke-width: 4; } 100% { opacity: .2; stroke-width: 2; } } +@media (prefers-reduced-motion: reduce) { .ng-new, .ng-color, .ng-hint { animation: none; } .ng-clue { transition: none; } } +`; + +interface Drag { + start: number; + end: number; + axis: 'row' | 'col' | null; + /** The mark the first cell had: the drag only changes cells that have it too. */ + from: string; + value: MarkValue; +} + +function NonoBoard({ view: v, me, players, act }: BoardProps) { + const { now, left, elapsed, countdown, mine } = useRaceClock(v, me); + const phone = useNarrow(); + const b = v.board; + const [mode, setMode] = useState<1 | 2>(1); + const [cursor, setCursor] = useState(0); + const [focused, setFocused] = useState(false); + const [drag, setDrag] = useState(null); + const [fresh, setFresh] = useState>(new Set()); + const [announce, setAnnounce] = useState(''); + const svgRef = useRef(null); + const prev = useRef<{ marks: string; ok: number; hint: number | null } | null>(null); + const playing = canPlayNow(v, me, now); + + const n = b?.size ?? 10; + const rowClues = (b?.rows ?? []).map((c) => (c.length ? c : [0])); + const colClues = (b?.cols ?? []).map((c) => (c.length ? c : [0])); + const lineOf = (line: number) => (line < n ? Array.from({ length: n }, (_, c) => line * n + c) : Array.from({ length: n }, (_, r) => r * n + line - n)); + const okLines = b ? [...rowClues, ...colClues].map((clue, line) => runsOf(lineOf(line).map((i) => (b.marks[i] === '1' ? '#' : '.')).join('')).join() === clue.join()) : []; + const okCount = okLines.filter(Boolean).length; + + // Sounds and the pop of newly marked cells; say when a line comes right. + useEffect(() => { + if (!b) return; + const was = prev.current; + prev.current = { marks: b.marks, ok: okCount, hint: b.lastHint }; + if (!was || was.marks.length !== b.marks.length) return; + const changed = new Set(); + let filled = 0; + let crossed = 0; + for (let i = 0; i < b.marks.length; i++) { + if (was.marks[i] === b.marks[i]) continue; + changed.add(i); + if (b.marks[i] === '1') filled++; + else if (b.marks[i] === '2') crossed++; + } + if (b.lastHint !== was.hint && b.hints) sfx.pop(); + else if (okCount > was.ok) tone(1175, 90, 'triangle', 0.09); + else if (filled) tone(820, 40, 'triangle', 0.1); + else if (crossed) tone(520, 40, 'square', 0.04); + else if (changed.size) tone(400, 40, 'sine', 0.06); + if (okCount !== was.ok) setAnnounce(`맞는 줄 ${okCount}/${2 * n}`); + if (changed.size) { + setFresh(changed); + const t = setTimeout(() => setFresh(new Set()), fxMs(260)); + return () => clearTimeout(t); + } + }, [b?.marks, b?.lastHint]); + + if (!b) { + return ( +
+ + + +
+ + +
+
+ ); + } + + // Layout in SVG units: row clues on the left, column clues on top, then the grid. + const numW = (x: number) => (x >= 10 ? 0.95 : 0.62) * S; + const L = Math.max(...rowClues.map((c) => c.reduce((a, x) => a + numW(x), 0))) + 0.4 * S; + const T = Math.max(...colClues.map((c) => c.length)) * 0.72 * S + 0.35 * S; + const W = L + n * S; + const H = T + n * S; + const answer = b.answer; + + const cellAt = (e: { clientX: number; clientY: number }, inside: boolean): number | null => { + const box = svgRef.current!.getBoundingClientRect(); + const k = W / box.width; + const c = Math.floor(((e.clientX - box.left) * k - L) / S); + const r = Math.floor(((e.clientY - box.top) * k - T) / S); + if (inside && (c < 0 || r < 0 || c >= n || r >= n)) return null; + return clamp(r, 0, n - 1) * n + clamp(c, 0, n - 1); + }; + const dragCells = (d: Drag): number[] => { + const r0 = Math.floor(d.start / n); + const c0 = d.start % n; + const out: number[] = []; + if (d.axis === 'row') { + const c1 = d.end % n; + for (let c = c0; ; c += Math.sign(c1 - c0)) { + out.push(r0 * n + c); + if (c === c1) break; + } + } else if (d.axis === 'col') { + const r1 = Math.floor(d.end / n); + for (let r = r0; ; r += Math.sign(r1 - r0)) { + out.push(r * n + c0); + if (r === r1) break; + } + } else out.push(d.start); + return out.filter((i) => b.marks[i] === d.from); + }; + const valueFor = (i: number, m: 1 | 2): MarkValue => (b.marks[i] === String(m) ? 0 : m); + const paint = (cells: number[], value: MarkValue) => { + if (!playing || !cells.length) return; + act({ type: 'paint', cells, value }); + haptic(8); + }; + + const onDown = (e: ReactPointerEvent) => { + if (!playing || (e.pointerType === 'mouse' && e.button !== 0 && e.button !== 2)) return; + const i = cellAt(e, true); + if (i === null) return; + e.preventDefault(); + svgRef.current!.setPointerCapture?.(e.pointerId); + setCursor(i); + setDrag({ start: i, end: i, axis: null, from: b.marks[i]!, value: valueFor(i, e.button === 2 ? 2 : mode) }); + }; + const onMove = (e: ReactPointerEvent) => { + if (!drag) return; + const i = cellAt(e, false)!; + const r = Math.floor(i / n); + const c = i % n; + const r0 = Math.floor(drag.start / n); + const c0 = drag.start % n; + if (i === drag.start && !drag.axis) return; + // The first step away from the start cell decides the row or column; then the line follows the pointer along it. + const axis = drag.axis ?? (r === r0 ? 'row' : c === c0 ? 'col' : Math.abs(c - c0) >= Math.abs(r - r0) ? 'row' : 'col'); + const end = axis === 'row' ? r0 * n + c : r * n + c0; + if (end !== drag.end || axis !== drag.axis) setDrag({ ...drag, axis, end }); + }; + const onUp = () => { + if (!drag) return; + setDrag(null); + paint(dragCells(drag), drag.value); + }; + + const describe = (i: number) => { + const r = Math.floor(i / n); + const c = i % n; + return `${r + 1}줄 ${c + 1}칸, ${MARK_WORD[b.marks[i]!]}. 가로 숫자 ${rowClues[r]!.join(' ')}, 세로 숫자 ${colClues[c]!.join(' ')}`; + }; + const onKey = (e: ReactKeyboardEvent) => { + const step: Record = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] }; + const m = step[e.key]; + if (m) { + e.preventDefault(); + const next = clamp(Math.floor(cursor / n) + m[0], 0, n - 1) * n + clamp((cursor % n) + m[1], 0, n - 1); + setCursor(next); + setAnnounce(describe(next)); + return; + } + if (e.key === ' ' || e.key === 'Enter') { + e.preventDefault(); + if (!e.repeat) paint([cursor], valueFor(cursor, 1)); + } else if (e.key === 'x' || e.key === 'X' || e.key === 'ㅌ') { + e.preventDefault(); + if (!e.repeat) paint([cursor], valueFor(cursor, 2)); + } + }; + + const preview = new Map(); + if (drag) for (const i of dragCells(drag)) preview.set(i, drag.value); + const cr = Math.floor(cursor / n); + const cc = cursor % n; + const showCursor = focused && playing; + const wrapStyle: CSSProperties = phone + ? { width: '100%' } + : { width: `min(100%, ${Math.round((W / S) * 40)}px, calc((var(--play-h, 100vh) - 230px) * ${(W / H).toFixed(3)}))`, minWidth: Math.min(320, (W / S) * 24) }; + const fill = (i: number) => { + if (answer) return answer.solution[i] === '#' ? answer.color : 'var(--surface)'; + const m = preview.get(i) ?? Number(b.marks[i]); + return m === 1 ? 'var(--text)' : 'var(--surface)'; + }; + const xMark = (i: number) => !answer && (preview.get(i) ?? Number(b.marks[i])) === 2; + const solvedByMe = mine?.status === 'solved'; + + return ( +
+ + + + ✔ {okCount}/{2 * n} + + {mine && playing && ( + <> + + + {v.options.hints && ( + + )} + + )} + + + {answer && ( +

+ {solvedByMe ? `다 풀었어요! ${answer.name}` : `정답 그림: ${answer.name}`} +

+ )} +
+ setDrag(null)} + onKeyDown={onKey} + onFocus={() => setFocused(true)} + onBlur={() => setFocused(false)} + onContextMenu={(e) => e.preventDefault()} + > + + + {showCursor && ( + <> + + + + )} + {colClues.map((clue, c) => + clue.map((x, j) => ( + + {x} + + )), + )} + {rowClues.map((clue, r) => { + let x = L - 0.25 * S; + return [...clue].reverse().map((num, j) => { + const at = x - numW(num) / 2; + x -= numW(num); + return ( + + {num} + + ); + }); + })} + {Array.from(b.marks, (ch, i) => { + const x = L + (i % n) * S; + const y = T + Math.floor(i / n) * S; + const colored = !!answer && answer.solution[i] === '#'; + return ( + + + {xMark(i) && } + + ); + })} + {Array.from({ length: n + 1 }, (_, k) => { + const thick = k % 5 === 0 || k === n; + const style = { stroke: thick ? 'var(--text-sub)' : 'var(--border)', strokeWidth: thick ? 1.4 : 0.6 }; + return ( + + + + + ); + })} + {!answer && b.lastHint !== null && ( + + )} + {showCursor && } + + +
+ {mine && playing && ( +
+ +
+ )} + {!phone && mine && v.phase !== 'ended' &&

왼쪽 클릭·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 오른쪽 클릭·끌기: ✕ 표시 · 키보드: 화살표 + 스페이스 칠하기, X ✕ 표시

} + {phone && mine && playing &&

누르기·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 한 줄로 끌면 한 번에 · 칠한 칸을 다시 누르면 지워요

} +

+ {announce} +

+
+ ); +} + +function NonoSide(props: BoardProps) { + return ; +} + +function statusText(v: NonogramView, me: string | null, players: Record): string { + return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자대로 칸을 칠해 그림을 완성해요', playing: '줄마다 숫자 = 이어서 칠할 칸 수 · 모든 줄을 숫자와 맞게 칠해요', failed: '' }); +} + +function Options({ value: o, onChange }: OptionsProps) { + return ( +
+
+ 크기 + [s, sizeInfo(s)])} onChange={(size) => onChange({ ...o, size })} /> +
+
+ 힌트 + onChange({ ...o, hints })} /> + {o.hints ? '막히면 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'} +
+ onChange({ ...o, timeLimitSec: timeLimitSec as NonogramOptions['timeLimitSec'] })} /> +
+ ); +} + +function optionsSummary(o: NonogramOptions): string { + return `${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`; +} + +function Rules({ options }: { options?: NonogramOptions }) { + const size = options?.size ?? 10; + return ( +
+

+ 줄마다 적힌 숫자대로 칸을 칠하면 그림이 나와요. 모두 똑같은 그림을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요. +

+
+ + 숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"은 한 칸, 한 칸 이상 띄고, 또 한 칸이에요. 숫자 순서대로 놓여요. +
+

+ 확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 두면 좋아요(✕는 답에 상관없어요). 칠한 칸이 맞는지는 알려 주지 않아요. 숫자와 맞게 칠해진 줄은 숫자가 흐려져요. 칠한 칸이 그림과 + 똑같아지면 다 푼 거예요. +

+

+ 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 숫자와 맞는 줄이 많은 사람이 이겨요. 힌트를 켜면 막힐 때 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요(쓴 횟수는 + 결과에 나와요). 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1200)}이고, 지금 크기는 {sizeInfo(size)}이에요. +

+

PC: 왼쪽 클릭·끌기 칠하기, 오른쪽 클릭·끌기 ✕. 휴대폰: 누르거나 끌어서 칠하고, 위의 [✕ 표시]로 바꾸면 ✕를 해요. 칠한 칸을 다시 누르면 지워요. 키보드: 화살표, 스페이스 칠하기, X로 ✕.

+
+ ); +} + +const ui: GameUI = { + Board: NonoBoard, + Side: NonoSide, + statusText, + liveStatus: true, + isMyTurn: raceIsMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/nonogram/quick.tsx b/apps/web/src/games/nonogram/quick.tsx new file mode 100644 index 0000000..9029a62 --- /dev/null +++ b/apps/web/src/games/nonogram/quick.tsx @@ -0,0 +1,26 @@ +/** 네모네모 로직 30초 규칙 요약 (docs/07 §5). Small puzzles drawn with ./art. */ +import type { QuickCard } from '../types'; +import { MiniNono } from './art'; + +const HEART = ['.#.#.', '#####', '#####', '.###.', '..#..']; + +export const quickStart: QuickCard[] = [ + { + pic: , + alt: '5×5 빈 칸 위와 왼쪽에 줄마다 숫자가 적혀 있어요', + title: '숫자 = 칠할 칸 덩어리', + text: '줄 옆 숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"이면 한 칸, 띄고, 한 칸이에요.', + }, + { + pic: , + alt: '위 세 줄은 칠한 칸과 ✕ 표시로 채워져 있어요', + title: '칠하기와 ✕ 표시', + text: '확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 둬요. 끌면 한 줄을 한 번에 칠해요.', + }, + { + pic: , + alt: '다 칠한 칸이 빨간 하트 그림이 됐어요', + title: '다 칠하면 그림이 나와요', + text: '모든 줄이 숫자와 맞으면 그림이 나와요. 모두 같은 그림이라 가장 먼저 푼 사람이 이겨요.', + }, +]; diff --git a/apps/web/src/games/race/kit.tsx b/apps/web/src/games/race/kit.tsx new file mode 100644 index 0000000..ba1e068 --- /dev/null +++ b/apps/web/src/games/race/kit.tsx @@ -0,0 +1,289 @@ +/** + * Shared screen parts for the race games (docs/games/race.md §4): the clock row, everyone's progress chips, the side + * ranking, the countdown and finished notes, 포기, the time limit option and the shared status / help lines. + * Each game draws its own board in between. + */ +import { useEffect, useRef, useState, type ReactNode } from 'react'; +import { formatElapsed, rankSeats, type RaceSeat, type RaceView } from '@bg/games/race'; +import type { PublicUser } from '@bg/shared/lite'; +import { Avatar } from '../../components/ui'; +import { useServerNow } from '../../components/TurnTimer'; +import { sfx, tone } from '../../lib/feedback'; +import { AfterMotion } from '../../lib/motion'; + +type V = RaceView; + +export { STATUS_WORD, limitLabel, mySeat, nick, raceHelp, raceIsMyTurn, raceStatusText } from './text'; +import { STATUS_WORD, limitLabel, mySeat, nick } from './text'; + +const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; +const clock = (ms: number) => { + const s = Math.ceil(Math.max(0, ms) / 1000); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; +}; +/** Stopwatch: "1:05.4". */ +const watch = (ms: number) => { + const t = Math.floor(Math.max(0, ms) / 100); + return `${Math.floor(t / 600)}:${String(Math.floor((t % 600) / 10)).padStart(2, '0')}.${t % 10}`; +}; + +export function canPlay(v: V, me: string | null, now: number): boolean { + const s = mySeat(v, me); + return !!s && s.status === 'playing' && v.phase === 'playing' && !!v.board && (v.endsAt === null || now < v.endsAt); +} + +export const RACE_CSS = ` +.rc { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 8px; } +.rc-top { width: 100%; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; } +.rc-pill { display: inline-flex; align-items: center; gap: 6px; border-radius: 999px; padding: 4px 12px; background: var(--surface); box-shadow: var(--shadow); + font-weight: 800; font-variant-numeric: tabular-nums; font-size: 1rem; white-space: nowrap; border: 0; color: inherit; } +.rc-pill b { font-size: 1.1rem; } +.rc-pill.warn { background: var(--danger-soft); color: var(--danger); } +button.rc-pill { cursor: pointer; min-height: 36px; } +button.rc-pill[aria-pressed='true'] { background: var(--primary); color: #fff; } +.rc-others { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 6px; justify-content: center; max-width: 100%; } +.rc-others li { display: inline-flex; align-items: center; gap: 4px; border-radius: 999px; padding: 2px 8px 2px 3px; background: var(--surface-2); font-size: .85rem; font-weight: 700; max-width: 46vw; } +.rc-others li span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.rc-others li b { font-variant-numeric: tabular-nums; margin-left: 2px; } +.rc-others li[data-me='true'] { background: var(--primary-soft); } +.rc-others li[data-out='true'] { opacity: .55; } +.rc-wrap { position: relative; max-width: 100%; } +.rc-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; pointer-events: none; + border-radius: 12px; text-align: center; padding: 12px; z-index: 4; } +.rc-over.count { background: rgba(0,0,0,.4); color: #fff; font-size: 4.5rem; font-weight: 900; text-shadow: 0 3px 8px rgba(0,0,0,.5); min-height: 180px; } +.rc-over.count small { font-size: 1.05rem; font-weight: 800; } +.rc-over.count b { display: block; animation: rc-count .9s ease-out both; } +.rc-over.note { inset: auto 8px 8px 8px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); font-weight: 800; } +.rc-over.note.win { color: var(--success); border: 3px solid var(--success); } +.rc-acts { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; } +.rc-acts .btn { min-height: 40px; } +.rc-keys { color: var(--text-sub); font-size: .85rem; font-weight: 600; text-align: center; margin: 0; } +.rc-wait { min-height: 220px; width: min(100%, 520px); border-radius: 12px; background: var(--surface-2); } +@keyframes rc-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } } +@media (prefers-reduced-motion: reduce) { .rc-over.count b { animation: none; } } +`; + +/** Clock values for the board: time left (time limit) or my stopwatch (무제한), the 3·2·1 countdown. */ +export function useRaceClock(v: V, me: string | null) { + const now = useServerNow(v.endsAt === null ? 100 : 200); + const mine = mySeat(v, me); + const left = v.endsAt === null ? null : Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt)); + const elapsed = mine?.timeMs ?? (v.phase === 'playing' && (!mine || mine.status === 'playing') ? Math.max(0, now - v.countdownEndsAt) : null); + const countdown = v.phase === 'countdown' ? Math.max(1, Math.ceil((v.countdownEndsAt - now) / 1000)) : 0; + // Sounds that follow the clock: 3·2·1, start, the last 10 seconds, finishing. + const lastSec = v.phase === 'playing' && left !== null && left > 0 && left <= 10_000 ? Math.ceil(left / 1000) : 0; + const heard = useRef({ countdown: 0, lastSec: 0, status: mine?.status ?? null }); + useEffect(() => { + const was = heard.current; + if (countdown !== was.countdown) { + if (countdown > 0) tone(660, 90, 'triangle', 0.12); + else if (was.countdown > 0 && v.phase === 'playing') { + tone(988, 120, 'triangle', 0.14); + tone(1318, 200, 'triangle', 0.12, 90); + } + } + if (lastSec && lastSec !== was.lastSec) sfx.tick(); + const st = mine?.status ?? null; + if (st !== was.status && was.status === 'playing') { + if (st === 'solved') sfx.fanfare(); + else if (st === 'failed') sfx.bad(); + } + heard.current = { countdown, lastSec, status: st }; + }); + return { now, left, elapsed, countdown, mine }; +} + +/** Top row: the clock first, then the game's own pills. */ +export function RaceTop({ v, left, elapsed, children }: { v: V; left: number | null; elapsed: number | null; children?: ReactNode }) { + return ( +
+ {left === null ? ( + + ⏱ {elapsed === null ? '무제한' : {watch(elapsed)}} + + ) : ( + + ⏱ {clock(left)} + + )} + {children} +
+ ); +} + +/** Everyone's progress (live), ranked; only with more than one player. */ +export function RaceSeats({ v, me, players }: { v: V; me: string | null; players: Record }) { + if (v.seats.length < 2) return null; + return ( +
    + {rankSeats(v.seats).map((s) => ( +
  1. + + {s.id === me ? '나' : nick(players, s.id)} + + {s.status === 'solved' ? `✔ ${formatElapsed(s.timeMs ?? 0)}` : s.progressText.replace(/^[^\d]*/, '')} + + {s.status !== 'playing' && s.status !== 'solved' && · {STATUS_WORD[s.status]}} +
  2. + ))} +
+ ); +} + +/** Countdown over the (still hidden) board. */ +export function RaceCountdown({ countdown, text }: { countdown: number; text: string }) { + if (!countdown) return null; + return ( +
+ {countdown} + {text} +
+ ); +} + +/** Notes over the board once I am finished, left, or watching. */ +export function RaceNotes({ v, mine, failText }: { v: V; mine: RaceSeat | null; failText: string }) { + const playing = v.phase === 'playing'; + const wait = v.seats.length > 1 ? ' · 모두 끝날 때까지 기다려요' : ''; + return ( + <> + +
+ 다 풀었어요! {formatElapsed(mine?.timeMs ?? 0)} + {mine?.extra} + {wait} +
+
+ +
+ {failText} {mine?.progressText} + {wait} +
+
+ {mine?.status === 'done' && playing && ( +
+ 포기했어요. {mine.progressText} + {wait} +
+ )} + {mine?.status === 'left' && v.phase !== 'ended' &&
게임에서 나갔어요.
} + {!mine && v.phase !== 'ended' &&
관전 중이에요 · 위에서 진행 상황을 볼 수 있어요
} + + ); +} + +/** 포기: press twice (the first press only asks). */ +export function GiveUp({ act }: { act: (a: unknown) => void }) { + const [ask, setAsk] = useState(false); + useEffect(() => { + if (!ask) return; + const t = setTimeout(() => setAsk(false), 3000); + return () => clearTimeout(t); + }, [ask]); + return ( + + ); +} + +/** Right panel: the live ranking, then the final one. */ +export function RaceSide({ v, me, players, title, info }: { v: V; me: string | null; players: Record; title: string; info: string }) { + return ( + <> + +
+ + {title} + {v.phase === 'ended' ? ' · 게임 끝' : ''} + + + {info} · 제한 시간 {limitLabel(v.options.timeLimitSec)} · 모두 같은 판 + +
    + {rankSeats(v.seats).map((s) => ( +
  1. + + {s.rank}등 + + + + {nick(players, s.id)} + {s.id === me ? ' (나)' : ''} + {STATUS_WORD[s.status] ? ` · ${STATUS_WORD[s.status]}` : ''} + + + {s.status === 'solved' ? formatElapsed(s.timeMs ?? 0) : s.progressText} + +
  2. + ))} +
+
+ + {v.result && ( +
+ 최종 순위 + {v.result.ranking.map((r) => ( + + {r.rank}등 {nick(players, r.id)} + · {r.text} + + ))} + {v.result.summary} +
+ )} +
+ + ); +} + +/** Time limit choice for the room settings. */ +export function TimeLimitOption({ value, choices, onChange }: { value: number | null; choices: number[]; onChange: (v: number | null) => void }) { + return ( +
+ 제한 시간 + [c, limitLabel(c)] as [number, string]), [null, '무제한']]} onChange={onChange} /> + + {value === null ? '시간 제한 없이 각자 다 풀거나 포기할 때까지 해요. 스톱워치로 걸린 시간을 재요.' : '시간이 끝나면 다 못 푼 사람은 푼 만큼으로 순위를 매겨요.'} + +
+ ); +} + +export function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { + return ( +
+ {options.map(([k, l]) => ( + + ))} +
+ ); +} + +/** Narrow screens (phones). */ +export function useNarrow(): boolean { + const q = '(max-width: 640px)'; + const [m, setM] = useState(() => typeof window !== 'undefined' && window.matchMedia(q).matches); + useEffect(() => { + const mq = window.matchMedia(q); + const on = () => setM(mq.matches); + mq.addEventListener('change', on); + return () => mq.removeEventListener('change', on); + }, []); + return m; +} diff --git a/apps/web/src/games/race/text.ts b/apps/web/src/games/race/text.ts new file mode 100644 index 0000000..d24d8a0 --- /dev/null +++ b/apps/web/src/games/race/text.ts @@ -0,0 +1,55 @@ +/** Pure text helpers for the race games (status line, [?] help); no DOM, so help tests can import them. */ +import { formatElapsed, rankSeats, type RaceSeat, type RaceView } from '@bg/games/race'; +import type { PublicUser } from '@bg/shared/lite'; + +type V = RaceView; + +export const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; +export const limitLabel = (sec: number | null) => (sec === null ? '무제한' : sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`); +export const STATUS_WORD: Record = { playing: '', solved: '다 풂', failed: '실패', done: '포기', left: '나감' }; + +export function mySeat(v: V, me: string | null): RaceSeat | null { + return v.seats.find((s) => s.id === me) ?? null; +} + +/** I can make moves now. */ +export function raceIsMyTurn(v: V, me: string | null): boolean { + return !!me && v.phase === 'playing' && v.seats.some((s) => s.id === me && s.status === 'playing'); +} + +/** Status line; `playing` is the game's line while I am still solving. */ +export function raceStatusText(v: V, me: string | null, players: Record, texts: { countdown: string; playing: string; failed: string }): string { + if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요'; + if (v.phase === 'countdown') return texts.countdown; + const mine = mySeat(v, me); + if (!mine) { + const top = rankSeats(v.seats)[0]; + return top && top.status === 'solved' ? `${nick(players, top.id)}님이 가장 먼저 다 풀었어요` : '모두 같은 판을 풀고 있어요'; + } + const wait = v.seats.length > 1 ? ' · 모두 끝날 때까지 기다려요' : ''; + if (mine.status === 'left') return '게임에서 나갔어요'; + if (mine.status === 'solved') return `다 풀었어요! ${formatElapsed(mine.timeMs ?? 0)}${mine.extra}${wait}`; + if (mine.status === 'failed') return `${texts.failed} ${mine.progressText}${wait}`; + if (mine.status === 'done') return `포기했어요 · ${mine.progressText}${wait}`; + return texts.playing; +} + +/** [?] lines every race game shares: phase, my state, who leads. `how` explains the game's moves. */ +export function raceHelp(v: V, me: string | null, players: Record, how: string[], failed: string): string { + if (v.phase === 'ended') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자 걸린 시간과 푼 만큼을 볼 수 있어요.'; + const secs = v.options.timeLimitSec; + const limitLine = secs === null ? '제한 시간은 없어요. 다 풀거나 포기할 때까지 해요.' : `제한 시간은 ${limitLabel(secs)}이에요.`; + const winLine = v.seats.length > 1 ? '가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 가장 많이 푼 사람이 이겨요.' : ''; + if (v.phase === 'countdown') return [`곧 시작해요. 모두 똑같은 판을 각자 풀어요. ${limitLine}`, ...how].join('\n'); + const mine = mySeat(v, me); + const solved = rankSeats(v.seats).filter((s) => s.status === 'solved'); + const lead = v.seats.length > 1 && solved.length ? `지금까지 ${solved.map((s) => (s.id === me ? '나' : `${nick(players, s.id)}님`)).join(', ')}이(가) 다 풀었어요.` : ''; + if (!mine) return [`모두 똑같은 판을 각자 풀고 있어요. ${winLine}`, lead].filter(Boolean).join('\n'); + if (mine.status === 'left') return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.'; + const waitLine = v.seats.length > 1 ? '모두 끝나면 순위가 나와요.' : ''; + if (mine.status === 'solved') return [`다 풀었어요! 걸린 시간은 ${formatElapsed(mine.timeMs ?? 0)}이에요.`, waitLine, lead].filter(Boolean).join('\n'); + if (mine.status === 'failed') return [`${failed} ${mine.progressText}.`, waitLine, lead].filter(Boolean).join('\n'); + if (mine.status === 'done') return [`포기했어요. ${mine.progressText}.`, waitLine, lead].filter(Boolean).join('\n'); + return [...how, `지금 ${mine.progressText}.`, limitLine, winLine, lead, '그만하고 싶으면 [포기할래요]를 두 번 눌러요.'].filter(Boolean).join('\n'); +} + diff --git a/apps/web/src/games/registry.ts b/apps/web/src/games/registry.ts index ff1600d..a02bd3c 100644 --- a/apps/web/src/games/registry.ts +++ b/apps/web/src/games/registry.ts @@ -27,6 +27,11 @@ export const GAME_UI: Record Promise<{ default: GameUI }>> = { 'ninety-nine': () => import('./ninety-nine'), 'connect-four': () => import('./connect-four'), typing: () => import('./typing'), + minesweeper: () => import('./minesweeper'), + shisen: () => import('./shisen'), + solitaire: () => import('./solitaire'), + sudoku: () => import('./sudoku'), + nonogram: () => import('./nonogram'), 'old-maid': () => import('./old-maid'), dobble: () => import('./dobble'), catchmind: () => import('./catchmind'), diff --git a/apps/web/src/games/shisen/art.tsx b/apps/web/src/games/shisen/art.tsx new file mode 100644 index 0000000..778eaf8 --- /dev/null +++ b/apps/web/src/games/shisen/art.tsx @@ -0,0 +1,41 @@ +/** 사천성 board geometry and small pictures for the rules and help cards (tiles: ../mahjong/Tile). */ +import { Tile } from '../mahjong/Tile'; + +/** Felt behind the tiles (the same in light and dark mode). */ +export const FELT = '#2f6b4f'; +export const LINE = '#fbbf24'; + +/** + * Where things sit on a board of `dR`×`dC` tiles `tw` px wide: tiles are 3:4, with a half-tile margin all round that + * connecting lines may run through. Margin rows/columns (-1 and dR/dC) map to the middle of that strip. + */ +export function geom(tw: number, dR: number, dC: number) { + const th = Math.round((tw * 4) / 3); + const m = Math.round(tw / 2); + const x = (c: number) => (c < 0 ? m / 2 : c >= dC ? m + dC * tw + m / 2 : m + (c + 0.5) * tw); + const y = (r: number) => (r < 0 ? m / 2 : r >= dR ? m + dR * th + m / 2 : m + (r + 0.5) * th); + return { tw, th, m, w: dC * tw + 2 * m, h: dR * th + 2 * m, x, y, left: (c: number) => m + c * tw, top: (r: number) => m + r * th }; +} + +/** A tiny board (rows of kind codes, '' = empty) with an optional line through [row, col] points. */ +export function MiniBoard({ rows, path, tw = 26, dim = [] }: { rows: string[][]; path?: [number, number][]; tw?: number; dim?: string[] }) { + const g = geom(tw, rows.length, rows[0]!.length); + return ( +
+ {rows.flatMap((row, r) => + row.map((k, c) => + k ? ( +
+ +
+ ) : null, + ), + )} + {path && ( + + `${g.x(c)},${g.y(r)}`).join(' ')} fill="none" stroke={LINE} strokeWidth={3.5} strokeLinecap="round" strokeLinejoin="round" /> + + )} +
+ ); +} diff --git a/apps/web/src/games/shisen/help.ts b/apps/web/src/games/shisen/help.ts new file mode 100644 index 0000000..18e2c5f --- /dev/null +++ b/apps/web/src/games/shisen/help.ts @@ -0,0 +1,19 @@ +/** 사천성 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { ShisenView } from '@bg/games/shisen'; +import type { PublicUser } from '@bg/shared/lite'; +import { raceHelp } from '../race/text'; + +const HOW = [ + '같은 그림의 패 두 장을 차례로 누르면 없어져요. 두 패 사이를 빈 칸으로만 지나는 선이 두 번 이하로 꺾여야 해요(판 바깥 테두리로 돌아가도 돼요).', + '고른 패를 다시 누르면 취소돼요. 이을 수 있는 쌍이 하나도 없으면 남은 패가 저절로 섞여요.', + '키보드: 화살표로 옮기고 스페이스(또는 Enter)로 골라요.', +]; + +export function helpNow(v: ShisenView, me: string | null, players: Record): string { + const lines = raceHelp(v, me, players, HOW, ''); + const mine = v.seats.find((s) => s.id === me); + if (!v.board || v.phase !== 'playing' || mine?.status !== 'playing') return lines; + const left = v.board.cells.filter((k) => k !== null).length; + const hint = !v.options.hints ? '이 방은 힌트를 쓰지 않아요.' : v.board.hint ? '빛나는 두 장이 힌트예요.' : '막히면 [💡 힌트]로 이을 수 있는 쌍 하나를 볼 수 있어요.'; + return `${lines}\n남은 패는 ${left}장이에요. ${hint}`; +} diff --git a/apps/web/src/games/shisen/index.tsx b/apps/web/src/games/shisen/index.tsx new file mode 100644 index 0000000..46e1b39 --- /dev/null +++ b/apps/web/src/games/shisen/index.tsx @@ -0,0 +1,445 @@ +/** 사천성 화면 (docs/games/shisen.md §9). */ +import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'; +import { SIZES, findPath, type Point, type ShisenOptions, type ShisenView, type Size } from '@bg/games/shisen'; +import type { PublicUser } from '@bg/shared/lite'; +import { haptic, sfx, tone } from '../../lib/feedback'; +import { fxMs } from '../../lib/motion'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { MAHJONG_TILE_CREDIT, Tile, tileName } from '../mahjong/Tile'; +import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit'; +import { FELT, LINE, MiniBoard, geom } from './art'; +import { helpNow } from './help'; +import { quickStart } from './quick'; + +const NOT_SAME = '같은 패가 아니에요'; +const TOO_MANY_TURNS = '두 번 넘게 꺾여야 이어져요'; +const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x)); + +const CSS = ` +.ss-fit { width: 100%; display: flex; justify-content: center; } +.ss-board { position: relative; border-radius: 12px; background: ${FELT}; box-shadow: var(--shadow), inset 0 0 0 2px rgba(0,0,0,.18); + touch-action: manipulation; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; outline: none; cursor: pointer; } +.ss-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); } +.ss-board[data-off='true'] { cursor: default; } +.ss-cell { position: absolute; transition: transform .12s ease; pointer-events: none; } +.ss-cell .mj-tile { filter: drop-shadow(0 1.5px 1px rgba(0,0,0,.4)); } +.ss-cell::after { content: ''; position: absolute; inset: -1px; border-radius: 7px; pointer-events: none; } +.ss-cell.sel { transform: translateY(-4px); z-index: 2; } +.ss-cell.sel::after { box-shadow: 0 0 0 3px #f59e0b, 0 0 12px 3px rgba(245,158,11,.75); } +.ss-cell.hint { transform: translateY(-2px); z-index: 2; } +.ss-cell.hint::after { box-shadow: 0 0 0 4px #0ea5e9, 0 0 16px 5px rgba(14,165,233,.95); animation: ss-pulse .8s ease-in-out infinite alternate; } +.ss-cell.cur::after { outline: 3px dashed #fff; outline-offset: 1px; } +.ss-shake { animation: ss-shake .35s ease both; } +.ss-gone { z-index: 3; animation: ss-gone var(--ss-ms) ease-in forwards; } +.ss-line { position: absolute; inset: 0; pointer-events: none; z-index: 4; overflow: visible; } +.ss-line polyline { animation: ss-fade var(--ss-ms) ease-in forwards; } +.ss-toast { position: absolute; top: 6px; left: 50%; transform: translateX(-50%); z-index: 5; padding: 6px 14px; border-radius: 999px; background: var(--surface); + color: var(--text); font-weight: 800; box-shadow: var(--shadow); pointer-events: none; white-space: nowrap; animation: ss-pop .25s ease-out both; } +.ss-toast.bad { color: var(--danger); } +.ss-probe-box { position: relative; width: 0; height: 0; overflow: hidden; flex: none; } +.ss-probe { position: absolute; top: 0; left: 0; width: 1px; height: var(--play-h, 100vh); visibility: hidden; } +@keyframes ss-shake { 20% { transform: translateX(-5px); } 40% { transform: translateX(5px); } 60% { transform: translateX(-3px); } 80% { transform: translateX(2px); } } +@keyframes ss-gone { to { opacity: 0; transform: scale(.7); } } +@keyframes ss-fade { 0%, 55% { opacity: 1; } 100% { opacity: 0; } } +@keyframes ss-pop { from { opacity: 0; transform: translate(-50%, -6px); } } +@keyframes ss-pulse { from { opacity: .6; } to { opacity: 1; } } +@media (prefers-reduced-motion: reduce) { + .ss-shake, .ss-toast, .ss-cell.hint::after, .ss-line polyline { animation: none; } + .ss-cell { transition: none; } + .ss-gone { animation: none; opacity: 0; } +} +`; + +const sizeInfo = (s: Size) => `${SIZES[s].name} ${SIZES[s].cols}×${SIZES[s].rows} · ${SIZES[s].rows * SIZES[s].cols}패`; + +interface Flash { + key: number; + pts: Point[]; + a: number; + b: number; + kind: string; +} + +function ShisenBoard({ view: v, me, players, act }: BoardProps) { + const { now, left, elapsed, countdown, mine } = useRaceClock(v, me); + const phone = useNarrow(); + const b = v.board; + const [sel, setSel] = useState(null); + const [cursor, setCursor] = useState(0); + // The keyboard cursor shows only while playing by keyboard (not after a click or tap). + const [keyCursor, setKeyCursor] = useState(false); + const [flash, setFlash] = useState(null); + const [shake, setShake] = useState<{ key: number; ids: number[] } | null>(null); + const [toast, setToast] = useState<{ key: number; text: string; bad: boolean } | null>(null); + const [announce, setAnnounce] = useState(''); + const [tw, setTw] = useState(40); + const fitRef = useRef(null); + const probeRef = useRef(null); + const boardRef = useRef(null); + const press = useRef(null); + const seenShuffles = useRef(null); + const seenHint = useRef(null); + const playing = canPlayNow(v, me, now); + + const rows = b?.rows ?? SIZES[v.options.size].rows; + const cols = b?.cols ?? SIZES[v.options.size].cols; + // Phones: a wide board is turned so it is taller than wide. + const turn = phone && cols > rows; + const dR = turn ? cols : rows; + const dC = turn ? rows : cols; + + // Tile width: fit the column width and the visible height. PC: the play area (--play-h, measured by a probe) minus + // the rows above and below the board. Phone: the first screen from the board's top down, minus the buttons below. + useLayoutEffect(() => { + const fit = fitRef.current; + const probe = probeRef.current; + if (!fit || !probe) return; + const update = () => { + const availH = phone ? window.innerHeight - (fit.getBoundingClientRect().top + window.scrollY) - 96 : probe.offsetHeight - 175; + const w = Math.floor(Math.min(fit.clientWidth / (dC + 1), availH / ((dR * 4) / 3 + 1), 64)); + setTw(Math.max(phone ? 34 : 28, w)); // phones: at least a finger-sized tile, scrolling if needed + }; + update(); + const ro = new ResizeObserver(update); + ro.observe(fit); + ro.observe(probe); + ro.observe(document.body); // rows above the board change height (status text) + window.addEventListener('resize', update); + return () => { + ro.disconnect(); + window.removeEventListener('resize', update); + }; + }, [dC, dR, phone, !!b]); + + // Auto-reshuffle: say so for a moment. + useEffect(() => { + const n = b?.shuffles ?? null; + const was = seenShuffles.current; + seenShuffles.current = n; + if (n === null || was === null || n <= was) return; + setSel(null); + setToast({ key: Date.now(), text: '섞었어요!', bad: false }); + sfx.shuffle(); + setAnnounce('이을 수 있는 쌍이 없어서 남은 패를 섞었어요.'); + }, [b?.shuffles]); + + // A new hint: announce the pair. + useEffect(() => { + const h = b?.hint ? `${b.hint[0]}-${b.hint[1]}` : null; + if (h && h !== seenHint.current && b?.hint) { + sfx.pop(); + setAnnounce(`힌트: 빛나는 ${tileName(b.cells[b.hint[0]]!)} 두 장을 이을 수 있어요.`); + } + seenHint.current = h; + }, [b?.hint?.[0], b?.hint?.[1]]); + + // The selected tile went away (removed, reshuffled): drop the selection. + useEffect(() => { + if (sel !== null && b && b.cells[sel] == null) setSel(null); + }, [b?.cells, sel]); + + useEffect(() => { + if (!flash) return; + const t = setTimeout(() => setFlash(null), fxMs(350)); + return () => clearTimeout(t); + }, [flash?.key]); + useEffect(() => { + if (!shake) return; + const t = setTimeout(() => setShake(null), fxMs(400)); + return () => clearTimeout(t); + }, [shake?.key]); + useEffect(() => { + if (!toast) return; + const t = setTimeout(() => setToast(null), fxMs(1200)); + return () => clearTimeout(t); + }, [toast?.key]); + + if (!b) { + return ( +
+ + + +
+ + +
+
+
+
+
+
+
+ ); + } + + const g = geom(tw, dR, dC); + const toDisp = (r: number, c: number): Point => (turn ? [c, rows - 1 - r] : [r, c]); + const dispOf = (i: number) => toDisp(Math.floor(i / cols), i % cols); + const toIndex = (dr: number, dc: number) => (turn ? (rows - 1 - dc) * cols + dr : dr * cols + dc); + const cellAt = (e: { clientX: number; clientY: number }): number | null => { + const box = boardRef.current!.getBoundingClientRect(); + const dc = Math.floor((e.clientX - box.left - g.m) / g.tw); + const dr = Math.floor((e.clientY - box.top - g.m) / g.th); + return dr < 0 || dc < 0 || dr >= dR || dc >= dC ? null : toIndex(dr, dc); + }; + const tilesLeft = b.cells.filter((k) => k !== null).length; + const describe = (i: number) => { + const [dr, dc] = dispOf(i); + const k = b.cells[i]; + return `${dr + 1}줄 ${dc + 1}칸, ${k ? tileName(k) : '빈 칸'}${i === sel ? '(고름)' : ''}`; + }; + + const tap = (i: number) => { + if (!playing) return; + setCursor(i); + const k = b.cells[i]; + if (k == null) return; + if (sel === null || b.cells[sel] == null) { + setSel(i); + sfx.select(); + setAnnounce(`골랐어요: ${describe(i)}. 같은 패를 하나 더 골라요.`); + return; + } + if (sel === i) { + setSel(null); + sfx.click(); + setAnnounce('고르기를 취소했어요.'); + return; + } + const pts = b.cells[sel] === k ? findPath(b.cells, b.rows, b.cols, sel, i) : null; + if (!pts) { + // Not a pair: shake both, say why, and start again from the tile just picked. + const why = b.cells[sel] === k ? TOO_MANY_TURNS : NOT_SAME; + setShake({ key: Date.now(), ids: [sel, i] }); + setToast({ key: Date.now(), text: why, bad: true }); + setSel(i); + tone(220, 120, 'square', 0.05); + haptic(30); + setAnnounce(`${why}. 새로 고른 패: ${describe(i)}.`); + return; + } + act({ type: 'pair', a: sel, b: i }); + setFlash({ key: Date.now(), pts, a: sel, b: i, kind: k }); + setSel(null); + tone(880, 60, 'triangle', 0.12); + tone(1320, 110, 'triangle', 0.1, 60); + haptic(12); + setAnnounce(`${tileName(k)} 한 쌍을 없앴어요. 남은 패 ${tilesLeft - 2}장.`); + }; + + const onDown = (e: ReactPointerEvent) => { + if (!playing || (e.pointerType === 'mouse' && e.button !== 0)) return; + setKeyCursor(false); + press.current = cellAt(e); + }; + const onUp = (e: ReactPointerEvent) => { + const p = press.current; + press.current = null; + if (p !== null && cellAt(e) === p) tap(p); + }; + const onKey = (e: ReactKeyboardEvent) => { + const step: Record = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] }; + const m = step[e.key]; + if (m) { + e.preventDefault(); + setKeyCursor(true); + const [dr, dc] = dispOf(cursor); + const next = toIndex(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1)); + setCursor(next); + setAnnounce(describe(next)); + } else if (e.key === ' ' || e.key === 'Enter') { + e.preventDefault(); + setKeyCursor(true); + if (!e.repeat) tap(cursor); + } else if (e.key === 'Escape' && sel !== null) { + setSel(null); + setAnnounce('고르기를 취소했어요.'); + } + }; + + const hint: number[] = b.hint ?? []; + const msVar = { '--ss-ms': `${fxMs(350)}ms` } as CSSProperties; + const showHint = !!mine && v.phase === 'playing' && v.options.hints; + + return ( +
+ + + + 🀄 {tilesLeft} + + + +
+
+
+
+
+
(press.current = null)} + onKeyDown={onKey} + onFocus={(e) => setKeyCursor(e.currentTarget.matches(':focus-visible'))} + onBlur={() => setKeyCursor(false)} + onContextMenu={(e) => e.preventDefault()} + > + {b.cells.map((k, i) => { + if (k == null || (flash && (i === flash.a || i === flash.b))) return null; + const [dr, dc] = dispOf(i); + const cls = ['ss-cell', i === sel && 'sel', hint.includes(i) && 'hint', keyCursor && playing && i === cursor && 'cur', shake?.ids.includes(i) && 'ss-shake'].filter(Boolean).join(' '); + return ( +
+ +
+ ); + })} + {keyCursor && playing && b.cells[cursor] == null && ( +
+ )} + {flash && + [flash.a, flash.b].map((i) => { + const [dr, dc] = dispOf(i); + return ( +
+ +
+ ); + })} + {flash && ( + + toDisp(r, c)).map(([dr, dc]) => `${g.x(dc)},${g.y(dr)}`).join(' ')} + fill="none" + stroke={LINE} + strokeWidth={Math.max(3, tw / 10)} + strokeLinecap="round" + strokeLinejoin="round" + /> + + )} + {toast && ( +
+ {toast.text} +
+ )} +
+ +
+
+ {mine && playing && ( +
+ {showHint && ( + + )} + +
+ )} + {!phone && mine && v.phase !== 'ended' &&

같은 패 두 장을 차례로 클릭 · 고른 패를 다시 누르면 취소 · 키보드: 화살표 + 스페이스, Esc 취소

} + {phone && mine && playing &&

같은 패 두 장을 차례로 눌러요 · 고른 패를 다시 누르면 취소

} +

+ {announce} +

+
+ ); +} + +function ShisenSide(props: BoardProps) { + const o = props.view.options; + return ; +} + +function statusText(v: ShisenView, me: string | null, players: Record): string { + return raceStatusText(v, me, players, { countdown: '곧 시작해요! 같은 패 두 장을 이어서 없애요', playing: '같은 패 두 장을 두 번 이하로 꺾인 선으로 이으면 없어져요', failed: '' }); +} + +function Options({ value: o, onChange }: OptionsProps) { + return ( +
+
+ 판 크기 + [s, SIZES[s].name])} onChange={(size) => onChange({ ...o, size })} /> + {sizeInfo(o.size)} +
+
+ 힌트 + onChange({ ...o, hints })} + /> + {o.hints ? '[💡 힌트]를 누르면 이을 수 있는 쌍 하나를 보여 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'} +
+ onChange({ ...o, timeLimitSec: timeLimitSec as ShisenOptions['timeLimitSec'] })} /> +
+ ); +} + +function optionsSummary(o: ShisenOptions): string { + return `${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`; +} + +function Rules({ options }: { options?: ShisenOptions }) { + const size = options?.size ?? 'normal'; + return ( +
+

+ 마작패가 깔린 판에서 같은 그림의 패 두 장을 골라 없애요. 패를 모두 없애면 이겨요. 모두 똑같은 판을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 + 있어요. +

+
+ + 두 패를 잇는 선이 빈 칸으로만 지나고 두 번까지만 꺾이면 돼요. 판 바깥 테두리로 돌아가도 돼요. +
+

+ 이을 수 있는 쌍이 하나도 없으면 남은 패가 같은 자리에서 저절로 섞여요(언제나 다 풀 수 있게). 판은 처음부터 끝까지 풀 수 있게 만들어져요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 + 풀면 없앤 쌍이 많은 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 900)}이고, 지금 판은 {sizeInfo(size)}이에요. +

+

PC: 패를 차례로 클릭. 휴대폰: 패를 차례로 눌러요(넓은 판은 세로로 돌려 보여 줘요). 키보드: 화살표로 옮기고 스페이스로 골라요. 힌트를 쓰는 방이면 [💡 힌트]로 한 쌍을 볼 수 있어요.

+

{MAHJONG_TILE_CREDIT}

+
+ ); +} + +const ui: GameUI = { + Board: ShisenBoard, + Side: ShisenSide, + statusText, + liveStatus: true, + isMyTurn: raceIsMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/shisen/quick.tsx b/apps/web/src/games/shisen/quick.tsx new file mode 100644 index 0000000..68c6877 --- /dev/null +++ b/apps/web/src/games/shisen/quick.tsx @@ -0,0 +1,60 @@ +/** 사천성 30초 규칙 요약 (docs/07 §5). Small boards drawn with the mahjong tiles. */ +import type { QuickCard } from '../types'; +import { MiniBoard } from './art'; + +export const quickStart: QuickCard[] = [ + { + pic: ( + + ), + alt: '같은 통수 3 두 장이 빈 칸을 지나는 곧은 선으로 이어져 있어요', + title: '같은 패 두 장을 이어요', + text: '같은 그림의 패 두 장을 차례로 누르면 없어져요. 모두 똑같은 판을 각자 풀어요.', + }, + { + pic: ( + + ), + alt: '가운데가 막힌 중 두 장이 판 바깥을 돌아 두 번 꺾인 선으로 이어져 있어요', + title: '두 번까지 꺾여도 돼요', + text: '빈 칸으로만 지나는 선이 두 번 이하로 꺾이면 이어져요. 판 바깥 테두리로 돌아가도 돼요.', + }, + { + pic: ( + + ), + alt: '판에 백 두 장만 남아 한 번 꺾인 선으로 이어져 있어요', + title: '모두 없애면 승리', + text: '패를 모두 없애면 다 푼 거예요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 이을 쌍이 없으면 저절로 섞여요.', + }, +]; diff --git a/apps/web/src/games/solitaire/help.ts b/apps/web/src/games/solitaire/help.ts new file mode 100644 index 0000000..c1797be --- /dev/null +++ b/apps/web/src/games/solitaire/help.ts @@ -0,0 +1,29 @@ +/** 솔리테어 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { Mode, SolitaireView } from '@bg/games/solitaire'; +import type { PublicUser } from '@bg/shared/lite'; +import { raceHelp } from '../race/text'; + +const HOW: Record = { + klondike: [ + '클론다이크: 줄에는 색을 번갈아 하나씩 작은 수를 쌓고, 빈 줄에는 K만 놓아요. 카드를 옮기면 아래 뒤집힌 카드가 열려요.', + '더미를 누르면 카드를 넘겨요. 더미가 비면 버린 카드를 다시 뒤집어 써요. A부터 무늬별로 52장을 모두 파운데이션에 올리면 다 푼 거예요.', + ], + freecell: [ + '프리셀: 모든 카드가 앞면이에요. 줄에는 색을 번갈아 하나씩 작은 수를 쌓고, 빈 칸 4개에는 카드를 한 장씩 잠깐 둘 수 있어요.', + '여러 장은 (빈 칸 수 + 1) × 2^(빈 줄 수)장까지 한 번에 옮겨요. 52장을 모두 파운데이션에 올리면 다 푼 거예요.', + ], + spider: [ + '스파이더: 무늬와 상관없이 하나 작은 수를 쌓지만, 함께 옮길 수 있는 건 같은 무늬로 이어진 카드뿐이에요.', + 'K부터 A까지 같은 무늬 한 줄이 되면 저절로 빠져요. 8줄을 모두 빼면 다 푼 거예요. 더미를 누르면 열 줄에 한 장씩 나눠요(빈 줄이 있으면 못 나눠요).', + ], +}; +const COMMON = ['카드를 눌러 고르고 놓을 곳을 눌러요. 두 번 누르면 파운데이션으로 올라가요. [되돌리기]로 한 수씩 되돌릴 수 있어요(횟수가 결과에 적혀요).']; + +export function helpNow(v: SolitaireView, me: string | null, players: Record): string { + const lines = raceHelp(v, me, players, [...HOW[v.options.mode], ...COMMON], '실패했어요.'); + const b = v.board; + if (!b || v.phase !== 'playing') return lines; + if (b.mode === 'spider') return `${lines}\n더미에서 ${b.stock / 10}번 더 나눌 수 있어요.`; + if (b.mode === 'klondike') return `${lines}\n더미에 ${b.stock}장, 버린 카드 ${b.waste.length}장이 있어요.`; + return `${lines}\n빈 칸 ${b.cells.filter((c) => !c).length}개가 비어 있어요.`; +} diff --git a/apps/web/src/games/solitaire/index.tsx b/apps/web/src/games/solitaire/index.tsx new file mode 100644 index 0000000..3f87696 --- /dev/null +++ b/apps/web/src/games/solitaire/index.tsx @@ -0,0 +1,510 @@ +/** 솔리테어 화면 (docs/games/solitaire.md §9). */ +import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent } from 'react'; +import { + MODE_NAME, + TIME_CHOICES, + canAuto, + freecellCapacity, + isRun, + moveProblem, + rankOf, + type Mode, + type SolitaireBoardView, + type SolitaireMove, + type SolitaireOptions, + type SolitaireView, +} from '@bg/games/solitaire'; +import type { PublicUser } from '@bg/shared/lite'; +import { PLAYING_CARD_CREDIT, PlayingCard, cardAria } from '../../components/cards/PlayingCard'; +import { haptic, sfx, tone } from '../../lib/feedback'; +import { fxMs } from '../../lib/motion'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit'; +import { helpNow } from './help'; +import { quickStart } from './quick'; + +const FAIL = '실패했어요.'; +const DOUBLE_TAP_MS = 380; + +const CSS = ` +.sl-felt { width: 100%; border-radius: 14px; background: var(--felt); box-shadow: inset 0 0 40px rgba(0,0,0,.25), var(--shadow); color: #fff; + user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation; } +.sl-row { display: grid; justify-content: center; align-items: start; } +.sl-pile { position: relative; } +.sl-slot { display: flex; align-items: center; justify-content: center; border-radius: 8%/6%; border: 2px dashed rgba(255,255,255,.45); background: rgba(0,0,0,.12); + color: rgba(255,255,255,.7); font-weight: 900; padding: 0; cursor: pointer; font-family: inherit; } +.sl-slot[data-hint='true'] { border-color: #fbbf24; border-style: solid; background: rgba(251,191,36,.18); } +.sl-slot:disabled { cursor: default; } +.sl-card { position: absolute; left: 0; padding: 0; border: 0; background: none; cursor: pointer; display: block; border-radius: 9%/6%; } +.sl-card:disabled, span.sl-card { cursor: default; } +.sl-card:focus-visible, .sl-slot:focus-visible, .sl-stock:focus-visible { outline: 3px solid #fbbf24; outline-offset: 2px; z-index: 50; } +.sl-stock { position: relative; padding: 0; border: 0; background: none; cursor: pointer; display: block; } +.sl-stock:disabled { cursor: default; } +.sl-badge { position: absolute; right: -4px; bottom: -6px; min-width: 22px; padding: 1px 5px; border-radius: 999px; background: #111827; color: #fff; font-size: .72rem; + font-weight: 800; font-variant-numeric: tabular-nums; box-shadow: 0 1px 3px rgba(0,0,0,.4); pointer-events: none; } +.sl-in { animation: sl-in .26s ease-out both; } +.sl-shake { animation: sl-shake .3s ease-in-out; } +@keyframes sl-in { from { transform: translateY(-14px) scale(1.06); opacity: .5; } } +@keyframes sl-shake { 25% { transform: translateX(-5px); } 75% { transform: translateX(5px); } } +@media (prefers-reduced-motion: reduce) { .sl-in, .sl-shake { animation: none; } } +`; + +interface Sel { + from: string; + n: number; +} + +const colsOf = (mode: Mode) => (mode === 'klondike' ? 7 : mode === 'freecell' ? 8 : 10); +const fTotal = (f: string[]) => f.reduce((n, c) => n + (c ? rankOf(c) : 0), 0); +const pileName = (id: string) => + id === 'w' ? '버린 카드' : id === 'f' ? '파운데이션' : id[0] === 't' ? `${Number(id.slice(1)) + 1}번째 줄` : id[0] === 'c' ? `빈 칸 ${Number(id.slice(1)) + 1}` : `파운데이션 ${Number(id.slice(1)) + 1}`; + +/** Every visible card on its pile ("t3:4" → "KS"), to spot cards that just arrived. */ +function cardSpots(b: SolitaireBoardView): Map { + const out = new Map(); + b.t.forEach((c, i) => c.forEach((x, k) => out.set(`t${i}:${k}`, x ?? ''))); + b.waste.forEach((x, k) => out.set(`w:${k}`, x)); + b.cells.forEach((x, i) => x && out.set(`c${i}:0`, x)); + b.f.forEach((x, i) => x && out.set(`f${i}:0`, x)); + return out; +} + +function SolBoard({ view: v, me, players, act }: BoardProps) { + const { now, left, elapsed, countdown, mine } = useRaceClock(v, me); + const phone = useNarrow(); + const b = v.board; + const [sel, setSel] = useState(null); + const [announce, setAnnounce] = useState(''); + const [fresh, setFresh] = useState>(new Set()); + const [shake, setShake] = useState(0); + const [box, setBox] = useState({ w: 0, h: 800 }); + const wrapRef = useRef(null); + const lastTap = useRef<{ key: string; at: number } | null>(null); + const prev = useRef(null); + const bKey = b ? JSON.stringify(b) : ''; + const playing = canPlayNow(v, me, now); + + useLayoutEffect(() => { + const el = wrapRef.current; + if (!el) return; + const update = () => { + const playH = parseFloat(getComputedStyle(el).getPropertyValue('--play-h')); + setBox({ w: el.clientWidth, h: Number.isFinite(playH) && playH > 0 ? playH : window.innerHeight }); + }; + update(); + const ro = new ResizeObserver(update); + ro.observe(el); + return () => ro.disconnect(); + }, [!!b]); + + // Cards that just arrived slide in; sounds for what changed. Any change ends the current selection. + useEffect(() => { + const was = prev.current; + prev.current = b; + setSel(null); + if (!b || !was) return; + const before = cardSpots(was); + const added = new Set(); + for (const [k, c] of cardSpots(b)) if (c && before.get(k) !== c) added.add(k); + const up = fTotal(b.f) - fTotal(was.f); + if (b.done.length > was.done.length) { + sfx.good(); + haptic([20, 30, 20]); + setAnnounce(`K부터 A까지 한 줄을 완성해서 뺐어요. 완성 ${b.done.length}/8줄`); + } else if (up > 0) { + [1046, 1318].forEach((f, i) => tone(f, 70, 'triangle', 0.1, i * 60)); + setAnnounce(`파운데이션에 올렸어요. 올린 카드 ${fTotal(b.f)}/52`); + } else if (b.stock < was.stock && b.mode === 'spider') sfx.deal(10, 35); + else if (b.stock !== was.stock || b.waste.length !== was.waste.length) sfx.cardFlip(); + else if (added.size) sfx.cardPlay(); + if (b.undos > was.undos) setAnnounce('한 수 되돌렸어요.'); + if (added.size) { + setFresh(added); + const t = setTimeout(() => setFresh(new Set()), fxMs(300)); + return () => clearTimeout(t); + } + }, [bKey]); + + if (!b) { + return ( +
+ + + +
+ + +
+
+ ); + } + + // Card size: the columns fill the width (phones: 7–8 columns ≈ 47 px, 10 columns ≈ 34 px). + const N = colsOf(b.mode); + const gap = phone ? (N >= 10 ? 2 : 4) : N >= 10 ? 8 : 12; + const pad = phone ? 4 : 14; + const w = Math.max(24, Math.min(N >= 10 ? 78 : 96, Math.floor((box.w - 2 * pad - gap * (N - 1)) / N))); + const h = Math.round(w * 1.4); + const colMax = phone ? Infinity : Math.max(h * 3, box.h - h - 230); + const offsets = (col: (string | null)[]) => { + const downs = col.filter((x) => x === null).length; + const ups = col.length - downs; + let dOff = Math.round(h * 0.11); + let uOff = Math.round(h * (phone ? 0.3 : 0.38)); + if (h + downs * dOff + Math.max(0, ups - 1) * uOff > colMax) { + dOff = Math.max(3, Math.round(h * 0.05)); + uOff = Math.max(Math.round(h * 0.24), Math.floor((colMax - h - downs * dOff) / Math.max(1, ups - 1))); + } + let y = 0; + return col.map((x) => { + const top = y; + y += x === null ? dOff : uOff; + return top; + }); + }; + const grid: CSSProperties = { gridTemplateColumns: `repeat(${N}, ${w}px)`, gap, padding: `${pad}px ${pad}px 0` }; + + const tops = (pile: string): number => { + if (pile === 'w') return b.waste.length - 1; + if (pile[0] === 't') return b.t[Number(pile.slice(1))]!.length - 1; + return 0; + }; + const cardAt = (pile: string, i: number): string | null => { + if (pile === 'w') return b.waste[i] ?? null; + if (pile[0] === 't') return b.t[Number(pile.slice(1))]![i] ?? null; + if (pile[0] === 'c') return b.cells[Number(pile.slice(1))] || null; + return b.f[Number(pile.slice(1))] || null; + }; + const nope = (why: string) => { + setAnnounce(why); + setShake((x) => x + 1); + tone(220, 110, 'sine', 0.07); + haptic(15); + }; + const send = (m: SolitaireMove) => { + const why = moveProblem(b, m); + if (why) return nope(why); + act(m); + }; + const dropOn = (pile: string) => { + if (!sel) return; + setSel(null); + const m: SolitaireMove = { type: 'move', from: sel.from, n: sel.n, to: pile }; + // A foundation tap means "up there": use the slot that fits when the tapped one does not. + if (pile[0] === 'f' && moveProblem(b, m)) m.to = 'f'; + send(m); + }; + const toFoundation = (pile: string) => { + const m: SolitaireMove = { type: 'move', from: pile, n: 1, to: 'f' }; + setSel(null); + send(m); + }; + + const tapCard = (pile: string, i: number) => { + if (!playing) return; + const t = performance.now(); + const key = `${pile}:${i}`; + const dbl = lastTap.current?.key === key && t - lastTap.current.at < DOUBLE_TAP_MS; + lastTap.current = dbl ? null : { key, at: t }; + const card = cardAt(pile, i); + if (dbl && pile[0] !== 'f' && i === tops(pile) && !moveProblem(b, { type: 'move', from: pile, n: 1, to: 'f' })) return toFoundation(pile); + if (sel && sel.from !== pile && pile !== 'w') return dropOn(pile); + if (!card) return; + const n = pile[0] === 't' ? b.t[Number(pile.slice(1))]!.length - i : 1; + if (sel && sel.n === n) { + setSel(null); + setAnnounce('고른 카드를 내려놓았어요.'); + return; + } + if (pile[0] === 'f' && b.mode !== 'klondike') return nope('올린 카드는 내릴 수 없어요.'); + if (pile[0] === 't' && !isRun(b.mode, b.t[Number(pile.slice(1))]!.slice(i))) + return nope(b.mode === 'spider' ? '같은 무늬로 이어진 카드만 함께 옮길 수 있어요.' : '색이 번갈아 하나씩 작아지게 이어진 카드만 함께 옮길 수 있어요.'); + setSel({ from: pile, n }); + sfx.select(); + setAnnounce(`${cardAria(card)}${n > 1 ? `부터 ${n}장` : ''}을 골랐어요. 놓을 곳을 눌러요.`); + }; + const onCardKey = (pile: string, i: number) => (e: ReactKeyboardEvent) => { + if (e.key === 'Escape') { + setSel(null); + setAnnounce('고르기를 그만뒀어요.'); + } else if ((e.key === 'f' || e.key === 'F' || e.key === 'ㄹ') && i === tops(pile) && pile[0] !== 'f') { + e.preventDefault(); + if (playing) toFoundation(pile); + } + }; + const tapStock = () => { + if (!playing) return; + setSel(null); + send(b.mode === 'spider' ? { type: 'deal' } : { type: 'draw' }); + }; + + /** Piles the selected cards may go to (a soft glow helps beginners). */ + const fits = (to: string) => !!sel && sel.from !== to && moveProblem(b, { type: 'move', from: sel.from, n: sel.n, to }) === null; + const isSel = (pile: string, i: number) => !!sel && sel.from === pile && i >= tops(pile) - sel.n + 1; + + const cardButton = (pile: string, i: number, card: string, style: CSSProperties, label: string) => ( + + ); + const slot = (pile: string, text: string, label: string, onClick?: () => void) => ( + + ); + + // Top row: stock / waste / foundations (Klondike), free cells / foundations (FreeCell), stock / completed runs (Spider). + const stockLeft = b.mode === 'spider' ? b.stock / 10 : b.stock; + const stock = ( +
+ {b.stock > 0 || b.mode === 'spider' ? ( + + ) : ( + slot('s', b.waste.length ? '↻' : '', b.waste.length ? '버린 카드를 다시 더미로 뒤집기' : '더미가 비었어요', tapStock) + )} +
+ ); + const fan = b.draw === 3 ? Math.round(w * 0.32) : 0; + const shownWaste = b.waste.slice(-(b.draw === 3 ? 3 : 2)); + const waste = ( +
+ {!b.waste.length && } + {shownWaste.map((c, k) => { + const i = b.waste.length - shownWaste.length + k; + const x = b.draw === 3 ? k * fan : 0; + return i === b.waste.length - 1 ? ( + cardButton('w', i, c, { left: x, top: 0 }, `버린 카드 맨 위 ${cardAria(c)}. 두 번 누르면 파운데이션으로`) + ) : ( + + + + ); + })} +
+ ); + const foundations = b.f.map((c, i) => ( +
+ {c ? cardButton(`f${i}`, 0, c, { top: 0 }, `파운데이션 ${i + 1}, 맨 위 ${cardAria(c)}`) : slot(`f${i}`, 'A', `파운데이션 ${i + 1}, 비었어요`)} +
+ )); + const cells = b.cells.map((c, i) => ( +
+ {c ? cardButton(`c${i}`, 0, c, { top: 0 }, `빈 칸 ${i + 1}의 ${cardAria(c)}`) : slot(`c${i}`, '', `빈 칸 ${i + 1}, 비었어요`)} +
+ )); + const done = Array.from({ length: 8 }, (_, i) => ( +
+ {b.done[i] ? : } +
+ )); + + const columns = b.t.map((col, i) => { + const pile = `t${i}`; + const ys = offsets(col); + const height = (ys.at(-1) ?? 0) + h; + return ( +
+ {!col.length && slot(pile, b.mode === 'klondike' ? 'K' : '', `${i + 1}번째 줄, 비었어요${b.mode === 'klondike' ? '. K만 놓을 수 있어요' : ''}`)} + {col.map((c, k) => + c === null ? ( + + + + ) : ( + cardButton(pile, k, c, { top: ys[k] }, `${i + 1}번째 줄 ${k + 1}번째 ${cardAria(c)}${k === col.length - 1 ? ', 맨 위' : ''}`) + ), + )} +
+ ); + }); + + const autoOk = b.mode !== 'spider' && canAuto(b); + return ( +
+ + + {MODE_NAME[b.mode]} + + {b.mode === 'spider' ? '🂮' : '🂡'} {b.mode === 'spider' ? `${b.done.length}/8` : `${fTotal(b.f)}/52`} + + {b.mode === 'freecell' && ( + + ⇅ {freecellCapacity(b, false)}장 + + )} + {b.undos > 0 && ↶ {b.undos}} + + +
+
+
+ {b.mode === 'klondike' && [stock, waste, ...foundations]} + {b.mode === 'freecell' && [...cells, ...foundations]} + {b.mode === 'spider' && [stock, ...done]} +
+
+ {columns} +
+
+ +
+ {mine && playing && ( +
+ + {b.mode !== 'spider' && ( + + )} + +
+ )} + {!phone && mine && v.phase !== 'ended' &&

카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로 · 키보드: Tab으로 옮기고 Enter로 고르기·놓기, F 파운데이션, Esc 취소

} + {phone && mine && playing &&

카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로

} +

+ {announce} +

+
+ ); +} + +const modeInfo = (o: SolitaireOptions) => + o.mode === 'klondike' ? `클론다이크 · ${o.draw}장씩 넘기기` : o.mode === 'spider' ? `스파이더 · 무늬 ${o.suits}가지` : '프리셀 · 빈 칸 4개'; + +function SolSide(props: BoardProps) { + return ; +} + +const PLAYING_LINE: Record = { + klondike: '색을 번갈아 하나씩 작게 쌓고, A부터 무늬별로 파운데이션에 올려요', + freecell: '빈 칸 4개를 잘 써서 모든 카드를 A부터 무늬별로 올려요', + spider: '하나 작은 수 위에 쌓아 K부터 A까지 같은 무늬 한 줄을 만들어요', +}; + +function statusText(v: SolitaireView, me: string | null, players: Record): string { + return raceStatusText(v, me, players, { countdown: `곧 시작해요! ${MODE_NAME[v.options.mode]} · 모두 같은 패예요`, playing: PLAYING_LINE[v.options.mode], failed: FAIL }); +} + +function Options({ value: o, onChange }: OptionsProps) { + return ( +
+
+ 종류 + [m, MODE_NAME[m]])} onChange={(mode) => onChange({ ...o, mode })} /> + + {o.mode === 'klondike' + ? '일곱 줄, 더미에서 카드를 넘겨 가며 풀어요.' + : o.mode === 'freecell' + ? '모든 카드가 앞면으로 여덟 줄. 빈 칸 4개를 잠깐 쓸 수 있어요.' + : '카드 두 벌로 열 줄. K부터 A까지 같은 무늬 한 줄을 만들면 빠져요.'} + +
+ {o.mode === 'klondike' && ( +
+ 한 번에 넘기는 카드 + onChange({ ...o, draw })} /> +
+ )} + {o.mode === 'spider' && ( +
+ 무늬 수 + onChange({ ...o, suits })} /> +
+ )} + onChange({ ...o, timeLimitSec: timeLimitSec as SolitaireOptions['timeLimitSec'] })} /> +
+ ); +} + +function optionsSummary(o: SolitaireOptions): string { + return `${modeInfo(o)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`; +} + +function Rules({ options }: { options?: SolitaireOptions }) { + const o = options ?? { mode: 'klondike', draw: 1, suits: 1, timeLimitSec: 900 }; + return ( +
+

+ 윈도우에 있던 그 카드놀이예요. 모두 똑같은 패를 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요. 지금은 {modeInfo(o)}, 제한 시간 {limitLabel(o.timeLimitSec)}이에요. +

+
+ + + + 줄에는 색을 번갈아 하나씩 작은 수를 쌓아요(스파이더는 색 상관없이). +
+

+ 클론다이크: 일곱 줄 가운데 맨 위만 앞면이에요. 아래 카드를 옮기면 뒤집힌 카드가 저절로 열려요. 빈 줄에는 K만 놓을 수 있어요. 더미를 누르면 카드를 1장(또는 3장)씩 넘기고, + 더미가 비면 버린 카드를 다시 뒤집어 써요. +

+

+ 프리셀: 모든 카드가 앞면이에요. 빈 칸 4개에 카드를 한 장씩 잠깐 둘 수 있고, 빈 줄에는 아무 카드나 놓아요. 여러 장은 (빈 칸 수 + 1) × 2^(빈 줄 수)장까지 한 번에 옮겨요. +

+

+ 스파이더: 카드 두 벌로 열 줄이에요. 무늬와 상관없이 하나 작은 수를 쌓지만, 함께 옮길 수 있는 건 같은 무늬로 이어진 카드뿐이에요. K부터 A까지 같은 무늬 한 줄이 되면 저절로 + 빠져요. 더미를 누르면 열 줄에 한 장씩 나눠 주는데, 빈 줄이 있으면 나눌 수 없어요. +

+

+ 카드를 눌러 고르고(위에 얹힌 카드까지 함께) 놓을 곳을 눌러요. 두 번 누르면 파운데이션으로 올라가요. [자동 정리]는 올릴 수 있는 카드를 모두 올려요. [되돌리기]는 몇 번이든 쓸 수 있지만 결과에 횟수가 + 적혀요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 가장 많이 올린(스파이더는 많이 완성한) 사람이 이겨요. 클론다이크는 가끔 풀 수 없는 패도 나와요. +

+

{PLAYING_CARD_CREDIT}

+
+ ); +} + +const ui: GameUI = { + Board: SolBoard, + Side: SolSide, + statusText, + liveStatus: true, + isMyTurn: raceIsMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/solitaire/quick.tsx b/apps/web/src/games/solitaire/quick.tsx new file mode 100644 index 0000000..2bed08c --- /dev/null +++ b/apps/web/src/games/solitaire/quick.tsx @@ -0,0 +1,63 @@ +/** 솔리테어 30초 규칙 요약 (docs/07 §5). Small tables drawn with the real playing cards. */ +import { PlayingCard } from '../../components/cards/PlayingCard'; +import type { QuickCard } from '../types'; + +/** A fanned column: face-down cards (null) then face-up ones. */ +function Fan({ cards, w = 34 }: { cards: (string | null)[]; w?: number }) { + const h = Math.round(w * 1.4); + let y = 0; + const ys = cards.map((c) => { + const top = y; + y += c === null ? h * 0.12 : h * 0.3; + return top; + }); + return ( + + {cards.map((c, i) => ( + + + + ))} + + ); +} + +const row = { display: 'inline-flex', gap: 6, alignItems: 'flex-start' } as const; + +export const quickStart: QuickCard[] = [ + { + pic: ( + + + + + ), + alt: '두 줄에 카드가 색을 번갈아 하나씩 작은 수로 쌓여 있어요', + title: '색을 번갈아 내려 쌓기', + text: '줄에는 색을 번갈아 하나씩 작은 수를 쌓아요. 모두 똑같은 패를 각자 풀어요.', + }, + { + pic: ( + + + + + + ), + alt: '하트 A, 2, 3이 차례로 놓여 있어요', + title: 'A부터 무늬별로 올리기', + text: '파운데이션에 A부터 같은 무늬로 차례대로 올려요. 두 번 누르면 바로 올라가요.', + }, + { + pic: ( + + + + + + ), + alt: '스페이드가 K부터 차례로 이어진 줄과 완성한 줄이에요', + title: '세 가지 솔리테어', + text: '클론다이크·프리셀은 52장을 다 올리면, 스파이더는 K→A 같은 무늬 8줄을 빼면 다 풀어요.', + }, +]; diff --git a/apps/web/src/games/sudoku/art.tsx b/apps/web/src/games/sudoku/art.tsx new file mode 100644 index 0000000..30a23e6 --- /dev/null +++ b/apps/web/src/games/sudoku/art.tsx @@ -0,0 +1,53 @@ +/** 스도쿠 small pictures for the rules and the summary cards (SVG, no image files). */ + +const U = 32; + +/** + * A few rows of cells. Per char: '1'..'9' given (bold), 'a'..'i' my number 1..9 (blue), '.' empty, '*' the selected + * empty cell. `bad` cells are red (a digit twice), `notes` puts small pencil marks in empty cells, `box` draws thick + * lines every 3 cells. + */ +export function MiniSudoku({ rows, bad = [], notes = {}, box = true, size = 28 }: { rows: string[]; bad?: number[]; notes?: Record; box?: boolean; size?: number }) { + const cols = rows[0]!.length; + const w = cols * U; + const h = rows.length * U; + return ( + + {rows.flatMap((row, r) => + [...row].map((ch, c) => { + const i = r * cols + c; + const x = c * U; + const y = r * U; + const mine = ch >= 'a' && ch <= 'i'; + const d = mine ? String(ch.charCodeAt(0) - 96) : ch >= '1' && ch <= '9' ? ch : ''; + const red = bad.includes(i); + return ( + + + {ch === '*' && } + {d && ( + + {d} + + )} + {!d && + [...(notes[i] ?? '')].map((n) => { + const k = Number(n) - 1; + return ( + + {n} + + ); + })} + + ); + }), + )} + {box && + Array.from({ length: Math.floor(cols / 3) + 1 }, (_, k) => )} + {box && + Array.from({ length: Math.floor(rows.length / 3) + 1 }, (_, k) => )} + {!box && } + + ); +} diff --git a/apps/web/src/games/sudoku/help.ts b/apps/web/src/games/sudoku/help.ts new file mode 100644 index 0000000..b6bac99 --- /dev/null +++ b/apps/web/src/games/sudoku/help.ts @@ -0,0 +1,41 @@ +/** 스도쿠 [?] "지금 할 수 있는 것" (docs/07 §5) and the conflict check the board uses. Pure: only reads the client view. */ +import type { SudokuView } from '@bg/games/sudoku'; +import type { PublicUser } from '@bg/shared/lite'; +import { raceHelp } from '../race/text'; + +/** Cells whose digit shows up twice in a row, column or box (visible numbers only, no answer). */ +export function conflicts(values: string): Set { + const out = new Set(); + const units: number[][] = []; + for (let k = 0; k < 9; k++) { + units.push(Array.from({ length: 9 }, (_, c) => k * 9 + c)); + units.push(Array.from({ length: 9 }, (_, r) => r * 9 + k)); + units.push(Array.from({ length: 9 }, (_, j) => (Math.floor(k / 3) * 3 + Math.floor(j / 3)) * 9 + (k % 3) * 3 + (j % 3))); + } + for (const u of units) { + const seen = new Map(); + for (const i of u) if (values[i] !== '0') seen.set(values[i]!, [...(seen.get(values[i]!) ?? []), i]); + for (const cells of seen.values()) if (cells.length > 1) for (const i of cells) out.add(i); + } + return out; +} + +const HOW = [ + '가로줄·세로줄·굵은 선 3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채워요. 다 맞게 채우면 다 푼 거예요.', + '칸을 고르고 아래 숫자를 누르거나 키보드로 숫자를 쳐요. 맞는지는 알려 주지 않아요(종이처럼). 같은 줄·상자에 같은 숫자가 겹치면 빨갛게 보여요.', + '[메모]를 켜면 숫자가 작은 후보 메모로 들어가요. 숫자를 넣으면 같은 줄·칸·상자의 그 숫자 메모는 지워져요.', + '키보드: 화살표로 칸을 옮기고 1~9 넣기, Backspace·Delete·0 지우기, N이나 스페이스로 메모 켜고 끄기예요.', +]; + +export function helpNow(v: SudokuView, me: string | null, players: Record): string { + const lines = raceHelp(v, me, players, HOW, ''); + const b = v.board; + const mine = v.seats.find((s) => s.id === me); + if (!b || v.phase !== 'playing' || mine?.status !== 'playing') return lines; + const extra: string[] = []; + const bad = conflicts(b.values).size; + if (bad) extra.push(`지금 숫자가 겹친 빨간 칸이 ${bad}개 있어요. 둘 중 하나는 틀렸어요.`); + if (v.options.hints) extra.push(`막히면 [💡 힌트]를 눌러요. 빈칸이나 틀린 칸 하나를 맞는 숫자로 채워 줘요(지금까지 ${b.hints}번, 결과에 남아요).`); + else extra.push('이 방은 힌트를 쓸 수 없어요.'); + return [lines, ...extra].join('\n'); +} diff --git a/apps/web/src/games/sudoku/index.tsx b/apps/web/src/games/sudoku/index.tsx new file mode 100644 index 0000000..dfcf81d --- /dev/null +++ b/apps/web/src/games/sudoku/index.tsx @@ -0,0 +1,428 @@ +/** 스도쿠 화면 (docs/games/sudoku.md §9). */ +import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react'; +import { DIFFICULTIES, type Difficulty, type SudokuOptions, type SudokuView } from '@bg/games/sudoku'; +import type { PublicUser } from '@bg/shared/lite'; +import { haptic, sfx, tone } from '../../lib/feedback'; +import { fxMs } from '../../lib/motion'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit'; +import { conflicts, helpNow } from './help'; +import { quickStart } from './quick'; +import { MiniSudoku } from './art'; + +const DIGITS = [1, 2, 3, 4, 5, 6, 7, 8, 9]; +const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x)); +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); + +const CSS = ` +.sd-main { display: flex; gap: 18px; align-items: flex-start; justify-content: center; width: 100%; } +.sd-main.phone { flex-direction: column; align-items: stretch; gap: 10px; } +.sd-grid { display: grid; grid-template-columns: repeat(9, 1fr); grid-template-rows: repeat(9, 1fr); aspect-ratio: 1; width: 100%; + background: var(--surface); border: 3px solid var(--text); border-radius: 8px; overflow: hidden; box-shadow: var(--shadow); + user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation; outline: none; cursor: pointer; } +.sd-grid:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); } +.sd-grid[data-off='true'] { cursor: default; } +.sd-cell { position: relative; display: flex; align-items: center; justify-content: center; min-width: 0; min-height: 0; + border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); font-variant-numeric: tabular-nums; + font-size: clamp(1.15rem, 6vw, 2rem); line-height: 1; transition: background-color .12s; } +.sd-cell[data-c='2'], .sd-cell[data-c='5'] { border-right: 2px solid var(--text); } +.sd-cell[data-c='8'] { border-right: 0; } +.sd-cell[data-r='2'], .sd-cell[data-r='5'] { border-bottom: 2px solid var(--text); } +.sd-cell[data-r='8'] { border-bottom: 0; } +.sd-cell.peer { background: var(--surface-2); } +.sd-cell.same { background: var(--primary-soft); } +.sd-cell.hint { background: var(--warning-soft); } +.sd-cell.sel { background: var(--primary-soft); box-shadow: inset 0 0 0 3px var(--primary); } +.sd-cell .d { font-weight: 600; color: var(--primary); } +.sd-cell[data-given='true'] .d { font-weight: 900; color: var(--text); } +.sd-cell.same .d { text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 3px; } +.sd-cell.bad { background: var(--danger-soft); } +.sd-cell.bad .d { color: var(--danger); } +.sd-cell.sol .d { color: var(--success); font-weight: 600; opacity: .85; } +.sd-cell.wrong { background: var(--danger-soft); } +.sd-cell.wrong .d { color: var(--success); } +.sd-notes { position: absolute; inset: 2px; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr); + font-size: clamp(.55rem, 2.6vw, .78rem); font-weight: 700; color: var(--text-sub); line-height: 1; } +.sd-notes span { display: flex; align-items: center; justify-content: center; } +.sd-notes span.on { color: var(--primary); } +.sd-pop .d { animation: sd-pop .3s ease-out both; } +.sd-glow { animation: sd-glow .9s ease-out both; } +@keyframes sd-pop { from { transform: scale(.4); opacity: .3; } 60% { transform: scale(1.18); } to { transform: scale(1); opacity: 1; } } +@keyframes sd-glow { 0% { box-shadow: inset 0 0 0 0 var(--warning); } 40% { box-shadow: inset 0 0 0 5px var(--warning); } 100% { box-shadow: inset 0 0 0 0 var(--warning); } } +.sd-pad { display: flex; flex-direction: column; gap: 8px; width: 216px; flex: none; } +.sd-digits { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; } +.sd-tools { display: grid; grid-template-columns: 1fr; gap: 6px; } +.sd-main.phone .sd-pad { width: 100%; } +.sd-main.phone .sd-digits { grid-template-columns: repeat(9, 1fr); gap: 4px; } +.sd-main.phone .sd-tools { grid-template-columns: repeat(3, 1fr); } +.sd-key { position: relative; border: 0; border-radius: 10px; background: var(--surface); color: var(--primary); box-shadow: var(--shadow); cursor: pointer; + font-size: 1.7rem; font-weight: 800; min-height: 64px; padding: 0; font-variant-numeric: tabular-nums; touch-action: manipulation; } +.sd-main.phone .sd-key { min-height: 54px; font-size: 1.45rem; border-radius: 8px; } +.sd-key small { position: absolute; right: 6px; bottom: 4px; font-size: .7rem; font-weight: 700; color: var(--text-sub); } +.sd-main.phone .sd-key small { right: 0; left: 0; bottom: 2px; text-align: center; font-size: .62rem; } +.sd-key[data-done='true'] { opacity: .35; } +.sd-key[data-memo='true'] { color: var(--text-sub); font-size: 1.15rem; } +.sd-key:active { transform: scale(.95); } +.sd-key:disabled { cursor: default; } +.sd-tool { min-height: 44px; border: 0; border-radius: 10px; background: var(--surface-2); color: var(--text); font-weight: 800; font-size: .98rem; cursor: pointer; padding: 0 8px; touch-action: manipulation; } +.sd-tool[aria-pressed='true'] { background: var(--primary); color: var(--primary-text); } +.sd-tool:disabled { opacity: .5; cursor: default; } +@media (prefers-reduced-motion: reduce) { .sd-pop .d, .sd-glow { animation: none; } .sd-key:active { transform: none; } } +`; + +const notesOf = (mask: number) => DIGITS.filter((n) => mask & (1 << n)); + +function SudokuBoardView({ view: v, me, players, act }: BoardProps) { + const { now, left, elapsed, countdown, mine } = useRaceClock(v, me); + const phone = useNarrow(); + const b = v.board; + const [sel, setSel] = useState(40); + const [memo, setMemo] = useState(false); + const [fresh, setFresh] = useState>(new Set()); + const [glow, setGlow] = useState(null); + const [announce, setAnnounce] = useState(''); + const gridRef = useRef(null); + const prev = useRef<{ values: string; notes: string; hints: number; bad: number } | null>(null); + const playing = canPlayNow(v, me, now); + const bad = b ? conflicts(b.values) : new Set(); + + // Pop-in for new numbers, a glow on the hinted cell, sounds for what changed. + useEffect(() => { + if (!b) return; + const cur = { values: b.values, notes: b.notes.join(','), hints: b.hints, bad: bad.size }; + const was = prev.current; + prev.current = cur; + if (!was || was.values.length !== cur.values.length) return; + const added = new Set(); + let cleared = 0; + for (let i = 0; i < 81; i++) { + if (was.values[i] === cur.values[i]) continue; + if (cur.values[i] === '0') cleared++; + else added.add(i); + } + if (cur.hints > was.hints) { + sfx.good(); + setGlow(b.hintAt); + } else if (cur.bad > was.bad) { + tone(240, 120, 'square', 0.05); + haptic([20, 30, 20]); + } else if (added.size) tone(880 + Number(b.values[[...added][0]!]) * 40, 60, 'triangle', 0.1); + else if (cleared) tone(420, 50, 'triangle', 0.07); + else if (cur.notes !== was.notes) tone(1300, 25, 'triangle', 0.05); + const timers: ReturnType[] = []; + if (added.size) { + setFresh(added); + timers.push(setTimeout(() => setFresh(new Set()), fxMs(320))); + } + if (cur.hints > was.hints) timers.push(setTimeout(() => setGlow(null), fxMs(900))); + return () => timers.forEach(clearTimeout); + }, [b?.values, b?.notes.join(','), b?.hints]); + + if (!b) { + return ( +
+ + + +
+ + +
+
+ ); + } + + const given = (i: number) => b.givens[i] === '1'; + const reveal = b.solution; + const counts = DIGITS.map((n) => [...b.values].filter((ch) => ch === String(n)).length); + const describe = (i: number) => { + const where = `${rowOf(i) + 1}줄 ${colOf(i) + 1}칸`; + const ch = b.values[i]!; + if (given(i)) return `${where}, 처음 숫자 ${ch}`; + if (ch !== '0') return `${where}, 내 숫자 ${ch}${bad.has(i) ? ', 겹침' : ''}`; + const ns = notesOf(b.notes[i]!); + return `${where}, 빈칸${ns.length ? `, 메모 ${ns.join(' ')}` : ''}`; + }; + + const select = (i: number, speak: boolean) => { + setSel(i); + if (speak) setAnnounce(describe(i)); + }; + const enter = (n: number) => { + if (!playing) return; + const ch = b.values[sel]!; + if (given(sel)) return setAnnounce('처음부터 있던 숫자는 바꿀 수 없어요.'); + if (memo) { + if (ch !== '0') return setAnnounce('숫자가 있는 칸에는 메모할 수 없어요. 먼저 지워 주세요.'); + act({ type: 'note', i: sel, n }); + setAnnounce(b.notes[sel]! & (1 << n) ? `메모 ${n}을(를) 지웠어요.` : `메모 ${n}을(를) 적었어요.`); + return; + } + haptic(8); + if (ch === String(n)) { + act({ type: 'clear', i: sel }); + setAnnounce(`${n}을(를) 지웠어요.`); + return; + } + act({ type: 'set', i: sel, n }); + const dup = [...b.values].some((c, j) => j !== sel && c === String(n) && (rowOf(j) === rowOf(sel) || colOf(j) === colOf(sel) || boxOf(j) === boxOf(sel))); + setAnnounce(`${n}을(를) 넣었어요.${dup ? ' 같은 줄·칸·상자에 이미 있는 숫자예요.' : ''}`); + }; + const erase = () => { + if (!playing) return; + if (given(sel)) return setAnnounce('처음부터 있던 숫자는 지울 수 없어요.'); + if (b.values[sel] === '0' && !b.notes[sel]) return setAnnounce('지울 것이 없어요.'); + act({ type: 'clear', i: sel }); + setAnnounce('지웠어요.'); + }; + const toggleMemo = () => { + setMemo((m) => !m); + setAnnounce(memo ? '메모 모드를 껐어요. 숫자를 넣어요.' : '메모 모드를 켰어요. 숫자가 작은 메모로 들어가요.'); + }; + const hint = () => { + if (!playing || !v.options.hints) return; + act({ type: 'hint' }); + setAnnounce('힌트로 한 칸을 맞는 숫자로 채웠어요.'); + }; + + const onDown = (e: ReactPointerEvent) => { + const box = gridRef.current!.getBoundingClientRect(); + const c = clamp(Math.floor(((e.clientX - box.left) / box.width) * 9), 0, 8); + const r = clamp(Math.floor(((e.clientY - box.top) / box.height) * 9), 0, 8); + select(r * 9 + c, false); + if (e.pointerType === 'mouse') gridRef.current!.focus({ preventScroll: true }); + }; + + const onKey = (e: ReactKeyboardEvent) => { + const step: Record = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] }; + const m = step[e.key]; + const onButton = (e.target as HTMLElement).tagName === 'BUTTON'; + if (m) { + e.preventDefault(); + select(clamp(rowOf(sel) + m[0], 0, 8) * 9 + clamp(colOf(sel) + m[1], 0, 8), true); + return; + } + const num = /^(Digit|Numpad)([0-9])$/.exec(e.code)?.[2] ?? (/^[0-9]$/.test(e.key) ? e.key : null); + if (num !== null) { + e.preventDefault(); + if (num === '0') erase(); + else enter(Number(num)); + } else if (e.key === 'Backspace' || e.key === 'Delete') { + e.preventDefault(); + erase(); + } else if ((e.key === ' ' && !onButton) || e.key === 'n' || e.key === 'N' || e.key === 'ㅜ') { + e.preventDefault(); + if (!e.repeat) toggleMemo(); + } + }; + + const wrapStyle: CSSProperties = phone ? { width: '100%' } : { width: 'min(100%, 600px, calc(var(--play-h, 100vh) - 150px))', minWidth: 300, flex: '0 1 auto' }; + const showPad = !!mine && mine.status === 'playing' && v.phase === 'playing'; + + return ( +
+ + + {mine && ( + + ✏️ {mine.progressText.replace(/^[^\d]*/, '')} + + )} + {b.hints > 0 && ( + + 💡 {b.hints} + + )} + + +
+
+
e.preventDefault()} + > + {Array.from(b.values, (ch, i) => { + const r = rowOf(i); + const c = colOf(i); + // Selection shading only while I can still play. + const s = playing ? b.values[sel]! : '0'; + const cls = ['sd-cell']; + const sol = reveal && ch !== reveal[i] ? reveal[i]! : null; + if (sol) cls.push(ch === '0' ? 'sol' : 'wrong'); + else if (bad.has(i)) cls.push('bad'); + if (playing && i === sel) cls.push('sel'); + else if (s !== '0' && ch === s) cls.push('same'); + else if (glow === i || (b.hintAt === i && playing)) cls.push('hint'); + else if (playing && (r === rowOf(sel) || c === colOf(sel) || boxOf(i) === boxOf(sel))) cls.push('peer'); + if (fresh.has(i)) cls.push('sd-pop'); + if (glow === i) cls.push('sd-glow'); + const shown = sol ?? (ch !== '0' ? ch : null); + return ( +
+ {shown ? ( + {shown} + ) : b.notes[i] ? ( + + {DIGITS.map((n) => ( + + {b.notes[i]! & (1 << n) ? n : ''} + + ))} + + ) : null} +
+ ); + })} +
+ +
+ {showPad && ( +
+
+ {DIGITS.map((n, k) => { + const rest = 9 - counts[k]!; + return ( + + ); + })} +
+
+ + + {v.options.hints && ( + + )} +
+
+ )} +
+ {mine && playing && ( +
+ +
+ )} + {!phone && showPad &&

칸 클릭 또는 화살표로 고르고 1~9 넣기 · Backspace·Delete·0 지우기 · N·스페이스 메모 켜고 끄기 · 같은 숫자를 다시 누르면 지워요

} + {phone && showPad &&

칸을 누르고 아래 숫자를 눌러요 · 같은 숫자를 다시 누르면 지워요

} + {reveal && v.phase === 'ended' &&

초록 숫자 = 정답(빈칸이었거나 틀린 칸)

} +

+ {announce} +

+
+ ); +} + +const diffInfo = (d: Difficulty) => `${DIFFICULTIES[d].name} · ${DIFFICULTIES[d].givens}`; + +function SudokuSide(props: BoardProps) { + const o = props.view.options; + return ; +} + +function statusText(v: SudokuView, me: string | null, players: Record): string { + return raceStatusText(v, me, players, { countdown: '곧 시작해요! 가로·세로·상자에 1~9를 한 번씩 넣어요', playing: '가로·세로·3×3 상자마다 1~9가 한 번씩 · 빈칸을 모두 맞게 채워요', failed: '' }); +} + +function Options({ value: o, onChange }: OptionsProps) { + return ( +
+
+ 난이도 + [d, DIFFICULTIES[d].name])} + onChange={(difficulty) => onChange({ ...o, difficulty })} + /> + + 처음부터 있는 {DIFFICULTIES[o.difficulty].givens} + {o.difficulty === 'easy' ? ' · 차근차근 하나씩 찾으면 풀려요' : ''} + +
+
+ 힌트 + onChange({ ...o, hints })} + /> + {o.hints ? '[💡 힌트]로 한 칸씩 맞는 숫자를 받을 수 있어요. 쓴 횟수는 결과에 남아요.' : '힌트 없이 풀어요.'} +
+ onChange({ ...o, timeLimitSec: timeLimitSec as SudokuOptions['timeLimitSec'] })} /> +
+ ); +} + +function optionsSummary(o: SudokuOptions): string { + return `${DIFFICULTIES[o.difficulty].name} · 힌트 ${o.hints ? '있음' : '없음'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`; +} + +function Rules({ options }: { options?: SudokuOptions }) { + const d = options?.difficulty ?? 'easy'; + return ( +
+

+ 9×9 판의 가로줄·세로줄·굵은 선 3×3 상자마다 1부터 9까지가 한 번씩 들어가게 빈칸을 채워요. 모두 똑같은 판을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 + 있어요. 답은 딱 하나뿐인 판만 나와요. +

+
+ + 굵은 숫자는 처음부터 있던 것, 파란 숫자는 내가 넣은 것, 작은 숫자는 메모예요. +
+

+ 칸을 고르고 숫자를 넣어요. 맞는지는 알려 주지 않지만(종이처럼), 같은 줄·칸·상자에 같은 숫자가 겹치면 빨갛게 보여요. [메모]를 켜면 후보 숫자를 작게 적어 둘 수 있고, 숫자를 넣으면 같은 줄·칸·상자의 그 숫자 메모는 + 저절로 지워져요. {options?.hints === false ? '이 방은 힌트가 없어요.' : '[💡 힌트]를 누르면 빈칸이나 틀린 칸 하나를 맞는 숫자로 채워 줘요(쓴 횟수는 결과에 남아요).'} +

+

+ 여럿이면 가장 먼저 다 맞게 채운 사람이 이기고, 아무도 못 풀면 많이 채운 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1800)}이고, 지금 난이도는 {diffInfo(d)}예요. +

+

PC: 칸을 클릭하거나 화살표로 고르고 1~9, Backspace로 지우기, N이나 스페이스로 메모. 휴대폰: 칸을 누르고 아래 숫자 버튼을 눌러요.

+
+ ); +} + +const ui: GameUI = { + Board: SudokuBoardView, + Side: SudokuSide, + statusText, + liveStatus: true, + isMyTurn: raceIsMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/sudoku/quick.tsx b/apps/web/src/games/sudoku/quick.tsx new file mode 100644 index 0000000..bc5a835 --- /dev/null +++ b/apps/web/src/games/sudoku/quick.tsx @@ -0,0 +1,24 @@ +/** 스도쿠 30초 규칙 요약 (docs/07 §5). Small grids drawn with the game's own look. */ +import type { QuickCard } from '../types'; +import { MiniSudoku } from './art'; + +export const quickStart: QuickCard[] = [ + { + pic: , + alt: '굵은 선 3×3 상자 하나에 숫자 몇 개가 처음부터 들어 있어요', + title: '1~9를 한 번씩', + text: '가로줄·세로줄·3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채워요. 모두 똑같은 판을 각자 풀어요.', + }, + { + pic: , + alt: '고른 칸이 파랗게 표시되고, 내가 넣은 숫자는 파란색, 빈칸에는 작은 메모가 있어요', + title: '칸을 고르고 숫자', + text: '칸을 누르고 아래 숫자를 눌러요. [메모]를 켜면 작은 후보 숫자로 적어 둘 수 있어요.', + }, + { + pic: , + alt: '같은 줄에 9가 두 번 들어가 두 칸이 빨갛게 보여요', + title: '겹치면 빨강', + text: '같은 줄·상자에 같은 숫자가 겹치면 빨갛게 보여요. 다 맞게 채우면 끝! 여럿이면 가장 먼저 푼 사람이 이겨요.', + }, +]; diff --git a/apps/web/src/lib/catalog-ui.ts b/apps/web/src/lib/catalog-ui.ts index f074ee3..0298839 100644 --- a/apps/web/src/lib/catalog-ui.ts +++ b/apps/web/src/lib/catalog-ui.ts @@ -36,6 +36,11 @@ export const GAME_ICON: Record = { 'six-nimmt': '🐮', gemblo: '💠', typing: '⌨️', + minesweeper: '💣', + shisen: '🀄', + solitaire: '♥', + sudoku: '🧮', + nonogram: '🧩', 'hot-streak': '🏁', tichu: '🐉', 'case-file': '🔍', @@ -50,4 +55,5 @@ export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [ { key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue', 'gemblo', 'castles-of-burgundy'] }, { key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code', 'six-nimmt', 'tichu'] }, { key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple', 'typing', 'hot-streak', 'case-file'] }, + { key: 'solo', label: '혼자·퍼즐', ids: ['minesweeper', 'shisen', 'solitaire', 'sudoku', 'nonogram', 'apple', 'typing', 'yacht', 'blackjack', 'case-file', 'castles-of-burgundy'] }, ]; diff --git a/docs/games/README.md b/docs/games/README.md index 7c6b176..ba2ded8 100644 --- a/docs/games/README.md +++ b/docs/games/README.md @@ -54,6 +54,11 @@ | `case-file` | 사건 파일 | 1~5 | 2026-10 새 게임 | | `castles-of-burgundy` | 버건디의 성 | 1~4 | 2026-10 새 게임 | | `typing` | 타자 대결 | 1~8 | 2026-11 새 게임 | +| `minesweeper` | 지뢰찾기(같은 판 경주, [공통 틀](race.md)) | 1~8 | 2026-11 새 게임 | +| `shisen` | 사천성(같은 판 경주, [공통 틀](race.md)) | 1~8 | 2026-11 새 게임 | +| `solitaire` | 솔리테어(클론다이크·프리셀·스파이더, 같은 판 경주) | 1~8 | 2026-11 새 게임 | +| `sudoku` | 스도쿠(같은 판 경주, [공통 틀](race.md)) | 1~8 | 2026-11 새 게임 | +| `nonogram` | 네모네모 로직(같은 판 경주, [공통 틀](race.md)) | 1~8 | 2026-11 새 게임 | 인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선). diff --git a/docs/games/minesweeper.md b/docs/games/minesweeper.md new file mode 100644 index 0000000..8b6525c --- /dev/null +++ b/docs/games/minesweeper.md @@ -0,0 +1,67 @@ +# 지뢰찾기 (`minesweeper`) + +> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 1~10분 · 난이도: 쉬움 + +## 1. 개요 +- 윈도우에 들어 있던 그 지뢰찾기. 숫자(주변 8칸의 지뢰 수)를 보고 지뢰가 없는 칸을 모두 연다. +- 원작은 혼자 하는 기록 도전이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 판을 각자 풀고 가장 먼저 다 연 사람이 이긴다. 혼자서도 한다. + +## 2. 모드와 옵션 +| 옵션 키 | 설명 | 선택지 | 기본값 | +|---|---|---|---| +| `level` | 난이도 | 초급 9×9 지뢰 10 / 중급 16×16 지뢰 40 / 고급 16×30 지뢰 99 (윈도우와 같음) | 초급 | +| `timeLimitSec` | 제한 시간 | 3분 / 5분 / 10분 / 20분 / 무제한 | 10분 | + +## 3~4. 구성과 준비 +- 시드로 **시작 칸** 하나를 고르고, 그 칸과 둘레 8칸을 뺀 곳에 지뢰를 고르게 놓는다. 시작 칸은 0이라 둘레가 열린다. +- 원작의 "첫 클릭에는 지뢰가 없게"를 같은 판 경주에 맞춘 것: 첫 클릭이 사람마다 다르면 판이 달라지므로, 대신 **모두에게 같은 곳이 열린 채로** 시작한다. + +## 5. 진행 규칙 +- 열기(`open`): 닫힌 칸, 깃발이 없을 때. 지뢰면 실패(`failed`), 0이면 이어진 0 영역과 그 둘레까지 연다. +- 깃발(`flag`): 닫힌 칸에 꽂기/치우기. 깃발 칸은 열 수 없다. +- 한꺼번에 열기(`chord`): 연 숫자 칸의 둘레 깃발 수 = 숫자이고 닫힌 칸이 남았을 때, 깃발 없는 둘레를 모두 연다. 깃발이 틀렸으면 지뢰가 터진다(원작과 같음). +- 지뢰 없는 칸을 모두 열면 다 풂(`solved`). 깃발은 다 꽂지 않아도 된다. +- 1초에 15번까지. + +## 6. 승패 +- `race.md` §2. 진행도 = 연 칸 수, 진행 문구 `연 칸 N/전체 안전한 칸`. 지뢰를 밟은 사람도 그때까지 연 칸으로 순위에 든다(결과 ` · 지뢰를 밟았어요`). + +## 7. 하우스 룰 +- 없음. "추측 없이 풀리는 판"은 만들지 않았다(원작처럼 가끔 찍어야 할 때가 있다). 모두 같은 판이라 운은 공평하다. + +## 8. 엔진 설계 +```ts +puzzle: { rows, cols, mines, field: string /* '*' 또는 '0'..'8' */, start: number } +board: { open: string /* '1' 연 칸 */, flags: string, opened: number, boom: number | null } +view.board: { rows, cols, mines, cells: string, flags } +// cells: '#' 닫힘, 'F' 깃발, '0'..'8' 연 칸; 내가 끝났거나 게임이 끝나면 '*' 지뢰, '!' 터진 지뢰, 'x' 잘못 꽂은 깃발 +``` +| type | payload | 검증 | +|---|---|---| +| `open` | `i`(칸 번호) | 닫힘, 깃발 아님 | +| `flag` | `i` | 닫힘 | +| `chord` | `i` | 연 숫자 칸, 둘레 깃발 = 숫자, 닫힌 둘레 있음 | +| `stop`·`tick`·`leave` | — | 공통 틀 | +- 랜덤: `setup`의 시작 칸·지뢰 배치만. 숨길 것: 끝나기 전에는 내 view에 지뢰 위치가 없다(테스트). + +## 9. UI/UX +- SVG 판(이미지 파일 없음). 닫힌 칸은 볼록한 회색, 연 칸은 흰색에 원작 색 숫자(1 파랑, 2 초록, 3 빨강…). 새로 열린 칸은 살짝 커지며 나타나고, 터진 지뢰는 빨간 칸. +- PC: 왼쪽 클릭 열기(숫자 칸은 한꺼번에 열기), 오른쪽 클릭 깃발. 칸 최대 56px, 화면 높이에 맞춤. +- 휴대폰: 누르기 = 열기, 길게 누르기(0.42초) = 깃발, 위의 [⛏ 칸 열기 / 🚩 깃발 꽂기] 버튼으로 바꿈. 고급(16×30)은 판을 세로로 돌려 16칸 폭으로 보여 주고 아래로 스크롤(드래그가 없어 `touch-action: manipulation`). +- 키보드: 화살표, 스페이스/Enter 열기, F 깃발. 스크린리더는 칸 위치와 내용을 읽어 준다. +- 위에 남은 지뢰(전체 − 내 깃발). + +## 10. 테스트 체크리스트 +- [x] 판: 난이도별 크기·지뢰 수, 시작 칸 둘레에 지뢰 없음, 숫자 = 둘레 지뢰 수, 같은 시드 = 같은 판, 모두 같은 시작 +- [x] 열기·0 이어 열기·깃발·한꺼번에 열기(틀린 깃발이면 터짐), 지뢰 → 실패·내 화면에만 지뢰 공개 +- [x] 다 풂 → 혼자면 끝, 순위(다 푼 사람 > 연 칸 많은 순, 같은 칸 같은 순위, 나간 사람 맨 아래), 제한 시간, 무제한 끊김, 속도 제한 +- [x] 무작위 대국(1·2·5·8명, 세 난이도), 컴퓨터(거절 0, 어려움이 쉬움보다 자주 풂), 방 통합(연습·끊김·무제한) +- [x] E2E: PC 클릭·오른쪽 클릭, 휴대폰 탭·길게 누르기·깃발 모드, 같은 시작 판, 상대 진행 표시, 포기 → 결과 + +## 11. 참고 +- Microsoft Minesweeper(초급 9×9/10, 중급 16×16/40, 고급 30×16/99). + +## 13. 컴퓨터 상대 +- 확실한 수 먼저: 둘레 깃발 = 숫자면 한꺼번에 열기, 닫힌 칸 수 = 남은 지뢰 수면 깃발. 강할수록 두 숫자를 비교하는 규칙(부분집합)도 자주 쓴다. +- 확실한 수가 없으면 찍는다: 강하면 지뢰일 가능성이 가장 낮아 보이는 칸, 약하면 아무 칸이나. +- 한 수에 레벨 1 약 3초 → 레벨 60 약 0.8초(찍을 때는 더 오래). 초급 20판에서 어려움 컴퓨터가 대부분 풀고 쉬움보다 자주 푼다(테스트). diff --git a/docs/games/nonogram.md b/docs/games/nonogram.md new file mode 100644 index 0000000..ecb6e88 --- /dev/null +++ b/docs/games/nonogram.md @@ -0,0 +1,71 @@ +# 네모네모 로직 (`nonogram`) + +> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 3~20분 · 난이도: 보통 + +## 1. 개요 +- 노노그램(Nonogram, 일본 이름 그림 로직). 줄마다 적힌 숫자대로 칸을 칠하면 그림이 나온다. +- 원작은 혼자 푸는 퍼즐이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 그림을 각자 풀고 가장 먼저 다 푼 사람이 이긴다. 혼자서도 한다. + +## 2. 모드와 옵션 +| 옵션 키 | 설명 | 선택지 | 기본값 | +|---|---|---|---| +| `size` | 크기 | 5×5 쉬움 / 10×10 보통 / 15×15 어려움 | 10×10 | +| `hints` | 힌트 쓰기 | 켬 / 끔 | 켬 | +| `timeLimitSec` | 제한 시간 | 5분 / 10분 / 20분 / 30분 / 무제한 | 20분 | + +## 3~4. 구성과 준비 +- 그림은 손으로 그린 픽셀 그림(`packages/games/src/nonogram/bank.ts`, `#` 칠함 · `.` 빔): 5×5 11장, 10×10 15장, 15×15 11장. 하트·집·나무·우산·별·음표·컵·버섯·고양이·사과·물고기·오리·자동차·로켓·꽃 … +- 모든 그림은 **답이 하나**이고 **줄 논리만으로** 끝까지 풀린다(아래 §8 줄 풀이를 모든 줄에 되풀이해 다 정해짐, 테스트). 빈 줄(숫자 0)은 없다. +- 시드로 크기에 맞는 그림 하나를 고른다. 모두 빈 판으로 시작. + +## 5. 진행 규칙 +- 칠하기(`paint`): 한 줄(가로 또는 세로)에 있는 1~15칸을 한꺼번에 `0` 비움 / `1` 칠함 / `2` ✕로 바꾼다. 화면에서 끌기 한 번 = 한 수. +- 맞았는지 틀렸는지는 알려 주지 않는다(원작과 같음). ✕는 표시일 뿐 답에 상관없다. +- 힌트(`hint`, 켠 방만): 틀렸거나 아직 안 정한 칸 하나를 골라(시드 랜덤) 바른 상태로 바꾼다(칠할 칸은 칠함, 빈 칸은 ✕). 쓴 횟수가 결과에 ` · 힌트 N번`으로 붙는다. +- 칠한 칸이 답과 똑같아지면 다 풂(`solved`). 1초에 12번까지. + +## 6. 승패 +- `race.md` §2. 진행도 = **지금 칠한 칸이 숫자와 맞는 줄 수**(가로 + 세로), 진행 문구 `맞는 줄 N/전체`. 숫자만 보고 누구나 셀 수 있는 값이라 답을 알려 주지 않는다. 실패는 없다. + +## 7. 하우스 룰 +- 힌트(끌 수 있음). 원작에는 없지만 처음 하는 사람이 막히지 않게 넣었다. 대신 결과에 횟수를 남긴다. + +## 8. 엔진 설계 +```ts +puzzle: { size, name, color, solution: string /* '#' | '.' */, rows: number[][], cols: number[][] } +board: { marks: string /* '0' | '1' | '2' */, hints: number, lastHint: number | null } +view.board: { size, rows, cols, marks, hints, lastHint, answer: { solution, name, color } | null /* 내가 끝났거나 게임이 끝나면 */ } +``` +| type | payload | 검증 | +|---|---|---| +| `paint` | `cells`(1~15칸), `value` 0/1/2 | 판 안, 겹치지 않음, 모두 한 가로줄 또는 한 세로줄, 바뀌는 칸이 있음 | +| `hint` | — | 힌트를 켠 방 | +| `stop`·`tick`·`leave` | — | 공통 틀 | +- 줄 풀이(`solver.ts`): 한 줄의 숫자와 아는 칸으로 앞·뒤에서 DP를 돌려, 어떤 배치에서도 칠해지는 칸과 어떤 배치에서도 비는 칸을 정한다. `solveGrid`는 이것을 바뀐 줄마다 다시 돌려 더 정할 칸이 없을 때까지. +- 랜덤: `setup`의 그림 고르기, 힌트 칸 고르기. 숨길 것: 끝내기 전에는 내 view·관전 view에 답 문자열과 그림 이름이 없다(테스트). + +## 9. UI/UX +- SVG 한 장: 위에 세로줄 숫자, 왼쪽에 가로줄 숫자, 그 안에 판(5칸마다 굵은 선). 숫자와 맞는 줄은 숫자가 흐려진다. 위 알약에 맞는 줄 수. +- 끌기: 첫 칸에서 한 칸 움직인 방향의 가로줄/세로줄로 고정되고, 첫 칸의 상태로 값이 정해진다(빈 칸이면 칠하기, 칠한 칸이면 지우기). 첫 칸과 같은 상태인 칸만 바뀐다. 끄는 동안 미리 보이고, 손을 떼면 한 수로 보낸다. +- [■ 채우기] / [✕ 표시] 버튼으로 바꾼다. PC는 오른쪽 클릭·끌기가 늘 ✕. 휴대폰은 판에 `touch-action: none`(끌기가 스크롤이 되지 않게). +- 키보드: 화살표, 스페이스/Enter 칠하기·지우기, X ✕. 스크린리더는 칸 위치·상태와 그 줄의 숫자를 읽어 주고, 맞는 줄 수가 바뀌면 알려 준다. +- [💡 힌트]: 고친 칸에 노란 테두리가 깜박인다. +- 다 풀면 그림이 왼쪽 위부터 색으로 물들고 이름이 나온다(`다 풀었어요! 고양이`). 시간이 끝나거나 포기하면 `정답 그림: …`과 그림. +- 휴대폰 390px에서 15×15가 숫자까지 들어간다(칸 약 19px), 320px에서도 칠할 수 있다. 소리: 칠하기·✕·지우기, 줄이 맞을 때, 힌트. + +## 10. 테스트 체크리스트 +- [x] 그림 은행: 크기별 수, 빈 줄 없음, 모든 그림이 줄 논리만으로 하나의 답으로 풀림; 줄 풀이 단위 테스트 +- [x] 같은 시드 = 같은 그림, 모두 같은 빈 판, 카운트다운에는 판 없음, 기본 옵션 +- [x] 칠하기·✕·지우기, 거절(판 밖·겹침·한 줄 아님·바뀌는 칸 없음·형식), 힌트(바른 상태·횟수·끈 방 거절·힌트만으로도 풀림) +- [x] 다 풂(✕ 상관없음, 칠한 칸이 하나 더 많으면 아직), 진행도 = 맞는 줄, 순위·같은 순위·나간 사람, 제한 시간, 무제한 끊김, 속도 제한 +- [x] 끝내기 전 내 화면·관전 화면에 답·이름 없음, 무작위 대국(1·2·5·8명, 세 크기) +- [x] 컴퓨터(거절 0, 끝까지, 50ms 안, 강한 컴퓨터가 기본 시간 안에 10×10을 풀고 더 빠름), 방 통합(연습·끊김·무제한) +- [x] E2E: PC 마우스 끌기·오른쪽 클릭·키보드, 휴대폰 터치 끌기·✕ 모드, 같은 시작 판, 상대 진행 표시, 다 풀기 → 그림 이름, 결과 + +## 11. 참고 +- Nonogram(Non Ishida, 1987). 한국에서는 "네모네모 로직"(잡지·게임 이름)으로 널리 알려졌다. + +## 13. 컴퓨터 상대 +- 자기 화면(숫자와 자기 표시)만 보고 §8의 줄 풀이로 정해지는 칸을 찾는다. 한 수 = 한 줄에서 새로 정해진 연속 칸 한 덩어리(칠하기 또는 ✕). +- 강할수록 가장 긴 칠하기 덩어리를 먼저 고르고, 약하면 아무 덩어리나. 약한 컴퓨터는 가끔 모르는 칸을 잘못 칠했다가 몇 수 뒤 지운다(그동안 그 칸은 모르는 칸으로 생각). +- 한 수에 레벨 1 약 6초 → 레벨 60 약 1.2초(5×5는 조금 짧게, 15×15는 조금 길게). 10×10을 레벨 60은 약 1분, 레벨 1은 약 6분에 푼다. diff --git a/docs/games/race.md b/docs/games/race.md new file mode 100644 index 0000000..018ed4f --- /dev/null +++ b/docs/games/race.md @@ -0,0 +1,38 @@ +# 같은 판 경주 공통 틀 (`race`) + +지뢰찾기·사천성·솔리테어·스도쿠·네모네모 로직이 함께 쓰는 틀. 원래 혼자 하는 퍼즐을 **모두 같은 판(같은 시드)** 으로 각자 동시에 풀게 해서, 혼자 하면 기록 도전, 여럿이면 "누가 먼저 푸나" 경주가 된다. 사과 게임(`apple.md`)의 방식을 퍼즐 게임용으로 일반화했다. + +코드: `packages/games/src/race/index.ts`(엔진 `makeRaceGame`), `race/bot.ts`(컴퓨터 `raceBot`), `apps/web/src/games/race/kit.tsx`(화면 부품), `race/text.ts`(상태 줄·도움말 글). + +## 1. 진행 +- 인원 1~8명. `setup`에서 시드로 퍼즐 하나를 만들어 모두에게 같은 시작 판을 준다(`puzzle` + 각자 `boards`). +- 3초 카운트다운 동안에는 판을 보내지 않는다(`view.board = null`, `secretsOf` = 퍼즐의 숨은 부분). +- 턴이 없다. 시작 뒤 누구나 언제든 자기 판에 수를 둔다(게임마다 1초에 정해진 횟수까지, 기본 12번). +- 상태: `playing` → `solved`(다 풂) / `failed`(지뢰를 밟는 것처럼 판이 끝나는 실수) / `done`(포기) / `left`(나감). +- `stop` = [포기할래요](두 번 눌러야 함). 제한 시간이 있어도 없어도 쓸 수 있다. +- 제한 시간: 게임마다 고르는 값 + 무제한. 마감 `tick`으로 끝난다. 마감 뒤 수는 `시간이 다 됐어요.`로 거절. +- 끝: 모두 `playing`이 아니면(다 풂·실패·포기·나감) 끝, 또는 마감. 한 사람이 나가도 남은 사람은 끝까지 푼다. + +## 2. 순위와 점수 +- 다 푼 사람이 먼저, **걸린 시간이 짧은 순**. 그다음 다 못 푼 사람(시간 끝·실패·포기)은 **푼 만큼(progress)이 많은 순**. 나간 사람은 맨 아래. +- 같은 시간 / 같은 진행도는 같은 순위. +- 걸린 시간 = 카운트다운이 끝난 때부터 다 풀었을 때(실패·포기한 때)까지, 서버 시계. +- 결과 문구(`scoreText`): `다 풀었어요 · 3분 05.4초`(+ 힌트 횟수 등), 다 못 풀면 게임의 진행 문구(`연 칸 40/71`) + ` · 지뢰를 밟았어요`/` · 포기`. +- 요약: 혼자 `다 풀었어요! 걸린 시간 …` / `시간이 다 됐어요. …` / `포기했어요. …`. 여럿 `가장 먼저 다 푼 사람이 이겼어요`, 아무도 못 풀면 `아무도 다 풀지 못했어요. 가장 많이 푼 사람이 이겼어요`(+ `공동 1등 N명`). +- `GameResult.scores` = 진행도. + +## 3. 보기(view)·타이머 +- 내 view: 내 판(게임이 정한 모양, 내가 끝났거나 게임이 끝나면 정답까지 보여 줌 `reveal`) + 모두의 상태·진행도·진행 문구·걸린 시간. 다른 사람 판은 보내지 않는다. 관전자는 판 없이 진행 상황만. +- 같은 판을 푸는 게임이라 "남의 비밀"은 없고, 숨길 것은 **아직 열지 않은 정답**(지뢰 위치, 뒤집힌 카드, 스도쿠·노노그램 답)뿐이다. 그래서 엔진 공통 검사(`checkNoLeak`)는 카운트다운만 보고, 각 게임 테스트가 "끝나기 전 내 view에 정답이 없다"를 따로 확인한다. +- `deadline`: 카운트다운 끝 / 마감. `timeoutNotBefore` = 같은 값이라 연결이 끊긴 사람이 일찍 시간 초과되지 않는다. 무제한이면 진행 중 마감이 없고, 끊긴 채 유예 시간이 지난 사람만 `tick`으로 포기(`done`) 처리. +- 컴퓨터 연습방이 사람 없이도 끝나도록 게임마다 **기본 제한 시간이 있다**(무제한은 고를 때만). + +## 4. 화면 부품 (`race/kit.tsx`) +- 위: 남은 시간(마지막 10초 빨강) 또는 무제한 스톱워치(0.1초) + 게임 알약들. 그 아래 여러 명이면 모두의 진행 칩(순위순, 실시간). +- 판 위에 카운트다운(3·2·1), 끝나면 `다 풀었어요! …`/실패/포기 안내, 관전 안내. +- [포기할래요] 두 번 누르기. 오른쪽 패널에 순위표와 최종 순위. +- 소리: 3·2·1, 시작, 마지막 10초 째깍, 다 풀면 팡파르, 실패하면 낮은 소리. + +## 5. 컴퓨터 (`raceBot`) +- live 전략: 서버가 컴퓨터마다 자기 타이머로 계속 묻고, 컴퓨터는 자기 view만 본다. 남의 판을 방해할 수 없어서 실시간 게임이지만 컴퓨터를 넣었다. +- 게임이 "다음 수 + 사람이 그 수를 찾는 데 걸릴 시간"을 정하면 그만큼 기다렸다 둔다. 레벨(1~60)이 시간과 실수를, 컴퓨터마다 빠르기(`pace`)가 시간을 조금 바꾼다. diff --git a/docs/games/shisen.md b/docs/games/shisen.md new file mode 100644 index 0000000..7e55285 --- /dev/null +++ b/docs/games/shisen.md @@ -0,0 +1,67 @@ +# 사천성 (`shisen`) + +> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 5~15분 · 난이도: 쉬움 + +## 1. 개요 +- 마작패로 하는 짝 맞추기 퍼즐(Shisen-Sho, 四川省). 같은 그림의 패 두 장을 **두 번 이하로 꺾인 선**으로 이어 없애고, 판을 모두 비우면 이긴다. +- 원작은 혼자 하는 퍼즐이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 판을 각자 풀고 가장 먼저 다 비운 사람이 이긴다. 혼자서도 한다. + +## 2. 모드와 옵션 +| 옵션 키 | 설명 | 선택지 | 기본값 | +|---|---|---|---| +| `size` | 판 크기 | 작게 12×6(72패, 18종) / 보통 14×8(112패, 28종) / 크게 17×8(136패, 34종 전부) | 보통 | +| `hints` | 힌트 쓰기 | 쓰기 / 안 쓰기 | 쓰기 | +| `timeLimitSec` | 제한 시간 | 5분 / 10분 / 15분 / 20분 / 무제한 | 15분 | + +## 3~4. 구성과 준비 +- 패 종류: 만수·통수·삭수 1~9, 자패 동·남·서·북·백·발·중 = 34종(`'1m'..'9m'`, `'1p'..'9p'`, `'1s'..'9s'`, `'1z'..'7z'`), 종류마다 4장. 작게·보통은 쓸 종류를 시드로 고른다. +- **언제나 풀리는 판**: 판을 거꾸로 만든다. 채울 칸 전체에서 "지금 이어지는 두 칸"(나머지 칸은 다 차 있다고 보고)을 하나씩 골라 비워 가며 쌍을 정하고, 다 비운 뒤 쌍마다 종류를 붙인다. 이것은 빈 판에 이어지는 두 칸씩 쌍을 놓아 가는 역방향 구성과 같고, 비운 순서가 곧 풀이다. 두 열의 맨 위 패(열이 하나면 맨 위 두 장)는 언제나 위 테두리로 이어지므로 막히는 일이 없다(재시도가 필요 없음). 크게도 1ms 안팎. + +## 5. 진행 규칙 +- 잇기(`pair`): 서로 다른 두 칸, 둘 다 패, 같은 종류, 그리고 둘을 잇는 가로·세로 선(최대 3토막 = 꺾임 2번)이 **빈 칸만** 지나야 한다. 선은 판 바로 바깥 한 칸 테두리를 지나도 된다. 맞으면 두 장이 없어진다. +- 없앤 뒤 패가 남았는데 이어지는 쌍이 하나도 없으면 **남은 패를 그 자리들에 저절로 섞는다**(위와 같은 방식이라 다시 풀림, 섞기 횟수 `shuffles`). 원작의 막힘 = 실패 대신, 경주가 끝까지 가게 했다. +- 힌트(`hint`): 힌트를 쓰는 방에서, 힌트가 안 보일 때만. 이어지는 쌍 하나를 보여 주고 횟수를 센다. 그 두 장 중 하나가 없어지거나 판이 섞이면 사라진다. +- 판이 비면 다 풂(`solved`). 실패는 없다. 1초에 12번까지. + +## 6. 승패 +- `race.md` §2. 진행도 = 없앤 쌍 수, 진행 문구 `없앤 쌍 N/전체 쌍`(보통이면 `/56`). 결과 문구에 ` · 섞기 N번`, ` · 힌트 N번`이 붙는다. + +## 7. 하우스 룰 +- 막히면 저절로 섞기(원작은 막히면 끝이거나 직접 섞기). 패를 쌓지 않는 한 층 판(원작의 기본형). + +## 8. 엔진 설계 +```ts +puzzle: { rows, cols, cells: (string | null)[] /* 칸마다 종류 코드 */ } +board: { cells, removed: number, hint: [a, b] | null, hints: number, shuffles: number } +view.board: { rows, cols, cells, hint, shuffles, hints } +findPath(cells, rows, cols, a, b): [row, col][] | null // [a, 꺾인 곳…, b], 테두리는 -1 / rows / cols +``` +| type | payload | 검증 | +|---|---|---| +| `pair` | `a`, `b`(칸 번호) | 판 안, 서로 다름, 둘 다 패, 같은 종류, 꺾임 2번 이하 길 | +| `hint` | — | 힌트 쓰는 방, 지금 힌트 없음 | +| `stop`·`tick`·`leave` | — | 공통 틀 | +- 랜덤: `setup`의 종류 고르기·배치, 저절로 섞기(`ctx.rng`). 숨길 것: 판 전체가 보이는 게임이라 카운트다운 동안만 판을 숨긴다(테스트). + +## 9. UI/UX +- 마작 화면의 패 그림(`mahjong/Tile`)을 녹색 판 위에 놓고, 둘레에 반 칸 테두리(선이 지나는 곳). 패 크기는 칸 폭과 보이는 높이에 맞춘다(최대 64px). +- 누르기(클릭·탭): 첫 패는 떠오르며 노란 테두리, 같은 패를 다시 누르면 취소. 두 번째 패가 이어지면 노란 선(테두리로 도는 것까지)을 0.35초 그리고 두 장이 작아지며 사라진다. 안 되면 두 장이 흔들리고 `같은 패가 아니에요` / `두 번 넘게 꺾여야 이어져요`를 보여 주고, 방금 누른 패가 새로 골라진다. +- [💡 힌트]: 이어지는 두 장이 파랗게 빛난다. 저절로 섞이면 `섞었어요!`. +- 휴대폰: 판이 가로로 길면(열 > 줄) 세로로 돌려 보여 주고, 작게·보통은 스크롤 없이 화면에 들어온다(크게는 조금 내려야 할 수 있음). +- 키보드: 화살표로 칸 옮기기, 스페이스/Enter 고르기, Esc 취소. 스크린리더는 칸 위치와 패 이름을 읽어 준다(`aria-live`). +- 위에 남은 패 수. 규칙 화면에 패 그림 출처(`MAHJONG_TILE_CREDIT`). + +## 10. 테스트 체크리스트 +- [x] 판: 크기별 칸·종류·종류마다 4장, 같은 시드 = 같은 판, 모두 같은 판, 크기마다 200판이 풀이 순서대로 모두 없어짐(100ms 안), 카운트다운에는 판 없음 +- [x] 길 찾기: 곧게·한 번·두 번 꺾기·테두리로 돌기·세 번이면 안 됨, `reachable`과 `findPath`가 같은 답 +- [x] 잇기·거절(다른 패, 같은 칸, 꺾임, 판 밖), 힌트(횟수·중복 금지·사라짐·끈 방), 막히면 저절로 섞기(같은 칸·같은 패·다시 풀림), 다 비우면 다 풂 +- [x] 순위(다 푼 사람 > 없앤 쌍 많은 순, 같으면 같은 순위, 나간 사람 맨 아래), 제한 시간, 무제한 끊김(한 번만 포기), 속도 제한 +- [x] 무작위 대국(1·2·5·8명, 세 크기), 컴퓨터(거절 0, 다 풂, 강할수록 빠름), 방 통합(연습·끊김·무제한) +- [x] E2E: PC 클릭·키보드, 휴대폰 탭, 같은 시작 판, 상대 진행 표시, 포기 → 결과 + +## 11. 참고 +- Shisen-Sho(四川省, 1989 Activision, KShisen 등): 같은 패 두 장을 꺾임 2번 이하로 잇는 규칙, 판 바깥 테두리 통과. + +## 13. 컴퓨터 상대 +- 자기 판에서 지금 이어지는 쌍을 찾는다(`findPath`). 약한 컴퓨터는 주로 곧게 이어지거나 가까운(꺾임 1번, 4칸 안) 쌍만 눈에 띄고, 먼 쌍만 남으면 더 오래 찾는다. 강할수록 어떤 쌍이든 본다. +- 한 쌍에 레벨 1 약 7초 → 레벨 60 약 1.5초. 작게 10판에서 강한 컴퓨터가 약한 컴퓨터보다 거의 늘 먼저 다 푼다(테스트). diff --git a/docs/games/solitaire.md b/docs/games/solitaire.md new file mode 100644 index 0000000..93d2757 --- /dev/null +++ b/docs/games/solitaire.md @@ -0,0 +1,91 @@ +# 솔리테어 (`solitaire`) + +> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 5~15분 · 난이도: 쉬움 + +## 1. 개요 +- 윈도우에 들어 있던 카드놀이 세 가지: 클론다이크(그냥 "솔리테어"), 프리셀, 스파이더. +- 원작은 혼자 하는 놀이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 패를 각자 풀고 가장 먼저 다 푼 사람이 이긴다. 혼자서도 한다. + +## 2. 모드와 옵션 +| 옵션 키 | 설명 | 선택지 | 기본값 | +|---|---|---|---| +| `mode` | 종류 | 클론다이크 / 프리셀 / 스파이더 | 클론다이크 | +| `draw` | 한 번에 넘기는 카드(클론다이크만) | 1장 / 3장 | 1장 | +| `suits` | 무늬 수(스파이더만) | 1가지(스페이드) / 2가지(스페이드·하트) / 4가지 | 1가지 | +| `timeLimitSec` | 제한 시간 | 10분 / 15분 / 20분 / 30분 / 무제한 | 15분 | + +## 3~4. 구성과 준비 +- 카드 id는 `PlayingCard`와 같다: 숫자 `A23456789TJQK` + 무늬 `SHDC`("AS", "TD"). +- 클론다이크: 52장. 일곱 줄에 1~7장(맨 위만 앞면), 나머지 24장은 더미. 파운데이션 4자리. +- 프리셀: 52장. 여덟 줄에 7·7·7·7·6·6·6·6장 모두 앞면. 빈 칸 4개, 파운데이션 4자리. +- 스파이더: 두 벌 104장(1가지면 모두 스페이드, 2가지면 스페이드·하트 반씩). 열 줄에 앞 네 줄 6장, 나머지 5장(맨 위만 앞면), 더미 50장(10장씩 5번). +- 시드로 섞은 한 벌을 모두에게 똑같이 돌린다. + +## 5. 진행 규칙 +- 옮기기(`move {from, n, to}`): 자리 id는 줄 `t0`~`t9`, 버린 카드 `w`, 빈 칸 `c0`~`c3`, 파운데이션 `f0`~`f3`(`to: 'f'` = 맞는 파운데이션 아무 곳). 줄에서는 맨 위 `n`장, 나머지 자리에서는 한 장. +- 줄 쌓기: 클론다이크·프리셀은 색을 번갈아 하나씩 작게, 스파이더는 무늬 상관없이 하나 작게. 빈 줄에는 클론다이크는 K만, 나머지는 아무 카드나. +- 한꺼번에 옮기기: 클론다이크·프리셀은 색이 번갈아 이어진 카드, 스파이더는 **같은 무늬로** 이어진 카드만. 프리셀은 (빈 칸 + 1) × 2^(빈 줄)장까지(빈 줄로 옮길 때 그 줄은 빼고 셈). +- 파운데이션: A부터 같은 무늬로 차례대로. 클론다이크는 올린 카드를 줄로 다시 내릴 수 있다(윈도우와 같음), 프리셀은 못 내린다. +- 뒤집힌 카드 위의 카드를 다 옮기면 저절로 앞면이 된다. +- 넘기기(`draw`, 클론다이크): 더미에서 1장(3장)을 버린 카드 위로. 더미가 비면 버린 카드를 다시 뒤집어 더미로(횟수 제한 없음). +- 나누기(`deal`, 스파이더): 열 줄에 한 장씩. 빈 줄이 있으면 못 나눈다(원작 규칙). 단 줄 위의 카드가 10장보다 적으면 빈 줄이 있어도 나눌 수 있다(채울 카드가 모자라 막히는 것을 피함). +- 스파이더: K부터 A까지 같은 무늬 13장이 앞면으로 이어지면 저절로 빠진다. +- 자동 정리(`auto`, 클론다이크·프리셀): 파운데이션에 올릴 수 있는 카드를 더 없을 때까지 모두 올린다. +- 되돌리기(`undo`): 바로 앞 판으로. 판마다 최근 50번까지 저장, 몇 번이든 쓸 수 있지만 결과에 ` · 되돌리기 N번`이 붙는다. 뒤집혔던 카드가 되돌리기로 다시 뒤집혀도 괜찮다(윈도우와 같음). +- 다 풂: 클론다이크·프리셀은 52장을 모두 올림, 스파이더는 8줄을 모두 뺌. 1초에 12번까지. + +## 6. 승패 +- `race.md` §2. 진행도 = 클론다이크·프리셀 올린 카드 수(0~52, 문구 `올린 카드 N/52`), 스파이더 뺀 카드 수(0~104, 문구 `완성 N/8줄`). +- 실패(`failed`)는 없다. 막히면 포기하거나 시간이 끝날 때까지 푼 만큼으로 순위. + +## 7. 하우스 룰 +- 클론다이크는 원작처럼 가끔 풀 수 없는 패가 나온다. 모두 같은 패라 공평하고, 그때는 진행도 순위가 된다. +- 점수(윈도우의 표준/라스베이거스 점수)는 쓰지 않는다. 경주라서 시간과 올린 카드만 본다. +- 스파이더 나누기의 "카드가 10장보다 적으면 빈 줄이 있어도 됨"(§5). +- 끝나도 뒤집힌 카드는 공개하지 않는다(정답이 따로 없는 놀이라서). + +## 8. 엔진 설계 +```ts +puzzle: { mode, deck: string /* 섞은 카드, 2글자씩 */ } +board: { t: string[][], down: number[] /* 줄마다 아래 뒤집힌 수 */, stock: string[], waste: string[], + cells: string[] /* '' 빈 칸 */, f: string[] /* 파운데이션 맨 위 */, done: string /* 스파이더 뺀 줄의 무늬 */, + hist: string[] /* 되돌리기용 이전 판(짧은 글자열), 최대 50 */, undos: number } +view.board: { mode, draw, t: (string | null)[][] /* 뒤집힌 카드 null */, stock: number /* 장수만 */, waste, cells, f, done, canUndo, undos } +``` +| type | payload | 검증 | +|---|---|---| +| `move` | `from`, `n`(1~13), `to` | 자리가 그 모드에 있음, 같은 자리 아님, 집을 카드가 앞면·이어짐, 놓을 곳 규칙(§5), 프리셀 장수 | +| `draw` | — | 클론다이크, 더미나 버린 카드가 있음 | +| `deal` | — | 스파이더, 더미 있음, 빈 줄 없음(§5 예외) | +| `auto` | — | 클론다이크·프리셀, 올릴 카드 있음 | +| `undo` | — | 이전 판이 있음 | +| `stop`·`tick`·`leave` | — | 공통 틀 | +- 규칙 검사(`moveProblem`)는 보이는 판(`Table` = view 모양)에서 한다. 서버·화면·컴퓨터가 같은 함수를 쓴다. +- 랜덤: `setup`의 섞기만. 숨길 것: 끝나기 전 내 view에 뒤집힌 카드와 더미 내용이 없다(테스트, 클론다이크는 카드가 모두 달라 글자로도 확인). + +## 9. UI/UX +- 카드는 `PlayingCard`(SVG, 그림카드는 CC0 그림, 규칙에 `PLAYING_CARD_CREDIT`). 초록 펠트 위에 위 줄(더미·버린 카드·파운데이션 / 빈 칸·파운데이션 / 더미·완성한 줄)과 줄들. 줄은 부채꼴로, 뒤집힌 카드는 더 촘촘히 겹친다. PC에서 줄이 길면 화면 높이에 맞게 간격을 줄인다. +- 카드를 누르면 그 카드와 위에 얹힌 카드가 함께 들리며 골라지고, 놓을 수 있는 곳이 노랗게 빛난다. 놓을 곳을 누르면 옮긴다. 두 번 누르면(더블 클릭/더블 탭) 파운데이션으로. 안 되는 수는 판이 살짝 흔들리고 이유를 읽어 준다. +- 더미를 누르면 넘기기/나누기, 비었으면 ↻(다시 뒤집기). 아래 [↶ 되돌리기] [자동 정리] [포기할래요]. +- 새로 놓인 카드는 살짝 내려앉는 움직임(`prefers-reduced-motion`이면 없음). 소리: 고르기, 놓기, 넘기기, 나누기, 파운데이션(높은 두 음), 한 줄 완성. +- 휴대폰 390px: 7·8줄은 카드 약 47px, 스파이더 10줄은 약 34px(320px에서는 약 27px). 세로로는 페이지가 스크롤된다. +- 키보드: Tab으로 카드·자리를 옮기고 Enter/스페이스로 고르기·놓기, F 파운데이션, Esc 취소. 스크린리더는 줄·카드 이름을 읽고, 고른 것·올린 것·거절 이유를 알려 준다. + +## 10. 테스트 체크리스트 +- [x] 패: 모드별 모양(1~7장·뒤집힘, 7·7·7·7·6·6·6·6, 6×4·5×6), 스파이더 무늬 구성, 같은 시드 = 같은 패, 모두 같은 시작, 카운트다운에 판 없음 +- [x] 클론다이크: 1장/3장 넘기기·다시 뒤집기, 쌓기·K만 빈 줄·뒤집힌 카드 못 옮김·저절로 뒤집힘, 파운데이션(`f`·`f0`)·다시 내리기, 자동 정리, 다 풂 +- [x] 프리셀: 빈 칸, 아무 카드 빈 줄, 장수 공식(빈 줄로 옮길 때 포함), 올린 카드 못 내림, 스크립트 풀이로 실제 다 풂 +- [x] 스파이더: 무늬 상관없이 쌓기, 같은 무늬만 함께, 빈 줄이면 못 나눔, 나누기 10장, 한 줄 완성·저절로 뒤집힘, 8줄 → 다 풂 +- [x] 되돌리기(50번 한도, 횟수 문구), 순위·제한 시간·무제한 끊김·속도 제한, 무작위 대국(1·2·5·8명, 모든 모드) 중 뒤집힌 카드·더미가 내 view에 없음 +- [x] 컴퓨터(거절 0, 끝없이 돌지 않음, 강할수록 평균 진행도가 높음), 방 통합(연습·끊김·무제한) +- [x] E2E: PC 마우스(클릭·더블 클릭·더미·되돌리기), 휴대폰 탭·더블 탭, 같은 시작 패, 상대 진행 표시, 포기 → 결과; 스파이더·프리셀 화면 + +## 11. 참고 +- Microsoft Solitaire(Windows XP/7): 클론다이크 1장/3장, 프리셀(빈 칸 4개, 여러 장 옮기기 공식), 스파이더(1·2·4가지 무늬, 빈 줄이면 나눌 수 없음). + +## 13. 컴퓨터 상대 +- 자기 화면만 본다(앞면 카드, 더미 장수). 모든 수에 점수를 매겨 고른다: 파운데이션 > 뒤집힌 카드 열기(뒤집힌 수가 많은 줄 먼저) > 줄 비우기(클론다이크는 놓을 K가 있을 때만) > 파운데이션에 갈 카드 드러내기 > 쌓기(스파이더는 같은 무늬 위를 크게). 이미 잘 이어진 카드를 떼어 내는 수는 하지 않는다. +- 강할수록 한 수 앞을 본다(그 수가 열어 주는 다음 수의 절반만큼 더함). 프리셀은 카드가 다 보이니 올릴 카드가 없을 때 짧게 찾아본다(강하면 400판, 약하면 60판까지) — 한 장 더 올리는 길을 찾으면 따라간다. +- 할 게 없으면 클론다이크는 넘기기, 스파이더는 나누기(빈 줄이 있으면 먼저 채움). +- 끝없이 돌지 않게: 같은 판에서 같은 수는 두 번 하지 않고, 클론다이크는 더미를 두 바퀴 돌도록 판이 그대로면, 할 수가 없으면, 또는 1200수가 넘으면 포기(`stop`). +- 한 수에 레벨 1 약 4초 → 레벨 60 약 1초(넘기기·나누기는 절반). 약할수록 가장 좋은 수를 가끔 놓친다. 같은 패 12판에서 강한 컴퓨터가 약한 컴퓨터보다 평균적으로 더 많이 올린다(테스트). diff --git a/docs/games/sudoku.md b/docs/games/sudoku.md new file mode 100644 index 0000000..78de51d --- /dev/null +++ b/docs/games/sudoku.md @@ -0,0 +1,70 @@ +# 스도쿠 (`sudoku`) + +> 2026-11 새 게임 · 인원: 1 ~ 8명 · 예상 시간: 약 5~30분 · 난이도: 보통 + +## 1. 개요 +- 9×9 판의 가로줄·세로줄·3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채우는 숫자 퍼즐. +- 원작은 혼자 푸는 퍼즐이다. 우리는 **같은 판 경주 틀**(`race.md`)로 모두 같은 퍼즐을 각자 풀고 가장 먼저 다 맞게 채운 사람이 이긴다. 혼자서도 한다. + +## 2. 모드와 옵션 +| 옵션 키 | 설명 | 선택지 | 기본값 | +|---|---|---|---| +| `difficulty` | 난이도 | 쉬움(처음 숫자 38~40개, 싱글만으로 풀림) / 보통(30~32개) / 어려움(26개 안팎) | 쉬움 | +| `hints` | 힌트 | 있음 / 없음 | 있음 | +| `timeLimitSec` | 제한 시간 | 10분 / 20분 / 30분 / 60분 / 무제한 | 30분 | + +## 3~4. 구성과 준비 +- 시드로 퍼즐을 만든다(`makePuzzle`). 먼저 무작위 백트래킹으로 9×9를 꽉 채우고, 칸을 무작위 순서로 하나씩 비우면서 **해답이 하나뿐일 때만** 비운 채로 둔다(비트마스크 풀이기가 해답을 2개까지 센다). +- 쉬움: 38~40개가 남을 때까지, 그리고 네이키드·히든 싱글(한 칸에 들어갈 수 있는 숫자가 하나 / 줄·상자에서 그 숫자가 갈 곳이 하나)만으로 풀려야 비운다. 보통: 30~32개까지. 어려움: 끝까지 비워 본다(보통 21~26개). +- 모두 같은 퍼즐(처음 숫자만 있는 판)로 시작한다. 만드는 데 300ms 안(테스트, 실제로는 수 ms). + +## 5. 진행 규칙 +- 숫자(`set`): 처음 숫자가 아닌 칸에 1~9. 내가 넣은 숫자는 바꿀 수 있다(같은 숫자는 거절). 그 칸의 메모는 지워지고, 같은 줄·칸·상자 메모에서 그 숫자가 빠진다. +- 지우기(`clear`): 내 숫자를 지운다. 숫자가 없으면 그 칸 메모를 지운다. +- 메모(`note`): 빈칸에 작은 후보 숫자를 켜고 끈다. +- 힌트(`hint`, 힌트 있음일 때): 빈칸이나 틀린 칸 하나(시드 rng로 고름)를 맞는 숫자로 채운다. 쓴 횟수가 결과에 ` · 힌트 N번`으로 남는다. +- 종이처럼 **맞는지 알려 주지 않는다**. 틀린 숫자도 넣을 수 있다. 81칸이 모두 정답과 같아지면 다 풂(`solved`). 실패(`failed`)는 없다. +- 1초에 12번까지. + +## 6. 승패 +- `race.md` §2. 진행도 = 채운 칸 수(처음 숫자 제외, 맞든 틀리든), 진행 문구 `채운 칸 N/빈칸 수`. 진행도로 맞고 틀림이 새지 않게 했다. + +## 7. 하우스 룰 +- 힌트(끌 수 있음), 겹친 숫자 빨간 표시(화면에 보이는 숫자끼리만 비교하므로 정답 정보가 아니다), 같은 숫자를 다시 누르면 지우기(화면). + +## 8. 엔진 설계 +```ts +puzzle: { difficulty, givens: string /* 81자 '0' 빈칸 */, solution: string } +board: { values: string /* 처음 숫자 포함 */, notes: number[] /* 칸마다 비트 n = 숫자 n */, hints, hintAt: number | null } +view.board: { difficulty, givens: string /* '1' 처음 숫자 */, values, notes, hints, hintAt, solution? /* 내가 끝났거나 게임이 끝났을 때만 */ } +``` +| type | payload | 검증 | +|---|---|---| +| `set` | `i`, `n`(1~9) | 처음 숫자 칸 아님, 지금 숫자와 다름 | +| `clear` | `i` | 처음 숫자 칸 아님, 숫자나 메모가 있음 | +| `note` | `i`, `n` | 처음 숫자 칸 아님, 빈칸 | +| `hint` | — | 힌트 있음 | +| `stop`·`tick`·`leave` | — | 공통 틀 | +- 랜덤: `setup`의 퍼즐 만들기, 힌트 칸 고르기. 숨길 것: 끝나기 전에는 내 view에 정답(`solution`)이 없다(테스트). 카운트다운 동안은 퍼즐 전체. + +## 9. UI/UX +- HTML 9×9 판(굵은 선 3×3 상자). 고른 칸은 파란 테두리, 같은 줄·칸·상자는 옅은 회색, 같은 숫자는 옅은 파랑+밑줄, 겹친 숫자는 빨강, 메모는 칸 안에 작은 3×3 숫자. 처음 숫자는 굵게, 내 숫자는 파랗게. 넣은 숫자는 톡 튀어나오고, 힌트 칸은 노랗게 빛난다. +- 숫자 패드 1~9(남은 개수 = 9 − 판에 있는 개수, 0이면 흐리게) + [⌫ 지우기] + [✏️ 메모] + [💡 힌트]. 같은 숫자를 다시 누르면 지운다. +- PC: 판 오른쪽에 3×3 패드. 키보드: 화살표, 1~9(숫자패드도), Backspace·Delete·0 지우기, N·스페이스 메모 켜고 끄기. +- 휴대폰: 판은 화면 폭 전체(320px까지), 아래에 1~9 한 줄 + 도구 한 줄 큰 버튼. +- 다 풀었거나 게임이 끝나면 빈칸·틀린 칸에 정답을 초록 숫자로 보여 준다. 스크린리더는 칸 위치·숫자·메모를 읽어 준다. + +## 10. 테스트 체크리스트 +- [x] 퍼즐: 난이도마다 30판 해답 하나·올바른 스도쿠·숫자 개수·쉬움은 싱글로 풀림·300ms 안·같은 시드 = 같은 판, 모두 같은 시작 +- [x] 숫자·지우기·메모(같은 줄·칸·상자 메모 지움)·힌트(횟수, 끈 방 거절), 틀린 숫자 허용, 진행도에 맞고 틀림 없음 +- [x] 다 풂 → 혼자면 끝, 끝난 뒤에만 정답 공개, 순위(다 푼 사람 > 채운 칸 많은 순, 같으면 같은 순위, 나간 사람 맨 아래), 제한 시간, 무제한 끊김, 속도 제한 +- [x] 무작위 대국(1·2·5·8명, 세 난이도, 다 풀기 전 내 view에 정답 없음), 컴퓨터(거절 0, 강한 컴퓨터가 30분 안에·약한 컴퓨터보다 빨리), 방 통합(연습·끊김·무제한) +- [x] E2E: PC 클릭+키보드·메모·겹침 빨강, 휴대폰 탭+패드·힌트, 같은 시작 판, 상대 진행 표시, PC 다 풂 + 휴대폰 포기 → 결과, 다크 모드·320px 휴대폰 화면 + +## 11. 참고 +- 스도쿠(Number Place). 해답이 하나뿐인 퍼즐, 네이키드/히든 싱글 기법. + +## 13. 컴퓨터 상대 +- 자기 화면의 처음 숫자(공개 정보)로 퍼즐을 한 번 풀어 두고, 후보가 가장 적은(가장 쉬운) 빈칸부터 하나씩 채운다. 힌트는 쓰지 않는다. +- 한 칸에 쉬움 기준 레벨 1 약 15초 → 레벨 60 약 4초, 보통 ×1.5, 어려움 ×2.2(후보가 많은 칸은 더 오래). +- 약한 컴퓨터는 가끔(레벨 1 약 15%) 틀린 숫자를 넣고, 나중에 알아채 고친다(판이 다 차면 반드시). diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index 33f7798..00ade0b 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -10,6 +10,12 @@ import { join } from 'node:path'; import { loadConfig } from '../apps/server/src/config'; import { startServer } from '../apps/server/src/server'; import { plan960 } from './chess960-plan'; +import { sureMove } from '../packages/games/src/minesweeper/bot'; +import { findPair as ssFindPair } from '../packages/games/src/shisen'; +import { chooseMove as solChoose } from '../packages/games/src/solitaire/bot'; +import type { SolitaireBoardView, SolitaireMove } from '../packages/games/src/solitaire'; +import { solve } from '../packages/games/src/sudoku'; +import { solveGrid } from '../packages/games/src/nonogram/solver'; const PORT = Number(process.env.E2E_PORT ?? 4519); const ORIGIN = `http://localhost:${PORT}`; @@ -849,6 +855,240 @@ async function appleDrag(p: Page, rect: [number, number, number, number], touch: await cdp.detach(); } +/** 지뢰찾기: my board as the screen draws it (canonical cells in index order) plus where each cell sits. */ +async function msGrid(p: Page) { + return p.evaluate(() => { + const out: { ch: string; x: number; y: number }[] = []; + for (const g of document.querySelectorAll('svg.ms-board g[data-i]')) { + const b = g.getBoundingClientRect(); + out[Number(g.getAttribute('data-i'))] = { ch: g.getAttribute('data-ch')!, x: b.left + b.width / 2, y: b.top + b.height / 2 }; + } + return out; + }); +} + +/** 지뢰찾기: one real tap on the phone through CDP (pointerType "touch"); `holdMs` makes it a long press. */ +async function touchTap(p: Page, x: number, y: number, holdMs = 0) { + const cdp = await p.context().newCDPSession(p); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }); + if (holdMs) await p.waitForTimeout(holdMs); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + await cdp.detach(); +} + +/** 사천성: my board as drawn (cells by index, from the tiles on screen) plus where each tile sits. */ +async function ssGrid(p: Page) { + return p.evaluate(() => { + const board = document.querySelector('.ss-board')!; + const rows = Number(board.getAttribute('data-rows')); + const cols = Number(board.getAttribute('data-cols')); + const cells: (string | null)[] = Array(rows * cols).fill(null); + const pos: { x: number; y: number }[] = []; + for (const el of board.querySelectorAll('.ss-cell[data-i]')) { + const i = Number(el.getAttribute('data-i')); + const b = el.getBoundingClientRect(); + cells[i] = el.getAttribute('data-k'); + pos[i] = { x: b.left + b.width / 2, y: b.top + b.height / 2 }; + } + return { rows, cols, cells, pos }; + }); +} + +/** 사천성: one real tap on the phone through CDP (pointerType "touch"). */ +async function ssTap(p: Page, x: number, y: number) { + const cdp = await p.context().newCDPSession(p); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + await cdp.detach(); +} + +/** 사천성: waits until my board shows `n` tiles. */ +async function ssWaitTiles(p: Page, n: number) { + await p.waitForFunction((k) => document.querySelectorAll('.ss-board .ss-cell[data-i]').length === k, n, { timeout: 5000 }); +} + +/** 솔리테어: my table as the screen draws it (face-down = null, only the waste top), read from the data attributes. */ +async function solRead(p: Page): Promise { + return p.evaluate(() => { + const mode = document.querySelector('.sl-felt')!.getAttribute('data-mode') as 'klondike' | 'freecell' | 'spider'; + const n = mode === 'klondike' ? 7 : mode === 'freecell' ? 8 : 10; + const cardsIn = (sel: string) => [...document.querySelectorAll(`${sel} [data-card]`)].map((e) => e.getAttribute('data-card') || null); + const t = Array.from({ length: n }, (_, i) => cardsIn(`[data-pile="t${i}"]`)); + const waste = cardsIn('[data-pile="w"]').filter((c): c is string => !!c); + const f = mode === 'spider' ? [] : [0, 1, 2, 3].map((i) => document.querySelector(`[data-pile="f${i}"]`)?.getAttribute('data-top') ?? ''); + const cells = mode === 'freecell' ? [0, 1, 2, 3].map((i) => cardsIn(`[data-pile="c${i}"]`)[0] ?? '') : []; + const stock = Number(document.querySelector('[data-pile="s"]')?.getAttribute('data-count') ?? 0); + const done = 'S'.repeat(document.querySelectorAll('.sl-done-card').length); + return { mode, draw: 1 as const, t, stock, waste, cells, f, done, canUndo: false, undos: 0 }; + }); +} +const solKey = async (p: Page) => JSON.stringify(await solRead(p)); + +/** 솔리테어: one real tap on the phone through CDP (pointerType "touch"). */ +async function solTap(p: Page, x: number, y: number) { + const cdp = await p.context().newCDPSession(p); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + await cdp.detach(); +} + +/** 솔리테어: where to press card `k` of a pile (the visible strip of a covered card), or the pile's slot / stock. */ +async function solSpot(p: Page, pile: string, k: number | 'top'): Promise<{ x: number; y: number }> { + const cards = p.locator(`[data-pile="${pile}"] [data-card]`); + const n = await cards.count(); + const idx = k === 'top' ? n - 1 : k; + const el = n ? cards.nth(idx) : p.locator(`[data-pile="${pile}"] button`).first(); + await el.scrollIntoViewIfNeeded(); + const b = await el.boundingBox(); + if (!b) throw new Error(`nothing to press on ${pile}`); + const covered = n > 0 && idx < n - 1; + return { x: b.x + b.width / 2, y: covered ? b.y + Math.min(9, b.height / 5) : b.y + b.height / 2 }; +} + +/** 솔리테어: plays one move the way a person would — PC mouse (click, click / double-click), phone touch (tap, tap / double tap). */ +async function solDo(p: Page, m: SolitaireMove, phone: boolean, v: SolitaireBoardView) { + const press = async (pt: { x: number; y: number }) => (phone ? solTap(p, pt.x, pt.y) : p.mouse.click(pt.x, pt.y)); + if (m.type === 'draw' || m.type === 'deal') return press(await solSpot(p, 's', 'top')); + if (m.type !== 'move') throw new Error(`unexpected ${m.type}`); + if (m.to === 'f') { + const pt = await solSpot(p, m.from, 'top'); + if (!phone) return p.mouse.dblclick(pt.x, pt.y); + await solTap(p, pt.x, pt.y); + await p.waitForTimeout(60); + return solTap(p, pt.x, pt.y); + } + const len = m.from[0] === 't' ? v.t[Number(m.from.slice(1))]!.length : 1; + await press(await solSpot(p, m.from, m.from[0] === 't' ? len - m.n : 'top')); + await p.locator(`[data-pile="${m.from}"] button[aria-pressed="true"]`).first().waitFor({ timeout: 3000 }); + await p.waitForTimeout(420); // not a double tap + await press(await solSpot(p, m.to, 'top')); +} + +/** 솔리테어: what each page's chooser already tried (so it never repeats a move from the same table). */ +const solMem = new WeakMap>(); + +/** 솔리테어: both screens start from the same deal, then each plays `steps` moves the computer's rules pick from that screen. */ +async function solPlay(pages: Page[], steps: number) { + const [host, guest] = pages as [Page, Page]; + for (const p of pages) await p.locator('.sl-felt [data-pile="t0"] [data-card]').first().waitFor({ timeout: 10_000 }); + for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 }); + if ((await solKey(host)) !== (await solKey(guest))) throw new Error('the two screens do not start from the same deal'); + const st = { pcF: 0, pcMove: 0, pcDraw: 0, phoneF: 0, phoneMove: 0, phoneDraw: 0 }; + const step = async (p: Page, phone: boolean) => { + const v = await solRead(p); + if (!solMem.has(p)) solMem.set(p, {}); + const m = solChoose(v, 0, () => 0.3, solMem.get(p)!); + if (m.type === 'stop') return false; + const before = JSON.stringify(v); + await solDo(p, m, phone, v); + for (let t = 0; t < 40 && (await solKey(p)) === before; t++) await p.waitForTimeout(100); + if ((await solKey(p)) === before) throw new Error(`${phone ? 'phone' : 'PC'}: ${JSON.stringify(m)} did not change the table`); + st[`${phone ? 'phone' : 'pc'}${m.type === 'move' ? (m.to === 'f' ? 'F' : 'Move') : 'Draw'}` as keyof typeof st]++; + await p.waitForTimeout(150); + return true; + }; + for (let i = 0; i < steps; i++) { + const a = await step(host, false); + const b = await step(guest, true); + if (!a && !b) break; + } + return st; +} + +/** 솔리테어: both give up (press twice) and the final ranking shows. */ +async function solGiveUp(pages: Page[]) { + for (const p of pages) { + if (await p.locator('.rc-over.note').count()) continue; + await p.getByRole('button', { name: '포기할래요' }).click(); + await p.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click(); + } + for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 }); +} + +/** 스도쿠: my board as the screen draws it (per cell in index order: digit, given, red, where it sits). */ +async function sdGrid(p: Page) { + return p.evaluate(() => + [...document.querySelectorAll('.sd-grid [data-i]')].map((el) => { + const b = el.getBoundingClientRect(); + return { v: el.getAttribute('data-v')!, given: el.getAttribute('data-given') === 'true', bad: el.getAttribute('data-bad') === 'true', x: b.left + b.width / 2, y: b.top + b.height / 2 }; + }), + ); +} + +/** 스도쿠: waits until cell `i` on the screen shows `v` ('0' = empty). */ +async function sdWaitCell(p: Page, i: number, v: string) { + await p.waitForFunction(([k, d]) => document.querySelector(`.sd-grid [data-i="${k}"]`)?.getAttribute('data-v') === d, [i, v] as const, { timeout: 3000 }); +} + +/** 스도쿠: one real tap on the phone through CDP (pointerType "touch"). */ +async function sdTouch(p: Page, x: number, y: number) { + const cdp = await p.context().newCDPSession(p); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + await cdp.detach(); +} + +/** 스도쿠: taps a button's centre on the phone. */ +async function sdTouchButton(p: Page, l: Locator) { + const b = (await l.boundingBox())!; + await sdTouch(p, b.x + b.width / 2, b.y + b.height / 2); +} + +/** 네모네모 로직: my marks as the screen draws them ('0' / '1' / '2' in index order), each cell's centre and the clues per line. */ +async function ngBoard(p: Page) { + return p.evaluate(() => { + const cells: { m: string; x: number; y: number; w: number }[] = []; + for (const g of document.querySelectorAll('svg.ng-board g[data-i]')) { + const b = g.querySelector('rect')!.getBoundingClientRect(); + cells[Number(g.getAttribute('data-i'))] = { m: g.getAttribute('data-m')!, x: b.left + b.width / 2, y: b.top + b.height / 2, w: b.width }; + } + const clues: number[][] = []; + for (const t of document.querySelectorAll('svg.ng-board text[data-line]')) { + const line = Number(t.getAttribute('data-line')); + (clues[line] ??= [])[Number(t.getAttribute('data-k'))] = Number(t.textContent); + } + return { cells, clues: clues.map((c) => c.filter((x) => x > 0)), size: Math.round(Math.sqrt(cells.length)) }; + }); +} + +/** 네모네모 로직: one straight drag from cell `a` to cell `b`, with the mouse (PC) or a real touch through CDP (phone). */ +async function ngDrag(p: Page, a: { x: number; y: number }, b: { x: number; y: number }, touch: boolean) { + const steps = 6; + if (!touch) { + await p.mouse.move(a.x, a.y); + await p.mouse.down(); + await p.mouse.move(b.x, b.y, { steps }); + await p.mouse.up(); + return; + } + const cdp = await p.context().newCDPSession(p); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: a.x, y: a.y }] }); + for (let k = 1; k <= steps; k++) await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: a.x + ((b.x - a.x) * k) / steps, y: a.y + ((b.y - a.y) * k) / steps }] }); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + await cdp.detach(); +} + +/** 네모네모 로직: fill row r's answer runs that are not filled yet, one drag per run; waits until the screen shows them. */ +async function ngFillRow(p: Page, answer: string, r: number, touch: boolean): Promise { + const { cells, size } = await ngBoard(p); + let drags = 0; + let c = 0; + while (c < size) { + if (answer[r * size + c] !== '#') { + c++; + continue; + } + const run: number[] = []; + while (c < size && answer[r * size + c] === '#') run.push(r * size + c++); + const todo = run.filter((i) => cells[i]!.m === '0'); + if (!todo.length) continue; + await ngDrag(p, cells[todo[0]!]!, cells[todo.at(-1)!]!, touch); + await p.waitForFunction((ids) => ids.every((i) => document.querySelector(`svg.ng-board g[data-i="${i}"]`)?.getAttribute('data-m') === '1'), todo, { timeout: 3000 }); + drags++; + } + return drags; +} + /** 그림 맞히기: non-white pixels on a page's drawing canvas (proves streamed strokes were rendered). */ async function cmInk(p: Page): Promise { return p.evaluate(() => { @@ -3613,6 +3853,454 @@ const PLANS: Record = { console.log(` apple: ${st.pc} mouse + ${st.key} keyboard clears on PC, ${st.phone}+ touch clears on the phone, ${st.miss} miss; final PC ${await appleScore(host)} / phone ${await appleScore(guest)}`); }, }, + minesweeper: { + // PC host + phone guest on the same 초급 field. Sure moves only (read from each screen): PC with left click (open / + // chord) and right click (flag), phone with taps and a long press (flag) plus the 깃발 mode button; progress reaches the + // other screen; both give up (press twice) and the result ranks them. + lobby: async (host) => { + await host.getByRole('group', { name: '난이도' }).getByRole('button', { name: '초급', exact: true }).click(); + await host.getByText(/초급 9×9/).first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + for (const p of pages) await p.locator('svg.ms-board g[data-i]').first().waitFor({ timeout: 10_000 }); + for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 }); + const a = await msGrid(host); + const b = await msGrid(guest); + if (a.map((c) => c.ch).join('') !== b.map((c) => c.ch).join('')) throw new Error('the two screens do not start from the same opening'); + const st = { pcOpen: 0, pcFlag: 0, phoneOpen: 0, phoneFlag: 0 }; + const cellsOf = (g: { ch: string }[]) => g.map((c) => c.ch).join(''); + const step = async (p: Page, phone: boolean) => { + const g = await msGrid(p); + const v = { rows: 9, cols: 9, mines: 10, cells: cellsOf(g), flags: 0 }; + const m = sureMove(v, true); + if (!m) return false; + const c = g[m.i]!; + const before = v.cells; + if (!phone) { + if (m.type === 'flag') await p.mouse.click(c.x, c.y, { button: 'right' }); + else await p.mouse.click(c.x, c.y); + } else if (m.type === 'flag') await touchTap(p, c.x, c.y, 600); + else await touchTap(p, c.x, c.y); + await p.waitForFunction((was) => [...document.querySelectorAll('svg.ms-board g[data-i]')].map((x) => x.getAttribute('data-ch')).join('') !== was, before, { timeout: 3000 }); + const k = `${phone ? 'phone' : 'pc'}${m.type === 'flag' ? 'Flag' : 'Open'}` as keyof typeof st; + st[k]++; + return true; + }; + for (let i = 0; i < 12; i++) { + const pc = await step(host, false); + const ph = await step(guest, true); + if (!pc && !ph) break; + if (await host.locator('.rc-over.note').count()) break; + } + // The 깃발 mode button on the phone turns a plain tap into a flag (and back). + const g = await msGrid(guest); + const closed = g.findIndex((c) => c.ch === '#'); + if (closed >= 0 && !(await guest.locator('.rc-over.note').count())) { + await guest.getByRole('button', { name: '깃발 모드' }).click(); + await touchTap(guest, g[closed]!.x, g[closed]!.y); + await guest.locator(`svg.ms-board g[data-i="${closed}"][data-ch="F"]`).waitFor({ timeout: 3000 }); + await touchTap(guest, g[closed]!.x, g[closed]!.y); + await guest.locator(`svg.ms-board g[data-i="${closed}"][data-ch="#"]`).waitFor({ timeout: 3000 }); + await guest.getByRole('button', { name: '깃발 모드' }).click(); + } + // The host's progress shows on the phone. + const opened = (await msGrid(host)).filter((c) => /[0-8]/.test(c.ch)).length; + await guest.waitForFunction((n) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${n}/71`)), opened, { timeout: 3000 }); + await host.screenshot({ path: join(SHOTS, 'minesweeper-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'minesweeper-mid-phone.png') }); + for (const p of pages) { + if (await p.locator('.rc-over.note').count()) continue; + await p.getByRole('button', { name: '포기할래요' }).click(); + await p.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click(); + } + for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 }); + await host.screenshot({ path: join(SHOTS, 'minesweeper-result-pc.png') }); + if (st.pcOpen + st.pcFlag + st.phoneOpen + st.phoneFlag < 4) throw new Error(`too few sure moves ${JSON.stringify(st)}`); + console.log(` minesweeper: ${JSON.stringify(st)}, flag mode, progress shared, both gave up → result`); + }, + }, + shisen: { + // PC host + phone guest on the same 작게 12×6 board. The PC removes pairs with the mouse and one with the keyboard, + // tries a wrong pair (shake + reason) and deselects; the phone (board turned upright) taps pairs and uses a hint; + // progress reaches the other screen; both give up (press twice) and the result ranks them. + lobby: async (host) => { + await host.getByRole('group', { name: '판 크기' }).getByRole('button', { name: '작게', exact: true }).click(); + await host.getByText(/작게 12×6/).first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + for (const p of pages) await p.locator('.ss-board .ss-cell[data-i]').first().waitFor({ timeout: 10_000 }); + for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 }); + const a = await ssGrid(host); + const b = await ssGrid(guest); + if (JSON.stringify(a.cells) !== JSON.stringify(b.cells) || a.cells.some((k) => !k)) throw new Error('the two screens do not start from the same full board'); + // Phone: the 12×6 board is turned upright and fits the screen without scrolling. + const box = await guest.locator('.ss-board').boundingBox(); + if (!box || box.height <= box.width || box.x < 0 || box.x + box.width > 390 || box.y + box.height > 844) throw new Error(`phone board ${JSON.stringify(box)}`); + const st = { pcMouse: 0, pcKey: 0, phoneTap: 0, phoneHint: 0 }; + const left = { host: 72, guest: 72 }; + /** Removes one pair that goes now, by mouse (PC) or touch (phone). */ + const pair = async (p: Page, phone: boolean, shot?: string) => { + const g = await ssGrid(p); + const two = ssFindPair(g.cells, g.rows, g.cols)!; + for (const i of two) { + const c = g.pos[i]!; + if (phone) await ssTap(p, c.x, c.y); + else await p.mouse.click(c.x, c.y); + } + if (shot) await p.screenshot({ path: join(SHOTS, shot) }); + const k = phone ? 'guest' : 'host'; + left[k] -= 2; + await ssWaitTiles(p, left[k]); + }; + for (let i = 0; i < 4; i++) { + await pair(host, false, i === 1 ? 'shisen-line-pc.png' : undefined); + st.pcMouse++; + await pair(guest, true, i === 1 ? 'shisen-line-phone.png' : undefined); + st.phoneTap++; + } + // PC keyboard: back to the top-left corner, then arrows + Space on both tiles of a pair. + { + const g = await ssGrid(host); + const two = ssFindPair(g.cells, g.rows, g.cols)!; + await host.locator('.ss-board').focus(); + for (let k = 0; k < g.rows; k++) await host.keyboard.press('ArrowUp'); + for (let k = 0; k < g.cols; k++) await host.keyboard.press('ArrowLeft'); + let at = [0, 0]; + for (const i of two) { + const to = [Math.floor(i / g.cols), i % g.cols]; + for (let k = 0; k < Math.abs(to[0]! - at[0]!); k++) await host.keyboard.press(to[0]! > at[0]! ? 'ArrowDown' : 'ArrowUp'); + for (let k = 0; k < Math.abs(to[1]! - at[1]!); k++) await host.keyboard.press(to[1]! > at[1]! ? 'ArrowRight' : 'ArrowLeft'); + await host.keyboard.press('Space'); + if (i === two[0]) { + await host.locator(`.ss-cell.sel.cur[data-i="${i}"]`).waitFor({ timeout: 3000 }); + await host.screenshot({ path: join(SHOTS, 'shisen-keys-pc.png') }); + } + at = to; + } + left.host -= 2; + await ssWaitTiles(host, left.host); + st.pcKey++; + } + // PC: a wrong pair shakes and says why; the tile picked last stays picked, and picking it again deselects. + { + const g = await ssGrid(host); + const i = g.cells.findIndex((k) => k); + const j = g.cells.findIndex((k) => k && k !== g.cells[i]); + await host.mouse.click(g.pos[i]!.x, g.pos[i]!.y); + await host.mouse.click(g.pos[j]!.x, g.pos[j]!.y); + await host.locator('.ss-toast', { hasText: '같은 패가 아니에요' }).waitFor({ timeout: 3000 }); + await host.locator(`.ss-cell.sel[data-i="${j}"]`).waitFor({ timeout: 3000 }); + await host.screenshot({ path: join(SHOTS, 'shisen-wrong-pc.png') }); + await host.mouse.click(g.pos[j]!.x, g.pos[j]!.y); + await host.waitForFunction(() => !document.querySelector('.ss-cell.sel'), null, { timeout: 3000 }); + } + // Phone: 💡 힌트 lights a pair; tapping those two removes them. + await guest.getByRole('button', { name: /힌트/ }).click(); + await guest.waitForFunction(() => document.querySelectorAll('.ss-cell.hint').length === 2, null, { timeout: 3000 }); + await guest.screenshot({ path: join(SHOTS, 'shisen-hint-phone.png') }); + { + const g = await ssGrid(guest); + const lit = await guest.$$eval('.ss-cell.hint', (els) => els.map((e) => Number(e.getAttribute('data-i')))); + for (const i of lit) await ssTap(guest, g.pos[i]!.x, g.pos[i]!.y); + left.guest -= 2; + await ssWaitTiles(guest, left.guest); + st.phoneHint++; + } + // The host's progress shows on the phone and the other way round. + const hostPairs = (72 - left.host) / 2; + await guest.waitForFunction((n) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${n}/36`)), hostPairs, { timeout: 3000 }); + await host.waitForFunction((n) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('친구') && li.textContent?.includes(`${n}/36`)), (72 - left.guest) / 2, { timeout: 3000 }); + await host.screenshot({ path: join(SHOTS, 'shisen-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'shisen-mid-phone.png') }); + for (const p of pages) await p.emulateMedia({ colorScheme: 'dark' }); + await host.waitForTimeout(300); + await host.screenshot({ path: join(SHOTS, 'shisen-mid-pc-dark.png') }); + await guest.screenshot({ path: join(SHOTS, 'shisen-mid-phone-dark.png') }); + for (const p of pages) await p.emulateMedia({ colorScheme: 'light' }); + // The smallest phone (320 px wide): the board still fits the width. + await guest.setViewportSize({ width: 320, height: 640 }); + await guest.waitForTimeout(300); + await guest.screenshot({ path: join(SHOTS, 'shisen-mid-phone-320.png') }); + const b320 = await guest.locator('.ss-board').boundingBox(); + if (!b320 || b320.x < 0 || b320.x + b320.width > 320) throw new Error(`320px board: ${JSON.stringify(b320)}`); + await guest.setViewportSize({ width: 390, height: 844 }); + for (const p of pages) { + await p.getByRole('button', { name: '포기할래요' }).click(); + await p.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click(); + } + for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 }); + await host.screenshot({ path: join(SHOTS, 'shisen-result-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'shisen-result-phone.png') }); + console.log(` shisen: ${JSON.stringify(st)}, wrong pair shakes, hint, progress shared, both gave up → result`); + }, + }, + solitaire: { + // PC host + phone guest on the same Klondike deal (draw 1). Each plays real moves the computer's rules pick from their + // own screen: PC with mouse clicks (pick, drop), double-clicks (to the foundation) and the stock; the phone with CDP + // taps and double taps. 되돌리기 on PC restores the table; progress reaches the other screen; both give up → result. + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + const st = await solPlay(pages, 1); + await host.screenshot({ path: join(SHOTS, 'solitaire-start-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'solitaire-start-phone.png') }); + // 되돌리기 (PC): one draw, then back to the same table. + const before = await solKey(host); + await host.locator('[data-pile="s"] button').first().click(); + for (let t = 0; t < 30 && (await solKey(host)) === before; t++) await host.waitForTimeout(100); + await host.getByRole('button', { name: '↶ 되돌리기' }).click(); + for (let t = 0; t < 30 && (await solKey(host)) !== before; t++) await host.waitForTimeout(100); + if ((await solKey(host)) !== before) throw new Error('되돌리기 did not restore the table'); + await host.locator('.rc-pill', { hasText: '↶ 1' }).waitFor({ timeout: 3000 }); + const more = await solPlay(pages, 30); + for (const k of Object.keys(st) as (keyof typeof st)[]) st[k] += more[k]; + // The host's progress shows on the phone. + const up = (await solRead(host)).f.reduce((n, c) => n + (c ? 'A23456789TJQK'.indexOf(c[0]!) + 1 : 0), 0); + await guest.waitForFunction((n) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${n}/52`)), up, { timeout: 3000 }); + await host.screenshot({ path: join(SHOTS, 'solitaire-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'solitaire-mid-phone.png'), fullPage: true }); + for (const p of pages) await p.emulateMedia({ colorScheme: 'dark' }); + await host.waitForTimeout(300); + await host.screenshot({ path: join(SHOTS, 'solitaire-mid-pc-dark.png') }); + await guest.screenshot({ path: join(SHOTS, 'solitaire-mid-phone-dark.png') }); + for (const p of pages) await p.emulateMedia({ colorScheme: 'light' }); + await solGiveUp(pages); + await host.screenshot({ path: join(SHOTS, 'solitaire-result-pc.png') }); + if (st.pcMove + st.pcF < 1 || st.phoneMove + st.phoneF < 1 || st.pcDraw + st.phoneDraw < 1) throw new Error(`too few moves ${JSON.stringify(st)}`); + console.log(` solitaire: ${JSON.stringify(st)}, same deal, undo, progress shared (${up}/52), both gave up → result`); + }, + }, + solitaireSpider: { + // 스파이더 1가지 무늬: 10 columns on the phone (≈34 px cards), a few real moves on both screens, then give up. + game: 'solitaire', + lobby: async (host) => { + await host.getByRole('group', { name: '종류' }).getByRole('button', { name: '스파이더', exact: true }).click(); + await host.getByText(/스파이더 · 무늬 1가지/).first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + const st = await solPlay(pages, 6); + await host.screenshot({ path: join(SHOTS, 'solitaire-spider-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'solitaire-spider-phone.png'), fullPage: true }); + await guest.setViewportSize({ width: 320, height: 700 }); + await guest.waitForTimeout(300); + await guest.screenshot({ path: join(SHOTS, 'solitaire-spider-phone-320.png'), fullPage: true }); + await guest.setViewportSize({ width: 390, height: 844 }); + await solGiveUp(pages); + console.log(` solitaireSpider: ${JSON.stringify(st)} → result`); + }, + }, + solitaireFreecell: { + // 프리셀: 8 columns all face up, free cells; a few real moves on both screens, then give up. + game: 'solitaire', + lobby: async (host) => { + await host.getByRole('group', { name: '종류' }).getByRole('button', { name: '프리셀', exact: true }).click(); + await host.getByText(/프리셀 · 빈 칸 4개/).first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + const st = await solPlay(pages, 6); + await host.screenshot({ path: join(SHOTS, 'solitaire-freecell-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'solitaire-freecell-phone.png'), fullPage: true }); + await solGiveUp(pages); + console.log(` solitaireFreecell: ${JSON.stringify(st)} → result`); + }, + }, + sudoku: { + // PC host + phone guest on the same 쉬움 puzzle (solved from the givens on screen). PC: mouse click + keyboard (a + // clashing digit turns red and is erased with Backspace, memo mode with N, arrows to move, a pad click); phone: taps on + // cells and the pad, a hint. Progress reaches the other screen; the PC solves it all, the phone gives up → result. + lobby: async (host) => { + await host.getByRole('group', { name: '난이도' }).getByRole('button', { name: '쉬움', exact: true }).click(); + await host.getByText(/숫자 38~40개/).first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + for (const p of pages) await p.locator('.sd-grid [data-i]').first().waitFor({ timeout: 10_000 }); + for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 }); + const g0 = await sdGrid(host); + if (g0.map((c) => c.v).join('') !== (await sdGrid(guest)).map((c) => c.v).join('')) throw new Error('the two screens do not start from the same puzzle'); + const sol = solve(g0.map((c) => (c.given ? Number(c.v) : 0)))!; + const blanks = g0.flatMap((c, i) => (c.given ? [] : [i])); + const st = { pcKeys: 0, pcPad: 0, phone: 0 }; + // PC: click the first blank, type a digit that is already in its row → red; Backspace clears it. + const e1 = blanks[0]!; + const clash = g0.find((c, j) => c.given && Math.floor(j / 9) === Math.floor(e1 / 9))!.v; + await host.mouse.click(g0[e1]!.x, g0[e1]!.y); + await host.keyboard.press(clash); + await sdWaitCell(host, e1, clash); + await host.locator(`.sd-grid [data-i="${e1}"][data-bad="true"]`).waitFor({ timeout: 3000 }); + await host.screenshot({ path: join(SHOTS, 'sudoku-clash-pc.png') }); + await host.keyboard.press('Backspace'); + await sdWaitCell(host, e1, '0'); + // Memo mode (N): two pencil marks, then the real digit wipes them. + await host.keyboard.press('n'); + await host.getByRole('button', { name: '✏️ 메모 켬' }).waitFor(); + const other = (sol[e1]! % 9) + 1; + for (const d of [sol[e1]!, other]) await host.keyboard.press(String(d)); + await host.waitForFunction((k) => (document.querySelector(`.sd-grid [data-i="${k}"] .sd-notes`)?.textContent ?? '').length === 2, e1, { timeout: 3000 }); + await host.keyboard.press('n'); + await host.keyboard.press(String(sol[e1])); + await sdWaitCell(host, e1, String(sol[e1])); + st.pcKeys++; + let at = e1; + /** PC: walk to cell `i` with the arrow keys and type its digit. */ + const pcKey = async (i: number) => { + const dr = Math.floor(i / 9) - Math.floor(at / 9); + const dc = (i % 9) - (at % 9); + for (let k = 0; k < Math.abs(dr); k++) await host.keyboard.press(dr > 0 ? 'ArrowDown' : 'ArrowUp'); + for (let k = 0; k < Math.abs(dc); k++) await host.keyboard.press(dc > 0 ? 'ArrowRight' : 'ArrowLeft'); + at = i; + await host.keyboard.press(String(sol[i])); + await sdWaitCell(host, i, String(sol[i])); + await host.waitForTimeout(90); // under 12 moves a second + st.pcKeys++; + }; + await pcKey(blanks[1]!); + // A pad click with the mouse. + const e3 = blanks[2]!; + await host.mouse.click(g0[e3]!.x, g0[e3]!.y); + at = e3; + await host.locator(`.sd-key[data-n="${sol[e3]}"]`).click(); + await sdWaitCell(host, e3, String(sol[e3])); + st.pcPad++; + // Phone: tap a blank from the end, then the pad digit (touch); then a hint. + const gp = await sdGrid(guest); + for (const i of blanks.slice(-3)) { + await sdTouch(guest, gp[i]!.x, gp[i]!.y); + await sdTouchButton(guest, guest.locator(`.sd-key[data-n="${sol[i]}"]`)); + await sdWaitCell(guest, i, String(sol[i])); + st.phone++; + } + await sdTouchButton(guest, guest.getByRole('button', { name: '💡 힌트' })); + await guest.getByLabel('힌트 1번').first().waitFor({ timeout: 3000 }); + // Progress reaches the other screen. + const total = blanks.length; + await guest.waitForFunction(([n, t]) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${n}/${t}`)), [3, total] as const, { timeout: 3000 }); + await host.waitForFunction(([n, t]) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('친구') && li.textContent?.includes(`${n}/${t}`)), [4, total] as const, { timeout: 3000 }); + await host.screenshot({ path: join(SHOTS, 'sudoku-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'sudoku-mid-phone.png') }); + // Dark mode on the PC and the narrowest phone (320px): nothing spills sideways, the pad stays on screen. + await host.emulateMedia({ colorScheme: 'dark' }); + await host.waitForTimeout(600); // colour transitions settle + await host.screenshot({ path: join(SHOTS, 'sudoku-mid-pc-dark.png') }); + await host.emulateMedia({ colorScheme: 'light' }); + await guest.setViewportSize({ width: 320, height: 640 }); + await guest.waitForTimeout(200); + const fit = await guest.evaluate(() => ({ page: document.documentElement.scrollWidth, grid: document.querySelector('.sd-grid')!.getBoundingClientRect().right, pad: document.querySelector('.sd-key[data-n="9"]')!.getBoundingClientRect().right })); + if (fit.page > 320 || fit.grid > 320 || fit.pad > 320) throw new Error(`320px phone overflows ${JSON.stringify(fit)}`); + await guest.screenshot({ path: join(SHOTS, 'sudoku-mid-phone320.png'), fullPage: true }); + await guest.setViewportSize({ width: 390, height: 844 }); + // The PC fills the rest with the keyboard. + for (const i of blanks.slice(3)) await pcKey(i); + await host.getByText(/다 풀었어요!/).first().waitFor({ timeout: 5000 }); + await guest.waitForFunction(() => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes('✔')), null, { timeout: 5000 }); + await guest.getByRole('button', { name: '포기할래요' }).click(); + await guest.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click(); + for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 }); + await host.screenshot({ path: join(SHOTS, 'sudoku-result-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'sudoku-result-phone.png'), fullPage: true }); + console.log(` sudoku: ${JSON.stringify(st)}, clash red + erase, memo, hint, progress shared, PC solved, phone gave up → result`); + }, + }, + nonogram: { + // PC host + phone guest on the same 15×15 picture (the tightest phone layout). The answer comes from the clues on + // screen (line logic). PC: keyboard fill + X, right click X, then mouse drags solve it → the picture's name shows. + // Phone: touch drags fill rows, the ✕ mode button marks a cell; progress reaches the other screen; the phone gives up + // (twice) → 최종 순위 on both. The phone also has to fit 15×15 at 390px and stay usable at 320px. + lobby: async (host) => { + await host.getByRole('group', { name: '크기' }).getByRole('button', { name: '15×15 어려움', exact: true }).click(); + await host.getByText(/15×15 어려움 · 힌트 켬/).first().waitFor(); + }, + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + for (const p of pages) await p.locator('svg.ng-board g[data-i]').first().waitFor({ timeout: 10_000 }); + for (const p of pages) await p.waitForFunction(() => !document.querySelector('.rc-over.count'), null, { timeout: 10_000 }); + const a = await ngBoard(host); + const b = await ngBoard(guest); + if (a.size !== 15 || JSON.stringify(a.clues) !== JSON.stringify(b.clues)) throw new Error('the two screens do not show the same clues'); + if (![...a.cells, ...b.cells].every((c) => c.m === '0')) throw new Error('boards should start empty'); + const n = a.size; + const g = solveGrid(n, a.clues.slice(0, n), a.clues.slice(n)); + if (!g || g.includes(-1)) throw new Error('clues on screen are not solvable by line logic'); + const answer = g.map((x) => (x === 1 ? '#' : '.')).join(''); + // Phone layout: 15×15 with its clues fits 390px, cells about 18–20px. + const box = (await guest.locator('svg.ng-board').boundingBox())!; + if (box.x < 0 || box.x + box.width > 390 + 0.5) throw new Error(`phone board overflows: ${JSON.stringify(box)}`); + if (b.cells[0]!.w < 17) throw new Error(`phone cells too small: ${b.cells[0]!.w}px`); + const st = { pcKey: 0, pcRight: 0, pcDrag: 0, phoneDrag: 0, phoneX: 0 }; + // PC keyboard: cursor starts at the top-left cell; Space fills an answer cell of row 0, X marks an empty one. + const svg = host.locator('svg.ng-board'); + await svg.focus(); + const fillAt = [...answer].findIndex((ch) => ch === '#'); + const xAt = [...answer].findIndex((ch, i) => ch === '.' && i > fillAt && i < n); + for (let c = 0; c < fillAt; c++) await host.keyboard.press('ArrowRight'); + await host.keyboard.press('Space'); + await host.locator(`svg.ng-board g[data-i="${fillAt}"][data-m="1"]`).waitFor({ timeout: 3000 }); + for (let c = fillAt; c < xAt; c++) await host.keyboard.press('ArrowRight'); + await host.keyboard.press('x'); + await host.locator(`svg.ng-board g[data-i="${xAt}"][data-m="2"]`).waitFor({ timeout: 3000 }); + st.pcKey += 2; + // PC right click: X on an empty cell of row 1. + const rx = [...answer].findIndex((ch, i) => ch === '.' && i >= n && i < 2 * n); + const hc = (await ngBoard(host)).cells; + await host.mouse.click(hc[rx]!.x, hc[rx]!.y, { button: 'right' }); + await host.locator(`svg.ng-board g[data-i="${rx}"][data-m="2"]`).waitFor({ timeout: 3000 }); + st.pcRight++; + // Phone: touch drags fill the first rows; the ✕ mode turns a tap into an X (and a second tap clears it). + for (let r = 0; r < 4; r++) st.phoneDrag += await ngFillRow(guest, answer, r, true); + const px = [...answer].findIndex((ch, i) => ch === '.' && i >= 5 * n); + await guest.getByRole('button', { name: '✕ 표시' }).click(); + const gc = (await ngBoard(guest)).cells; + await touchTap(guest, gc[px]!.x, gc[px]!.y); + await guest.locator(`svg.ng-board g[data-i="${px}"][data-m="2"]`).waitFor({ timeout: 3000 }); + await touchTap(guest, gc[px]!.x, gc[px]!.y); + await guest.locator(`svg.ng-board g[data-i="${px}"][data-m="0"]`).waitFor({ timeout: 3000 }); + await touchTap(guest, gc[px]!.x, gc[px]!.y); + await guest.locator(`svg.ng-board g[data-i="${px}"][data-m="2"]`).waitFor({ timeout: 3000 }); + st.phoneX++; + await guest.getByRole('button', { name: '■ 채우기' }).click(); + // PC drags its first rows, then each side sees the other's progress. + for (let r = 0; r < 5; r++) st.pcDrag += await ngFillRow(host, answer, r, false); + const chip = (p: Page, who: string) => + p.evaluate((w) => [...document.querySelectorAll('.rc-others li')].find((li) => li.textContent?.includes(w))?.querySelector('b')?.textContent ?? '', who); + const hostOk = async () => Number((await host.locator('.rc-pill', { hasText: '✔' }).innerText()).match(/(\d+)\s*\//)![1]); + const want = await hostOk(); + if (want < 5) throw new Error(`host should have at least 5 lines right, has ${want}`); + await guest.waitForFunction((w) => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes(`${w}/30`)), want, { timeout: 3000 }); + if (!(await chip(host, '친구')).match(/^\d+\/30$/)) throw new Error('host does not see the phone progress'); + await host.screenshot({ path: join(SHOTS, 'nonogram-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'nonogram-mid-phone.png') }); + await guest.screenshot({ path: join(SHOTS, 'nonogram-mid-phone-full.png'), fullPage: true }); + await guest.emulateMedia({ colorScheme: 'dark' }); + await guest.waitForTimeout(400); + await guest.screenshot({ path: join(SHOTS, 'nonogram-mid-phone-dark.png') }); + await guest.emulateMedia({ colorScheme: 'light' }); + // 320px phone: still on screen and tappable. + await guest.setViewportSize({ width: 320, height: 700 }); + await guest.waitForTimeout(300); + const small = (await guest.locator('svg.ng-board').boundingBox())!; + if (small.x < 0 || small.x + small.width > 320 + 0.5) throw new Error(`320px board overflows: ${JSON.stringify(small)}`); + st.phoneDrag += await ngFillRow(guest, answer, 4, true); + await guest.screenshot({ path: join(SHOTS, 'nonogram-320-phone.png') }); + await guest.setViewportSize({ width: 390, height: 844 }); + // PC solves the rest; the picture's name shows. + for (let r = 5; r < n; r++) st.pcDrag += await ngFillRow(host, answer, r, false); + await host.locator('.ng-title', { hasText: '다 풀었어요!' }).waitFor({ timeout: 5000 }); + await host.locator('svg.ng-board .ng-color').first().waitFor(); + await host.waitForTimeout(1500); + await host.screenshot({ path: join(SHOTS, 'nonogram-solved-pc.png') }); + await guest.waitForFunction(() => [...document.querySelectorAll('.rc-others li')].some((li) => li.textContent?.includes('방장') && li.textContent?.includes('✔')), null, { timeout: 3000 }); + await guest.getByRole('button', { name: '포기할래요' }).click(); + await guest.getByRole('button', { name: '한 번 더 누르면 포기해요' }).click(); + for (const p of pages) await p.getByText('최종 순위').first().waitFor({ timeout: 10_000 }); + await guest.locator('.ng-title', { hasText: '정답 그림:' }).waitFor({ timeout: 5000 }); + await host.screenshot({ path: join(SHOTS, 'nonogram-result-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'nonogram-result-phone.png'), fullPage: true }); + console.log(` nonogram: ${JSON.stringify(st)}, same clues, progress shared, PC solved (${await host.locator('.ng-title').innerText()}), phone gave up → result`); + }, + }, typing: { // 2026-11-12 타자 대결, 가장 먼저 입력 · 짧은글 · 1라운드: host and phone take turns typing each sentence for real // (keyboard, one key at a time). A wrong Enter shakes the box and keeps the text; the other side sees the "먼저 쳤어요" diff --git a/packages/games/src/bots/index.ts b/packages/games/src/bots/index.ts index cdb821a..6079436 100644 --- a/packages/games/src/bots/index.ts +++ b/packages/games/src/bots/index.ts @@ -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 = { apple: appleBot, liar: liarBot, typing: typingBot, + minesweeper: minesweeperBot, + shisen: shisenBot, + solitaire: solitaireBot, + sudoku: sudokuBot, + nonogram: nonogramBot, }; diff --git a/packages/games/src/index.ts b/packages/games/src/index.ts index b7e3954..aa7e7b7 100644 --- a/packages/games/src/index.ts +++ b/packages/games/src/index.ts @@ -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 = { [omok.id]: omok, @@ -83,4 +88,9 @@ export const GAMES: Record = { [caseFile.id]: caseFile, [castlesOfBurgundy.id]: castlesOfBurgundy, [typing.id]: typing, + [minesweeper.id]: minesweeper, + [shisen.id]: shisen, + [solitaire.id]: solitaire, + [sudoku.id]: sudoku, + [nonogram.id]: nonogram, }; diff --git a/packages/games/src/minesweeper/bot.test.ts b/packages/games/src/minesweeper/bot.test.ts new file mode 100644 index 0000000..95388a0 --- /dev/null +++ b/packages/games/src/minesweeper/bot.test.ts @@ -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 }); + }); +}); diff --git a/packages/games/src/minesweeper/bot.ts b/packages/games/src/minesweeper/bot.ts new file mode 100644 index 0000000..f958647 --- /dev/null +++ b/packages/games/src/minesweeper/bot.ts @@ -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(); + 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, 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()) }; +}); diff --git a/packages/games/src/minesweeper/index.ts b/packages/games/src/minesweeper/index.ts new file mode 100644 index 0000000..096c5cb --- /dev/null +++ b/packages/games/src/minesweeper/index.ts @@ -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('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; + +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; +export type MinesweeperView = RaceView; + +/** 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({ + 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], +}); diff --git a/packages/games/src/minesweeper/minesweeper.test.ts b/packages/games/src/minesweeper/minesweeper.test.ts new file mode 100644 index 0000000..d375c8c --- /dev/null +++ b/packages/games/src/minesweeper/minesweeper.test.ts @@ -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[2]; + +function make(players = ['A', 'B'], opts: Partial = {}, 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, 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)); + } + } + }); +}); diff --git a/packages/games/src/nonogram/bank.ts b/packages/games/src/nonogram/bank.ts new file mode 100644 index 0000000..c14a42a --- /dev/null +++ b/packages/games/src/nonogram/bank.ts @@ -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: ['.......#.......', '......###......', '......###......', '.....#####.....', '###############', '.#############.', '..###########..', '...#########...', '....#######....', '...#########...', '...####.####...', '..####...####..', '..###.....###..', '.##.........##.', '.#...........#.'], + }, + ], +}; diff --git a/packages/games/src/nonogram/bot.test.ts b/packages/games/src/nonogram/bot.test.ts new file mode 100644 index 0000000..7c97ba5 --- /dev/null +++ b/packages/games/src/nonogram/bot.test.ts @@ -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 }); + }); +}); diff --git a/packages/games/src/nonogram/bot.ts b/packages/games/src/nonogram/bot.ts new file mode 100644 index 0000000..4365971 --- /dev/null +++ b/packages/games/src/nonogram/bot.ts @@ -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, 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 }; +}); diff --git a/packages/games/src/nonogram/index.ts b/packages/games/src/nonogram/index.ts new file mode 100644 index 0000000..e9d49c3 --- /dev/null +++ b/packages/games/src/nonogram/index.ts @@ -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 = { 5: '쉬움', 10: '보통', 15: '어려움' }; + +export const nonogramOptionsSchema = z.object({ + size: lit(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; + +/** 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(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; +export type NonogramView = RaceView; + +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({ + 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], +}); diff --git a/packages/games/src/nonogram/nonogram.test.ts b/packages/games/src/nonogram/nonogram.test.ts new file mode 100644 index 0000000..56ba6f6 --- /dev/null +++ b/packages/games/src/nonogram/nonogram.test.ts @@ -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[2]; + +function make(players = ['A', 'B'], opts: Partial = {}, 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, 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(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)); + } + } + }); +}); diff --git a/packages/games/src/nonogram/solver.ts b/packages/games/src/nonogram/solver.ts new file mode 100644 index 0000000..eab7f52 --- /dev/null +++ b/packages/games/src/nonogram/solver.ts @@ -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): 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(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(n).fill(false); + const canFill = new Array(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(size * size).fill(-1); + const clues = [...rows, ...cols]; + let dirty = new Set(clues.map((_, i) => i)); + while (dirty.size) { + const next = new Set(); + 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; +} diff --git a/packages/games/src/race/bot.ts b/packages/games/src/race/bot.ts new file mode 100644 index 0000000..043142e --- /dev/null +++ b/packages/games/src/race/bot.ts @@ -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 { + /** 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(plan: (board: BV, skill: number, random: () => number, memory: Record) => RacePlan): LiveBotStrategy> { + return ({ me, view: v, now, random, persona, level, memory }: LiveBotInput>): LiveBotDecision => { + 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 }; + }; +} diff --git a/packages/games/src/race/index.ts b/packages/games/src/race/index.ts new file mode 100644 index 0000000..6aafd4b --- /dev/null +++ b/packages/games/src/race/index.ts @@ -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 = (...vals: T[]) => + z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral, z.ZodLiteral, ...z.ZodLiteral[]]); + +/** The time limit option every race game has: null = 무제한 (until everyone solves or gives up). */ +export function timeLimitOption(choices: T[], def: T | null) { + const labels: Record = { null: '무제한' }; + for (const c of choices) labels[String(c)] = c % 60 === 0 ? `${c / 60}분` : `${c}초`; + return lit(...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 { + options: O; + order: PlayerId[]; + /** The shared puzzle (hidden during the countdown). */ + puzzle: P; + boards: Record; + status: Record; + /** Server time each player solved / failed / gave up. */ + finishedAt: Record; + /** Server times of each player's recent moves (rate limit). */ + recent: Record; + 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 { + 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 | StopAction | { type: 'tick' } | { type: 'leave' }; + +export interface MoveOutcome { + board: B; + /** The move finished the puzzle, or ended it by a mistake (지뢰). */ + outcome?: 'solved' | 'failed'; + events?: GameEvent[]; +} + +export interface RaceSpec { + id: string; + nameKo: string; + optionsSchema: z.ZodType; + /** The game's own moves (each a `z.object` with a literal `type`). */ + moveSchemas: [z.ZodObject<{ type: z.ZodLiteral } & z.ZodRawShape>, ...z.ZodObject<{ type: z.ZodLiteral } & 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; + /** 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, '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 = { 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(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( + spec: RaceSpec, +): GameDefinition, RaceAction, RaceView, O> { + type S = RaceState; + type A = RaceAction; + type Def = GameDefinition, 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 = (v: () => T) => Object.fromEntries(players.map((p) => [p, v()])) as Record; + const countdownEndsAt = now + COUNTDOWN_MS; + return { + options, + order: [...players], + puzzle, + boards: per(() => board), + status: per(() => 'playing'), + finishedAt: {}, + recent: per(() => []), + 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(); + 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; +} diff --git a/packages/games/src/shisen/bot.test.ts b/packages/games/src/shisen/bot.test.ts new file mode 100644 index 0000000..c67e10e --- /dev/null +++ b/packages/games/src/shisen/bot.test.ts @@ -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 }, + ]); + }); +}); diff --git a/packages/games/src/shisen/bot.ts b/packages/games/src/shisen/bot.ts new file mode 100644 index 0000000..19277d9 --- /dev/null +++ b/packages/games/src/shisen/bot.ts @@ -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, 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()) }; +}); diff --git a/packages/games/src/shisen/index.ts b/packages/games/src/shisen/index.ts new file mode 100644 index 0000000..4e952fc --- /dev/null +++ b/packages/games/src/shisen/index.ts @@ -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('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; + +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; +export type ShisenView = RaceView; + +/** 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(); + 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(); + 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(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({ + 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('')], +}); diff --git a/packages/games/src/shisen/shisen.test.ts b/packages/games/src/shisen/shisen.test.ts new file mode 100644 index 0000000..d5a4d3f --- /dev/null +++ b/packages/games/src/shisen/shisen.test.ts @@ -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[2]; + +function make(players = ['A', 'B'], opts: Partial = {}, 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, 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(); + 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)); + } + } + }); +}); diff --git a/packages/games/src/solitaire/bot.test.ts b/packages/games/src/solitaire/bot.test.ts new file mode 100644 index 0000000..bde5ab6 --- /dev/null +++ b/packages/games/src/solitaire/bot.test.ts @@ -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[] = [{ 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' }); + }); +}); diff --git a/packages/games/src/solitaire/bot.ts b/packages/games/src/solitaire/bot.ts new file mode 100644 index 0000000..94463c8 --- /dev/null +++ b/packages/games/src/solitaire/bot.ts @@ -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(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([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; + 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, 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()) }; +}); diff --git a/packages/games/src/solitaire/index.ts b/packages/games/src/solitaire/index.ts new file mode 100644 index 0000000..57f5295 --- /dev/null +++ b/packages/games/src/solitaire/index.ts @@ -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 = { 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('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; + +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 = { 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; +export type SolitaireView = RaceView; + +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): 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): 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({ + 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], +}); diff --git a/packages/games/src/solitaire/solitaire.test.ts b/packages/games/src/solitaire/solitaire.test.ts new file mode 100644 index 0000000..b4aa2d5 --- /dev/null +++ b/packages/games/src/solitaire/solitaire.test.ts @@ -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[2]; + +function make(players = ['A', 'B'], opts: Partial = {}, 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, 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 & { 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 = {}): 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(); + 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; +} diff --git a/packages/games/src/sudoku/bot.test.ts b/packages/games/src/sudoku/bot.test.ts new file mode 100644 index 0000000..7e3c292 --- /dev/null +++ b/packages/games/src/sudoku/bot.test.ts @@ -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); + }); +}); diff --git a/packages/games/src/sudoku/bot.ts b/packages/games/src/sudoku/bot.ts new file mode 100644 index 0000000..41f17cf --- /dev/null +++ b/packages/games/src/sudoku/bot.ts @@ -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 = { 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 { + 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(); + 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, 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 }; +}); diff --git a/packages/games/src/sudoku/index.ts b/packages/games/src/sudoku/index.ts new file mode 100644 index 0000000..4af94c3 --- /dev/null +++ b/packages/games/src/sudoku/index.ts @@ -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('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; + +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; +export type SudokuView = RaceView; + +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(9).fill(0); + const cols = new Array(9).fill(0); + const boxes = new Array(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(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(81).fill(0); + search(new Array(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({ + id: 'sudoku', + nameKo: '스도쿠', + optionsSchema: sudokuOptionsSchema, + moveSchemas: moveSchemas as never, + + makePuzzle: (rng, o) => makePuzzle(rng, o.difficulty), + + startBoard: (p) => ({ values: p.givens, notes: new Array(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], +}); diff --git a/packages/games/src/sudoku/sudoku.test.ts b/packages/games/src/sudoku/sudoku.test.ts new file mode 100644 index 0000000..b0902c5 --- /dev/null +++ b/packages/games/src/sudoku/sudoku.test.ts @@ -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[2]; + +function make(players = ['A', 'B'], opts: Partial = {}, 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, 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)); + } + } + }); +}); diff --git a/packages/shared/src/bots.ts b/packages/shared/src/bots.ts index af80130..ed5b5ee 100644 --- a/packages/shared/src/bots.ts +++ b/packages/shared/src/bots.ts @@ -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명). */ diff --git a/packages/shared/src/catalog.ts b/packages/shared/src/catalog.ts index 93ef541..01792fb 100644 --- a/packages/shared/src/catalog.ts +++ b/packages/shared/src/catalog.ts @@ -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 },