새 게임 타자 대결: 한국어·영어, 가장 먼저 입력·서바이벌·타수 비교·정확도 대결·타임어택, 단어·짧은글·긴글, 주제 여러 개, 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

@@ -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 },