사과 게임: 같은 판(17×10) 합 10 만들기 경주, 1~8명·혼자 가능, 레벨별 컴퓨터(라이브 봇)

- 규칙 모듈 packages/games/src/apple: 시드로 만든 한 판(1~9, 합 10의 배수)을 모두 각자 풀고,
  직사각형 합이 딱 10이면 지운 개수만큼 점수. 빈 칸은 합에 영향 없음, 합≠10·빈 직사각형은 거절(벌점 없음).
  3초 카운트다운(판 숨김) → 제한 시간 1/2/3분(기본 2분), 서버 시계 마감(deadline = timeoutNotBefore,
  끊긴 사람 조기 시간 초과 없음), 1초 5번 속도 제한, 더 지울 게 없으면 막힘 → 모두 막히면 조기 종료,
  나가면 맨 아래 순위·혼자 남으면 끝. 동점은 같은 순위, 결과 "사과 N개".
- view는 내 판(170자 문자열)과 모두의 점수만(남의 판 없음). findMoves는 누적합으로 가장 좁은 합 10 직사각형 전부.
- 컴퓨터: 마피아처럼 LIVE_BOT_STRATEGIES.apple. live 전략에 level 전달(서버 bots.ts, live-playout).
  레벨 따라 찾는 시간(6초→2초)·시야·놓침(쉬움 30%)·고르기가 달라짐. 2분 평균 레벨1 약 28개 ~ 레벨60 약 99개.
- 화면 apps/web/src/games/apple: SVG 사과, 포인터 드래그(마우스·터치), 합계 실시간·10이면 초록,
  낙관적 지우기와 튀어 오르는 애니메이션, 휴대폰은 판을 돌려 10열×17줄, 키보드(화살표+스페이스 두 번, Esc),
  다른 사람 점수 칩, 다크 모드, 도움말·30초 요약.
- 등록(GAMES, CATALOG, BOT_GAMES, 화면 레지스트리, 아이콘·파티 탭), 문서 docs/games/apple.md, 09 §9 라이브 봇 줄.
- 테스트: 규칙 15개(무차별 대조, 무작위 대국 1·2·5·8명), 컴퓨터 5개, 도움말 2개, 방 통합 2개(컴퓨터와 끝까지),
  E2E(PC 마우스·키보드, 휴대폰 CDP 터치, 320px, 1분 뒤 결과).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-12 22:20:49 +09:00
parent 2ec622ebf6
commit b98775b0a6
24 changed files with 2056 additions and 8 deletions

View File

@@ -0,0 +1,42 @@
import { expect, test } from 'bun:test';
import { setupGame, usersOf } from '../help-kit.test-util';
import { GAMES } from '@bg/games';
import { helpNow } from './help';
const users = usersOf(['A', 'B', 'C']);
const view = (s: unknown, who: string | null) => GAMES.apple!.view(s, who) as any;
function playing(options: Record<string, unknown> = {}) {
const { state } = setupGame('apple', 3, options);
state.phase = 'playing';
return state;
}
test('사과 게임: 카운트다운 / 진행 중 / 관전', () => {
const { state: s0 } = setupGame('apple', 3, { timeLimitSec: 60 });
const c = helpNow(view(s0, 'A'), 'A', users);
expect(c).toContain('곧 시작해요');
expect(c).toContain('1분');
const s = playing();
const t = helpNow(view(s, 'A'), 'A', users);
expect(t).toContain('딱 10');
expect(t).toContain('빈 칸은 합에 들어가지 않아서');
expect(t).toContain('아직 아무도');
expect(t).toContain('스페이스');
s.score.B = 12;
expect(helpNow(view(s, 'A'), 'A', users)).toContain('지금 1등은 고양이님(사과 12개)');
expect(helpNow(view(s, 'B'), 'B', users)).toContain('지금 1등은 나(사과 12개)');
expect(helpNow(view(s, null), null, users)).toContain('가장 많이 지운 사람이 이겨요');
});
test('사과 게임: 막힘 / 나감 / 끝', () => {
const s = playing();
s.status.A = 'stuck';
s.score.A = 40;
expect(helpNow(view(s, 'A'), 'A', users)).toContain('사과 40개를 지웠어요');
s.status.B = 'left';
expect(helpNow(view(s, 'B'), 'B', users)).toContain('게임에서 나갔어요');
s.phase = 'ended';
s.final = { endReason: 'time', ranking: [], summary: '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요' };
expect(helpNow(view(s, 'A'), 'A', users)).toContain('시간이 다 됐어요');
});

View File

@@ -0,0 +1,33 @@
/** 사과 게임 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
import type { AppleView } from '@bg/games/apple';
import type { PublicUser } from '@bg/shared/lite';
const HOW = '사과 여러 개를 직사각형으로 드래그해서 숫자 합이 딱 10이 되면 손을 떼요. 그 사과들이 사라지고 사라진 개수만큼 점수를 얻어요.';
const KEYS = '키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 시작점, 한 번 더 눌러 끝점을 정해요. Esc는 취소예요.';
function leaders(v: AppleView, players: Record<string, PublicUser>, me: string | null): string {
const live = v.seats.filter((s) => s.status !== 'left');
if (live.length < 2) return '';
const best = Math.max(...live.map((s) => s.score));
if (best === 0) return '아직 아무도 사과를 지우지 않았어요.';
const top = live.filter((s) => s.score === best).map((s) => (s.id === me ? '나' : `${players[s.id]?.nickname ?? '다른 사람'}님`));
return `지금 1등은 ${top.join(', ')}(사과 ${best}개)예요.`;
}
export function helpNow(v: AppleView, me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'ended') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자 지운 사과 개수를 볼 수 있어요.';
const secs = v.options.timeLimitSec;
const limit = secs % 60 === 0 ? `${secs / 60}분` : `${secs}초`;
if (v.phase === 'countdown') return `곧 시작해요. 모두 똑같은 사과 판을 각자 풀어요. 제한 시간은 ${limit}이에요.\n${HOW}`;
const mine = v.seats.find((s) => s.id === me) ?? null;
const lead = leaders(v, players, me);
if (!mine) return `모두 똑같은 판을 각자 풀고 있어요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.${lead ? `\n${lead}` : ''}`;
if (mine.status === 'left') return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
if (mine.status === 'stuck') {
return `내 판에는 이제 합이 10이 되는 사과 묶음이 없어요. 사과 ${mine.score}개를 지웠어요. 시간이 끝나거나 모두 막히면 순위가 나와요.${lead ? `\n${lead}` : ''}`;
}
const lines = [HOW, '빈 칸은 합에 들어가지 않아서, 사이가 비어 있어도 멀리 있는 사과끼리 묶을 수 있어요.', `지금 내 점수는 사과 ${mine.score}개예요.`];
if (lead) lines.push(lead);
lines.push(KEYS);
return lines.join('\n');
}

View File

@@ -0,0 +1,600 @@
/** 사과 게임 화면 (docs/games/apple.md §9). */
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent, type ReactNode } from 'react';
import type { AppleOptions, AppleView, SeatView } from '@bg/games/apple';
import type { PublicUser } from '@bg/shared/lite';
import { Avatar } from '../../components/ui';
import { useServerNow } from '../../components/TurnTimer';
import { haptic, sounds } from '../../lib/feedback';
import { socket } from '../../net/socket';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { helpNow } from './help';
import { quickStart } from './quick';
/** Canonical board: 10 rows × 17 columns (phones show it turned: 17 rows × 10 columns). */
const ROWS = 10;
const COLS = 17;
/** SVG units per cell. */
const S = 40;
type Cell = [number, number];
interface Rect {
r0: number;
c0: number;
r1: number;
c1: number;
}
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 clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
const rectOf = (a: Cell, b: Cell): Rect => ({ r0: Math.min(a[0], b[0]), c0: Math.min(a[1], b[1]), r1: Math.max(a[0], b[0]), c1: Math.max(a[1], b[1]) });
/** Apples (indices) inside a rectangle and their sum. */
function inside(cells: string, r: Rect): { sum: number; idx: number[] } {
let sum = 0;
const idx: number[] = [];
for (let y = r.r0; y <= r.r1; y++) {
for (let x = r.c0; x <= r.c1; x++) {
const v = cells.charCodeAt(y * COLS + x) - 48;
if (v > 0) {
sum += v;
idx.push(y * COLS + x);
}
}
}
return { sum, idx };
}
const clock = (ms: number) => {
const s = Math.ceil(Math.max(0, ms) / 1000);
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
};
const limitLabel = (sec: number) => (sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
/** Ranks by score (ties share), players who left last. */
function ranked(seats: SeatView[]): (SeatView & { rank: number })[] {
const sorted = [...seats].sort((a, b) => Number(a.status === 'left') - Number(b.status === 'left') || b.score - a.score);
const out: (SeatView & { rank: number })[] = [];
sorted.forEach((s, i) => {
const prev = out[i - 1];
const tie = prev && prev.score === s.score && (prev.status === 'left') === (s.status === 'left');
out.push({ ...s, rank: tie ? prev.rank : i + 1 });
});
return out;
}
const CSS = `
.ap { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 8px; }
.ap-top { width: 100%; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; }
.ap-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; font-size: 1rem; white-space: nowrap; }
.ap-pill b { font-size: 1.2rem; }
.ap-pill.warn { background: var(--danger-soft); color: var(--danger); }
.ap-pill.sum { min-width: 104px; justify-content: center; border: 2px solid transparent; }
.ap-pill.sum[data-s='ok'] { background: var(--success-soft); color: var(--success); border-color: var(--success); }
.ap-pill.sum[data-s='over'] { background: var(--danger-soft); color: var(--danger); }
.ap-pill.sum[data-s='idle'] { color: var(--text-sub); }
.ap-others { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 6px; justify-content: center; max-width: 100%; }
.ap-others li { display: inline-flex; align-items: center; gap: 4px; border-radius: 999px; padding: 2px 8px 2px 3px; background: var(--surface-2); font-size: .85rem; font-weight: 700; max-width: 46vw; }
.ap-others li span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ap-others li b { font-variant-numeric: tabular-nums; }
.ap-others li[data-me='true'] { background: var(--primary-soft); }
.ap-others li[data-out='true'] { opacity: .55; }
.ap-wrap { position: relative; width: min(100%, 980px, calc((100vh - var(--site-h) - 250px) * 1.7)); min-width: 280px; }
.ap-wrap[data-phone='true'] { width: min(100%, 480px, max(280px, calc((100svh - 235px) / 1.7))); }
.ap-board { display: block; width: 100%; height: auto; touch-action: none; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none;
border-radius: 14px; background: #fff8e7; box-shadow: var(--shadow), inset 0 0 0 3px #e9c98a; cursor: crosshair; outline: none; }
.ap-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
.ap-board[data-off='true'] { cursor: default; }
:root[data-theme='dark'] .ap-board { background: #3b2f22; box-shadow: var(--shadow), inset 0 0 0 3px #6b4f2a; }
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .ap-board { background: #3b2f22; box-shadow: var(--shadow), inset 0 0 0 3px #6b4f2a; } }
.ap-pop { animation: ap-pop .42s ease-out forwards; transform-box: fill-box; transform-origin: center; pointer-events: none; }
.ap-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; pointer-events: none;
border-radius: 14px; text-align: center; padding: 12px; }
.ap-over.count { background: rgba(0,0,0,.35); color: #fff; font-size: 5rem; font-weight: 900; text-shadow: 0 3px 8px rgba(0,0,0,.5); }
.ap-over.count small { font-size: 1.05rem; font-weight: 800; }
.ap-over.note { inset: auto 8px 8px 8px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); font-weight: 800; }
.ap-flash { position: absolute; left: 50%; top: 8px; transform: translateX(-50%); z-index: 3; pointer-events: none; border-radius: 999px; padding: 4px 14px;
font-weight: 900; font-size: 1.05rem; background: var(--surface); box-shadow: 0 4px 14px rgba(0,0,0,.25); animation: ap-flash .9s ease forwards; }
.ap-flash.ok { color: var(--success); border: 3px solid var(--success); }
.ap-flash.bad { color: var(--text-sub); border: 3px solid var(--border); }
.ap-keys { color: var(--text-sub); font-size: .85rem; font-weight: 600; text-align: center; margin: 0; }
@keyframes ap-pop { 0% { transform: scale(1); opacity: 1; } 40% { transform: scale(1.25); opacity: .9; } 100% { transform: scale(.2) translateY(-30px); opacity: 0; } }
@keyframes ap-flash { 0% { opacity: 0; transform: translateX(-50%) scale(.8); } 15% { opacity: 1; transform: translateX(-50%) scale(1.05); } 70% { opacity: 1; } 100% { opacity: 0; } }
@media (prefers-reduced-motion: reduce) { .ap-pop { animation-duration: .01s; } .ap-flash { animation: none; } }
`;
// ---------------------------------------------------------------- art
/** The apple shape in a 40×40 cell (number drawn on top). */
function AppleDefs() {
return (
<defs>
<radialGradient id="ap-grad" cx="35%" cy="35%" r="70%">
<stop offset="0%" stopColor="#ff6b6b" />
<stop offset="55%" stopColor="#e11d2e" />
<stop offset="100%" stopColor="#a3111f" />
</radialGradient>
<g id="ap-apple">
<path d="M20 10 C20.5 6 22.5 3.5 25.5 2.5" stroke="#78350f" strokeWidth="2.2" fill="none" strokeLinecap="round" />
<ellipse cx="27" cy="6" rx="5.5" ry="2.6" fill="#22a447" transform="rotate(-28 27 6)" />
<path d="M20 11 C14 6.5 4.5 8.5 4.5 20 C4.5 30 11.5 37.5 20 36 C28.5 37.5 35.5 30 35.5 20 C35.5 8.5 26 6.5 20 11 Z" fill="url(#ap-grad)" stroke="#8f1020" strokeWidth="1.2" />
<ellipse cx="12.5" cy="17" rx="3" ry="5" fill="#fff" opacity=".32" />
</g>
</defs>
);
}
function AppleCell({ x, y, n }: { x: number; y: number; n: number }) {
return (
<g transform={`translate(${x} ${y})`}>
<use href="#ap-apple" />
<text x="20" y="29" textAnchor="middle" fontSize="17" fontWeight="900" fill="#fff" stroke="#6b0b16" strokeWidth="0.8" paintOrder="stroke">
{n}
</text>
</g>
);
}
/** Small stand-alone apple for the rules and options (own defs). */
function AppleIcon({ n, size = 34 }: { n: number; size?: number }) {
return (
<svg viewBox="0 0 40 40" width={size} height={size} aria-hidden style={{ verticalAlign: 'middle' }}>
<path d="M20 10 C20.5 6 22.5 3.5 25.5 2.5" stroke="#78350f" strokeWidth="2.2" fill="none" strokeLinecap="round" />
<ellipse cx="27" cy="6" rx="5.5" ry="2.6" fill="#22a447" transform="rotate(-28 27 6)" />
<path d="M20 11 C14 6.5 4.5 8.5 4.5 20 C4.5 30 11.5 37.5 20 36 C28.5 37.5 35.5 30 35.5 20 C35.5 8.5 26 6.5 20 11 Z" fill="#e11d2e" stroke="#8f1020" strokeWidth="1.2" />
<text x="20" y="29" textAnchor="middle" fontSize="17" fontWeight="900" fill="#fff">
{n}
</text>
</svg>
);
}
function useNarrow(): boolean {
const q = '(max-width: 640px)';
const [m, setM] = useState(() => typeof window !== 'undefined' && window.matchMedia(q).matches);
useEffect(() => {
const mq = window.matchMedia(q);
const on = () => setM(mq.matches);
mq.addEventListener('change', on);
return () => mq.removeEventListener('change', on);
}, []);
return m;
}
// ---------------------------------------------------------------- board
interface Pop {
key: number;
cells: { i: number; n: number }[];
}
function AppleBoard({ view: v, me, players, act }: BoardProps<AppleView>) {
const now = useServerNow(200);
const phone = useNarrow();
const [drag, setDrag] = useState<{ a: Cell; b: Cell } | null>(null);
const [cursor, setCursor] = useState<Cell>([0, 0]);
const [focused, setFocused] = useState(false);
const [gone, setGone] = useState<number[]>([]);
const [pops, setPops] = useState<Pop[]>([]);
const [flash, setFlash] = useState<{ key: number; ok: boolean; text: string } | null>(null);
const [announce, setAnnounce] = useState('');
const svgRef = useRef<SVGSVGElement>(null);
const dragRef = useRef(drag);
dragRef.current = drag;
const seq = useRef(0);
const mine = v.seats.find((s) => s.id === me) ?? null;
const canPlay = !!mine && mine.status === 'playing' && v.phase === 'playing' && !!v.cells && now < v.endsAt;
// My board as I see it: the server's, minus the apples I just cleared and the server has not confirmed yet.
const cells = useMemo(() => {
if (!v.cells) return null;
if (!gone.length) return v.cells;
const a = v.cells.split('');
for (const i of gone) a[i] = '0';
return a.join('');
}, [v.cells, gone]);
useEffect(() => {
setGone((g) => (g.length ? g.filter((i) => v.cells?.[i] !== '0' && v.cells !== null) : g));
}, [v.cells]);
// A refused select (too fast, time over): show the apples again.
useEffect(() => socket.subscribe((m) => m.t === 'reject' && setGone([])), []);
useEffect(() => {
if (!canPlay) setDrag(null);
}, [canPlay]);
useEffect(() => {
if (!pops.length) return;
const t = setTimeout(() => setPops((p) => p.slice(1)), 450);
return () => clearTimeout(t);
}, [pops]);
useEffect(() => {
if (!flash) return;
const t = setTimeout(() => setFlash(null), 900);
return () => clearTimeout(t);
}, [flash]);
const dR = phone ? COLS : ROWS;
const dC = phone ? ROWS : COLS;
const toDisp = (c: Cell): Cell => (phone ? [c[1], ROWS - 1 - c[0]] : c);
const toCanon = (dr: number, dc: number): Cell => (phone ? [ROWS - 1 - dc, dr] : [dr, dc]);
const cellAt = (e: { clientX: number; clientY: number }): Cell => {
const box = svgRef.current!.getBoundingClientRect();
const dc = clamp(Math.floor(((e.clientX - box.left) / box.width) * dC), 0, dC - 1);
const dr = clamp(Math.floor(((e.clientY - box.top) / box.height) * dR), 0, dR - 1);
return toCanon(dr, dc);
};
const sel = drag && cells ? inside(cells, rectOf(drag.a, drag.b)) : null;
const say = (t: string) => setAnnounce(t);
const finish = (a: Cell, b: Cell, fromKey: boolean) => {
if (!cells || !canPlay) return;
const rect = rectOf(a, b);
const { sum, idx } = inside(cells, rect);
if (idx.length === 0) {
if (fromKey) say('고른 칸에 사과가 없어요.');
return;
}
if (sum !== 10) {
if (idx.length >= 2 || fromKey) {
setFlash({ key: ++seq.current, ok: false, text: `합 ${sum} · 10이 아니에요` });
say(`합이 ${sum}이에요. 딱 10이 되게 골라 주세요.`);
}
return;
}
setGone((g) => [...g, ...idx]);
setPops((p) => [...p, { key: ++seq.current, cells: idx.map((i) => ({ i, n: cells.charCodeAt(i) - 48 })) }]);
setFlash({ key: ++seq.current, ok: true, text: `+${idx.length}` });
sounds.stone();
haptic(15);
act({ type: 'select', ...rect });
say(`사과 ${idx.length}개를 지웠어요.`);
};
const onDown = (e: ReactPointerEvent<SVGSVGElement>) => {
if (!canPlay || (e.pointerType === 'mouse' && e.button !== 0)) return;
e.preventDefault();
e.currentTarget.setPointerCapture?.(e.pointerId);
const c = cellAt(e);
setDrag({ a: c, b: c });
setCursor(c);
};
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
const d = dragRef.current;
if (!d) return;
const c = cellAt(e);
if (c[0] !== d.b[0] || c[1] !== d.b[1]) setDrag({ a: d.a, b: c });
};
const onUp = (e: ReactPointerEvent<SVGSVGElement>) => {
const d = dragRef.current;
if (!d) return;
const c = cellAt(e);
setDrag(null);
setCursor(c);
finish(d.a, c, false);
};
const describe = (c: Cell) => {
const [dr, dc] = toDisp(c);
const n = cells ? cells.charCodeAt(c[0] * COLS + c[1]) - 48 : 0;
return `${dr + 1}줄 ${dc + 1}칸, ${n > 0 ? `사과 ${n}` : '빈 칸'}`;
};
const onKey = (e: ReactKeyboardEvent<SVGSVGElement>) => {
const step: Record<string, Cell> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
const m = step[e.key];
if (m) {
e.preventDefault();
const [dr, dc] = toDisp(cursor);
const next = toCanon(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1));
setCursor(next);
if (drag) {
setDrag({ a: drag.a, b: next });
const s = cells ? inside(cells, rectOf(drag.a, next)).sum : 0;
say(`${describe(next)}. 고른 합 ${s}${s === 10 ? ', 지금 누르면 지워져요' : ''}`);
} else say(describe(next));
return;
}
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
if (!canPlay || e.repeat) return;
if (!drag) {
setDrag({ a: cursor, b: cursor });
say('시작점을 정했어요. 화살표로 끝점까지 옮긴 뒤 다시 눌러요.');
} else {
setDrag(null);
finish(drag.a, cursor, true);
}
return;
}
if (e.key === 'Escape' && drag) {
e.preventDefault();
setDrag(null);
say('고르기를 취소했어요.');
}
};
const left = Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt));
const countdown = v.phase === 'countdown' ? Math.max(1, Math.ceil((v.countdownEndsAt - now) / 1000)) : 0;
const sumState = !sel || sel.idx.length === 0 ? 'idle' : sel.sum === 10 ? 'ok' : sel.sum > 10 ? 'over' : 'under';
const others = ranked(v.seats);
// Selection rectangle in display coordinates.
let selBox: ReactNode = null;
if (drag) {
const [ar, ac] = toDisp(drag.a);
const [br, bc] = toDisp(drag.b);
const color = sumState === 'ok' ? '#16a34a' : sumState === 'over' ? '#dc2626' : '#2563eb';
const fill = sumState === 'ok' ? 'rgba(22,163,74,.28)' : sumState === 'over' ? 'rgba(220,38,38,.16)' : 'rgba(37,99,235,.16)';
selBox = (
<rect
x={Math.min(ac, bc) * S + 1.5}
y={Math.min(ar, br) * S + 1.5}
width={(Math.abs(ac - bc) + 1) * S - 3}
height={(Math.abs(ar - br) + 1) * S - 3}
rx={7}
fill={fill}
stroke={color}
strokeWidth={3}
pointerEvents="none"
/>
);
}
const [cr, cc] = toDisp(cursor);
return (
<div className="ap">
<style>{CSS}</style>
<div className="ap-top">
<span className={`ap-pill${v.phase === 'playing' && left <= 10_000 ? ' warn' : ''}`} role="timer" aria-label={`남은 시간 ${Math.floor(Math.ceil(left / 1000) / 60)}분 ${Math.ceil(left / 1000) % 60}초`}>
⏱ {clock(left)}
</span>
{mine && (
<span className="ap-pill" aria-label={`내 점수 사과 ${mine.score}개`}>
🍎 <b>{mine.score}</b>
</span>
)}
{mine && v.phase !== 'ended' && (
<span className="ap-pill sum" data-s={sumState} aria-hidden>
합 {sel && sel.idx.length ? sel.sum : '-'} / 10
</span>
)}
</div>
{v.seats.length > 1 && (
<ol className="ap-others" aria-label="점수">
{others.map((s) => (
<li key={s.id} data-me={s.id === me} data-out={s.status === 'left'} aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''} 사과 ${s.score}개${s.status === 'stuck' ? ', 더 지울 사과 없음' : s.status === 'left' ? ', 나감' : ''}`}>
<Avatar user={userOf(players, s.id)} size={20} />
<span>{s.id === me ? '나' : nick(players, s.id)}</span>
<b>{s.score}</b>
{s.status === 'stuck' && <span aria-hidden>✔</span>}
</li>
))}
</ol>
)}
<div className="ap-wrap" data-phone={phone}>
<svg
ref={svgRef}
className="ap-board"
data-off={!canPlay}
viewBox={`0 0 ${dC * S} ${dR * S}`}
role="application"
aria-roledescription="사과 판"
aria-label={
canPlay
? `사과 판 ${dR}줄 ${dC}칸. 화살표로 칸을 옮기고 스페이스나 Enter로 시작점과 끝점을 정해요. 지금 ${describe(cursor)}`
: '사과 판'
}
tabIndex={0}
onPointerDown={onDown}
onPointerMove={onMove}
onPointerUp={onUp}
onPointerCancel={() => setDrag(null)}
onKeyDown={onKey}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onContextMenu={(e) => e.preventDefault()}
>
<AppleDefs />
{cells &&
Array.from(cells, (ch, i) => {
const n = ch.charCodeAt(0) - 48;
if (n <= 0) return null;
const [dr, dc] = toDisp([Math.floor(i / COLS), i % COLS]);
return <AppleCell key={i} x={dc * S} y={dr * S} n={n} />;
})}
{pops.map((p) =>
p.cells.map(({ i, n }) => {
const [dr, dc] = toDisp([Math.floor(i / COLS), i % COLS]);
return (
<g key={`${p.key}-${i}`} className="ap-pop">
<AppleCell x={dc * S} y={dr * S} n={n} />
</g>
);
}),
)}
{selBox}
{focused && canPlay && <rect x={cc * S + 2} y={cr * S + 2} width={S - 4} height={S - 4} rx={8} fill="none" stroke="#f59e0b" strokeWidth={3} strokeDasharray="5 3" pointerEvents="none" />}
</svg>
{flash && (
<div key={flash.key} className={`ap-flash ${flash.ok ? 'ok' : 'bad'}`} aria-hidden>
{flash.text}
</div>
)}
{countdown > 0 && (
<div className="ap-over count" aria-hidden>
{countdown}
<small>합이 10이 되게 사과를 묶어요!</small>
</div>
)}
{mine && mine.status === 'stuck' && v.phase === 'playing' && (
<div className="ap-over note" role="status">
더 지울 수 있는 사과가 없어요! 사과 {mine.score}개 · 끝날 때까지 기다려요
</div>
)}
{mine && mine.status === 'left' && v.phase !== 'ended' && <div className="ap-over note">게임에서 나갔어요.</div>}
{!mine && v.phase !== 'ended' && <div className="ap-over note">관전 중이에요 · 위에서 점수를 볼 수 있어요</div>}
</div>
{!phone && mine && v.phase !== 'ended' && <p className="ap-keys">마우스로 드래그해서 합이 10이면 손을 떼요 · 키보드: 화살표 + 스페이스(시작점·끝점), Esc 취소</p>}
<p className="sr-only" aria-live="polite">
{announce}
</p>
</div>
);
}
// ---------------------------------------------------------------- side
function AppleSide({ view: v, me, players }: BoardProps<AppleView>) {
const rows = ranked(v.seats);
return (
<>
<style>{CSS}</style>
<div className="card stack" style={{ gap: 6, padding: 12 }}>
<strong>사과 게임{v.phase === 'ended' ? ' · 게임 끝' : ''}</strong>
<span className="small muted">17×10 판 · 제한 시간 {limitLabel(v.options.timeLimitSec)} · 모두 같은 판</span>
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
{rows.map((s) => (
<li
key={s.id}
className="row"
style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'left' ? 0.55 : 1 }}
aria-label={`${s.rank}등 ${nick(players, s.id)}${s.id === me ? '(나)' : ''}, 사과 ${s.score}개, ${s.clears}번 지움${s.status === 'stuck' ? ', 더 지울 사과 없음' : s.status === 'left' ? ', 나감' : ''}`}
>
<span aria-hidden style={{ width: 28, fontWeight: 800 }}>
{s.rank}등
</span>
<Avatar user={userOf(players, s.id)} size={24} />
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }} aria-hidden>
{nick(players, s.id)}
{s.id === me ? ' (나)' : ''}
{s.status === 'stuck' ? ' · 다 지움' : s.status === 'left' ? ' · 나감' : ''}
</span>
<strong style={{ fontVariantNumeric: 'tabular-nums' }} aria-hidden>
🍎 {s.score}
</strong>
</li>
))}
</ol>
</div>
{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.score}개 · {r.clears}번{r.left ? ' · 나감' : ''}
</span>
</span>
))}
<span className="small muted">{v.result.summary}</span>
</div>
)}
</>
);
}
// ---------------------------------------------------------------- status
function isMyTurn(v: AppleView, me: string | null): boolean {
return !!me && v.phase === 'playing' && v.seats.some((s) => s.id === me && s.status === 'playing');
}
function statusText(v: AppleView, me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요';
if (v.phase === 'countdown') return '곧 시작해요! 합이 10이 되게 사과를 드래그해요';
const mine = v.seats.find((s) => s.id === me);
if (!mine) {
const top = ranked(v.seats)[0];
return top && top.score > 0 ? `${nick(players, top.id)}님이 사과 ${top.score}개로 앞서요` : '모두 같은 판을 풀고 있어요';
}
if (mine.status === 'left') return '게임에서 나갔어요';
if (mine.status === 'stuck') return `더 지울 사과가 없어요 · 사과 ${mine.score}개 · 끝날 때까지 기다려요`;
return `사과 ${mine.score}개 지웠어요 · 합이 10이 되게 드래그!`;
}
// ---------------------------------------------------------------- options
function Seg<T extends string | number | boolean>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
return (
<div className="segmented" role="group" aria-label={label}>
{options.map(([k, l]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
function Options({ value: o, onChange }: OptionsProps<AppleOptions>) {
return (
<div className="stack" style={{ gap: 16 }}>
<div className="stack" style={{ gap: 6 }}>
<strong>제한 시간</strong>
<Seg
label="제한 시간"
value={o.timeLimitSec}
options={[
[60, '1분'],
[120, '2분'],
[180, '3분'],
]}
onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec })}
/>
<span className="small muted">원래 게임은 2분이에요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.</span>
</div>
</div>
);
}
function optionsSummary(o: AppleOptions): string {
return `제한 시간 ${limitLabel(o.timeLimitSec)} · 17×10 판`;
}
// ---------------------------------------------------------------- rules
function Rules({ options }: { options?: AppleOptions }) {
const limit = limitLabel(options?.timeLimitSec ?? 120);
return (
<div className="stack">
<p>
가로 17칸, 세로 10줄 판에 1부터 9까지 숫자가 적힌 사과 170개가 가득 놓여 있어요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요.
</p>
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
<AppleIcon n={3} />
<AppleIcon n={4} />
<AppleIcon n={3} />
<span>= 10 → 사과 3개가 사라지고 3점!</span>
</div>
<p>
사과들을 <strong>직사각형으로 드래그</strong>해서 그 안의 숫자 합이 <strong>딱 10</strong>이면 손을 뗐을 때 사과가 사라지고, 사라진 개수만큼 점수를 얻어요. 합이 10이 아니면 아무 일도
일어나지 않고 벌칙도 없어요. 지운 자리는 빈 칸이 되고 빈 칸은 합에 들어가지 않아서, 사이가 비면 멀리 있는 사과끼리도 묶을 수 있어요.
</p>
<p>
제한 시간은 {limit}이에요. 시간이 끝나면 사과를 가장 많이 지운 사람이 이기고, 개수가 같으면 같은 순위예요. 모두 더 지울 수 있는 묶음이 없으면 조금 일찍 끝나요. 혼자서도 할 수 있어요.
</p>
<p>
휴대폰에서는 판을 세로로 돌려서 보여 줘요. 키보드로는 화살표로 칸을 옮기고 <strong>스페이스</strong>(또는 Enter)로 시작점, 한 번 더 눌러 끝점을 정해요. <strong>Esc</strong>는 취소예요.
</p>
</div>
);
}
const ui: GameUI<AppleView, AppleOptions> = {
Board: AppleBoard,
Side: AppleSide,
statusText,
isMyTurn,
Options,
optionsSummary,
Rules,
quickStart,
helpNow,
};
export default ui;

View File

@@ -0,0 +1,81 @@
/** 사과 게임 30초 규칙 요약 (docs/07 §5). Simple redraws of the board apples. */
import type { ReactNode } from 'react';
import type { QuickCard } from '../types';
/** One apple with its number, centred at (x, y), about 26 units wide. */
function Apple({ x, y, n, dim = false }: { x: number; y: number; n: number; dim?: boolean }) {
return (
<g transform={`translate(${x} ${y})`} opacity={dim ? 0.3 : 1}>
<path d="M0 -11 C1 -15 3 -17 5 -18" stroke="#78350f" strokeWidth={2} fill="none" strokeLinecap="round" />
<ellipse cx={5} cy={-15} rx={4.5} ry={2.2} fill="#16a34a" transform="rotate(-25 5 -15)" />
<circle cx={0} cy={2} r={12} fill="#dc2626" stroke="#991b1b" strokeWidth={1.5} />
<text x={0} y={7.5} textAnchor="middle" fontSize={15} fontWeight={900} fill="#fff">
{n}
</text>
</g>
);
}
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="#fef3c7" />
{children}
</svg>
);
}
const ROW1 = [3, 7, 5, 2, 8, 1, 6];
const ROW2 = [4, 1, 5, 9, 2, 2, 6];
const ROW3 = [6, 2, 8, 1, 3, 9, 4];
function Grid({ gone = [] as number[] }) {
return (
<>
{[ROW1, ROW2, ROW3].map((row, r) =>
row.map((n, c) => <Apple key={`${r}-${c}`} x={30 + c * 30} y={36 + r * 38} n={n} dim={gone.includes(r * 7 + c)} />),
)}
</>
);
}
export const quickStart: QuickCard[] = [
{
pic: (
<Frame>
<Grid />
</Frame>
),
alt: '숫자 1부터 9가 적힌 빨간 사과가 줄지어 놓인 판이에요',
title: '모두 같은 판을 풀어요',
text: '숫자가 적힌 사과 판이 나와요. 모두 똑같은 판을 각자 자기 화면에서 동시에 풀어요.',
},
{
pic: (
<Frame>
<Grid />
<rect x={14} y={18} width={62} height={36} rx={6} fill="rgba(22,163,74,.25)" stroke="#16a34a" strokeWidth={3} />
<text x={200} y={140} textAnchor="middle" fontSize={16} fontWeight={900} fill="#15803d">
3+7=10!
</text>
</Frame>
),
alt: '3과 7이 적힌 사과 두 개를 초록 네모로 묶은 모습이에요. 합이 10이에요',
title: '합이 10이면 사라져요',
text: '사과를 직사각형으로 드래그해서 숫자 합이 딱 10이면 손을 떼요. 사과가 사라지고 개수만큼 점수예요.',
},
{
pic: (
<Frame>
<Grid gone={[0, 1, 7, 14, 2, 9]} />
<rect x={150} y={8} width={82} height={26} rx={13} fill="#1f2937" />
<text x={191} y={26} textAnchor="middle" fontSize={15} fontWeight={800} fill="#fff">
⏱ 1:42
</text>
</Frame>
),
alt: '몇 개의 사과가 지워져 흐려졌고, 오른쪽 위에 남은 시간 1분 42초가 보여요',
title: '2분 동안 많이 지우기',
text: '빈 칸은 합에 안 들어가요. 시간이 끝났을 때 사과를 가장 많이 지운 사람이 이겨요.',
},
];

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(26);
expect(IDS).toHaveLength(27);
for (const id of IDS) {
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
expect(src, id).toMatch(/\bquickStart,/);

View File

@@ -28,6 +28,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
dobble: () => import('./dobble'),
catchmind: () => import('./catchmind'),
mafia: () => import('./mafia'),
apple: () => import('./apple'),
};
const cache = new Map<string, GameUI>();

View File

@@ -25,6 +25,7 @@ export const GAME_ICON: Record<string, string> = {
dobble: '👀',
catchmind: '🖍️',
mafia: '🌙',
apple: '🍎',
};
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
@@ -34,5 +35,5 @@ export const UPCOMING: string[] = [];
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
{ key: 'board', label: '판·주사위', ids: ['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas'] },
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'one-card', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'mahjong', 'rummikub', 'davinci-code'] },
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia'] },
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'apple'] },
];