Files
joke-app/packages/games/src/catchmind/text.ts
EJClaw 16d3c86486 M8: 그림 맞히기 규칙·화면·테스트
- packages/games/src/catchmind: 규칙 모듈(출제 순서·단어 풀 RNG, 고르기/그리기/공개 단계,
  정답 정규화(NFKC·제로폭·끝말·초성 차단·정답 포함 차단·자모 거리 "아까워요"), multi/firstOnly 점수,
  힌트 50%/75%, 신고 과반, 출제자 연결 끊김 10초, 자리 비움 건너뛰기와 "돌아왔어요", 결과 순위),
  단어 740개(words.ko.json, 10개 분야·쉬움/보통, 어린이 안전), 테스트 34개(§10 전부 + 무작위 1,000판)
- 그림 스트리밍: draw 액션은 canvasOp 이벤트만 'stream' 메시지로 중계하고 view에는 개수만,
  (재)접속·sync 때만 syncView로 전체 그림 기록 전송. 스트림 액션 로그는 묶어서(최대 1초) 저장
- 엔진/서버 최소 확장(하위 호환): validate(..., ctx?: {now}), isStreamAction, syncView,
  disconnectGraceMs 선택 훅, ServerMessage 'stream', RoomStore.save 로그 배열 허용
- apps/web/src/games/catchmind: 캔버스 그리기(포인터·coalesced 이벤트, 색 12·굵기 4·지우개·되돌리기·
  전체 지우기), 게이트웨이 한도 아래로 맞춘 배치 전송, 중간점 곡선 렌더링, 힌트 줄·시간 막대·점수판,
  정답/채팅 입력과 "아까워요"·"정답!" 표시, 단어 고르기, 그림 PNG 저장, 옵션·규칙
- 등록(GAMES, 카탈로그, 화면 레지스트리, 아이콘), 방 단위 테스트 4개, E2E 계획(PC+폰 실제 그리기·맞히기)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 00:38:30 +09:00

174 lines
6.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 그림 맞히기 text rules: answer normalisation, initial consonants, "아까워요" distance (docs/games/catchmind.md §5.3). */
const CHO = ['ㄱ', 'ㄲ', 'ㄴ', 'ㄷ', 'ㄸ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅃ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅉ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'];
const JUNG = ['ㅏ', 'ㅐ', 'ㅑ', 'ㅒ', 'ㅓ', 'ㅔ', 'ㅕ', 'ㅖ', 'ㅗ', 'ㅘ', 'ㅙ', 'ㅚ', 'ㅛ', 'ㅜ', 'ㅝ', 'ㅞ', 'ㅟ', 'ㅠ', 'ㅡ', 'ㅢ', 'ㅣ'];
const JONG = ['', 'ㄱ', 'ㄲ', 'ㄳ', 'ㄴ', 'ㄵ', 'ㄶ', 'ㄷ', 'ㄹ', 'ㄺ', 'ㄻ', 'ㄼ', 'ㄽ', 'ㄾ', 'ㄿ', 'ㅀ', 'ㅁ', 'ㅂ', 'ㅄ', 'ㅅ', 'ㅆ', 'ㅇ', 'ㅈ', 'ㅊ', 'ㅋ', 'ㅌ', 'ㅍ', 'ㅎ'];
/** Compound vowels and double finals split into their parts (§5.3 "겹받침·이중모음도 분해"). */
const SPLIT: Record<string, string> = {
ㅘ: 'ㅗㅏ',
ㅙ: 'ㅗㅐ',
ㅚ: 'ㅗㅣ',
ㅝ: 'ㅜㅓ',
ㅞ: 'ㅜㅔ',
ㅟ: 'ㅜㅣ',
ㅢ: 'ㅡㅣ',
ㄳ: 'ㄱㅅ',
ㄵ: 'ㄴㅈ',
ㄶ: 'ㄴㅎ',
ㄺ: 'ㄹㄱ',
ㄻ: 'ㄹㅁ',
ㄼ: 'ㄹㅂ',
ㄽ: 'ㄹㅅ',
ㄾ: 'ㄹㅌ',
ㄿ: 'ㄹㅍ',
ㅀ: 'ㄹㅎ',
ㅄ: 'ㅂㅅ',
};
const SYL_FIRST = 0xac00;
const SYL_LAST = 0xd7a3;
const isSyllable = (ch: string): boolean => {
const c = ch.codePointAt(0)!;
return c >= SYL_FIRST && c <= SYL_LAST;
};
/** Text without spaces, punctuation and symbols (raw, before NFKC). */
const bare = (raw: string): string => raw.replace(/[\s\p{P}\p{S}\u200B-\u200D\uFEFF]/gu, '');
/** Hangul compatibility jamo only (U+3131–U+318E), ignoring spaces and punctuation. */
export function isCompatJamoOnly(raw: string): boolean {
const t = bare(raw);
return t.length > 0 && /^[ㄱ-ㆎ]+$/u.test(t);
}
const ENDINGS = ['요', '다', '이다', '입니다', '인가', '인가요'];
/** §5.3 normalize(): NFKC, zero-width, spaces, punctuation/symbols/emoji, lower case. */
export function normalize(s: string): string {
return s
.normalize('NFKC')
.replace(/[\u200B-\u200D\uFEFF\u2060\uFE0F\u20E3]/gu, '')
.replace(/\s+/gu, '')
.replace(/[\p{P}\p{S}\p{Extended_Pictographic}]/gu, '')
.toLowerCase();
}
/** Initial consonants of every syllable (other characters kept as they are). */
export function chosung(word: string): string {
return [...word]
.map((ch) => (isSyllable(ch) ? CHO[Math.floor((ch.codePointAt(0)! - SYL_FIRST) / 588)]! : ch))
.join('');
}
export function initialOf(ch: string): string {
return isSyllable(ch) ? CHO[Math.floor((ch.codePointAt(0)! - SYL_FIRST) / 588)]! : ch;
}
/** Syllables → compatibility jamo with compound vowels / double finals split. */
export function jamo(s: string): string {
let out = '';
for (const ch of s) {
if (!isSyllable(ch)) {
out += SPLIT[ch] ?? ch;
continue;
}
const i = ch.codePointAt(0)! - SYL_FIRST;
const l = CHO[Math.floor(i / 588)]!;
const v = JUNG[Math.floor((i % 588) / 28)]!;
const t = JONG[i % 28]!;
out += l + (SPLIT[v] ?? v) + (SPLIT[t] ?? t);
}
return out;
}
export function levenshtein(a: string, b: string): number {
const x = [...a];
const y = [...b];
let prev = Array.from({ length: y.length + 1 }, (_, j) => j);
for (let i = 1; i <= x.length; i++) {
const cur = [i];
for (let j = 1; j <= y.length; j++) {
cur[j] = Math.min(prev[j]! + 1, cur[j - 1]! + 1, prev[j - 1]! + (x[i - 1] === y[j - 1] ? 0 : 1));
}
prev = cur;
}
return prev[y.length]!;
}
export type Judgement = 'correct' | 'chosung' | 'contains' | 'close' | 'plain';
/**
* Judges one guess against the answer and its aliases (§5.3).
* - Compatibility-jamo-only text is never correct; it is held back when it spells the answer's initials or the answer itself.
* - correct: exact match after normalize, optionally followed by a polite ending (요/다/이다/입니다/인가/인가요).
* - contains: the answer inside a longer message → held back.
* - close: jamo edit distance ≤ 1 (answers up to 3 letters) or ≤ 2 (4+ letters).
*/
export function judge(text: string, answers: string[], closeHint: boolean): Judgement {
const cands = answers.map(normalize).filter((c) => c.length > 0);
if (isCompatJamoOnly(text)) {
const t = bare(text);
const spelled = normalize(text);
if (cands.some((c) => chosung(c) === t || spelled === c || spelled.includes(c))) return 'chosung';
return 'plain';
}
const n = normalize(text);
if (!n) return 'plain';
for (const c of cands) {
if (n === c) return 'correct';
if (n.startsWith(c) && ENDINGS.includes(n.slice(c.length))) return 'correct';
}
if (cands.some((c) => n.includes(c))) return 'contains';
if (closeHint) {
const jn = jamo(n);
for (const c of cands) {
const limit = [...c].length <= 3 ? 1 : 2;
if (levenshtein(jn, jamo(c)) <= limit) return 'close';
}
}
return 'plain';
}
// ---------------------------------------------------------------- filters
/** Small built-in list (same spirit as the nickname filter). Matching ignores spaces and punctuation. */
const BANNED = ['시발', '씨발', '병신', '좆', '개새끼', '느금', '니애미', '섹스', '자살', '살인', 'fuck', 'shit', 'bitch', 'sex'];
export function isBanned(text: string): boolean {
const squashed = text.normalize('NFKC').toLowerCase().replace(/[\s_.\-*0-9]/g, '');
return BANNED.some((w) => squashed.includes(w));
}
export function maskBanned(text: string): string {
let out = text;
for (const w of BANNED) {
const re = new RegExp(w.split('').join('[\\s_.\\-*]*'), 'gi');
out = out.replace(re, (m) => '*'.repeat(m.length));
}
return out;
}
/** Control characters out, trimmed. */
export function cleanText(text: string): string {
return text.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
}
export const CUSTOM_WORD_RE = /^[가-힣A-Za-z0-9]{1,10}$/;
export const MAX_CUSTOM_WORDS = 200;
/** §3.2 customWords: one per line, 1–10 Hangul/Latin/digits, filtered, deduplicated, at most 200. */
export function parseCustomWords(raw: string): string[] {
const out: string[] = [];
const seen = new Set<string>();
for (const line of raw.split(/\r?\n/)) {
const w = line.normalize('NFC').trim();
if (!CUSTOM_WORD_RE.test(w) || isBanned(w)) continue;
const key = normalize(w);
if (seen.has(key)) continue;
seen.add(key);
out.push(w);
if (out.length >= MAX_CUSTOM_WORDS) break;
}
return out;
}