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