타자 대결 연습 모드: 한컴 타자연습처럼 짧은글 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>
This commit is contained in:
EJClaw
2026-11-12 17:09:23 +09:00
parent 122cf5ed1f
commit 943e4be3fd
11 changed files with 321 additions and 51 deletions

View File

@@ -19,9 +19,11 @@ describe('한 판 전체', () => {
{ mode: 'speed', category: 'long' },
{ mode: 'accuracy' },
{ mode: 'timeAttack', attackSec: 30 },
{ mode: 'practice', category: 'word' },
];
test.each(modes.map((m) => [JSON.stringify(m), m] as const))('%s: 사람 1명(가만히) + 컴퓨터, 컴퓨터끼리만: 거절 0, 끝까지', (_, m) => {
for (const humans of [1, 0]) {
// 연습 has no clock: an idle person would keep it open (as in a room), so only the computers play it here.
for (const humans of m.mode === 'practice' ? [0] : [1, 0]) {
const players = ['human0', 'bot:2:a', 'bot:3:b', 'bot:4:c'].slice(humans ? 0 : 1);
const r = liveBotPlayout(typing, typingBot, { players, options: opts(m), seed: seedN(humans + 3), isBot, levelOf: (p) => (p.endsWith('a') ? 5 : p.endsWith('b') ? 30 : 58) });
expect(r.finished).toBe(true);

View File

@@ -67,8 +67,11 @@ export function typingBot({ me, view: v, now, random, persona, level, memory }:
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)));
// 연습 times a line from its first key, so that key goes out as soon as it is typed (as a person's screen does).
const practice = v.options.mode === 'practice';
const typed = chars.slice(0, Math.max(practice && now >= plan.from ? 1 : 0, Math.floor(chars.length * frac))).join('');
let wait = Math.min(Math.round(350 + random() * 300), Math.max(60, Math.ceil(plan.doneAt - now)));
if (practice && now < plan.from) wait = Math.min(wait, Math.max(1, Math.ceil(plan.from - now)));
return typed ? { action: { type: 'progress', item: item.idx, text: typed }, next: wait } : { action: null, next: wait };
}
if (plan.typo) {

View File

@@ -3,7 +3,8 @@
* 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.
* - 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';
@@ -44,6 +45,8 @@ 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;
@@ -52,6 +55,10 @@ const AUTO_KPM = 120;
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';
@@ -143,6 +150,10 @@ function dealRound(s: S, rng: Rng | null): void {
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]!);
@@ -161,7 +172,7 @@ function dealRound(s: S, rng: Rng | null): void {
topics.push(id);
}
} else {
const n = ROUND_ITEMS[o.mode === 'first' ? 'first' : 'lane'][o.category];
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;
@@ -210,7 +221,7 @@ function beginPlay(s: S, ctx: Ctx): void {
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);
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 });
}
@@ -360,6 +371,7 @@ function roundOrder(s: S): PlayerId[] {
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)];
@@ -391,7 +403,8 @@ function endRound(s: S, ctx: Ctx): void {
case 'survival':
return r.alive ? 'alive' : String(r.place);
case 'speed':
return String(roundKpm(r));
case 'practice':
return `${roundKpm(r)}/${Math.round(roundAcc(r) * 1000)}`;
case 'accuracy':
return `${Math.round(roundAcc(r) * 1000)}/${roundKpm(r)}`;
case 'timeAttack':
@@ -410,7 +423,7 @@ function endRound(s: S, ctx: Ctx): void {
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 {
} 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) : [];
@@ -435,13 +448,14 @@ function endRound(s: S, ctx: Ctx): void {
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);
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) {
@@ -485,7 +499,8 @@ function finish(s: S, ctx: Ctx): void {
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 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} 사람이 이겼어요`;
@@ -599,6 +614,12 @@ const targetOf = (s: S, p: PlayerId) => itemText(s, flowOf(s.options) === 'share
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);
@@ -643,8 +664,12 @@ function submit(s: S, p: PlayerId, text: string, ctx: Ctx): void {
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);
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++;
@@ -711,6 +736,7 @@ function seatView(s: S, p: PlayerId): SeatView {
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,
@@ -926,10 +952,11 @@ export const typing: Def = {
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, `${r.points}${unit} · 평균 ${r.kpm}타 · 정확도 ${r.acc}%`])),
scoreText: Object.fromEntries(f.ranking.map((r) => [r.id, `${head(r)}평균 ${r.kpm}타 · 정확도 ${r.acc}%`])),
summary: f.summary,
reason: 'normal',
};

View File

@@ -8,9 +8,9 @@ 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 const MODES = ['first', 'survival', 'speed', 'accuracy', 'timeAttack', 'practice'] as const;
export type Mode = (typeof MODES)[number];
export const MODE_KO: Record<Mode, string> = { first: '가장 먼저 입력', survival: '서바이벌', speed: '타수 비교', accuracy: '정확도 대결', timeAttack: '타임어택' };
export const MODE_KO: Record<Mode, string> = { first: '가장 먼저 입력', survival: '서바이벌', speed: '타수 비교', accuracy: '정확도 대결', timeAttack: '타임어택', practice: '연습' };
export const ELIMS = ['wrong', 'sentence', 'interval', 'deadline'] as const;
export type Elim = (typeof ELIMS)[number];
@@ -53,7 +53,7 @@ export type TypingAction = TypingClientAction | { type: 'tick' } | { type: 'leav
/**
* `shared`: everybody types the same item at the same time (가장 먼저 입력, 서바이벌 except 시간별).
* `lane`: everybody goes through the round's items on their own (타수 비교, 정확도 대결, 타임어택, 서바이벌 시간별).
* `lane`: everybody goes through the round's items on their own (타수 비교, 정확도 대결, 타임어택, 서바이벌 시간별, 연습).
*/
export type Flow = 'shared' | 'lane';
@@ -93,6 +93,9 @@ export interface RoundSeat {
solvedAt: number | null;
/** Server times of recent actions (rate limit). */
recent: number[];
/** 연습: the best 타수 of one line this round; whether the current line's clock has started (at its first key). */
best?: number;
started?: boolean;
}
export interface SeatTotals {
@@ -190,6 +193,8 @@ export interface SeatView {
prog: number;
roundKpm: number;
roundAcc: number;
/** 연습: the best 타수 of one line this round. */
bestKpm: number;
/** Something was submitted this round / this game (so an accuracy of 0 is a real 0, not "nothing yet"). */
roundTried: boolean;
tried: boolean;

View File

@@ -9,7 +9,12 @@ import {
autoItemMs,
itemLimit,
ROUND_ITEMS,
PRACTICE_ITEMS,
REACTION_MS,
TOPIC_BY_ID,
flowOf,
kpm,
wrapLines,
itemText,
keyCount,
minTypingMs,
@@ -316,6 +321,72 @@ describe('타수 비교 · 정확도 대결 · 타임어택', () => {
});
});
describe('연습', () => {
test('짧은글: one round of 10 sentences, no clock, no points; the next sentence comes at once', () => {
let s = tick(make({ mode: 'practice', rounds: 5, timeLimit: 30 }, ['A']), START);
expect(flowOf(s.options)).toBe('lane');
expect(s.items.length).toBe(PRACTICE_ITEMS.short);
expect(s.roundEndsAt).toBeNull();
expect(typing.deadline!(s)).toBeNull();
// Long after any clock would have run out, typing goes on.
let t = START + 10 * 60_000;
for (let i = 0; i < s.items.length; i++) {
s = act(s, 'A', { type: 'progress', item: i, text: s.items[i]!.slice(0, 1) }, (t += 1000));
s = act(s, 'A', { type: 'submit', item: i, text: i === 0 ? `${s.items[i]}x` : s.items[i]! }, (t += 8000));
}
expect(s.phase).toBe('ended');
expect(s.rounds.length).toBe(1);
expect(s.rounds[0]!.winners).toEqual([]);
expect(s.totals.A!.points).toBe(0);
const v = typing.view(s, 'A').seats[0]!;
expect(v.wrong).toBe(1);
expect(v.done).toBe(PRACTICE_ITEMS.short);
expect(typing.result(s)!.scoreText!.A).toMatch(/^평균 \d+타 · 정확도 [\d.]+%$/);
});
test('a line is timed from its first key: a rest before it does not lower the 타수; the best line is kept', () => {
let s = tick(make({ mode: 'practice', category: 'word' }, ['A']), START);
expect(s.items.length).toBe(PRACTICE_ITEMS.word);
const w0 = s.items[0]!;
// A long rest, then the word typed in 2 s.
s = act(s, 'A', { type: 'progress', item: 0, text: w0.slice(0, 1) }, START + 60_000);
s = act(s, 'A', { type: 'submit', item: 0, text: w0 }, START + 62_000);
expect(s.rs.A!.ms).toBe(2000 + REACTION_MS);
const fast = kpm(keyCount(w0), 2000 + REACTION_MS);
expect(typing.view(s, 'A').seats[0]!.bestKpm).toBe(fast);
// A slower second word keeps the best.
const w1 = s.items[1]!;
s = act(s, 'A', { type: 'progress', item: 1, text: w1.slice(0, 1) }, START + 63_000);
s = act(s, 'A', { type: 'submit', item: 1, text: w1 }, START + 73_000);
expect(typing.view(s, 'A').seats[0]!.bestKpm).toBe(Math.max(fast, kpm(keyCount(w1), 10_000 + REACTION_MS)));
// Still no pasting: Enter right after the first key is refused.
s = act(s, 'A', { type: 'progress', item: 2, text: s.items[2]!.slice(0, 1) }, START + 80_000);
expect(reason(s, 'A', { type: 'submit', item: 2, text: s.items[2]! }, START + 80_001)).toContain('붙여 넣기');
});
test('긴글: one whole text, first line to last, shown as one passage', () => {
const s = tick(make({ mode: 'practice', category: 'long', topics: ['ko-anthem'] }, ['A']), START);
const t = TOPIC_BY_ID['ko-anthem']!;
expect(s.items).toEqual(wrapLines(t.items, 'ko'));
expect(s.items.length).toBeGreaterThan(8);
const v = typing.view(s, 'A');
expect(v.passage).toEqual(s.items);
expect(v.passageTitle).toBe(t.name);
expect(v.total).toBe(s.items.length);
});
test('with others: everybody at their own pace; ranked by 타수; the game ends when all are done', () => {
let s = tick(make({ mode: 'practice', category: 'word' }), START);
const n = s.items.length;
for (let i = 0; i < n; i++) s = act(s, 'A', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 3000);
expect(s.phase).toBe('playing');
for (let i = 0; i < n; i++) s = act(s, 'B', { type: 'submit', item: i, text: s.items[i]! }, START + (i + 1) * 6000);
expect(s.phase).toBe('ended');
expect(s.final!.ranking.map((r) => r.id)).toEqual(['A', 'B']);
expect(s.final!.summary).toContain('연습 끝');
});
});
describe('서바이벌은 반드시 끝나요', () => {
/** Fires the server clock until the game ends (nobody types). */
const runClock = (s: TypingState, max = 500) => {
@@ -435,6 +506,8 @@ describe('random playouts', () => {
{ mode: 'speed', category: 'long' },
{ mode: 'accuracy', timeLimit: null },
{ mode: 'timeAttack', category: 'word' },
{ mode: 'practice' },
{ mode: 'practice', category: 'long', lang: 'en' },
];
test.each(combos.map((c) => [JSON.stringify(c), c] as const))('%s finishes without leaking the next text', (_, c) => {
const seeds = playoutSeeds(60);