Files
joke-app/packages/games/src/typing/index.ts
EJClaw 943e4be3fd 타자 대결 연습 모드: 한컴 타자연습처럼 짧은글 10문장·단어 20개·긴글 한 편 전체를 제한 시간·점수 없이
- 대결 방식에 "연습" 추가(각자 치기, 라운드 1번, 시계·점수 없음). 긴글은 고른 주제 중 한 편을 처음부터 끝까지(8줄 단락이 아님).
- 줄마다 첫 타부터 시간을 재서 줄 사이에 쉬어도 타수가 안 떨어짐(첫 타 몫 0.15초 앞당김 → 붙여 넣기 막기 그대로).
  줄 최고 타수(best) 기록. 컴퓨터도 연습에서는 첫 타를 바로 보냄.
- 화면: 라운드 대신 걸린 시간, 지금·평균·최고 타수·정확도·진행 %, 끝나면 평균·최고·정확도·틀린 줄, 참가자 옆은 타수.
  설정에서 라운드·제한 시간 숨김, 종목 이름 "연습 종목", 도움말·규칙·요약 카드·docs.
- 테스트: 연습 4개(엔진), 무작위 대국 2가지, 컴퓨터 1가지, 도움말 1개, e2e typingPractice·typingPracticeLong.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 17:09:37 +09:00

989 lines
39 KiB
TypeScript

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