새 게임 타자 대결: 한국어·영어, 가장 먼저 입력·서바이벌·타수 비교·정확도 대결·타임어택, 단어·짧은글·긴글, 주제 여러 개, 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>
This commit is contained in:
EJClaw
2026-11-12 12:39:37 +09:00
parent f793391b79
commit fffb860282
25 changed files with 4130 additions and 7 deletions

View File

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

View File

@@ -0,0 +1,139 @@
/** 타자 대결 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('진행은 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);
test('모든 게임에 도움말이 있어요', () => {
expect(IDS).toHaveLength(40);
expect(IDS).toHaveLength(41);
for (const id of IDS) {
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
expect(src, id).toMatch(/\bquickStart,/);

View File

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

View File

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

View File

@@ -0,0 +1,47 @@
/** 타자 대결 [?] "지금 할 수 있는 것" (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점이에요.',
};
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.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_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(`이번 라운드: ${mine.roundKpm}타, 정확도 ${mine.roundAcc || 100}%${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,834 @@
/** 타자 대결 화면 (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' ? '점' : '승';
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} />} {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 startedAt = useRef<{ key: string; at: number }>({ key: '', at: 0 });
if (startedAt.current.key !== itemKey && item) startedAt.current = { key: itemKey, at: 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 ? 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 = `라운드 ${v.round}/${v.options.rounds}`;
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">
<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>
)}
</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'
? '게임 끝!'
: 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();
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' && (
<div className="ty-stats">
<span>지금 {curKpm}타</span>
<span>이번 라운드 {mine.roundKpm}타</span>
<span>정확도 {mine.roundAcc || 100}%</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 ? `라운드 ${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' ? '점' : '승';
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.acc ? `${s.acc}%` : '-'}
</span>
<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 }}>
라운드 {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">
{' '}
· {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.round} 곧 시작! 나오는 글을 그대로 쳐요`;
if (v.phase === 'roundEnd') return v.rounds.at(-1)?.summary ?? '라운드 끝';
const s = v.seats.find((x) => x.id === me);
if (!s) return `${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' ? '시간 안에 최대한 많이 쳐요!' : '한 줄씩 치고 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점이에요.',
};
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 showTime = o.mode !== 'timeAttack' && !(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>대결 종목</strong>
<Seg label="대결 종목" 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' ? ' 긴글은 라운드마다 한 단락(8줄 안팎)씩 이어서 쳐요.' : ''}
</span>
</div>
<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.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>
</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,7 @@ export const GAME_ICON: Record<string, string> = {
blackjack: '🂡',
'six-nimmt': '🐮',
gemblo: '💠',
typing: '⌨️',
'hot-streak': '🏁',
tichu: '🐉',
'case-file': '🔍',
@@ -48,5 +49,5 @@ export const UPCOMING: 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: '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'] },
];

View File

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

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

@@ -0,0 +1,96 @@
# 타자 대결 (`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자).
- 서바이벌·타임어택은 글이 끝없이 돈다.
- 라운드마다 3초 카운트다운. 그동안 첫 글은 숨긴다.
## 5. 진행 규칙
- **함께 치기**(가장 먼저 입력, 서바이벌 중 시간별 아닌 것): 모두 같은 문제를 동시에 친다. 문제가 정해지면 1.5초 쉬고 다음 문제가 열린다.
- 가장 먼저 입력: 먼저 정확하게 친 사람 1점. 틀리면 고쳐서 다시. 시간이 끝나면 아무도 점수 없음.
- 서바이벌 틀렸을 때: 틀린 Enter·시간 초과마다 목숨 −1, 0이면 탈락. 살아 있는 사람이 모두 치면 다음 문제.
- 서바이벌 문장별: 남은 사람 중 마지막 한 사람이 남으면 그 사람 탈락. 시간 안에 못 친 사람도 탈락.
- 서바이벌 시간 초과: 시간 안에 못 친 사람 모두 탈락.
- **각자 치기**(타수 비교, 정확도 대결, 타임어택, 서바이벌 시간별): 각자 한 줄 치고 Enter → 다음 줄. 틀린 채로 넘어가도 되고 그만큼 정확도·타수가 깎인다.
- 서바이벌 시간별: 정해진 간격마다 그때까지 친 타 수(지금 줄 포함)가 가장 적은 사람(같으면 함께) 탈락.
- 서바이벌은 문제마다 제한 시간이 0.9배씩 줄고(무제한은 자동으로 친다), 아주 빠른 사람(900타)이 치는 시간 + 1초 아래로는 줄지 않는다. 그래서 라운드가 반드시 끝난다.
- 남은 사람이 모두 한꺼번에 탈락하게 되면 아무도 탈락하지 않는다(목숨은 1개로).
- 붙여 넣기 막기: 화면에서 붙여 넣기·끌어 놓기를 막고, 서버는 2,400타/분 + 0.15초보다 빠른 Enter를 거절하며 진행 막대도 그 속도 이상 앞서지 않는다.
## 6. 승패와 점수 계산
- 타수 = 1분에 친 자판 수(두벌식: 겹모음·겹받침 2타, 쌍자음 1타, 영어는 글자 수). 각자 치기는 줄의 타 수 × 정확도, 함께 치기는 맞게 친 문제(못 친 문제는 맞게 친 데까지).
- 정확도 = 1 − 편집 거리 / 긴 쪽 글자 수.
- 라운드 점수: 가장 먼저 입력은 문제마다 1점, 나머지는 라운드 1등(같으면 모두) 1점 — 타수 비교는 타수, 정확도 대결은 정확도(같으면 타수), 타임어택은 친 타 수, 서바이벌은 끝까지 남은 사람.
- 최종: 점수 → 평균 타수 → 평균 정확도 순. 나간 사람은 맨 뒤.
## 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가지 설정(누출 없음).
- bot.test: 9가지 설정 × (사람 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

@@ -1385,6 +1385,22 @@ async function cobStep(p: Page, st: Record<string, number>): Promise<string | nu
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> = {
'case-file': {
// PC host + phone guest, "고른 사람만 읽기": 의뢰 → 반장 돌기(두 번 눌러 고르기) → 단서 읽기(다른 사람은 제목만)
@@ -3597,6 +3613,139 @@ 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)}`);
},
},
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)}`);
},
},
appleUnlimited: {
// 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번.

View File

@@ -43,6 +43,7 @@ import { gembloBot } from '../gemblo/bot';
import { hotStreakBot } from '../hot-streak/bot';
import { tichuBot } from '../tichu/bot';
import { cobBot } from '../castles-of-burgundy/bot';
import { typingBot } from '../typing/bot';
export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
@@ -137,9 +138,10 @@ export function decideBotAction(
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> = {
mafia: mafiaBot,
apple: appleBot,
liar: liarBot,
typing: typingBot,
};

View File

@@ -39,6 +39,7 @@ import { hotStreak } from './hot-streak';
import { tichu } from './tichu';
import { caseFile } from './case-file';
import { castlesOfBurgundy } from './castles-of-burgundy';
import { typing } from './typing';
export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -81,4 +82,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[tichu.id]: tichu,
[caseFile.id]: caseFile,
[castlesOfBurgundy.id]: castlesOfBurgundy,
[typing.id]: typing,
};

View File

@@ -0,0 +1,73 @@
/** 타자 대결 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 },
];
test.each(modes.map((m) => [JSON.stringify(m), m] as const))('%s: 사람 1명(가만히) + 컴퓨터, 컴퓨터끼리만: 거절 0, 끝까지', (_, m) => {
for (const humans of [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,86 @@
/**
* 타자 대결 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];
const typed = chars.slice(0, Math.floor(chars.length * frac)).join('');
const wait = Math.min(Math.round(350 + random() * 300), Math.max(60, Math.ceil(plan.doneAt - 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,941 @@
/**
* 타자 대결 (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.
* 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;
/** 자동 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';
/** 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;
/**
* 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 {
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 = 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.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 ? 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;
return !s.cycle && nextIdx >= s.items.length;
}
/** 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 });
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).
for (const p of hit) if (s.rs[p]!.lives <= 0) s.rs[p]!.lives = 1;
ctx.events.push({ type: 'spared', players: hit });
return [];
}
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) 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':
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':
return String(roundKpm(r));
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 {
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 >= o.rounds || 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 (!n) return mode === 'first' ? '아무도 먼저 치지 못했어요' : '이번 라운드는 승자가 없어요';
const many = n > 1 ? ` (공동 ${n}명)` : '';
switch (mode) {
case 'first':
return solo ? '라운드 끝!' : `가장 많이 먼저 친 사람이 이 라운드 1등이에요${many}`;
case 'survival':
return `끝까지 살아남은 사람이 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 (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);
// 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 타수.
r.keys += Math.round(keys * acc);
r.ms += Math.max(1, ctx.now - r.itemAt);
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));
if (stayed.length === 0 || (stayed.length === 1 && s.order.length > 1)) {
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 target = s.phase === 'playing' && s.items.length ? targetOf(s, p) : '';
const of = target ? keyCount(target) : 0;
return {
id: p,
points: t.points,
kpm: avgKpm({ keys: t.keys + r.keys, ms: t.ms + r.ms }),
acc: avgAcc({ accSum: t.accSum + r.accSum, accLen: t.accLen + r.accLen }),
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)),
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' ? '문제' : '승';
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, `${r.points}${unit} · 평균 ${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,221 @@
/** 타자 대결 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'] as const;
export type Mode = (typeof MODES)[number];
export const MODE_KO: Record<Mode, string> = { first: '가장 먼저 입력', survival: '서바이벌', speed: '타수 비교', accuracy: '정확도 대결', timeAttack: '타임어택' };
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[];
}
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;
/** 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;
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,375 @@
import { describe, expect, test } from 'bun:test';
import { SeededRng, checkNoLeak, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import {
COUNTDOWN_MS,
GAP_MS,
ROUND_END_MS,
autoItemMs,
itemLimit,
ROUND_ITEMS,
flowOf,
itemText,
keyCount,
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);
/** 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('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' },
];
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
* 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
* 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[] = [
'omok',
@@ -64,6 +64,7 @@ export const BOT_GAMES: readonly string[] = [
'hot-streak',
'tichu',
'castles-of-burgundy',
'typing',
];
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */

View File

@@ -38,6 +38,7 @@ export const CATALOG: CatalogEntry[] = [
{ 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: '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: 'connect-four', nameKo: '커넥트 포', minPlayers: 2, maxPlayers: 2, minutes: '3~10', level: '쉬움', blurb: '열을 골라 돌을 떨어뜨려 네 개를 먼저 한 줄로! · 사목', available: true },
{ id: 'magical-athlete', nameKo: '야단법석 달리기', minPlayers: 2, maxPlayers: 6, minutes: '20~30', level: '쉬움', blurb: '엉뚱한 능력 선수를 뽑아 주사위 경주 4번! 1·2등만 점수', available: true },
{ id: 'mafia', nameKo: '마피아', minPlayers: 4, maxPlayers: 12, minutes: '10~25', level: '보통', blurb: '낮에는 토론하고 밤에는 몰래! 숨은 마피아를 찾아요 · 채팅 추리', available: true },