타자 대결 연습 모드: 한컴 타자연습처럼 짧은글 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:
@@ -43,3 +43,15 @@ test('글자 표시: 맞음·틀림·조합 중인 글자', () => {
|
||||
expect(marks('강아지', '강오지').marks).toEqual(['ok', 'bad', 'ok']);
|
||||
expect(marks('abc', 'abcd')).toEqual({ marks: ['ok', 'ok', 'ok'], extra: 1 });
|
||||
});
|
||||
|
||||
test('타자 대결: 연습은 라운드·점수 없이 평균·최고 타수', () => {
|
||||
const { state: s0, now } = setupGame('typing', 1, { mode: 'practice' });
|
||||
const s = tick(s0, now + 3000);
|
||||
const t = helpNow(view(s, 'A'), 'A', users);
|
||||
expect(t).toContain('연습.');
|
||||
expect(t).not.toContain('라운드');
|
||||
expect(t).toContain('최고 0타');
|
||||
s.phase = 'ended';
|
||||
s.final = { ranking: [], summary: '연습 끝! 타수와 정확도를 확인해요' };
|
||||
expect(helpNow(view(s, 'A'), 'A', users)).toContain('연습이 끝났어요');
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@ const MODE_LINE: Record<TypingView['options']['mode'], string> = {
|
||||
speed: '각자 한 줄씩 치고 Enter를 누르면 다음 줄이 나와요. 라운드 타수(1분에 친 타 수, 틀린 만큼은 빼요)가 가장 높은 사람이 1점이에요.',
|
||||
accuracy: '각자 한 줄씩 치고 Enter를 누르면 다음 줄이 나와요. 정확도가 가장 높은 사람이 1점이에요(같으면 타수).',
|
||||
timeAttack: '시간이 끝날 때까지 나오는 글을 계속 쳐요. 정확하게 친 타 수가 가장 많은 사람이 1점이에요.',
|
||||
practice: '제한 시간과 점수 없이 한 줄씩 제 속도로 쳐요. 문장마다 첫 글자를 친 때부터 타수를 재요.',
|
||||
};
|
||||
|
||||
function leader(v: TypingView, players: Record<string, PublicUser>, me: string | null): string {
|
||||
@@ -22,10 +23,13 @@ function leader(v: TypingView, players: Record<string, PublicUser>, me: string |
|
||||
}
|
||||
|
||||
export function helpNow(v: TypingView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
if (v.phase === 'ended') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자의 점수, 평균 타수와 정확도를 볼 수 있어요.';
|
||||
if (v.phase === 'ended')
|
||||
return v.options.mode === 'practice'
|
||||
? `연습이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n평균·최고 타수와 정확도를 확인하고, [한 판 더]로 한 번 더 연습할 수 있어요.'
|
||||
: `게임이 끝났어요. ${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 head = mode === 'practice' ? `${MODE_KO[mode]}.` : `${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}` : ''}`;
|
||||
@@ -39,7 +43,7 @@ export function helpNow(v: TypingView, me: string | null, players: Record<string
|
||||
else if (v.flow === 'lane' && mine.finished) lines.push('이번 라운드를 다 쳤어요. 다른 사람이 끝내기를 기다려요.');
|
||||
else lines.push(HOW);
|
||||
lines.push(MODE_LINE[mode]);
|
||||
lines.push(`이번 라운드: ${mine.roundKpm}타, 정확도 ${mine.roundTried ? `${mine.roundAcc}%` : '아직 없음'}${mine.wrong ? `, 틀린 Enter ${mine.wrong}번` : ''}.`);
|
||||
lines.push(`${mode === 'practice' ? `지금까지: 평균 ${mine.roundKpm}타, 최고 ${mine.bestKpm}타` : `이번 라운드: ${mine.roundKpm}타`}, 정확도 ${mine.roundTried ? `${mine.roundAcc}%` : '아직 없음'}${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' ? '영어가 쳐지면 한/영 키를 눌러 한글로 바꿔요.' : '한글이 쳐지면 한/영 키를 눌러 영어로 바꿔요.');
|
||||
|
||||
@@ -181,6 +181,7 @@ function Seats({ v, me, players, live }: { v: TypingView; me: string | null; pla
|
||||
const surv = v.options.mode === 'survival';
|
||||
const lives = surv && v.options.elimination === 'wrong';
|
||||
const unit = v.options.mode === 'first' ? '점' : '승';
|
||||
const practice = v.options.mode === 'practice';
|
||||
return (
|
||||
<ul className="ty-seats" aria-label="참가자">
|
||||
{v.seats.map((s) => {
|
||||
@@ -197,8 +198,7 @@ function Seats({ v, me, players, live }: { v: TypingView; me: string | null; pla
|
||||
{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}
|
||||
{lives && s.alive && <Hearts n={s.lives} max={v.options.lives} />} {practice ? `${s.roundKpm}타` : `${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)}%` }} />
|
||||
@@ -269,8 +269,10 @@ function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
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 practice = v.options.mode === 'practice';
|
||||
// When the current item's clock started (연습: at its first key, 0 = not yet).
|
||||
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 };
|
||||
if (startedAt.current.key !== itemKey && item) startedAt.current = { key: itemKey, at: practice ? 0 : shared ? Math.max(v.curAt, now) : now };
|
||||
|
||||
// A new item: empty box, focus on it.
|
||||
useEffect(() => {
|
||||
@@ -390,11 +392,14 @@ function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
});
|
||||
|
||||
const ck = item ? correctKeys(item.text, typed) : 0;
|
||||
const elapsed = item ? Math.max(0, now - startedAt.current.at) : 0;
|
||||
const elapsed = item && startedAt.current.at ? 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 roundLabel = practice ? null : `라운드 ${v.round}/${v.options.rounds}`;
|
||||
// 연습: how long I have been at it (like 한컴 타자연습's 경과 시간).
|
||||
const spent = practice && v.phase === 'playing' && mine && !mine.finished && !laneDone ? Math.max(0, now - v.roundStartedAt) : null;
|
||||
const progressPct = v.total ? Math.round((Math.min(myIdx, v.total) / v.total) * 100) : 0;
|
||||
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;
|
||||
@@ -412,7 +417,7 @@ function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
<div className="ty">
|
||||
<style>{CSS}</style>
|
||||
<div className="ty-top">
|
||||
<span className="ty-pill">{roundLabel}</span>
|
||||
{roundLabel && <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>}
|
||||
@@ -421,6 +426,11 @@ function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
⏱ {surv && !shared ? `탈락까지 ${clock(left)}` : clock(left)}
|
||||
</span>
|
||||
)}
|
||||
{spent !== null && (
|
||||
<span className="ty-pill" aria-label={`걸린 시간 ${clock(spent)}`}>
|
||||
⏱ {clock(spent)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="ty-card">
|
||||
{v.passage && (
|
||||
@@ -447,7 +457,9 @@ function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
) : (
|
||||
<div className="ty-target" style={{ color: 'var(--text-sub)', fontSize: '1.15rem' }}>
|
||||
{v.phase === 'ended'
|
||||
? '게임 끝!'
|
||||
? practice
|
||||
? '연습 끝!'
|
||||
: '게임 끝!'
|
||||
: v.phase === 'countdown'
|
||||
? '곧 시작해요!'
|
||||
: gap
|
||||
@@ -496,6 +508,7 @@ function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
onChange={(e) => {
|
||||
const t = e.target.value;
|
||||
if (t.length > typed.length && !composing.current) tySound.key();
|
||||
if (practice && !startedAt.current.at && normalize(t)) startedAt.current.at = socket.now();
|
||||
setTyped(t);
|
||||
sendProgress(t);
|
||||
}}
|
||||
@@ -525,7 +538,26 @@ function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
{note.text}
|
||||
</div>
|
||||
)}
|
||||
{mine && v.phase === 'playing' && (
|
||||
{mine && v.phase === 'playing' && practice && (
|
||||
<div className="ty-stats">
|
||||
<span>지금 {curKpm}타</span>
|
||||
<span>평균 {mine.roundKpm}타</span>
|
||||
<span>최고 {mine.bestKpm}타</span>
|
||||
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
|
||||
<span>진행 {progressPct}%</span>
|
||||
</div>
|
||||
)}
|
||||
{mine && v.phase === 'ended' && practice && (
|
||||
<div className="ty-stats" role="status" style={{ fontSize: '1.05rem' }}>
|
||||
<span>평균 {mine.roundKpm}타</span>
|
||||
<span>최고 {mine.bestKpm}타</span>
|
||||
<span>정확도 {mine.roundTried ? `${mine.roundAcc}%` : '-'}</span>
|
||||
<span>
|
||||
{mine.done}줄 중 틀린 줄 {mine.wrong}개
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{mine && v.phase === 'playing' && !practice && (
|
||||
<div className="ty-stats">
|
||||
<span>지금 {curKpm}타</span>
|
||||
<span>이번 라운드 {mine.roundKpm}타</span>
|
||||
@@ -538,7 +570,7 @@ function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
<div className="ty-over" aria-hidden>
|
||||
<b key={countdown}>{countdown}</b>
|
||||
<small>
|
||||
{v.round > 1 ? `라운드 ${v.round} · ` : ''}
|
||||
{v.round > 1 && !practice ? `라운드 ${v.round} · ` : ''}
|
||||
{CATEGORY_KO[v.options.category]} · {MODE_KO[v.options.mode]}
|
||||
</small>
|
||||
</div>
|
||||
@@ -563,6 +595,7 @@ function TypingBoard({ view: v, me, players, act }: BoardProps<TypingView>) {
|
||||
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' ? '점' : '승';
|
||||
const practice = v.options.mode === 'practice';
|
||||
return (
|
||||
<>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
@@ -580,10 +613,12 @@ function TypingSide({ view: v, players }: BoardProps<TypingView>) {
|
||||
<span className="small muted" style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.kpm}타 · {s.tried ? `${s.acc}%` : '-'}
|
||||
</span>
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.points}
|
||||
{unit}
|
||||
</strong>
|
||||
{!practice && (
|
||||
<strong style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.points}
|
||||
{unit}
|
||||
</strong>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
@@ -595,7 +630,7 @@ function TypingSide({ view: v, players }: BoardProps<TypingView>) {
|
||||
{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(', ') : '승자 없음'}
|
||||
{practice ? '연습 기록' : `라운드 ${r.round} · ${r.winners.length ? r.winners.map((w) => nick(players, w)).join(', ') : '승자 없음'}`}
|
||||
</span>
|
||||
<RoundTable r={r} players={players} mode={v.options.mode} />
|
||||
</div>
|
||||
@@ -612,8 +647,7 @@ function TypingSide({ view: v, players }: BoardProps<TypingView>) {
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small">
|
||||
{' '}
|
||||
· {r.points}
|
||||
{unit} · 평균 {r.kpm}타 · 정확도 {r.acc}%{r.left ? ' · 나감' : ''}
|
||||
· {practice ? '' : `${r.points}${unit} · `}평균 {r.kpm}타 · 정확도 {r.acc}%{r.left ? ' · 나감' : ''}
|
||||
</span>
|
||||
</span>
|
||||
))}
|
||||
@@ -635,10 +669,10 @@ function isMyTurn(v: TypingView, me: string | null): boolean {
|
||||
|
||||
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 === 'countdown') return `${v.options.mode === 'practice' ? '연습' : `라운드 ${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) return v.options.mode === 'practice' ? MODE_KO.practice : `${MODE_KO[v.options.mode]} · 라운드 ${v.round}/${v.options.rounds}`;
|
||||
if (s.left) return '게임에서 나갔어요';
|
||||
if (!s.alive) return '탈락했어요 · 다음 라운드를 기다려요';
|
||||
if (v.flow === 'shared') {
|
||||
@@ -647,7 +681,7 @@ function statusText(v: TypingView, me: string | null, players: Record<string, Pu
|
||||
return v.options.mode === 'first' ? '가장 먼저 정확하게 치면 1점!' : '제한 시간 안에 정확하게 쳐요!';
|
||||
}
|
||||
if (s.finished) return '다 쳤어요! 다른 사람을 기다려요';
|
||||
return v.options.mode === 'timeAttack' ? '시간 안에 최대한 많이 쳐요!' : '한 줄씩 치고 Enter!';
|
||||
return v.options.mode === 'timeAttack' ? '시간 안에 최대한 많이 쳐요!' : v.options.mode === 'practice' ? '한 줄씩 치고 Enter! 천천히 정확하게 연습해요' : '한 줄씩 치고 Enter!';
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
@@ -670,6 +704,7 @@ const MODE_HELP: Record<Mode, string> = {
|
||||
speed: '각자 자기 속도로 글을 치고, 라운드의 타수(1분에 친 타 수, 오타는 빼고)가 가장 높은 사람이 1점이에요.',
|
||||
accuracy: '각자 글을 치고, 정확도가 가장 높은 사람이 1점이에요. 정확도가 같으면 타수가 높은 사람이 이겨요.',
|
||||
timeAttack: '정해진 시간 동안 끝없이 나오는 글을 쳐요. 정확하게 친 타 수가 가장 많은 사람이 1점이에요.',
|
||||
practice: '한컴 타자연습처럼 혼자(또는 함께) 제 속도로 연습해요. 제한 시간과 점수 없이 짧은글은 10문장, 단어는 20개, 긴글은 한 편을 처음부터 끝까지 쳐요. 문장마다 첫 글자를 친 때부터 타수를 재요.',
|
||||
};
|
||||
const ELIM_HELP: Record<Elim, string> = {
|
||||
wrong: '틀린 채로 Enter를 누르거나 시간 안에 못 치면 목숨이 하나 줄고, 목숨을 다 쓰면 탈락해요.',
|
||||
@@ -688,7 +723,8 @@ function Options({ value: o, onChange }: OptionsProps<TypingOptions>) {
|
||||
set({ topics: [...others, ...next] });
|
||||
};
|
||||
const timeLabel = o.mode === 'speed' || o.mode === 'accuracy' ? '라운드 제한 시간' : '한 문제 제한 시간';
|
||||
const showTime = o.mode !== 'timeAttack' && !(o.mode === 'survival' && o.elimination === 'interval');
|
||||
const practice = o.mode === 'practice';
|
||||
const showTime = o.mode !== 'timeAttack' && !practice && !(o.mode === 'survival' && o.elimination === 'interval');
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
@@ -720,8 +756,8 @@ function Options({ value: o, onChange }: OptionsProps<TypingOptions>) {
|
||||
</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 })} />
|
||||
<strong>{practice ? '연습 종목' : '대결 종목'}</strong>
|
||||
<Seg label={practice ? '연습 종목' : '대결 종목'} 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>
|
||||
@@ -737,13 +773,15 @@ function Options({ value: o, onChange }: OptionsProps<TypingOptions>) {
|
||||
</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줄 안팎)씩 이어서 쳐요.' : ''}
|
||||
{o.category === 'long' ? (practice ? ' 연습은 그중 한 편을 처음부터 끝까지 쳐요.' : ' 긴글은 라운드마다 한 단락(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>
|
||||
{!practice && (
|
||||
<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>
|
||||
@@ -778,7 +816,7 @@ 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}라운드`;
|
||||
return `${LANG_KO[o.lang]} · ${MODE_KO[o.mode]}${sub} · ${CATEGORY_KO[o.category]}(${picked.length ? picked.join(', ') : '전체 주제'})${o.mode === 'practice' ? '' : ` · ${o.rounds}라운드`}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- rules
|
||||
@@ -808,6 +846,9 @@ function Rules({ options: o }: { options?: TypingOptions }) {
|
||||
<li>
|
||||
<strong>타임어택</strong>: 정해진 시간 동안 끝없이 나오는 글을 쳐서, 정확하게 친 타 수가 가장 많은 사람이 1점.
|
||||
</li>
|
||||
<li>
|
||||
<strong>연습</strong>: 한컴 타자연습처럼 제한 시간·점수 없이 제 속도로 쳐요. 짧은글 10문장, 단어 20개, 긴글은 한 편 전체. 지금·평균·최고 타수, 정확도, 진행률과 걸린 시간을 보여 줘요.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
라운드는 1~10번(기본 3번)이에요. 모두 끝나면 점수가 가장 높은 사람이 이기고, 같으면 평균 타수가 높은 사람이 앞서요. 한국어·영어, 단어·짧은글·긴글과 주제(여러 개)를 방 설정에서 골라요. 혼자서도, 컴퓨터와도 할 수
|
||||
|
||||
@@ -78,7 +78,7 @@ export const quickStart: QuickCard[] = [
|
||||
),
|
||||
alt: '세 사람의 진행 막대예요. 호랑이가 먼저 다 쳤어요',
|
||||
title: '빠르고 정확하게',
|
||||
text: '가장 먼저 입력·서바이벌·타수 비교·정확도 대결·타임어택 중에서 골라요. 다른 사람이 친 만큼 막대로 보여요.',
|
||||
text: '가장 먼저 입력·서바이벌·타수 비교·정확도 대결·타임어택 중에서 골라요. 다른 사람이 친 만큼 막대로 보여요. 혼자 연습하려면 연습!',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
| 옵션 | 값 (기본값 굵게) |
|
||||
|---|---|
|
||||
| 언어 | **한국어**, 영어 |
|
||||
| 대결 방식 | **가장 먼저 입력**, 서바이벌, 타수 비교, 정확도 대결, 타임어택 |
|
||||
| 대결 방식 | **가장 먼저 입력**, 서바이벌, 타수 비교, 정확도 대결, 타임어택, 연습 |
|
||||
| 대결 종목 | 단어, **짧은글**, 긴글 |
|
||||
| 주제 | 여러 개 고르기, 비우면 **전체**(언어·종목에 맞는 주제만 쓰임) |
|
||||
| 라운드 | 1~10 (**3**) |
|
||||
@@ -33,6 +33,7 @@
|
||||
- 단어·짧은글: 고른 주제의 항목을 모두 섞은 덱 하나(시드 RNG). 라운드마다 덱에서 차례로 뽑는다(가장 먼저 입력: 단어 10개·짧은글 5문장, 타수 비교·정확도 대결: 단어 15개·짧은글 3문장). 덱을 다 쓰면 다시 섞는다.
|
||||
- 긴글: 주제 순서를 섞고 라운드마다 다음 주제의 다음 단락(8줄 안팎, 남는 2줄 이하는 앞 단락에 붙임)을 친다. 긴 줄은 띄어쓰기에서 나눈다(한국어 34자, 영어 52자).
|
||||
- 서바이벌·타임어택은 글이 끝없이 돈다.
|
||||
- 연습(2026-11-12 사용자 요청, 한컴 타자연습의 짧은글·긴글 연습처럼): 라운드 1번, 제한 시간·점수 없음(라운드·제한 시간 옵션은 안 씀). 단어 20개·짧은글 10문장, 긴글은 고른 주제 중 한 편을 처음부터 끝까지.
|
||||
- 라운드마다 3초 카운트다운. 그동안 첫 글은 숨긴다.
|
||||
|
||||
## 5. 진행 규칙
|
||||
@@ -41,8 +42,9 @@
|
||||
- 서바이벌 틀렸을 때: 틀린 Enter·시간 초과마다 목숨 −1, 0이면 탈락. 살아 있는 사람이 모두 치면 다음 문제.
|
||||
- 서바이벌 문장별: 남은 사람 중 마지막 한 사람이 남으면 그 사람 탈락. 시간 안에 못 친 사람도 탈락.
|
||||
- 서바이벌 시간 초과: 시간 안에 못 친 사람 모두 탈락.
|
||||
- **각자 치기**(타수 비교, 정확도 대결, 타임어택, 서바이벌 시간별): 각자 한 줄 치고 Enter → 다음 줄. 틀린 채로 넘어가도 되고 그만큼 정확도·타수가 깎인다.
|
||||
- **각자 치기**(타수 비교, 정확도 대결, 타임어택, 서바이벌 시간별, 연습): 각자 한 줄 치고 Enter → 다음 줄. 틀린 채로 넘어가도 되고 그만큼 정확도·타수가 깎인다.
|
||||
- 서바이벌 시간별: 정해진 간격마다 그때까지 친 타 수(지금 줄 포함)가 가장 적은 사람(같으면 함께) 탈락.
|
||||
- 연습: 줄마다 첫 타(첫 진행)부터 시간을 잰다(줄 사이에 쉬어도 타수가 안 떨어짐). 첫 타의 시간 몫으로 0.15초 앞당겨 시작하고, 그래서 붙여 넣기 막기도 다른 방식과 같다. 줄마다 타수의 최고값(`best`)을 둔다. 모두 다 치면 끝(여럿이면 각자 속도로).
|
||||
- 서바이벌은 문제마다 제한 시간이 0.9배씩 줄고(무제한은 자동으로 친다), 아주 빠른 사람(900타)이 치는 시간 + 1초 아래로는 줄지 않는다. 그래서 라운드가 반드시 끝난다.
|
||||
- 남은 사람이 모두 한꺼번에 탈락하게 되면 아무도 탈락하지 않는다(목숨은 1개로).
|
||||
- 붙여 넣기 막기: 화면에서 붙여 넣기·끌어 놓기를 막고, 서버는 2,400타/분 + 0.15초보다 빠른 Enter를 거절하며 진행 막대도 그 속도 이상 앞서지 않는다.
|
||||
@@ -52,6 +54,7 @@
|
||||
- 정확도 = 1 − 편집 거리 / 긴 쪽 글자 수.
|
||||
- 라운드 점수: 가장 먼저 입력은 문제마다 1점, 나머지는 라운드 1등(같으면 모두) 1점 — 타수 비교는 타수, 정확도 대결은 정확도(같으면 타수), 타임어택은 친 타 수, 서바이벌은 끝까지 남은 사람.
|
||||
- 최종: 점수 → 평균 타수 → 평균 정확도 순. 나간 사람은 맨 뒤.
|
||||
- 연습: 점수 없음, 순위는 평균 타수 → 정확도. `scoreText` = "평균 N타 · 정확도 N%".
|
||||
|
||||
## 7. 하우스 룰
|
||||
- 없음(위 옵션으로 조절).
|
||||
@@ -75,6 +78,7 @@
|
||||
- 한글 조합 중 Enter는 조합이 끝난 뒤 보낸다(IME가 Enter를 두 번 보내는 것도 거름). 붙여 넣기·끌어 놓기 막음, 자동 완성·맞춤법 끔.
|
||||
- 한/영이 반대로 쳐지면 경고. 지금 타수·라운드 타수·정확도·틀린 횟수 표시.
|
||||
- 아래: 모두의 진행 막대(stream으로 실시간), 목숨 하트, 탈락·다 침 표시. 문제가 정해지면 "OO님이 먼저 쳤어요! 352타"/"OO님 탈락!" 띠. 라운드 끝 표(순위·친 문제·타수·정확도), 6초 뒤 다음 라운드.
|
||||
- 연습: 라운드 표시 대신 걸린 시간(⏱), 아래에 지금·평균·최고 타수, 정확도, 진행 %. 끝나면 평균·최고 타수, 정확도, 틀린 줄. 참가자 막대 옆은 점수 대신 타수.
|
||||
- 소리: 자판 딸깍, 맞음, 틀림 삐, 먼저 침 팡파르, 탈락, 3·2·1, 마지막 5초.
|
||||
### 9.1 설정 화면
|
||||
언어·방식(서바이벌이면 탈락 조건·목숨·간격)·종목·주제(전체 또는 여러 개)·라운드 1~10·제한 시간/타임어택 시간. 방식마다 한 줄 설명.
|
||||
@@ -82,7 +86,9 @@
|
||||
## 10. 테스트 체크리스트
|
||||
- keys.test: 두벌식 타 수, 조합 중 글자, 정확도·편집 거리, 글 묶음 글자 검사·줄 나누기.
|
||||
- typing.test: 옵션·주제, 가장 먼저 입력(쉬는 시간, 늦은 답, 붙여 넣기, 시간 초과, 라운드·최종), 서바이벌 4가지와 모두 탈락 방지·줄어드는 시계, 타수 비교·정확도 대결·타임어택·무제한, 나가기, 무작위 대국 10가지 설정(누출 없음).
|
||||
- bot.test: 9가지 설정 × (사람 1 + 컴퓨터 / 컴퓨터만) 거절 0, 레벨별 타수.
|
||||
- typing.test 연습: 10문장·시계 없음·점수 없음, 첫 타부터 시간·최고 타수·붙여 넣기 막기, 긴글 한 편 전체, 여럿이 각자.
|
||||
- e2e typingPractice(짧은글, 3초 쉬어도 타수 유지)·typingPracticeLong(애국가 16줄 전체).
|
||||
- bot.test: 10가지 설정(연습은 컴퓨터끼리만) × (사람 1 + 컴퓨터 / 컴퓨터만) 거절 0, 레벨별 타수.
|
||||
- typing.room.test: 진행 stream, 연습 방, 끊긴 사람.
|
||||
- 웹 help.test: 도움말, 글자 표시.
|
||||
|
||||
|
||||
@@ -3746,6 +3746,103 @@ const PLANS: Record<string, Plan> = {
|
||||
console.log(` typingSurvival: result: ${text.replace(/\n/g, ' ').slice(0, 120)}`);
|
||||
},
|
||||
},
|
||||
typingPractice: {
|
||||
// 2026-11-12 연습 · 짧은글: like 한컴 타자연습 — no round, no clock, no points; 10 sentences one after another. The
|
||||
// stats show 지금·평균·최고 타수, 정확도, 진행 %, and a running ⏱. The host rests 3 s before a sentence: its 타수 is
|
||||
// timed from the first key, so the rest does not pull it down. Both finish; the result has 타수 and 정확도 only.
|
||||
game: 'typing',
|
||||
lobby: async (host) => {
|
||||
await host.getByRole('group', { name: '대결 방식' }).getByRole('button', { name: '연습' }).click();
|
||||
if (await host.getByRole('group', { name: '라운드' }).count()) throw new Error('연습 should not ask for rounds');
|
||||
await host.getByText(/한국어 · 연습 · 짧은글\(전체 주제\)(?! · )/).first().waitFor();
|
||||
},
|
||||
drive: async (pages) => {
|
||||
const [host, guest] = pages as [Page, Page];
|
||||
const lines: Record<string, number> = { host: 0, guest: 0 };
|
||||
const over = () => host.getByRole('dialog', { name: '게임 결과' }).count();
|
||||
const until = Date.now() + 150_000;
|
||||
let rested = false;
|
||||
while (Date.now() < until && !(await over())) {
|
||||
let acted = false;
|
||||
for (const [who, p] of [['host', host], ['guest', guest]] as const) {
|
||||
const text = await typingTarget(p);
|
||||
if (!text) continue;
|
||||
if (who === 'host' && lines.host === 0) {
|
||||
const top = await host.locator('.ty-top').innerText();
|
||||
if (/라운드/.test(top) || !/연습/.test(top) || !/⏱/.test(top)) throw new Error(`top bar: ${top.replace(/\n/g, ' ')}`);
|
||||
const stats = await host.locator('.ty-stats').innerText();
|
||||
if (!/최고 0타/.test(stats) || !/진행 0%/.test(stats)) throw new Error(`stats: ${stats.replace(/\n/g, ' ')}`);
|
||||
}
|
||||
if (who === 'host' && lines.host === 1 && !rested) {
|
||||
rested = true;
|
||||
await host.waitForTimeout(3000);
|
||||
}
|
||||
// A Hangul syllable is 2~3 keys: about 1,200타 at this pace (under the paste guard).
|
||||
await typeLine(p, text, 120);
|
||||
lines[who]!++;
|
||||
acted = true;
|
||||
if (who === 'host' && lines.host === 2) {
|
||||
// A 3 s rest before the second sentence would have made it < 150타 if it counted.
|
||||
await host.waitForFunction(() => /최고 (\d+)타/.test(document.querySelector('.ty-stats')?.textContent ?? ''));
|
||||
const stats = await host.locator('.ty-stats').innerText();
|
||||
const avg = Number(/평균 (\d+)타/.exec(stats)?.[1] ?? 0);
|
||||
if (avg < 250 || !/진행 20%/.test(stats)) throw new Error(`after the rest: ${stats.replace(/\n/g, ' ')}`);
|
||||
await host.screenshot({ path: join(SHOTS, 'typing-practice-pc.png') });
|
||||
await guest.screenshot({ path: join(SHOTS, 'typing-practice-phone.png') });
|
||||
}
|
||||
}
|
||||
if (!acted) await host.waitForTimeout(200);
|
||||
}
|
||||
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
|
||||
await host.waitForTimeout(600);
|
||||
await host.screenshot({ path: join(SHOTS, 'typing-practice-result-pc.png') });
|
||||
const text = await host.getByRole('dialog', { name: '게임 결과' }).innerText();
|
||||
if (lines.host !== 10 || lines.guest !== 10 || !/정확도 100%/.test(text) || !/방장\s*평균 \d+타/.test(text) || /방장\s*\d+승/.test(text)) throw new Error(`lines ${JSON.stringify(lines)}; result: ${text.replace(/\n/g, ' ')}`);
|
||||
console.log(` typingPractice: lines ${JSON.stringify(lines)}; result: ${text.replace(/\n/g, ' ').slice(0, 160)}`);
|
||||
},
|
||||
},
|
||||
typingPracticeLong: {
|
||||
// 연습 · 긴글 · 애국가: the whole text from the first line to the last (not one 8-line passage), shown as one
|
||||
// passage with the line I am on; the phone just watches the host's bar after typing one line.
|
||||
game: 'typing',
|
||||
lobby: async (host) => {
|
||||
await host.getByRole('group', { name: '대결 방식' }).getByRole('button', { name: '연습' }).click();
|
||||
await host.getByRole('group', { name: '연습 종목' }).getByRole('button', { name: '긴글' }).click();
|
||||
await host.getByRole('group', { name: '주제' }).getByRole('button', { name: '애국가' }).click();
|
||||
await host.getByText(/연습 · 긴글\(애국가\)(?! · )/).first().waitFor();
|
||||
},
|
||||
drive: async (pages) => {
|
||||
const [host, guest] = pages as [Page, Page];
|
||||
let total = 0;
|
||||
let typed = 0;
|
||||
const until = Date.now() + 150_000;
|
||||
while (Date.now() < until && !(await host.getByRole('dialog', { name: '게임 결과' }).count())) {
|
||||
const text = await typingTarget(host);
|
||||
if (!text) {
|
||||
if (typed && (await host.getByText('다 쳤어요! 다른 사람을 기다려요').count())) break;
|
||||
await host.waitForTimeout(200);
|
||||
continue;
|
||||
}
|
||||
if (!total) total = await host.locator('.ty-passage li').count();
|
||||
await host.locator('.ty-passage li[data-s="cur"]').filter({ hasText: text }).first().waitFor({ timeout: 3000 });
|
||||
await typeLine(host, text, 110);
|
||||
typed++;
|
||||
}
|
||||
// The guest has not finished: the game waits for them.
|
||||
if (await host.getByRole('dialog', { name: '게임 결과' }).count()) throw new Error('ended before the guest finished');
|
||||
await host.getByText('다 쳤어요! 다른 사람을 기다려요').waitFor();
|
||||
await host.screenshot({ path: join(SHOTS, 'typing-practice-long-pc.png') });
|
||||
for (let n = 0; n < 100; n++) {
|
||||
const text = await typingTarget(guest);
|
||||
if (text) await typeLine(guest, text, 110);
|
||||
else if (await guest.getByRole('dialog', { name: '게임 결과' }).count()) break;
|
||||
else await guest.waitForTimeout(200);
|
||||
}
|
||||
for (const p of pages) await p.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 20_000 });
|
||||
if (total <= 8 || typed !== total) throw new Error(`passage ${total} lines, typed ${typed}`);
|
||||
console.log(` typingPracticeLong: the whole 애국가, ${typed} lines`);
|
||||
},
|
||||
},
|
||||
appleUnlimited: {
|
||||
// 2026-10-14: 무제한 — the stopwatch runs (tenths) and stops when I finish; 💡 힌트 shows a glowing box that adds up
|
||||
// to 10 (button off while it shows), using it clears the box; the result shows 걸린 시간 and 힌트 N번.
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user