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

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -35,6 +35,7 @@ export const GAME_ICON: Record<string, string> = {
blackjack: '🂡',
'six-nimmt': '🐮',
gemblo: '💠',
typing: '⌨️',
'hot-streak': '🏁',
tichu: '🐉',
'case-file': '🔍',
@@ -48,5 +49,5 @@ export const UPCOMING: string[] = [];
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue', 'gemblo', 'castles-of-burgundy'] },
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code', 'six-nimmt', 'tichu'] },
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple', 'hot-streak', 'case-file'] },
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple', 'typing', 'hot-streak', 'case-file'] },
];