Compare commits

...

8 Commits

Author SHA1 Message Date
EJClaw
c2aaff5762 같은 판 경주: 포기·실패한 사람에게는 다른 사람이 푸는 동안 정답을 보내지 않음(다 풀었거나 게임이 끝났을 때만), 지뢰찾기는 밟은 지뢰만 바로 표시
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:40:57 +09:00
EJClaw
9f9d20a641 솔리테어 아이콘을 빨간 하트 이모지로(글자 하트는 검게 보임)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:29:59 +09:00
EJClaw
1b9acb9fc1 새 게임 5개(같은 판 경주): 지뢰찾기, 사천성, 솔리테어, 스도쿠, 네모네모 로직
- 공통 틀 race: 같은 시드 판을 모두 각자 동시에, 3초 카운트다운, 제한 시간/무제한, 포기, 다 푼 시간 → 푼 만큼 순위, live 컴퓨터
- 지뢰찾기: 초급·중급·고급, 모두에게 같은 곳이 열린 채 시작, 깃발·한꺼번에 열기, 휴대폰 길게 누르기·깃발 모드
- 사천성: 마작패 72·112·136장, 두 번 이하로 꺾이는 선, 항상 풀리는 배치, 막히면 자동 섞기, 힌트
- 솔리테어: 클론다이크(1장·3장)·프리셀·스파이더(1·2·4무늬), 되돌리기, 자동 정리
- 스도쿠: 답이 하나인 문제 생성기(쉬움·보통·어려움), 메모, 겹침 표시, 힌트
- 네모네모 로직: 그림 37개(5×5·10×10·15×15, 모두 줄 논리만으로 풀림), 드래그 칠하기·X 표시, 풀면 그림과 이름
- 게임 46개, 컴퓨터 상대 42개, 게임 고르기에 혼자·퍼즐 탭
(아발론·모노레일은 아직 공개 전이라 이 배포에서 뺌; 작업 갈래 codex/owner/grp_discord_joke-app 2773f5c..에서 옮김)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 14:29:01 +09:00
EJClaw
35f2310f8d 타자 대결 연습: 한 사람이 나가도 남은 사람은 끝까지 침(대결만 한 명 남으면 끝)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:21:21 +09:00
EJClaw
892f64db0e e2e typingPracticeLong: '다 쳤어요' 글이 상태 줄과 판에 함께 있어 first()
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:13:02 +09:00
EJClaw
943e4be3fd 타자 대결 연습 모드: 한컴 타자연습처럼 짧은글 10문장·단어 20개·긴글 한 편 전체를 제한 시간·점수 없이
- 대결 방식에 "연습" 추가(각자 치기, 라운드 1번, 시계·점수 없음). 긴글은 고른 주제 중 한 편을 처음부터 끝까지(8줄 단락이 아님).
- 줄마다 첫 타부터 시간을 재서 줄 사이에 쉬어도 타수가 안 떨어짐(첫 타 몫 0.15초 앞당김 → 붙여 넣기 막기 그대로).
  줄 최고 타수(best) 기록. 컴퓨터도 연습에서는 첫 타를 바로 보냄.
- 화면: 라운드 대신 걸린 시간, 지금·평균·최고 타수·정확도·진행 %, 끝나면 평균·최고·정확도·틀린 줄, 참가자 옆은 타수.
  설정에서 라운드·제한 시간 숨김, 종목 이름 "연습 종목", 도움말·규칙·요약 카드·docs.
- 테스트: 연습 4개(엔진), 무작위 대국 2가지, 컴퓨터 1가지, 도움말 1개, e2e typingPractice·typingPracticeLong.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:09:37 +09:00
EJClaw
122cf5ed1f 타자 대결: 서바이벌이 반드시 끝나게(모두 동시 탈락·동점 3번 연속이면 남은 사람 공동 1점, 문제 60개 상한), 라운드 끝난 뒤 평균 타수·정확도 중복 합산 고침, 정확도 0%를 100%로 보이던 것 고침
- 남은 사람이 모두 한꺼번에 탈락하게 되어 아무도 안 빠지는 문제(시간별은 모두 동점인 간격)가 SURVIVAL_STALL_LIMIT(3)번
  이어지면 라운드를 끝내고 남은 사람이 함께 1점. 누가 치거나 탈락하면 횟수는 0으로. 함께 치기는 SURVIVAL_MAX_ITEMS(60)번째
  문제에서도 끝. 라운드 요약 "더 탈락하는 사람이 없어서 남은 사람이 함께 1점을 얻어요".
- seatView: 진행 중인 라운드만 누적에 더하고, roundEnd·ended에서는 endRound가 이미 더한 누적만 보여 줌.
- SeatView.roundTried·tried(무언가 제출했는지)로 "아직 없음"(-)과 실제 0%를 구분(화면·도움말).
- 테스트: 네 탈락 조건 모두 아무도 안 칠 때 200번 안에 끝남, 모두 늘 시간 안에 칠 때 60문제에서 끝, 진짜 탈락이 횟수를
  초기화, 라운드 뒤 자리 표시 = 최종 결과, 전부 틀린 답의 정확도 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:53:52 +09:00
EJClaw
fffb860282 새 게임 타자 대결: 한국어·영어, 가장 먼저 입력·서바이벌·타수 비교·정확도 대결·타임어택, 단어·짧은글·긴글, 주제 여러 개, 1~10라운드
- 규칙 packages/games/src/typing: 함께 치기(같은 문제를 동시에, 정해지면 1.5초 쉬고 다음)와 각자 치기(한 줄씩 자기 속도로).
  가장 먼저 입력은 문제마다 먼저 정확하게 친 사람 1점, 나머지는 라운드 1등 1점, 최종은 점수 → 평균 타수 → 정확도.
  서바이벌 탈락 조건: 틀렸을 때(목숨 1~5, 기본 3)·문장별(가장 늦게 친 사람)·시간별(간격마다 가장 적게 친 사람)·시간 초과.
  서바이벌은 문제마다 시간이 0.9배씩 줄어(900타 + 1초 아래로는 안 줄어) 반드시 끝나고, 모두 한꺼번에 탈락하게 되면 아무도 탈락하지 않음.
  제한 시간 자동(글 길이)/10초~5분/무제한, 타임어택 30초~2분, 3초 카운트다운, 라운드 결과 6초.
- 타수: 두벌식 자판 수(겹모음·겹받침 2타), 조합 중 글자는 친 자판까지 맞은 것으로, 정확도 = 1 − 편집 거리/길이.
  붙여 넣기 막기: 화면에서 막고 서버는 2,400타/분 + 0.15초보다 빠른 정답을 거절, 진행 막대도 그 속도 이상 못 앞섬.
- 진행은 stream 액션(progress)이라 서버는 이벤트만 전달(보기 재계산·DB 쓰기 없이 묶어서 저장).
- 글 묶음 37개 주제: 한국어 단어 8(과일·동물·채소·나라·음식·직업·스포츠·사자성어), 짧은글 4(속담·명언·잰말놀이·일상 문장),
  긴글 11(애국가·별 헤는 밤·서시·진달래꽃·산유화·님의 침묵·훈민정음 서문·전래 동화 3), 영어 단어 7·짧은글 4·긴글 7.
  시는 위키문헌 원문과 대조해 현대 맞춤법으로. 일반 자판 글자만(테스트로 확인), 긴 줄은 띄어쓰기에서 나눔.
- 컴퓨터(live): 레벨에 따라 120~620타(영어 100~500), 읽는 시간, 오타 확률. 함께 치기는 틀리면 고쳐서 다시.
- 화면: 글자별 초록/빨강/조합 중 표시, 긴글은 단락 전체와 지금 줄(자동 스크롤), 다음 두 줄 미리 보기, 한글 조합 중 Enter 처리,
  한/영 경고, 지금 타수·정확도, 모두의 진행 막대(실시간)·목숨 하트, "먼저 쳤어요"/"탈락" 띠, 라운드 결과 표, 소리, 휴대폰.
- 등록: GAMES·LIVE_BOT_STRATEGIES·BOT_GAMES·CATALOG·GAME_UI·아이콘 ⌨️·파티 탭, README(43개), docs/games/typing.md.
- 테스트: 규칙 34·타수/글 묶음 9·컴퓨터 12·방 통합 4·웹 도움말 3, e2e games.e2e.ts typing·typingSpeed·typingSurvival.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 12:45:19 +09:00
81 changed files with 13533 additions and 7 deletions

View File

@@ -5,13 +5,14 @@
운영 중: https://game.tkrmagid.kr 운영 중: https://game.tkrmagid.kr
## 게임 (40개) ## 게임 (46개)
| 종류 | 게임 | | 종류 | 게임 |
|---|---| |---|---|
| 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) | | 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 티츄, 젝스님트, 구십구, 바퀴벌레 포커, 뱅! | | 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 티츄, 젝스님트, 구십구, 바퀴벌레 포커, 뱅! |
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택, 증강 윷놀이), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 | | 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택, 증강 윷놀이), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 |
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) | | 혼자·퍼즐(같은 판 경주) | 지뢰찾기, 사천성, 솔리테어(클론다이크·프리셀·스파이더), 스도쿠, 네모네모 로직 |
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 타자 대결, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) |
칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음). 칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음).
@@ -19,7 +20,7 @@
- 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다. - 로그인: 디스코드 또는 게스트(닉네임만). 게스트는 로그아웃하거나 하루 동안 접속하지 않으면 계정이 지워진다.
- 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다. - 방: 방 링크를 보내면 친구가 바로 들어온다. 방 막대에서 링크 복사·채팅·규칙·설정(글자 크기·소리)·나가기를 한 번에 누른다. 게임 중에 나가면 기권으로 처리된다.
- 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다. - 모든 게임에 효과음과 움직임(상대·컴퓨터의 수에도 나옴), 오른쪽 위 소리 크기(0~100, 기본 50). 시간 제한이 있는 게임은 모두 "무제한"도 고를 수 있다.
- 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 36개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만. - 컴퓨터 상대: 실시간·그림 게임(할리갈리, 도블, 그림 맞히기)과 협력 추리(사건 파일)를 뺀 42개 게임. 마피아·라이어 게임의 컴퓨터는 채팅으로 말하고, 다른 게임의 컴퓨터 잡담은 방장이 켤 때만.
- 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드. - 처음 하는 사람을 위한 30초 규칙 요약, 게임별 규칙 페이지, 끝난 판 다시 보기, 이름을 누르면 나오는 기록 카드.
- 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드. - 홈 화면에 추가(PWA), 휴대폰(320px부터)·PC, 다크 모드.
- 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 라이어 게임 주제·제시어 추가/수정/삭제, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록. - 관리자 화면(`/admin`): 게임 규칙 기본값·잠금, 라이어 게임 주제·제시어 추가/수정/삭제, 게임 속도 배율(애니메이션·컴퓨터 생각 시간, 1/16~16배), 사용자·방 관리, 계정별 기록.

View File

@@ -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<ServerMessage, { t: 'state' }>).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);
});
});

View File

@@ -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<ServerMessage, { t: 'state' }>).view as NonogramView;
function twoPlayerRoom(h: ReturnType<typeof harness>, 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);
});
});

View File

@@ -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<ServerMessage, { t: 'state' }>).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']);
});
});

View File

@@ -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<ServerMessage, { t: 'state' }>).view as SolitaireView;
function twoPlayers(h: ReturnType<typeof harness>, options: Record<string, unknown>) {
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);
});
});

View File

@@ -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<ServerMessage, { t: 'state' }>).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);
});
});

View File

@@ -0,0 +1,159 @@
/** 타자 대결 through a real Room: progress streams, a practice game against a computer, away players (docs/games/typing.md §8). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { TypingState, TypingView } from '@bg/games/typing';
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<ServerMessage, { t: 'state' }>).view as TypingView;
function twoPlayers(options: Record<string, unknown>) {
const h = harness();
const r = h.manager.create('A', 'typing', '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: { ...GAMES.typing!.defaultOptions, ...options } })).toBeNull();
expect(room.start('A')).toBeNull();
h.clock.advance(3000);
room.onTimer();
return { h, room, a, b, s: () => room.game!.state as TypingState };
}
describe('타자 대결 room flow', () => {
test('연습: 먼저 다 친 사람이 방을 나가도 남은 사람은 끝까지 쳐요', () => {
const { h, room, b, s } = twoPlayers({ mode: 'practice', category: 'word' });
const typeAll = (who: string) => {
const n = s().items.length;
for (let i = 0; i < n; i++) {
h.clock.advance(3000);
room.act(who, 100 + i, { type: 'submit', item: i, text: s().items[i]! });
}
};
typeAll('A');
expect(s().rs.A!.finishedAt).not.toBeNull();
room.leave('A');
expect(s().phase).toBe('playing');
expect(lastView(b).upcoming[0]!.idx).toBe(0);
typeAll('B');
expect(b.msgs.filter((m) => m.t === 'reject')).toEqual([]);
expect(s().phase).toBe('ended');
expect(s().final!.ranking[0]).toMatchObject({ id: 'B', left: false });
});
test('진행은 stream으로만 가고(보기 다시 계산 없음), 먼저 정확하게 친 사람이 점수를 얻어요', () => {
const { h, room, a, b, s } = twoPlayers({ rounds: 1 });
const v = lastView(b);
expect(v.phase).toBe('playing');
const item = v.upcoming[0]!;
// A paste the moment the text appears is refused.
room.act('B', 1, { type: 'submit', item: item.idx, text: item.text });
expect((b.msgs.filter((m) => m.t === 'reject').at(-1) as { reason: string }).reason).toContain('너무 빨라요');
const states = b.msgs.filter((m) => m.t === 'state').length;
h.clock.advance(1500);
room.act('A', 1, { type: 'progress', item: item.idx, text: item.text.slice(0, 2) });
const stream = b.msgs.filter((m) => m.t === 'stream').at(-1) as Extract<ServerMessage, { t: 'stream' }>;
expect(stream.events).toEqual([expect.objectContaining({ type: 'progress', player: 'A', item: item.idx })]);
expect(b.msgs.filter((m) => m.t === 'state').length).toBe(states);
h.clock.advance(3000);
room.act('A', 2, { type: 'submit', item: item.idx, text: item.text });
expect(a.msgs.filter((m) => m.t === 'reject').map((m) => JSON.stringify(m))).toEqual([]);
expect(s().totals.A!.points).toBe(1);
expect(lastView(b).last).toMatchObject({ winner: 'A', text: item.text });
// The next item opens after the gap, from the server clock.
expect(lastView(b).upcoming).toEqual([]);
h.clock.advance(1500);
room.onTimer();
expect(lastView(b).upcoming[0]!.idx).toBe(1);
});
test('컴퓨터와 연습(타수 비교): 사람도 컴퓨터도 끝까지 치고, 거절 없이 끝나요', () => {
const h = harness();
const room = h.manager.createPractice('A', 'typing') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.configure('A', { options: { ...GAMES.typing!.defaultOptions, mode: 'speed', rounds: 1 } })).toBeNull();
expect(room.start('A')).toBeNull();
const bot = room.game!.players.find(isBotId)!;
expect(bot).toBeDefined();
let cs = 0;
for (let i = 0; i < 4 * 400 && !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();
// The person sends a line every 6 seconds, read from their own screen.
const v = lastView(a);
const me = v.seats.find((x) => x.id === 'A')!;
if (i % 24 === 23 && v.phase === 'playing' && !me.finished && v.upcoming[0]) room.act('A', ++cs, { type: 'submit', item: v.upcoming[0].idx, text: v.upcoming[0].text });
}
expect(room.game!.finished).toBe(true);
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
const s = room.game!.state as TypingState;
expect(s.totals.A!.keys).toBeGreaterThan(0);
expect(s.totals[bot]!.keys).toBeGreaterThan(0);
expect(lastView(a).result!.ranking.map((r) => r.id).sort()).toEqual(['A', bot].sort());
});
test('서바이벌 문장별(무제한은 자동 시간으로): 끊긴 사람을 기다리지 않고, 먼저 친 사람이 남아 이겨요', () => {
const { h, room, a, b, s } = twoPlayers({ mode: 'survival', elimination: 'sentence', timeLimit: null, rounds: 1 });
// 서바이벌 always has a clock (무제한 plays as 자동).
expect(s().curEndsAt).not.toBeNull();
room.disconnect(b);
const item = lastView(a).upcoming[0]!;
h.clock.advance(4000);
room.act('A', 1, { type: 'submit', item: item.idx, text: item.text });
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
expect(room.game!.finished).toBe(true);
expect(s().rs.B!.outReason).toBe('slowest');
expect(lastView(a).result!.ranking[0]!.id).toBe('A');
});
test('타수 비교 무제한: 끊긴 사람은 유예 뒤 친 데까지로 멈추고, 다음 타이머는 없어요', () => {
const { h, room, a, b, s } = twoPlayers({ mode: 'speed', timeLimit: null, rounds: 1 });
expect(room.effectiveDeadline()).toBeNull();
room.disconnect(b);
const d = room.effectiveDeadline()!;
expect(d).toBeGreaterThan(h.clock.now());
h.clock.advance(d - h.clock.now());
room.onTimer();
expect(s().rs.B!.finishedAt).not.toBeNull();
expect(room.effectiveDeadline()).toBeNull();
let cs = 0;
while (!room.game!.finished) {
const v = lastView(a);
h.clock.advance(5000);
room.act('A', ++cs, { type: 'submit', item: v.upcoming[0]!.idx, text: v.upcoming[0]!.text });
}
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
expect(lastView(a).result!.ranking[0]!.id).toBe('A');
});
});

View File

@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
const IDS = Object.keys(GAME_UI); const IDS = Object.keys(GAME_UI);
test('모든 게임에 도움말이 있어요', () => { test('모든 게임에 도움말이 있어요', () => {
expect(IDS).toHaveLength(40); expect(IDS).toHaveLength(46);
for (const id of IDS) { for (const id of IDS) {
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8'); const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
expect(src, id).toMatch(/\bquickStart,/); expect(src, id).toMatch(/\bquickStart,/);

View File

@@ -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 (
<g transform={`translate(${x} ${y})`} pointerEvents="none">
<path d="M12 7 V25" stroke="#111827" strokeWidth={2.2} strokeLinecap="round" />
<path d="M12 7 L24 11.5 L12 16 Z" fill="#dc2626" />
<path d="M8 25 H18" stroke="#111827" strokeWidth={2.4} strokeLinecap="round" />
{wrong && <path d="M5 5 L27 27 M27 5 L5 27" stroke="#111827" strokeWidth={2.6} strokeLinecap="round" />}
</g>
);
}
function Mine({ x, y }: { x: number; y: number }) {
return (
<g transform={`translate(${x} ${y})`} pointerEvents="none">
<path d="M16 6 V26 M6 16 H26 M9 9 L23 23 M23 9 L9 23" stroke="#111827" strokeWidth={2.2} strokeLinecap="round" />
<circle cx={16} cy={16} r={7.5} fill="#111827" />
<circle cx={13.5} cy={13.5} r={2} fill="#fff" opacity={0.8} />
</g>
);
}
/** Small stand-alone pictures for rules and help cards. */
export function MiniCell({ ch, size = 30 }: { ch: string; size?: number }) {
return (
<svg viewBox="0 0 32 32" width={size} height={size} aria-hidden style={{ verticalAlign: 'middle' }}>
<CellArt ch={ch} x={0} y={0} />
</svg>
);
}
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 (
<g className={cls} data-i={i} data-ch={i === undefined ? undefined : ch}>
{closed ? (
<>
<rect x={x + 0.5} y={y + 0.5} width={S - 1} height={S - 1} rx={4} fill="#e5e7eb" />
<path d={`M${x + 2} ${y + S - 3} V${y + 3} Q${x + 2} ${y + 2} ${x + 3} ${y + 2} H${x + S - 3}`} stroke="#fff" strokeWidth={2} fill="none" />
<path d={`M${x + 3} ${y + S - 2} H${x + S - 3} Q${x + S - 2} ${y + S - 2} ${x + S - 2} ${y + S - 3} V${y + 3}`} stroke="#9ca3af" strokeWidth={2} fill="none" />
</>
) : (
<rect x={x + 0.5} y={y + 0.5} width={S - 1} height={S - 1} rx={3} fill={ch === '!' ? '#ef4444' : '#f8fafc'} />
)}
{(ch === 'F' || ch === 'x') && <Flag x={x} y={y} wrong={ch === 'x'} />}
{(ch === '*' || ch === '!') && <Mine x={x} y={y} />}
{ch >= '1' && ch <= '8' && (
<text x={x + S / 2} y={y + 23} textAnchor="middle" fontSize={20} fontWeight={900} fill={NUM_COLOR[Number(ch)]} pointerEvents="none">
{ch}
</text>
)}
</g>
);
}

View File

@@ -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, PublicUser>): 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;
}

View File

@@ -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<MinesweeperView>) {
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<Set<number>>(new Set());
const [announce, setAnnounce] = useState('');
const svgRef = useRef<SVGSVGElement>(null);
const press = useRef<{ i: number; x: number; y: number; timer: ReturnType<typeof setTimeout> | null; long: boolean; button: number } | null>(null);
const prev = useRef<string | null>(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<number>();
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 (
<div className="rc">
<style>{RACE_CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed} />
<RaceSeats v={v} me={me} players={players} />
<div className="rc-wrap rc-wait">
<RaceCountdown countdown={countdown} text="숫자를 보고 지뢰를 피해 모든 칸을 열어요!" />
<RaceNotes v={v} mine={mine} failText={FAIL} />
</div>
</div>
);
}
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<SVGSVGElement>) => {
if (!playing) return;
const i = cellAt(e);
setCursor(i);
const p = { i, x: e.clientX, y: e.clientY, timer: null as ReturnType<typeof setTimeout> | 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<SVGSVGElement>) => {
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<SVGSVGElement>) => {
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<SVGSVGElement>) => {
const step: Record<string, Cell> = { 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 (
<div className="rc">
<style>{RACE_CSS + CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed}>
<span className="rc-pill" aria-label={`남은 지뢰 ${b.mines - b.flags}개`}>
💣 <b>{b.mines - b.flags}</b>
</span>
{mine && v.phase === 'playing' && (
<button type="button" className="rc-pill" aria-pressed={flagMode} onClick={() => setFlagMode((f) => !f)} aria-label="깃발 모드">
{flagMode ? '🚩 깃발 꽂기' : '⛏ 칸 열기'}
</button>
)}
</RaceTop>
<RaceSeats v={v} me={me} players={players} />
<div className="rc-wrap" style={wrapStyle}>
<svg
ref={svgRef}
className="ms-board"
data-off={!playing}
viewBox={`0 0 ${dC * S} ${dR * S}`}
role="application"
aria-roledescription="지뢰 판"
aria-label={playing ? `지뢰 판 ${dR}줄 ${dC}칸. 화살표로 옮기고 스페이스로 열기, F로 깃발. 지금 ${describe(cursor)}` : '지뢰 판'}
tabIndex={0}
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={() => {
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 <CellArt key={i} i={i} ch={ch} x={dc * S} y={dr * S} cls={ch === '!' ? 'ms-boom' : fresh.has(i) ? 'ms-new' : undefined} />;
})}
{focused && playing && <rect x={cc * S + 1.5} y={cr * S + 1.5} width={S - 3} height={S - 3} rx={5} fill="none" stroke="#f59e0b" strokeWidth={3} pointerEvents="none" />}
</svg>
<RaceNotes v={v} mine={mine} failText={FAIL} />
</div>
{mine && playing && (
<div className="rc-acts">
<GiveUp act={act} />
</div>
)}
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">왼쪽 클릭: 열기(숫자는 주변 한꺼번에) · 오른쪽 클릭: 깃발 · 키보드: 화살표 + 스페이스, F 깃발</p>}
{phone && mine && playing && <p className="rc-keys">누르기: {flagMode ? '깃발' : '열기'} · 길게 누르기: {flagMode ? '열기' : '깃발'} · 숫자를 누르면 주변을 한꺼번에 열어요</p>}
<p className="sr-only" aria-live="polite">
{announce}
</p>
</div>
);
}
const levelInfo = (l: Level) => `${LEVELS[l].name} ${LEVELS[l].rows}×${LEVELS[l].cols} · 지뢰 ${LEVELS[l].mines}`;
function MinesSide(props: BoardProps<MinesweeperView>) {
return <RaceSide v={props.view} me={props.me} players={props.players} title="지뢰찾기" info={levelInfo(props.view.options.level)} />;
}
function statusText(v: MinesweeperView, me: string | null, players: Record<string, PublicUser>): string {
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자를 보고 지뢰를 피해 칸을 열어요', playing: '숫자는 주변 8칸의 지뢰 수예요 · 지뢰 없는 칸을 모두 열어요', failed: FAIL });
}
function Options({ value: o, onChange }: OptionsProps<MinesweeperOptions>) {
return (
<div className="stack" style={{ gap: 16 }}>
<div className="stack" style={{ gap: 6 }}>
<strong>난이도</strong>
<Seg
label="난이도"
value={o.level}
options={(Object.keys(LEVELS) as Level[]).map((l) => [l, LEVELS[l].name])}
onChange={(level) => onChange({ ...o, level })}
/>
<span className="small muted">{levelInfo(o.level)}</span>
</div>
<TimeLimitOption value={o.timeLimitSec} choices={[180, 300, 600, 1200]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as MinesweeperOptions['timeLimitSec'] })} />
</div>
);
}
function optionsSummary(o: MinesweeperOptions): string {
return `${levelInfo(o.level)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
}
function Rules({ options }: { options?: MinesweeperOptions }) {
const level = options?.level ?? 'beginner';
return (
<div className="stack">
<p>
판 아래에 지뢰가 숨어 있어요. 지뢰가 없는 칸을 <strong>모두 열면</strong> 이겨요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요.
</p>
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
<MiniCell ch="1" />
<MiniCell ch="2" />
<MiniCell ch="3" />
<span>연 칸의 숫자 = 그 칸을 둘러싼 8칸에 있는 지뢰 수</span>
</div>
<p>
시작할 때 지뢰가 없는 한 곳이 모두에게 똑같이 열려 있어요. 숫자를 보고 지뢰가 확실한 칸에는 <MiniCell ch="F" size={22} /> 깃발을 꽂고, 안전한 칸을 열어요. 주변이 비어 있는 칸(0)을 열면 이어진 칸이
한꺼번에 열려요. 깃발 수가 숫자와 같아진 숫자 칸을 누르면 남은 주변 칸을 한꺼번에 열어요(깃발이 틀렸으면 지뢰가 터져요).
</p>
<p>
<strong>지뢰를 밟으면</strong> 그 판은 끝이에요. 여럿이면 가장 먼저 다 연 사람이 이기고, 아무도 못 열면 연 칸이 많은 사람이 이겨요(지뢰를 밟은 사람도 그때까지 연 칸으로 셈). 제한 시간은{' '}
{limitLabel(options ? options.timeLimitSec : 600)}이고, 지금 난이도는 {levelInfo(level)}이에요.
</p>
<p>PC: 왼쪽 클릭 열기, 오른쪽 클릭 깃발. 휴대폰: 누르면 열기, 길게 누르면 깃발(위의 [⛏ 칸 열기] 버튼으로 바꿀 수 있어요). 키보드: 화살표로 옮기고 스페이스로 열기, F로 깃발.</p>
</div>
);
}
const ui: GameUI<MinesweeperView, MinesweeperOptions> = {
Board: MinesBoard,
Side: MinesSide,
statusText,
liveStatus: true,
isMyTurn: raceIsMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;

View File

@@ -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 (
<svg viewBox={`0 0 ${rows[0]!.length * 32} ${rows.length * 32}`} width={rows[0]!.length * 30} height={rows.length * 30} aria-hidden>
{rows.flatMap((row, r) =>
[...row].map((ch, c) => (
<svg key={`${r}-${c}`} x={c * 32} y={r * 32} width={32} height={32} viewBox="0 0 32 32">
<MiniCell ch={ch} size={32} />
</svg>
)),
)}
</svg>
);
}
export const quickStart: QuickCard[] = [
{
pic: <Grid rows={['1##', '1#1', '110']} />,
alt: '닫힌 칸 사이에 숫자 1이 적힌 연 칸들이 있어요',
title: '숫자 = 주변 지뢰 수',
text: '연 칸의 숫자는 둘러싼 8칸에 있는 지뢰 수예요. 모두 똑같은 판을 각자 풀어요.',
},
{
pic: <Grid rows={['1F#', '1#1', '110']} />,
alt: '지뢰가 확실한 칸에 빨간 깃발을 꽂은 모습이에요',
title: '지뢰에는 깃발',
text: '지뢰가 확실한 칸에 깃발을 꽂아요(오른쪽 클릭, 휴대폰은 길게 누르기). 지뢰를 밟으면 끝이에요.',
},
{
pic: <Grid rows={['1F1', '111', '110']} />,
alt: '지뢰 칸만 남기고 모든 칸이 열렸어요',
title: '모든 칸을 열면 승리',
text: '지뢰 없는 칸을 모두 열면 다 푼 거예요. 여럿이면 가장 먼저 다 연 사람이 이겨요.',
},
];

View File

@@ -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 (
<svg viewBox={`0 0 ${w} ${h}`} width={(w * cell) / S} height={(h * cell) / S} aria-hidden style={{ maxWidth: '100%', height: 'auto' }}>
{cols.map((clue, c) =>
clue.map((x, j) => (
<text key={`c${c}-${j}`} x={left + c * S + S / 2} y={top - 4 - (clue.length - 1 - j) * 13} textAnchor="middle" fontSize={12} fontWeight={800} fill="var(--text)">
{x}
</text>
)),
)}
{rows.map((clue, r) =>
clue.map((x, j) => (
<text key={`r${r}-${j}`} x={left - 6 - (clue.length - 1 - j) * 12} y={top + r * S + 14.5} textAnchor="end" fontSize={12} fontWeight={800} fill="var(--text)">
{x}
</text>
)),
)}
{marks.flatMap((row, r) =>
[...row].map((ch, c) => {
const x = left + c * S;
const y = top + r * S;
return (
<g key={`${r}-${c}`}>
<rect x={x} y={y} width={S} height={S} fill={ch === '#' ? (color ?? 'var(--text)') : 'var(--surface)'} stroke="var(--border)" strokeWidth={1} />
{ch === 'x' && <path d={`M${x + 6} ${y + 6} L${x + S - 6} ${y + S - 6} M${x + S - 6} ${y + 6} L${x + 6} ${y + S - 6}`} stroke="var(--text-sub)" strokeWidth={1.8} strokeLinecap="round" />}
</g>
);
}),
)}
<rect x={left} y={top} width={n * S} height={n * S} fill="none" stroke="var(--text-sub)" strokeWidth={1.5} />
</svg>
);
}

View File

@@ -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, PublicUser>): 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;
}

View File

@@ -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<NonogramSize, string> = { 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<string, string> = { '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<NonogramView>) {
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<Drag | null>(null);
const [fresh, setFresh] = useState<Set<number>>(new Set());
const [announce, setAnnounce] = useState('');
const svgRef = useRef<SVGSVGElement>(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<number>();
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 (
<div className="rc">
<style>{RACE_CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed} />
<RaceSeats v={v} me={me} players={players} />
<div className="rc-wrap rc-wait">
<RaceCountdown countdown={countdown} text="숫자대로 칸을 칠해 그림을 완성해요!" />
<RaceNotes v={v} mine={mine} failText="" />
</div>
</div>
);
}
// 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<SVGSVGElement>) => {
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<SVGSVGElement>) => {
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<SVGSVGElement>) => {
const step: Record<string, [number, number]> = { 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<number, MarkValue>();
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 (
<div className="rc">
<style>{RACE_CSS + CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed}>
<span className="rc-pill" aria-label={`맞는 줄 ${okCount}개, 전체 ${2 * n}줄`}>
✔ <b>{okCount}/{2 * n}</b>
</span>
{mine && playing && (
<>
<button type="button" className="rc-pill" aria-pressed={mode === 1} onClick={() => setMode(1)}>
■ 채우기
</button>
<button type="button" className="rc-pill" aria-pressed={mode === 2} onClick={() => setMode(2)}>
✕ 표시
</button>
{v.options.hints && (
<button type="button" className="rc-pill" onClick={() => act({ type: 'hint' })} aria-label={`힌트 쓰기, 지금까지 ${b.hints}번`}>
💡 힌트{b.hints ? ` ${b.hints}` : ''}
</button>
)}
</>
)}
</RaceTop>
<RaceSeats v={v} me={me} players={players} />
{answer && (
<p className={`ng-title${solvedByMe ? '' : ' ans'}`} role="status">
{solvedByMe ? `다 풀었어요! ${answer.name}` : `정답 그림: ${answer.name}`}
</p>
)}
<div className="rc-wrap" style={wrapStyle}>
<svg
ref={svgRef}
className="ng-board"
data-off={!playing}
viewBox={`0 0 ${W} ${H}`}
role="application"
aria-roledescription="네모네모 로직 판"
aria-label={playing ? `네모네모 로직 ${n}×${n}. 화살표로 옮기고 스페이스로 칠하기, X로 ✕ 표시. 지금 ${describe(cursor)}` : '네모네모 로직 판'}
tabIndex={0}
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={() => setDrag(null)}
onKeyDown={onKey}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onContextMenu={(e) => e.preventDefault()}
>
<rect x={0} y={0} width={L} height={H} fill="var(--surface-2)" />
<rect x={L} y={0} width={n * S} height={T} fill="var(--surface-2)" />
{showCursor && (
<>
<rect x={0} y={T + cr * S} width={L} height={S} fill="var(--primary-soft)" />
<rect x={L + cc * S} y={0} width={S} height={T} fill="var(--primary-soft)" />
</>
)}
{colClues.map((clue, c) =>
clue.map((x, j) => (
<text key={`c${c}-${j}`} className="ng-clue" data-ok={okLines[n + c]} data-line={n + c} data-k={j} x={L + c * S + S / 2} y={T - 0.3 * S - (clue.length - 1 - j) * 0.72 * S} textAnchor="middle" fontSize={0.6 * S}>
{x}
</text>
)),
)}
{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 (
<text key={`r${r}-${j}`} className="ng-clue" data-ok={okLines[r]} data-line={r} data-k={clue.length - 1 - j} x={at} y={T + r * S + 0.71 * S} textAnchor="middle" fontSize={0.6 * S}>
{num}
</text>
);
});
})}
{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 (
<g key={i} data-i={i} data-m={ch} className={!answer && fresh.has(i) ? 'ng-new' : undefined}>
<rect
x={x}
y={y}
width={S}
height={S}
fill={fill(i)}
opacity={preview.has(i) ? 0.6 : 1}
className={colored ? 'ng-color' : undefined}
style={colored ? { animationDelay: `${fxMs(((i % n) + Math.floor(i / n)) * 18)}ms` } : undefined}
/>
{xMark(i) && <path d={`M${x + 5.5} ${y + 5.5} L${x + S - 5.5} ${y + S - 5.5} M${x + S - 5.5} ${y + 5.5} L${x + 5.5} ${y + S - 5.5}`} stroke="var(--text-sub)" strokeWidth={1.8} strokeLinecap="round" opacity={preview.has(i) ? 0.6 : 1} />}
</g>
);
})}
{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 (
<g key={`l${k}`} pointerEvents="none">
<line x1={L + k * S} y1={thick ? 0 : T} x2={L + k * S} y2={H} {...style} />
<line x1={thick ? 0 : L} y1={T + k * S} x2={W} y2={T + k * S} {...style} />
</g>
);
})}
{!answer && b.lastHint !== null && (
<rect key={`h${b.hints}`} className="ng-hint" x={L + (b.lastHint % n) * S + 1.5} y={T + Math.floor(b.lastHint / n) * S + 1.5} width={S - 3} height={S - 3} rx={3} fill="none" stroke="#f59e0b" strokeWidth={2} pointerEvents="none" />
)}
{showCursor && <rect x={L + cc * S + 1} y={T + cr * S + 1} width={S - 2} height={S - 2} rx={3} fill="none" stroke="var(--focus)" strokeWidth={2.4} pointerEvents="none" />}
</svg>
<RaceNotes v={v} mine={mine} failText="" />
</div>
{mine && playing && (
<div className="rc-acts">
<GiveUp act={act} />
</div>
)}
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">왼쪽 클릭·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 오른쪽 클릭·끌기: ✕ 표시 · 키보드: 화살표 + 스페이스 칠하기, X ✕ 표시</p>}
{phone && mine && playing && <p className="rc-keys">누르기·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 한 줄로 끌면 한 번에 · 칠한 칸을 다시 누르면 지워요</p>}
<p className="sr-only" aria-live="polite">
{announce}
</p>
</div>
);
}
function NonoSide(props: BoardProps<NonogramView>) {
return <RaceSide v={props.view} me={props.me} players={props.players} title="네모네모 로직" info={`${sizeInfo(props.view.options.size)} · 힌트 ${props.view.options.hints ? '켬' : '끔'}`} />;
}
function statusText(v: NonogramView, me: string | null, players: Record<string, PublicUser>): string {
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자대로 칸을 칠해 그림을 완성해요', playing: '줄마다 숫자 = 이어서 칠할 칸 수 · 모든 줄을 숫자와 맞게 칠해요', failed: '' });
}
function Options({ value: o, onChange }: OptionsProps<NonogramOptions>) {
return (
<div className="stack" style={{ gap: 16 }}>
<div className="stack" style={{ gap: 6 }}>
<strong>크기</strong>
<Seg label="크기" value={o.size} options={([5, 10, 15] as NonogramSize[]).map((s) => [s, sizeInfo(s)])} onChange={(size) => onChange({ ...o, size })} />
</div>
<div className="stack" style={{ gap: 6 }}>
<strong>힌트</strong>
<Seg label="힌트" value={o.hints} options={[[true, '켬'], [false, '끔']]} onChange={(hints) => onChange({ ...o, hints })} />
<span className="small muted">{o.hints ? '막히면 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'}</span>
</div>
<TimeLimitOption value={o.timeLimitSec} choices={[300, 600, 1200, 1800]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as NonogramOptions['timeLimitSec'] })} />
</div>
);
}
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 (
<div className="stack">
<p>
줄마다 적힌 숫자대로 칸을 칠하면 <strong>그림</strong>이 나와요. 모두 <strong>똑같은 그림</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요.
</p>
<div className="row" style={{ gap: 12, alignItems: 'center' }}>
<MiniNono answer={['.#.#.', '#####', '#####', '.###.', '..#..']} marks={['x#x#x', '#####', '.....', '.....', '.....']} cell={18} />
<span>숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"은 한 칸, 한 칸 이상 띄고, 또 한 칸이에요. 숫자 순서대로 놓여요.</span>
</div>
<p>
확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 두면 좋아요(✕는 답에 상관없어요). 칠한 칸이 맞는지는 알려 주지 않아요. 숫자와 맞게 칠해진 줄은 숫자가 흐려져요. 칠한 칸이 그림과
똑같아지면 다 푼 거예요.
</p>
<p>
여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 <strong>숫자와 맞는 줄</strong>이 많은 사람이 이겨요. 힌트를 켜면 막힐 때 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요(쓴 횟수는
결과에 나와요). 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1200)}이고, 지금 크기는 {sizeInfo(size)}이에요.
</p>
<p>PC: 왼쪽 클릭·끌기 칠하기, 오른쪽 클릭·끌기 ✕. 휴대폰: 누르거나 끌어서 칠하고, 위의 [✕ 표시]로 바꾸면 ✕를 해요. 칠한 칸을 다시 누르면 지워요. 키보드: 화살표, 스페이스 칠하기, X로 ✕.</p>
</div>
);
}
const ui: GameUI<NonogramView, NonogramOptions> = {
Board: NonoBoard,
Side: NonoSide,
statusText,
liveStatus: true,
isMyTurn: raceIsMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;

View File

@@ -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: <MiniNono answer={HEART} marks={['.....', '.....', '.....', '.....', '.....']} />,
alt: '5×5 빈 칸 위와 왼쪽에 줄마다 숫자가 적혀 있어요',
title: '숫자 = 칠할 칸 덩어리',
text: '줄 옆 숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"이면 한 칸, 띄고, 한 칸이에요.',
},
{
pic: <MiniNono answer={HEART} marks={['x#x#x', '#####', '#####', '.....', '.....']} />,
alt: '위 세 줄은 칠한 칸과 ✕ 표시로 채워져 있어요',
title: '칠하기와 ✕ 표시',
text: '확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 둬요. 끌면 한 줄을 한 번에 칠해요.',
},
{
pic: <MiniNono answer={HEART} color="#ef4444" />,
alt: '다 칠한 칸이 빨간 하트 그림이 됐어요',
title: '다 칠하면 그림이 나와요',
text: '모든 줄이 숫자와 맞으면 그림이 나와요. 모두 같은 그림이라 가장 먼저 푼 사람이 이겨요.',
},
];

View File

@@ -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<unknown, { timeLimitSec: number | null }>;
export { STATUS_WORD, limitLabel, mySeat, nick, raceHelp, raceIsMyTurn, raceStatusText } from './text';
import { STATUS_WORD, limitLabel, mySeat, nick } from './text';
const userOf = (players: Record<string, PublicUser>, 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 (
<div className="rc-top">
{left === null ? (
<span className="rc-pill" aria-label={elapsed === null ? '제한 시간 없음' : `걸린 시간 ${formatElapsed(elapsed)}`}>
⏱ {elapsed === null ? '무제한' : <b style={{ fontSize: '1rem' }}>{watch(elapsed)}</b>}
</span>
) : (
<span className={`rc-pill${v.phase === 'playing' && left <= 10_000 ? ' warn' : ''}`} role="timer" aria-label={`남은 시간 ${Math.floor(Math.ceil(left / 1000) / 60)}분 ${Math.ceil(left / 1000) % 60}초`}>
⏱ {clock(left)}
</span>
)}
{children}
</div>
);
}
/** Everyone's progress (live), ranked; only with more than one player. */
export function RaceSeats({ v, me, players }: { v: V; me: string | null; players: Record<string, PublicUser> }) {
if (v.seats.length < 2) return null;
return (
<ol className="rc-others" aria-label="진행 상황">
{rankSeats(v.seats).map((s) => (
<li
key={s.id}
data-me={s.id === me}
data-out={s.status === 'left'}
aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''}, ${s.status === 'solved' ? `다 풀었어요 ${formatElapsed(s.timeMs ?? 0)}` : s.progressText}${s.status !== 'playing' && s.status !== 'solved' ? `, ${STATUS_WORD[s.status]}` : ''}`}
>
<Avatar user={userOf(players, s.id)} size={20} />
<span>{s.id === me ? '나' : nick(players, s.id)}</span>
<b key={s.progress} className={s.progress ? 'anim-bump' : undefined}>
{s.status === 'solved' ? `✔ ${formatElapsed(s.timeMs ?? 0)}` : s.progressText.replace(/^[^\d]*/, '')}
</b>
{s.status !== 'playing' && s.status !== 'solved' && <span aria-hidden>· {STATUS_WORD[s.status]}</span>}
</li>
))}
</ol>
);
}
/** Countdown over the (still hidden) board. */
export function RaceCountdown({ countdown, text }: { countdown: number; text: string }) {
if (!countdown) return null;
return (
<div className="rc-over count" aria-hidden>
<b key={countdown}>{countdown}</b>
<small>{text}</small>
</div>
);
}
/** 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 (
<>
<AfterMotion when={!!mine && mine.status === 'solved' && playing}>
<div className="rc-over note win" role="status">
다 풀었어요! {formatElapsed(mine?.timeMs ?? 0)}
{mine?.extra}
{wait}
</div>
</AfterMotion>
<AfterMotion when={!!mine && mine.status === 'failed' && playing}>
<div className="rc-over note" role="status">
{failText} {mine?.progressText}
{wait}
</div>
</AfterMotion>
{mine?.status === 'done' && playing && (
<div className="rc-over note" role="status">
포기했어요. {mine.progressText}
{wait}
</div>
)}
{mine?.status === 'left' && v.phase !== 'ended' && <div className="rc-over note">게임에서 나갔어요.</div>}
{!mine && v.phase !== 'ended' && <div className="rc-over note">관전 중이에요 · 위에서 진행 상황을 볼 수 있어요</div>}
</>
);
}
/** 포기: 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 (
<button
type="button"
className={`btn ${ask ? 'btn-primary' : 'btn-secondary'}`}
onClick={() => {
if (!ask) return setAsk(true);
setAsk(false);
act({ type: 'stop' });
}}
>
{ask ? '한 번 더 누르면 포기해요' : '포기할래요'}
</button>
);
}
/** Right panel: the live ranking, then the final one. */
export function RaceSide({ v, me, players, title, info }: { v: V; me: string | null; players: Record<string, PublicUser>; title: string; info: string }) {
return (
<>
<style>{RACE_CSS}</style>
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<strong>
{title}
{v.phase === 'ended' ? ' · 게임 끝' : ''}
</strong>
<span className="small muted">
{info} · 제한 시간 {limitLabel(v.options.timeLimitSec)} · 모두 같은 판
</span>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
{rankSeats(v.seats).map((s) => (
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'left' ? 0.55 : 1 }}>
<span aria-hidden style={{ width: 28, fontWeight: 800 }}>
{s.rank}등
</span>
<Avatar user={userOf(players, s.id)} size={24} />
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }}>
{nick(players, s.id)}
{s.id === me ? ' (나)' : ''}
{STATUS_WORD[s.status] ? ` · ${STATUS_WORD[s.status]}` : ''}
</span>
<strong className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>
{s.status === 'solved' ? formatElapsed(s.timeMs ?? 0) : s.progressText}
</strong>
</li>
))}
</ol>
</div>
<AfterMotion when={!!v.result}>
{v.result && (
<div className="card stack" style={{ gap: 4, padding: 12 }}>
<strong>최종 순위</strong>
{v.result.ranking.map((r) => (
<span key={r.id}>
{r.rank}등 {nick(players, r.id)}
<span className="muted small"> · {r.text}</span>
</span>
))}
<span className="small muted">{v.result.summary}</span>
</div>
)}
</AfterMotion>
</>
);
}
/** Time limit choice for the room settings. */
export function TimeLimitOption({ value, choices, onChange }: { value: number | null; choices: number[]; onChange: (v: number | null) => void }) {
return (
<div className="stack" style={{ gap: 6 }}>
<strong>제한 시간</strong>
<Seg label="제한 시간" value={value} options={[...choices.map((c) => [c, limitLabel(c)] as [number, string]), [null, '무제한']]} onChange={onChange} />
<span className="small muted">
{value === null ? '시간 제한 없이 각자 다 풀거나 포기할 때까지 해요. 스톱워치로 걸린 시간을 재요.' : '시간이 끝나면 다 못 푼 사람은 푼 만큼으로 순위를 매겨요.'}
</span>
</div>
);
}
export function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
/** 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;
}

View File

@@ -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<unknown, { timeLimitSec: number | null }>;
export const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
export const limitLabel = (sec: number | null) => (sec === null ? '무제한' : sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
export const STATUS_WORD: Record<RaceSeat['status'], string> = { 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<string, PublicUser>, 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<string, PublicUser>, 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');
}

View File

@@ -26,6 +26,12 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
'cockroach-poker': () => import('./cockroach-poker'), 'cockroach-poker': () => import('./cockroach-poker'),
'ninety-nine': () => import('./ninety-nine'), 'ninety-nine': () => import('./ninety-nine'),
'connect-four': () => import('./connect-four'), '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'), 'old-maid': () => import('./old-maid'),
dobble: () => import('./dobble'), dobble: () => import('./dobble'),
catchmind: () => import('./catchmind'), catchmind: () => import('./catchmind'),

View File

@@ -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 (
<div aria-hidden style={{ position: 'relative', width: g.w, height: g.h, background: FELT, borderRadius: 8, flex: 'none' }}>
{rows.flatMap((row, r) =>
row.map((k, c) =>
k ? (
<div key={`${r}-${c}`} style={{ position: 'absolute', left: g.left(c), top: g.top(r), opacity: dim.includes(k) ? 0.35 : 1 }}>
<Tile code={k} w={tw} />
</div>
) : null,
),
)}
{path && (
<svg width={g.w} height={g.h} style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
<polyline points={path.map(([r, c]) => `${g.x(c)},${g.y(r)}`).join(' ')} fill="none" stroke={LINE} strokeWidth={3.5} strokeLinecap="round" strokeLinejoin="round" />
</svg>
)}
</div>
);
}

View File

@@ -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, PublicUser>): 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}`;
}

View File

@@ -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<ShisenView>) {
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
const phone = useNarrow();
const b = v.board;
const [sel, setSel] = useState<number | null>(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<Flash | null>(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<HTMLDivElement>(null);
const probeRef = useRef<HTMLDivElement>(null);
const boardRef = useRef<HTMLDivElement>(null);
const press = useRef<number | null>(null);
const seenShuffles = useRef<number | null>(null);
const seenHint = useRef<string | null>(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 (
<div className="rc">
<style>{RACE_CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed} />
<RaceSeats v={v} me={me} players={players} />
<div className="rc-wrap rc-wait">
<RaceCountdown countdown={countdown} text="같은 패 두 장을 두 번 이하로 꺾인 선으로 이어요!" />
<RaceNotes v={v} mine={mine} failText="" />
</div>
<div ref={fitRef} className="ss-fit">
<div className="ss-probe-box">
<div ref={probeRef} className="ss-probe" />
</div>
</div>
</div>
);
}
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<HTMLDivElement>) => {
if (!playing || (e.pointerType === 'mouse' && e.button !== 0)) return;
setKeyCursor(false);
press.current = cellAt(e);
};
const onUp = (e: ReactPointerEvent<HTMLDivElement>) => {
const p = press.current;
press.current = null;
if (p !== null && cellAt(e) === p) tap(p);
};
const onKey = (e: ReactKeyboardEvent<HTMLDivElement>) => {
const step: Record<string, Point> = { 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 (
<div className="rc">
<style>{RACE_CSS + CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed}>
<span className="rc-pill" aria-label={`남은 패 ${tilesLeft}장`}>
🀄 <b>{tilesLeft}</b>
</span>
</RaceTop>
<RaceSeats v={v} me={me} players={players} />
<div ref={fitRef} className="ss-fit">
<div className="ss-probe-box">
<div ref={probeRef} className="ss-probe" />
</div>
<div className="rc-wrap" style={{ width: g.w }}>
<div
ref={boardRef}
className="ss-board"
data-off={!playing}
data-rows={rows}
data-cols={cols}
style={{ width: g.w, height: g.h, ...msVar }}
role="application"
aria-roledescription="사천성 판"
aria-label={playing ? `사천성 판 ${dR}줄 ${dC}칸. 화살표로 옮기고 스페이스로 패 고르기. 지금 ${describe(cursor)}` : '사천성 판'}
tabIndex={0}
onPointerDown={onDown}
onPointerUp={onUp}
onPointerCancel={() => (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 (
<div key={i} className={cls} data-i={i} data-k={k} style={{ left: g.left(dc), top: g.top(dr) }}>
<Tile code={k} w={tw} />
</div>
);
})}
{keyCursor && playing && b.cells[cursor] == null && (
<div className="ss-cell cur" style={{ left: g.left(dispOf(cursor)[1]), top: g.top(dispOf(cursor)[0]), width: g.tw, height: g.th }} />
)}
{flash &&
[flash.a, flash.b].map((i) => {
const [dr, dc] = dispOf(i);
return (
<div key={`g${flash.key}-${i}`} className="ss-cell ss-gone" style={{ left: g.left(dc), top: g.top(dr) }}>
<Tile code={flash.kind} w={tw} />
</div>
);
})}
{flash && (
<svg key={flash.key} className="ss-line" width={g.w} height={g.h} aria-hidden>
<polyline
points={flash.pts.map(([r, c]) => 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"
/>
</svg>
)}
{toast && (
<div key={toast.key} className={`ss-toast${toast.bad ? ' bad' : ''}`} aria-hidden>
{toast.text}
</div>
)}
</div>
<RaceNotes v={v} mine={mine} failText="" />
</div>
</div>
{mine && playing && (
<div className="rc-acts">
{showHint && (
<button type="button" className="btn btn-secondary" disabled={!!b.hint} onClick={() => act({ type: 'hint' })}>
💡 힌트{b.hints ? ` (${b.hints}번 씀)` : ''}
</button>
)}
<GiveUp act={act} />
</div>
)}
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">같은 패 두 장을 차례로 클릭 · 고른 패를 다시 누르면 취소 · 키보드: 화살표 + 스페이스, Esc 취소</p>}
{phone && mine && playing && <p className="rc-keys">같은 패 두 장을 차례로 눌러요 · 고른 패를 다시 누르면 취소</p>}
<p className="sr-only" aria-live="polite">
{announce}
</p>
</div>
);
}
function ShisenSide(props: BoardProps<ShisenView>) {
const o = props.view.options;
return <RaceSide v={props.view} me={props.me} players={props.players} title="사천성" info={`${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'}`} />;
}
function statusText(v: ShisenView, me: string | null, players: Record<string, PublicUser>): string {
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 같은 패 두 장을 이어서 없애요', playing: '같은 패 두 장을 두 번 이하로 꺾인 선으로 이으면 없어져요', failed: '' });
}
function Options({ value: o, onChange }: OptionsProps<ShisenOptions>) {
return (
<div className="stack" style={{ gap: 16 }}>
<div className="stack" style={{ gap: 6 }}>
<strong>판 크기</strong>
<Seg label="판 크기" value={o.size} options={(Object.keys(SIZES) as Size[]).map((s) => [s, SIZES[s].name])} onChange={(size) => onChange({ ...o, size })} />
<span className="small muted">{sizeInfo(o.size)}</span>
</div>
<div className="stack" style={{ gap: 6 }}>
<strong>힌트</strong>
<Seg
label="힌트"
value={o.hints}
options={[
[true, '쓰기'],
[false, '안 쓰기'],
]}
onChange={(hints) => onChange({ ...o, hints })}
/>
<span className="small muted">{o.hints ? '[💡 힌트]를 누르면 이을 수 있는 쌍 하나를 보여 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'}</span>
</div>
<TimeLimitOption value={o.timeLimitSec} choices={[300, 600, 900, 1200]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as ShisenOptions['timeLimitSec'] })} />
</div>
);
}
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 (
<div className="stack">
<p>
마작패가 깔린 판에서 <strong>같은 그림의 패 두 장</strong>을 골라 없애요. 패를 모두 없애면 이겨요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수
있어요.
</p>
<div className="row" style={{ gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
<MiniBoard
rows={[
['7z', '1m', '7z'],
['2s', '4p', '9m'],
]}
path={[
[0, 0],
[-1, 0],
[-1, 2],
[0, 2],
]}
/>
<span>두 패를 잇는 선이 빈 칸으로만 지나고 두 번까지만 꺾이면 돼요. 판 바깥 테두리로 돌아가도 돼요.</span>
</div>
<p>
이을 수 있는 쌍이 하나도 없으면 남은 패가 같은 자리에서 저절로 섞여요(언제나 다 풀 수 있게). 판은 처음부터 끝까지 풀 수 있게 만들어져요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못
풀면 없앤 쌍이 많은 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 900)}이고, 지금 판은 {sizeInfo(size)}이에요.
</p>
<p>PC: 패를 차례로 클릭. 휴대폰: 패를 차례로 눌러요(넓은 판은 세로로 돌려 보여 줘요). 키보드: 화살표로 옮기고 스페이스로 골라요. 힌트를 쓰는 방이면 [💡 힌트]로 한 쌍을 볼 수 있어요.</p>
<p className="small muted">{MAHJONG_TILE_CREDIT}</p>
</div>
);
}
const ui: GameUI<ShisenView, ShisenOptions> = {
Board: ShisenBoard,
Side: ShisenSide,
statusText,
liveStatus: true,
isMyTurn: raceIsMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;

View File

@@ -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: (
<MiniBoard
rows={[
['3p', '', '3p'],
['1z', '5s', '2m'],
]}
path={[
[0, 0],
[0, 2],
]}
/>
),
alt: '같은 통수 3 두 장이 빈 칸을 지나는 곧은 선으로 이어져 있어요',
title: '같은 패 두 장을 이어요',
text: '같은 그림의 패 두 장을 차례로 누르면 없어져요. 모두 똑같은 판을 각자 풀어요.',
},
{
pic: (
<MiniBoard
rows={[
['7z', '1m', '7z'],
['2s', '4p', '9m'],
]}
path={[
[0, 0],
[-1, 0],
[-1, 2],
[0, 2],
]}
/>
),
alt: '가운데가 막힌 중 두 장이 판 바깥을 돌아 두 번 꺾인 선으로 이어져 있어요',
title: '두 번까지 꺾여도 돼요',
text: '빈 칸으로만 지나는 선이 두 번 이하로 꺾이면 이어져요. 판 바깥 테두리로 돌아가도 돼요.',
},
{
pic: (
<MiniBoard
rows={[
['', '5z', ''],
['', '', '5z'],
]}
path={[
[0, 1],
[1, 1],
[1, 2],
]}
/>
),
alt: '판에 백 두 장만 남아 한 번 꺾인 선으로 이어져 있어요',
title: '모두 없애면 승리',
text: '패를 모두 없애면 다 푼 거예요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 이을 쌍이 없으면 저절로 섞여요.',
},
];

View File

@@ -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<Mode, string[]> = {
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, PublicUser>): 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}개가 비어 있어요.`;
}

View File

@@ -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<string, string> {
const out = new Map<string, string>();
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<SolitaireView>) {
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
const phone = useNarrow();
const b = v.board;
const [sel, setSel] = useState<Sel | null>(null);
const [announce, setAnnounce] = useState('');
const [fresh, setFresh] = useState<Set<string>>(new Set());
const [shake, setShake] = useState(0);
const [box, setBox] = useState({ w: 0, h: 800 });
const wrapRef = useRef<HTMLDivElement>(null);
const lastTap = useRef<{ key: string; at: number } | null>(null);
const prev = useRef<SolitaireBoardView | null>(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<string>();
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 (
<div className="rc">
<style>{RACE_CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed} />
<RaceSeats v={v} me={me} players={players} />
<div className="rc-wrap rc-wait">
<RaceCountdown countdown={countdown} text={`${MODE_NAME[v.options.mode]} · 모두 같은 패예요!`} />
<RaceNotes v={v} mine={mine} failText={FAIL} />
</div>
</div>
);
}
// 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) => (
<button
key={`${pile}-${i}`}
type="button"
className={`sl-card${fresh.has(`${pile}:${i}`) ? ' sl-in' : ''}`}
style={{ ...style, zIndex: i + 1 }}
data-card={card}
aria-label={label}
aria-pressed={isSel(pile, i)}
tabIndex={playing ? 0 : -1}
onClick={() => tapCard(pile, i)}
onKeyDown={onCardKey(pile, i)}
>
<PlayingCard card={card} width={w} selected={isSel(pile, i)} highlight={i === tops(pile) && fits(pile)} />
</button>
);
const slot = (pile: string, text: string, label: string, onClick?: () => void) => (
<button
key={`${pile}-slot`}
type="button"
className="sl-slot"
style={{ width: w, height: h, fontSize: Math.max(11, w * 0.32) }}
data-hint={fits(pile)}
aria-label={label}
tabIndex={playing ? 0 : -1}
disabled={!playing}
onClick={onClick ?? (() => dropOn(pile))}
>
{text}
</button>
);
// 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 = (
<div className="sl-pile" data-pile="s" data-count={b.stock} style={{ gridColumn: 1 }}>
{b.stock > 0 || b.mode === 'spider' ? (
<button
type="button"
className="sl-stock"
disabled={!playing || b.stock === 0}
onClick={tapStock}
aria-label={b.mode === 'spider' ? (b.stock ? `카드 나누기, ${stockLeft}번 남음` : '나눌 카드가 없어요') : `더미에서 카드 넘기기, ${b.stock}장 남음`}
style={{ width: w, height: h }}
>
{b.stock > 0 ? (
Array.from({ length: Math.min(b.mode === 'spider' ? stockLeft : 3, 5) }, (_, k) => (
<span key={k} style={{ position: 'absolute', left: k * Math.max(2, w * 0.06), top: 0 }}>
<PlayingCard card={null} width={w} />
</span>
))
) : (
<span className="sl-slot" style={{ width: w, height: h, cursor: 'default' }} aria-hidden />
)}
{b.stock > 0 && <span className="sl-badge">{b.mode === 'spider' ? `${stockLeft}번` : b.stock}</span>}
</button>
) : (
slot('s', b.waste.length ? '↻' : '', b.waste.length ? '버린 카드를 다시 더미로 뒤집기' : '더미가 비었어요', tapStock)
)}
</div>
);
const fan = b.draw === 3 ? Math.round(w * 0.32) : 0;
const shownWaste = b.waste.slice(-(b.draw === 3 ? 3 : 2));
const waste = (
<div className="sl-pile" data-pile="w" style={{ gridColumn: 2, width: w, height: h }}>
{!b.waste.length && <span className="sl-slot" style={{ width: w, height: h, cursor: 'default' }} aria-hidden />}
{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)}. 두 번 누르면 파운데이션으로`)
) : (
<span key={`w-${i}`} className="sl-card" style={{ left: x, top: 0, zIndex: k }} aria-hidden>
<PlayingCard card={c} width={w} />
</span>
);
})}
</div>
);
const foundations = b.f.map((c, i) => (
<div key={`f${i}`} className="sl-pile" data-pile={`f${i}`} data-top={c} style={{ gridColumn: N - 3 + i, width: w, height: h }}>
{c ? cardButton(`f${i}`, 0, c, { top: 0 }, `파운데이션 ${i + 1}, 맨 위 ${cardAria(c)}`) : slot(`f${i}`, 'A', `파운데이션 ${i + 1}, 비었어요`)}
</div>
));
const cells = b.cells.map((c, i) => (
<div key={`c${i}`} className="sl-pile" data-pile={`c${i}`} style={{ gridColumn: 1 + i, width: w, height: h }}>
{c ? cardButton(`c${i}`, 0, c, { top: 0 }, `빈 칸 ${i + 1}의 ${cardAria(c)}`) : slot(`c${i}`, '', `빈 칸 ${i + 1}, 비었어요`)}
</div>
));
const done = Array.from({ length: 8 }, (_, i) => (
<div key={`d${i}`} className="sl-pile" style={{ gridColumn: 3 + i, width: w, height: h }} aria-hidden>
{b.done[i] ? <span className="sl-done-card"><PlayingCard card={`K${b.done[i]}`} width={w} /></span> : <span className="sl-slot" style={{ width: w, height: h, cursor: 'default', opacity: 0.6 }} />}
</div>
));
const columns = b.t.map((col, i) => {
const pile = `t${i}`;
const ys = offsets(col);
const height = (ys.at(-1) ?? 0) + h;
return (
<div key={pile} className="sl-pile" data-pile={pile} role="group" aria-label={`${i + 1}번째 줄, ${col.length}장`} style={{ width: w, height: height + Math.round(w * 0.25) }}>
{!col.length && slot(pile, b.mode === 'klondike' ? 'K' : '', `${i + 1}번째 줄, 비었어요${b.mode === 'klondike' ? '. K만 놓을 수 있어요' : ''}`)}
{col.map((c, k) =>
c === null ? (
<span key={`${pile}-${k}`} className="sl-card" style={{ top: ys[k], zIndex: k + 1 }} data-card="">
<PlayingCard card={null} width={w} title="뒤집힌 카드" />
</span>
) : (
cardButton(pile, k, c, { top: ys[k] }, `${i + 1}번째 줄 ${k + 1}번째 ${cardAria(c)}${k === col.length - 1 ? ', 맨 위' : ''}`)
),
)}
</div>
);
});
const autoOk = b.mode !== 'spider' && canAuto(b);
return (
<div className="rc">
<style>{RACE_CSS + CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed}>
<span className="rc-pill">{MODE_NAME[b.mode]}</span>
<span className="rc-pill" aria-label={b.mode === 'spider' ? `완성 ${b.done.length}/8줄` : `올린 카드 ${fTotal(b.f)}/52`}>
{b.mode === 'spider' ? '🂮' : '🂡'} <b>{b.mode === 'spider' ? `${b.done.length}/8` : `${fTotal(b.f)}/52`}</b>
</span>
{b.mode === 'freecell' && (
<span className="rc-pill" aria-label={`한 번에 ${freecellCapacity(b, false)}장까지 옮길 수 있어요`}>
⇅ <b>{freecellCapacity(b, false)}장</b>
</span>
)}
{b.undos > 0 && <span className="rc-pill" aria-label={`되돌리기 ${b.undos}번`}>↶ {b.undos}</span>}
</RaceTop>
<RaceSeats v={v} me={me} players={players} />
<div className="rc-wrap" style={{ width: '100%' }} ref={wrapRef}>
<div key={shake} className={`sl-felt${shake ? ' sl-shake' : ''}`} data-mode={b.mode} style={{ paddingBottom: pad }}>
<div className="sl-row" style={grid} role="group" aria-label={b.mode === 'freecell' ? '빈 칸과 파운데이션' : b.mode === 'spider' ? '더미와 완성한 줄' : '더미, 버린 카드, 파운데이션'}>
{b.mode === 'klondike' && [stock, waste, ...foundations]}
{b.mode === 'freecell' && [...cells, ...foundations]}
{b.mode === 'spider' && [stock, ...done]}
</div>
<div className="sl-row" style={{ ...grid, paddingTop: Math.max(8, Math.round(h * 0.18)) }}>
{columns}
</div>
</div>
<RaceNotes v={v} mine={mine} failText={FAIL} />
</div>
{mine && playing && (
<div className="rc-acts">
<button type="button" className="btn btn-secondary" disabled={!b.canUndo} onClick={() => send({ type: 'undo' })}>
↶ 되돌리기
</button>
{b.mode !== 'spider' && (
<button type="button" className="btn btn-secondary" disabled={!autoOk} onClick={() => send({ type: 'auto' })}>
자동 정리
</button>
)}
<GiveUp act={act} />
</div>
)}
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로 · 키보드: Tab으로 옮기고 Enter로 고르기·놓기, F 파운데이션, Esc 취소</p>}
{phone && mine && playing && <p className="rc-keys">카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로</p>}
<p className="sr-only" aria-live="polite">
{announce}
</p>
</div>
);
}
const modeInfo = (o: SolitaireOptions) =>
o.mode === 'klondike' ? `클론다이크 · ${o.draw}장씩 넘기기` : o.mode === 'spider' ? `스파이더 · 무늬 ${o.suits}가지` : '프리셀 · 빈 칸 4개';
function SolSide(props: BoardProps<SolitaireView>) {
return <RaceSide v={props.view} me={props.me} players={props.players} title="솔리테어" info={modeInfo(props.view.options)} />;
}
const PLAYING_LINE: Record<Mode, string> = {
klondike: '색을 번갈아 하나씩 작게 쌓고, A부터 무늬별로 파운데이션에 올려요',
freecell: '빈 칸 4개를 잘 써서 모든 카드를 A부터 무늬별로 올려요',
spider: '하나 작은 수 위에 쌓아 K부터 A까지 같은 무늬 한 줄을 만들어요',
};
function statusText(v: SolitaireView, me: string | null, players: Record<string, PublicUser>): 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<SolitaireOptions>) {
return (
<div className="stack" style={{ gap: 16 }}>
<div className="stack" style={{ gap: 6 }}>
<strong>종류</strong>
<Seg label="종류" value={o.mode} options={(Object.keys(MODE_NAME) as Mode[]).map((m) => [m, MODE_NAME[m]])} onChange={(mode) => onChange({ ...o, mode })} />
<span className="small muted">
{o.mode === 'klondike'
? '일곱 줄, 더미에서 카드를 넘겨 가며 풀어요.'
: o.mode === 'freecell'
? '모든 카드가 앞면으로 여덟 줄. 빈 칸 4개를 잠깐 쓸 수 있어요.'
: '카드 두 벌로 열 줄. K부터 A까지 같은 무늬 한 줄을 만들면 빠져요.'}
</span>
</div>
{o.mode === 'klondike' && (
<div className="stack" style={{ gap: 6 }}>
<strong>한 번에 넘기는 카드</strong>
<Seg label="한 번에 넘기는 카드" value={o.draw} options={[[1, '1장(쉬움)'], [3, '3장(어려움)']]} onChange={(draw) => onChange({ ...o, draw })} />
</div>
)}
{o.mode === 'spider' && (
<div className="stack" style={{ gap: 6 }}>
<strong>무늬 수</strong>
<Seg label="무늬 수" value={o.suits} options={[[1, '1가지(쉬움)'], [2, '2가지(보통)'], [4, '4가지(어려움)']]} onChange={(suits) => onChange({ ...o, suits })} />
</div>
)}
<TimeLimitOption value={o.timeLimitSec} choices={[...TIME_CHOICES]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as SolitaireOptions['timeLimitSec'] })} />
</div>
);
}
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 (
<div className="stack">
<p>
윈도우에 있던 그 카드놀이예요. 모두 <strong>똑같은 패</strong>를 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요. 지금은 {modeInfo(o)}, 제한 시간 {limitLabel(o.timeLimitSec)}이에요.
</p>
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
<PlayingCard card="8S" width={40} />
<PlayingCard card="7H" width={40} style={{ marginLeft: -22, marginTop: 14 }} />
<PlayingCard card="6C" width={40} style={{ marginLeft: -22, marginTop: 28 }} />
<span style={{ marginLeft: 8 }}>줄에는 색을 번갈아 하나씩 작은 수를 쌓아요(스파이더는 색 상관없이).</span>
</div>
<p>
<strong>클론다이크</strong>: 일곱 줄 가운데 맨 위만 앞면이에요. 아래 카드를 옮기면 뒤집힌 카드가 저절로 열려요. 빈 줄에는 K만 놓을 수 있어요. 더미를 누르면 카드를 1장(또는 3장)씩 넘기고,
더미가 비면 버린 카드를 다시 뒤집어 써요.
</p>
<p>
<strong>프리셀</strong>: 모든 카드가 앞면이에요. 빈 칸 4개에 카드를 한 장씩 잠깐 둘 수 있고, 빈 줄에는 아무 카드나 놓아요. 여러 장은 (빈 칸 수 + 1) × 2^(빈 줄 수)장까지 한 번에 옮겨요.
</p>
<p>
<strong>스파이더</strong>: 카드 두 벌로 열 줄이에요. 무늬와 상관없이 하나 작은 수를 쌓지만, 함께 옮길 수 있는 건 같은 무늬로 이어진 카드뿐이에요. K부터 A까지 같은 무늬 한 줄이 되면 저절로
빠져요. 더미를 누르면 열 줄에 한 장씩 나눠 주는데, 빈 줄이 있으면 나눌 수 없어요.
</p>
<p>
카드를 눌러 고르고(위에 얹힌 카드까지 함께) 놓을 곳을 눌러요. 두 번 누르면 파운데이션으로 올라가요. [자동 정리]는 올릴 수 있는 카드를 모두 올려요. [되돌리기]는 몇 번이든 쓸 수 있지만 결과에 횟수가
적혀요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 가장 많이 올린(스파이더는 많이 완성한) 사람이 이겨요. 클론다이크는 가끔 풀 수 없는 패도 나와요.
</p>
<p className="small muted">{PLAYING_CARD_CREDIT}</p>
</div>
);
}
const ui: GameUI<SolitaireView, SolitaireOptions> = {
Board: SolBoard,
Side: SolSide,
statusText,
liveStatus: true,
isMyTurn: raceIsMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;

View File

@@ -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 (
<span style={{ position: 'relative', display: 'inline-block', width: w, height: (ys.at(-1) ?? 0) + h }}>
{cards.map((c, i) => (
<span key={i} style={{ position: 'absolute', left: 0, top: ys[i] }}>
<PlayingCard card={c} width={w} />
</span>
))}
</span>
);
}
const row = { display: 'inline-flex', gap: 6, alignItems: 'flex-start' } as const;
export const quickStart: QuickCard[] = [
{
pic: (
<span style={row} aria-hidden>
<Fan cards={[null, null, 'KS', 'QH', 'JC']} />
<Fan cards={[null, '8D', '7S', '6H']} />
</span>
),
alt: '두 줄에 카드가 색을 번갈아 하나씩 작은 수로 쌓여 있어요',
title: '색을 번갈아 내려 쌓기',
text: '줄에는 색을 번갈아 하나씩 작은 수를 쌓아요. 모두 똑같은 패를 각자 풀어요.',
},
{
pic: (
<span style={row} aria-hidden>
<PlayingCard card="AH" width={34} />
<PlayingCard card="2H" width={34} />
<PlayingCard card="3H" width={34} />
</span>
),
alt: '하트 A, 2, 3이 차례로 놓여 있어요',
title: 'A부터 무늬별로 올리기',
text: '파운데이션에 A부터 같은 무늬로 차례대로 올려요. 두 번 누르면 바로 올라가요.',
},
{
pic: (
<span style={row} aria-hidden>
<Fan cards={[null, 'KS', 'QS', 'JS', 'TS']} w={30} />
<PlayingCard card="KS" width={30} />
<PlayingCard card="KS" width={30} />
</span>
),
alt: '스페이드가 K부터 차례로 이어진 줄과 완성한 줄이에요',
title: '세 가지 솔리테어',
text: '클론다이크·프리셀은 52장을 다 올리면, 스파이더는 K→A 같은 무늬 8줄을 빼면 다 풀어요.',
},
];

View File

@@ -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<number, string>; box?: boolean; size?: number }) {
const cols = rows[0]!.length;
const w = cols * U;
const h = rows.length * U;
return (
<svg viewBox={`-2 -2 ${w + 4} ${h + 4}`} width={cols * size} height={rows.length * size} aria-hidden style={{ verticalAlign: 'middle', maxWidth: '100%' }}>
{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 (
<g key={i}>
<rect x={x} y={y} width={U} height={U} fill={red ? '#fee2e2' : ch === '*' ? '#dbe7ff' : '#ffffff'} stroke="#cbd5e1" strokeWidth={1} />
{ch === '*' && <rect x={x + 2} y={y + 2} width={U - 4} height={U - 4} fill="none" stroke="#2563eb" strokeWidth={3} />}
{d && (
<text x={x + U / 2} y={y + 23} textAnchor="middle" fontSize={20} fontWeight={mine ? 600 : 900} fill={red ? '#dc2626' : mine ? '#2563eb' : '#111827'}>
{d}
</text>
)}
{!d &&
[...(notes[i] ?? '')].map((n) => {
const k = Number(n) - 1;
return (
<text key={n} x={x + 6 + (k % 3) * 10} y={y + 10 + Math.floor(k / 3) * 10} textAnchor="middle" fontSize={8.5} fontWeight={700} fill="#64748b">
{n}
</text>
);
})}
</g>
);
}),
)}
{box &&
Array.from({ length: Math.floor(cols / 3) + 1 }, (_, k) => <line key={`v${k}`} x1={k * 3 * U} y1={0} x2={k * 3 * U} y2={h} stroke="#111827" strokeWidth={2.5} />)}
{box &&
Array.from({ length: Math.floor(rows.length / 3) + 1 }, (_, k) => <line key={`h${k}`} x1={0} y1={k * 3 * U} x2={w} y2={k * 3 * U} stroke="#111827" strokeWidth={2.5} />)}
{!box && <rect x={0} y={0} width={w} height={h} fill="none" stroke="#111827" strokeWidth={2.5} />}
</svg>
);
}

View File

@@ -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<number> {
const out = new Set<number>();
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<string, number[]>();
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, PublicUser>): 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');
}

View File

@@ -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<SudokuView>) {
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<Set<number>>(new Set());
const [glow, setGlow] = useState<number | null>(null);
const [announce, setAnnounce] = useState('');
const gridRef = useRef<HTMLDivElement>(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<number>();
// 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<number>();
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<typeof setTimeout>[] = [];
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 (
<div className="rc">
<style>{RACE_CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed} />
<RaceSeats v={v} me={me} players={players} />
<div className="rc-wrap rc-wait">
<RaceCountdown countdown={countdown} text="가로·세로·상자에 1~9를 한 번씩!" />
<RaceNotes v={v} mine={mine} failText="" />
</div>
</div>
);
}
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<HTMLDivElement>) => {
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<HTMLDivElement>) => {
const step: Record<string, [number, number]> = { 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 (
<div className="rc">
<style>{RACE_CSS + CSS}</style>
<RaceTop v={v} left={left} elapsed={elapsed}>
{mine && (
<span className="rc-pill" aria-label={mine.progressText}>
✏️ <b>{mine.progressText.replace(/^[^\d]*/, '')}</b>
</span>
)}
{b.hints > 0 && (
<span className="rc-pill" aria-label={`힌트 ${b.hints}번`}>
💡 <b>{b.hints}</b>
</span>
)}
</RaceTop>
<RaceSeats v={v} me={me} players={players} />
<div className={`sd-main${phone ? ' phone' : ''}`} onKeyDown={onKey}>
<div className="rc-wrap" style={wrapStyle}>
<div
ref={gridRef}
className="sd-grid"
data-off={!playing}
role="application"
aria-roledescription="스도쿠 판"
aria-label={playing ? `스도쿠 판. 화살표로 옮기고 1~9로 넣기, Backspace로 지우기, N으로 메모. 지금 ${describe(sel)}` : '스도쿠 판'}
tabIndex={0}
onPointerDown={onDown}
onContextMenu={(e) => 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 (
<div key={i} className={cls.join(' ')} data-i={i} data-v={ch} data-r={r} data-c={c} data-given={given(i)} data-bad={bad.has(i)} aria-hidden>
{shown ? (
<span className="d">{shown}</span>
) : b.notes[i] ? (
<span className="sd-notes">
{DIGITS.map((n) => (
<span key={n} className={s !== '0' && String(n) === s ? 'on' : undefined}>
{b.notes[i]! & (1 << n) ? n : ''}
</span>
))}
</span>
) : null}
</div>
);
})}
</div>
<RaceNotes v={v} mine={mine} failText="" />
</div>
{showPad && (
<div className="sd-pad" role="group" aria-label="숫자 패드">
<div className="sd-digits">
{DIGITS.map((n, k) => {
const rest = 9 - counts[k]!;
return (
<button
key={n}
type="button"
className="sd-key"
data-n={n}
data-done={rest <= 0}
data-memo={memo}
disabled={!playing}
aria-label={`${memo ? '메모 ' : ''}${n}, ${Math.max(0, rest)}개 남음`}
onClick={() => enter(n)}
>
{n}
<small aria-hidden>{Math.max(0, rest)}</small>
</button>
);
})}
</div>
<div className="sd-tools">
<button type="button" className="sd-tool" disabled={!playing} onClick={erase}>
⌫ 지우기
</button>
<button type="button" className="sd-tool" aria-pressed={memo} onClick={toggleMemo}>
✏️ 메모 {memo ? '켬' : '끔'}
</button>
{v.options.hints && (
<button type="button" className="sd-tool" disabled={!playing} onClick={hint}>
💡 힌트
</button>
)}
</div>
</div>
)}
</div>
{mine && playing && (
<div className="rc-acts">
<GiveUp act={act} />
</div>
)}
{!phone && showPad && <p className="rc-keys">칸 클릭 또는 화살표로 고르고 1~9 넣기 · Backspace·Delete·0 지우기 · N·스페이스 메모 켜고 끄기 · 같은 숫자를 다시 누르면 지워요</p>}
{phone && showPad && <p className="rc-keys">칸을 누르고 아래 숫자를 눌러요 · 같은 숫자를 다시 누르면 지워요</p>}
{reveal && v.phase === 'ended' && <p className="rc-keys">초록 숫자 = 정답(빈칸이었거나 틀린 칸)</p>}
<p className="sr-only" aria-live="polite">
{announce}
</p>
</div>
);
}
const diffInfo = (d: Difficulty) => `${DIFFICULTIES[d].name} · ${DIFFICULTIES[d].givens}`;
function SudokuSide(props: BoardProps<SudokuView>) {
const o = props.view.options;
return <RaceSide v={props.view} me={props.me} players={props.players} title="스도쿠" info={`${diffInfo(o.difficulty)} · 힌트 ${o.hints ? '있음' : '없음'}`} />;
}
function statusText(v: SudokuView, me: string | null, players: Record<string, PublicUser>): string {
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 가로·세로·상자에 1~9를 한 번씩 넣어요', playing: '가로·세로·3×3 상자마다 1~9가 한 번씩 · 빈칸을 모두 맞게 채워요', failed: '' });
}
function Options({ value: o, onChange }: OptionsProps<SudokuOptions>) {
return (
<div className="stack" style={{ gap: 16 }}>
<div className="stack" style={{ gap: 6 }}>
<strong>난이도</strong>
<Seg
label="난이도"
value={o.difficulty}
options={(Object.keys(DIFFICULTIES) as Difficulty[]).map((d) => [d, DIFFICULTIES[d].name])}
onChange={(difficulty) => onChange({ ...o, difficulty })}
/>
<span className="small muted">
처음부터 있는 {DIFFICULTIES[o.difficulty].givens}
{o.difficulty === 'easy' ? ' · 차근차근 하나씩 찾으면 풀려요' : ''}
</span>
</div>
<div className="stack" style={{ gap: 6 }}>
<strong>힌트</strong>
<Seg
label="힌트"
value={o.hints}
options={[
[true, '있음'],
[false, '없음'],
]}
onChange={(hints) => onChange({ ...o, hints })}
/>
<span className="small muted">{o.hints ? '[💡 힌트]로 한 칸씩 맞는 숫자를 받을 수 있어요. 쓴 횟수는 결과에 남아요.' : '힌트 없이 풀어요.'}</span>
</div>
<TimeLimitOption value={o.timeLimitSec} choices={[600, 1200, 1800, 3600]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as SudokuOptions['timeLimitSec'] })} />
</div>
);
}
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 (
<div className="stack">
<p>
9×9 판의 <strong>가로줄·세로줄·굵은 선 3×3 상자</strong>마다 1부터 9까지가 <strong>한 번씩</strong> 들어가게 빈칸을 채워요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수
있어요. 답은 딱 하나뿐인 판만 나와요.
</p>
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
<MiniSudoku rows={['53.', '6*9', 'b87']} notes={{ 2: '14', 4: '14' }} size={26} />
<span>굵은 숫자는 처음부터 있던 것, 파란 숫자는 내가 넣은 것, 작은 숫자는 메모예요.</span>
</div>
<p>
칸을 고르고 숫자를 넣어요. 맞는지는 알려 주지 않지만(종이처럼), 같은 줄·칸·상자에 같은 숫자가 겹치면 빨갛게 보여요. [메모]를 켜면 후보 숫자를 작게 적어 둘 수 있고, 숫자를 넣으면 같은 줄·칸·상자의 그 숫자 메모는
저절로 지워져요. {options?.hints === false ? '이 방은 힌트가 없어요.' : '[💡 힌트]를 누르면 빈칸이나 틀린 칸 하나를 맞는 숫자로 채워 줘요(쓴 횟수는 결과에 남아요).'}
</p>
<p>
여럿이면 <strong>가장 먼저 다 맞게 채운 사람</strong>이 이기고, 아무도 못 풀면 많이 채운 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1800)}이고, 지금 난이도는 {diffInfo(d)}예요.
</p>
<p>PC: 칸을 클릭하거나 화살표로 고르고 1~9, Backspace로 지우기, N이나 스페이스로 메모. 휴대폰: 칸을 누르고 아래 숫자 버튼을 눌러요.</p>
</div>
);
}
const ui: GameUI<SudokuView, SudokuOptions> = {
Board: SudokuBoardView,
Side: SudokuSide,
statusText,
liveStatus: true,
isMyTurn: raceIsMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;

View File

@@ -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: <MiniSudoku rows={['53.', '6.9', '.87']} size={30} />,
alt: '굵은 선 3×3 상자 하나에 숫자 몇 개가 처음부터 들어 있어요',
title: '1~9를 한 번씩',
text: '가로줄·세로줄·3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채워요. 모두 똑같은 판을 각자 풀어요.',
},
{
pic: <MiniSudoku rows={['53.', '6*9', 'b87']} notes={{ 2: '14', 4: '14' }} size={30} />,
alt: '고른 칸이 파랗게 표시되고, 내가 넣은 숫자는 파란색, 빈칸에는 작은 메모가 있어요',
title: '칸을 고르고 숫자',
text: '칸을 누르고 아래 숫자를 눌러요. [메모]를 켜면 작은 후보 숫자로 적어 둘 수 있어요.',
},
{
pic: <MiniSudoku rows={['53.', '6i9', '.87']} bad={[4, 5]} size={30} />,
alt: '같은 줄에 9가 두 번 들어가 두 칸이 빨갛게 보여요',
title: '겹치면 빨강',
text: '같은 줄·상자에 같은 숫자가 겹치면 빨갛게 보여요. 다 맞게 채우면 끝! 여럿이면 가장 먼저 푼 사람이 이겨요.',
},
];

View File

@@ -0,0 +1,57 @@
import { expect, test } from 'bun:test';
import { setupGame, usersOf } from '../help-kit.test-util';
import { GAMES } from '@bg/games';
import { marks } from './marks';
import { helpNow } from './help';
const users = usersOf(['A', 'B', 'C']);
const def = GAMES.typing!;
const view = (s: unknown, who: string | null) => def.view(s, who) as any;
const tick = (s: any, now: number) => def.apply(s, 'A', { type: 'tick' }, { rng: { next: () => 0, int: () => 0, shuffle: (a: unknown[]) => [...a] } as any, now }).state as any;
test('타자 대결: 카운트다운 / 치는 중 / 관전 / 1등', () => {
const { state: s0, now } = setupGame('typing', 3);
expect(helpNow(view(s0, 'A'), 'A', users)).toContain('곧 시작해요');
const s = tick(s0, now + 3000);
const t = helpNow(view(s, 'A'), 'A', users);
expect(t).toContain('Enter');
expect(t).toContain('가장 먼저 정확하게');
expect(t).toContain('한/영');
expect(helpNow(view(s, null), null, users)).toContain('관전 중');
s.totals.B.points = 2;
expect(helpNow(view(s, 'A'), 'A', users)).toContain('지금 1등은 고양이님(2점)');
});
test('타자 대결: 서바이벌 목숨 / 탈락 / 끝', () => {
const { state: s0, now } = setupGame('typing', 3, { mode: 'survival', lives: 2 });
const s = tick(s0, now + 3000);
expect(helpNow(view(s, 'A'), 'A', users)).toContain('목숨은 2개');
s.rs.B.alive = false;
expect(helpNow(view(s, 'B'), 'B', users)).toContain('탈락했어요');
s.phase = 'ended';
s.final = { ranking: [], summary: '라운드 점수가 가장 높은 사람이 이겼어요' };
expect(helpNow(view(s, 'A'), 'A', users)).toContain('라운드 점수가 가장 높은');
});
test('글자 표시: 맞음·틀림·조합 중인 글자', () => {
expect(marks('강아지', '강').marks).toEqual(['ok', '', '']);
expect(marks('강아지', '가').marks).toEqual(['comp', '', '']);
// 도깨비불: "가나" 쪽으로 가는 "간"은 아직 조합 중이에요.
expect(marks('가나', '간').marks).toEqual(['comp', '']);
expect(marks('강아지', '강오').marks).toEqual(['ok', 'bad', '']);
expect(marks('강아지', '강앚').marks).toEqual(['ok', 'comp', '']);
expect(marks('강아지', '강오지').marks).toEqual(['ok', 'bad', 'ok']);
expect(marks('abc', 'abcd')).toEqual({ marks: ['ok', 'ok', 'ok'], extra: 1 });
});
test('타자 대결: 연습은 라운드·점수 없이 평균·최고 타수', () => {
const { state: s0, now } = setupGame('typing', 1, { mode: 'practice' });
const s = tick(s0, now + 3000);
const t = helpNow(view(s, 'A'), 'A', users);
expect(t).toContain('연습.');
expect(t).not.toContain('라운드');
expect(t).toContain('최고 0타');
s.phase = 'ended';
s.final = { ranking: [], summary: '연습 끝! 타수와 정확도를 확인해요' };
expect(helpNow(view(s, 'A'), 'A', users)).toContain('연습이 끝났어요');
});

View File

@@ -0,0 +1,51 @@
/** 타자 대결 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
import { ELIM_KO, MODE_KO, type TypingView } from '@bg/games/typing';
import type { PublicUser } from '@bg/shared/lite';
const HOW = '위에 나온 글을 입력 칸에 그대로 치고 Enter를 눌러요. 맞게 친 글자는 초록, 틀린 글자는 빨강으로 보여요. 붙여 넣기는 안 돼요.';
const MODE_LINE: Record<TypingView['options']['mode'], string> = {
first: '가장 먼저 정확하게 친 사람이 1점을 얻어요. 틀리면 빨간 글자를 고쳐서 다시 Enter를 눌러요.',
survival: '탈락 조건에 걸리지 않게 끝까지 버티면 라운드 1점이에요. 문제마다 제한 시간이 조금씩 줄어요.',
speed: '각자 한 줄씩 치고 Enter를 누르면 다음 줄이 나와요. 라운드 타수(1분에 친 타 수, 틀린 만큼은 빼요)가 가장 높은 사람이 1점이에요.',
accuracy: '각자 한 줄씩 치고 Enter를 누르면 다음 줄이 나와요. 정확도가 가장 높은 사람이 1점이에요(같으면 타수).',
timeAttack: '시간이 끝날 때까지 나오는 글을 계속 쳐요. 정확하게 친 타 수가 가장 많은 사람이 1점이에요.',
practice: '제한 시간과 점수 없이 한 줄씩 제 속도로 쳐요. 문장마다 첫 글자를 친 때부터 타수를 재요.',
};
function leader(v: TypingView, players: Record<string, PublicUser>, me: string | null): string {
const live = v.seats.filter((s) => !s.left);
if (live.length < 2) return '';
const best = Math.max(...live.map((s) => s.points));
if (best === 0) return '아직 아무도 점수가 없어요.';
const top = live.filter((s) => s.points === best).map((s) => (s.id === me ? '나' : `${players[s.id]?.nickname ?? '다른 사람'}님`));
return `지금 1등은 ${top.join(', ')}(${best}${v.options.mode === 'first' ? '점' : '승'})예요.`;
}
export function helpNow(v: TypingView, me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'ended')
return v.options.mode === 'practice'
? `연습이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n평균·최고 타수와 정확도를 확인하고, [한 판 더]로 한 번 더 연습할 수 있어요.'
: `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자의 점수, 평균 타수와 정확도를 볼 수 있어요.';
const mode = v.options.mode;
const surv = mode === 'survival' ? ` 탈락 조건은 "${ELIM_KO[v.options.elimination]}"${v.options.elimination === 'wrong' ? `, 목숨은 ${v.options.lives}개` : ''}예요.` : '';
const head = mode === 'practice' ? `${MODE_KO[mode]}.` : `${MODE_KO[mode]} · 라운드 ${v.round}/${v.options.rounds}.${surv}`;
const lead = leader(v, players, me);
if (v.phase === 'countdown') return `${head}\n곧 시작해요. ${HOW}\n${MODE_LINE[mode]}`;
if (v.phase === 'roundEnd') return `${head}\n라운드가 끝났어요. ${v.rounds.at(-1)?.summary ?? ''}. 잠시 뒤 다음 라운드가 시작해요.${lead ? `\n${lead}` : ''}`;
const mine = v.seats.find((s) => s.id === me) ?? null;
if (!mine) return `${head}\n관전 중이에요. 아래 막대로 각자 얼마나 쳤는지 볼 수 있어요.${lead ? `\n${lead}` : ''}`;
if (mine.left) return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
if (!mine.alive) return `${head}\n이번 라운드에서 탈락했어요. 다음 라운드에 다시 참가해요.${lead ? `\n${lead}` : ''}`;
const lines = [head];
if (v.flow === 'shared' && v.upcoming.length === 0) lines.push('다음 문제가 곧 나와요. 나오자마자 쳐요!');
else if (v.flow === 'shared' && mine.solved) lines.push('이번 문제를 쳤어요. 다른 사람이 끝내기를 기다려요.');
else if (v.flow === 'lane' && mine.finished) lines.push('이번 라운드를 다 쳤어요. 다른 사람이 끝내기를 기다려요.');
else lines.push(HOW);
lines.push(MODE_LINE[mode]);
lines.push(`${mode === 'practice' ? `지금까지: 평균 ${mine.roundKpm}타, 최고 ${mine.bestKpm}타` : `이번 라운드: ${mine.roundKpm}타`}, 정확도 ${mine.roundTried ? `${mine.roundAcc}%` : '아직 없음'}${mine.wrong ? `, 틀린 Enter ${mine.wrong}번` : ''}.`);
if (mode === 'survival' && v.options.elimination === 'wrong') lines.push(`남은 목숨 ${mine.lives}개.`);
if (lead) lines.push(lead);
lines.push(v.options.lang === 'ko' ? '영어가 쳐지면 한/영 키를 눌러 한글로 바꿔요.' : '한글이 쳐지면 한/영 키를 눌러 영어로 바꿔요.');
return lines.join('\n');
}

View File

@@ -0,0 +1,875 @@
/** 타자 대결 화면 (docs/games/typing.md §9). */
import { useEffect, useRef, useState, type FormEvent, type KeyboardEvent as ReactKeyboardEvent } from 'react';
import {
CATEGORY_KO,
ELIM_KO,
LANG_KO,
MODE_KO,
TOPIC_BY_ID,
correctKeys,
keyCount,
kpm,
normalize,
topicsFor,
type Category,
type Elim,
type Mode,
type RoundResult,
type SeatView,
type TypingOptions,
type TypingView,
} from '@bg/games/typing';
import type { PublicUser, ServerMessage } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { useServerNow } from '../../components/TurnTimer';
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
import { socket } from '../../net/socket';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
import { marks } from './marks';
import { AfterMotion } from '../../lib/motion';
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
const secs = (ms: number) => Math.max(0, Math.ceil(ms / 1000));
const clock = (ms: number) => {
const s = secs(ms);
return s >= 60 ? `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}` : `${s}초`;
};
/** Progress is sent at most this often while typing. */
const PROGRESS_MS = 300;
const tySound = {
key: () => tone(1800, 12, 'square', 0.025),
right: () => {
tone(880, 70, 'triangle', 0.13);
tone(1320, 110, 'triangle', 0.11, 60);
},
wrong: () => sounds.buzz(),
first: () => sfx.fanfare(),
out: () => [440, 330, 247].forEach((f, i) => tone(f, 160, 'sine', 0.13, i * 130)),
count: () => tone(660, 90, 'triangle', 0.12),
go: () => {
tone(988, 120, 'triangle', 0.14);
tone(1318, 200, 'triangle', 0.12, 90);
},
};
const OUT_KO: Record<string, string> = { lives: '목숨을 다 썼어요', slowest: '가장 늦게 쳤어요', least: '가장 적게 쳤어요', time: '시간 안에 못 쳤어요', left: '나갔어요' };
const CSS = `
.ty { width: 100%; max-width: 860px; margin: 0 auto; display: flex; flex-direction: column; gap: 10px; }
.ty-top { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; }
.ty-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; white-space: nowrap; }
.ty-pill.warn { background: var(--danger-soft); color: var(--danger); }
.ty-card { position: relative; background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 16px; display: flex; flex-direction: column; gap: 12px; min-height: 180px; }
.ty-topic { color: var(--text-sub); font-weight: 700; font-size: .9rem; text-align: center; }
.ty-target { font-size: clamp(1.25rem, 4.2vw, 1.9rem); font-weight: 800; line-height: 1.5; text-align: center; word-break: keep-all; overflow-wrap: anywhere; letter-spacing: .01em; }
.ty-target span { border-radius: 3px; }
.ty-target .ok { color: var(--success); }
.ty-target .bad { color: #fff; background: var(--danger); }
.ty-target .comp { color: var(--primary); text-decoration: underline; }
.ty-target .cur { box-shadow: inset 0 -3px 0 var(--primary); }
.ty-target .extra { color: #fff; background: var(--danger); margin-left: 2px; }
.ty-next { color: var(--text-sub); font-size: 1.05rem; font-weight: 600; text-align: center; opacity: .8; word-break: keep-all; }
.ty-passage { max-height: 210px; overflow: auto; border-radius: 10px; background: var(--surface-2); padding: 8px 12px; margin: 0; list-style: none; display: grid; gap: 2px; }
.ty-passage li { font-size: .98rem; line-height: 1.5; color: var(--text-sub); }
.ty-passage li[data-s='done'] { color: var(--success); }
.ty-passage li[data-s='cur'] { color: var(--text); font-weight: 800; }
.ty-form { display: flex; gap: 8px; }
.ty-input { flex: 1; min-width: 0; font-size: 1.25rem !important; padding: 12px 14px !important; border-radius: 12px; font-weight: 700; }
.ty-input[data-shake='true'] { animation: ty-shake .35s; border-color: var(--danger) !important; }
.ty-stats { display: flex; flex-wrap: wrap; gap: 4px 14px; justify-content: center; color: var(--text-sub); font-weight: 700; font-size: .92rem; font-variant-numeric: tabular-nums; }
.ty-warn { color: var(--danger); font-weight: 800; text-align: center; }
.ty-banner { text-align: center; font-weight: 900; font-size: 1.15rem; padding: 8px 12px; border-radius: 12px; background: var(--primary-soft); animation: ty-pop .35s ease-out; }
.ty-banner.bad { background: var(--danger-soft); color: var(--danger); }
.ty-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; border-radius: 16px;
background: rgba(0,0,0,.45); color: #fff; text-align: center; padding: 12px; z-index: 2; }
.ty-over b { font-size: 4.5rem; font-weight: 900; line-height: 1; text-shadow: 0 3px 8px rgba(0,0,0,.5); }
.ty-over small { font-size: 1.05rem; font-weight: 800; }
.ty-seats { list-style: none; margin: 0; padding: 0; display: grid; gap: 6px; }
.ty-seat { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; gap: 4px 8px; align-items: center; background: var(--surface); border-radius: 12px; padding: 6px 10px; box-shadow: var(--shadow); }
.ty-seat[data-me='true'] { outline: 2px solid var(--primary); }
.ty-seat[data-out='true'] { background: var(--surface-2); }
.ty-seat .nm { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 700; }
.ty-seat .sc { font-weight: 900; font-variant-numeric: tabular-nums; }
.ty-bar { grid-column: 1 / -1; height: 8px; border-radius: 99px; background: var(--surface-2); overflow: hidden; }
.ty-bar i { display: block; height: 100%; border-radius: 99px; background: var(--primary); transition: width .25s ease-out; }
.ty-bar i[data-s='done'] { background: var(--success); }
.ty-bar i[data-s='out'] { background: var(--border); }
.ty-hearts { color: var(--danger); letter-spacing: 1px; }
.ty-table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
.ty-table th, .ty-table td { padding: 4px 6px; text-align: left; border-bottom: 1px solid var(--border); font-size: .92rem; }
.ty-table td.n { text-align: right; }
@keyframes ty-shake { 0%,100% { transform: translateX(0); } 25% { transform: translateX(-6px); } 75% { transform: translateX(6px); } }
@keyframes ty-pop { from { transform: scale(.9); opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .ty-input[data-shake='true'], .ty-banner { animation: none; } .ty-bar i { transition: none; } }
`;
// ---------------------------------------------------------------- text marks
function Target({ text, typed }: { text: string; typed: string }) {
const { marks: m, extra } = marks(text, typed);
const at = Math.min([...typed.replace(/^\s+/, '')].length, m.length);
return (
<div className="ty-target" aria-hidden>
{[...text].map((ch, i) => (
<span key={i} className={`${m[i]}${i === at ? ' cur' : ''}`}>
{ch === ' ' && m[i] === 'bad' ? '␣' : ch}
</span>
))}
{extra > 0 && <span className="extra">+{extra}</span>}
</div>
);
}
/** Typed in the wrong keyboard language (한/영). */
const wrongLang = (lang: 'ko' | 'en', typed: string) => (lang === 'ko' ? /[a-zA-Z]{2,}/.test(typed) : /[ㄱ-ㅎㅏ-ㅣ가-힣]/.test(typed));
// ---------------------------------------------------------------- live progress (streamed)
type Live = Record<string, { round: number; item: number; n: number; of: number }>;
function useLiveProgress(round: number): Live {
const [live, setLive] = useState<Live>({});
useEffect(() => setLive({}), [round]);
useEffect(
() =>
socket.subscribe((m: ServerMessage) => {
if (m.t !== 'stream') return;
const evs = (m.events as { type?: string; player?: string; item?: number; n?: number; of?: number }[]).filter((e) => e.type === 'progress' && e.player);
if (!evs.length) return;
setLive((cur) => {
const next = { ...cur };
for (const e of evs) next[e.player!] = { round, item: e.item ?? 0, n: e.n ?? 0, of: e.of ?? 1 };
return next;
});
}),
[round],
);
return live;
}
/** A seat's progress on its current item, 0..1: the latest streamed value when it is about the same item. */
function progOf(s: SeatView, v: TypingView, live: Live): number {
if (v.flow === 'shared' ? s.solved : s.finished) return 1;
const l = live[s.id];
const idx = v.flow === 'shared' ? v.cur : s.idx;
if (l && l.round === v.round && l.item === idx) return Math.min(1, l.n / Math.max(1, l.of));
return s.prog;
}
/** Whole-round bar for lanes with a fixed number of items; the current item otherwise. */
function barOf(s: SeatView, v: TypingView, live: Live): number {
const p = progOf(s, v, live);
if (v.flow === 'lane' && v.total) return s.finished ? 1 : Math.min(1, (s.done + p) / v.total);
return p;
}
function Hearts({ n, max }: { n: number; max: number }) {
return (
<span className="ty-hearts" aria-label={`목숨 ${n}개`}>
{'♥'.repeat(Math.max(0, n))}
<span style={{ opacity: 0.25 }}>{'♥'.repeat(Math.max(0, max - n))}</span>
</span>
);
}
function Seats({ v, me, players, live }: { v: TypingView; me: string | null; players: Record<string, PublicUser>; live: Live }) {
const surv = v.options.mode === 'survival';
const lives = surv && v.options.elimination === 'wrong';
const unit = v.options.mode === 'first' ? '점' : '승';
const practice = v.options.mode === 'practice';
return (
<ul className="ty-seats" aria-label="참가자">
{v.seats.map((s) => {
const out = !s.alive && v.phase === 'playing';
const bar = barOf(s, v, live);
const state = out ? 'out' : (v.flow === 'shared' ? s.solved : s.finished) ? 'done' : '';
const tag = s.left ? '나감' : out ? `탈락 · ${OUT_KO[s.outReason ?? ''] ?? ''}` : v.flow === 'shared' && s.solved ? '✓ 쳤어요' : s.finished && v.phase === 'playing' ? '✓ 다 쳤어요' : '';
return (
<li key={s.id} className="ty-seat" data-me={s.id === me} data-out={out || s.left}>
<Avatar user={userOf(players, s.id)} size={24} />
<span className="nm">
{nick(players, s.id)}
{s.id === me ? ' (나)' : ''}
{tag && <span className="small muted"> · {tag}</span>}
</span>
<span className="sc">
{lives && s.alive && <Hearts n={s.lives} max={v.options.lives} />} {practice ? `${s.roundKpm}타` : `${s.points}${unit}`}
</span>
<span className="ty-bar" role="progressbar" aria-label={`${nick(players, s.id)} 진행`} aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(bar * 100)}>
<i data-s={state} style={{ width: `${Math.round(bar * 100)}%` }} />
</span>
</li>
);
})}
</ul>
);
}
function RoundTable({ r, players, mode }: { r: RoundResult; players: Record<string, PublicUser>; mode: Mode }) {
return (
<table className="ty-table">
<thead>
<tr>
<th>순위</th>
<th>이름</th>
<th className="n">{mode === 'first' ? '먼저 친 문제' : mode === 'survival' ? '친 문제' : '친 줄'}</th>
<th className="n">타수</th>
<th className="n">정확도</th>
</tr>
</thead>
<tbody>
{r.rows.map((row) => (
<tr key={row.id}>
<td>
{row.rank}등{r.winners.includes(row.id) ? ' 🏆' : ''}
</td>
<td>
{nick(players, row.id)}
{row.out && row.out !== 'left' ? <span className="small muted"> · 탈락</span> : row.out === 'left' ? <span className="small muted"> · 나감</span> : null}
</td>
<td className="n">{row.done}</td>
<td className="n">{row.kpm}타</td>
<td className="n">{row.acc}%</td>
</tr>
))}
</tbody>
</table>
);
}
// ---------------------------------------------------------------- board
function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
const now = useServerNow(200);
const live = useLiveProgress(v.round);
const mine = v.seats.find((s) => s.id === me) ?? null;
const shared = v.flow === 'shared';
const [typed, setTyped] = useState('');
const [shake, setShake] = useState(false);
const [note, setNote] = useState<{ key: number; text: string; bad: boolean } | null>(null);
// Lanes: the line I have sent but the server has not confirmed yet (so the next line shows at once).
const [sent, setSent] = useState<{ round: number; idx: number } | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const composing = useRef(false);
const enterAfterCompose = useRef(false);
const lastSubmit = useRef(0);
const lastProgress = useRef({ at: 0, text: '' });
const seq = useRef(0);
const passageRef = useRef<HTMLOListElement>(null);
const serverIdx = mine ? (shared ? v.cur : mine.idx) : 0;
const myIdx = !shared && sent && sent.round === v.round && sent.idx >= serverIdx ? sent.idx + 1 : serverIdx;
const item = v.upcoming.find((u) => u.idx === myIdx) ?? null;
const following = shared ? [] : v.upcoming.filter((u) => u.idx > myIdx).slice(0, 2);
const laneDone = !shared && v.total !== null && myIdx >= v.total;
const canType = !!mine && mine.alive && !mine.left && v.phase === 'playing' && !!item && !(shared && mine.solved) && !(!shared && (mine.finished || laneDone));
const itemKey = `${v.round}:${myIdx}`;
const practice = v.options.mode === 'practice';
// When the current item's clock started (연습: at its first key, 0 = not yet).
const startedAt = useRef<{ key: string; at: number }>({ key: '', at: 0 });
if (startedAt.current.key !== itemKey && item) startedAt.current = { key: itemKey, at: practice ? 0 : shared ? Math.max(v.curAt, now) : now };
// A new item: empty box, focus on it.
useEffect(() => {
setTyped('');
lastProgress.current = { at: 0, text: '' };
if (canType) inputRef.current?.focus({ preventScroll: true });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [itemKey, canType]);
useEffect(() => setSent(null), [v.round]);
// Long texts: keep the line I am on in the middle of the passage box.
useEffect(() => {
const ol = passageRef.current;
const li = ol?.querySelector<HTMLElement>('li[data-s="cur"]');
if (ol && li) ol.scrollTop = Math.max(0, li.offsetTop - ol.offsetTop - ol.clientHeight / 2 + li.clientHeight / 2);
}, [myIdx, v.passage]);
// A refused line (too fast, time over): back to what the server has.
useEffect(() => socket.subscribe((m) => m.t === 'reject' && setSent(null)), []);
useEffect(() => {
if (!shake) return;
const t = setTimeout(() => setShake(false), 400);
return () => clearTimeout(t);
}, [shake]);
useEffect(() => {
if (!note) return;
const t = setTimeout(() => setNote(null), 1600);
return () => clearTimeout(t);
}, [note]);
// What happened: first typist, wrong answers, people knocked out, my lines.
const lastKey = v.last ? `${v.round}:${v.cur}:${v.last.winner}:${v.last.out.join(',')}` : '';
const heardLast = useRef(lastKey);
useEffect(() => {
if (!v.last || heardLast.current === lastKey) return;
heardLast.current = lastKey;
if (v.last.winner === me) tySound.first();
else if (me && v.last.out.includes(me)) tySound.out();
else if (v.last.winner) tySound.wrong();
}, [lastKey, v.last, me]);
const sendProgress = (text: string, force = false) => {
if (!item) return;
const t = Date.now();
if (!force && t - lastProgress.current.at < PROGRESS_MS) return;
if (text === lastProgress.current.text) return;
lastProgress.current = { at: t, text };
act({ type: 'progress', item: item.idx, text: text.slice(0, 400) });
};
// Throttled progress also goes out when typing pauses.
useEffect(() => {
if (!canType || !typed) return;
const t = setTimeout(() => sendProgress(typed, true), PROGRESS_MS);
return () => clearTimeout(t);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [typed, canType]);
const submit = (raw: string) => {
if (!canType || !item) return;
const t = Date.now();
if (t - lastSubmit.current < 150) return; // Enter that the IME reported twice
const text = raw.slice(0, 400);
if (!normalize(text)) return;
lastSubmit.current = t;
const right = normalize(text) === normalize(item.text);
act({ type: 'submit', item: item.idx, text });
if (shared) {
if (right) {
tySound.right();
haptic(15);
setTyped('');
} else {
tySound.wrong();
haptic([40, 30, 40]);
setShake(true);
++seq.current;
const surv = v.options.mode === 'survival' && v.options.elimination === 'wrong';
setNote({ key: seq.current, text: surv ? '틀렸어요! 목숨 하나를 잃었어요' : '틀린 곳이 있어요. 빨간 글자를 고쳐요', bad: true });
}
return;
}
// Lane: the line goes in as typed; the next one shows right away.
if (right) tySound.right();
else tySound.wrong();
setSent({ round: v.round, idx: item.idx });
setTyped('');
};
const onKeyDown = (e: ReactKeyboardEvent<HTMLInputElement>) => {
if (e.key !== 'Enter') return;
e.preventDefault();
// Enter while a syllable is being composed: the IME finishes it first, then the line goes.
if (e.nativeEvent.isComposing || composing.current || e.keyCode === 229) {
enterAfterCompose.current = true;
return;
}
submit(e.currentTarget.value);
};
const onSubmitForm = (e: FormEvent) => {
e.preventDefault();
if (!composing.current) submit(inputRef.current?.value ?? typed);
};
// Clocks.
const countdown = v.phase === 'countdown' && v.phaseEndsAt ? Math.max(1, Math.ceil((v.phaseEndsAt - now) / 1000)) : 0;
const gap = shared && v.phase === 'playing' && !item && now < v.curAt;
const clockEnd = v.phase !== 'playing' ? null : shared ? (item ? v.curEndsAt : null) : v.options.mode === 'survival' ? v.nextCutAt : v.roundEndsAt;
const left = clockEnd === null ? null : clockEnd - now;
const heard = useRef({ countdown: 0, warn: 0 });
const warnSec = left !== null && left > 0 && left <= 5000 ? secs(left) : 0;
useEffect(() => {
const was = heard.current;
if (countdown !== was.countdown) {
if (countdown > 0) tySound.count();
else if (was.countdown > 0) tySound.go();
}
if (warnSec && warnSec !== was.warn && canType) sfx.tick();
heard.current = { countdown, warn: warnSec };
});
const ck = item ? correctKeys(item.text, typed) : 0;
const elapsed = item && startedAt.current.at ? Math.max(0, now - startedAt.current.at) : 0;
const curKpm = typed && elapsed > 500 ? kpm(ck, elapsed) : 0;
const langWarn = typed.length >= 2 && wrongLang(v.options.lang, typed);
const surv = v.options.mode === 'survival';
const roundLabel = practice ? null : `라운드 ${v.round}/${v.options.rounds}`;
// 연습: how long I have been at it (like 한컴 타자연습's 경과 시간).
const spent = practice && v.phase === 'playing' && mine && !mine.finished && !laneDone ? Math.max(0, now - v.roundStartedAt) : null;
const progressPct = v.total ? Math.round((Math.min(myIdx, v.total) / v.total) * 100) : 0;
const itemLabel = shared ? (v.total ? `${Math.min(v.cur + 1, v.total)}/${v.total}번째` : `${v.cur + 1}번째`) : v.total ? `${Math.min(myIdx + 1, v.total)}/${v.total}줄` : `${myIdx + 1}번째 줄`;
const lastRound = v.rounds.at(-1);
const alive = v.seats.filter((s) => s.alive).length;
let banner: { text: string; bad: boolean } | null = null;
if (v.phase === 'playing' && shared && !item && v.last) {
const w = v.last.winner;
const outs = v.last.out.map((p) => (p === me ? '나' : `${nick(players, p)}님`));
if (w) banner = { text: `${w === me ? '내가' : `${nick(players, w)}님이`} 먼저 쳤어요! ${v.last.kpm}타`, bad: false };
else if (outs.length) banner = { text: `${outs.join(', ')} 탈락!`, bad: true };
else banner = { text: v.options.mode === 'first' ? '시간 끝! 아무도 못 쳤어요' : '다음 문제!', bad: v.options.mode === 'first' };
}
return (
<div className="ty">
<style>{CSS}</style>
<div className="ty-top">
{roundLabel && <span className="ty-pill">{roundLabel}</span>}
<span className="ty-pill">{MODE_KO[v.options.mode]}</span>
{v.phase === 'playing' && <span className="ty-pill">{itemLabel}</span>}
{surv && v.phase === 'playing' && <span className="ty-pill">남은 사람 {alive}명</span>}
{left !== null && (
<span className={`ty-pill ${left <= 5000 ? 'warn' : ''}`} aria-label={`남은 시간 ${secs(left)}초`}>
⏱ {surv && !shared ? `탈락까지 ${clock(left)}` : clock(left)}
</span>
)}
{spent !== null && (
<span className="ty-pill" aria-label={`걸린 시간 ${clock(spent)}`}>
⏱ {clock(spent)}
</span>
)}
</div>
<div className="ty-card">
{v.passage && (
<div className="stack" style={{ gap: 4 }}>
<div className="ty-topic">
{v.passageTitle}
{v.passageBy ? ` · ${v.passageBy}` : ''}
</div>
<ol className="ty-passage" aria-label="긴글 전체" ref={passageRef}>
{v.passage.map((l, i) => (
<li key={i} data-s={i < myIdx ? 'done' : i === myIdx ? 'cur' : ''}>
{l}
</li>
))}
</ol>
</div>
)}
{item && !v.passage && <div className="ty-topic">{TOPIC_BY_ID[item.topic]?.name ?? ''}</div>}
{item ? (
<>
<p className="sr-only">칠 글: {item.text}</p>
<Target text={item.text} typed={canType ? typed : ''} />
</>
) : (
<div className="ty-target" style={{ color: 'var(--text-sub)', fontSize: '1.15rem' }}>
{v.phase === 'ended'
? practice
? '연습 끝!'
: '게임 끝!'
: v.phase === 'countdown'
? '곧 시작해요!'
: gap
? '다음 문제가 곧 나와요…'
: v.phase === 'roundEnd'
? '라운드 끝!'
: !mine
? '관전 중이에요 · 아래에서 진행을 볼 수 있어요'
: mine.left
? '게임에서 나갔어요'
: !mine.alive
? '탈락했어요. 다음 라운드를 기다려요'
: laneDone || mine.finished
? '다 쳤어요! 다른 사람을 기다려요'
: ''}
</div>
)}
{following.map((u) => (
<div key={u.idx} className="ty-next" aria-hidden>
{u.text}
</div>
))}
{banner && (
<div key={lastKey} className={`ty-banner ${banner.bad ? 'bad' : ''}`} role="status">
{banner.text}
</div>
)}
{mine && !mine.left && v.phase !== 'ended' && (
<form className="ty-form" onSubmit={onSubmitForm} autoComplete="off">
<input
ref={inputRef}
className="input ty-input"
data-shake={shake}
value={typed}
disabled={!canType}
lang={v.options.lang === 'ko' ? 'ko' : 'en'}
inputMode="text"
enterKeyHint="send"
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck={false}
maxLength={400}
aria-label={item ? `여기에 쳐요: ${item.text}` : '입력 칸'}
placeholder={canType ? '위의 글을 그대로 치고 Enter' : ''}
onChange={(e) => {
const t = e.target.value;
if (t.length > typed.length && !composing.current) tySound.key();
if (practice && !startedAt.current.at && normalize(t)) startedAt.current.at = socket.now();
setTyped(t);
sendProgress(t);
}}
onCompositionStart={() => {
composing.current = true;
}}
onCompositionEnd={(e) => {
composing.current = false;
const el = e.currentTarget;
if (enterAfterCompose.current) {
enterAfterCompose.current = false;
setTimeout(() => submit(el.value), 0);
}
}}
onKeyDown={onKeyDown}
onPaste={(e) => e.preventDefault()}
onDrop={(e) => e.preventDefault()}
/>
<button type="submit" className="btn btn-primary" disabled={!canType} onPointerDown={(e) => e.preventDefault()} onMouseDown={(e) => e.preventDefault()}>
입력
</button>
</form>
)}
{langWarn && <div className="ty-warn">{v.options.lang === 'ko' ? '한/영 키를 눌러 한글로 바꿔 주세요' : 'Press the 한/영 key to type in English (영어로 바꿔 주세요)'}</div>}
{note && (
<div key={note.key} className={`ty-banner ${note.bad ? 'bad' : ''}`} role="alert">
{note.text}
</div>
)}
{mine && v.phase === 'playing' && practice && (
<div className="ty-stats">
<span>지금 {curKpm}타</span>
<span>평균 {mine.roundKpm}타</span>
<span>최고 {mine.bestKpm}타</span>
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
<span>진행 {progressPct}%</span>
</div>
)}
{mine && v.phase === 'ended' && practice && (
<div className="ty-stats" role="status" style={{ fontSize: '1.05rem' }}>
<span>평균 {mine.roundKpm}타</span>
<span>최고 {mine.bestKpm}타</span>
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
<span>
{mine.done}줄 중 틀린 줄 {mine.wrong}개
</span>
</div>
)}
{mine && v.phase === 'playing' && !practice && (
<div className="ty-stats">
<span>지금 {curKpm}타</span>
<span>이번 라운드 {mine.roundKpm}타</span>
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
{mine.wrong > 0 && <span>틀림 {mine.wrong}번</span>}
{item && <span>{keyCount(item.text)}타짜리</span>}
</div>
)}
{countdown > 0 && (
<div className="ty-over" aria-hidden>
<b key={countdown}>{countdown}</b>
<small>
{v.round > 1 && !practice ? `라운드 ${v.round} · ` : ''}
{CATEGORY_KO[v.options.category]} · {MODE_KO[v.options.mode]}
</small>
</div>
)}
</div>
{v.phase === 'roundEnd' && lastRound && (
<div className="card stack" style={{ gap: 6, padding: 12 }} role="status">
<strong>
라운드 {lastRound.round} 결과 · {lastRound.summary}
</strong>
<RoundTable r={lastRound} players={players} mode={v.options.mode} />
{v.phaseEndsAt && <span className="small muted">{secs(v.phaseEndsAt - now)}초 뒤 다음 라운드</span>}
</div>
)}
<Seats v={v} me={me} players={players} live={live} />
</div>
);
}
// ---------------------------------------------------------------- side
function TypingSide({ view: v, players }: BoardProps<TypingView>) {
const rows = [...v.seats].sort((a, b) => Number(a.left) - Number(b.left) || b.points - a.points || b.kpm - a.kpm);
const unit = v.options.mode === 'first' ? '점' : '승';
const practice = v.options.mode === 'practice';
return (
<>
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<strong>타자 대결{v.phase === 'ended' ? ' · 게임 끝' : ''}</strong>
<span className="small muted">{optionsSummary(v.options)}</span>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
{rows.map((s, i) => (
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.left ? 0.6 : 1 }}>
<span style={{ width: 22, fontWeight: 800 }}>{i + 1}</span>
<Avatar user={userOf(players, s.id)} size={22} />
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 600 }}>
{nick(players, s.id)}
{s.left ? ' · 나감' : ''}
</span>
<span className="small muted" style={{ fontVariantNumeric: 'tabular-nums' }}>
{s.kpm}타 · {s.tried ? `${s.acc}%` : '-'}
</span>
{!practice && (
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>
{s.points}
{unit}
</strong>
)}
</li>
))}
</ol>
</div>
{v.rounds.length > 0 && (
<details className="card" style={{ padding: 12 }} open={v.phase === 'ended'}>
<summary style={{ fontWeight: 800, cursor: 'pointer' }}>라운드 기록 ({v.rounds.length})</summary>
<div className="stack" style={{ gap: 10, marginTop: 8 }}>
{v.rounds.map((r) => (
<div key={r.round} className="stack" style={{ gap: 4 }}>
<span className="small" style={{ fontWeight: 700 }}>
{practice ? '연습 기록' : `라운드 ${r.round} · ${r.winners.length ? r.winners.map((w) => nick(players, w)).join(', ') : '승자 없음'}`}
</span>
<RoundTable r={r} players={players} mode={v.options.mode} />
</div>
))}
</div>
</details>
)}
<AfterMotion when={!!v.result}>
{v.result && (
<div className="card stack" style={{ gap: 4, padding: 12 }}>
<strong>최종 순위</strong>
{v.result.ranking.map((r) => (
<span key={r.id}>
{r.rank}등 {nick(players, r.id)}
<span className="muted small">
{' '}
· {practice ? '' : `${r.points}${unit} · `}평균 {r.kpm}타 · 정확도 {r.acc}%{r.left ? ' · 나감' : ''}
</span>
</span>
))}
<span className="small muted">{v.result.summary}</span>
</div>
)}
</AfterMotion>
</>
);
}
// ---------------------------------------------------------------- status
function isMyTurn(v: TypingView, me: string | null): boolean {
const s = v.seats.find((x) => x.id === me);
if (!s || v.phase !== 'playing' || !s.alive) return false;
return v.flow === 'shared' ? v.upcoming.length > 0 && !s.solved : !s.finished;
}
function statusText(v: TypingView, me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요';
if (v.phase === 'countdown') return `${v.options.mode === 'practice' ? '연습' : `라운드 ${v.round}`} 곧 시작! 나오는 글을 그대로 쳐요`;
if (v.phase === 'roundEnd') return v.rounds.at(-1)?.summary ?? '라운드 끝';
const s = v.seats.find((x) => x.id === me);
if (!s) return v.options.mode === 'practice' ? MODE_KO.practice : `${MODE_KO[v.options.mode]} · 라운드 ${v.round}/${v.options.rounds}`;
if (s.left) return '게임에서 나갔어요';
if (!s.alive) return '탈락했어요 · 다음 라운드를 기다려요';
if (v.flow === 'shared') {
if (!v.upcoming.length) return v.last?.winner ? `${v.last.winner === me ? '내가' : `${nick(players, v.last.winner)}님이`} 먼저 쳤어요!` : '다음 문제가 곧 나와요';
if (s.solved) return '쳤어요! 다른 사람을 기다려요';
return v.options.mode === 'first' ? '가장 먼저 정확하게 치면 1점!' : '제한 시간 안에 정확하게 쳐요!';
}
if (s.finished) return '다 쳤어요! 다른 사람을 기다려요';
return v.options.mode === 'timeAttack' ? '시간 안에 최대한 많이 쳐요!' : v.options.mode === 'practice' ? '한 줄씩 치고 Enter! 천천히 정확하게 연습해요' : '한 줄씩 치고 Enter!';
}
// ---------------------------------------------------------------- options
function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<div className="segmented" role="group" aria-label={label} style={{ flexWrap: 'wrap' }}>
{options.map(([k, l]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
const MODE_HELP: Record<Mode, string> = {
first: '모두에게 같은 글이 나오고, 가장 먼저 정확하게 친 사람이 1점을 얻어요. 틀리면 고쳐서 다시 쳐요.',
survival: '같은 글을 모두 함께 치고, 탈락 조건에 걸리면 빠져요. 끝까지 남은 사람이 라운드 1점. 문제마다 제한 시간이 조금씩 줄어요.',
speed: '각자 자기 속도로 글을 치고, 라운드의 타수(1분에 친 타 수, 오타는 빼고)가 가장 높은 사람이 1점이에요.',
accuracy: '각자 글을 치고, 정확도가 가장 높은 사람이 1점이에요. 정확도가 같으면 타수가 높은 사람이 이겨요.',
timeAttack: '정해진 시간 동안 끝없이 나오는 글을 쳐요. 정확하게 친 타 수가 가장 많은 사람이 1점이에요.',
practice: '한컴 타자연습처럼 혼자(또는 함께) 제 속도로 연습해요. 제한 시간과 점수 없이 짧은글은 10문장, 단어는 20개, 긴글은 한 편을 처음부터 끝까지 쳐요. 문장마다 첫 글자를 친 때부터 타수를 재요.',
};
const ELIM_HELP: Record<Elim, string> = {
wrong: '틀린 채로 Enter를 누르거나 시간 안에 못 치면 목숨이 하나 줄고, 목숨을 다 쓰면 탈락해요.',
sentence: '문장마다 가장 늦게 친 한 사람이 탈락해요.',
interval: '모두 각자 치다가, 정해진 시간마다 그때까지 가장 적게 친 사람이 탈락해요.',
deadline: '문장마다 제한 시간 안에 못 친 사람은 모두 탈락해요.',
};
function Options({ value: o, onChange }: OptionsProps<TypingOptions>) {
const set = (p: Partial<TypingOptions>) => onChange({ ...o, ...p });
const topics = topicsFor(o.lang, o.category);
const picked = o.topics.filter((t) => topics.some((x) => x.id === t));
const toggle = (id: string) => {
const others = o.topics.filter((t) => !topics.some((x) => x.id === t));
const next = picked.includes(id) ? picked.filter((t) => t !== id) : [...picked, id];
set({ topics: [...others, ...next] });
};
const timeLabel = o.mode === 'speed' || o.mode === 'accuracy' ? '라운드 제한 시간' : '한 문제 제한 시간';
const practice = o.mode === 'practice';
const showTime = o.mode !== 'timeAttack' && !practice && !(o.mode === 'survival' && o.elimination === 'interval');
return (
<div className="stack" style={{ gap: 16 }}>
<div className="stack" style={{ gap: 6 }}>
<strong>언어</strong>
<Seg label="언어" value={o.lang} options={[['ko', LANG_KO.ko], ['en', LANG_KO.en]]} onChange={(lang) => set({ lang })} />
</div>
<div className="stack" style={{ gap: 6 }}>
<strong>대결 방식</strong>
<Seg label="대결 방식" value={o.mode} options={(Object.keys(MODE_KO) as Mode[]).map((m) => [m, MODE_KO[m]])} onChange={(mode) => set({ mode })} />
<span className="small muted">{MODE_HELP[o.mode]}</span>
</div>
{o.mode === 'survival' && (
<div className="stack" style={{ gap: 6, paddingLeft: 10, borderLeft: '3px solid var(--border)' }}>
<strong>탈락 조건</strong>
<Seg label="탈락 조건" value={o.elimination} options={(Object.keys(ELIM_KO) as Elim[]).map((m) => [m, ELIM_KO[m].replace(/\(.*\)/, '')])} onChange={(elimination) => set({ elimination })} />
<span className="small muted">{ELIM_HELP[o.elimination]}</span>
{o.elimination === 'wrong' && (
<>
<strong>목숨</strong>
<Seg label="목숨" value={o.lives} options={[1, 2, 3, 4, 5].map((n) => [n, `${n}개`] as [number, string])} onChange={(lives) => set({ lives })} />
</>
)}
{o.elimination === 'interval' && (
<>
<strong>탈락 간격</strong>
<Seg label="탈락 간격" value={o.intervalSec} options={([10, 15, 20, 30] as const).map((n) => [n, `${n}초`] as [typeof n, string])} onChange={(intervalSec) => set({ intervalSec })} />
</>
)}
</div>
)}
<div className="stack" style={{ gap: 6 }}>
<strong>{practice ? '연습 종목' : '대결 종목'}</strong>
<Seg label={practice ? '연습 종목' : '대결 종목'} value={o.category} options={(['word', 'short', 'long'] as Category[]).map((c) => [c, CATEGORY_KO[c]])} onChange={(category) => set({ category })} />
</div>
<div className="stack" style={{ gap: 6 }}>
<strong>주제 (여러 개 고를 수 있어요)</strong>
<div className="segmented" role="group" aria-label="주제" style={{ flexWrap: 'wrap' }}>
<button type="button" aria-pressed={picked.length === 0} onClick={() => set({ topics: o.topics.filter((t) => !topics.some((x) => x.id === t)) })}>
전체
</button>
{topics.map((t) => (
<button key={t.id} type="button" aria-pressed={picked.includes(t.id)} onClick={() => toggle(t.id)}>
{t.name}
</button>
))}
</div>
<span className="small muted">
{picked.length === 0 ? `전체 ${topics.length}개 주제에서 골고루 나와요.` : `${picked.map((id) => topics.find((t) => t.id === id)?.name).join(', ')}에서 나와요.`}
{o.category === 'long' ? (practice ? ' 연습은 그중 한 편을 처음부터 끝까지 쳐요.' : ' 긴글은 라운드마다 한 단락(8줄 안팎)씩 이어서 쳐요.') : ''}
</span>
</div>
{!practice && (
<div className="stack" style={{ gap: 6 }}>
<strong>라운드</strong>
<Seg label="라운드" value={o.rounds} options={Array.from({ length: 10 }, (_, i) => [i + 1, `${i + 1}`] as [number, string])} onChange={(rounds) => set({ rounds })} />
</div>
)}
{showTime && (
<div className="stack" style={{ gap: 6 }}>
<strong>{timeLabel}</strong>
<select
className="input"
aria-label={timeLabel}
style={{ maxWidth: 260 }}
value={o.timeLimit === null ? 'null' : String(o.timeLimit)}
onChange={(e) => set({ timeLimit: (e.target.value === 'null' ? null : Number(e.target.value)) as TypingOptions['timeLimit'] })}
>
<option value="0">자동(글 길이에 맞게)</option>
{[10, 20, 30, 60, 120, 180, 300].map((n) => (
<option key={n} value={n}>
{n < 60 ? `${n}초` : `${n / 60}분`}
</option>
))}
<option value="null">{o.mode === 'survival' ? '무제한(서바이벌은 자동으로 해요)' : '무제한'}</option>
</select>
</div>
)}
{o.mode === 'timeAttack' && (
<div className="stack" style={{ gap: 6 }}>
<strong>타임어택 시간</strong>
<Seg label="타임어택 시간" value={o.attackSec} options={([30, 60, 90, 120] as const).map((n) => [n, n < 60 ? `${n}초` : n === 90 ? '1분 30초' : `${n / 60}분`] as [typeof n, string])} onChange={(attackSec) => set({ attackSec })} />
</div>
)}
</div>
);
}
function optionsSummary(o: TypingOptions): string {
const topics = topicsFor(o.lang, o.category);
const picked = topics.filter((t) => o.topics.includes(t.id)).map((t) => t.name);
const sub = o.mode === 'survival' ? `(${ELIM_KO[o.elimination].replace(/\(.*\)/, '')}${o.elimination === 'wrong' ? ` · 목숨 ${o.lives}` : ''})` : '';
return `${LANG_KO[o.lang]} · ${MODE_KO[o.mode]}${sub} · ${CATEGORY_KO[o.category]}(${picked.length ? picked.join(', ') : '전체 주제'})${o.mode === 'practice' ? '' : ` · ${o.rounds}라운드`}`;
}
// ---------------------------------------------------------------- rules
function Rules({ options: o }: { options?: TypingOptions }) {
return (
<div className="stack">
<p>
모두에게 <strong>같은 글</strong>이 나와요. 입력 칸에 그대로 치고 <strong>Enter</strong>를 눌러요. 맞게 친 글자는 초록, 틀린 글자는 빨강으로 보여요. 붙여 넣기는 쓸 수 없어요.
</p>
<p>
<strong>타수</strong>는 1분 동안 친 자판 수예요(두벌식: "강" = ㄱ·ㅏ·ㅇ 3타, "과" = ㄱ·ㅗ·ㅏ 3타). 틀린 만큼은 빼고 세요. <strong>정확도</strong>는 글과 얼마나 똑같이 쳤는지예요.
</p>
<ul>
<li>
<strong>가장 먼저 입력</strong>: 같은 글을 동시에 치고, 가장 먼저 정확하게 친 사람이 1점. 단어는 한 라운드에 10개, 짧은글은 5문장, 긴글은 한 단락을 한 줄씩 겨뤄요.
</li>
<li>
<strong>서바이벌</strong>: 탈락 조건 — 틀렸을 때(목숨, 기본 3개), 문장별(가장 늦게 친 사람), 시간별(정해진 시간마다 가장 적게 친 사람), 시간 초과(제한 시간 안에 못 친 사람). 끝까지 남으면 1점. 문제마다 제한 시간이 조금씩 줄어요. 남은 사람이 모두 한꺼번에 탈락하게 되면 아무도 탈락하지 않아요.
</li>
<li>
<strong>타수 비교</strong>: 각자 자기 속도로 치고, 라운드 타수가 가장 높은 사람이 1점.
</li>
<li>
<strong>정확도 대결</strong>: 정확도가 가장 높은 사람이 1점(같으면 타수).
</li>
<li>
<strong>타임어택</strong>: 정해진 시간 동안 끝없이 나오는 글을 쳐서, 정확하게 친 타 수가 가장 많은 사람이 1점.
</li>
<li>
<strong>연습</strong>: 한컴 타자연습처럼 제한 시간·점수 없이 제 속도로 쳐요. 짧은글 10문장, 단어 20개, 긴글은 한 편 전체. 지금·평균·최고 타수, 정확도, 진행률과 걸린 시간을 보여 줘요.
</li>
</ul>
<p>
라운드는 1~10번(기본 3번)이에요. 모두 끝나면 점수가 가장 높은 사람이 이기고, 같으면 평균 타수가 높은 사람이 앞서요. 한국어·영어, 단어·짧은글·긴글과 주제(여러 개)를 방 설정에서 골라요. 혼자서도, 컴퓨터와도 할 수
있어요.
</p>
{o && <p className="small muted">이 방: {optionsSummary(o)}</p>}
</div>
);
}
const ui: GameUI<TypingView, TypingOptions> = {
Board: TypingBoard,
Side: TypingSide,
statusText,
liveStatus: true,
isMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;

View File

@@ -0,0 +1,17 @@
/** 타자 대결: how each letter of the text looks against what is typed (pure, for the screen and its tests). */
import { toKeys } from '@bg/games/typing';
export type Mark = 'ok' | 'bad' | 'comp' | '';
/** How each letter of the target looks against what is typed: right, wrong, or the syllable still being composed. */
export function marks(target: string, typed: string): { marks: Mark[]; extra: number } {
const t = [...target];
const y = [...typed.replace(/^\s+/, '')];
const out: Mark[] = t.map(() => '');
for (let i = 0; i < y.length && i < t.length; i++) {
if (y[i] === t[i]) out[i] = 'ok';
else if (i === y.length - 1 && toKeys(t.slice(i).join('')).startsWith(toKeys(y[i]!))) out[i] = 'comp';
else out[i] = 'bad';
}
return { marks: out, extra: Math.max(0, y.length - t.length) };
}

View File

@@ -0,0 +1,99 @@
/** 타자 대결 30초 규칙 요약 (docs/07 §5). Simple redraws of the typing card. */
import type { ReactNode } from 'react';
import type { QuickCard } from '../types';
function Frame({ children }: { children: ReactNode }) {
return (
<svg viewBox="0 0 240 150" width={240} height={150} aria-hidden>
<rect x={0} y={0} width={240} height={150} rx={14} fill="#eef2ff" />
{children}
</svg>
);
}
/** A text line where the first `ok` letters are green and letter `bad` (if any) is red. */
function Line({ y, text, ok, bad = -1, size = 20 }: { y: number; text: string; ok: number; bad?: number; size?: number }) {
const chars = [...text];
const w = size * 0.95;
const x0 = 120 - (chars.length * w) / 2;
return (
<>
{chars.map((c, i) => (
<g key={i}>
{i === bad && <rect x={x0 + i * w - 1} y={y - size + 2} width={w} height={size + 4} rx={3} fill="#dc2626" />}
<text x={x0 + i * w + w / 2} y={y} textAnchor="middle" fontSize={size} fontWeight={800} fill={i === bad ? '#fff' : i < ok ? '#16a34a' : '#1f2937'}>
{c}
</text>
</g>
))}
</>
);
}
function Box({ y, text }: { y: number; text: string }) {
return (
<>
<rect x={20} y={y} width={200} height={32} rx={8} fill="#fff" stroke="#6366f1" strokeWidth={2} />
<text x={30} y={y + 22} fontSize={15} fontWeight={700} fill="#1f2937">
{text}
</text>
</>
);
}
function Bar({ y, name, frac, color }: { y: number; name: string; frac: number; color: string }) {
return (
<>
<text x={20} y={y + 9} fontSize={12} fontWeight={700} fill="#374151">
{name}
</text>
<rect x={70} y={y} width={150} height={10} rx={5} fill="#e5e7eb" />
<rect x={70} y={y} width={150 * frac} height={10} rx={5} fill={color} />
</>
);
}
export const quickStart: QuickCard[] = [
{
pic: (
<Frame>
<Line y={52} text="티끌 모아 태산." ok={4} />
<Box y={80} text="티끌 모|" />
</Frame>
),
alt: '위에 "티끌 모아 태산."이 있고, 아래 입력 칸에 "티끌 모"까지 쳤어요. 친 글자는 초록이에요',
title: '나온 글을 그대로',
text: '모두에게 같은 글이 나와요. 입력 칸에 그대로 치고 Enter! 맞은 글자는 초록, 틀린 글자는 빨강이에요.',
},
{
pic: (
<Frame>
<Bar y={34} name="호랑이" frac={1} color="#16a34a" />
<Bar y={64} name="나" frac={0.7} color="#6366f1" />
<Bar y={94} name="토끼" frac={0.4} color="#6366f1" />
<text x={120} y={135} textAnchor="middle" fontSize={15} fontWeight={900} fill="#15803d">
호랑이님이 먼저 쳤어요! 352타
</text>
</Frame>
),
alt: '세 사람의 진행 막대예요. 호랑이가 먼저 다 쳤어요',
title: '빠르고 정확하게',
text: '가장 먼저 입력·서바이벌·타수 비교·정확도 대결·타임어택 중에서 골라요. 다른 사람이 친 만큼 막대로 보여요. 혼자 연습하려면 연습!',
},
{
pic: (
<Frame>
<Line y={52} text="천 리 길도" ok={2} bad={2} size={22} />
<text x={120} y={92} textAnchor="middle" fontSize={22} fill="#dc2626">
♥♥♡
</text>
<text x={120} y={128} textAnchor="middle" fontSize={14} fontWeight={800} fill="#374151">
라운드 1/3 · 평균 280타 · 정확도 97%
</text>
</Frame>
),
alt: '틀린 글자가 빨갛게 보이고, 목숨 하트 3개 중 1개가 비었어요',
title: '라운드 점수로 승부',
text: '서바이벌은 틀리면 목숨이 줄어요. 1~10라운드(기본 3) 점수를 모아 1등을 가려요. 혼자서도 OK!',
},
];

View File

@@ -35,6 +35,12 @@ export const GAME_ICON: Record<string, string> = {
blackjack: '🂡', blackjack: '🂡',
'six-nimmt': '🐮', 'six-nimmt': '🐮',
gemblo: '💠', gemblo: '💠',
typing: '⌨️',
minesweeper: '💣',
shisen: '🀄',
solitaire: '♥️',
sudoku: '🧮',
nonogram: '🧩',
'hot-streak': '🏁', 'hot-streak': '🏁',
tichu: '🐉', tichu: '🐉',
'case-file': '🔍', 'case-file': '🔍',
@@ -48,5 +54,6 @@ export const UPCOMING: string[] = [];
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [ 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: '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: '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', 'hot-streak', 'case-file'] }, { 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'] },
]; ];

View File

@@ -53,6 +53,12 @@
| `tichu` | 티츄 | 4 (변형 3·6) | 2026-10 새 게임 | | `tichu` | 티츄 | 4 (변형 3·6) | 2026-10 새 게임 |
| `case-file` | 사건 파일 | 1~5 | 2026-10 새 게임 | | `case-file` | 사건 파일 | 1~5 | 2026-10 새 게임 |
| `castles-of-burgundy` | 버건디의 성 | 1~4 | 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 새 게임 |
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선). 인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).

67
docs/games/minesweeper.md Normal file
View File

@@ -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판에서 어려움 컴퓨터가 대부분 풀고 쉬움보다 자주 푼다(테스트).

71
docs/games/nonogram.md Normal file
View File

@@ -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분에 푼다.

38
docs/games/race.md Normal file
View File

@@ -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`)가 시간을 조금 바꾼다.

67
docs/games/shisen.md Normal file
View File

@@ -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판에서 강한 컴퓨터가 약한 컴퓨터보다 거의 늘 먼저 다 푼다(테스트).

91
docs/games/solitaire.md Normal file
View File

@@ -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판에서 강한 컴퓨터가 약한 컴퓨터보다 평균적으로 더 많이 올린다(테스트).

70
docs/games/sudoku.md Normal file
View File

@@ -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%) 틀린 숫자를 넣고, 나중에 알아채 고친다(판이 다 차면 반드시).

102
docs/games/typing.md Normal file
View File

@@ -0,0 +1,102 @@
# 타자 대결 (`typing`)
> 사이트에서 직접 만든 게임(2026-11-12 사용자 요청). 한컴 타자연습의 타수·정확도 개념에 여러 명 대결 방식을 더했다.
## 1. 개요
- 1~8명(서바이벌은 2명부터), 컴퓨터 상대 가능. 한 판 3~10분.
- 모두에게 같은 글이 나오고, 입력 칸에 그대로 친 뒤 Enter. 맞은 글자는 초록, 틀린 글자는 빨강, 조합 중인 글자는 파랑 밑줄.
## 2. 모드와 옵션
| 옵션 | 값 (기본값 굵게) |
|---|---|
| 언어 | **한국어**, 영어 |
| 대결 방식 | **가장 먼저 입력**, 서바이벌, 타수 비교, 정확도 대결, 타임어택, 연습 |
| 대결 종목 | 단어, **짧은글**, 긴글 |
| 주제 | 여러 개 고르기, 비우면 **전체**(언어·종목에 맞는 주제만 쓰임) |
| 라운드 | 1~10 (**3**) |
| 서바이벌 탈락 조건 | **틀렸을 때**, 문장별, 시간별, 시간 초과 |
| 목숨(틀렸을 때) | 1~5 (**3**) |
| 탈락 간격(시간별) | 10·**15**·20·30초 |
| 제한 시간 | **자동(글 길이)**, 10초~5분, 무제한 — 가장 먼저 입력·서바이벌은 한 문제, 타수 비교·정확도 대결은 한 라운드 |
| 타임어택 시간 | 30초·**1분**·1분 30초·2분 |
## 3. 구성물 (글 묶음, `packages/games/src/typing/texts.ts`)
- 한국어 단어: 과일, 동물, 채소, 나라, 음식, 직업, 스포츠, 사자성어
- 한국어 짧은글: 속담, 명언, 잰말놀이, 일상 문장
- 한국어 긴글: 애국가, 별 헤는 밤·서시(윤동주), 진달래꽃·산유화(김소월), 님의 침묵(한용운), 훈민정음 서문(현대어 풀이), 흥부와 놀부·해님 달님·토끼와 거북(사이트에서 다시 씀)
- 영어 단어: Fruits, Animals, Colors, Countries, Food, Jobs, Sports
- 영어 짧은글: Proverbs, Famous quotes, Tongue twisters, Pangrams
- 영어 긴글: Gettysburg Address, The Road Not Taken, Sonnet 18, Daffodils, Twinkle Twinkle Little Star, US Constitution Preamble, The Tortoise and the Hare
- 시는 위키문헌 원문과 대조해 현대 맞춤법으로 적었다. 일반 자판으로 칠 수 있는 글자만(한자·둥근 따옴표·줄표 없음, 테스트로 확인).
## 4. 준비
- 단어·짧은글: 고른 주제의 항목을 모두 섞은 덱 하나(시드 RNG). 라운드마다 덱에서 차례로 뽑는다(가장 먼저 입력: 단어 10개·짧은글 5문장, 타수 비교·정확도 대결: 단어 15개·짧은글 3문장). 덱을 다 쓰면 다시 섞는다.
- 긴글: 주제 순서를 섞고 라운드마다 다음 주제의 다음 단락(8줄 안팎, 남는 2줄 이하는 앞 단락에 붙임)을 친다. 긴 줄은 띄어쓰기에서 나눈다(한국어 34자, 영어 52자).
- 서바이벌·타임어택은 글이 끝없이 돈다.
- 연습(2026-11-12 사용자 요청, 한컴 타자연습의 짧은글·긴글 연습처럼): 라운드 1번, 제한 시간·점수 없음(라운드·제한 시간 옵션은 안 씀). 단어 20개·짧은글 10문장, 긴글은 고른 주제 중 한 편을 처음부터 끝까지.
- 라운드마다 3초 카운트다운. 그동안 첫 글은 숨긴다.
## 5. 진행 규칙
- **함께 치기**(가장 먼저 입력, 서바이벌 중 시간별 아닌 것): 모두 같은 문제를 동시에 친다. 문제가 정해지면 1.5초 쉬고 다음 문제가 열린다.
- 가장 먼저 입력: 먼저 정확하게 친 사람 1점. 틀리면 고쳐서 다시. 시간이 끝나면 아무도 점수 없음.
- 서바이벌 틀렸을 때: 틀린 Enter·시간 초과마다 목숨 −1, 0이면 탈락. 살아 있는 사람이 모두 치면 다음 문제.
- 서바이벌 문장별: 남은 사람 중 마지막 한 사람이 남으면 그 사람 탈락. 시간 안에 못 친 사람도 탈락.
- 서바이벌 시간 초과: 시간 안에 못 친 사람 모두 탈락.
- **각자 치기**(타수 비교, 정확도 대결, 타임어택, 서바이벌 시간별, 연습): 각자 한 줄 치고 Enter → 다음 줄. 틀린 채로 넘어가도 되고 그만큼 정확도·타수가 깎인다.
- 서바이벌 시간별: 정해진 간격마다 그때까지 친 타 수(지금 줄 포함)가 가장 적은 사람(같으면 함께) 탈락.
- 연습: 줄마다 첫 타(첫 진행)부터 시간을 잰다(줄 사이에 쉬어도 타수가 안 떨어짐). 첫 타의 시간 몫으로 0.15초 앞당겨 시작하고, 그래서 붙여 넣기 막기도 다른 방식과 같다. 줄마다 타수의 최고값(`best`)을 둔다. 모두 다 치면 끝(여럿이면 각자 속도로).
- 서바이벌은 문제마다 제한 시간이 0.9배씩 줄고(무제한은 자동으로 친다), 아주 빠른 사람(900타)이 치는 시간 + 1초 아래로는 줄지 않는다. 그래서 라운드가 반드시 끝난다.
- 남은 사람이 모두 한꺼번에 탈락하게 되면 아무도 탈락하지 않는다(목숨은 1개로).
- 붙여 넣기 막기: 화면에서 붙여 넣기·끌어 놓기를 막고, 서버는 2,400타/분 + 0.15초보다 빠른 Enter를 거절하며 진행 막대도 그 속도 이상 앞서지 않는다.
## 6. 승패와 점수 계산
- 타수 = 1분에 친 자판 수(두벌식: 겹모음·겹받침 2타, 쌍자음 1타, 영어는 글자 수). 각자 치기는 줄의 타 수 × 정확도, 함께 치기는 맞게 친 문제(못 친 문제는 맞게 친 데까지).
- 정확도 = 1 − 편집 거리 / 긴 쪽 글자 수.
- 라운드 점수: 가장 먼저 입력은 문제마다 1점, 나머지는 라운드 1등(같으면 모두) 1점 — 타수 비교는 타수, 정확도 대결은 정확도(같으면 타수), 타임어택은 친 타 수, 서바이벌은 끝까지 남은 사람.
- 최종: 점수 → 평균 타수 → 평균 정확도 순. 나간 사람은 맨 뒤.
- 연습: 점수 없음, 순위는 평균 타수 → 정확도. `scoreText` = "평균 N타 · 정확도 N%".
## 7. 하우스 룰
- 없음(위 옵션으로 조절).
## 8. 엔진 설계
### 8.1 상태
`phase`(countdown·playing·roundEnd·ended), `round`, `items`·`itemTopic`·`cycle`, 함께 치기의 `cur`·`curAt`·`curOpen`·`curEndsAt`·`last`, 시간별 `nextCutAt`, 각자의 라운드 기록 `rs`(idx·prog·done·keys·ms·정확도 합·wrong·lives·alive·place), 누적 `totals`, 라운드 결과 `rounds`, 덱 `deck`·`deckAt`, 긴글 `longOrder`·`longAt`.
### 8.2 액션
`progress { item, text }`(stream: 서버는 이벤트만 전달, 보기를 다시 보내지 않음), `submit { item, text }`, 시스템 `tick`·`leave`. 초당 15번 제한.
### 8.3 공개/비공개 정보
다른 사람이 친 글은 보내지 않고 진행 비율만. 카운트다운과 문제 사이 쉬는 동안 다음 글은 숨김.
### 8.4 랜덤 요소
덱 섞기, 긴글 주제 순서.
### 8.5 타이머·연결 끊김
`realtime`. 시계가 있는 단계(카운트다운, 쉬는 시간, 문제·라운드 시간, 시간별 간격)는 그 시각에만 끝나고 끊긴 사람 때문에 당겨지지 않는다. 시계가 없는 단계(무제한)는 기다리는 사람만 시간 초과 대상이라, 끊긴 사람은 방의 유예 시간 뒤 한 번만 처리된다(각자 치기: 친 데까지로 멈춤).
### 8.6 종료와 결과
마지막 라운드가 끝나거나 한 명만 남으면(나머지가 나감) 끝. 연습은 남은 사람이 다 칠 때까지 계속하고, 모두 나가야 끝. `scoreText` = "N문제/N승 · 평균 N타 · 정확도 N%".
## 9. UI/UX
- 위: 라운드·방식·몇 번째·남은 사람·시계. 가운데 카드: 주제, 칠 글(글자별 색, 커서 밑줄), 긴글은 단락 전체와 지금 줄, 각자 치기는 다음 두 줄 미리 보기, 입력 칸 + [입력].
- 한글 조합 중 Enter는 조합이 끝난 뒤 보낸다(IME가 Enter를 두 번 보내는 것도 거름). 붙여 넣기·끌어 놓기 막음, 자동 완성·맞춤법 끔.
- 한/영이 반대로 쳐지면 경고. 지금 타수·라운드 타수·정확도·틀린 횟수 표시.
- 아래: 모두의 진행 막대(stream으로 실시간), 목숨 하트, 탈락·다 침 표시. 문제가 정해지면 "OO님이 먼저 쳤어요! 352타"/"OO님 탈락!" 띠. 라운드 끝 표(순위·친 문제·타수·정확도), 6초 뒤 다음 라운드.
- 연습: 라운드 표시 대신 걸린 시간(⏱), 아래에 지금·평균·최고 타수, 정확도, 진행 %. 끝나면 평균·최고 타수, 정확도, 틀린 줄. 참가자 막대 옆은 점수 대신 타수.
- 소리: 자판 딸깍, 맞음, 틀림 삐, 먼저 침 팡파르, 탈락, 3·2·1, 마지막 5초.
### 9.1 설정 화면
언어·방식(서바이벌이면 탈락 조건·목숨·간격)·종목·주제(전체 또는 여러 개)·라운드 1~10·제한 시간/타임어택 시간. 방식마다 한 줄 설명.
## 10. 테스트 체크리스트
- keys.test: 두벌식 타 수, 조합 중 글자, 정확도·편집 거리, 글 묶음 글자 검사·줄 나누기.
- typing.test: 옵션·주제, 가장 먼저 입력(쉬는 시간, 늦은 답, 붙여 넣기, 시간 초과, 라운드·최종), 서바이벌 4가지와 모두 탈락 방지·줄어드는 시계, 타수 비교·정확도 대결·타임어택·무제한, 나가기, 무작위 대국 10가지 설정(누출 없음).
- typing.test 연습: 10문장·시계 없음·점수 없음, 첫 타부터 시간·최고 타수·붙여 넣기 막기, 긴글 한 편 전체, 여럿이 각자.
- e2e typingPractice(짧은글, 3초 쉬어도 타수 유지)·typingPracticeLong(애국가 16줄 전체).
- bot.test: 10가지 설정(연습은 컴퓨터끼리만) × (사람 1 + 컴퓨터 / 컴퓨터만) 거절 0, 레벨별 타수.
- typing.room.test: 진행 stream, 연습 방, 끊긴 사람.
- 웹 help.test: 도움말, 글자 표시.
## 11. 참고 자료
- 한컴 타자연습(타수·정확도 개념), 위키문헌(애국가·윤동주·김소월·한용운 원문).
## 12. 메모
- 시·노래는 저작권이 끝난 것만(저자 사후 70년 경과, 애국가). 동화는 직접 다시 썼다.
## 13. 컴퓨터 상대
- `LIVE_BOT_STRATEGIES.typing`: 자기 화면만 보고 자기 시계로 친다. 레벨 1~60에 따라 한국어 120~620타(영어 100~500), 읽는 시간 0.9~0.35초, 오타 확률(글이 길수록 높음). 함께 치기에서는 틀린 Enter 뒤 고쳐서 다시, 각자 치기에서는 오타를 둔 채 넘어간다. 진행은 0.35~0.65초마다 보낸다.

View File

@@ -10,6 +10,12 @@ import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config'; import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server'; import { startServer } from '../apps/server/src/server';
import { plan960 } from './chess960-plan'; 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 PORT = Number(process.env.E2E_PORT ?? 4519);
const ORIGIN = `http://localhost:${PORT}`; const ORIGIN = `http://localhost:${PORT}`;
@@ -849,6 +855,240 @@ async function appleDrag(p: Page, rect: [number, number, number, number], touch:
await cdp.detach(); 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<SolitaireBoardView> {
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<Page, Record<string, unknown>>();
/** 솔리테어: 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<number> {
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). */ /** 그림 맞히기: non-white pixels on a page's drawing canvas (proves streamed strokes were rendered). */
async function cmInk(p: Page): Promise<number> { async function cmInk(p: Page): Promise<number> {
return p.evaluate(() => { return p.evaluate(() => {
@@ -1385,6 +1625,22 @@ async function cobStep(p: Page, st: Record<string, number>): Promise<string | nu
return null; return null;
} }
/** 타자 대결: the text my input asks for (its label), or null when it is off. */
async function typingTarget(p: Page): Promise<string | null> {
const box = p.locator('input.ty-input');
if (!(await box.count()) || !(await box.isEnabled().catch(() => false))) return null;
const label = (await box.getAttribute('aria-label')) ?? '';
return label.startsWith('여기에 쳐요: ') ? label.slice('여기에 쳐요: '.length) : null;
}
/** Types like a person (one key at a time, so the paste guard lets it in) and presses Enter. */
async function typeLine(p: Page, text: string, delay = 70) {
const box = p.locator('input.ty-input');
await box.click();
await p.keyboard.type(text, { delay });
await p.keyboard.press('Enter');
}
const PLANS: Record<string, Plan> = { const PLANS: Record<string, Plan> = {
'case-file': { 'case-file': {
// PC host + phone guest, "고른 사람만 읽기": 의뢰 → 반장 돌기(두 번 눌러 고르기) → 단서 읽기(다른 사람은 제목만) // PC host + phone guest, "고른 사람만 읽기": 의뢰 → 반장 돌기(두 번 눌러 고르기) → 단서 읽기(다른 사람은 제목만)
@@ -3597,6 +3853,684 @@ const PLANS: Record<string, Plan> = {
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)}`); 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 "먼저 쳤어요"
// banner and the score; the progress bar of the one typing moves on the other screen while they type.
lobby: async (host) => {
await host.getByRole('group', { name: '라운드' }).getByRole('button', { name: '1', exact: true }).click();
await host.getByText(/짧은글\(전체 주제\) · 1라운드/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
let n = 0;
let wrongShown = false;
let barSeen = false;
const over = () => host.getByRole('dialog', { name: '게임 결과' }).count();
const until = Date.now() + 120_000;
while (Date.now() < until && !(await over())) {
const typer = n % 2 === 0 ? host : guest;
const other = typer === host ? guest : host;
const text = await typingTarget(typer);
if (!text) {
await host.waitForTimeout(150);
continue;
}
if (!wrongShown) {
await typeLine(typer, 'ㅋ');
await typer.getByText('틀린 곳이 있어요. 빨간 글자를 고쳐요').waitFor({ timeout: 3000 });
await typer.locator('.ty-target .bad').first().waitFor();
await typer.screenshot({ path: join(SHOTS, 'typing-wrong.png') });
await typer.locator('input.ty-input').fill('');
wrongShown = true;
}
const box = typer.locator('input.ty-input');
await box.click();
const half = Math.ceil([...text].length / 2);
await typer.keyboard.type([...text].slice(0, half).join(''), { delay: 70 });
if (!barSeen) {
// The other screen shows my bar moving (streamed progress), before I press Enter.
await other.waitForFunction(() => [...document.querySelectorAll('.ty-bar')].some((b) => Number(b.getAttribute('aria-valuenow')) > 0), null, { timeout: 3000 });
barSeen = true;
await host.screenshot({ path: join(SHOTS, 'typing-typing-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'typing-typing-phone.png') });
}
await typer.keyboard.type([...text].slice(half).join(''), { delay: 70 });
await typer.keyboard.press('Enter');
await other.locator('.ty-banner').filter({ hasText: '먼저 쳤어요' }).first().waitFor({ timeout: 4000 }).catch(() => {});
n++;
}
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
await host.waitForTimeout(600);
await host.screenshot({ path: join(SHOTS, 'typing-result-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'typing-result-phone.png') });
const text = await host.getByRole('dialog', { name: '게임 결과' }).innerText();
if (!/3문제 · 평균 \d+타 · 정확도 \d+(\.\d)?%/.test(text) || !/2문제/.test(text)) throw new Error(`result: ${text.replace(/\n/g, ' ')}`);
console.log(` typing: ${n} sentences typed for real; result: ${text.replace(/\n/g, ' ').slice(0, 160)}`);
},
},
typingSpeed: {
// 타수 비교 · 영어 · 긴글 · 1라운드: each types the passage line by line at their own pace; the next line shows at once
// after Enter; the phone makes a typo on purpose and gets the lower accuracy; the round table shows 타수 and 정확도.
game: 'typing',
lobby: async (host) => {
await host.getByRole('group', { name: '언어' }).getByRole('button', { name: '영어' }).click();
await host.getByRole('group', { name: '대결 방식' }).getByRole('button', { name: '타수 비교' }).click();
await host.getByRole('group', { name: '대결 종목' }).getByRole('button', { name: '긴글' }).click();
await host.getByRole('group', { name: '주제' }).getByRole('button', { name: 'Twinkle, Twinkle, Little Star' }).click();
await host.getByRole('group', { name: '라운드' }).getByRole('button', { name: '1', exact: true }).click();
await host.getByText(/영어 · 타수 비교 · 긴글\(Twinkle, Twinkle, Little Star\) · 1라운드/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
const lines: Record<string, number> = { host: 0, guest: 0 };
const over = () => host.getByRole('dialog', { name: '게임 결과' }).count();
const until = Date.now() + 150_000;
let shot = false;
while (Date.now() < until && !(await over())) {
let acted = false;
for (const [who, p] of [['host', host], ['guest', guest]] as const) {
const text = await typingTarget(p);
if (!text) continue;
// The passage is shown with the line I am on.
await p.locator('.ty-passage li[data-s="cur"]').filter({ hasText: text }).first().waitFor({ timeout: 3000 });
await typeLine(p, who === 'guest' && lines.guest === 0 ? text.replace(/a/, 'q') : text, 25);
lines[who]!++;
acted = true;
if (!shot && lines.host === 2) {
shot = true;
await host.screenshot({ path: join(SHOTS, 'typing-speed-pc.png') });
}
}
if (!acted) await host.waitForTimeout(200);
}
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
await host.waitForTimeout(600);
await host.screenshot({ path: join(SHOTS, 'typing-speed-result-pc.png') });
const text = await host.getByRole('dialog', { name: '게임 결과' }).innerText();
if (lines.host < 8 || !/정확도 100%/.test(text) || !/정확도 9\d(\.\d)?%/.test(text)) throw new Error(`lines ${JSON.stringify(lines)}; result: ${text.replace(/\n/g, ' ')}`);
console.log(` typingSpeed: lines ${JSON.stringify(lines)}; result: ${text.replace(/\n/g, ' ').slice(0, 160)}`);
},
},
typingSurvival: {
// 서바이벌 · 틀렸을 때(목숨 2) · 단어 · 1라운드: the phone presses Enter on a wrong word twice — a heart goes the
// first time (both screens), the second time it is out and the host is the survivor.
game: 'typing',
lobby: async (host) => {
await host.getByRole('group', { name: '대결 방식' }).getByRole('button', { name: '서바이벌' }).click();
await host.getByRole('group', { name: '목숨' }).getByRole('button', { name: '2개' }).click();
await host.getByRole('group', { name: '대결 종목' }).getByRole('button', { name: '단어' }).click();
await host.getByRole('group', { name: '라운드' }).getByRole('button', { name: '1', exact: true }).click();
await host.getByText(/서바이벌\(틀렸을 때 · 목숨 2\) · 단어\(전체 주제\) · 1라운드/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
let word: string | null = null;
for (let t = 0; t < 100 && !word; t++) {
word = await typingTarget(guest);
if (!word) await guest.waitForTimeout(150);
}
if (!word) throw new Error('no word to type');
await host.getByLabel('목숨 2개').first().waitFor();
await typeLine(guest, '틀림');
await guest.getByText('틀렸어요! 목숨 하나를 잃었어요').waitFor({ timeout: 3000 });
await host.getByLabel('목숨 1개').first().waitFor({ timeout: 3000 });
await guest.waitForTimeout(400);
// Out of lives with only the host left: the round (and this one-round game) ends at once.
await typeLine(guest, '또틀림');
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
await guest.screenshot({ path: join(SHOTS, 'typing-survival-out-phone.png') });
const text = await host.getByRole('dialog', { name: '게임 결과' }).innerText();
if (!/1등\s*방\s*방장\s*1승/.test(text)) throw new Error(`result: ${text.replace(/\n/g, ' ')}`);
await host.getByRole('cell', { name: /친구 · 탈락/ }).first().waitFor();
console.log(` typingSurvival: result: ${text.replace(/\n/g, ' ').slice(0, 120)}`);
},
},
typingPractice: {
// 2026-11-12 연습 · 짧은글: like 한컴 타자연습 — no round, no clock, no points; 10 sentences one after another. The
// stats show 지금·평균·최고 타수, 정확도, 진행 %, and a running ⏱. The host rests 3 s before a sentence: its 타수 is
// timed from the first key, so the rest does not pull it down. Both finish; the result has 타수 and 정확도 only.
game: 'typing',
lobby: async (host) => {
await host.getByRole('group', { name: '대결 방식' }).getByRole('button', { name: '연습' }).click();
if (await host.getByRole('group', { name: '라운드' }).count()) throw new Error('연습 should not ask for rounds');
await host.getByText(/한국어 · 연습 · 짧은글\(전체 주제\)(?! · )/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
const lines: Record<string, number> = { host: 0, guest: 0 };
const over = () => host.getByRole('dialog', { name: '게임 결과' }).count();
const until = Date.now() + 150_000;
let rested = false;
while (Date.now() < until && !(await over())) {
let acted = false;
for (const [who, p] of [['host', host], ['guest', guest]] as const) {
const text = await typingTarget(p);
if (!text) continue;
if (who === 'host' && lines.host === 0) {
const top = await host.locator('.ty-top').innerText();
if (/라운드/.test(top) || !/연습/.test(top) || !/⏱/.test(top)) throw new Error(`top bar: ${top.replace(/\n/g, ' ')}`);
const stats = await host.locator('.ty-stats').innerText();
if (!/최고 0타/.test(stats) || !/진행 0%/.test(stats)) throw new Error(`stats: ${stats.replace(/\n/g, ' ')}`);
}
if (who === 'host' && lines.host === 1 && !rested) {
rested = true;
await host.waitForTimeout(3000);
}
// A Hangul syllable is 2~3 keys: about 1,200타 at this pace (under the paste guard).
await typeLine(p, text, 120);
lines[who]!++;
acted = true;
if (who === 'host' && lines.host === 2) {
// A 3 s rest before the second sentence would have made it < 150타 if it counted.
await host.waitForFunction(() => /최고 (\d+)타/.test(document.querySelector('.ty-stats')?.textContent ?? ''));
const stats = await host.locator('.ty-stats').innerText();
const avg = Number(/평균 (\d+)타/.exec(stats)?.[1] ?? 0);
if (avg < 250 || !/진행 20%/.test(stats)) throw new Error(`after the rest: ${stats.replace(/\n/g, ' ')}`);
await host.screenshot({ path: join(SHOTS, 'typing-practice-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'typing-practice-phone.png') });
}
}
if (!acted) await host.waitForTimeout(200);
}
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
await host.waitForTimeout(600);
await host.screenshot({ path: join(SHOTS, 'typing-practice-result-pc.png') });
const text = await host.getByRole('dialog', { name: '게임 결과' }).innerText();
if (lines.host !== 10 || lines.guest !== 10 || !/정확도 100%/.test(text) || !/방장\s*평균 \d+타/.test(text) || /방장\s*\d+승/.test(text)) throw new Error(`lines ${JSON.stringify(lines)}; result: ${text.replace(/\n/g, ' ')}`);
console.log(` typingPractice: lines ${JSON.stringify(lines)}; result: ${text.replace(/\n/g, ' ').slice(0, 160)}`);
},
},
typingPracticeLong: {
// 연습 · 긴글 · 애국가: the whole text from the first line to the last (not one 8-line passage), shown as one
// passage with the line I am on; the phone just watches the host's bar after typing one line.
game: 'typing',
lobby: async (host) => {
await host.getByRole('group', { name: '대결 방식' }).getByRole('button', { name: '연습' }).click();
await host.getByRole('group', { name: '연습 종목' }).getByRole('button', { name: '긴글' }).click();
await host.getByRole('group', { name: '주제' }).getByRole('button', { name: '애국가' }).click();
await host.getByText(/연습 · 긴글\(애국가\)(?! · )/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
let total = 0;
let typed = 0;
const until = Date.now() + 150_000;
while (Date.now() < until && !(await host.getByRole('dialog', { name: '게임 결과' }).count())) {
const text = await typingTarget(host);
if (!text) {
if (typed && (await host.getByText('다 쳤어요! 다른 사람을 기다려요').count())) break;
await host.waitForTimeout(200);
continue;
}
if (!total) total = await host.locator('.ty-passage li').count();
await host.locator('.ty-passage li[data-s="cur"]').filter({ hasText: text }).first().waitFor({ timeout: 3000 });
await typeLine(host, text, 110);
typed++;
}
// The guest has not finished: the game waits for them.
if (await host.getByRole('dialog', { name: '게임 결과' }).count()) throw new Error('ended before the guest finished');
await host.getByText('다 쳤어요! 다른 사람을 기다려요').first().waitFor();
await host.screenshot({ path: join(SHOTS, 'typing-practice-long-pc.png') });
for (let n = 0; n < 100; n++) {
const text = await typingTarget(guest);
if (text) await typeLine(guest, text, 110);
else if (await guest.getByRole('dialog', { name: '게임 결과' }).count()) break;
else await guest.waitForTimeout(200);
}
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
if (total <= 8 || typed !== total) throw new Error(`passage ${total} lines, typed ${typed}`);
console.log(` typingPracticeLong: the whole 애국가, ${typed} lines`);
},
},
appleUnlimited: { appleUnlimited: {
// 2026-10-14: 무제한 — the stopwatch runs (tenths) and stops when I finish; 💡 힌트 shows a glowing box that adds up // 2026-10-14: 무제한 — the stopwatch runs (tenths) and stops when I finish; 💡 힌트 shows a glowing box that adds up
// to 10 (button off while it shows), using it clears the box; the result shows 걸린 시간 and 힌트 N번. // to 10 (button off while it shows), using it clears the box; the result shows 걸린 시간 and 힌트 N번.

View File

@@ -43,6 +43,12 @@ import { gembloBot } from '../gemblo/bot';
import { hotStreakBot } from '../hot-streak/bot'; import { hotStreakBot } from '../hot-streak/bot';
import { tichuBot } from '../tichu/bot'; import { tichuBot } from '../tichu/bot';
import { cobBot } from '../castles-of-burgundy/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 type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona'; export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
@@ -137,9 +143,15 @@ export function decideBotAction(
return rest.length ? pick(playable(rest), random) : null; return rest.length ? pick(playable(rest), random) : null;
} }
/** Live strategies (games where everybody acts at once: 마피아·라이어 게임 talk, 사과 게임 races on its own board); also in `BOT_GAMES`. */ /** Live strategies (games where everybody acts at once: 마피아·라이어 게임 talk, 사과 게임 and 타자 대결 race on their own); also in `BOT_GAMES`. */
export const LIVE_BOT_STRATEGIES: Record<string, LiveBotStrategy> = { export const LIVE_BOT_STRATEGIES: Record<string, LiveBotStrategy> = {
mafia: mafiaBot, mafia: mafiaBot,
apple: appleBot, apple: appleBot,
liar: liarBot, liar: liarBot,
typing: typingBot,
minesweeper: minesweeperBot,
shisen: shisenBot,
solitaire: solitaireBot,
sudoku: sudokuBot,
nonogram: nonogramBot,
}; };

View File

@@ -39,6 +39,12 @@ import { hotStreak } from './hot-streak';
import { tichu } from './tichu'; import { tichu } from './tichu';
import { caseFile } from './case-file'; import { caseFile } from './case-file';
import { castlesOfBurgundy } from './castles-of-burgundy'; import { castlesOfBurgundy } from './castles-of-burgundy';
import { typing } from './typing';
import { minesweeper } from './minesweeper';
import { shisen } from './shisen';
import { solitaire } from './solitaire';
import { sudoku } from './sudoku';
import { nonogram } from './nonogram';
export const GAMES: Record<string, AnyGameDefinition> = { export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok, [omok.id]: omok,
@@ -81,4 +87,10 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[tichu.id]: tichu, [tichu.id]: tichu,
[caseFile.id]: caseFile, [caseFile.id]: caseFile,
[castlesOfBurgundy.id]: castlesOfBurgundy, [castlesOfBurgundy.id]: castlesOfBurgundy,
[typing.id]: typing,
[minesweeper.id]: minesweeper,
[shisen.id]: shisen,
[solitaire.id]: solitaire,
[sudoku.id]: sudoku,
[nonogram.id]: nonogram,
}; };

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,221 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import { COUNTDOWN_MS, LEVELS, around, makeField, minesweeper, type MinesweeperOptions, type MinesweeperState } from './index';
const T0 = 1_000_000;
const START = T0 + COUNTDOWN_MS;
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
type A = Parameters<typeof minesweeper.apply>[2];
function make(players = ['A', 'B'], opts: Partial<MinesweeperOptions> = {}, seed = 1): MinesweeperState {
return minesweeper.setup({ players, options: minesweeper.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 });
}
function act(s: MinesweeperState, p: string, a: A, now = START + 1000): MinesweeperState {
const v = minesweeper.validate(s, p, a, { now });
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
return minesweeper.apply(s, p, a, { rng: rng(), now }).state;
}
const reason = (s: MinesweeperState, p: string, a: A, now = START + 1000) => {
const v = minesweeper.validate(s, p, a, { now });
return v.ok ? 'ok' : v.reason;
};
const started = (players?: string[], opts?: Partial<MinesweeperOptions>, seed?: number) => minesweeper.apply(make(players, opts, seed), 'A', { type: 'tick' }, { rng: rng(), now: START }).state;
const safe = (s: MinesweeperState) => [...s.puzzle.field].flatMap((ch, i) => (ch !== '*' && s.boards.A!.open[i] !== '1' ? [i] : []));
const mines = (s: MinesweeperState) => [...s.puzzle.field].flatMap((ch, i) => (ch === '*' ? [i] : []));
describe('판 만들기', () => {
test('난이도별 크기·지뢰 수, 시작 칸 주변 3×3에는 지뢰 없음, 숫자 = 주변 지뢰 수, 같은 시드 = 같은 판', () => {
for (const level of ['beginner', 'intermediate', 'expert'] as const) {
for (let k = 1; k <= 20; k++) {
const p = makeField(SeededRng.fromSeed(seedN(k)), level);
const L = LEVELS[level];
expect(p.field).toHaveLength(L.rows * L.cols);
expect([...p.field].filter((c) => c === '*')).toHaveLength(L.mines);
expect(p.field[p.start]).toBe('0');
for (const j of around(p.rows, p.cols, p.start)) expect(p.field[j]).not.toBe('*');
for (let i = 0; i < p.field.length; i++) {
if (p.field[i] === '*') continue;
expect(Number(p.field[i])).toBe(around(p.rows, p.cols, i).filter((j) => p.field[j] === '*').length);
}
expect(makeField(SeededRng.fromSeed(seedN(k)), level)).toEqual(p);
}
}
});
test('모두 같은 판, 시작 칸과 그 주변이 열린 채로 시작, 카운트다운에는 판을 안 보여 줌', () => {
const s = make(['A', 'B', 'C']);
expect(new Set(Object.values(s.boards).map((b) => b.open)).size).toBe(1);
expect(s.boards.A!.open[s.puzzle.start]).toBe('1');
expect(s.boards.A!.opened).toBeGreaterThan(1);
expect(minesweeper.view(s, 'A').board).toBeNull();
expect(reason(s, 'A', { type: 'open', i: 0 }, T0 + 100)).toContain('곧 시작');
checkNoLeak(minesweeper, s, 'A', s.order);
});
});
describe('열기·깃발·한꺼번에 열기', () => {
test('안전한 칸을 열면 열리고(0이면 이어서), 내 판만 바뀜', () => {
let s = started();
const i = safe(s)[0]!;
s = act(s, 'A', { type: 'open', i });
expect(s.boards.A!.open[i]).toBe('1');
expect(s.boards.B!.open[i]).toBe('0');
expect(reason(s, 'A', { type: 'open', i })).toBe('이미 연 칸이에요.');
});
test('깃발: 꽂고 치우기, 깃발 칸은 열 수 없음, 연 칸에는 못 꽂음', () => {
let s = started();
const m = mines(s)[0]!;
s = act(s, 'A', { type: 'flag', i: m });
expect(minesweeper.view(s, 'A').board!.cells[m]).toBe('F');
expect(minesweeper.view(s, 'A').board!.flags).toBe(1);
expect(reason(s, 'A', { type: 'open', i: m })).toContain('깃발');
s = act(s, 'A', { type: 'flag', i: m });
expect(minesweeper.view(s, 'A').board!.cells[m]).toBe('#');
expect(reason(s, 'A', { type: 'flag', i: s.puzzle.start })).toContain('이미 연 칸');
});
test('지뢰를 밟으면 실패(시간 멈춤), 다른 사람이 푸는 동안에는 밟은 지뢰만 보이고 끝나면 모두 보임', () => {
let s = started();
const m = mines(s)[0]!;
s = act(s, 'A', { type: 'open', i: m }, START + 5000);
expect(s.status.A).toBe('failed');
expect(s.status.B).toBe('playing');
const v = minesweeper.view(s, 'A');
expect(v.board!.cells[m]).toBe('!');
// The other mines stay hidden from A while B still plays (A could pass them on).
expect(v.board!.cells).not.toContain('*');
expect(v.seats.find((x) => x.id === 'A')!.timeMs).toBe(5000);
const ended = act(s, 'B', { type: 'stop' }, START + 6000);
expect(ended.phase).toBe('ended');
expect([...minesweeper.view(ended, 'A').board!.cells].filter((c) => c === '*' || c === '!')).toHaveLength(s.puzzle.mines);
// 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('포기한 사람도 다른 사람이 푸는 동안에는 지뢰 위치를 받지 않아요', () => {
let s = started(['A', 'B']);
s = act(s, 'A', { type: 'stop' });
expect(s.status.A).toBe('done');
expect(minesweeper.view(s, 'A').board!.cells).not.toMatch(/[*!x]/);
});
test('제한 시간: 마감 tick으로 끝, 마감 뒤 거절, 아무도 못 풀면 연 칸 많은 사람이 이김', () => {
let s = started(['A', 'B'], { timeLimitSec: 180 });
const i = safe(s).find((j) => s.puzzle.field[j] !== '0')!;
s = act(s, 'A', { type: 'open', i });
const end = START + 180_000;
expect(minesweeper.deadline!(s)).toBe(end);
expect(reason(s, 'B', { type: 'open', i }, end)).toBe('시간이 다 됐어요.');
s = minesweeper.apply(s, 'A', { type: 'tick' }, { rng: rng(), now: end }).state;
expect(s.final!.endReason).toBe('time');
expect(s.final!.ranking[0]!.id).toBe('A');
expect(s.final!.summary).toBe('시간이 다 됐어요. 아무도 다 풀지 못했어요. 가장 많이 푼 사람이 이겼어요');
});
test('무제한: 끊긴 사람은 tick 한 번으로 포기 처리, 모두 끝나면 끝', () => {
let s = started(['A', 'B'], { timeLimitSec: null });
expect(minesweeper.deadline!(s)).toBeNull();
s = minesweeper.apply(s, 'B', { type: 'tick' }, { rng: rng(), now: START + 70_000 }).state;
expect(s.status.B).toBe('done');
s = act(s, 'A', { type: 'stop' }, START + 80_000);
expect(s.phase).toBe('ended');
expect(s.final!.summary).toContain('아무도 다 풀지 못했어요');
});
test('속도 제한: 1초에 15번까지', () => {
let s = started(['A']);
const cells = mines(s);
for (let k = 0; k < 15; k++) s = act(s, 'A', { type: 'flag', i: cells[k % cells.length]! }, START + 100 + k);
expect(reason(s, 'A', { type: 'flag', i: cells[0]! }, START + 200)).toBe('조금 천천히 해 주세요.');
expect(reason(s, 'A', { type: 'flag', i: cells[0]! }, START + 1200)).toBe('ok');
});
});
describe('무작위 대국', () => {
test('1·2·5·8명, 난이도 셋: 유출·JSON·결정성', () => {
for (let k = 1; k <= playoutSeeds(60); k++) {
for (const n of [1, 2, 5, 8]) {
const level = (['beginner', 'intermediate', 'expert'] as const)[k % 3]!;
const players = Array.from({ length: n }, (_, i) => `p${i}`);
const options = minesweeper.optionsSchema.parse({ level, timeLimitSec: k % 2 ? null : 180 });
const a = randomPlayout(minesweeper, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000 });
expect(a.finished).toBe(true);
const b = randomPlayout(minesweeper, { players, options, seed: seedN(k * 10 + n), maxSteps: 3000 });
expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState));
}
}
});
});

View File

@@ -0,0 +1,101 @@
/**
* 네모네모 로직 pictures (docs/games/nonogram.md §3). Hand-drawn, '#' filled, '.' empty. Every one has exactly one
* answer that line logic alone reaches (nonogram.test.ts checks each with ./solver), and no empty row or column.
* `color` paints the picture once it is solved.
*/
export interface Picture {
name: string;
color: string;
rows: string[];
}
export const PICTURES: Record<5 | 10 | 15, Picture[]> = {
5: [
{ name: '하트', color: '#ef4444', rows: ['.#.#.', '#####', '#####', '.###.', '..#..'] },
{ name: '집', color: '#c2410c', rows: ['..#..', '.###.', '#####', '.#.#.', '.###.'] },
{ name: '나무', color: '#16a34a', rows: ['..#..', '.###.', '#####', '..#..', '.###.'] },
{ name: '우산', color: '#7c3aed', rows: ['.###.', '#####', '..#..', '..#..', '.##..'] },
{ name: '별', color: '#eab308', rows: ['..#..', '#####', '.###.', '.#.#.', '#...#'] },
{ name: '화살표', color: '#2563eb', rows: ['..#..', '.###.', '#.#.#', '..#..', '..#..'] },
{ name: '음표', color: '#4f46e5', rows: ['..##.', '..#.#', '..#..', '###..', '###..'] },
{ name: '컵', color: '#a16207', rows: ['####.', '###.#', '###.#', '####.', '.##..'] },
{ name: '버섯', color: '#dc2626', rows: ['.###.', '#####', '#.#.#', '..#..', '.###.'] },
{ name: '고양이', color: '#f97316', rows: ['#...#', '#####', '#.#.#', '#####', '.###.'] },
{ name: '해', color: '#f59e0b', rows: ['#.#.#', '.###.', '#####', '.###.', '#.#.#'] },
],
10: [
{ name: '고양이', color: '#f97316', rows: ['.#......#.', '.##....##.', '.########.', '##########', '##.####.##', '##########', '###.##.###', '####..####', '.########.', '..######..'] },
{ name: '사과', color: '#dc2626', rows: ['.....#....', '....#.....', '..##.###..', '.########.', '##########', '##########', '##########', '.########.', '.########.', '..##..##..'] },
{ name: '물고기', color: '#0ea5e9', rows: ['....###...', '...#####..', '#.#######.', '##.####.##', '###.######', '###.######', '##.#######', '#.#######.', '...#####..', '....###...'] },
{ name: '오리', color: '#eab308', rows: ['...###....', '..#####...', '..##.###..', '..########', '...####...', '#..#####..', '##########', '##########', '.########.', '..######..'] },
{ name: '자동차', color: '#2563eb', rows: ['...#####..', '..##.#.##.', '.###.#.###', '##########', '##########', '##########', '##########', '.###..###.', '.###..###.', '..#....#..'] },
{ name: '로켓', color: '#64748b', rows: ['....##....', '...####...', '...####...', '..##..##..', '..##..##..', '..######..', '..######..', '.########.', '##.####.##', '##..##..##'] },
{ name: '꽃', color: '#ec4899', rows: ['..#.##.#..', '..######..', '..######..', '...####...', '....##....', '#...##...#', '##..##..##', '.##.##.##.', '..######..', '....##....'] },
{ name: '우산', color: '#7c3aed', rows: ['....##....', '..######..', '.########.', '##########', '##..##..##', '....##....', '....##....', '....##....', '.#..##....', '.####.....'] },
{ name: '집', color: '#c2410c', rows: ['....##....', '...####...', '..######..', '.########.', '##########', '.########.', '.#..##..#.', '.#..##..#.', '.#####..#.', '.#####..#.'] },
{ name: '하트', color: '#ef4444', rows: ['.##....##.', '####..####', '#.########', '##########', '##########', '.########.', '..######..', '...####...', '....##....', '....##....'] },
{ name: '컵', color: '#a16207', rows: ['..#..#....', '.#..#.....', '..#..#....', '#######...', '##########', '#######..#', '#######..#', '##########', '#######...', '.#####....'] },
{ name: '버섯', color: '#dc2626', rows: ['...####...', '.########.', '##..##..##', '##..##..##', '##########', '.########.', '...####...', '...####...', '...####...', '..######..'] },
{ name: '별', color: '#eab308', rows: ['....##....', '....##....', '...####...', '##########', '.########.', '..######..', '..######..', '.###..###.', '.##....##.', '##......##'] },
{ name: '음표', color: '#4f46e5', rows: ['...#######', '...#######', '...#.....#', '...#.....#', '...#.....#', '...#.....#', '.###...###', '####..####', '####..####', '.##....##.'] },
{ name: '나무', color: '#16a34a', rows: ['....##....', '...####...', '..######..', '...####...', '..######..', '.########.', '##########', '....##....', '....##....', '..######..'] },
],
15: [
{
name: '고양이',
color: '#f97316',
rows: ['.#...........#.', '.##.........##.', '.###.......###.', '.#############.', '###############', '###############', '###..#####..###', '###..#####..###', '###############', '######...######', '#######.#######', '#####.###.#####', '###############', '.#############.', '...#########...'],
},
{
name: '로켓',
color: '#64748b',
rows: ['.......#.......', '......###......', '.....#####.....', '.....#####.....', '....###.###....', '....##...##....', '....###.###....', '....#######....', '....#######....', '....#######....', '...#########...', '..###########..', '#####.###.#####', '###...###...###', '......#.#......'],
},
{
name: '자동차',
color: '#2563eb',
rows: ['.....#####.....', '....#..#..#....', '...##..#..##...', '..###..#..###..', '.#############.', '###############', '#.###########.#', '###############', '###############', '###...###...###', '..###.....###..', '.#####...#####.', '.#####...#####.', '..###.....###..', '###############'],
},
{
name: '집',
color: '#c2410c',
rows: ['.......#.......', '......###.##...', '.....#######...', '....#######....', '...#########...', '..###########..', '.#############.', '###############', '..###########..', '..##..#######..', '..##..##...##..', '..######...##..', '..######...##..', '..######...##..', '..######...##..'],
},
{
name: '나무',
color: '#16a34a',
rows: ['.......#.......', '......###......', '.....#####.....', '....#######....', '......###......', '.....#####.....', '...#########...', '..###########..', '.....#####.....', '...#########...', '.#############.', '###############', '......###......', '......###......', '....#######....'],
},
{
name: '오리',
color: '#eab308',
rows: ['......####.....', '.....######....', '.....###.##....', '..#########....', '.##########....', '......#####....', '......####...#.', '....#######.##.', '.#############.', '###############', '###.....#######', '####...########', '###############', '.#############.', '...#########...'],
},
{
name: '꽃',
color: '#ec4899',
rows: ['.....#####.....', '..##.#####.##..', '.####.###.####.', '.#####...#####.', '..###.....###..', '.#####...#####.', '.####.###.####.', '..##.#####.##..', '.....#####.....', '.......#.......', '.###...#...###.', '#####..#..#####', '.#####.#.#####.', '...#########...', '.......#.......'],
},
{
name: '물고기',
color: '#0ea5e9',
rows: ['...........#...', '........#......', '.......###.....', '......######...', '.....########..', '#...##########.', '##.#######.####', '###############', '###############', '##.############', '#...##########.', '.....########..', '......######...', '.......###.....', '........#......'],
},
{
name: '우산',
color: '#7c3aed',
rows: ['.......#.......', '....#######....', '..###########..', '.#############.', '###############', '###############', '##..#..#..#..##', '.......#.......', '.......#.......', '.......#.......', '.......#.......', '.......#.......', '..#....#.......', '..##..##.......', '...####........'],
},
{
name: '컵',
color: '#a16207',
rows: ['...#...#...#...', '....#...#...#..', '...#...#...#...', '.###########...', '.##############', '.###########..#', '.###########..#', '.###########..#', '.##############', '.###########...', '.###########...', '..#########....', '...#######.....', '###############', '..###########..'],
},
{
name: '별',
color: '#eab308',
rows: ['.......#.......', '......###......', '......###......', '.....#####.....', '###############', '.#############.', '..###########..', '...#########...', '....#######....', '...#########...', '...####.####...', '..####...####..', '..###.....###..', '.##.........##.', '.#...........#.'],
},
],
};

View File

@@ -0,0 +1,65 @@
/** 네모네모 로직 computers (docs/games/nonogram.md §13): never refused, finish the race, stronger levels are faster. */
import { describe, expect, test } from 'bun:test';
import { seedN } from '@bg/engine';
import { liveBotPlayout } from '../bots/live-playout';
import { deductions, nonogramBot } from './bot';
import { makePicture, nonogram, type NonogramBoardView, type NonogramState } from './index';
const isBot = (p: string) => p.startsWith('bot:');
describe('nonogram · 한 판 전체', () => {
test('사람(가만히) + 컴퓨터, 컴퓨터끼리만, 세 크기: 거절 0, 모두 끝까지, 빠른 판단', () => {
for (const n of [2, 4]) {
for (const humans of [1, 0]) {
const players = Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i + 1}:n${n}${i}`));
for (const size of [5, 10, 15] as const) {
const r = liveBotPlayout(nonogram, nonogramBot, {
players,
options: nonogram.optionsSchema.parse({ size, timeLimitSec: humans ? 1200 : null }),
seed: seedN(n * 10 + humans + size),
isBot,
levelOf: (p) => 1 + ((p.length * 7 + size) % 60),
});
expect(r.finished).toBe(true);
expect(r.rejected).toEqual([]);
expect(r.maxBotMs).toBeLessThan(50);
const s = r.state as NonogramState;
// Without a person and without a limit every computer solves it.
if (!humans) for (const p of players) expect(s.status[p]).toBe('solved');
}
}
}
});
test('강한 컴퓨터는 10×10을 기본 제한 시간 안에 풀고, 약한 컴퓨터보다 대체로 빨라요', () => {
let strongFaster = 0;
for (let k = 0; k < 8; k++) {
const r = liveBotPlayout(nonogram, nonogramBot, {
players: ['bot:1:easy', 'bot:2:hard'],
options: nonogram.optionsSchema.parse({}),
seed: seedN(700 + k),
isBot,
levelOf: (p) => (p.endsWith('easy') ? 3 : 58),
});
const s = r.state as NonogramState;
expect(s.status['bot:2:hard']).toBe('solved');
const hard = s.final!.ranking.find((x) => x.id === 'bot:2:hard')!;
const easy = s.final!.ranking.find((x) => x.id === 'bot:1:easy')!;
expect(hard.timeMs!).toBeLessThan(1_200_000);
if (easy.status !== 'solved' || hard.timeMs! < easy.timeMs!) strongFaster++;
}
expect(strongFaster).toBeGreaterThanOrEqual(7);
});
});
describe('nonogram · 줄 논리로 찾는 칸', () => {
test('겹치는 칸은 채우기, 다 채운 줄의 나머지는 X', () => {
const p = makePicture(['#####', '#...#', '#...#', '#...#', '#####'], '테스트', '#000');
const v: NonogramBoardView = { size: 5, rows: p.rows, cols: p.cols, marks: '0'.repeat(25), hints: 0, lastHint: null, answer: null };
const d = deductions(v);
expect(d).toContainEqual({ cells: [0, 1, 2, 3, 4], value: 1 });
expect(d.every((x) => x.cells.every((i) => p.solution[i] === (x.value === 1 ? '#' : '.')))).toBe(true);
v.marks = '11111' + '1000' + '1' + '0'.repeat(15);
expect(deductions(v)).toContainEqual({ cells: [6, 7, 8], value: 2 });
});
});

View File

@@ -0,0 +1,74 @@
/**
* 네모네모 로직 computers (docs/games/nonogram.md §13). They only read their own screen (the clues and their marks).
* - Line logic (./solver) on each row and column finds the cells it forces; one paint = one such run of cells in one
* line (filled or X). A stronger computer takes the longest run of filled cells first, a weaker one any run.
* - A weak computer now and then fills a cell it has not worked out (a slip) and clears it again a few moves later.
* - Time per paint: about 6 s at level 1 … 1.2 s at level 60, a little longer on bigger pictures.
*/
import { raceBot } from '../race/bot';
import type { MarkValue, NonogramBoardView, NonogramMove } from './index';
import { lineCells, solveLine, type Known } from './solver';
type V = NonogramBoardView;
export interface Deduction {
cells: number[];
value: 1 | 2;
}
/** Every run of not-yet-marked cells that one line forces. `ignore` is treated as not known (a cell I am unsure of). */
export function deductions(v: V, ignore: number | null = null): Deduction[] {
const n = v.size;
const known: Known[] = Array.from(v.marks, (ch, i) => (i === ignore ? -1 : ch === '1' ? 1 : ch === '2' ? 0 : -1));
const clues = [...v.rows, ...v.cols];
const out: Deduction[] = [];
for (let line = 0; line < 2 * n; line++) {
const cells = lineCells(n, line);
const solved = solveLine(clues[line]!, cells.map((i) => known[i]!));
if (!solved) continue;
let run: Deduction | null = null;
for (let t = 0; t <= n; t++) {
const i = cells[t];
const value = t < n && known[i!] === -1 && solved[t] !== -1 ? (solved[t] === 1 ? 1 : 2) : null;
if (run && value === run.value) run.cells.push(i!);
else {
if (run) out.push(run);
run = value ? { cells: [i!], value } : null;
}
}
}
return out;
}
export const nonogramBot = raceBot<V, NonogramMove>((v, skill, random, memory) => {
const step = (6000 - 4800 * skill) * (0.6 + 0.04 * v.size) * (0.6 + 0.8 * random());
const slip = typeof memory.slip === 'number' && v.marks[memory.slip] === '1' ? memory.slip : null;
if (slip !== null && typeof memory.slipIn === 'number') {
memory.slipIn -= 1;
if (memory.slipIn <= 0) {
memory.slip = null;
return { move: { type: 'paint', cells: [slip], value: 0 }, ms: step * 0.6 };
}
}
if (slip === null && random() < 0.15 * (1 - skill)) {
const open: number[] = [];
for (let i = 0; i < v.marks.length; i++) if (v.marks[i] === '0') open.push(i);
if (open.length > 1) {
memory.slip = open[Math.floor(random() * open.length)]!;
memory.slipIn = 2 + Math.floor(random() * 3);
return { move: { type: 'paint', cells: [memory.slip as number], value: 1 }, ms: step };
}
}
const found = deductions(v, slip);
if (!found.length) return { move: null, ms: 2000 };
let pick = found[Math.floor(random() * found.length)]!;
if (random() < 0.4 + 0.6 * skill) pick = found.reduce((a, b) => (b.value < a.value || (b.value === a.value && b.cells.length > a.cells.length) ? b : a));
let cells = pick.cells;
if (slip !== null && cells.includes(slip)) {
// Line logic just settled the cell I slipped on: it was right after all (keep it) or gets its X now.
memory.slip = null;
if (pick.value === 1) cells = cells.filter((i) => i !== slip);
if (!cells.length) return { move: null, ms: step * 0.3 };
}
return { move: { type: 'paint', cells, value: pick.value as MarkValue }, ms: step };
});

View File

@@ -0,0 +1,169 @@
/**
* 네모네모 로직 (docs/games/nonogram.md). Everyone solves the same picture on their own copy (race frame, ../race).
* Each row and column has number clues (the lengths of its filled runs, in order); fill the cells so every line
* matches. Players only mark their own board (fill / X / clear); nothing tells them a cell is right or wrong.
* Progress counts lines whose current filled cells match their clue, which anyone could check from the clues, so it
* gives nothing of the answer away.
*/
import { z } from 'zod';
import type { GameEvent } from '@bg/engine';
import { lit, makeRaceGame, timeLimitOption, type RaceState, type RaceView } from '../race';
import { PICTURES } from './bank';
import { clueOf, colCells, rowCells, sameClue } from './solver';
export { COUNTDOWN_MS, formatElapsed } from '../race';
export type NonogramSize = 5 | 10 | 15;
export const SIZE_NAME: Record<NonogramSize, string> = { 5: '쉬움', 10: '보통', 15: '어려움' };
export const nonogramOptionsSchema = z.object({
size: lit<NonogramSize>(5, 10, 15)
.default(10)
.meta({ title: '크기', labels: { 5: '5×5 쉬움', 10: '10×10 보통', 15: '15×15 어려움' } }),
hints: z.boolean().default(true).meta({ title: '힌트 쓰기(틀렸거나 모르는 칸 하나를 알려 줌)' }),
timeLimitSec: timeLimitOption([300, 600, 1200, 1800], 1200),
});
export type NonogramOptions = z.infer<typeof nonogramOptionsSchema>;
/** Mark values: 0 empty (not decided), 1 filled, 2 X (sure it is empty). */
export type MarkValue = 0 | 1 | 2;
const cell = z.number().int().min(0).max(224);
const moveSchemas = [
z.object({ type: z.literal('paint'), cells: z.array(cell).min(1).max(15), value: lit<MarkValue>(0, 1, 2) }),
z.object({ type: z.literal('hint') }),
] as const;
export type NonogramMove = { type: 'paint'; cells: number[]; value: MarkValue } | { type: 'hint' };
export interface NonogramPuzzle {
size: NonogramSize;
name: string;
color: string;
/** Per cell '#' filled or '.' empty, row-major. */
solution: string;
rows: number[][];
cols: number[][];
}
export interface NonogramBoard {
/** Per cell '0' empty, '1' filled, '2' X. */
marks: string;
hints: number;
/** The cell the last hint set, or null. */
lastHint: number | null;
}
export interface NonogramBoardView {
size: NonogramSize;
rows: number[][];
cols: number[][];
marks: string;
hints: number;
lastHint: number | null;
/** Only once I am finished (or the game is over): the picture. */
answer: { solution: string; name: string; color: string } | null;
}
export type NonogramState = RaceState<NonogramPuzzle, NonogramBoard, NonogramOptions>;
export type NonogramView = RaceView<NonogramBoardView, NonogramOptions>;
export function makePicture(rows: readonly string[], name: string, color: string): NonogramPuzzle {
const size = rows.length as NonogramSize;
const solution = rows.join('');
return {
size,
name,
color,
solution,
rows: rows.map((r) => clueOf(r)),
cols: Array.from({ length: size }, (_, c) => clueOf(colCells(size, c).map((i) => solution[i]!))),
};
}
/** Lines (rows, then columns) whose filled cells right now match their clue. */
export function matchedLines(size: number, rows: readonly number[][], cols: readonly number[][], marks: string): boolean[] {
const filled = (cells: number[]) => cells.map((i) => marks[i]!);
return [...rows.map((clue, r) => sameClue(clueOf(filled(rowCells(size, r))), clue)), ...cols.map((clue, c) => sameClue(clueOf(filled(colCells(size, c))), clue))];
}
const isSolved = (p: NonogramPuzzle, marks: string) => [...p.solution].every((ch, i) => (ch === '#') === (marks[i] === '1'));
const setCells = (marks: string, cells: readonly number[], ch: string) => {
const m = marks.split('');
for (const i of cells) m[i] = ch;
return m.join('');
};
/** What a hint would set the cell to: filled, or X for an empty one. */
const rightMark = (p: NonogramPuzzle, i: number) => (p.solution[i] === '#' ? '1' : '2');
export const nonogram = makeRaceGame<NonogramPuzzle, NonogramBoard, NonogramMove, NonogramBoardView, NonogramOptions>({
id: 'nonogram',
nameKo: '네모네모 로직',
optionsSchema: nonogramOptionsSchema,
moveSchemas: moveSchemas as never,
makePuzzle(rng, o) {
const list = PICTURES[o.size];
const pic = list[rng.int(list.length)]!;
return makePicture(pic.rows, pic.name, pic.color);
},
startBoard: (p) => ({ marks: '0'.repeat(p.size * p.size), hints: 0, lastHint: null }),
checkMove(p, b, m, o) {
if (m.type === 'hint') return o.hints ? null : '이 방은 힌트를 쓰지 않아요.';
const n = p.size;
if (m.cells.some((i) => i >= n * n)) return '판 밖의 칸이에요.';
if (new Set(m.cells).size !== m.cells.length) return '같은 칸이 두 번 들어 있어요.';
const r0 = Math.floor(m.cells[0]! / n);
const c0 = m.cells[0]! % n;
if (!m.cells.every((i) => Math.floor(i / n) === r0) && !m.cells.every((i) => i % n === c0)) return '한 줄(가로 또는 세로)에 있는 칸만 한 번에 칠할 수 있어요.';
if (m.cells.every((i) => b.marks[i] === String(m.value))) return '바뀌는 칸이 없어요.';
return null;
},
applyMove(p, b, m, { rng }) {
let next: NonogramBoard;
const events: GameEvent[] = [];
if (m.type === 'hint') {
const wrong: number[] = [];
for (let i = 0; i < p.solution.length; i++) if (b.marks[i] !== rightMark(p, i)) wrong.push(i);
if (!wrong.length) return { board: b };
const i = wrong[rng.int(wrong.length)]!;
next = { marks: setCells(b.marks, [i], rightMark(p, i)), hints: b.hints + 1, lastHint: i };
events.push({ type: 'hint', i });
} else next = { ...b, marks: setCells(b.marks, m.cells, String(m.value)) };
return { board: next, outcome: isSolved(p, next.marks) ? 'solved' : undefined, events };
},
boardView: (p, b, reveal) => ({
size: p.size,
rows: p.rows,
cols: p.cols,
marks: b.marks,
hints: b.hints,
lastHint: b.lastHint,
answer: reveal ? { solution: p.solution, name: p.name, color: p.color } : null,
}),
progress: (p, b) => matchedLines(p.size, p.rows, p.cols, b.marks).filter(Boolean).length,
progressText: (p, b) => `맞는 줄 ${matchedLines(p.size, p.rows, p.cols, b.marks).filter(Boolean).length}/${p.size * 2}`,
extraText: (b) => (b.hints ? ` · 힌트 ${b.hints}번` : ''),
/** Test helper: a few right cells, one wrong fill, one X, an X over a whole row, and a hint. */
legalMoves(p, b, o) {
const out: NonogramMove[] = [];
for (let i = 0; i < p.solution.length && out.length < 3; i++) {
const want = p.solution[i] === '#';
if (want && b.marks[i] !== '1') out.push({ type: 'paint', cells: [i], value: 1 });
else if (!want && b.marks[i] === '1') out.push({ type: 'paint', cells: [i], value: 0 });
}
const wrong = [...p.solution].findIndex((ch, i) => ch === '.' && b.marks[i] === '0');
if (wrong >= 0) out.push({ type: 'paint', cells: [wrong], value: 1 }, { type: 'paint', cells: [wrong], value: 2 });
const row = rowCells(p.size, Math.floor((b.hints * 7 + out.length) % p.size)).filter((i) => b.marks[i] !== '2');
if (row.length) out.push({ type: 'paint', cells: row, value: 2 });
if (o.hints) out.push({ type: 'hint' });
return out;
},
secrets: (p) => [p.solution, p.name],
});

View File

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

View File

@@ -0,0 +1,121 @@
/**
* 네모네모 로직 line logic (docs/games/nonogram.md §8, §13). A cell is 1 (filled), 0 (empty) or -1 (not known yet).
* `solveLine` finds every cell one row/column forces from its clue and what is already known; `solveGrid` repeats
* that over all rows and columns until nothing changes. Every bank picture must come out complete this way (so it has
* exactly one answer and needs no guessing), and the computer players think with the same line logic.
*/
export type Known = 1 | 0 | -1;
/** Run lengths of filled cells ('#' or 1); an empty line is []. */
export function clueOf(line: ArrayLike<string | number>): number[] {
const out: number[] = [];
let run = 0;
for (let i = 0; i < line.length; i++) {
const on = line[i] === '#' || line[i] === 1 || line[i] === '1';
if (on) run++;
else if (run) {
out.push(run);
run = 0;
}
}
if (run) out.push(run);
return out;
}
export const sameClue = (a: readonly number[], b: readonly number[]) => a.length === b.length && a.every((x, i) => x === b[i]);
/**
* Every cell the clue forces, given what is known: the new line (known cells kept), or null when no arrangement fits.
* Prefix / suffix DP over "cells so far, runs placed so far", split by whether the last cell is filled.
*/
export function solveLine(clue: readonly number[], line: readonly Known[]): Known[] | null {
const n = line.length;
const k = clue.length;
const notOn = (i: number) => line[i] !== 1;
// runFits[j][s]: run j can sit on cells s … s+len-1 (none known empty).
const runFits = clue.map((len) => {
const out: boolean[] = [];
for (let s = 0; s + len <= n; s++) {
let okRun = true;
for (let t = s; t < s + len && okRun; t++) if (line[t] === 0) okRun = false;
out[s] = okRun;
}
return out;
});
// Forward: E[i][j] = cells [0,i) hold runs 0..j-1 exactly and cell i-1 is empty (or i = 0); F[i][j] = … ends a run at i-1.
const grid = () => Array.from({ length: n + 1 }, () => new Array<boolean>(k + 1).fill(false));
const E = grid();
const F = grid();
E[0]![0] = true;
for (let i = 0; i <= n; i++)
for (let j = 0; j <= k; j++) {
const e = E[i]![j]!;
const f = F[i]![j]!;
if (!e && !f) continue;
if (i < n && notOn(i)) E[i + 1]![j] = true;
if (e && j < k && runFits[j]![i]) F[i + clue[j]!]![j + 1] = true;
}
if (!E[n]![k] && !F[n]![k]) return null;
// Backward: E2[i][j] = cells [i,n) hold runs j..k-1 exactly and cell i is empty (or i = n); F2[i][j] = run j starts at i.
const E2 = grid();
const F2 = grid();
E2[n]![k] = true;
for (let i = n; i >= 0; i--)
for (let j = k; j >= 0; j--) {
if (i < n && notOn(i) && (E2[i + 1]![j] || F2[i + 1]![j])) E2[i]![j] = true;
if (j < k && runFits[j]![i]) {
const end = i + clue[j]!;
if (end === n ? j + 1 === k : E2[end]![j + 1]) F2[i]![j] = true;
}
}
const canEmpty = new Array<boolean>(n).fill(false);
const canFill = new Array<boolean>(n).fill(false);
for (let x = 0; x < n; x++) {
if (!notOn(x)) continue;
for (let j = 0; j <= k && !canEmpty[x]; j++) if ((E[x]![j] || F[x]![j]) && (E2[x + 1]![j] || F2[x + 1]![j])) canEmpty[x] = true;
}
for (let j = 0; j < k; j++) {
const len = clue[j]!;
for (let s = 0; s + len <= n; s++) {
if (!E[s]![j] || !F2[s]![j]) continue;
for (let t = s; t < s + len; t++) canFill[t] = true;
}
}
const out: Known[] = [];
for (let x = 0; x < n; x++) {
if (!canFill[x] && !canEmpty[x]) return null;
out.push(line[x] !== -1 ? line[x]! : canFill[x] && !canEmpty[x] ? 1 : canEmpty[x] && !canFill[x] ? 0 : -1);
}
return out;
}
export const rowCells = (size: number, r: number) => Array.from({ length: size }, (_, c) => r * size + c);
export const colCells = (size: number, c: number) => Array.from({ length: size }, (_, r) => r * size + c);
/** Lines 0..size-1 are the rows, size..2·size-1 the columns. */
export const lineCells = (size: number, line: number) => (line < size ? rowCells(size, line) : colCells(size, line - size));
/** Line logic to a fixed point. Returns the grid (row-major, -1 where unknown) or null on a contradiction. */
export function solveGrid(size: number, rows: readonly number[][], cols: readonly number[][], start?: readonly Known[]): Known[] | null {
const g: Known[] = start ? [...start] : new Array<Known>(size * size).fill(-1);
const clues = [...rows, ...cols];
let dirty = new Set(clues.map((_, i) => i));
while (dirty.size) {
const next = new Set<number>();
for (const line of dirty) {
const cells = lineCells(size, line);
const solved = solveLine(clues[line]!, cells.map((i) => g[i]!));
if (!solved) return null;
cells.forEach((i, t) => {
if (g[i] === -1 && solved[t] !== -1) {
g[i] = solved[t]!;
const r = Math.floor(i / size);
const c = i % size;
next.add(line < size ? size + c : r);
}
});
}
dirty = next;
}
return g;
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,56 @@
/** 스도쿠 computers (docs/games/sudoku.md §13): never refused, finish the race, stronger levels are faster. */
import { describe, expect, test } from 'bun:test';
import { seedN } from '@bg/engine';
import { liveBotPlayout } from '../bots/live-playout';
import { sudokuBot } from './bot';
import { sudoku, type SudokuState } from './index';
const isBot = (p: string) => p.startsWith('bot:');
describe('sudoku · 한 판 전체', () => {
test('사람(가만히) + 컴퓨터, 컴퓨터끼리만, 세 난이도: 거절 0, 모두 끝까지, 빠른 판단', () => {
for (const n of [2, 4]) {
for (const humans of [1, 0]) {
const players = Array.from({ length: n }, (_, i) => (i < humans ? `human${i}` : `bot:${i + 1}:s${n}${i}`));
for (const difficulty of ['easy', 'normal', 'hard'] as const) {
const r = liveBotPlayout(sudoku, sudokuBot, {
players,
options: sudoku.optionsSchema.parse({ difficulty, timeLimitSec: humans ? 1800 : null }),
seed: seedN(n * 10 + humans),
isBot,
levelOf: (p) => 1 + ((p.length * 7) % 60),
});
expect(r.finished).toBe(true);
expect(r.rejected).toEqual([]);
expect(r.maxBotMs).toBeLessThan(50);
const s = r.state as SudokuState;
for (const p of players) if (isBot(p) && !humans) expect(s.status[p]).toBe('solved');
for (const p of players) if (isBot(p)) expect(s.boards[p]!.hints).toBe(0);
}
}
}
});
test('강한 컴퓨터는 쉬움을 기본 제한 시간(30분) 안에 풀고, 약한 컴퓨터보다 빨라요', () => {
let faster = 0;
const times = { weak: 0, strong: 0 };
for (let k = 0; k < 8; k++) {
const r = liveBotPlayout(sudoku, sudokuBot, {
players: ['bot:1:weak', 'bot:2:strong'],
options: sudoku.optionsSchema.parse({}),
seed: seedN(700 + k),
isBot,
levelOf: (p) => (p.endsWith('weak') ? 3 : 58),
});
const s = r.state as SudokuState;
expect(s.status['bot:2:strong']).toBe('solved');
const t = (p: string) => s.finishedAt[p]! - s.countdownEndsAt;
expect(t('bot:2:strong')).toBeLessThan(600_000);
times.weak += s.status['bot:1:weak'] === 'solved' ? t('bot:1:weak') : 1_800_000;
times.strong += t('bot:2:strong');
if (s.status['bot:1:weak'] !== 'solved' || t('bot:2:strong') < t('bot:1:weak')) faster++;
}
expect(faster).toBeGreaterThanOrEqual(7);
expect(times.strong * 2).toBeLessThan(times.weak);
});
});

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,75 @@
/** 타자 대결 computers (docs/games/typing.md §10): never refused, finish every mode, stronger levels type faster. */
import { describe, expect, test } from 'bun:test';
import { seedN } from '@bg/engine';
import { liveBotPlayout } from '../bots/live-playout';
import { botKpm, skillOf, typingBot, withTypo } from './bot';
import { typing, type TypingOptions, type TypingState } from './index';
const isBot = (p: string) => p.startsWith('bot:');
const opts = (o: Partial<TypingOptions>) => typing.optionsSchema.parse({ rounds: 2, ...o });
describe('한 판 전체', () => {
const modes: Partial<TypingOptions>[] = [
{},
{ category: 'word', lang: 'en' },
{ mode: 'survival' },
{ mode: 'survival', elimination: 'sentence' },
{ mode: 'survival', elimination: 'interval', intervalSec: 10 },
{ mode: 'survival', elimination: 'deadline' },
{ mode: 'speed', category: 'long' },
{ mode: 'accuracy' },
{ mode: 'timeAttack', attackSec: 30 },
{ mode: 'practice', category: 'word' },
];
test.each(modes.map((m) => [JSON.stringify(m), m] as const))('%s: 사람 1명(가만히) + 컴퓨터, 컴퓨터끼리만: 거절 0, 끝까지', (_, m) => {
// 연습 has no clock: an idle person would keep it open (as in a room), so only the computers play it here.
for (const humans of m.mode === 'practice' ? [0] : [1, 0]) {
const players = ['human0', 'bot:2:a', 'bot:3:b', 'bot:4:c'].slice(humans ? 0 : 1);
const r = liveBotPlayout(typing, typingBot, { players, options: opts(m), seed: seedN(humans + 3), isBot, levelOf: (p) => (p.endsWith('a') ? 5 : p.endsWith('b') ? 30 : 58) });
expect(r.finished).toBe(true);
expect(r.rejected).toEqual([]);
expect(r.maxBotMs).toBeLessThan(20);
const s = r.state as TypingState;
const keys = (p: string) => s.totals[p]!.keys;
if (humans) expect(keys('human0')).toBe(0);
for (const p of players.filter(isBot)) if (m.mode !== 'survival') expect(keys(p)).toBeGreaterThan(0);
}
});
test('레벨이 높을수록 빨라요: 타수 비교에서 어려움 > 보통 > 쉬움(여러 판 평균)', () => {
const sum: Record<string, number> = { e: 0, n: 0, h: 0 };
for (let i = 0; i < 6; i++) {
const players = ['bot:1:e', 'bot:2:n', 'bot:3:h'];
const r = liveBotPlayout(typing, typingBot, {
players,
options: opts({ mode: 'speed', rounds: 1 }),
seed: seedN(40 + i),
isBot,
levelOf: (p) => ({ e: 5, n: 30, h: 58 })[p.at(-1)!]!,
});
const s = r.state as TypingState;
for (const p of players) sum[p.at(-1)!]! += s.rounds[0]!.rows.find((x) => x.id === p)!.kpm;
}
expect(sum.h!).toBeGreaterThan(sum.n!);
expect(sum.n!).toBeGreaterThan(sum.e!);
});
});
describe('parts', () => {
test('speed by level', () => {
expect(botKpm(skillOf(1), 'ko')).toBe(120);
expect(botKpm(skillOf(60), 'ko')).toBe(620);
expect(botKpm(skillOf(60), 'en')).toBe(500);
});
test('a typo changes exactly one letter', () => {
let n = 0;
const r = () => ((n = (n * 9301 + 49297) % 233280), n / 233280);
for (const t of ['가는 말이 고와야 오는 말이 곱다.', 'apple']) {
const w = withTypo(t, r);
expect(w).not.toBe(t);
expect([...w].length).toBe([...t].length);
expect([...w].filter((c, i) => c !== [...t][i]).length).toBe(1);
}
});
});

View File

@@ -0,0 +1,89 @@
/**
* 타자 대결 computer players (docs/games/typing.md §10). A live bot like 사과 게임's: it types on its own timer, sends
* its progress now and then (so its bar moves like a person's) and presses Enter when it has typed the whole item.
* It only reads its own screen (`view`).
*
* The level (1~60) sets how it types, like a person getting better:
* - speed: about 120타 a minute at level 1 … 620타 at level 60 (English: 100 … 500 letters a minute),
* - a moment to read before typing (0.9 s … 0.35 s),
* - typos: a weak computer often makes one in a sentence; a strong one rarely. In 가장 먼저 입력 and 서바이벌 a typo
* is noticed when Enter is refused, then fixed; in the other modes it stays in the line (lower accuracy).
* The computer's own pace (`persona.pace`) makes some a little quicker or slower than others of the same level.
*/
import type { LiveBotDecision, LiveBotInput } from '../bots/types';
import { keyCount } from './keys';
import type { TypingClientAction, TypingView } from './types';
type In = LiveBotInput<TypingView>;
const DEFAULT_LEVEL = 30;
export const skillOf = (level: number | undefined): number => Math.max(0, Math.min(1, ((level ?? DEFAULT_LEVEL) - 1) / 59));
/** Keystrokes a minute at this skill (before the computer's own pace). */
export const botKpm = (skill: number, lang: 'ko' | 'en') => (lang === 'ko' ? 120 + 500 * skill : 100 + 400 * skill);
/** One wrong letter somewhere in the middle of the text. */
export function withTypo(text: string, random: () => number): string {
const chars = [...text];
if (!chars.length) return 'ㅋ';
const i = Math.floor(random() * chars.length);
const ko = /[가-힣]/.test(text);
const pool = ko ? '가나다라마바사아자차카타파하' : 'abcdefghijklmnopqrstuvwxyz';
let c = pool[Math.floor(random() * pool.length)]!;
if (c === chars[i]) c = ko ? '흐' : 'q';
chars[i] = c;
return chars.join('');
}
interface Plan {
key: string;
/** When typing (after reading) began, when it will be done. */
from: number;
doneAt: number;
typo: boolean;
}
export function typingBot({ me, view: v, now, random, persona, level, memory }: In): LiveBotDecision<TypingClientAction> {
if (v.phase === 'ended') return { action: null, next: 10_000 };
if (v.phase !== 'playing') return { action: null, next: Math.max(100, (v.phaseEndsAt ?? now + 1000) - now + 60) };
const seat = v.seats.find((s) => s.id === me);
if (!seat || !seat.alive || seat.finished) return { action: null, next: 1500 };
const item = v.upcoming[0];
const shared = v.flow === 'shared';
if (!item) return { action: null, next: shared ? Math.max(100, v.curAt - now + 60) : 1000 };
if (shared && seat.solved) return { action: null, next: 700 };
const skill = skillOf(level);
const key = `${v.round}:${item.idx}`;
let plan = memory.plan as Plan | undefined;
if (!plan || plan.key !== key) {
const speed = botKpm(skill, v.options.lang) / (0.75 + 0.25 * persona.pace) * (0.85 + 0.3 * random());
const read = (900 - 550 * skill) * (0.7 + 0.6 * random());
const start = shared ? Math.max(now, v.curAt) : now;
const keys = keyCount(item.text);
const typoChance = Math.min(0.7, (0.35 - 0.31 * skill) * Math.max(0.3, keys / 40));
plan = { key, from: start + read, doneAt: start + read + (keys * 60_000) / speed, typo: random() < typoChance };
memory.plan = plan;
}
if (now < plan.doneAt) {
const frac = Math.max(0, Math.min(1, (now - plan.from) / Math.max(1, plan.doneAt - plan.from)));
const chars = [...item.text];
// 연습 times a line from its first key, so that key goes out as soon as it is typed (as a person's screen does).
const practice = v.options.mode === 'practice';
const typed = chars.slice(0, Math.max(practice && now >= plan.from ? 1 : 0, Math.floor(chars.length * frac))).join('');
let wait = Math.min(Math.round(350 + random() * 300), Math.max(60, Math.ceil(plan.doneAt - now)));
if (practice && now < plan.from) wait = Math.min(wait, Math.max(1, Math.ceil(plan.from - now)));
return typed ? { action: { type: 'progress', item: item.idx, text: typed }, next: wait } : { action: null, next: wait };
}
if (plan.typo) {
const text = withTypo(item.text, random);
if (shared) {
// Enter is refused: it looks for the mistake and fixes it.
plan.typo = false;
plan.from = now;
plan.doneAt = now + 500 + (1600 - 1000 * skill) * (0.6 + 0.8 * random());
return { action: { type: 'submit', item: item.idx, text }, next: Math.ceil(plan.doneAt - now) };
}
return { action: { type: 'submit', item: item.idx, text }, next: 120 };
}
return { action: { type: 'submit', item: item.idx, text: item.text }, next: shared ? 600 : 120 };
}

View File

@@ -0,0 +1,989 @@
/**
* 타자 대결 (docs/games/typing.md). Pure and deterministic; state is JSON; time only via ctx.now.
* Everyone types the same seeded texts. Two flows:
* - shared (가장 먼저 입력, 서바이벌 except 시간별): one item at a time for everybody; it closes when it is decided,
* then the next opens after a short gap;
* - lane (타수 비교, 정확도 대결, 타임어택, 서바이벌 시간별, 연습): each player goes through the round's items on their own.
* 연습 is one round without a clock or points, like 한컴 타자연습: a set of sentences / words, or one long text whole.
* What people type so far streams as `progress` (others see a bar); Enter is `submit`.
*/
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng, type Validation } from '@bg/engine';
import { accuracy, correctKeys, keyCount, kpm, minTypingMs, normalize, MAX_KPM, REACTION_MS } from './keys';
import { TOPIC_BY_ID, topicsFor, wrapLines, type Topic } from './texts';
import {
typingActionSchema,
typingOptionsSchema,
type Flow,
type LastItem,
type OutReason,
type RoundResult,
type RoundSeat,
type SeatTotals,
type SeatView,
type TypingAction,
type TypingFinal,
type TypingOptions,
type TypingState,
type TypingView,
} from './types';
export * from './types';
export * from './keys';
export { TOPICS, TOPIC_BY_ID, topicsFor, wrapLine, wrapLines, type Topic } from './texts';
type S = TypingState;
type A = TypingAction;
export const MAX_PLAYERS = 8;
export const COUNTDOWN_MS = 3000;
/** Shared items: pause after one is decided (who typed it first / who is out) before the next opens. */
export const GAP_MS = 1500;
/** Round results stay this long before the next round's countdown. */
export const ROUND_END_MS = 6000;
/** Rate limit: actions (progress + submit) per second per player. */
export const ACTIONS_PER_SEC = 15;
/** Items in one round: words and sentences (a long text gives a passage of `LONG_LINES` lines). */
export const ROUND_ITEMS: Record<'first' | 'lane', { word: number; short: number }> = { first: { word: 10, short: 5 }, lane: { word: 15, short: 3 } };
export const LONG_LINES = 8;
/** 연습: words / sentences in the set (a long text is typed whole). */
export const PRACTICE_ITEMS = { word: 20, short: 10 } as const;
/** 자동 time limits: generous for a person typing about this many keystrokes a minute. */
const AUTO_KPM = 120;
// ---------------------------------------------------------------- helpers
export const flowOf = (o: Pick<TypingOptions, 'mode' | 'elimination'>): Flow =>
o.mode === 'first' || (o.mode === 'survival' && o.elimination !== 'interval') ? 'shared' : 'lane';
const isPractice = (o: Pick<TypingOptions, 'mode'>) => o.mode === 'practice';
/** Rounds in the game: 연습 is always one. */
export const roundsOf = (o: Pick<TypingOptions, 'mode' | 'rounds'>) => (isPractice(o) ? 1 : o.rounds);
/** Items never run out (the round ends by survivors or by the clock). */
const cycles = (o: TypingOptions) => o.mode === 'survival' || o.mode === 'timeAttack';
/** Topics in play: the picked ones that fit the language and category, or all of them. */
export function topicIdsFor(o: Pick<TypingOptions, 'lang' | 'category' | 'topics'>): string[] {
const all = topicsFor(o.lang, o.category).map((t) => t.id);
const picked = all.filter((id) => o.topics.includes(id));
return picked.length ? picked : all;
}
/** Lines of a long topic as typed (long lines wrapped). */
const longLines = (t: Topic) => wrapLines(t.items, t.lang);
/** 자동 limit for one item. */
export const autoItemMs = (text: string) => Math.max(8000, 4000 + Math.round((keyCount(text) * 60_000) / AUTO_KPM));
/** 자동 limit for a whole lane round. */
export const autoRoundMs = (items: readonly string[]) => 10_000 + Math.round((items.reduce((n, t) => n + keyCount(t), 0) * 60_000) / (AUTO_KPM * 0.85));
/** 서바이벌: each item's clock is this much shorter than the one before … */
export const SURVIVAL_SHRINK = 0.9;
/** … but never below the time a very fast typist (this many 타 a minute) needs, plus a second to read. */
export const SURVIVAL_FLOOR_KPM = 900;
/** 서바이벌 always ends: after this many items (or cuts) in a row where nobody could be knocked out, or this many items, the survivors share the round. */
export const SURVIVAL_STALL_LIMIT = 3;
export const SURVIVAL_MAX_ITEMS = 60;
/**
* The clock of shared item `i`. 서바이벌 always has one (무제한 plays as 자동) and it gets shorter item by item, so a round
* always ends: sooner or later someone cannot keep up.
*/
export function itemLimit(s: Pick<S, 'options'>, text: string, i: number): number | null {
const t = s.options.timeLimit;
const base = t === null || t === 0 ? (t === null && s.options.mode !== 'survival' ? null : autoItemMs(text)) : t * 1000;
if (base === null || s.options.mode !== 'survival') return base;
const floor = 1000 + Math.round((keyCount(text) * 60_000) / SURVIVAL_FLOOR_KPM);
return Math.max(Math.min(base, floor), Math.round(base * SURVIVAL_SHRINK ** i));
}
export const itemText = (s: Pick<S, 'items'>, i: number) => s.items[i % s.items.length]!;
const inGame = (s: S, p: PlayerId) => !s.totals[p]!.left;
const alive = (s: S) => s.order.filter((p) => s.rs[p]!.alive);
const isSurvival = (s: S) => s.options.mode === 'survival';
function clone(s: S): S {
return {
...s,
order: [...s.order],
outOrder: [...s.outOrder],
rs: Object.fromEntries(Object.entries(s.rs).map(([k, v]) => [k, { ...v, recent: [...v.recent] }])),
totals: Object.fromEntries(Object.entries(s.totals).map(([k, v]) => [k, { ...v }])),
rounds: [...s.rounds],
longAt: { ...s.longAt },
};
}
interface Ctx {
now: number;
rng: Rng | null;
events: GameEvent[];
}
const freshSeat = (lives: number, inPlay: boolean, now: number): RoundSeat => ({
idx: 0,
itemAt: now,
prog: 0,
done: 0,
keys: 0,
ms: 0,
accSum: 0,
accLen: 0,
wrong: 0,
finishedAt: inPlay ? null : now,
lives,
alive: inPlay,
outReason: inPlay ? null : 'left',
place: null,
solvedAt: null,
recent: [],
});
// ---------------------------------------------------------------- rounds
/** This round's items (and the topic of each), taken from the deck / the next passage of a long text. */
function dealRound(s: S, rng: Rng | null): void {
const o = s.options;
const topics: string[] = [];
let items: string[] = [];
if (o.category === 'long') {
if (cycles(o)) {
// Survival / time attack: the texts one after another, without end.
for (const id of s.longOrder) for (const l of longLines(TOPIC_BY_ID[id]!)) (items.push(l), topics.push(id));
} else if (isPractice(o)) {
// 연습: one text, from its first line to its last.
const id = s.longOrder[0]!;
for (const l of longLines(TOPIC_BY_ID[id]!)) (items.push(l), topics.push(id));
} else {
const id = s.longOrder[(s.round - 1) % s.longOrder.length]!;
const all = longLines(TOPIC_BY_ID[id]!);
let at = s.longAt[id] ?? 0;
if (at >= all.length) at = 0;
// The last few lines join the passage before them rather than making a stub of their own.
const end = all.length - (at + LONG_LINES) < 3 ? all.length : at + LONG_LINES;
items = all.slice(at, end);
for (let i = 0; i < items.length; i++) topics.push(id);
s.longAt[id] = end >= all.length ? 0 : end;
}
} else if (cycles(o)) {
for (const k of s.deck) {
const [id, i] = k.split('|') as [string, string];
items.push(TOPIC_BY_ID[id]!.items[Number(i)]!);
topics.push(id);
}
} else {
const n = isPractice(o) ? PRACTICE_ITEMS[o.category] : ROUND_ITEMS[o.mode === 'first' ? 'first' : 'lane'][o.category];
for (let k = 0; k < n; k++) {
if (s.deckAt >= s.deck.length) {
s.deck = rng ? rng.shuffle(s.deck) : s.deck;
s.deckAt = 0;
}
const [id, i] = s.deck[s.deckAt++]!.split('|') as [string, string];
items.push(TOPIC_BY_ID[id]!.items[Number(i)]!);
topics.push(id);
}
}
s.items = items;
s.itemTopic = topics;
s.cycle = cycles(o);
}
/** A new round: fresh round seats, its items, the countdown. */
function startRound(s: S, round: number, ctx: Ctx): void {
s.round = round;
s.phase = 'countdown';
s.phaseEndsAt = ctx.now + COUNTDOWN_MS;
s.roundStartedAt = s.phaseEndsAt;
s.roundEndsAt = null;
s.nextCutAt = null;
s.outOrder = [];
s.stalls = 0;
s.stalled = false;
s.last = null;
s.cur = 0;
s.curOpen = false;
s.curAt = s.phaseEndsAt;
s.curEndsAt = null;
for (const p of s.order) s.rs[p] = freshSeat(s.options.lives, inGame(s, p), s.phaseEndsAt);
dealRound(s, ctx.rng);
ctx.events.push({ type: 'round', round });
}
/** The countdown is over: the first item opens / everybody starts on their lane. */
function beginPlay(s: S, ctx: Ctx): void {
const t = s.phaseEndsAt ?? ctx.now;
s.phase = 'playing';
s.phaseEndsAt = null;
s.roundStartedAt = t;
if (flowOf(s.options) === 'shared') openItem(s, 0, t);
else {
for (const p of s.order) s.rs[p]!.itemAt = t;
const o = s.options;
if (o.mode === 'timeAttack') s.roundEndsAt = t + o.attackSec * 1000;
else if (o.mode === 'survival') s.nextCutAt = t + o.intervalSec * 1000;
else s.roundEndsAt = o.timeLimit === null || isPractice(o) ? null : t + (o.timeLimit === 0 ? autoRoundMs(s.items) : o.timeLimit * 1000);
}
ctx.events.push({ type: 'start', round: s.round });
}
function openItem(s: S, i: number, at: number): void {
s.cur = i;
s.curAt = at;
s.curOpen = false;
const lim = itemLimit(s, itemText(s, i), i);
s.curEndsAt = lim === null ? null : at + lim;
for (const p of s.order) {
const r = s.rs[p]!;
r.solvedAt = null;
r.prog = 0;
}
}
/** Does the shared round end after item `i` (the last item, or survival is decided)? */
function sharedOver(s: S, nextIdx: number): boolean {
if (isSurvival(s)) return alive(s).length <= 1 || survivalStalled(s, nextIdx);
return !s.cycle && nextIdx >= s.items.length;
}
/** 서바이벌 undecided: nobody could be knocked out several times in a row, or the item cap is reached. */
function survivalStalled(s: S, nextIdx: number): boolean {
if ((s.stalls ?? 0) < SURVIVAL_STALL_LIMIT && nextIdx < SURVIVAL_MAX_ITEMS) return false;
s.stalled = true;
return true;
}
/** The current shared item is decided: remember it, then the next opens after the gap (or the round ends). */
function closeItem(s: S, winner: PlayerId | null, out: PlayerId[], ctx: Ctx): void {
const text = itemText(s, s.cur);
// Those still typing it: what they had typed counts toward their 타수 (like a lane line cut by the clock).
for (const p of s.order) {
const r = s.rs[p]!;
if (r.solvedAt !== null || r.outReason === 'left' || (!r.alive && !out.includes(p))) continue;
r.keys += r.prog;
r.ms += Math.max(0, ctx.now - s.curAt);
}
const w = winner ? s.rs[winner]! : null;
const ms = w && w.solvedAt !== null ? w.solvedAt - s.curAt : 0;
s.last = { text, winner, kpm: w ? kpm(keyCount(text), ms) : 0, out } satisfies LastItem;
ctx.events.push({ type: 'itemEnd', item: s.cur, winner, out });
// Somebody typed it or went out: the survivors are not stuck (only all-at-once misses in a row count as a stall).
if (out.length || s.order.some((p) => s.rs[p]!.alive && s.rs[p]!.solvedAt !== null && s.rs[p]!.prog >= keyCount(text))) s.stalls = 0;
const next = s.cur + 1;
if (sharedOver(s, next)) return endRound(s, ctx);
openItem(s, next, ctx.now + GAP_MS);
}
/** Survival: knock `ps` out together (they share a place). Never everybody at once: then nobody goes out. */
function knockOut(s: S, ps: PlayerId[], why: OutReason, ctx: Ctx, force = false): PlayerId[] {
const live = alive(s);
const hit = ps.filter((p) => s.rs[p]!.alive);
if (!hit.length) return [];
if (!force && hit.length >= live.length) {
// Everyone left would go: they all stay (a 목숨 rule keeps one life) — but not for ever (`SURVIVAL_STALL_LIMIT`).
for (const p of hit) if (s.rs[p]!.lives <= 0) s.rs[p]!.lives = 1;
s.stalls = (s.stalls ?? 0) + 1;
ctx.events.push({ type: 'spared', players: hit });
return [];
}
s.stalls = 0;
const place = live.length - hit.length + 1;
for (const p of hit) {
const r = s.rs[p]!;
r.alive = false;
r.outReason = why;
r.place = place;
r.finishedAt ??= ctx.now;
s.outOrder.push(p);
}
ctx.events.push({ type: 'out', players: hit, reason: why });
return hit;
}
/** Shared survival: is the current item decided after this change? */
function checkShared(s: S, ctx: Ctx, outNow: PlayerId[] = []): void {
if (s.phase !== 'playing' || !s.curOpen) return;
const live = alive(s);
if (live.length <= 1) return closeItem(s, null, outNow, ctx);
const open = live.filter((p) => s.rs[p]!.solvedAt === null);
if (s.options.elimination === 'sentence' && open.length === 1) {
const out = knockOut(s, open, 'slowest', ctx);
return closeItem(s, null, [...outNow, ...out], ctx);
}
if (open.length === 0) closeItem(s, null, outNow, ctx);
}
/** The shared item's clock ran out. */
function itemTimeout(s: S, ctx: Ctx): void {
if (!isSurvival(s)) return closeItem(s, null, [], ctx);
const open = alive(s).filter((p) => s.rs[p]!.solvedAt === null);
let out: PlayerId[] = [];
if (s.options.elimination === 'wrong') {
const dead: PlayerId[] = [];
for (const p of open) if (--s.rs[p]!.lives <= 0) dead.push(p);
if (open.length) ctx.events.push({ type: 'miss', players: open });
out = knockOut(s, dead, 'lives', ctx);
} else out = knockOut(s, open, 'time', ctx);
closeItem(s, null, out, ctx);
}
/** 서바이벌 시간별: whoever typed the least so far goes (ties together). */
function intervalCut(s: S, ctx: Ctx): void {
const live = alive(s);
const score = (p: PlayerId) => s.rs[p]!.keys + s.rs[p]!.prog;
const least = Math.min(...live.map(score));
knockOut(
s,
live.filter((p) => score(p) === least),
'least',
ctx,
);
if (alive(s).length <= 1 || survivalStalled(s, 0)) endRound(s, ctx);
else s.nextCutAt = (s.nextCutAt ?? ctx.now) + s.options.intervalSec * 1000;
}
/** Lane round over by the clock: what each player has typed of the line they are on counts too. */
function laneTimeUp(s: S, ctx: Ctx): void {
const t = s.roundEndsAt ?? ctx.now;
for (const p of s.order) {
const r = s.rs[p]!;
if (r.finishedAt !== null) continue;
r.keys += r.prog;
r.ms += Math.max(0, t - r.itemAt);
r.finishedAt = t;
}
endRound(s, ctx);
}
const roundKpm = (r: RoundSeat) => kpm(r.keys, r.ms);
const roundAcc = (r: RoundSeat) => (r.accLen ? r.accSum / r.accLen : 0);
const pct = (x: number) => Math.round(x * 1000) / 10;
/** Round ranking value(s), best first, by mode. */
function roundOrder(s: S): PlayerId[] {
const o = s.options.mode;
const rs = s.rs;
const key = (p: PlayerId): number[] => {
const r = rs[p]!;
const left = s.totals[p]!.left ? 1 : 0;
switch (o) {
case 'first':
return [-left, r.done, roundKpm(r)];
case 'survival':
return [-left, -(r.alive ? 1 : (r.place ?? 99)), r.keys];
case 'speed':
case 'practice':
return [-left, roundKpm(r), roundAcc(r)];
case 'accuracy':
return [-left, Math.round(roundAcc(r) * 1000), roundKpm(r)];
case 'timeAttack':
return [-left, r.keys, roundAcc(r)];
}
};
return [...s.order].sort((a, b) => {
const ka = key(a);
const kb = key(b);
for (let i = 0; i < ka.length; i++) if (ka[i] !== kb[i]) return kb[i]! - ka[i]!;
return 0;
});
}
function endRound(s: S, ctx: Ctx): void {
if (s.phase !== 'playing') return;
const o = s.options;
const order = roundOrder(s);
const rs = s.rs;
// Places: survival by when people went out; other modes by the ranking value (equal values share).
const rows: RoundResult['rows'] = [];
const val = (p: PlayerId): string => {
const r = rs[p]!;
if (s.totals[p]!.left) return 'left';
switch (o.mode) {
case 'first':
return String(r.done);
case 'survival':
return r.alive ? 'alive' : String(r.place);
case 'speed':
case 'practice':
return `${roundKpm(r)}/${Math.round(roundAcc(r) * 1000)}`;
case 'accuracy':
return `${Math.round(roundAcc(r) * 1000)}/${roundKpm(r)}`;
case 'timeAttack':
return String(r.keys);
}
};
order.forEach((p, i) => {
const prev = rows[i - 1];
const rank = prev && val(order[i - 1]!) === val(p) ? prev.rank : i + 1;
const r = rs[p]!;
rows.push({ id: p, rank, points: 0, kpm: roundKpm(r), acc: pct(roundAcc(r)), done: r.done, out: r.outReason });
});
// Points: 가장 먼저 입력 already scored per item; other modes give the round's best a point (nothing for nobody).
let winners: PlayerId[] = [];
if (o.mode === 'first') {
const best = Math.max(0, ...rows.map((r) => r.done));
winners = best > 0 ? rows.filter((r) => r.done === best && !s.totals[r.id]!.left).map((r) => r.id) : [];
for (const row of rows) row.points = rs[row.id]!.done;
} else if (o.mode !== 'practice') {
const top = rows.filter((r) => r.rank === 1 && !s.totals[r.id]!.left);
const somethingDone = top.some((r) => (o.mode === 'survival' ? true : r.done > 0 || rs[r.id]!.keys > 0));
winners = somethingDone ? top.map((r) => r.id) : [];
for (const w of winners) {
s.totals[w]!.points += 1;
rows.find((r) => r.id === w)!.points = 1;
}
}
for (const p of s.order) {
const r = rs[p]!;
const t = s.totals[p]!;
t.keys += r.keys;
t.ms += r.ms;
t.accSum += r.accSum;
t.accLen += r.accLen;
t.wrong += r.wrong;
if (r.alive && o.mode === 'survival') r.place = 1;
}
const summary = roundSummary(s, winners);
s.rounds = [...s.rounds, { round: s.round, rows, winners, summary }];
s.phase = 'roundEnd';
s.phaseEndsAt = ctx.now + ROUND_END_MS;
s.curOpen = false;
ctx.events.push({ type: 'roundEnd', round: s.round, winners });
if (s.round >= roundsOf(o) || s.order.filter((p) => inGame(s, p)).length === 0) finish(s, ctx);
}
function roundSummary(s: S, winners: PlayerId[]): string {
const mode = s.options.mode;
const n = winners.length;
const solo = s.order.length === 1;
if (mode === 'practice') return solo ? '연습 끝! 타수와 정확도를 확인해요' : '연습 끝! 타수가 높은 순서로 보여요';
if (!n) return mode === 'first' ? '아무도 먼저 치지 못했어요' : '이번 라운드는 승자가 없어요';
const many = n > 1 ? ` (공동 ${n}명)` : '';
switch (mode) {
case 'first':
return solo ? '라운드 끝!' : `가장 많이 먼저 친 사람이 이 라운드 1등이에요${many}`;
case 'survival':
return s.stalled ? `더 탈락하는 사람이 없어서 남은 사람이 함께 1점을 얻어요${many}` : `끝까지 살아남은 사람이 1점을 얻어요${many}`;
case 'speed':
return solo ? '라운드 끝! 타수를 확인해요' : `타수가 가장 높은 사람이 1점을 얻어요${many}`;
case 'accuracy':
return solo ? '라운드 끝! 정확도를 확인해요' : `정확도가 가장 높은 사람이 1점을 얻어요${many}`;
case 'timeAttack':
return solo ? '시간 끝! 친 타수를 확인해요' : `시간 안에 가장 많이 친 사람이 1점을 얻어요${many}`;
}
}
// ---------------------------------------------------------------- ending
export const avgKpm = (t: Pick<SeatTotals, 'keys' | 'ms'>) => kpm(t.keys, t.ms);
export const avgAcc = (t: Pick<SeatTotals, 'accSum' | 'accLen'>) => (t.accLen ? pct(t.accSum / t.accLen) : 0);
export function finalRanking(s: Pick<S, 'order' | 'totals'>): TypingFinal['ranking'] {
const rows = s.order.map((id) => {
const t = s.totals[id]!;
return { id, rank: 0, points: t.points, kpm: avgKpm(t), acc: avgAcc(t), left: t.left };
});
rows.sort((a, b) => Number(a.left) - Number(b.left) || b.points - a.points || b.kpm - a.kpm || b.acc - a.acc);
rows.forEach((r, i) => {
const p = rows[i - 1];
r.rank = p && p.left === r.left && p.points === r.points && p.kpm === r.kpm && p.acc === r.acc ? p.rank : i + 1;
});
return rows;
}
function finish(s: S, ctx: Ctx): void {
if (s.phase === 'ended') return;
const ranking = finalRanking(s);
const top = ranking.filter((r) => r.rank === 1 && !r.left);
const stayed = s.order.filter((p) => inGame(s, p));
let summary: string;
if (s.order.length === 1) {
const r = ranking[0]!;
summary = `평균 ${r.kpm}타 · 정확도 ${r.acc}%로 끝냈어요`;
} else if (isPractice(s.options)) summary = '연습 끝! 평균 타수가 높은 순서예요';
else if (stayed.length <= 1 && s.round < s.options.rounds) summary = '다른 사람이 모두 나가서 남은 사람이 이겼어요';
else {
const what = s.options.mode === 'first' ? '먼저 친 문제가 가장 많은' : '라운드 점수가 가장 높은';
summary = `${what} 사람이 이겼어요`;
if (top.length > 1) summary += ` (공동 1등 ${top.length}명)`;
}
s.phase = 'ended';
s.phaseEndsAt = null;
s.final = { ranking, summary };
ctx.events.push({ type: 'gameEnd' });
}
// ---------------------------------------------------------------- clock
/** Brings everything due up to the clock (several steps can fall due at once). */
function catchUp(s: S, ctx: Ctx): void {
for (let guard = 0; guard < 50; guard++) {
const now = ctx.now;
if (s.phase === 'countdown' && s.phaseEndsAt !== null && now >= s.phaseEndsAt) {
beginPlay(s, ctx);
continue;
}
if (s.phase === 'roundEnd' && s.phaseEndsAt !== null && now >= s.phaseEndsAt) {
startRound(s, s.round + 1, ctx);
continue;
}
if (s.phase !== 'playing') return;
if (flowOf(s.options) === 'shared') {
if (!s.curOpen && now >= s.curAt) {
s.curOpen = true;
ctx.events.push({ type: 'itemOpen', item: s.cur });
continue;
}
if (s.curOpen && s.curEndsAt !== null && now >= s.curEndsAt) {
itemTimeout(s, ctx);
continue;
}
return;
}
if (s.nextCutAt !== null && now >= s.nextCutAt) {
intervalCut(s, ctx);
continue;
}
if (s.roundEndsAt !== null && now >= s.roundEndsAt) {
laneTimeUp(s, ctx);
continue;
}
return;
}
}
/** A timed-out player with nothing due (away past the grace period in a 무제한 step): they give up this step. */
function awayTimeout(s: S, p: PlayerId, ctx: Ctx): void {
if (s.phase !== 'playing') return;
const r = s.rs[p]!;
if (flowOf(s.options) === 'shared') {
if (!isSurvival(s) || !s.curOpen || !r.alive || r.solvedAt !== null) return;
if (s.options.elimination === 'wrong') {
r.lives--;
const out = r.lives <= 0 ? knockOut(s, [p], 'lives', ctx) : [];
// A life lost while away still counts as this item done for them (no endless wait).
if (r.alive) r.solvedAt = ctx.now;
return checkShared(s, ctx, out);
}
const out = knockOut(s, [p], 'time', ctx);
if (!out.length) r.solvedAt = ctx.now;
return checkShared(s, ctx, out);
}
if (r.finishedAt !== null) return;
r.finishedAt = ctx.now;
ctx.events.push({ type: 'stopped', player: p });
laneMaybeOver(s, ctx);
}
function laneMaybeOver(s: S, ctx: Ctx): void {
if (s.phase !== 'playing') return;
if (isSurvival(s)) {
if (alive(s).length <= 1) endRound(s, ctx);
return;
}
if (s.order.every((p) => s.rs[p]!.finishedAt !== null)) endRound(s, ctx);
}
// ---------------------------------------------------------------- actions
function rateOk(times: readonly number[], now: number | undefined): boolean {
if (now === undefined || times.length < ACTIONS_PER_SEC) return true;
return now - times[times.length - ACTIONS_PER_SEC]! >= 1000;
}
/** Can `p` type item `item` now? (Item check, alive, open.) */
function canType(s: S, p: PlayerId, item: number, now: number | undefined): Validation {
if (s.phase !== 'playing') return fail(s.phase === 'roundEnd' ? '다음 라운드를 기다려 주세요.' : '곧 시작해요. 잠시만 기다려 주세요.');
const r = s.rs[p]!;
if (!r.alive) return fail(r.outReason === 'left' ? '게임에서 빠졌어요.' : '이번 라운드에서 탈락했어요. 다음 라운드를 기다려 주세요.');
if (flowOf(s.options) === 'shared') {
if (!s.curOpen && (now === undefined || now < s.curAt)) return fail('다음 문제가 곧 나와요.');
if (item !== s.cur) return fail('이미 지나간 문제예요.');
if (now !== undefined && s.curEndsAt !== null && now >= s.curEndsAt) return fail('시간이 다 됐어요.');
if (r.solvedAt !== null) return fail(isSurvival(s) ? '이미 쳤어요. 다른 사람을 기다려요.' : '이미 쳤어요.');
return ok;
}
if (r.finishedAt !== null) return fail('이번 라운드를 다 쳤어요.');
if (item !== r.idx) return fail('이미 지나간 줄이에요.');
if (now !== undefined && s.roundEndsAt !== null && now >= s.roundEndsAt) return fail('시간이 다 됐어요.');
return ok;
}
const startOf = (s: S, p: PlayerId) => (flowOf(s.options) === 'shared' ? s.curAt : s.rs[p]!.itemAt);
const targetOf = (s: S, p: PlayerId) => itemText(s, flowOf(s.options) === 'shared' ? s.cur : s.rs[p]!.idx);
function progress(s: S, p: PlayerId, text: string, ctx: Ctx): void {
const r = s.rs[p]!;
const target = targetOf(s, p);
// 연습: a line's clock starts at its first key (a rest between lines does not count), like 한컴 타자연습. It is set a
// reaction time back: that stands for the first key's own time, and keeps the paste guard as for the other modes.
if (isPractice(s.options) && !r.started && normalize(text)) {
r.started = true;
r.itemAt = Math.max(r.itemAt, ctx.now - REACTION_MS);
}
// Never more than a person could have typed since the item began (a pasted text does not jump ahead).
const cap = Math.max(0, Math.floor(((ctx.now - startOf(s, p) - REACTION_MS) * MAX_KPM) / 60_000));
r.prog = Math.min(correctKeys(target, text), keyCount(target), cap);
r.recent = [...r.recent.slice(-(ACTIONS_PER_SEC - 1)), ctx.now];
ctx.events.push({ type: 'progress', player: p, item: flowOf(s.options) === 'shared' ? s.cur : r.idx, n: r.prog, of: keyCount(target) });
}
function submit(s: S, p: PlayerId, text: string, ctx: Ctx): void {
const r = s.rs[p]!;
r.recent = [...r.recent.slice(-(ACTIONS_PER_SEC - 1)), ctx.now];
const target = targetOf(s, p);
const keys = keyCount(target);
const len = [...normalize(target)].length;
const acc = accuracy(target, text);
const right = normalize(text) === normalize(target);
if (flowOf(s.options) === 'shared') {
if (!right) {
r.wrong++;
r.accSum += acc * len;
r.accLen += len;
ctx.events.push({ type: 'wrong', player: p, item: s.cur });
if (isSurvival(s) && s.options.elimination === 'wrong') {
r.lives--;
const out = r.lives <= 0 ? knockOut(s, [p], 'lives', ctx) : [];
// Spared (everyone else is out too): keep typing on one life.
checkShared(s, ctx, out);
}
return;
}
r.solvedAt = ctx.now;
r.done++;
r.keys += keys;
r.ms += Math.max(1, ctx.now - s.curAt);
r.accSum += len;
r.accLen += len;
r.prog = keys;
ctx.events.push({ type: 'solved', player: p, item: s.cur, ms: ctx.now - s.curAt });
if (s.options.mode === 'first') {
s.totals[p]!.points += 1;
return closeItem(s, p, [], ctx);
}
return checkShared(s, ctx);
}
// Lane: whatever was typed goes in; mistakes lower the accuracy and the 타수.
const lineKeys = Math.round(keys * acc);
const lineMs = Math.max(1, ctx.now - r.itemAt);
r.keys += lineKeys;
r.ms += lineMs;
r.best = Math.max(r.best ?? 0, kpm(lineKeys, lineMs));
r.started = false;
r.accSum += acc * len;
r.accLen += len;
if (!right) r.wrong++;
r.done++;
r.idx++;
r.itemAt = ctx.now;
r.prog = 0;
ctx.events.push({ type: 'line', player: p, item: r.idx - 1, acc: pct(acc), right });
if (!s.cycle && r.idx >= s.items.length) {
r.finishedAt = ctx.now;
ctx.events.push({ type: 'finished', player: p });
laneMaybeOver(s, ctx);
}
}
function leave(s: S, p: PlayerId, ctx: Ctx): void {
s.totals[p]!.left = true;
const r = s.rs[p]!;
ctx.events.push({ type: 'left', player: p });
const stayed = s.order.filter((q) => inGame(s, q));
// A contest ends when one is left; 연습 goes on for whoever is still typing.
if (stayed.length === 0 || (stayed.length === 1 && s.order.length > 1 && !isPractice(s.options))) {
r.alive = false;
r.outReason = 'left';
r.finishedAt ??= ctx.now;
if (s.phase === 'playing') endRound(s, ctx);
return finish(s, ctx);
}
if (s.phase !== 'playing') {
r.alive = false;
r.outReason = 'left';
return;
}
if (r.alive && isSurvival(s)) knockOut(s, [p], 'left', ctx, true);
else {
r.alive = false;
r.outReason = 'left';
}
r.finishedAt ??= ctx.now;
if (flowOf(s.options) === 'shared') {
if (isSurvival(s)) checkShared(s, ctx);
} else laneMaybeOver(s, ctx);
}
// ---------------------------------------------------------------- view
function seatView(s: S, p: PlayerId): SeatView {
const r = s.rs[p]!;
const t = s.totals[p]!;
const shared = flowOf(s.options) === 'shared';
const live = s.phase === 'playing';
const target = s.phase === 'playing' && s.items.length ? targetOf(s, p) : '';
const of = target ? keyCount(target) : 0;
return {
id: p,
points: t.points,
// While a round is played its numbers are not in the totals yet; once it ends (`endRound`) they are.
kpm: avgKpm(live ? { keys: t.keys + r.keys, ms: t.ms + r.ms } : t),
acc: avgAcc(live ? { accSum: t.accSum + r.accSum, accLen: t.accLen + r.accLen } : t),
tried: t.accLen + (live ? r.accLen : 0) > 0,
roundTried: r.accLen > 0,
left: t.left,
idx: shared ? s.cur : r.idx,
done: r.done,
prog: of ? Math.min(1, r.prog / of) : 0,
roundKpm: roundKpm(r),
roundAcc: pct(roundAcc(r)),
bestKpm: r.best ?? 0,
wrong: r.wrong,
finished: r.finishedAt !== null,
lives: r.lives,
alive: r.alive,
outReason: r.outReason,
solved: r.solvedAt !== null,
};
}
function buildView(s: S, viewer: PlayerId | null): TypingView {
const me = viewer && s.order.includes(viewer) ? viewer : null;
const shared = flowOf(s.options) === 'shared';
const upcoming: TypingView['upcoming'] = [];
const item = (i: number) => ({ idx: i, text: itemText(s, i), topic: s.itemTopic[i % s.itemTopic.length]! });
if (s.phase === 'playing' && s.items.length) {
if (shared) {
if (s.curOpen) upcoming.push(item(s.cur));
} else {
const r = me ? s.rs[me]! : null;
const from = r ? r.idx : 0;
const done = r ? r.finishedAt !== null : false;
if (!done) for (let i = from; i < from + 3 && (s.cycle || i < s.items.length); i++) upcoming.push(item(i));
}
}
const long = s.options.category === 'long' && !s.cycle && s.phase !== 'countdown' && s.phase !== 'ended';
const topic = long ? TOPIC_BY_ID[s.itemTopic[0]!] : undefined;
return {
options: s.options,
me,
flow: flowOf(s.options),
phase: s.phase,
round: s.round,
phaseEndsAt: s.phaseEndsAt,
roundStartedAt: s.roundStartedAt,
roundEndsAt: s.roundEndsAt,
total: s.cycle ? null : s.items.length,
cur: s.cur,
curAt: s.curAt,
curEndsAt: s.curEndsAt,
upcoming,
// The whole passage is shown only once typing has begun (a head start otherwise) — and to spectators.
passage: long && s.phase === 'playing' && (!shared || s.curOpen) ? [...s.items] : null,
passageTitle: topic?.name ?? null,
passageBy: topic?.by ?? null,
last: s.last,
nextCutAt: s.nextCutAt,
seats: s.order.map((p) => seatView(s, p)),
rounds: s.rounds,
result: s.final,
};
}
// ---------------------------------------------------------------- definition
type Def = GameDefinition<S, A, TypingView, TypingOptions>;
export const typing: Def = {
id: 'typing',
nameKo: '타자 대결',
realtime: true,
minPlayers: 1,
maxPlayers: MAX_PLAYERS,
stateVersion: 1,
defaultOptions: typingOptionsSchema.parse({}),
optionsSchema: typingOptionsSchema as unknown as Def['optionsSchema'],
actionSchema: typingActionSchema as unknown as Def['actionSchema'],
playersFor(o) {
return { min: o.mode === 'survival' ? 2 : 1, max: MAX_PLAYERS };
},
setup({ players, options, rng, now }) {
if (players.length < 1 || players.length > MAX_PLAYERS) throw new Error(`typing: ${players.length} players not allowed`);
const topicIds = topicIdsFor(options);
const deck =
options.category === 'long' ? [] : rng.shuffle(topicIds.flatMap((id) => TOPIC_BY_ID[id]!.items.map((_, i) => `${id}|${i}`)));
const s: S = {
options,
topicIds,
order: [...players],
phase: 'countdown',
round: 0,
phaseEndsAt: null,
roundStartedAt: now,
roundEndsAt: null,
items: [],
cycle: false,
itemTopic: [],
cur: 0,
curAt: now,
curEndsAt: null,
curOpen: false,
last: null,
nextCutAt: null,
outOrder: [],
rs: {},
totals: Object.fromEntries(players.map((p) => [p, { points: 0, keys: 0, ms: 0, accSum: 0, accLen: 0, wrong: 0, left: false }])),
rounds: [],
deck,
deckAt: 0,
longOrder: options.category === 'long' ? rng.shuffle(topicIds) : [],
longAt: {},
final: null,
};
startRound(s, 1, { now, rng, events: [] });
return s;
},
validate(s, actor, a, vctx) {
if (!s.order.includes(actor)) return fail('이 게임의 플레이어가 아니에요.');
if (s.phase === 'ended') return fail('게임이 이미 끝났어요.');
const now = vctx?.now;
switch (a.type) {
case 'tick':
return ok;
case 'leave':
return inGame(s, actor) ? ok : fail('이미 게임에서 빠졌어요.');
case 'progress':
case 'submit': {
if (!inGame(s, actor)) return fail('게임에서 빠졌어요.');
const v = canType(s, actor, a.item, now);
if (!v.ok) return v;
if (!rateOk(s.rs[actor]!.recent, now)) return fail('조금 천천히 해 주세요.');
if (a.type === 'submit') {
if (!normalize(a.text)) return fail('친 글자가 없어요.');
// A wrong answer in a shared item gains nothing, so only right answers (and every lane line) face the paste guard.
if (flowOf(s.options) === 'shared' && normalize(a.text) !== normalize(targetOf(s, actor))) return ok;
const since = now === undefined ? Infinity : now - Math.max(startOf(s, actor), s.phase === 'playing' ? s.roundStartedAt : 0);
if (since < minTypingMs(keyCount(normalize(a.text)))) return fail('너무 빨라요. 붙여 넣기는 쓸 수 없어요.');
}
return ok;
}
}
},
apply(prev, actor, a, { now, rng }) {
const s = clone(prev);
const ctx: Ctx = { now, rng, events: [] };
// A tick in a step without a clock can only be the room passing an away player (nothing else is ever due).
const unclocked = typing.deadline!(prev) === null;
catchUp(s, ctx);
if (s.phase !== 'ended') {
if (a.type === 'leave') leave(s, actor, ctx);
else if ((a.type === 'progress' || a.type === 'submit') && canType(s, actor, a.item, now).ok) {
if (a.type === 'progress') progress(s, actor, a.text, ctx);
else submit(s, actor, a.text, ctx);
} else if (a.type === 'tick' && unclocked) awayTimeout(s, actor, ctx);
}
return { state: s, events: ctx.events };
},
view: buildView,
/** Progress is streamed: the server relays its event instead of sending everybody a new view. */
isStreamAction(a) {
return a.type === 'progress';
},
activePlayers(s) {
if (s.phase === 'ended') return [];
const live = s.order.filter((p) => inGame(s, p));
if (s.phase !== 'playing') return live;
if (flowOf(s.options) === 'shared') {
if (!s.curOpen) return live;
const open = live.filter((p) => s.rs[p]!.alive && s.rs[p]!.solvedAt === null);
return open.length ? open : live;
}
const typing = live.filter((p) => s.rs[p]!.alive && s.rs[p]!.finishedAt === null);
return typing.length ? typing : live;
},
deadline(s) {
if (s.phase === 'ended') return null;
if (s.phase !== 'playing') return s.phaseEndsAt;
if (flowOf(s.options) === 'shared') return s.curOpen ? s.curEndsAt : s.curAt;
const ds = [s.roundEndsAt, s.nextCutAt].filter((d): d is number => d !== null);
return ds.length ? Math.min(...ds) : null;
},
/**
* Clock steps (countdown, gaps, item and round clocks) need anyone in the game to fire them. In a 무제한 step only
* those it waits on are timed, so an away player is passed after the room's grace period.
*/
timeoutPlayers(s) {
if (s.phase === 'ended') return [];
const live = s.order.filter((p) => inGame(s, p));
if (typing.deadline!(s) !== null) return live;
if (s.phase !== 'playing') return live;
if (flowOf(s.options) === 'shared') {
if (!isSurvival(s)) return [];
return live.filter((p) => s.rs[p]!.alive && s.rs[p]!.solvedAt === null);
}
return live.filter((p) => s.rs[p]!.alive && s.rs[p]!.finishedAt === null);
},
/** A step with a clock never ends early because someone is away: their typing simply stops. */
timeoutNotBefore(s) {
return typing.deadline!(s);
},
onTimeout() {
return { type: 'tick' };
},
onLeave(s, player) {
if (s.phase === 'ended' || !inGame(s, player)) return null;
return { type: 'leave' };
},
result(s): GameResult | null {
const f = s.final;
if (!f) return null;
const groups = new Map<number, PlayerId[]>();
for (const r of f.ranking) groups.set(r.rank, [...(groups.get(r.rank) ?? []), r.id]);
const unit = s.options.mode === 'first' ? '문제' : '승';
const head = (r: TypingFinal['ranking'][number]) => (isPractice(s.options) ? '' : `${r.points}${unit} · `);
return {
ranking: [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ids]) => ids),
scores: Object.fromEntries(f.ranking.map((r) => [r.id, r.points])),
scoreText: Object.fromEntries(f.ranking.map((r) => [r.id, `${head(r)}평균 ${r.kpm}타 · 정확도 ${r.acc}%`])),
summary: f.summary,
reason: 'normal',
};
},
/** Test helper: the clock, typing the item right, a typo, and some progress. */
legalActions(s, p) {
if (s.phase === 'ended' || !s.order.includes(p)) return [];
const out: A[] = [{ type: 'tick' }];
if (s.phase === 'playing' && inGame(s, p) && s.rs[p]!.alive) {
const shared = flowOf(s.options) === 'shared';
const item = shared ? s.cur : s.rs[p]!.idx;
if (canType(s, p, item, undefined).ok && (!shared || s.curOpen)) {
const t = targetOf(s, p);
out.push({ type: 'submit', item, text: t }, { type: 'submit', item, text: `${t}x` }, { type: 'progress', item, text: t.slice(0, Math.ceil(t.length / 2)) });
}
}
return out.filter((x) => typing.validate(s, p, x).ok);
},
/** The texts are the same for everybody; only the countdown / gap hides them (no head start). */
secretsOf(s) {
let hidden: string | null = null;
if (s.phase === 'countdown' && s.items.length) hidden = s.items[0]!;
else if (s.phase === 'playing' && flowOf(s.options) === 'shared' && !s.curOpen) hidden = itemText(s, s.cur);
// The same words can come again (a refrain, a word in two topics): what was just shown is no secret.
return hidden !== null && hidden !== s.last?.text ? [hidden] : [];
},
};

View File

@@ -0,0 +1,85 @@
import { describe, expect, test } from 'bun:test';
import { accuracy, correctKeys, editDistance, keyCount, kpm, minTypingMs, normalize, toKeys } from './keys';
import { MAX_LINE, TOPICS, topicsFor, wrapLine, wrapLines } from './texts';
describe('keystrokes (두벌식)', () => {
test('syllables split into keys; compound vowels and double finals are two keys', () => {
expect(toKeys('강')).toBe('ㄱㅏㅇ');
expect(keyCount('가')).toBe(2);
expect(keyCount('왔')).toBe(4); // ㅇ ㅗ ㅏ ㅆ
expect(keyCount('닭')).toBe(4); // ㄷ ㅏ ㄹ ㄱ
expect(keyCount('의')).toBe(3);
expect(keyCount('까')).toBe(2); // 쌍자음 = one key (with shift)
expect(keyCount('사과 먹자.')).toBe(2 + 3 + 1 + 3 + 2 + 1);
expect(keyCount('Hello!')).toBe(6);
});
test('a syllable being composed counts by the keys already typed', () => {
expect(correctKeys('강', '가')).toBe(2);
expect(correctKeys('강', '강')).toBe(3);
// 도깨비불: typing 가나 shows 간 after the ㄴ.
expect(correctKeys('가나', '간')).toBe(3);
expect(correctKeys('사과', '사고')).toBe(4); // 사고 is on the way to 사과
expect(correctKeys('사과', '사기')).toBe(3);
expect(correctKeys('hello world', 'hello w')).toBe(7);
expect(correctKeys('abc', 'x')).toBe(0);
// A lone compound jamo from the IME is its keys.
expect(correctKeys('닭', '다ㄺ')).toBe(4);
});
test('normalize: ends trimmed, spaces folded', () => {
expect(normalize(' 가는 말이 \t고와야 ')).toBe('가는 말이 고와야');
});
test('accuracy and edit distance by characters', () => {
expect(editDistance('kitten', 'sitting')).toBe(3);
expect(editDistance('사과', '사과')).toBe(0);
expect(accuracy('사과나무', '사과나무')).toBe(1);
expect(accuracy('사과나무', '사과나')).toBeCloseTo(0.75);
expect(accuracy('abcd', '')).toBe(0);
expect(accuracy('abcd', 'abcdxxxx')).toBeCloseTo(0.5);
});
test('타수 and the paste guard', () => {
expect(kpm(100, 60_000)).toBe(100);
expect(kpm(50, 10_000)).toBe(300);
expect(kpm(10, 0)).toBe(0);
expect(minTypingMs(40)).toBe(150 + 1000);
});
});
describe('text bank', () => {
test('ids are unique and every language × category has topics', () => {
expect(new Set(TOPICS.map((t) => t.id)).size).toBe(TOPICS.length);
for (const lang of ['ko', 'en'] as const) for (const cat of ['word', 'short', 'long'] as const) expect(topicsFor(lang, cat).length).toBeGreaterThanOrEqual(4);
});
test('the topics the request names are there', () => {
const names = TOPICS.map((t) => `${t.lang}:${t.cat}:${t.name}`);
for (const n of ['ko:word:과일', 'ko:short:속담', 'ko:long:애국가', 'ko:long:별 헤는 밤']) expect(names).toContain(n);
});
test('only keys on a plain keyboard: complete Hangul syllables, ASCII letters, digits and common punctuation', () => {
const okChar = /^[가-힣a-zA-Z0-9 .,!?'"\-:;()]$/;
for (const t of TOPICS) {
for (const item of t.items) {
expect(item, t.id).toBe(normalize(item));
for (const ch of item) expect(okChar.test(ch), `${t.id}: "${item}" has "${ch}"`).toBe(true);
if (t.lang === 'ko' && t.cat !== 'long') expect(/[a-zA-Z]/.test(item), `${t.id}: ${item}`).toBe(false);
if (t.lang === 'en') expect(/[가-힣]/.test(item), `${t.id}: ${item}`).toBe(false);
}
if (t.cat === 'word') for (const w of t.items) expect(w.includes(' '), w).toBe(false);
if (t.cat !== 'long') expect(new Set(t.items).size, t.id).toBe(t.items.length);
}
});
test('long lines wrap at spaces and never lose a word', () => {
expect(wrapLine('aa bb cc dd', 5)).toEqual(['aa bb', 'cc dd']);
expect(wrapLine('short', 10)).toEqual(['short']);
for (const t of TOPICS.filter((x) => x.cat === 'long')) {
const w = wrapLines(t.items, t.lang);
for (const l of w) expect(l.length, `${t.id}: ${l}`).toBeLessThanOrEqual(MAX_LINE[t.lang]);
expect(w.join(' ')).toBe(t.items.join(' '));
}
});
});

View File

@@ -0,0 +1,81 @@
/**
* 타자 대결 typing math (docs/games/typing.md §5): keystrokes as a 두벌식 keyboard counts them, how much of a text is
* typed correctly so far, accuracy and 타수 (keystrokes per minute). Shared by the rules, the computer and the screen.
*/
const L = 'ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ';
/** Vowels as keys: compound vowels take two keys (ㅘ = ㅗ + ㅏ). */
const V = ['ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅗㅏ', 'ㅗㅐ', 'ㅗㅣ', 'ㅛ', 'ㅜ', 'ㅜㅓ', 'ㅜㅔ', 'ㅜㅣ', 'ㅠ', 'ㅡ', 'ㅡㅣ', 'ㅣ'];
/** Final consonants as keys: double finals take two keys (ㄳ = ㄱ + ㅅ). */
const T = ['', 'ㄱ', 'ㄲ', 'ㄱㅅ', 'ㄴ', 'ㄴㅈ', 'ㄴㅎ', 'ㄷ', 'ㄹ', 'ㄹㄱ', 'ㄹㅁ', 'ㄹㅂ', 'ㄹㅅ', 'ㄹㅌ', 'ㄹㅍ', 'ㄹㅎ', 'ㅁ', 'ㅂ', 'ㅂㅅ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'];
/** Lone compatibility jamo that are two keys (what an IME shows while a compound is being typed). */
const JAMO2: Record<string, string> = {
ㄳ: 'ㄱㅅ', ㄵ: 'ㄴㅈ', ㄶ: 'ㄴㅎ', ㄺ: 'ㄹㄱ', ㄻ: 'ㄹㅁ', ㄼ: 'ㄹㅂ', ㄽ: 'ㄹㅅ', ㄾ: 'ㄹㅌ', ㄿ: 'ㄹㅍ', ㅀ: 'ㄹㅎ', ㅄ: 'ㅂㅅ',
ㅘ: 'ㅗㅏ', ㅙ: 'ㅗㅐ', ㅚ: 'ㅗㅣ', ㅝ: 'ㅜㅓ', ㅞ: 'ㅜㅔ', ㅟ: 'ㅜㅣ', ㅢ: 'ㅡㅣ',
};
/** One string of keys (jamo, letters, spaces, punctuation) for a text, as typed on a 두벌식 keyboard. */
export function toKeys(text: string): string {
let out = '';
for (const ch of text) {
const c = ch.charCodeAt(0);
if (c >= 0xac00 && c <= 0xd7a3) {
const i = c - 0xac00;
out += L[Math.floor(i / 588)]! + V[Math.floor((i % 588) / 28)]! + T[i % 28]!;
} else out += JAMO2[ch] ?? ch;
}
return out;
}
/** Keystrokes of a text (`toKeys` length). */
export const keyCount = (text: string): number => toKeys(text).length;
/** What counts when comparing: same Unicode form, no spaces at the ends, single spaces inside. */
export const normalize = (text: string): string => text.normalize('NFC').replace(/\s+/g, ' ').trim();
/**
* Keys of `target` already typed correctly from the start (a syllable still being composed counts by its keys:
* "가" typed toward "강" is 2 of 3). The typed text is not normalized at the end: a trailing space is a key too.
*/
export function correctKeys(target: string, typed: string): number {
const a = toKeys(target);
const b = toKeys(typed.normalize('NFC').replace(/\s+/g, ' ').replace(/^ /, ''));
let n = 0;
while (n < a.length && n < b.length && a[n] === b[n]) n++;
return n;
}
/** Edit distance between two strings by characters (syllables), O(n·m) with two rows. */
export function editDistance(a: string, b: string): number {
const x = [...a];
const y = [...b];
let prev = Array.from({ length: y.length + 1 }, (_, j) => j);
for (let i = 1; i <= x.length; i++) {
const cur = [i];
for (let j = 1; j <= y.length; j++) cur[j] = Math.min(prev[j]! + 1, cur[j - 1]! + 1, prev[j - 1]! + (x[i - 1] === y[j - 1] ? 0 : 1));
prev = cur;
}
return prev[y.length]!;
}
/** Accuracy 0..1 of a submitted text: 1 − edits / the longer length (an empty answer is 0). */
export function accuracy(target: string, typed: string): number {
const t = normalize(target);
const s = normalize(typed);
if (!s.length) return 0;
const len = Math.max([...t].length, [...s].length);
return Math.max(0, 1 - editDistance(t, s) / len);
}
/** 타수: keystrokes per minute (0 when no time passed). */
export const kpm = (keys: number, ms: number): number => (ms > 0 ? Math.round((keys * 60_000) / ms) : 0);
/**
* Fastest a person can be: a submit or progress implying more than this many keystrokes per minute is refused (a paste).
* Record typists reach about 1,000~1,500타 for a short burst; a fixed reaction time comes on top.
*/
export const MAX_KPM = 2400;
export const REACTION_MS = 150;
/** Shortest time in which `keys` keystrokes can honestly be typed. */
export const minTypingMs = (keys: number): number => REACTION_MS + Math.ceil((keys * 60_000) / MAX_KPM);

View File

@@ -0,0 +1,826 @@
/**
* 타자 대결 text bank (docs/games/typing.md §4). Every topic belongs to one language and one category:
* - word: single words, one per item;
* - short: one sentence per item;
* - long: a whole text, typed line by line (long lines are wrapped at spaces, `wrapLines`).
* Poems and songs are public domain (the authors died more than 70 years ago, 애국가 is the national anthem);
* the fables are the site's own retellings. Only characters on a plain keyboard (no hanja, curly quotes or dashes).
*/
export type Lang = 'ko' | 'en';
export type Category = 'word' | 'short' | 'long';
export interface Topic {
id: string;
lang: Lang;
cat: Category;
/** Name in the settings ("과일", "애국가"). */
name: string;
/** Shown under a long text (author / source). */
by?: string;
/** word / short: the items. long: the lines of the text in order. */
items: readonly string[];
}
const words = (s: string) => s.trim().split(/\s+/);
const lines = (s: string) =>
s
.split('\n')
.map((l) => l.trim())
.filter(Boolean);
export const TOPICS: readonly Topic[] = [
// ---------------------------------------------------------------- 한국어 단어
{
id: 'ko-fruit',
lang: 'ko',
cat: 'word',
name: '과일',
items: words(`사과 바나나 딸기 포도 수박 참외 복숭아 자두 살구 체리 키위 망고 파인애플 귤 오렌지 레몬 라임 자몽 감 곶감 배 석류 무화과 블루베리
라즈베리 앵두 매실 유자 한라봉 천혜향 멜론 코코넛 아보카도 두리안 리치 용과 대추 모과 오디 크랜베리 파파야 구아바 패션프루트 산딸기 청포도 샤인머스캣`),
},
{
id: 'ko-animal',
lang: 'ko',
cat: 'word',
name: '동물',
items: words(`호랑이 사자 코끼리 기린 얼룩말 하마 코뿔소 원숭이 고릴라 침팬지 판다 곰 여우 늑대 사슴 노루 토끼 다람쥐 고슴도치 너구리 수달 비버
캥거루 코알라 펭귄 독수리 부엉이 올빼미 참새 까치 비둘기 앵무새 공작 타조 오리 거위 닭 병아리 강아지 고양이 햄스터 염소 양 소 돼지 말
낙타 거북이 악어 도마뱀 개구리 두꺼비 고래 돌고래 상어 문어 오징어 해파리 불가사리 나비 잠자리 무당벌레 개미 꿀벌 메뚜기 반딧불이`),
},
{
id: 'ko-veg',
lang: 'ko',
cat: 'word',
name: '채소',
items: words(`배추 무 당근 감자 고구마 양파 대파 쪽파 마늘 생강 오이 호박 애호박 가지 토마토 고추 피망 파프리카 시금치 상추 깻잎 양배추 브로콜리
콜리플라워 셀러리 아스파라거스 옥수수 콩나물 숙주 버섯 표고버섯 느타리 팽이버섯 연근 우엉 도라지 더덕 고사리 미나리 부추 냉이 달래 쑥 케일 비트 청경채`),
},
{
id: 'ko-country',
lang: 'ko',
cat: 'word',
name: '나라',
items: words(`대한민국 일본 중국 대만 몽골 베트남 태국 필리핀 인도네시아 말레이시아 싱가포르 인도 네팔 파키스탄 이란 이라크 튀르키예 이집트 케냐
나이지리아 남아프리카공화국 모로코 프랑스 독일 영국 이탈리아 스페인 포르투갈 네덜란드 벨기에 스위스 오스트리아 스웨덴 노르웨이 핀란드 덴마크
폴란드 그리스 러시아 우크라이나 미국 캐나다 멕시코 브라질 아르헨티나 칠레 페루 콜롬비아 쿠바 호주 뉴질랜드`),
},
{
id: 'ko-food',
lang: 'ko',
cat: 'word',
name: '음식',
items: words(`김치찌개 된장찌개 순두부찌개 부대찌개 비빔밥 불고기 갈비찜 삼겹살 떡볶이 김밥 라면 냉면 칼국수 수제비 잡채 김치전 파전 만두 순대 어묵
삼계탕 설렁탕 갈비탕 미역국 떡국 육개장 감자탕 닭갈비 족발 보쌈 짜장면 짬뽕 탕수육 볶음밥 오므라이스 돈가스 카레 초밥 우동 피자 햄버거
스파게티 샌드위치 샐러드 붕어빵 호떡 팥빙수 약과 송편 식혜`),
},
{
id: 'ko-job',
lang: 'ko',
cat: 'word',
name: '직업',
items: words(`의사 간호사 약사 선생님 교수 경찰관 소방관 군인 변호사 판사 검사 기자 작가 화가 가수 배우 감독 요리사 제빵사 농부 어부 목수
미용사 디자이너 건축가 과학자 연구원 프로그래머 비행기조종사 승무원 운전기사 택배기사 우체부 은행원 회계사 수의사 사진작가 통역사 번역가 아나운서
운동선수 코치 사서 상담사 정원사 바리스타`),
},
{
id: 'ko-sport',
lang: 'ko',
cat: 'word',
name: '스포츠',
items: words(`축구 야구 농구 배구 탁구 테니스 배드민턴 골프 볼링 당구 수영 다이빙 육상 마라톤 체조 태권도 유도 검도 씨름 복싱 레슬링 펜싱 양궁
사격 역도 스키 스노보드 스케이트 컬링 아이스하키 핸드볼 럭비 하키 승마 조정 카누 서핑 요트 클라이밍 사이클 철인삼종 피구 족구 줄넘기`),
},
{
id: 'ko-idiom',
lang: 'ko',
cat: 'word',
name: '사자성어',
items: words(`일석이조 다다익선 동문서답 이심전심 오리무중 우왕좌왕 자업자득 작심삼일 전화위복 죽마고우 천고마비 청출어람 토사구팽 팔방미인 표리부동
학수고대 함흥차사 호시탐탐 고진감래 과유불급 금상첨화 대기만성 마이동풍 백문불여일견 사필귀정 새옹지마 십시일반 아전인수 역지사지 온고지신
유비무환 일취월장 일편단심 적반하장 조삼모사 진퇴양난 칠전팔기 타산지석 동고동락 일거양득`),
},
// ---------------------------------------------------------------- 한국어 짧은글
{
id: 'ko-proverb',
lang: 'ko',
cat: 'short',
name: '속담',
items: lines(`
가는 말이 고와야 오는 말이 곱다.
낮말은 새가 듣고 밤말은 쥐가 듣는다.
천 리 길도 한 걸음부터.
세 살 버릇 여든까지 간다.
소 잃고 외양간 고친다.
원숭이도 나무에서 떨어질 때가 있다.
말 한마디로 천 냥 빚을 갚는다.
티끌 모아 태산.
백지장도 맞들면 낫다.
고래 싸움에 새우 등 터진다.
돌다리도 두들겨 보고 건너라.
바늘 도둑이 소도둑 된다.
콩 심은 데 콩 나고 팥 심은 데 팥 난다.
등잔 밑이 어둡다.
호랑이도 제 말 하면 온다.
호랑이에게 물려 가도 정신만 차리면 산다.
우물을 파도 한 우물을 파라.
하늘이 무너져도 솟아날 구멍이 있다.
벼는 익을수록 고개를 숙인다.
빈 수레가 요란하다.
개구리 올챙이 적 생각 못 한다.
누워서 떡 먹기.
식은 죽 먹기.
가랑비에 옷 젖는 줄 모른다.
발 없는 말이 천 리 간다.
아니 땐 굴뚝에 연기 날까.
오르지 못할 나무는 쳐다보지도 마라.
윗물이 맑아야 아랫물이 맑다.
사공이 많으면 배가 산으로 간다.
서당 개 삼 년이면 풍월을 읊는다.
쥐구멍에도 볕 들 날 있다.
구슬이 서 말이라도 꿰어야 보배다.
금강산도 식후경.
될성부른 나무는 떡잎부터 알아본다.
믿는 도끼에 발등 찍힌다.
남의 떡이 더 커 보인다.
도토리 키 재기.
똥 묻은 개가 겨 묻은 개 나무란다.
열 번 찍어 안 넘어가는 나무 없다.
작은 고추가 더 맵다.
시작이 반이다.
백 번 듣는 것이 한 번 보는 것만 못하다.
얌전한 고양이가 부뚜막에 먼저 올라간다.
우는 아이 젖 준다.
제 눈에 안경.
공든 탑이 무너지랴.
꿩 먹고 알 먹는다.
번갯불에 콩 볶아 먹겠다.
산 넘어 산이다.
목마른 사람이 우물 판다.
`),
},
{
id: 'ko-quote',
lang: 'ko',
cat: 'short',
name: '명언',
items: lines(`
아는 것이 힘이다.
나는 생각한다, 그러므로 나는 존재한다.
시간은 금이다.
내일 지구가 멸망할지라도 나는 오늘 한 그루의 사과나무를 심겠다.
배우고 때때로 익히면 또한 기쁘지 아니한가.
아는 것을 안다고 하고 모르는 것을 모른다고 하는 것이 아는 것이다.
천재는 1퍼센트의 영감과 99퍼센트의 노력으로 이루어진다.
실패는 성공의 어머니이다.
오늘 할 일을 내일로 미루지 마라.
너 자신을 알라.
인생은 짧고 예술은 길다.
펜은 칼보다 강하다.
행복은 습관이다, 그것을 몸에 지녀라.
가장 큰 영광은 한 번도 실패하지 않음이 아니라 실패할 때마다 다시 일어서는 데 있다.
세 사람이 길을 가면 그중에 반드시 나의 스승이 있다.
배움에는 왕도가 없다.
늦었다고 생각할 때가 가장 빠를 때이다.
꿈을 꿀 수 있다면 그 꿈을 이룰 수도 있다.
한 번의 실패와 영원한 실패를 혼동하지 마라.
건강한 몸에 건강한 정신이 깃든다.
지금 이 순간을 즐겨라.
작은 기회로부터 종종 위대한 업적이 시작된다.
평생 살 것처럼 꿈을 꾸고 내일 죽을 것처럼 오늘을 살아라.
노력은 배신하지 않는다.
웃음은 마음의 보약이다.
`),
},
{
id: 'ko-twister',
lang: 'ko',
cat: 'short',
name: '잰말놀이',
items: lines(`
간장 공장 공장장은 강 공장장이고 된장 공장 공장장은 공 공장장이다.
내가 그린 기린 그림은 잘 그린 기린 그림이다.
저기 있는 말뚝이 말 맬 말뚝이냐 말 못 맬 말뚝이냐.
경찰청 쇠창살 외철창살 검찰청 쇠창살 쌍철창살.
들의 콩깍지는 깐 콩깍지인가 안 깐 콩깍지인가.
앞집 팥죽은 붉은 팥 풋팥죽이고 뒷집 콩죽은 햇콩 단콩 콩죽이다.
한영양장점 옆 한양양장점, 한양양장점 옆 한영양장점.
저 분은 백 법학박사이고 이 분은 박 법학박사이다.
상표 붙은 큰 깡통은 깐 깡통인가 안 깐 깡통인가.
작은 토끼 토끼 통 옆 큰 토끼 토끼 통.
중앙청 창살은 쌍창살이고 시청의 창살은 외창살이다.
서울 특허 허가과 허가과장 허과장.
철수 책상 철 책상, 영희 책상 쇠 책상.
신진 샹송 가수의 신춘 샹송 쇼.
고려고 교복은 고급 교복이고 고려고 교복은 고급 원단을 사용했다.
`),
},
{
id: 'ko-daily',
lang: 'ko',
cat: 'short',
name: '일상 문장',
items: lines(`
오늘 점심은 뭘 먹을까요?
주말에 같이 영화 보러 갈래요?
창밖에 첫눈이 소복소복 내리고 있어요.
버스가 생각보다 일찍 와서 다행이에요.
따뜻한 차 한잔 마시면서 쉬어 가요.
내일은 아침 일찍 일어나야 해요.
강아지가 꼬리를 흔들며 반겨 줘요.
도서관에서 재미있는 책을 빌렸어요.
비가 오니까 우산을 꼭 챙기세요.
생일 축하해요, 행복한 하루 보내세요!
공원에 벚꽃이 활짝 피었어요.
배가 고파서 라면을 끓여 먹었어요.
오랜만에 친구에게 전화를 걸었어요.
시험이 끝나서 마음이 홀가분해요.
이번 여름에는 바다로 여행을 가요.
엘리베이터가 고장 나서 계단으로 올라갔어요.
할머니 댁 마당에 감나무가 있어요.
새로 산 운동화가 아주 편해요.
밤하늘에 별이 반짝반짝 빛나요.
오늘도 수고 많으셨습니다.
아침마다 동네를 한 바퀴 달려요.
냉장고에 우유가 다 떨어졌어요.
다음 역은 시청, 시청역입니다.
천천히 하나씩 해 보면 돼요.
고마운 마음을 담아 편지를 썼어요.
`),
},
// ---------------------------------------------------------------- 한국어 긴글
{
id: 'ko-anthem',
lang: 'ko',
cat: 'long',
name: '애국가',
by: '대한민국 국가',
items: lines(`
동해 물과 백두산이 마르고 닳도록
하느님이 보우하사 우리나라 만세
무궁화 삼천리 화려 강산
대한 사람 대한으로 길이 보전하세
남산 위에 저 소나무 철갑을 두른 듯
바람 서리 불변함은 우리 기상일세
무궁화 삼천리 화려 강산
대한 사람 대한으로 길이 보전하세
가을 하늘 공활한데 높고 구름 없이
밝은 달은 우리 가슴 일편단심일세
무궁화 삼천리 화려 강산
대한 사람 대한으로 길이 보전하세
이 기상과 이 맘으로 충성을 다하여
괴로우나 즐거우나 나라 사랑하세
무궁화 삼천리 화려 강산
대한 사람 대한으로 길이 보전하세
`),
},
{
id: 'ko-stars',
lang: 'ko',
cat: 'long',
name: '별 헤는 밤',
by: '윤동주',
items: lines(`
계절이 지나가는 하늘에는
가을로 가득 차 있습니다.
나는 아무 걱정도 없이
가을 속의 별들을 다 헤일 듯합니다.
가슴속에 하나 둘 새겨지는 별을
이제 다 못 헤는 것은
쉬이 아침이 오는 까닭이요,
내일 밤이 남은 까닭이요,
아직 나의 청춘이 다하지 않은 까닭입니다.
별 하나에 추억과
별 하나에 사랑과
별 하나에 쓸쓸함과
별 하나에 동경과
별 하나에 시와
별 하나에 어머니, 어머니,
어머님, 나는 별 하나에 아름다운 말 한마디씩 불러 봅니다.
소학교 때 책상을 같이 했던 아이들의 이름과,
패, 경, 옥 이런 이국 소녀들의 이름과,
벌써 아기 어머니 된 계집애들의 이름과,
가난한 이웃 사람들의 이름과,
비둘기, 강아지, 토끼, 노새, 노루,
프랑시스 잠, 라이너 마리아 릴케 이런 시인의 이름을 불러 봅니다.
이네들은 너무나 멀리 있습니다.
별이 아슬히 멀듯이,
어머님,
그리고 당신은 멀리 북간도에 계십니다.
나는 무엇인지 그리워
이 많은 별빛이 내린 언덕 위에
내 이름자를 써 보고,
흙으로 덮어 버리었습니다.
딴은 밤을 새워 우는 벌레는
부끄러운 이름을 슬퍼하는 까닭입니다.
그러나 겨울이 지나고 나의 별에도 봄이 오면
무덤 위에 파란 잔디가 피어나듯이
내 이름자 묻힌 언덕 위에도
자랑처럼 풀이 무성할 거외다.
`),
},
{
id: 'ko-prologue',
lang: 'ko',
cat: 'long',
name: '서시',
by: '윤동주',
items: lines(`
죽는 날까지 하늘을 우러러
한 점 부끄럼이 없기를,
잎새에 이는 바람에도
나는 괴로워했다.
별을 노래하는 마음으로
모든 죽어 가는 것을 사랑해야지
그리고 나한테 주어진 길을
걸어가야겠다.
오늘 밤에도 별이 바람에 스치운다.
`),
},
{
id: 'ko-azalea',
lang: 'ko',
cat: 'long',
name: '진달래꽃',
by: '김소월',
items: lines(`
나 보기가 역겨워
가실 때에는
말없이 고이 보내 드리우리다.
영변에 약산
진달래꽃
아름 따다 가실 길에 뿌리우리다.
가시는 걸음걸음
놓인 그 꽃을
사뿐히 즈려밟고 가시옵소서.
나 보기가 역겨워
가실 때에는
죽어도 아니 눈물 흘리우리다.
`),
},
{
id: 'ko-mountain-flower',
lang: 'ko',
cat: 'long',
name: '산유화',
by: '김소월',
items: lines(`
산에는 꽃 피네
꽃이 피네
갈 봄 여름 없이
꽃이 피네
산에
산에
피는 꽃은
저만치 혼자서 피어 있네
산에서 우는 작은 새요
꽃이 좋아
산에서
사노라네
산에는 꽃 지네
꽃이 지네
갈 봄 여름 없이
꽃이 지네
`),
},
{
id: 'ko-silence',
lang: 'ko',
cat: 'long',
name: '님의 침묵',
by: '한용운',
items: lines(`
님은 갔습니다. 아아, 사랑하는 나의 님은 갔습니다.
푸른 산빛을 깨치고 단풍나무 숲을 향하여 난 작은 길을 걸어서 차마 떨치고 갔습니다.
황금의 꽃같이 굳고 빛나던 옛 맹세는 차디찬 티끌이 되어서 한숨의 미풍에 날아갔습니다.
날카로운 첫 키스의 추억은 나의 운명의 지침을 돌려 놓고 뒷걸음쳐서 사라졌습니다.
나는 향기로운 님의 말소리에 귀먹고 꽃다운 님의 얼굴에 눈멀었습니다.
사랑도 사람의 일이라 만날 때에 미리 떠날 것을 염려하고 경계하지 아니한 것은 아니지만,
이별은 뜻밖의 일이 되고 놀란 가슴은 새로운 슬픔에 터집니다.
그러나 이별을 쓸데없는 눈물의 원천을 만들고 마는 것은 스스로 사랑을 깨치는 것인 줄 아는 까닭에,
걷잡을 수 없는 슬픔의 힘을 옮겨서 새 희망의 정수박이에 들이부었습니다.
우리는 만날 때에 떠날 것을 염려하는 것과 같이 떠날 때에 다시 만날 것을 믿습니다.
아아, 님은 갔지마는 나는 님을 보내지 아니하였습니다.
제 곡조를 못 이기는 사랑의 노래는 님의 침묵을 휩싸고 돕니다.
`),
},
{
id: 'ko-hunmin',
lang: 'ko',
cat: 'long',
name: '훈민정음 서문',
by: '세종대왕(현대어 풀이)',
items: lines(`
나랏말이 중국과 달라 한자와는 서로 통하지 아니하므로,
어리석은 백성이 말하고자 하는 바가 있어도
마침내 제 뜻을 능히 펴지 못하는 사람이 많다.
내가 이를 불쌍히 여겨 새로 스물여덟 자를 만드니,
사람마다 하여금 쉽게 익혀 날마다 씀에 편안하게 하고자 할 따름이다.
`),
},
{
id: 'ko-heungbu',
lang: 'ko',
cat: 'long',
name: '흥부와 놀부',
by: '전래 동화(이 사이트에서 다시 씀)',
items: lines(`
옛날 어느 마을에 욕심 많은 형 놀부와 마음씨 착한 아우 흥부가 살았어요.
부모님이 돌아가시자 놀부는 재산을 모두 차지하고 흥부네 식구를 내쫓았어요.
흥부는 가난했지만 늘 웃으며 부지런히 일했어요.
어느 봄날, 흥부는 다리가 부러진 제비 한 마리를 정성껏 고쳐 주었어요.
이듬해 돌아온 제비는 박씨 하나를 물어다 주었어요.
가을이 되어 커다란 박을 타 보니 쌀과 비단과 금은보화가 쏟아져 나왔어요.
소문을 들은 놀부는 일부러 제비 다리를 부러뜨리고 고쳐 주는 척했어요.
놀부가 받은 박을 타자 도깨비와 똥물이 쏟아져 나와 집이 엉망이 되었어요.
흥부는 빈털터리가 된 형을 따뜻하게 맞아 주었고,
놀부는 잘못을 뉘우치고 형제가 사이좋게 살았답니다.
`),
},
{
id: 'ko-sun-moon',
lang: 'ko',
cat: 'long',
name: '해님 달님',
by: '전래 동화(이 사이트에서 다시 씀)',
items: lines(`
깊은 산골에 엄마와 오누이가 살았어요.
떡을 팔고 돌아오던 엄마 앞에 호랑이가 나타났어요.
떡 하나 주면 안 잡아먹지! 호랑이는 떡을 모두 빼앗고 엄마까지 잡아먹었어요.
호랑이는 엄마 옷을 입고 오누이가 사는 집에 찾아갔어요.
문틈으로 내민 털북숭이 손을 보고 오누이는 호랑이인 것을 알아챘어요.
오누이는 뒷문으로 빠져나가 우물가 나무 위로 올라갔어요.
하느님, 저희를 살려 주시려거든 튼튼한 동아줄을 내려 주세요.
하늘에서 내려온 동아줄을 잡고 오누이는 하늘로 올라갔어요.
뒤따라 썩은 동아줄을 잡은 호랑이는 수수밭에 떨어지고 말았어요.
그 뒤 오빠는 달이 되고 누이는 해가 되어 세상을 밝게 비추었답니다.
`),
},
{
id: 'ko-tortoise',
lang: 'ko',
cat: 'long',
name: '토끼와 거북',
by: '이솝 우화(이 사이트에서 다시 씀)',
items: lines(`
발이 빠른 토끼는 느림보 거북을 늘 놀려 댔어요.
참다못한 거북이 말했어요. 그럼 저 언덕까지 달리기 시합을 하자.
출발하자마자 토끼는 저만치 앞서 나갔어요.
뒤를 돌아보니 거북은 아직 출발선 근처에서 엉금엉금 기고 있었어요.
토끼는 나무 그늘에 누워 한숨 자고 가도 이기겠다고 생각했어요.
그사이 거북은 한 번도 쉬지 않고 한 걸음 한 걸음 걸어갔어요.
잠에서 깬 토끼가 허둥지둥 뛰어갔지만 거북은 벌써 언덕 위에 있었어요.
꾸준히 노력하는 사람이 끝내 이긴다는 이야기랍니다.
`),
},
// ---------------------------------------------------------------- English words
{
id: 'en-fruit',
lang: 'en',
cat: 'word',
name: 'Fruits',
items: words(`apple banana cherry grape lemon lime mango melon orange peach pear plum kiwi papaya pineapple strawberry blueberry raspberry
blackberry watermelon apricot coconut fig guava lychee nectarine olive pomegranate tangerine cranberry avocado date grapefruit persimmon quince`),
},
{
id: 'en-animal',
lang: 'en',
cat: 'word',
name: 'Animals',
items: words(`tiger lion elephant giraffe zebra hippo rhino monkey gorilla panda bear fox wolf deer rabbit squirrel hedgehog raccoon otter beaver
kangaroo koala penguin eagle owl sparrow parrot peacock ostrich duck goose chicken puppy kitten hamster goat sheep cow pig horse camel turtle
crocodile lizard frog whale dolphin shark octopus squid jellyfish butterfly dragonfly ladybug ant bee`),
},
{
id: 'en-color',
lang: 'en',
cat: 'word',
name: 'Colors',
items: words(`red orange yellow green blue purple pink brown black white gray silver gold navy beige ivory maroon violet indigo turquoise
crimson scarlet lavender olive teal coral peach mint lemon cream`),
},
{
id: 'en-country',
lang: 'en',
cat: 'word',
name: 'Countries',
items: words(`Korea Japan China Mongolia Vietnam Thailand Philippines Indonesia Malaysia Singapore India Nepal Pakistan Iran Iraq Egypt Kenya Nigeria
Morocco France Germany England Italy Spain Portugal Netherlands Belgium Switzerland Austria Sweden Norway Finland Denmark Poland Greece Russia
Ukraine Canada Mexico Brazil Argentina Chile Peru Colombia Cuba Australia`),
},
{
id: 'en-food',
lang: 'en',
cat: 'word',
name: 'Food',
items: words(`pizza burger pasta salad sandwich noodles rice bread cheese butter cookie cake muffin pancake waffle donut bagel cereal yogurt
omelet sausage bacon steak chicken soup curry taco burrito sushi dumpling popcorn pretzel chocolate candy pudding pie toast honey jam`),
},
{
id: 'en-job',
lang: 'en',
cat: 'word',
name: 'Jobs',
items: words(`doctor nurse teacher farmer pilot police firefighter soldier lawyer judge reporter writer painter singer actor dancer chef baker
carpenter plumber barber designer architect scientist engineer programmer driver mailman banker dentist vet photographer librarian coach`),
},
{
id: 'en-sport',
lang: 'en',
cat: 'word',
name: 'Sports',
items: words(`soccer baseball basketball volleyball tennis badminton golf bowling swimming diving running marathon boxing wrestling fencing archery
skiing skating hockey rugby cricket cycling surfing sailing rowing climbing karate judo taekwondo gymnastics`),
},
// ---------------------------------------------------------------- English short
{
id: 'en-proverb',
lang: 'en',
cat: 'short',
name: 'Proverbs',
items: lines(`
Actions speak louder than words.
All that glitters is not gold.
A picture is worth a thousand words.
Better late than never.
The early bird catches the worm.
Practice makes perfect.
Rome was not built in a day.
When in Rome, do as the Romans do.
Where there is a will, there is a way.
Two heads are better than one.
Every cloud has a silver lining.
Honesty is the best policy.
Look before you leap.
Time flies like an arrow.
No pain, no gain.
Easy come, easy go.
Knowledge is power.
A friend in need is a friend indeed.
Do not judge a book by its cover.
Do not count your chickens before they hatch.
Birds of a feather flock together.
The pen is mightier than the sword.
An apple a day keeps the doctor away.
Slow and steady wins the race.
Laughter is the best medicine.
Necessity is the mother of invention.
Still waters run deep.
Absence makes the heart grow fonder.
There is no place like home.
You cannot have your cake and eat it too.
Too many cooks spoil the broth.
Out of sight, out of mind.
Curiosity killed the cat.
Great minds think alike.
The grass is always greener on the other side.
Do not put all your eggs in one basket.
It is no use crying over spilt milk.
Strike while the iron is hot.
Beauty is in the eye of the beholder.
A journey of a thousand miles begins with a single step.
`),
},
{
id: 'en-quote',
lang: 'en',
cat: 'short',
name: 'Famous quotes',
items: lines(`
I think, therefore I am.
Know thyself.
To be, or not to be, that is the question.
Genius is one percent inspiration and ninety-nine percent perspiration.
Well done is better than well said.
An investment in knowledge pays the best interest.
Life is really simple, but we insist on making it complicated.
The only thing we have to fear is fear itself.
Imagination is more important than knowledge.
It does not matter how slowly you go as long as you do not stop.
Whatever you are, be a good one.
In the middle of difficulty lies opportunity.
Be yourself; everyone else is already taken.
Simplicity is the ultimate sophistication.
The best way out is always through.
Turn your face to the sun and the shadows fall behind you.
Fortune favors the bold.
Happiness depends upon ourselves.
Brevity is the soul of wit.
All the world's a stage.
`),
},
{
id: 'en-twister',
lang: 'en',
cat: 'short',
name: 'Tongue twisters',
items: lines(`
She sells seashells by the seashore.
Peter Piper picked a peck of pickled peppers.
How much wood would a woodchuck chuck if a woodchuck could chuck wood?
Red lorry, yellow lorry, red lorry, yellow lorry.
Unique New York, unique New York, you know you need unique New York.
Fuzzy Wuzzy was a bear. Fuzzy Wuzzy had no hair.
I scream, you scream, we all scream for ice cream.
A big black bug bit a big black bear.
Six slippery snails slid slowly seaward.
Fred fed Ted bread, and Ted fed Fred bread.
Toy boat, toy boat, toy boat.
Betty Botter bought some butter, but she said the butter's bitter.
Can you can a can as a canner can can a can?
Which witch switched the Swiss wristwatches?
Eleven benevolent elephants.
`),
},
{
id: 'en-pangram',
lang: 'en',
cat: 'short',
name: 'Pangrams',
items: lines(`
The quick brown fox jumps over the lazy dog.
Pack my box with five dozen liquor jugs.
How vexingly quick daft zebras jump!
Sphinx of black quartz, judge my vow.
The five boxing wizards jump quickly.
Jackdaws love my big sphinx of quartz.
Bright vixens jump; dozy fowl quack.
Waltz, bad nymph, for quick jigs vex.
Quick zephyrs blow, vexing daft Jim.
Crazy Fredrick bought many very exquisite opal jewels.
`),
},
// ---------------------------------------------------------------- English long
{
id: 'en-gettysburg',
lang: 'en',
cat: 'long',
name: 'Gettysburg Address',
by: 'Abraham Lincoln, 1863',
items: lines(`
Four score and seven years ago our fathers brought forth on this continent, a new nation,
conceived in Liberty, and dedicated to the proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure.
We are met on a great battle-field of that war.
We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live.
It is altogether fitting and proper that we should do this.
But, in a larger sense, we can not dedicate, we can not consecrate, we can not hallow this ground.
The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract.
The world will little note, nor long remember what we say here, but it can never forget what they did here.
It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced.
It is rather for us to be here dedicated to the great task remaining before us,
that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion,
that we here highly resolve that these dead shall not have died in vain,
that this nation, under God, shall have a new birth of freedom,
and that government of the people, by the people, for the people, shall not perish from the earth.
`),
},
{
id: 'en-road',
lang: 'en',
cat: 'long',
name: 'The Road Not Taken',
by: 'Robert Frost, 1916',
items: lines(`
Two roads diverged in a yellow wood,
And sorry I could not travel both
And be one traveler, long I stood
And looked down one as far as I could
To where it bent in the undergrowth;
Then took the other, as just as fair,
And having perhaps the better claim,
Because it was grassy and wanted wear;
Though as for that the passing there
Had worn them really about the same,
And both that morning equally lay
In leaves no step had trodden black.
Oh, I kept the first for another day!
Yet knowing how way leads on to way,
I doubted if I should ever come back.
I shall be telling this with a sigh
Somewhere ages and ages hence:
Two roads diverged in a wood, and I,
I took the one less traveled by,
And that has made all the difference.
`),
},
{
id: 'en-sonnet18',
lang: 'en',
cat: 'long',
name: 'Sonnet 18',
by: 'William Shakespeare',
items: lines(`
Shall I compare thee to a summer's day?
Thou art more lovely and more temperate:
Rough winds do shake the darling buds of May,
And summer's lease hath all too short a date;
Sometime too hot the eye of heaven shines,
And often is his gold complexion dimm'd;
And every fair from fair sometime declines,
By chance or nature's changing course untrimm'd;
But thy eternal summer shall not fade,
Nor lose possession of that fair thou ow'st;
Nor shall Death brag thou wander'st in his shade,
When in eternal lines to time thou grow'st:
So long as men can breathe or eyes can see,
So long lives this, and this gives life to thee.
`),
},
{
id: 'en-daffodils',
lang: 'en',
cat: 'long',
name: 'Daffodils',
by: 'William Wordsworth',
items: lines(`
I wandered lonely as a cloud
That floats on high o'er vales and hills,
When all at once I saw a crowd,
A host, of golden daffodils;
Beside the lake, beneath the trees,
Fluttering and dancing in the breeze.
Continuous as the stars that shine
And twinkle on the milky way,
They stretched in never-ending line
Along the margin of a bay:
Ten thousand saw I at a glance,
Tossing their heads in sprightly dance.
`),
},
{
id: 'en-twinkle',
lang: 'en',
cat: 'long',
name: 'Twinkle, Twinkle, Little Star',
by: 'Jane Taylor, 1806',
items: lines(`
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
When the blazing sun is gone,
When he nothing shines upon,
Then you show your little light,
Twinkle, twinkle, all the night.
Twinkle, twinkle, little star,
How I wonder what you are!
`),
},
{
id: 'en-preamble',
lang: 'en',
cat: 'long',
name: 'US Constitution Preamble',
by: '1787',
items: lines(`
We the People of the United States, in Order to form a more perfect Union,
establish Justice, insure domestic Tranquility, provide for the common defence,
promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity,
do ordain and establish this Constitution for the United States of America.
`),
},
{
id: 'en-hare',
lang: 'en',
cat: 'long',
name: 'The Tortoise and the Hare',
by: "Aesop's fable (retold for this site)",
items: lines(`
A hare was always laughing at a tortoise for being so slow.
One day the tortoise said, "Let us race to the top of that hill."
The hare laughed and agreed, and the race began.
In no time the hare was far ahead, and the tortoise was barely past the start.
"I have plenty of time," thought the hare, and he lay down under a tree for a nap.
Meanwhile the tortoise kept walking, one small step after another, without ever stopping.
When the hare woke up and dashed to the hill, the tortoise was already waiting at the top.
Slow and steady wins the race.
`),
},
];
export const TOPIC_BY_ID: Readonly<Record<string, Topic>> = Object.fromEntries(TOPICS.map((t) => [t.id, t]));
export const topicsFor = (lang: Lang, cat: Category): Topic[] => TOPICS.filter((t) => t.lang === lang && t.cat === cat);
/** Longest line typed at once (long texts): Korean lines are wider on screen than English ones. */
export const MAX_LINE: Readonly<Record<Lang, number>> = { ko: 34, en: 52 };
/** Breaks a long line at spaces so each piece fits in one row of the typing box (greedy, words are never split). */
export function wrapLine(line: string, max: number): string[] {
if (line.length <= max) return [line];
const out: string[] = [];
let cur = '';
for (const w of line.split(' ')) {
if (!cur) cur = w;
else if (cur.length + 1 + w.length <= max) cur += ` ${w}`;
else {
out.push(cur);
cur = w;
}
}
if (cur) out.push(cur);
return out;
}
export const wrapLines = (items: readonly string[], lang: Lang): string[] => items.flatMap((l) => wrapLine(l, MAX_LINE[lang]));

View File

@@ -0,0 +1,235 @@
/** 타자 대결 options, actions, state and view types (docs/games/typing.md §2, §8). */
import { z } from 'zod';
import type { PlayerId } from '@bg/engine';
import type { Category, Lang } from './texts';
export type { Category, Lang } from './texts';
const lit = <T extends number | null>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
export const MODES = ['first', 'survival', 'speed', 'accuracy', 'timeAttack', 'practice'] as const;
export type Mode = (typeof MODES)[number];
export const MODE_KO: Record<Mode, string> = { first: '가장 먼저 입력', survival: '서바이벌', speed: '타수 비교', accuracy: '정확도 대결', timeAttack: '타임어택', practice: '연습' };
export const ELIMS = ['wrong', 'sentence', 'interval', 'deadline'] as const;
export type Elim = (typeof ELIMS)[number];
export const ELIM_KO: Record<Elim, string> = { wrong: '틀렸을 때', sentence: '문장별(가장 늦게 친 사람)', interval: '시간별(가장 적게 친 사람)', deadline: '시간 초과(제한 시간 안에 못 치면)' };
export const CATEGORY_KO: Record<Category, string> = { word: '단어', short: '짧은글', long: '긴글' };
export const LANG_KO: Record<Lang, string> = { ko: '한국어', en: '영어' };
export const typingOptionsSchema = z.object({
lang: z.enum(['ko', 'en']).default('ko').meta({ title: '언어', labels: LANG_KO }),
mode: z.enum(MODES).default('first').meta({ title: '대결 방식', labels: MODE_KO }),
category: z.enum(['word', 'short', 'long']).default('short').meta({ title: '대결 종목', labels: CATEGORY_KO }),
/** Topic ids (texts.ts); several may be picked. Empty, or none that fits the language and category = every topic of it. */
topics: z.array(z.string().regex(/^[a-z0-9-]{1,40}$/)).max(40).default([]).meta({ title: '주제(여러 개 고를 수 있어요, 비우면 전체)' }),
rounds: z.number().int().min(1).max(10).default(3).meta({ title: '라운드 수(1~10)' }),
elimination: z.enum(ELIMS).default('wrong').meta({ title: '서바이벌 탈락 조건', labels: ELIM_KO }),
lives: z.number().int().min(1).max(5).default(3).meta({ title: '서바이벌 목숨(틀렸을 때 탈락)' }),
intervalSec: lit(10, 15, 20, 30).default(15).meta({ title: '서바이벌 시간별: 탈락 간격', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초' } }),
/**
* 0 = 자동 (from the text's length), null = 무제한. One item (가장 먼저 입력·서바이벌) or one round (타수 비교·정확도 대결).
*/
timeLimit: lit<0 | 10 | 20 | 30 | 60 | 120 | 180 | 300 | null>(0, 10, 20, 30, 60, 120, 180, 300, null)
.default(0)
.meta({ title: '제한 시간', labels: { 0: '자동(글 길이에 맞게)', 10: '10초', 20: '20초', 30: '30초', 60: '1분', 120: '2분', 180: '3분', 300: '5분', null: '무제한' } }),
attackSec: lit(30, 60, 90, 120).default(60).meta({ title: '타임어택 시간', labels: { 30: '30초', 60: '1분', 90: '1분 30초', 120: '2분' } }),
});
export type TypingOptions = z.infer<typeof typingOptionsSchema>;
const text = z.string().max(400);
const idx = z.number().int().min(0).max(100_000);
export const typingActionSchema = z.discriminatedUnion('type', [
/** What I have typed so far on item `item` (streamed, throttled by the screen). */
z.object({ type: z.literal('progress'), item: idx, text }),
/** Enter on item `item`. */
z.object({ type: z.literal('submit'), item: idx, text }),
]);
export type TypingClientAction = z.infer<typeof typingActionSchema>;
/** Client actions plus system-only ones (server clock, leaving). */
export type TypingAction = TypingClientAction | { type: 'tick' } | { type: 'leave' };
/**
* `shared`: everybody types the same item at the same time (가장 먼저 입력, 서바이벌 except 시간별).
* `lane`: everybody goes through the round's items on their own (타수 비교, 정확도 대결, 타임어택, 서바이벌 시간별, 연습).
*/
export type Flow = 'shared' | 'lane';
export type Phase = 'countdown' | 'playing' | 'roundEnd' | 'ended';
/** Why a survivor was knocked out. */
export type OutReason = 'lives' | 'slowest' | 'least' | 'time' | 'left';
/** One player in the current round. */
export interface RoundSeat {
/** lane: index of the item I am on (may run past the end: finished). */
idx: number;
/** lane: when my current item began (server time). */
itemAt: number;
/** Keys of the current item typed correctly so far (last progress). */
prog: number;
/** Items done this round (shared: items I solved; lane: items submitted). */
done: number;
/** Correct keystrokes this round (keys × accuracy of each submitted item). */
keys: number;
/** Typing time this round (ms) that `keys` took. */
ms: number;
/** Accuracy accumulator: Σ accuracy × target length, Σ target length. */
accSum: number;
accLen: number;
/** Wrong submits this round. */
wrong: number;
/** lane: when I finished every item (or was stopped); null while typing. */
finishedAt: number | null;
/** Survival. */
lives: number;
alive: boolean;
outReason: OutReason | null;
/** Survival: rank in this round (1 = survivor), set when knocked out / at the end. */
place: number | null;
/** shared: solved the current item; when (server time). */
solvedAt: number | null;
/** Server times of recent actions (rate limit). */
recent: number[];
/** 연습: the best 타수 of one line this round; whether the current line's clock has started (at its first key). */
best?: number;
started?: boolean;
}
export interface SeatTotals {
points: number;
keys: number;
ms: number;
accSum: number;
accLen: number;
wrong: number;
left: boolean;
}
/** One finished round, for the result table. */
export interface RoundResult {
round: number;
/** Players with their round numbers, best first. */
rows: { id: PlayerId; rank: number; points: number; kpm: number; acc: number; done: number; out: OutReason | null }[];
/** Players who got the round's point(s). */
winners: PlayerId[];
summary: string;
}
/** What happened to the last shared item (shown during the short gap before the next one). */
export interface LastItem {
text: string;
/** 가장 먼저 입력: who typed it first (null = time ran out). */
winner: PlayerId | null;
kpm: number;
/** 서바이벌: who was knocked out by this item. */
out: PlayerId[];
}
export interface TypingFinal {
ranking: { id: PlayerId; rank: number; points: number; kpm: number; acc: number; left: boolean }[];
summary: string;
}
export interface TypingState {
options: TypingOptions;
/** Topic ids in play (the options' topics that fit, or every topic of the language and category). */
topicIds: string[];
order: PlayerId[];
phase: Phase;
round: number;
/** countdown / roundEnd: when it ends. */
phaseEndsAt: number | null;
roundStartedAt: number;
/** lane: the round's time limit (null = none). */
roundEndsAt: number | null;
/** This round's items; `cycle` = items repeat without end (서바이벌, 타임어택). */
items: string[];
cycle: boolean;
/** Topic of each item (title shown above long texts). */
itemTopic: string[];
/** shared: the current item index, when it opens (after the gap) and its time limit. */
cur: number;
curAt: number;
curEndsAt: number | null;
last: LastItem | null;
/** 서바이벌 시간별: the next cut. */
nextCutAt: number | null;
/**
* 서바이벌: items / cuts in a row where everyone left would have gone out at once (so nobody did), and whether the
* round ended undecided (that went on too long, or the item cap) — the survivors then share the point.
*/
stalls?: number;
stalled?: boolean;
/** Survivors knocked out so far this round, in order (for places). */
outOrder: PlayerId[];
rs: Record<PlayerId, RoundSeat>;
totals: Record<PlayerId, SeatTotals>;
rounds: RoundResult[];
/** word / short: every item of the topics in play as "topicId|index", shuffled; rounds take it in turn from `deckAt`. */
deck: string[];
deckAt: number;
/** long: the topics in the order the rounds use them, and where each continues next round (line index). */
longOrder: string[];
longAt: Record<string, number>;
/** shared: the current item has opened (its gap is over); until then its text is hidden. */
curOpen: boolean;
final: TypingFinal | null;
}
export interface SeatView {
id: PlayerId;
points: number;
/** Average 타수 and accuracy (0..100) over the whole game so far. */
kpm: number;
acc: number;
left: boolean;
/** This round. */
idx: number;
done: number;
/** Current item progress 0..1. */
prog: number;
roundKpm: number;
roundAcc: number;
/** 연습: the best 타수 of one line this round. */
bestKpm: number;
/** Something was submitted this round / this game (so an accuracy of 0 is a real 0, not "nothing yet"). */
roundTried: boolean;
tried: boolean;
wrong: number;
finished: boolean;
lives: number;
alive: boolean;
outReason: OutReason | null;
solved: boolean;
}
export interface TypingView {
options: TypingOptions;
me: PlayerId | null;
flow: Flow;
phase: Phase;
round: number;
phaseEndsAt: number | null;
roundStartedAt: number;
roundEndsAt: number | null;
/** Items in this round (null = 끝없이). */
total: number | null;
/** shared: current item (text null during the gap before it opens and during the countdown). */
cur: number;
curAt: number;
curEndsAt: number | null;
/** The item(s) I type now: shared → [current]; lane → my current and the next two (empty when I am done). */
upcoming: { idx: number; text: string; topic: string }[];
/** The whole text of the round (long texts, shown with the line I am on); null otherwise. */
passage: string[] | null;
passageTitle: string | null;
passageBy: string | null;
last: LastItem | null;
nextCutAt: number | null;
seats: SeatView[];
rounds: RoundResult[];
result: TypingFinal | null;
}

View File

@@ -0,0 +1,548 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import {
COUNTDOWN_MS,
GAP_MS,
ROUND_END_MS,
SURVIVAL_MAX_ITEMS,
SURVIVAL_STALL_LIMIT,
autoItemMs,
itemLimit,
ROUND_ITEMS,
PRACTICE_ITEMS,
REACTION_MS,
TOPIC_BY_ID,
flowOf,
kpm,
wrapLines,
itemText,
keyCount,
minTypingMs,
topicIdsFor,
typing,
type TypingAction,
type TypingOptions,
type TypingState,
} from './index';
const T0 = 1_000_000;
const START = T0 + COUNTDOWN_MS;
const rng = () => SeededRng.fromSeed([7, 7, 7, 7]);
function make(opts: Partial<TypingOptions> = {}, players = ['A', 'B'], seed = 1): TypingState {
return typing.setup({ players, options: typing.optionsSchema.parse(opts), rng: SeededRng.fromSeed(seedN(seed)), now: T0 });
}
function act(s: TypingState, p: string, a: TypingAction, now: number): TypingState {
const v = typing.validate(s, p, a, { now });
if (!v.ok) throw new Error(`${p} ${JSON.stringify(a)}: ${v.reason}`);
return typing.apply(s, p, a, { rng: rng(), now }).state;
}
const tick = (s: TypingState, now: number, p = s.order[0]!) => typing.apply(s, p, { type: 'tick' }, { rng: rng(), now }).state;
const reason = (s: TypingState, p: string, a: TypingAction, now: number) => {
const v = typing.validate(s, p, a, { now });
return v.ok ? 'ok' : v.reason;
};
/** Plenty of time after `at` to type any item honestly. */
const later = (at: number) => at + 4000;
/** Shared: the current item, typed right by `p` well after it opened. */
const solve = (s: TypingState, p: string, at = later(s.curAt)) => act(s, p, { type: 'submit', item: s.cur, text: itemText(s, s.cur) }, at);
/** 서바이벌 문장별, three players, playing. */
const surv3 = () => tick(make({ mode: 'survival', elimination: 'sentence', rounds: 1 }, ['A', 'B', 'C']), START);
/** Opens the next shared item (after the gap). */
const open = (s: TypingState) => tick(s, s.curAt);
describe('setup and options', () => {
test('defaults: Korean, 가장 먼저 입력, 짧은글, 3 rounds, survival 틀렸을 때 with 3 lives', () => {
const o = typing.defaultOptions;
expect(o).toMatchObject({ lang: 'ko', mode: 'first', category: 'short', rounds: 3, elimination: 'wrong', lives: 3, topics: [] });
expect(() => typing.optionsSchema.parse({ rounds: 11 })).toThrow();
expect(() => typing.optionsSchema.parse({ rounds: 0 })).toThrow();
});
test('topics: several may be picked; ones that do not fit the language/category are ignored; none = all', () => {
expect(topicIdsFor({ lang: 'ko', category: 'word', topics: ['ko-fruit', 'ko-animal'] })).toEqual(['ko-fruit', 'ko-animal']);
expect(topicIdsFor({ lang: 'ko', category: 'word', topics: ['ko-proverb'] }).length).toBeGreaterThan(4);
const s = make({ category: 'word', topics: ['ko-fruit'] });
expect(s.items).toHaveLength(ROUND_ITEMS.first.word);
for (const t of s.itemTopic) expect(t).toBe('ko-fruit');
});
test('survival needs two players; the others can be played alone', () => {
expect(typing.playersFor!(typing.optionsSchema.parse({ mode: 'survival' }))).toEqual({ min: 2, max: 8 });
expect(typing.playersFor!(typing.optionsSchema.parse({ mode: 'speed' })).min).toBe(1);
});
test('a long text is typed as a passage of lines and continues where it stopped next round', () => {
let s = make({ category: 'long', topics: ['ko-anthem'], mode: 'speed', rounds: 2 }, ['A']);
expect(s.items[0]).toBe('동해 물과 백두산이 마르고 닳도록');
expect(s.items).toHaveLength(8);
s = tick(s, START);
for (let i = 0; i < 8; i++) s = act(s, 'A', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 20_000);
expect(s.phase).toBe('roundEnd');
s = tick(s, s.phaseEndsAt!);
expect(s.items[0]).toBe('가을 하늘 공활한데 높고 구름 없이');
});
});
describe('가장 먼저 입력', () => {
test('nothing to type during the countdown; the first right answer scores and the next item opens after the gap', () => {
let s = make();
expect(typing.view(s, 'A').upcoming).toEqual([]);
expect(reason(s, 'A', { type: 'submit', item: 0, text: 'x' }, T0 + 100)).toContain('곧 시작');
s = tick(s, START);
expect(s.phase).toBe('playing');
expect(s.curOpen).toBe(true);
const text = itemText(s, 0);
expect(typing.view(s, 'B').upcoming[0]!.text).toBe(text);
// A typo: no point, keep trying.
s = act(s, 'A', { type: 'submit', item: 0, text: `${text}ㅋ` }, START + 15_000);
expect(s.totals.A!.points).toBe(0);
expect(s.rs.A!.wrong).toBe(1);
s = act(s, 'B', { type: 'submit', item: 0, text: ` ${text} ` }, START + 16_000);
expect(s.totals.B!.points).toBe(1);
expect(s.last).toMatchObject({ text, winner: 'B' });
expect(s.cur).toBe(1);
expect(s.curOpen).toBe(false);
expect(s.curAt).toBe(START + 16_000 + GAP_MS);
// The next item stays hidden until the gap is over; the late answer to item 0 is refused.
expect(typing.view(s, 'A').upcoming).toEqual([]);
expect(reason(s, 'A', { type: 'submit', item: 0, text }, START + 16_100)).toContain('다음 문제');
s = open(s);
expect(reason(s, 'A', { type: 'submit', item: 0, text }, s.curAt + 5000)).toBe('이미 지나간 문제예요.');
});
test('a paste (faster than a person can type) is refused', () => {
let s = tick(make(), START);
const text = itemText(s, 0);
expect(reason(s, 'A', { type: 'submit', item: 0, text }, START + 200)).toContain('너무 빨라요');
// A quick wrong answer gains nothing: it is taken (and counted as wrong).
expect(reason(s, 'A', { type: 'submit', item: 0, text: 'ㅋ' }, START + 50)).toBe('ok');
expect(reason(s, 'A', { type: 'submit', item: 0, text }, START + 150 + Math.ceil((keyCount(text) * 60_000) / 2400))).toBe('ok');
// Progress cannot run ahead of a person either.
s = act(s, 'A', { type: 'progress', item: 0, text }, START + 300);
expect(s.rs.A!.prog).toBeLessThan(keyCount(text));
});
test('time runs out: nobody scores, the next item opens', () => {
let s = tick(make({ timeLimit: 10 }), START);
expect(s.curEndsAt).toBe(START + 10_000);
s = tick(s, START + 10_000);
expect(s.last).toMatchObject({ winner: null });
expect(s.cur).toBe(1);
});
test('a round is its items; after the last round the most items typed first wins', () => {
let s = tick(make({ rounds: 2 }), START);
const n = ROUND_ITEMS.first.short;
for (let i = 0; i < n; i++) {
s = solve(s, i < 3 ? 'A' : 'B');
if (i < n - 1) s = open(s);
}
expect(s.phase).toBe('roundEnd');
expect(s.rounds[0]!.winners).toEqual(['A']);
expect(s.rounds[0]!.rows[0]).toMatchObject({ id: 'A', rank: 1, points: 3 });
s = tick(s, s.phaseEndsAt!);
expect(s.phase).toBe('countdown');
expect(s.round).toBe(2);
s = tick(s, s.phaseEndsAt!);
for (let i = 0; i < n; i++) {
s = solve(s, 'B');
if (i < n - 1) s = open(s);
}
expect(s.phase).toBe('ended');
const r = typing.result(s)!;
expect(r.ranking).toEqual([['B'], ['A']]);
expect(r.scores).toEqual({ A: 3, B: 7 });
expect(r.scoreText!.B).toMatch(/^7문제 · 평균 \d+타 · 정확도 100%$/);
});
test('progress streams: only the event goes out, and others see a bar, not my text', () => {
let s = tick(make(), START);
const text = itemText(s, 0);
const half = text.slice(0, 3);
expect(typing.isStreamAction!({ type: 'progress', item: 0, text: half })).toBe(true);
expect(typing.isStreamAction!({ type: 'submit', item: 0, text: half })).toBe(false);
const r = typing.apply(s, 'A', { type: 'progress', item: 0, text: half }, { rng: rng(), now: START + 5000 });
expect(r.events).toEqual([{ type: 'progress', player: 'A', item: 0, n: keyCount(half), of: keyCount(text) }]);
s = r.state;
const seat = typing.view(s, 'B').seats.find((x) => x.id === 'A')!;
expect(seat.prog).toBeCloseTo(keyCount(half) / keyCount(text));
expect(JSON.stringify(typing.view(s, 'B'))).not.toContain('"typed"');
});
});
describe('서바이벌', () => {
const surv = (o: Partial<TypingOptions> = {}, players = ['A', 'B', 'C']) => tick(make({ mode: 'survival', rounds: 1, ...o }, players), START);
test('틀렸을 때: a wrong answer costs a life; out of lives = out; the last survivor gets the point', () => {
let s = surv({ lives: 2 });
expect(flowOf(s.options)).toBe('shared');
const at = later(s.curAt);
s = act(s, 'C', { type: 'submit', item: 0, text: 'ㅋ' }, at);
expect(s.rs.C!.lives).toBe(1);
s = act(s, 'C', { type: 'submit', item: 0, text: 'ㅋㅋ' }, at + 100);
expect(s.rs.C).toMatchObject({ alive: false, outReason: 'lives', place: 3 });
expect(reason(s, 'C', { type: 'submit', item: 0, text: 'x' }, at + 200)).toContain('탈락');
// The item is decided once every survivor has typed it.
s = solve(s, 'A', at + 300);
expect(s.cur).toBe(0);
s = solve(s, 'B', at + 400);
expect(s.cur).toBe(1);
expect(s.last!.text).toBe(itemText(s, 0));
s = open(s);
// Time runs out on B: a life lost (B had 2).
s = act(s, 'A', { type: 'submit', item: 1, text: itemText(s, 1) }, later(s.curAt));
s = tick(s, s.curEndsAt!);
expect(s.rs.B!.lives).toBe(1);
s = open(s);
s = act(s, 'B', { type: 'submit', item: 2, text: 'nope' }, later(s.curAt));
expect(s.phase).toBe('ended');
expect(s.rounds[0]!.winners).toEqual(['A']);
expect(typing.result(s)!.ranking).toEqual([['A'], ['B'], ['C']]);
});
test('everybody left would go out at once: nobody does (one life kept)', () => {
let s = surv({ lives: 1 }, ['A', 'B']);
s = tick(s, s.curEndsAt!);
expect(s.rs.A).toMatchObject({ alive: true, lives: 1 });
expect(s.rs.B).toMatchObject({ alive: true, lives: 1 });
expect(s.phase).toBe('playing');
});
test('the clock gets shorter item by item (무제한 plays as 자동), never below what a very fast typist needs', () => {
const o = (x: Partial<TypingOptions>) => ({ options: typing.optionsSchema.parse({ mode: 'survival', ...x }) });
const text = '가는 말이 고와야 오는 말이 곱다.';
expect(itemLimit(o({ timeLimit: null }), text, 0)).toBe(autoItemMs(text));
expect(itemLimit(o({}), text, 1)).toBe(Math.round(autoItemMs(text) * 0.9));
const floor = 1000 + Math.round((keyCount(text) * 60_000) / 900);
expect(itemLimit(o({}), text, 200)).toBe(floor);
// Outside survival the clock stays as set.
expect(itemLimit({ options: typing.optionsSchema.parse({ timeLimit: 30 }) }, text, 50)).toBe(30_000);
expect(itemLimit({ options: typing.optionsSchema.parse({ timeLimit: null }) }, text, 0)).toBeNull();
});
test('문장별: the last one still typing goes out right away', () => {
let s = surv({ elimination: 'sentence' });
s = solve(s, 'B');
s = solve(s, 'C');
expect(s.rs.A).toMatchObject({ alive: false, outReason: 'slowest' });
expect(s.last!.out).toEqual(['A']);
s = open(s);
s = solve(s, 'C');
expect(s.phase).toBe('ended');
expect(typing.result(s)!.ranking).toEqual([['C'], ['B'], ['A']]);
});
test('시간 초과: whoever has not typed it when the time runs out goes (together)', () => {
let s = surv({ elimination: 'deadline', timeLimit: null });
// 무제한 is not allowed here: the item gets the 자동 limit.
expect(s.curEndsAt).not.toBeNull();
s = solve(s, 'A');
s = tick(s, s.curEndsAt!);
expect(s.rs.B!.outReason).toBe('time');
expect(s.rs.C!.outReason).toBe('time');
expect(s.rs.B!.place).toBe(2);
expect(s.phase).toBe('ended');
});
test('시간별: everybody types on their own; every N seconds whoever typed the least goes', () => {
let s = surv({ elimination: 'interval', intervalSec: 10 });
expect(flowOf(s.options)).toBe('lane');
expect(s.nextCutAt).toBe(START + 10_000);
s = act(s, 'A', { type: 'submit', item: 0, text: itemText(s, 0) }, START + 9000);
s = act(s, 'B', { type: 'progress', item: 0, text: itemText(s, 0).slice(0, 2) }, START + 9000);
s = tick(s, START + 10_000);
expect(s.rs.C).toMatchObject({ alive: false, outReason: 'least' });
expect(s.nextCutAt).toBe(START + 20_000);
s = tick(s, START + 20_000);
expect(s.rs.B!.alive).toBe(false);
expect(s.phase).toBe('ended');
expect(s.rounds[0]!.winners).toEqual(['A']);
});
});
describe('타수 비교 · 정확도 대결 · 타임어택', () => {
test('타수 비교: own pace through the round; typos lower 타수; the higher 타수 wins the round', () => {
let s = tick(make({ mode: 'speed', rounds: 1 }), START);
expect(flowOf(s.options)).toBe('lane');
const n = s.items.length;
expect(n).toBe(ROUND_ITEMS.lane.short);
expect(typing.view(s, 'A').upcoming.map((u) => u.idx)).toEqual([0, 1, 2]);
for (let i = 0; i < n; i++) s = act(s, 'A', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 10_000);
expect(s.rs.A!.finishedAt).not.toBeNull();
expect(typing.view(s, 'A').upcoming).toEqual([]);
expect(s.phase).toBe('playing');
// B is as quick but sloppy.
for (let i = 0; i < n; i++) s = act(s, 'B', { type: 'submit', item: i, text: s.items[i]!.slice(0, -3) }, START + (i + 1) * 10_000);
expect(s.phase).toBe('ended');
const rows = s.rounds[0]!.rows;
expect(rows[0]!.id).toBe('A');
expect(rows[0]!.acc).toBe(100);
expect(rows[1]!.acc).toBeLessThan(100);
expect(rows[0]!.kpm).toBeGreaterThan(rows[1]!.kpm);
});
test('정확도 대결: the more accurate wins even if slower', () => {
let s = tick(make({ mode: 'accuracy', rounds: 1, category: 'word', timeLimit: null }), START);
const n = s.items.length;
for (let i = 0; i < n; i++) s = act(s, 'A', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 9000);
for (let i = 0; i < n; i++) s = act(s, 'B', { type: 'submit', item: i, text: i === 0 ? `${s.items[i]}x` : s.items[i]! }, START + (i + 1) * 3000);
expect(s.rounds[0]!.winners).toEqual(['A']);
});
test('the round clock: what is typed of the current line counts; unfinished players stop', () => {
let s = tick(make({ mode: 'speed', rounds: 1, timeLimit: 30 }), START);
expect(s.roundEndsAt).toBe(START + 30_000);
s = act(s, 'A', { type: 'progress', item: 0, text: s.items[0]!.slice(0, 4) }, START + 10_000);
s = tick(s, START + 30_000);
expect(s.phase).toBe('ended');
expect(s.rounds[0]!.rows.find((r) => r.id === 'A')!.kpm).toBeGreaterThan(0);
expect(s.rounds[0]!.winners).toEqual(['A']);
});
test('타임어택: lines never run out; the most keystrokes in the time wins', () => {
let s = tick(make({ mode: 'timeAttack', rounds: 1, attackSec: 30 }), START);
expect(s.cycle).toBe(true);
expect(s.roundEndsAt).toBe(START + 30_000);
for (let i = 0; i < 3; i++) s = act(s, 'B', { type: 'submit', item: i, text: itemText(s, i) }, START + (i + 1) * 8000);
s = act(s, 'A', { type: 'submit', item: 0, text: itemText(s, 0) }, START + 8000);
s = tick(s, START + 30_000);
expect(s.rounds[0]!.winners).toEqual(['B']);
});
test('무제한: a player away past the grace period is stopped with what they typed', () => {
let s = tick(make({ mode: 'speed', rounds: 1, timeLimit: null }), START);
expect(typing.deadline!(s)).toBeNull();
expect(typing.timeoutPlayers!(s)).toEqual(['A', 'B']);
for (let i = 0; i < s.items.length; i++) s = act(s, 'A', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 10_000);
expect(typing.timeoutPlayers!(s)).toEqual(['B']);
s = tick(s, START + 100_000, 'B');
expect(s.phase).toBe('ended');
});
});
describe('연습', () => {
test('짧은글: one round of 10 sentences, no clock, no points; the next sentence comes at once', () => {
let s = tick(make({ mode: 'practice', rounds: 5, timeLimit: 30 }, ['A']), START);
expect(flowOf(s.options)).toBe('lane');
expect(s.items.length).toBe(PRACTICE_ITEMS.short);
expect(s.roundEndsAt).toBeNull();
expect(typing.deadline!(s)).toBeNull();
// Long after any clock would have run out, typing goes on.
let t = START + 10 * 60_000;
for (let i = 0; i < s.items.length; i++) {
s = act(s, 'A', { type: 'progress', item: i, text: s.items[i]!.slice(0, 1) }, (t += 1000));
s = act(s, 'A', { type: 'submit', item: i, text: i === 0 ? `${s.items[i]}x` : s.items[i]! }, (t += 8000));
}
expect(s.phase).toBe('ended');
expect(s.rounds.length).toBe(1);
expect(s.rounds[0]!.winners).toEqual([]);
expect(s.totals.A!.points).toBe(0);
const v = typing.view(s, 'A').seats[0]!;
expect(v.wrong).toBe(1);
expect(v.done).toBe(PRACTICE_ITEMS.short);
expect(typing.result(s)!.scoreText!.A).toMatch(/^평균 \d+타 · 정확도 [\d.]+%$/);
});
test('a line is timed from its first key: a rest before it does not lower the 타수; the best line is kept', () => {
let s = tick(make({ mode: 'practice', category: 'word' }, ['A']), START);
expect(s.items.length).toBe(PRACTICE_ITEMS.word);
const w0 = s.items[0]!;
// A long rest, then the word typed in 2 s.
s = act(s, 'A', { type: 'progress', item: 0, text: w0.slice(0, 1) }, START + 60_000);
s = act(s, 'A', { type: 'submit', item: 0, text: w0 }, START + 62_000);
expect(s.rs.A!.ms).toBe(2000 + REACTION_MS);
const fast = kpm(keyCount(w0), 2000 + REACTION_MS);
expect(typing.view(s, 'A').seats[0]!.bestKpm).toBe(fast);
// A slower second word keeps the best.
const w1 = s.items[1]!;
s = act(s, 'A', { type: 'progress', item: 1, text: w1.slice(0, 1) }, START + 63_000);
s = act(s, 'A', { type: 'submit', item: 1, text: w1 }, START + 73_000);
expect(typing.view(s, 'A').seats[0]!.bestKpm).toBe(Math.max(fast, kpm(keyCount(w1), 10_000 + REACTION_MS)));
// Still no pasting: Enter right after the first key is refused.
s = act(s, 'A', { type: 'progress', item: 2, text: s.items[2]!.slice(0, 1) }, START + 80_000);
expect(reason(s, 'A', { type: 'submit', item: 2, text: s.items[2]! }, START + 80_001)).toContain('붙여 넣기');
});
test('긴글: one whole text, first line to last, shown as one passage', () => {
const s = tick(make({ mode: 'practice', category: 'long', topics: ['ko-anthem'] }, ['A']), START);
const t = TOPIC_BY_ID['ko-anthem']!;
expect(s.items).toEqual(wrapLines(t.items, 'ko'));
expect(s.items.length).toBeGreaterThan(8);
const v = typing.view(s, 'A');
expect(v.passage).toEqual(s.items);
expect(v.passageTitle).toBe(t.name);
expect(v.total).toBe(s.items.length);
});
test('with others: everybody at their own pace; ranked by 타수; the game ends when all are done', () => {
let s = tick(make({ mode: 'practice', category: 'word' }), START);
const n = s.items.length;
for (let i = 0; i < n; i++) s = act(s, 'A', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 3000);
expect(s.phase).toBe('playing');
for (let i = 0; i < n; i++) s = act(s, 'B', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 6000);
expect(s.phase).toBe('ended');
expect(s.final!.ranking.map((r) => r.id)).toEqual(['A', 'B']);
expect(s.final!.summary).toContain('연습 끝');
});
test('someone leaves (done or not): the others keep typing until they finish', () => {
let s = tick(make({ mode: 'practice', category: 'word' }), START);
const n = s.items.length;
for (let i = 0; i < n; i++) s = act(s, 'A', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 3000);
s = act(s, 'A', { type: 'leave' }, START + n * 3000 + 100);
expect(s.phase).toBe('playing');
expect(typing.validate(s, 'B', { type: 'submit', item: 0, text: s.items[0]! }, { now: START + 70_000 }).ok).toBe(true);
for (let i = 0; i < n; i++) s = act(s, 'B', { type: 'submit', item: i, text: s.items[i]! }, START + 70_000 + i * 3000);
expect(s.phase).toBe('ended');
expect(s.final!.ranking.map((r) => [r.id, r.left])).toEqual([['B', false], ['A', true]]);
// Leaving midway works the same; the last one leaving ends it.
let t = tick(make({ mode: 'practice' }, ['A', 'B', 'C']), START);
t = act(t, 'A', { type: 'leave' }, START + 1000);
t = act(t, 'B', { type: 'leave' }, START + 2000);
expect(t.phase).toBe('playing');
t = act(t, 'C', { type: 'leave' }, START + 3000);
expect(t.phase).toBe('ended');
});
});
describe('서바이벌은 반드시 끝나요', () => {
/** Fires the server clock until the game ends (nobody types). */
const runClock = (s: TypingState, max = 500) => {
let n = 0;
while (s.phase !== 'ended' && n < max) {
s = tick(s, typing.deadline!(s)!);
n++;
}
return { s, n };
};
test.each(['wrong', 'sentence', 'interval', 'deadline'] as const)('%s: everybody away (all miss / all tie) → the survivors share the round after a few tries', (elimination) => {
const { s, n } = runClock(make({ mode: 'survival', elimination, rounds: 2, lives: 3 }, ['A', 'B', 'C']));
expect(s.phase).toBe('ended');
expect(n).toBeLessThan(200);
for (const r of s.rounds) {
expect(r.winners.sort()).toEqual(['A', 'B', 'C']);
expect(r.summary).toContain('더 탈락하는 사람이 없어서');
}
expect(typing.result(s)!.ranking).toEqual([['A', 'B', 'C']]);
});
test(`a round where everybody always types in time stops after ${SURVIVAL_MAX_ITEMS} items`, () => {
let s = tick(make({ mode: 'survival', elimination: 'deadline', rounds: 1 }, ['A', 'B']), START);
let items = 0;
while (s.phase === 'playing') {
const fast = s.curAt + minTypingMs(keyCount(itemText(s, s.cur))) + 10;
s = solve(s, 'A', fast);
s = solve(s, 'B', fast + 10);
items++;
if (s.phase === 'playing') s = open(s);
}
expect(items).toBe(SURVIVAL_MAX_ITEMS);
expect(s.rounds[0]!.winners.sort()).toEqual(['A', 'B']);
});
test('one real knock-out resets the count of all-at-once misses', () => {
let s = surv3();
for (let i = 0; i < SURVIVAL_STALL_LIMIT - 1; i++) s = open(tick(s, s.curEndsAt!));
expect(s.stalls).toBe(SURVIVAL_STALL_LIMIT - 1);
s = solve(s, 'A');
s = solve(s, 'B');
expect(s.rs.C!.alive).toBe(false);
expect(s.stalls).toBe(0);
});
});
describe('기록 표시', () => {
test('after a round, a seat shows the same 타수 and accuracy as the result (nothing counted twice)', () => {
let s = tick(make({ mode: 'speed', rounds: 2, category: 'word' }, ['A']), START);
for (let r = 0; r < 2; r++) {
const t0 = s.roundStartedAt;
for (let i = 0; i < s.items.length; i++) s = act(s, 'A', { type: 'submit', item: i, text: i % 2 ? s.items[i]! : `${s.items[i]}x` }, t0 + (i + 1) * 3000);
if (s.phase === 'roundEnd') {
const seat = typing.view(s, 'A').seats[0]!;
expect(seat.kpm).toBe(Math.round((s.totals.A!.keys * 60_000) / s.totals.A!.ms));
s = tick(s, s.phaseEndsAt!);
s = tick(s, s.phaseEndsAt!);
}
}
expect(s.phase).toBe('ended');
const seat = typing.view(s, 'A').seats[0]!;
const fin = s.final!.ranking[0]!;
expect(seat.kpm).toBe(fin.kpm);
expect(seat.acc).toBe(fin.acc);
});
test('all wrong answers: accuracy 0 is a real 0 (tried), not "nothing yet"', () => {
let s = tick(make({ mode: 'speed', rounds: 1 }), START);
let seat = typing.view(s, 'A').seats[0]!;
expect(seat).toMatchObject({ roundTried: false, tried: false });
s = act(s, 'A', { type: 'submit', item: 0, text: 'ㅋㅋㅋ' }, START + 5000);
seat = typing.view(s, 'A').seats[0]!;
expect(seat).toMatchObject({ roundTried: true, tried: true, roundAcc: 0, acc: 0 });
});
});
describe('leaving and clocks', () => {
test('when everyone else leaves, the one who stayed wins', () => {
let s = tick(make({}, ['A', 'B', 'C']), START);
s = act(s, 'B', { type: 'leave' }, START + 1000);
expect(s.phase).toBe('playing');
s = act(s, 'C', { type: 'leave' }, START + 2000);
expect(s.phase).toBe('ended');
expect(typing.result(s)!.ranking[0]).toEqual(['A']);
expect(s.final!.summary).toContain('나가서');
});
test('a clocked step is never cut short for an away player', () => {
const s = tick(make({ timeLimit: 30 }), START);
expect(typing.timeoutNotBefore!(s)).toBe(START + 30_000);
const t = tick(s, START + 1000, 'B');
expect(t.cur).toBe(0);
expect(t.rs.B!.alive).toBe(true);
});
test('round results stay up, then the next countdown', () => {
let s = tick(make({ mode: 'speed', rounds: 2, category: 'word' }, ['A']), START);
for (let i = 0; i < s.items.length; i++) s = act(s, 'A', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 5000);
expect(s.phase).toBe('roundEnd');
expect(typing.deadline!(s)).toBe(s.phaseEndsAt);
const end = s.phaseEndsAt!;
expect(end - (START + s.items.length * 5000)).toBe(ROUND_END_MS);
s = tick(s, end);
expect(s).toMatchObject({ phase: 'countdown', round: 2 });
});
});
describe('random playouts', () => {
const combos: Partial<TypingOptions>[] = [
{},
{ category: 'word' },
{ category: 'long', lang: 'en' },
{ mode: 'survival' },
{ mode: 'survival', elimination: 'sentence', category: 'word' },
{ mode: 'survival', elimination: 'interval' },
{ mode: 'survival', elimination: 'deadline', lang: 'en' },
{ mode: 'speed', category: 'long' },
{ mode: 'accuracy', timeLimit: null },
{ mode: 'timeAttack', category: 'word' },
{ mode: 'practice' },
{ mode: 'practice', category: 'long', lang: 'en' },
];
test.each(combos.map((c) => [JSON.stringify(c), c] as const))('%s finishes without leaking the next text', (_, c) => {
const seeds = playoutSeeds(60);
for (let i = 0; i < seeds; i++) {
const players = ['A', 'B', 'C'].slice(0, c.mode === 'survival' ? 3 : 1 + (i % 3));
const r = randomPlayout(typing, { players, options: typing.optionsSchema.parse({ rounds: 2, ...c }), seed: seedN(i + 1), maxSteps: 20_000 });
expect(r.finished).toBe(true);
const res = typing.result(r.finalState as TypingState)!;
expect(res.ranking.flat().sort()).toEqual([...players].sort());
}
});
test('no head start: the countdown hides the first text from everybody', () => {
const s = make({ mode: 'speed' });
checkNoLeak(typing, s, 'A', ['A', 'B']);
expect(typing.secretsOf!(s, 'A')).toEqual([s.items[0]!]);
expect(JSON.stringify(typing.view(s, null))).not.toContain(s.items[0]!);
});
});

View File

@@ -25,7 +25,7 @@ export function botProfile(id: string): PublicUser | null {
* Games that offer computer players. Real-time and drawing games (도블, 할리갈리, 그림 맞히기) don't: a bot there is * Games that offer computer players. Real-time and drawing games (도블, 할리갈리, 그림 맞히기) don't: a bot there is
* either unbeatable or meaningless. 마피아 has talking computers (2026-10-11). 사과 게임 is a race where everyone solves * either unbeatable or meaningless. 마피아 has talking computers (2026-10-11). 사과 게임 is a race where everyone solves
* their own copy of the board, so a computer simply races too at its level's speed (2026-10-12). 라이어 게임 has * their own copy of the board, so a computer simply races too at its level's speed (2026-10-12). 라이어 게임 has
* talking computers like 마피아 (2026-10-12). * talking computers like 마피아 (2026-10-12). 타자 대결 computers type at their level's speed (2026-11-12).
*/ */
export const BOT_GAMES: readonly string[] = [ export const BOT_GAMES: readonly string[] = [
'omok', 'omok',
@@ -64,6 +64,12 @@ export const BOT_GAMES: readonly string[] = [
'hot-streak', 'hot-streak',
'tichu', 'tichu',
'castles-of-burgundy', '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명). */ /** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */

View File

@@ -38,6 +38,12 @@ export const CATALOG: CatalogEntry[] = [
{ id: 'dobble', nameKo: '도블', minPlayers: 2, maxPlayers: 8, minutes: '3~10', level: '쉬움', blurb: '어느 두 카드에나 딱 하나 있는 같은 그림을 누구보다 빨리 콕!', available: true }, { id: 'dobble', nameKo: '도블', minPlayers: 2, maxPlayers: 8, minutes: '3~10', level: '쉬움', blurb: '어느 두 카드에나 딱 하나 있는 같은 그림을 누구보다 빨리 콕!', available: true },
{ id: 'catchmind', nameKo: '그림 맞히기', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '한 사람이 그림을 그리면 나머지가 채팅으로 정답을 맞혀요!', available: true }, { 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: '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: '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: '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 }, { id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },