새 게임 5개(같은 판 경주): 지뢰찾기, 사천성, 솔리테어, 스도쿠, 네모네모 로직
- 공통 틀 race: 같은 시드 판을 모두 각자 동시에, 3초 카운트다운, 제한 시간/무제한, 포기, 다 푼 시간 → 푼 만큼 순위, live 컴퓨터 - 지뢰찾기: 초급·중급·고급, 모두에게 같은 곳이 열린 채 시작, 깃발·한꺼번에 열기, 휴대폰 길게 누르기·깃발 모드 - 사천성: 마작패 72·112·136장, 두 번 이하로 꺾이는 선, 항상 풀리는 배치, 막히면 자동 섞기, 힌트 - 솔리테어: 클론다이크(1장·3장)·프리셀·스파이더(1·2·4무늬), 되돌리기, 자동 정리 - 스도쿠: 답이 하나인 문제 생성기(쉬움·보통·어려움), 메모, 겹침 표시, 힌트 - 네모네모 로직: 그림 37개(5×5·10×10·15×15, 모두 줄 논리만으로 풀림), 드래그 칠하기·X 표시, 풀면 그림과 이름 - 게임 46개, 컴퓨터 상대 42개, 게임 고르기에 혼자·퍼즐 탭 (아발론·모노레일은 아직 공개 전이라 이 배포에서 뺌; 작업 갈래 codex/owner/grp_discord_joke-app 2773f5c..에서 옮김) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
|
||||
const IDS = Object.keys(GAME_UI);
|
||||
|
||||
test('모든 게임에 도움말이 있어요', () => {
|
||||
expect(IDS).toHaveLength(41);
|
||||
expect(IDS).toHaveLength(46);
|
||||
for (const id of IDS) {
|
||||
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
|
||||
expect(src, id).toMatch(/\bquickStart,/);
|
||||
|
||||
60
apps/web/src/games/minesweeper/art.tsx
Normal file
60
apps/web/src/games/minesweeper/art.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
/** 지뢰찾기 cell pictures (SVG, no image files). */
|
||||
|
||||
/** SVG units per cell. */
|
||||
export const S = 32;
|
||||
const NUM_COLOR = ['', '#1d4ed8', '#15803d', '#dc2626', '#1e3a8a', '#7f1d1d', '#0f766e', '#111827', '#6b7280'];
|
||||
|
||||
function Flag({ x, y, wrong }: { x: number; y: number; wrong?: boolean }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`} pointerEvents="none">
|
||||
<path d="M12 7 V25" stroke="#111827" strokeWidth={2.2} strokeLinecap="round" />
|
||||
<path d="M12 7 L24 11.5 L12 16 Z" fill="#dc2626" />
|
||||
<path d="M8 25 H18" stroke="#111827" strokeWidth={2.4} strokeLinecap="round" />
|
||||
{wrong && <path d="M5 5 L27 27 M27 5 L5 27" stroke="#111827" strokeWidth={2.6} strokeLinecap="round" />}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function Mine({ x, y }: { x: number; y: number }) {
|
||||
return (
|
||||
<g transform={`translate(${x} ${y})`} pointerEvents="none">
|
||||
<path d="M16 6 V26 M6 16 H26 M9 9 L23 23 M23 9 L9 23" stroke="#111827" strokeWidth={2.2} strokeLinecap="round" />
|
||||
<circle cx={16} cy={16} r={7.5} fill="#111827" />
|
||||
<circle cx={13.5} cy={13.5} r={2} fill="#fff" opacity={0.8} />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
/** Small stand-alone pictures for rules and help cards. */
|
||||
export function MiniCell({ ch, size = 30 }: { ch: string; size?: number }) {
|
||||
return (
|
||||
<svg viewBox="0 0 32 32" width={size} height={size} aria-hidden style={{ verticalAlign: 'middle' }}>
|
||||
<CellArt ch={ch} x={0} y={0} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function CellArt({ ch, x, y, cls, i }: { ch: string; x: number; y: number; cls?: string; i?: number }) {
|
||||
const closed = ch === '#' || ch === 'F' || ch === 'x';
|
||||
return (
|
||||
<g className={cls} data-i={i} data-ch={i === undefined ? undefined : ch}>
|
||||
{closed ? (
|
||||
<>
|
||||
<rect x={x + 0.5} y={y + 0.5} width={S - 1} height={S - 1} rx={4} fill="#e5e7eb" />
|
||||
<path d={`M${x + 2} ${y + S - 3} V${y + 3} Q${x + 2} ${y + 2} ${x + 3} ${y + 2} H${x + S - 3}`} stroke="#fff" strokeWidth={2} fill="none" />
|
||||
<path d={`M${x + 3} ${y + S - 2} H${x + S - 3} Q${x + S - 2} ${y + S - 2} ${x + S - 2} ${y + S - 3} V${y + 3}`} stroke="#9ca3af" strokeWidth={2} fill="none" />
|
||||
</>
|
||||
) : (
|
||||
<rect x={x + 0.5} y={y + 0.5} width={S - 1} height={S - 1} rx={3} fill={ch === '!' ? '#ef4444' : '#f8fafc'} />
|
||||
)}
|
||||
{(ch === 'F' || ch === 'x') && <Flag x={x} y={y} wrong={ch === 'x'} />}
|
||||
{(ch === '*' || ch === '!') && <Mine x={x} y={y} />}
|
||||
{ch >= '1' && ch <= '8' && (
|
||||
<text x={x + S / 2} y={y + 23} textAnchor="middle" fontSize={20} fontWeight={900} fill={NUM_COLOR[Number(ch)]} pointerEvents="none">
|
||||
{ch}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
17
apps/web/src/games/minesweeper/help.ts
Normal file
17
apps/web/src/games/minesweeper/help.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
/** 지뢰찾기 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { MinesweeperView } from '@bg/games/minesweeper';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW = [
|
||||
'연 칸의 숫자는 그 칸을 둘러싼 8칸에 있는 지뢰 수예요. 지뢰가 없는 칸을 모두 열면 다 푼 거예요.',
|
||||
'지뢰가 확실한 칸에는 깃발을 꽂아요(PC 오른쪽 클릭, 휴대폰 길게 누르기). 깃발 수가 숫자와 같아진 숫자 칸을 누르면 주변을 한꺼번에 열어요.',
|
||||
'지뢰를 밟으면 그 판은 끝이에요.',
|
||||
'키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 열기, F로 깃발이에요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: MinesweeperView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '지뢰를 밟았어요.');
|
||||
if (v.board && v.phase === 'playing') return `${lines}\n남은 지뢰(전체 지뢰 − 내 깃발)는 ${v.board.mines - v.board.flags}개예요.`;
|
||||
return lines;
|
||||
}
|
||||
321
apps/web/src/games/minesweeper/index.tsx
Normal file
321
apps/web/src/games/minesweeper/index.tsx
Normal file
@@ -0,0 +1,321 @@
|
||||
/** 지뢰찾기 화면 (docs/games/minesweeper.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { LEVELS, type Level, type MinesweeperOptions, type MinesweeperView } from '@bg/games/minesweeper';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { CellArt, MiniCell, S } from './art';
|
||||
|
||||
const FAIL = '지뢰를 밟았어요!';
|
||||
const LONG_PRESS_MS = 420;
|
||||
|
||||
type Cell = [number, number];
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
|
||||
const CSS = `
|
||||
.ms-board { display: block; width: 100%; height: auto; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation;
|
||||
border-radius: 10px; background: #9ca3af; box-shadow: var(--shadow); outline: none; cursor: pointer; }
|
||||
.ms-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ms-board[data-off='true'] { cursor: default; }
|
||||
.ms-new { animation: ms-in .28s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.ms-boom { animation: ms-boom .6s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
@keyframes ms-in { from { opacity: 0; transform: scale(.6); } }
|
||||
@keyframes ms-boom { 0% { transform: scale(.4); } 40% { transform: scale(1.3); } 100% { transform: scale(1); } }
|
||||
@media (prefers-reduced-motion: reduce) { .ms-new, .ms-boom { animation: none; } }
|
||||
`;
|
||||
|
||||
const describeCh = (ch: string) =>
|
||||
ch === '#' ? '닫힌 칸' : ch === 'F' ? '깃발' : ch === '0' ? '빈 칸' : ch === '*' ? '지뢰' : ch === '!' ? '터진 지뢰' : ch === 'x' ? '잘못 꽂은 깃발' : `숫자 ${ch}`;
|
||||
|
||||
function MinesBoard({ view: v, me, players, act }: BoardProps<MinesweeperView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [flagMode, setFlagMode] = useState(false);
|
||||
const [cursor, setCursor] = useState(0);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [fresh, setFresh] = useState<Set<number>>(new Set());
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const press = useRef<{ i: number; x: number; y: number; timer: ReturnType<typeof setTimeout> | null; long: boolean; button: number } | null>(null);
|
||||
const prev = useRef<string | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
// Newly opened cells pop in; sounds for what changed.
|
||||
useEffect(() => {
|
||||
const cur = b?.cells ?? null;
|
||||
const was = prev.current;
|
||||
prev.current = cur;
|
||||
if (!cur || !was || was.length !== cur.length) return;
|
||||
const added = new Set<number>();
|
||||
let flagged = 0;
|
||||
for (let i = 0; i < cur.length; i++) {
|
||||
if (was[i] === '#' && cur[i]! >= '0' && cur[i]! <= '8') added.add(i);
|
||||
if (was[i] !== cur[i] && (cur[i] === 'F' || was[i] === 'F') && cur[i] !== '*') flagged++;
|
||||
}
|
||||
if (cur.includes('!') && !was.includes('!')) {
|
||||
noise(500, 0.2, 0, 'lowpass', 400, 0.7);
|
||||
haptic([30, 40, 60]);
|
||||
} else if (added.size > 8) sfx.whoosh();
|
||||
else if (added.size) tone(900, 40, 'triangle', 0.1);
|
||||
else if (flagged === 1) tone(640, 50, 'square', 0.05);
|
||||
if (added.size) {
|
||||
setFresh(added);
|
||||
const t = setTimeout(() => setFresh(new Set()), fxMs(320));
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [b?.cells]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="숫자를 보고 지뢰를 피해 모든 칸을 열어요!" />
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const turn = phone && b.cols > b.rows;
|
||||
const dR = turn ? b.cols : b.rows;
|
||||
const dC = turn ? b.rows : b.cols;
|
||||
const toDisp = (i: number): Cell => {
|
||||
const r = Math.floor(i / b.cols);
|
||||
const c = i % b.cols;
|
||||
return turn ? [c, b.rows - 1 - r] : [r, c];
|
||||
};
|
||||
const toIndex = (dr: number, dc: number) => (turn ? (b.rows - 1 - dc) * b.cols + dr : dr * b.cols + dc);
|
||||
const cellAt = (e: { clientX: number; clientY: number }) => {
|
||||
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 toIndex(dr, dc);
|
||||
};
|
||||
|
||||
const describe = (i: number) => {
|
||||
const [dr, dc] = toDisp(i);
|
||||
return `${dr + 1}줄 ${dc + 1}칸, ${describeCh(b.cells[i]!)}`;
|
||||
};
|
||||
/** Primary action on a cell: open a closed one, open around a number, or flag (깃발 mode / right click / long press). */
|
||||
const hit = (i: number, flag: boolean) => {
|
||||
if (!playing) return;
|
||||
const ch = b.cells[i]!;
|
||||
if (flag) {
|
||||
if (ch === '#' || ch === 'F') {
|
||||
act({ type: 'flag', i });
|
||||
haptic(10);
|
||||
setAnnounce(ch === 'F' ? '깃발을 치웠어요.' : '깃발을 꽂았어요.');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (ch === '#') act({ type: 'open', i });
|
||||
else if (ch >= '1' && ch <= '8') {
|
||||
// A number opens the cells around it once its flags match.
|
||||
let flags = 0;
|
||||
let closed = 0;
|
||||
const r = Math.floor(i / b.cols);
|
||||
const c = i % b.cols;
|
||||
for (let y = r - 1; y <= r + 1; y++)
|
||||
for (let x = c - 1; x <= c + 1; x++) {
|
||||
if (y < 0 || x < 0 || y >= b.rows || x >= b.cols || (y === r && x === c)) continue;
|
||||
const k = b.cells[y * b.cols + x];
|
||||
if (k === 'F') flags++;
|
||||
else if (k === '#') closed++;
|
||||
}
|
||||
if (closed && flags === Number(ch)) act({ type: 'chord', i });
|
||||
else if (closed) setAnnounce(`주변 깃발이 ${flags}개예요. ${ch}개를 꽂아야 한꺼번에 열 수 있어요.`);
|
||||
} else if (ch === 'F') setAnnounce('깃발을 꽂은 칸이에요. 깃발 모드나 오른쪽 클릭으로 치워요.');
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!playing) return;
|
||||
const i = cellAt(e);
|
||||
setCursor(i);
|
||||
const p = { i, x: e.clientX, y: e.clientY, timer: null as ReturnType<typeof setTimeout> | null, long: false, button: e.button };
|
||||
if (e.pointerType !== 'mouse')
|
||||
p.timer = setTimeout(() => {
|
||||
p.long = true;
|
||||
hit(p.i, !flagMode);
|
||||
}, LONG_PRESS_MS);
|
||||
press.current = p;
|
||||
};
|
||||
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const p = press.current;
|
||||
if (p && Math.hypot(e.clientX - p.x, e.clientY - p.y) > 10) {
|
||||
if (p.timer) clearTimeout(p.timer);
|
||||
press.current = null; // scrolling, not a tap
|
||||
}
|
||||
};
|
||||
const onUp = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
const p = press.current;
|
||||
press.current = null;
|
||||
if (!p) return;
|
||||
if (p.timer) clearTimeout(p.timer);
|
||||
if (p.long) return;
|
||||
if (cellAt(e) !== p.i) return;
|
||||
hit(p.i, p.button === 2 || flagMode);
|
||||
};
|
||||
|
||||
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 = toIndex(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1));
|
||||
setCursor(next);
|
||||
setAnnounce(describe(next));
|
||||
return;
|
||||
}
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) hit(cursor, flagMode);
|
||||
} else if (e.key === 'f' || e.key === 'F' || e.key === 'ㄹ') {
|
||||
e.preventDefault();
|
||||
hit(cursor, true);
|
||||
}
|
||||
};
|
||||
|
||||
const [cr, cc] = toDisp(cursor);
|
||||
const wrapStyle: CSSProperties = phone
|
||||
? { width: '100%' }
|
||||
: { width: `min(100%, ${dC * 56}px, calc((var(--play-h, 100vh) - 170px) * ${dC / dR}))`, minWidth: Math.min(280, dC * 22) };
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill" aria-label={`남은 지뢰 ${b.mines - b.flags}개`}>
|
||||
💣 <b>{b.mines - b.flags}</b>
|
||||
</span>
|
||||
{mine && v.phase === 'playing' && (
|
||||
<button type="button" className="rc-pill" aria-pressed={flagMode} onClick={() => setFlagMode((f) => !f)} aria-label="깃발 모드">
|
||||
{flagMode ? '🚩 깃발 꽂기' : '⛏ 칸 열기'}
|
||||
</button>
|
||||
)}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap" style={wrapStyle}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="ms-board"
|
||||
data-off={!playing}
|
||||
viewBox={`0 0 ${dC * S} ${dR * S}`}
|
||||
role="application"
|
||||
aria-roledescription="지뢰 판"
|
||||
aria-label={playing ? `지뢰 판 ${dR}줄 ${dC}칸. 화살표로 옮기고 스페이스로 열기, F로 깃발. 지금 ${describe(cursor)}` : '지뢰 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => {
|
||||
if (press.current?.timer) clearTimeout(press.current.timer);
|
||||
press.current = null;
|
||||
}}
|
||||
onKeyDown={onKey}
|
||||
onFocus={() => setFocused(true)}
|
||||
onBlur={() => setFocused(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{Array.from(b.cells, (ch, i) => {
|
||||
const [dr, dc] = toDisp(i);
|
||||
return <CellArt key={i} i={i} ch={ch} x={dc * S} y={dr * S} cls={ch === '!' ? 'ms-boom' : fresh.has(i) ? 'ms-new' : undefined} />;
|
||||
})}
|
||||
{focused && playing && <rect x={cc * S + 1.5} y={cr * S + 1.5} width={S - 3} height={S - 3} rx={5} fill="none" stroke="#f59e0b" strokeWidth={3} pointerEvents="none" />}
|
||||
</svg>
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">왼쪽 클릭: 열기(숫자는 주변 한꺼번에) · 오른쪽 클릭: 깃발 · 키보드: 화살표 + 스페이스, F 깃발</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">누르기: {flagMode ? '깃발' : '열기'} · 길게 누르기: {flagMode ? '열기' : '깃발'} · 숫자를 누르면 주변을 한꺼번에 열어요</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const levelInfo = (l: Level) => `${LEVELS[l].name} ${LEVELS[l].rows}×${LEVELS[l].cols} · 지뢰 ${LEVELS[l].mines}`;
|
||||
|
||||
function MinesSide(props: BoardProps<MinesweeperView>) {
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="지뢰찾기" info={levelInfo(props.view.options.level)} />;
|
||||
}
|
||||
|
||||
function statusText(v: MinesweeperView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자를 보고 지뢰를 피해 칸을 열어요', playing: '숫자는 주변 8칸의 지뢰 수예요 · 지뢰 없는 칸을 모두 열어요', failed: FAIL });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<MinesweeperOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>난이도</strong>
|
||||
<Seg
|
||||
label="난이도"
|
||||
value={o.level}
|
||||
options={(Object.keys(LEVELS) as Level[]).map((l) => [l, LEVELS[l].name])}
|
||||
onChange={(level) => onChange({ ...o, level })}
|
||||
/>
|
||||
<span className="small muted">{levelInfo(o.level)}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[180, 300, 600, 1200]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as MinesweeperOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: MinesweeperOptions): string {
|
||||
return `${levelInfo(o.level)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: MinesweeperOptions }) {
|
||||
const level = options?.level ?? 'beginner';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
판 아래에 지뢰가 숨어 있어요. 지뢰가 없는 칸을 <strong>모두 열면</strong> 이겨요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
|
||||
<MiniCell ch="1" />
|
||||
<MiniCell ch="2" />
|
||||
<MiniCell ch="3" />
|
||||
<span>연 칸의 숫자 = 그 칸을 둘러싼 8칸에 있는 지뢰 수</span>
|
||||
</div>
|
||||
<p>
|
||||
시작할 때 지뢰가 없는 한 곳이 모두에게 똑같이 열려 있어요. 숫자를 보고 지뢰가 확실한 칸에는 <MiniCell ch="F" size={22} /> 깃발을 꽂고, 안전한 칸을 열어요. 주변이 비어 있는 칸(0)을 열면 이어진 칸이
|
||||
한꺼번에 열려요. 깃발 수가 숫자와 같아진 숫자 칸을 누르면 남은 주변 칸을 한꺼번에 열어요(깃발이 틀렸으면 지뢰가 터져요).
|
||||
</p>
|
||||
<p>
|
||||
<strong>지뢰를 밟으면</strong> 그 판은 끝이에요. 여럿이면 가장 먼저 다 연 사람이 이기고, 아무도 못 열면 연 칸이 많은 사람이 이겨요(지뢰를 밟은 사람도 그때까지 연 칸으로 셈). 제한 시간은{' '}
|
||||
{limitLabel(options ? options.timeLimitSec : 600)}이고, 지금 난이도는 {levelInfo(level)}이에요.
|
||||
</p>
|
||||
<p>PC: 왼쪽 클릭 열기, 오른쪽 클릭 깃발. 휴대폰: 누르면 열기, 길게 누르면 깃발(위의 [⛏ 칸 열기] 버튼으로 바꿀 수 있어요). 키보드: 화살표로 옮기고 스페이스로 열기, F로 깃발.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<MinesweeperView, MinesweeperOptions> = {
|
||||
Board: MinesBoard,
|
||||
Side: MinesSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
38
apps/web/src/games/minesweeper/quick.tsx
Normal file
38
apps/web/src/games/minesweeper/quick.tsx
Normal file
@@ -0,0 +1,38 @@
|
||||
/** 지뢰찾기 30초 규칙 요약 (docs/07 §5). Small boards drawn with the game's own cells. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniCell } from './art';
|
||||
|
||||
function Grid({ rows }: { rows: string[] }) {
|
||||
return (
|
||||
<svg viewBox={`0 0 ${rows[0]!.length * 32} ${rows.length * 32}`} width={rows[0]!.length * 30} height={rows.length * 30} aria-hidden>
|
||||
{rows.flatMap((row, r) =>
|
||||
[...row].map((ch, c) => (
|
||||
<svg key={`${r}-${c}`} x={c * 32} y={r * 32} width={32} height={32} viewBox="0 0 32 32">
|
||||
<MiniCell ch={ch} size={32} />
|
||||
</svg>
|
||||
)),
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <Grid rows={['1##', '1#1', '110']} />,
|
||||
alt: '닫힌 칸 사이에 숫자 1이 적힌 연 칸들이 있어요',
|
||||
title: '숫자 = 주변 지뢰 수',
|
||||
text: '연 칸의 숫자는 둘러싼 8칸에 있는 지뢰 수예요. 모두 똑같은 판을 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: <Grid rows={['1F#', '1#1', '110']} />,
|
||||
alt: '지뢰가 확실한 칸에 빨간 깃발을 꽂은 모습이에요',
|
||||
title: '지뢰에는 깃발',
|
||||
text: '지뢰가 확실한 칸에 깃발을 꽂아요(오른쪽 클릭, 휴대폰은 길게 누르기). 지뢰를 밟으면 끝이에요.',
|
||||
},
|
||||
{
|
||||
pic: <Grid rows={['1F1', '111', '110']} />,
|
||||
alt: '지뢰 칸만 남기고 모든 칸이 열렸어요',
|
||||
title: '모든 칸을 열면 승리',
|
||||
text: '지뢰 없는 칸을 모두 열면 다 푼 거예요. 여럿이면 가장 먼저 다 연 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
53
apps/web/src/games/nonogram/art.tsx
Normal file
53
apps/web/src/games/nonogram/art.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
/** 네모네모 로직 small pictures for the rules and the 30-second cards (SVG, no image files). */
|
||||
|
||||
/** Run lengths of the '#' cells; an empty line is [0]. */
|
||||
export function runsOf(line: string): number[] {
|
||||
const out = line.split(/[^#]+/).filter(Boolean).map((s) => s.length);
|
||||
return out.length ? out : [0];
|
||||
}
|
||||
|
||||
/**
|
||||
* A small puzzle: clues from `answer`, cells from `marks` ('#' filled, 'x' X, '.' empty; default = the answer).
|
||||
* `color` paints the filled cells (a solved picture).
|
||||
*/
|
||||
export function MiniNono({ answer, marks = answer, color, cell = 22 }: { answer: string[]; marks?: string[]; color?: string; cell?: number }) {
|
||||
const n = answer.length;
|
||||
const S = 20;
|
||||
const rows = answer.map(runsOf);
|
||||
const cols = Array.from({ length: n }, (_, c) => runsOf(answer.map((r) => r[c]).join('')));
|
||||
const left = Math.max(...rows.map((r) => r.length)) * 12 + 6;
|
||||
const top = Math.max(...cols.map((c) => c.length)) * 13 + 4;
|
||||
const w = left + n * S;
|
||||
const h = top + n * S;
|
||||
return (
|
||||
<svg viewBox={`0 0 ${w} ${h}`} width={(w * cell) / S} height={(h * cell) / S} aria-hidden style={{ maxWidth: '100%', height: 'auto' }}>
|
||||
{cols.map((clue, c) =>
|
||||
clue.map((x, j) => (
|
||||
<text key={`c${c}-${j}`} x={left + c * S + S / 2} y={top - 4 - (clue.length - 1 - j) * 13} textAnchor="middle" fontSize={12} fontWeight={800} fill="var(--text)">
|
||||
{x}
|
||||
</text>
|
||||
)),
|
||||
)}
|
||||
{rows.map((clue, r) =>
|
||||
clue.map((x, j) => (
|
||||
<text key={`r${r}-${j}`} x={left - 6 - (clue.length - 1 - j) * 12} y={top + r * S + 14.5} textAnchor="end" fontSize={12} fontWeight={800} fill="var(--text)">
|
||||
{x}
|
||||
</text>
|
||||
)),
|
||||
)}
|
||||
{marks.flatMap((row, r) =>
|
||||
[...row].map((ch, c) => {
|
||||
const x = left + c * S;
|
||||
const y = top + r * S;
|
||||
return (
|
||||
<g key={`${r}-${c}`}>
|
||||
<rect x={x} y={y} width={S} height={S} fill={ch === '#' ? (color ?? 'var(--text)') : 'var(--surface)'} stroke="var(--border)" strokeWidth={1} />
|
||||
{ch === 'x' && <path d={`M${x + 6} ${y + 6} L${x + S - 6} ${y + S - 6} M${x + S - 6} ${y + 6} L${x + 6} ${y + S - 6}`} stroke="var(--text-sub)" strokeWidth={1.8} strokeLinecap="round" />}
|
||||
</g>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
<rect x={left} y={top} width={n * S} height={n * S} fill="none" stroke="var(--text-sub)" strokeWidth={1.5} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
18
apps/web/src/games/nonogram/help.ts
Normal file
18
apps/web/src/games/nonogram/help.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
/** 네모네모 로직 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { NonogramView } from '@bg/games/nonogram';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW = [
|
||||
'줄 옆의 숫자는 그 줄에서 이어서 칠할 칸 수예요. 숫자가 여러 개면 그 순서대로, 덩어리 사이는 한 칸 이상 띄어요.',
|
||||
'모든 가로줄과 세로줄이 숫자와 맞게 칠하면 그림이 나오고 다 푼 거예요. 칠한 칸이 맞는지는 알려 주지 않아요.',
|
||||
'비어야 할 칸에는 ✕를 해 두면 헷갈리지 않아요(PC 오른쪽 클릭, 휴대폰은 [✕ 표시]로 바꿔서). 끌면 한 줄을 한 번에 칠해요.',
|
||||
'키보드: 화살표로 칸을 옮기고 스페이스(또는 Enter)로 칠하기, X로 ✕ 표시예요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: NonogramView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '');
|
||||
if (v.board && v.phase === 'playing' && v.options.hints && v.seats.some((s) => s.id === me && s.status === 'playing'))
|
||||
return `${lines}\n막히면 [💡 힌트]로 틀렸거나 모르는 칸 하나를 바르게 고칠 수 있어요(쓴 횟수는 결과에 나와요). 지금까지 ${v.board.hints}번 썼어요.`;
|
||||
return lines;
|
||||
}
|
||||
412
apps/web/src/games/nonogram/index.tsx
Normal file
412
apps/web/src/games/nonogram/index.tsx
Normal file
@@ -0,0 +1,412 @@
|
||||
/** 네모네모 로직 화면 (docs/games/nonogram.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import type { MarkValue, NonogramOptions, NonogramSize, NonogramView } from '@bg/games/nonogram';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { MiniNono, runsOf } from './art';
|
||||
|
||||
/** SVG units per cell. */
|
||||
const S = 20;
|
||||
const SIZE_NAME: Record<NonogramSize, string> = { 5: '쉬움', 10: '보통', 15: '어려움' };
|
||||
const sizeInfo = (n: NonogramSize) => `${n}×${n} ${SIZE_NAME[n]}`;
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
const MARK_WORD: Record<string, string> = { '0': '빈 칸', '1': '칠한 칸', '2': '✕ 표시' };
|
||||
|
||||
const CSS = `
|
||||
.ng-board { display: block; width: 100%; height: auto; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: none;
|
||||
border-radius: 10px; background: var(--surface); box-shadow: var(--shadow); outline: none; cursor: crosshair; }
|
||||
.ng-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ng-board[data-off='true'] { cursor: default; }
|
||||
.ng-clue { font-weight: 800; fill: var(--text); transition: opacity .3s; }
|
||||
.ng-clue[data-ok='true'] { opacity: .3; }
|
||||
.ng-new { animation: ng-in .22s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.ng-color { animation: ng-color .7s ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.ng-hint { animation: ng-hint 1.2s ease-out 2 both; transform-box: fill-box; transform-origin: center; }
|
||||
.ng-title { font-weight: 900; font-size: 1.15rem; color: var(--success); margin: 0; text-align: center; }
|
||||
.ng-title.ans { color: var(--text-sub); font-size: 1rem; }
|
||||
@keyframes ng-in { from { transform: scale(.4); } }
|
||||
@keyframes ng-color { 0% { fill: var(--text); transform: scale(1); } 40% { transform: scale(1.12); } 100% { transform: scale(1); } }
|
||||
@keyframes ng-hint { 0% { opacity: 1; stroke-width: 4; } 100% { opacity: .2; stroke-width: 2; } }
|
||||
@media (prefers-reduced-motion: reduce) { .ng-new, .ng-color, .ng-hint { animation: none; } .ng-clue { transition: none; } }
|
||||
`;
|
||||
|
||||
interface Drag {
|
||||
start: number;
|
||||
end: number;
|
||||
axis: 'row' | 'col' | null;
|
||||
/** The mark the first cell had: the drag only changes cells that have it too. */
|
||||
from: string;
|
||||
value: MarkValue;
|
||||
}
|
||||
|
||||
function NonoBoard({ view: v, me, players, act }: BoardProps<NonogramView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [mode, setMode] = useState<1 | 2>(1);
|
||||
const [cursor, setCursor] = useState(0);
|
||||
const [focused, setFocused] = useState(false);
|
||||
const [drag, setDrag] = useState<Drag | null>(null);
|
||||
const [fresh, setFresh] = useState<Set<number>>(new Set());
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prev = useRef<{ marks: string; ok: number; hint: number | null } | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
const n = b?.size ?? 10;
|
||||
const rowClues = (b?.rows ?? []).map((c) => (c.length ? c : [0]));
|
||||
const colClues = (b?.cols ?? []).map((c) => (c.length ? c : [0]));
|
||||
const lineOf = (line: number) => (line < n ? Array.from({ length: n }, (_, c) => line * n + c) : Array.from({ length: n }, (_, r) => r * n + line - n));
|
||||
const okLines = b ? [...rowClues, ...colClues].map((clue, line) => runsOf(lineOf(line).map((i) => (b.marks[i] === '1' ? '#' : '.')).join('')).join() === clue.join()) : [];
|
||||
const okCount = okLines.filter(Boolean).length;
|
||||
|
||||
// Sounds and the pop of newly marked cells; say when a line comes right.
|
||||
useEffect(() => {
|
||||
if (!b) return;
|
||||
const was = prev.current;
|
||||
prev.current = { marks: b.marks, ok: okCount, hint: b.lastHint };
|
||||
if (!was || was.marks.length !== b.marks.length) return;
|
||||
const changed = new Set<number>();
|
||||
let filled = 0;
|
||||
let crossed = 0;
|
||||
for (let i = 0; i < b.marks.length; i++) {
|
||||
if (was.marks[i] === b.marks[i]) continue;
|
||||
changed.add(i);
|
||||
if (b.marks[i] === '1') filled++;
|
||||
else if (b.marks[i] === '2') crossed++;
|
||||
}
|
||||
if (b.lastHint !== was.hint && b.hints) sfx.pop();
|
||||
else if (okCount > was.ok) tone(1175, 90, 'triangle', 0.09);
|
||||
else if (filled) tone(820, 40, 'triangle', 0.1);
|
||||
else if (crossed) tone(520, 40, 'square', 0.04);
|
||||
else if (changed.size) tone(400, 40, 'sine', 0.06);
|
||||
if (okCount !== was.ok) setAnnounce(`맞는 줄 ${okCount}/${2 * n}`);
|
||||
if (changed.size) {
|
||||
setFresh(changed);
|
||||
const t = setTimeout(() => setFresh(new Set()), fxMs(260));
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [b?.marks, b?.lastHint]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="숫자대로 칸을 칠해 그림을 완성해요!" />
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Layout in SVG units: row clues on the left, column clues on top, then the grid.
|
||||
const numW = (x: number) => (x >= 10 ? 0.95 : 0.62) * S;
|
||||
const L = Math.max(...rowClues.map((c) => c.reduce((a, x) => a + numW(x), 0))) + 0.4 * S;
|
||||
const T = Math.max(...colClues.map((c) => c.length)) * 0.72 * S + 0.35 * S;
|
||||
const W = L + n * S;
|
||||
const H = T + n * S;
|
||||
const answer = b.answer;
|
||||
|
||||
const cellAt = (e: { clientX: number; clientY: number }, inside: boolean): number | null => {
|
||||
const box = svgRef.current!.getBoundingClientRect();
|
||||
const k = W / box.width;
|
||||
const c = Math.floor(((e.clientX - box.left) * k - L) / S);
|
||||
const r = Math.floor(((e.clientY - box.top) * k - T) / S);
|
||||
if (inside && (c < 0 || r < 0 || c >= n || r >= n)) return null;
|
||||
return clamp(r, 0, n - 1) * n + clamp(c, 0, n - 1);
|
||||
};
|
||||
const dragCells = (d: Drag): number[] => {
|
||||
const r0 = Math.floor(d.start / n);
|
||||
const c0 = d.start % n;
|
||||
const out: number[] = [];
|
||||
if (d.axis === 'row') {
|
||||
const c1 = d.end % n;
|
||||
for (let c = c0; ; c += Math.sign(c1 - c0)) {
|
||||
out.push(r0 * n + c);
|
||||
if (c === c1) break;
|
||||
}
|
||||
} else if (d.axis === 'col') {
|
||||
const r1 = Math.floor(d.end / n);
|
||||
for (let r = r0; ; r += Math.sign(r1 - r0)) {
|
||||
out.push(r * n + c0);
|
||||
if (r === r1) break;
|
||||
}
|
||||
} else out.push(d.start);
|
||||
return out.filter((i) => b.marks[i] === d.from);
|
||||
};
|
||||
const valueFor = (i: number, m: 1 | 2): MarkValue => (b.marks[i] === String(m) ? 0 : m);
|
||||
const paint = (cells: number[], value: MarkValue) => {
|
||||
if (!playing || !cells.length) return;
|
||||
act({ type: 'paint', cells, value });
|
||||
haptic(8);
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!playing || (e.pointerType === 'mouse' && e.button !== 0 && e.button !== 2)) return;
|
||||
const i = cellAt(e, true);
|
||||
if (i === null) return;
|
||||
e.preventDefault();
|
||||
svgRef.current!.setPointerCapture?.(e.pointerId);
|
||||
setCursor(i);
|
||||
setDrag({ start: i, end: i, axis: null, from: b.marks[i]!, value: valueFor(i, e.button === 2 ? 2 : mode) });
|
||||
};
|
||||
const onMove = (e: ReactPointerEvent<SVGSVGElement>) => {
|
||||
if (!drag) return;
|
||||
const i = cellAt(e, false)!;
|
||||
const r = Math.floor(i / n);
|
||||
const c = i % n;
|
||||
const r0 = Math.floor(drag.start / n);
|
||||
const c0 = drag.start % n;
|
||||
if (i === drag.start && !drag.axis) return;
|
||||
// The first step away from the start cell decides the row or column; then the line follows the pointer along it.
|
||||
const axis = drag.axis ?? (r === r0 ? 'row' : c === c0 ? 'col' : Math.abs(c - c0) >= Math.abs(r - r0) ? 'row' : 'col');
|
||||
const end = axis === 'row' ? r0 * n + c : r * n + c0;
|
||||
if (end !== drag.end || axis !== drag.axis) setDrag({ ...drag, axis, end });
|
||||
};
|
||||
const onUp = () => {
|
||||
if (!drag) return;
|
||||
setDrag(null);
|
||||
paint(dragCells(drag), drag.value);
|
||||
};
|
||||
|
||||
const describe = (i: number) => {
|
||||
const r = Math.floor(i / n);
|
||||
const c = i % n;
|
||||
return `${r + 1}줄 ${c + 1}칸, ${MARK_WORD[b.marks[i]!]}. 가로 숫자 ${rowClues[r]!.join(' ')}, 세로 숫자 ${colClues[c]!.join(' ')}`;
|
||||
};
|
||||
const onKey = (e: ReactKeyboardEvent<SVGSVGElement>) => {
|
||||
const step: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
const next = clamp(Math.floor(cursor / n) + m[0], 0, n - 1) * n + clamp((cursor % n) + m[1], 0, n - 1);
|
||||
setCursor(next);
|
||||
setAnnounce(describe(next));
|
||||
return;
|
||||
}
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) paint([cursor], valueFor(cursor, 1));
|
||||
} else if (e.key === 'x' || e.key === 'X' || e.key === 'ㅌ') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) paint([cursor], valueFor(cursor, 2));
|
||||
}
|
||||
};
|
||||
|
||||
const preview = new Map<number, MarkValue>();
|
||||
if (drag) for (const i of dragCells(drag)) preview.set(i, drag.value);
|
||||
const cr = Math.floor(cursor / n);
|
||||
const cc = cursor % n;
|
||||
const showCursor = focused && playing;
|
||||
const wrapStyle: CSSProperties = phone
|
||||
? { width: '100%' }
|
||||
: { width: `min(100%, ${Math.round((W / S) * 40)}px, calc((var(--play-h, 100vh) - 230px) * ${(W / H).toFixed(3)}))`, minWidth: Math.min(320, (W / S) * 24) };
|
||||
const fill = (i: number) => {
|
||||
if (answer) return answer.solution[i] === '#' ? answer.color : 'var(--surface)';
|
||||
const m = preview.get(i) ?? Number(b.marks[i]);
|
||||
return m === 1 ? 'var(--text)' : 'var(--surface)';
|
||||
};
|
||||
const xMark = (i: number) => !answer && (preview.get(i) ?? Number(b.marks[i])) === 2;
|
||||
const solvedByMe = mine?.status === 'solved';
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill" aria-label={`맞는 줄 ${okCount}개, 전체 ${2 * n}줄`}>
|
||||
✔ <b>{okCount}/{2 * n}</b>
|
||||
</span>
|
||||
{mine && playing && (
|
||||
<>
|
||||
<button type="button" className="rc-pill" aria-pressed={mode === 1} onClick={() => setMode(1)}>
|
||||
■ 채우기
|
||||
</button>
|
||||
<button type="button" className="rc-pill" aria-pressed={mode === 2} onClick={() => setMode(2)}>
|
||||
✕ 표시
|
||||
</button>
|
||||
{v.options.hints && (
|
||||
<button type="button" className="rc-pill" onClick={() => act({ type: 'hint' })} aria-label={`힌트 쓰기, 지금까지 ${b.hints}번`}>
|
||||
💡 힌트{b.hints ? ` ${b.hints}` : ''}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
{answer && (
|
||||
<p className={`ng-title${solvedByMe ? '' : ' ans'}`} role="status">
|
||||
{solvedByMe ? `다 풀었어요! ${answer.name}` : `정답 그림: ${answer.name}`}
|
||||
</p>
|
||||
)}
|
||||
<div className="rc-wrap" style={wrapStyle}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="ng-board"
|
||||
data-off={!playing}
|
||||
viewBox={`0 0 ${W} ${H}`}
|
||||
role="application"
|
||||
aria-roledescription="네모네모 로직 판"
|
||||
aria-label={playing ? `네모네모 로직 ${n}×${n}. 화살표로 옮기고 스페이스로 칠하기, X로 ✕ 표시. 지금 ${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()}
|
||||
>
|
||||
<rect x={0} y={0} width={L} height={H} fill="var(--surface-2)" />
|
||||
<rect x={L} y={0} width={n * S} height={T} fill="var(--surface-2)" />
|
||||
{showCursor && (
|
||||
<>
|
||||
<rect x={0} y={T + cr * S} width={L} height={S} fill="var(--primary-soft)" />
|
||||
<rect x={L + cc * S} y={0} width={S} height={T} fill="var(--primary-soft)" />
|
||||
</>
|
||||
)}
|
||||
{colClues.map((clue, c) =>
|
||||
clue.map((x, j) => (
|
||||
<text key={`c${c}-${j}`} className="ng-clue" data-ok={okLines[n + c]} data-line={n + c} data-k={j} x={L + c * S + S / 2} y={T - 0.3 * S - (clue.length - 1 - j) * 0.72 * S} textAnchor="middle" fontSize={0.6 * S}>
|
||||
{x}
|
||||
</text>
|
||||
)),
|
||||
)}
|
||||
{rowClues.map((clue, r) => {
|
||||
let x = L - 0.25 * S;
|
||||
return [...clue].reverse().map((num, j) => {
|
||||
const at = x - numW(num) / 2;
|
||||
x -= numW(num);
|
||||
return (
|
||||
<text key={`r${r}-${j}`} className="ng-clue" data-ok={okLines[r]} data-line={r} data-k={clue.length - 1 - j} x={at} y={T + r * S + 0.71 * S} textAnchor="middle" fontSize={0.6 * S}>
|
||||
{num}
|
||||
</text>
|
||||
);
|
||||
});
|
||||
})}
|
||||
{Array.from(b.marks, (ch, i) => {
|
||||
const x = L + (i % n) * S;
|
||||
const y = T + Math.floor(i / n) * S;
|
||||
const colored = !!answer && answer.solution[i] === '#';
|
||||
return (
|
||||
<g key={i} data-i={i} data-m={ch} className={!answer && fresh.has(i) ? 'ng-new' : undefined}>
|
||||
<rect
|
||||
x={x}
|
||||
y={y}
|
||||
width={S}
|
||||
height={S}
|
||||
fill={fill(i)}
|
||||
opacity={preview.has(i) ? 0.6 : 1}
|
||||
className={colored ? 'ng-color' : undefined}
|
||||
style={colored ? { animationDelay: `${fxMs(((i % n) + Math.floor(i / n)) * 18)}ms` } : undefined}
|
||||
/>
|
||||
{xMark(i) && <path d={`M${x + 5.5} ${y + 5.5} L${x + S - 5.5} ${y + S - 5.5} M${x + S - 5.5} ${y + 5.5} L${x + 5.5} ${y + S - 5.5}`} stroke="var(--text-sub)" strokeWidth={1.8} strokeLinecap="round" opacity={preview.has(i) ? 0.6 : 1} />}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{Array.from({ length: n + 1 }, (_, k) => {
|
||||
const thick = k % 5 === 0 || k === n;
|
||||
const style = { stroke: thick ? 'var(--text-sub)' : 'var(--border)', strokeWidth: thick ? 1.4 : 0.6 };
|
||||
return (
|
||||
<g key={`l${k}`} pointerEvents="none">
|
||||
<line x1={L + k * S} y1={thick ? 0 : T} x2={L + k * S} y2={H} {...style} />
|
||||
<line x1={thick ? 0 : L} y1={T + k * S} x2={W} y2={T + k * S} {...style} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{!answer && b.lastHint !== null && (
|
||||
<rect key={`h${b.hints}`} className="ng-hint" x={L + (b.lastHint % n) * S + 1.5} y={T + Math.floor(b.lastHint / n) * S + 1.5} width={S - 3} height={S - 3} rx={3} fill="none" stroke="#f59e0b" strokeWidth={2} pointerEvents="none" />
|
||||
)}
|
||||
{showCursor && <rect x={L + cc * S + 1} y={T + cr * S + 1} width={S - 2} height={S - 2} rx={3} fill="none" stroke="var(--focus)" strokeWidth={2.4} pointerEvents="none" />}
|
||||
</svg>
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">왼쪽 클릭·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 오른쪽 클릭·끌기: ✕ 표시 · 키보드: 화살표 + 스페이스 칠하기, X ✕ 표시</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">누르기·끌기: {mode === 1 ? '칠하기' : '✕ 표시'} · 한 줄로 끌면 한 번에 · 칠한 칸을 다시 누르면 지워요</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NonoSide(props: BoardProps<NonogramView>) {
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="네모네모 로직" info={`${sizeInfo(props.view.options.size)} · 힌트 ${props.view.options.hints ? '켬' : '끔'}`} />;
|
||||
}
|
||||
|
||||
function statusText(v: NonogramView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자대로 칸을 칠해 그림을 완성해요', playing: '줄마다 숫자 = 이어서 칠할 칸 수 · 모든 줄을 숫자와 맞게 칠해요', failed: '' });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<NonogramOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>크기</strong>
|
||||
<Seg label="크기" value={o.size} options={([5, 10, 15] as NonogramSize[]).map((s) => [s, sizeInfo(s)])} onChange={(size) => onChange({ ...o, size })} />
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>힌트</strong>
|
||||
<Seg label="힌트" value={o.hints} options={[[true, '켬'], [false, '끔']]} onChange={(hints) => onChange({ ...o, hints })} />
|
||||
<span className="small muted">{o.hints ? '막히면 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[300, 600, 1200, 1800]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as NonogramOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: NonogramOptions): string {
|
||||
return `${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: NonogramOptions }) {
|
||||
const size = options?.size ?? 10;
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
줄마다 적힌 숫자대로 칸을 칠하면 <strong>그림</strong>이 나와요. 모두 <strong>똑같은 그림</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 12, alignItems: 'center' }}>
|
||||
<MiniNono answer={['.#.#.', '#####', '#####', '.###.', '..#..']} marks={['x#x#x', '#####', '.....', '.....', '.....']} cell={18} />
|
||||
<span>숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"은 한 칸, 한 칸 이상 띄고, 또 한 칸이에요. 숫자 순서대로 놓여요.</span>
|
||||
</div>
|
||||
<p>
|
||||
확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 두면 좋아요(✕는 답에 상관없어요). 칠한 칸이 맞는지는 알려 주지 않아요. 숫자와 맞게 칠해진 줄은 숫자가 흐려져요. 칠한 칸이 그림과
|
||||
똑같아지면 다 푼 거예요.
|
||||
</p>
|
||||
<p>
|
||||
여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 <strong>숫자와 맞는 줄</strong>이 많은 사람이 이겨요. 힌트를 켜면 막힐 때 틀렸거나 모르는 칸 하나를 바르게 고쳐 줘요(쓴 횟수는
|
||||
결과에 나와요). 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1200)}이고, 지금 크기는 {sizeInfo(size)}이에요.
|
||||
</p>
|
||||
<p>PC: 왼쪽 클릭·끌기 칠하기, 오른쪽 클릭·끌기 ✕. 휴대폰: 누르거나 끌어서 칠하고, 위의 [✕ 표시]로 바꾸면 ✕를 해요. 칠한 칸을 다시 누르면 지워요. 키보드: 화살표, 스페이스 칠하기, X로 ✕.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<NonogramView, NonogramOptions> = {
|
||||
Board: NonoBoard,
|
||||
Side: NonoSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
26
apps/web/src/games/nonogram/quick.tsx
Normal file
26
apps/web/src/games/nonogram/quick.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
/** 네모네모 로직 30초 규칙 요약 (docs/07 §5). Small puzzles drawn with ./art. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniNono } from './art';
|
||||
|
||||
const HEART = ['.#.#.', '#####', '#####', '.###.', '..#..'];
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <MiniNono answer={HEART} marks={['.....', '.....', '.....', '.....', '.....']} />,
|
||||
alt: '5×5 빈 칸 위와 왼쪽에 줄마다 숫자가 적혀 있어요',
|
||||
title: '숫자 = 칠할 칸 덩어리',
|
||||
text: '줄 옆 숫자는 그 줄에서 이어서 칠할 칸 수예요. "1 1"이면 한 칸, 띄고, 한 칸이에요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniNono answer={HEART} marks={['x#x#x', '#####', '#####', '.....', '.....']} />,
|
||||
alt: '위 세 줄은 칠한 칸과 ✕ 표시로 채워져 있어요',
|
||||
title: '칠하기와 ✕ 표시',
|
||||
text: '확실한 칸은 칠하고, 비어야 할 칸에는 ✕를 해 둬요. 끌면 한 줄을 한 번에 칠해요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniNono answer={HEART} color="#ef4444" />,
|
||||
alt: '다 칠한 칸이 빨간 하트 그림이 됐어요',
|
||||
title: '다 칠하면 그림이 나와요',
|
||||
text: '모든 줄이 숫자와 맞으면 그림이 나와요. 모두 같은 그림이라 가장 먼저 푼 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
289
apps/web/src/games/race/kit.tsx
Normal file
289
apps/web/src/games/race/kit.tsx
Normal file
@@ -0,0 +1,289 @@
|
||||
/**
|
||||
* Shared screen parts for the race games (docs/games/race.md §4): the clock row, everyone's progress chips, the side
|
||||
* ranking, the countdown and finished notes, 포기, the time limit option and the shared status / help lines.
|
||||
* Each game draws its own board in between.
|
||||
*/
|
||||
import { useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { formatElapsed, rankSeats, type RaceSeat, type RaceView } from '@bg/games/race';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { sfx, tone } from '../../lib/feedback';
|
||||
import { AfterMotion } from '../../lib/motion';
|
||||
|
||||
type V = RaceView<unknown, { timeLimitSec: number | null }>;
|
||||
|
||||
export { STATUS_WORD, limitLabel, mySeat, nick, raceHelp, raceIsMyTurn, raceStatusText } from './text';
|
||||
import { STATUS_WORD, limitLabel, mySeat, nick } from './text';
|
||||
|
||||
const userOf = (players: Record<string, PublicUser>, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' };
|
||||
const clock = (ms: number) => {
|
||||
const s = Math.ceil(Math.max(0, ms) / 1000);
|
||||
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
|
||||
};
|
||||
/** Stopwatch: "1:05.4". */
|
||||
const watch = (ms: number) => {
|
||||
const t = Math.floor(Math.max(0, ms) / 100);
|
||||
return `${Math.floor(t / 600)}:${String(Math.floor((t % 600) / 10)).padStart(2, '0')}.${t % 10}`;
|
||||
};
|
||||
|
||||
export function canPlay(v: V, me: string | null, now: number): boolean {
|
||||
const s = mySeat(v, me);
|
||||
return !!s && s.status === 'playing' && v.phase === 'playing' && !!v.board && (v.endsAt === null || now < v.endsAt);
|
||||
}
|
||||
|
||||
export const RACE_CSS = `
|
||||
.rc { width: 100%; display: flex; flex-direction: column; align-items: center; gap: 8px; }
|
||||
.rc-top { width: 100%; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; justify-content: center; }
|
||||
.rc-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; border: 0; color: inherit; }
|
||||
.rc-pill b { font-size: 1.1rem; }
|
||||
.rc-pill.warn { background: var(--danger-soft); color: var(--danger); }
|
||||
button.rc-pill { cursor: pointer; min-height: 36px; }
|
||||
button.rc-pill[aria-pressed='true'] { background: var(--primary); color: #fff; }
|
||||
.rc-others { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 6px; justify-content: center; max-width: 100%; }
|
||||
.rc-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; }
|
||||
.rc-others li span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.rc-others li b { font-variant-numeric: tabular-nums; margin-left: 2px; }
|
||||
.rc-others li[data-me='true'] { background: var(--primary-soft); }
|
||||
.rc-others li[data-out='true'] { opacity: .55; }
|
||||
.rc-wrap { position: relative; max-width: 100%; }
|
||||
.rc-over { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; pointer-events: none;
|
||||
border-radius: 12px; text-align: center; padding: 12px; z-index: 4; }
|
||||
.rc-over.count { background: rgba(0,0,0,.4); color: #fff; font-size: 4.5rem; font-weight: 900; text-shadow: 0 3px 8px rgba(0,0,0,.5); min-height: 180px; }
|
||||
.rc-over.count small { font-size: 1.05rem; font-weight: 800; }
|
||||
.rc-over.count b { display: block; animation: rc-count .9s ease-out both; }
|
||||
.rc-over.note { inset: auto 8px 8px 8px; background: var(--surface); color: var(--text); box-shadow: var(--shadow); font-weight: 800; }
|
||||
.rc-over.note.win { color: var(--success); border: 3px solid var(--success); }
|
||||
.rc-acts { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; }
|
||||
.rc-acts .btn { min-height: 40px; }
|
||||
.rc-keys { color: var(--text-sub); font-size: .85rem; font-weight: 600; text-align: center; margin: 0; }
|
||||
.rc-wait { min-height: 220px; width: min(100%, 520px); border-radius: 12px; background: var(--surface-2); }
|
||||
@keyframes rc-count { 0% { transform: scale(1.8); opacity: 0; } 25% { transform: scale(1); opacity: 1; } 100% { transform: scale(.85); opacity: .85; } }
|
||||
@media (prefers-reduced-motion: reduce) { .rc-over.count b { animation: none; } }
|
||||
`;
|
||||
|
||||
/** Clock values for the board: time left (time limit) or my stopwatch (무제한), the 3·2·1 countdown. */
|
||||
export function useRaceClock(v: V, me: string | null) {
|
||||
const now = useServerNow(v.endsAt === null ? 100 : 200);
|
||||
const mine = mySeat(v, me);
|
||||
const left = v.endsAt === null ? null : Math.max(0, v.endsAt - Math.max(now, v.countdownEndsAt));
|
||||
const elapsed = mine?.timeMs ?? (v.phase === 'playing' && (!mine || mine.status === 'playing') ? Math.max(0, now - v.countdownEndsAt) : null);
|
||||
const countdown = v.phase === 'countdown' ? Math.max(1, Math.ceil((v.countdownEndsAt - now) / 1000)) : 0;
|
||||
// Sounds that follow the clock: 3·2·1, start, the last 10 seconds, finishing.
|
||||
const lastSec = v.phase === 'playing' && left !== null && left > 0 && left <= 10_000 ? Math.ceil(left / 1000) : 0;
|
||||
const heard = useRef({ countdown: 0, lastSec: 0, status: mine?.status ?? null });
|
||||
useEffect(() => {
|
||||
const was = heard.current;
|
||||
if (countdown !== was.countdown) {
|
||||
if (countdown > 0) tone(660, 90, 'triangle', 0.12);
|
||||
else if (was.countdown > 0 && v.phase === 'playing') {
|
||||
tone(988, 120, 'triangle', 0.14);
|
||||
tone(1318, 200, 'triangle', 0.12, 90);
|
||||
}
|
||||
}
|
||||
if (lastSec && lastSec !== was.lastSec) sfx.tick();
|
||||
const st = mine?.status ?? null;
|
||||
if (st !== was.status && was.status === 'playing') {
|
||||
if (st === 'solved') sfx.fanfare();
|
||||
else if (st === 'failed') sfx.bad();
|
||||
}
|
||||
heard.current = { countdown, lastSec, status: st };
|
||||
});
|
||||
return { now, left, elapsed, countdown, mine };
|
||||
}
|
||||
|
||||
/** Top row: the clock first, then the game's own pills. */
|
||||
export function RaceTop({ v, left, elapsed, children }: { v: V; left: number | null; elapsed: number | null; children?: ReactNode }) {
|
||||
return (
|
||||
<div className="rc-top">
|
||||
{left === null ? (
|
||||
<span className="rc-pill" aria-label={elapsed === null ? '제한 시간 없음' : `걸린 시간 ${formatElapsed(elapsed)}`}>
|
||||
⏱ {elapsed === null ? '무제한' : <b style={{ fontSize: '1rem' }}>{watch(elapsed)}</b>}
|
||||
</span>
|
||||
) : (
|
||||
<span className={`rc-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>
|
||||
)}
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Everyone's progress (live), ranked; only with more than one player. */
|
||||
export function RaceSeats({ v, me, players }: { v: V; me: string | null; players: Record<string, PublicUser> }) {
|
||||
if (v.seats.length < 2) return null;
|
||||
return (
|
||||
<ol className="rc-others" aria-label="진행 상황">
|
||||
{rankSeats(v.seats).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.status === 'solved' ? `다 풀었어요 ${formatElapsed(s.timeMs ?? 0)}` : s.progressText}${s.status !== 'playing' && s.status !== 'solved' ? `, ${STATUS_WORD[s.status]}` : ''}`}
|
||||
>
|
||||
<Avatar user={userOf(players, s.id)} size={20} />
|
||||
<span>{s.id === me ? '나' : nick(players, s.id)}</span>
|
||||
<b key={s.progress} className={s.progress ? 'anim-bump' : undefined}>
|
||||
{s.status === 'solved' ? `✔ ${formatElapsed(s.timeMs ?? 0)}` : s.progressText.replace(/^[^\d]*/, '')}
|
||||
</b>
|
||||
{s.status !== 'playing' && s.status !== 'solved' && <span aria-hidden>· {STATUS_WORD[s.status]}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
/** Countdown over the (still hidden) board. */
|
||||
export function RaceCountdown({ countdown, text }: { countdown: number; text: string }) {
|
||||
if (!countdown) return null;
|
||||
return (
|
||||
<div className="rc-over count" aria-hidden>
|
||||
<b key={countdown}>{countdown}</b>
|
||||
<small>{text}</small>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Notes over the board once I am finished, left, or watching. */
|
||||
export function RaceNotes({ v, mine, failText }: { v: V; mine: RaceSeat | null; failText: string }) {
|
||||
const playing = v.phase === 'playing';
|
||||
const wait = v.seats.length > 1 ? ' · 모두 끝날 때까지 기다려요' : '';
|
||||
return (
|
||||
<>
|
||||
<AfterMotion when={!!mine && mine.status === 'solved' && playing}>
|
||||
<div className="rc-over note win" role="status">
|
||||
다 풀었어요! {formatElapsed(mine?.timeMs ?? 0)}
|
||||
{mine?.extra}
|
||||
{wait}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
<AfterMotion when={!!mine && mine.status === 'failed' && playing}>
|
||||
<div className="rc-over note" role="status">
|
||||
{failText} {mine?.progressText}
|
||||
{wait}
|
||||
</div>
|
||||
</AfterMotion>
|
||||
{mine?.status === 'done' && playing && (
|
||||
<div className="rc-over note" role="status">
|
||||
포기했어요. {mine.progressText}
|
||||
{wait}
|
||||
</div>
|
||||
)}
|
||||
{mine?.status === 'left' && v.phase !== 'ended' && <div className="rc-over note">게임에서 나갔어요.</div>}
|
||||
{!mine && v.phase !== 'ended' && <div className="rc-over note">관전 중이에요 · 위에서 진행 상황을 볼 수 있어요</div>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** 포기: press twice (the first press only asks). */
|
||||
export function GiveUp({ act }: { act: (a: unknown) => void }) {
|
||||
const [ask, setAsk] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!ask) return;
|
||||
const t = setTimeout(() => setAsk(false), 3000);
|
||||
return () => clearTimeout(t);
|
||||
}, [ask]);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={`btn ${ask ? 'btn-primary' : 'btn-secondary'}`}
|
||||
onClick={() => {
|
||||
if (!ask) return setAsk(true);
|
||||
setAsk(false);
|
||||
act({ type: 'stop' });
|
||||
}}
|
||||
>
|
||||
{ask ? '한 번 더 누르면 포기해요' : '포기할래요'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Right panel: the live ranking, then the final one. */
|
||||
export function RaceSide({ v, me, players, title, info }: { v: V; me: string | null; players: Record<string, PublicUser>; title: string; info: string }) {
|
||||
return (
|
||||
<>
|
||||
<style>{RACE_CSS}</style>
|
||||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||||
<strong>
|
||||
{title}
|
||||
{v.phase === 'ended' ? ' · 게임 끝' : ''}
|
||||
</strong>
|
||||
<span className="small muted">
|
||||
{info} · 제한 시간 {limitLabel(v.options.timeLimitSec)} · 모두 같은 판
|
||||
</span>
|
||||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||||
{rankSeats(v.seats).map((s) => (
|
||||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: s.status === 'left' ? 0.55 : 1 }}>
|
||||
<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 }}>
|
||||
{nick(players, s.id)}
|
||||
{s.id === me ? ' (나)' : ''}
|
||||
{STATUS_WORD[s.status] ? ` · ${STATUS_WORD[s.status]}` : ''}
|
||||
</span>
|
||||
<strong className="small" style={{ fontVariantNumeric: 'tabular-nums' }}>
|
||||
{s.status === 'solved' ? formatElapsed(s.timeMs ?? 0) : s.progressText}
|
||||
</strong>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
<AfterMotion when={!!v.result}>
|
||||
{v.result && (
|
||||
<div className="card stack" style={{ gap: 4, padding: 12 }}>
|
||||
<strong>최종 순위</strong>
|
||||
{v.result.ranking.map((r) => (
|
||||
<span key={r.id}>
|
||||
{r.rank}등 {nick(players, r.id)}
|
||||
<span className="muted small"> · {r.text}</span>
|
||||
</span>
|
||||
))}
|
||||
<span className="small muted">{v.result.summary}</span>
|
||||
</div>
|
||||
)}
|
||||
</AfterMotion>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Time limit choice for the room settings. */
|
||||
export function TimeLimitOption({ value, choices, onChange }: { value: number | null; choices: number[]; onChange: (v: number | null) => void }) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>제한 시간</strong>
|
||||
<Seg label="제한 시간" value={value} options={[...choices.map((c) => [c, limitLabel(c)] as [number, string]), [null, '무제한']]} onChange={onChange} />
|
||||
<span className="small muted">
|
||||
{value === null ? '시간 제한 없이 각자 다 풀거나 포기할 때까지 해요. 스톱워치로 걸린 시간을 재요.' : '시간이 끝나면 다 못 푼 사람은 푼 만큼으로 순위를 매겨요.'}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Seg<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||||
return (
|
||||
<div className="segmented" role="group" aria-label={label}>
|
||||
{options.map(([k, l]) => (
|
||||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Narrow screens (phones). */
|
||||
export 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;
|
||||
}
|
||||
55
apps/web/src/games/race/text.ts
Normal file
55
apps/web/src/games/race/text.ts
Normal file
@@ -0,0 +1,55 @@
|
||||
/** Pure text helpers for the race games (status line, [?] help); no DOM, so help tests can import them. */
|
||||
import { formatElapsed, rankSeats, type RaceSeat, type RaceView } from '@bg/games/race';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
|
||||
type V = RaceView<unknown, { timeLimitSec: number | null }>;
|
||||
|
||||
export const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||||
export const limitLabel = (sec: number | null) => (sec === null ? '무제한' : sec % 60 === 0 ? `${sec / 60}분` : `${sec}초`);
|
||||
export const STATUS_WORD: Record<RaceSeat['status'], string> = { playing: '', solved: '다 풂', failed: '실패', done: '포기', left: '나감' };
|
||||
|
||||
export function mySeat(v: V, me: string | null): RaceSeat | null {
|
||||
return v.seats.find((s) => s.id === me) ?? null;
|
||||
}
|
||||
|
||||
/** I can make moves now. */
|
||||
export function raceIsMyTurn(v: V, me: string | null): boolean {
|
||||
return !!me && v.phase === 'playing' && v.seats.some((s) => s.id === me && s.status === 'playing');
|
||||
}
|
||||
|
||||
/** Status line; `playing` is the game's line while I am still solving. */
|
||||
export function raceStatusText(v: V, me: string | null, players: Record<string, PublicUser>, texts: { countdown: string; playing: string; failed: string }): string {
|
||||
if (v.phase === 'ended') return v.result?.summary ?? '게임이 끝났어요';
|
||||
if (v.phase === 'countdown') return texts.countdown;
|
||||
const mine = mySeat(v, me);
|
||||
if (!mine) {
|
||||
const top = rankSeats(v.seats)[0];
|
||||
return top && top.status === 'solved' ? `${nick(players, top.id)}님이 가장 먼저 다 풀었어요` : '모두 같은 판을 풀고 있어요';
|
||||
}
|
||||
const wait = v.seats.length > 1 ? ' · 모두 끝날 때까지 기다려요' : '';
|
||||
if (mine.status === 'left') return '게임에서 나갔어요';
|
||||
if (mine.status === 'solved') return `다 풀었어요! ${formatElapsed(mine.timeMs ?? 0)}${mine.extra}${wait}`;
|
||||
if (mine.status === 'failed') return `${texts.failed} ${mine.progressText}${wait}`;
|
||||
if (mine.status === 'done') return `포기했어요 · ${mine.progressText}${wait}`;
|
||||
return texts.playing;
|
||||
}
|
||||
|
||||
/** [?] lines every race game shares: phase, my state, who leads. `how` explains the game's moves. */
|
||||
export function raceHelp(v: V, me: string | null, players: Record<string, PublicUser>, how: string[], failed: string): string {
|
||||
if (v.phase === 'ended') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n최종 순위에서 각자 걸린 시간과 푼 만큼을 볼 수 있어요.';
|
||||
const secs = v.options.timeLimitSec;
|
||||
const limitLine = secs === null ? '제한 시간은 없어요. 다 풀거나 포기할 때까지 해요.' : `제한 시간은 ${limitLabel(secs)}이에요.`;
|
||||
const winLine = v.seats.length > 1 ? '가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 가장 많이 푼 사람이 이겨요.' : '';
|
||||
if (v.phase === 'countdown') return [`곧 시작해요. 모두 똑같은 판을 각자 풀어요. ${limitLine}`, ...how].join('\n');
|
||||
const mine = mySeat(v, me);
|
||||
const solved = rankSeats(v.seats).filter((s) => s.status === 'solved');
|
||||
const lead = v.seats.length > 1 && solved.length ? `지금까지 ${solved.map((s) => (s.id === me ? '나' : `${nick(players, s.id)}님`)).join(', ')}이(가) 다 풀었어요.` : '';
|
||||
if (!mine) return [`모두 똑같은 판을 각자 풀고 있어요. ${winLine}`, lead].filter(Boolean).join('\n');
|
||||
if (mine.status === 'left') return '게임에서 나갔어요. 남은 사람들이 끝날 때까지 기다려 주세요.';
|
||||
const waitLine = v.seats.length > 1 ? '모두 끝나면 순위가 나와요.' : '';
|
||||
if (mine.status === 'solved') return [`다 풀었어요! 걸린 시간은 ${formatElapsed(mine.timeMs ?? 0)}이에요.`, waitLine, lead].filter(Boolean).join('\n');
|
||||
if (mine.status === 'failed') return [`${failed} ${mine.progressText}.`, waitLine, lead].filter(Boolean).join('\n');
|
||||
if (mine.status === 'done') return [`포기했어요. ${mine.progressText}.`, waitLine, lead].filter(Boolean).join('\n');
|
||||
return [...how, `지금 ${mine.progressText}.`, limitLine, winLine, lead, '그만하고 싶으면 [포기할래요]를 두 번 눌러요.'].filter(Boolean).join('\n');
|
||||
}
|
||||
|
||||
@@ -27,6 +27,11 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
'ninety-nine': () => import('./ninety-nine'),
|
||||
'connect-four': () => import('./connect-four'),
|
||||
typing: () => import('./typing'),
|
||||
minesweeper: () => import('./minesweeper'),
|
||||
shisen: () => import('./shisen'),
|
||||
solitaire: () => import('./solitaire'),
|
||||
sudoku: () => import('./sudoku'),
|
||||
nonogram: () => import('./nonogram'),
|
||||
'old-maid': () => import('./old-maid'),
|
||||
dobble: () => import('./dobble'),
|
||||
catchmind: () => import('./catchmind'),
|
||||
|
||||
41
apps/web/src/games/shisen/art.tsx
Normal file
41
apps/web/src/games/shisen/art.tsx
Normal file
@@ -0,0 +1,41 @@
|
||||
/** 사천성 board geometry and small pictures for the rules and help cards (tiles: ../mahjong/Tile). */
|
||||
import { Tile } from '../mahjong/Tile';
|
||||
|
||||
/** Felt behind the tiles (the same in light and dark mode). */
|
||||
export const FELT = '#2f6b4f';
|
||||
export const LINE = '#fbbf24';
|
||||
|
||||
/**
|
||||
* Where things sit on a board of `dR`×`dC` tiles `tw` px wide: tiles are 3:4, with a half-tile margin all round that
|
||||
* connecting lines may run through. Margin rows/columns (-1 and dR/dC) map to the middle of that strip.
|
||||
*/
|
||||
export function geom(tw: number, dR: number, dC: number) {
|
||||
const th = Math.round((tw * 4) / 3);
|
||||
const m = Math.round(tw / 2);
|
||||
const x = (c: number) => (c < 0 ? m / 2 : c >= dC ? m + dC * tw + m / 2 : m + (c + 0.5) * tw);
|
||||
const y = (r: number) => (r < 0 ? m / 2 : r >= dR ? m + dR * th + m / 2 : m + (r + 0.5) * th);
|
||||
return { tw, th, m, w: dC * tw + 2 * m, h: dR * th + 2 * m, x, y, left: (c: number) => m + c * tw, top: (r: number) => m + r * th };
|
||||
}
|
||||
|
||||
/** A tiny board (rows of kind codes, '' = empty) with an optional line through [row, col] points. */
|
||||
export function MiniBoard({ rows, path, tw = 26, dim = [] }: { rows: string[][]; path?: [number, number][]; tw?: number; dim?: string[] }) {
|
||||
const g = geom(tw, rows.length, rows[0]!.length);
|
||||
return (
|
||||
<div aria-hidden style={{ position: 'relative', width: g.w, height: g.h, background: FELT, borderRadius: 8, flex: 'none' }}>
|
||||
{rows.flatMap((row, r) =>
|
||||
row.map((k, c) =>
|
||||
k ? (
|
||||
<div key={`${r}-${c}`} style={{ position: 'absolute', left: g.left(c), top: g.top(r), opacity: dim.includes(k) ? 0.35 : 1 }}>
|
||||
<Tile code={k} w={tw} />
|
||||
</div>
|
||||
) : null,
|
||||
),
|
||||
)}
|
||||
{path && (
|
||||
<svg width={g.w} height={g.h} style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
|
||||
<polyline points={path.map(([r, c]) => `${g.x(c)},${g.y(r)}`).join(' ')} fill="none" stroke={LINE} strokeWidth={3.5} strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
apps/web/src/games/shisen/help.ts
Normal file
19
apps/web/src/games/shisen/help.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
/** 사천성 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { ShisenView } from '@bg/games/shisen';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW = [
|
||||
'같은 그림의 패 두 장을 차례로 누르면 없어져요. 두 패 사이를 빈 칸으로만 지나는 선이 두 번 이하로 꺾여야 해요(판 바깥 테두리로 돌아가도 돼요).',
|
||||
'고른 패를 다시 누르면 취소돼요. 이을 수 있는 쌍이 하나도 없으면 남은 패가 저절로 섞여요.',
|
||||
'키보드: 화살표로 옮기고 스페이스(또는 Enter)로 골라요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: ShisenView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '');
|
||||
const mine = v.seats.find((s) => s.id === me);
|
||||
if (!v.board || v.phase !== 'playing' || mine?.status !== 'playing') return lines;
|
||||
const left = v.board.cells.filter((k) => k !== null).length;
|
||||
const hint = !v.options.hints ? '이 방은 힌트를 쓰지 않아요.' : v.board.hint ? '빛나는 두 장이 힌트예요.' : '막히면 [💡 힌트]로 이을 수 있는 쌍 하나를 볼 수 있어요.';
|
||||
return `${lines}\n남은 패는 ${left}장이에요. ${hint}`;
|
||||
}
|
||||
445
apps/web/src/games/shisen/index.tsx
Normal file
445
apps/web/src/games/shisen/index.tsx
Normal file
@@ -0,0 +1,445 @@
|
||||
/** 사천성 화면 (docs/games/shisen.md §9). */
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { SIZES, findPath, type Point, type ShisenOptions, type ShisenView, type Size } from '@bg/games/shisen';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { MAHJONG_TILE_CREDIT, Tile, tileName } from '../mahjong/Tile';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { FELT, LINE, MiniBoard, geom } from './art';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const NOT_SAME = '같은 패가 아니에요';
|
||||
const TOO_MANY_TURNS = '두 번 넘게 꺾여야 이어져요';
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
|
||||
const CSS = `
|
||||
.ss-fit { width: 100%; display: flex; justify-content: center; }
|
||||
.ss-board { position: relative; border-radius: 12px; background: ${FELT}; box-shadow: var(--shadow), inset 0 0 0 2px rgba(0,0,0,.18);
|
||||
touch-action: manipulation; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; outline: none; cursor: pointer; }
|
||||
.ss-board:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.ss-board[data-off='true'] { cursor: default; }
|
||||
.ss-cell { position: absolute; transition: transform .12s ease; pointer-events: none; }
|
||||
.ss-cell .mj-tile { filter: drop-shadow(0 1.5px 1px rgba(0,0,0,.4)); }
|
||||
.ss-cell::after { content: ''; position: absolute; inset: -1px; border-radius: 7px; pointer-events: none; }
|
||||
.ss-cell.sel { transform: translateY(-4px); z-index: 2; }
|
||||
.ss-cell.sel::after { box-shadow: 0 0 0 3px #f59e0b, 0 0 12px 3px rgba(245,158,11,.75); }
|
||||
.ss-cell.hint { transform: translateY(-2px); z-index: 2; }
|
||||
.ss-cell.hint::after { box-shadow: 0 0 0 4px #0ea5e9, 0 0 16px 5px rgba(14,165,233,.95); animation: ss-pulse .8s ease-in-out infinite alternate; }
|
||||
.ss-cell.cur::after { outline: 3px dashed #fff; outline-offset: 1px; }
|
||||
.ss-shake { animation: ss-shake .35s ease both; }
|
||||
.ss-gone { z-index: 3; animation: ss-gone var(--ss-ms) ease-in forwards; }
|
||||
.ss-line { position: absolute; inset: 0; pointer-events: none; z-index: 4; overflow: visible; }
|
||||
.ss-line polyline { animation: ss-fade var(--ss-ms) ease-in forwards; }
|
||||
.ss-toast { position: absolute; top: 6px; left: 50%; transform: translateX(-50%); z-index: 5; padding: 6px 14px; border-radius: 999px; background: var(--surface);
|
||||
color: var(--text); font-weight: 800; box-shadow: var(--shadow); pointer-events: none; white-space: nowrap; animation: ss-pop .25s ease-out both; }
|
||||
.ss-toast.bad { color: var(--danger); }
|
||||
.ss-probe-box { position: relative; width: 0; height: 0; overflow: hidden; flex: none; }
|
||||
.ss-probe { position: absolute; top: 0; left: 0; width: 1px; height: var(--play-h, 100vh); visibility: hidden; }
|
||||
@keyframes ss-shake { 20% { transform: translateX(-5px); } 40% { transform: translateX(5px); } 60% { transform: translateX(-3px); } 80% { transform: translateX(2px); } }
|
||||
@keyframes ss-gone { to { opacity: 0; transform: scale(.7); } }
|
||||
@keyframes ss-fade { 0%, 55% { opacity: 1; } 100% { opacity: 0; } }
|
||||
@keyframes ss-pop { from { opacity: 0; transform: translate(-50%, -6px); } }
|
||||
@keyframes ss-pulse { from { opacity: .6; } to { opacity: 1; } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.ss-shake, .ss-toast, .ss-cell.hint::after, .ss-line polyline { animation: none; }
|
||||
.ss-cell { transition: none; }
|
||||
.ss-gone { animation: none; opacity: 0; }
|
||||
}
|
||||
`;
|
||||
|
||||
const sizeInfo = (s: Size) => `${SIZES[s].name} ${SIZES[s].cols}×${SIZES[s].rows} · ${SIZES[s].rows * SIZES[s].cols}패`;
|
||||
|
||||
interface Flash {
|
||||
key: number;
|
||||
pts: Point[];
|
||||
a: number;
|
||||
b: number;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
function ShisenBoard({ view: v, me, players, act }: BoardProps<ShisenView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
const [cursor, setCursor] = useState(0);
|
||||
// The keyboard cursor shows only while playing by keyboard (not after a click or tap).
|
||||
const [keyCursor, setKeyCursor] = useState(false);
|
||||
const [flash, setFlash] = useState<Flash | null>(null);
|
||||
const [shake, setShake] = useState<{ key: number; ids: number[] } | null>(null);
|
||||
const [toast, setToast] = useState<{ key: number; text: string; bad: boolean } | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [tw, setTw] = useState(40);
|
||||
const fitRef = useRef<HTMLDivElement>(null);
|
||||
const probeRef = useRef<HTMLDivElement>(null);
|
||||
const boardRef = useRef<HTMLDivElement>(null);
|
||||
const press = useRef<number | null>(null);
|
||||
const seenShuffles = useRef<number | null>(null);
|
||||
const seenHint = useRef<string | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
const rows = b?.rows ?? SIZES[v.options.size].rows;
|
||||
const cols = b?.cols ?? SIZES[v.options.size].cols;
|
||||
// Phones: a wide board is turned so it is taller than wide.
|
||||
const turn = phone && cols > rows;
|
||||
const dR = turn ? cols : rows;
|
||||
const dC = turn ? rows : cols;
|
||||
|
||||
// Tile width: fit the column width and the visible height. PC: the play area (--play-h, measured by a probe) minus
|
||||
// the rows above and below the board. Phone: the first screen from the board's top down, minus the buttons below.
|
||||
useLayoutEffect(() => {
|
||||
const fit = fitRef.current;
|
||||
const probe = probeRef.current;
|
||||
if (!fit || !probe) return;
|
||||
const update = () => {
|
||||
const availH = phone ? window.innerHeight - (fit.getBoundingClientRect().top + window.scrollY) - 96 : probe.offsetHeight - 175;
|
||||
const w = Math.floor(Math.min(fit.clientWidth / (dC + 1), availH / ((dR * 4) / 3 + 1), 64));
|
||||
setTw(Math.max(phone ? 34 : 28, w)); // phones: at least a finger-sized tile, scrolling if needed
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(fit);
|
||||
ro.observe(probe);
|
||||
ro.observe(document.body); // rows above the board change height (status text)
|
||||
window.addEventListener('resize', update);
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
window.removeEventListener('resize', update);
|
||||
};
|
||||
}, [dC, dR, phone, !!b]);
|
||||
|
||||
// Auto-reshuffle: say so for a moment.
|
||||
useEffect(() => {
|
||||
const n = b?.shuffles ?? null;
|
||||
const was = seenShuffles.current;
|
||||
seenShuffles.current = n;
|
||||
if (n === null || was === null || n <= was) return;
|
||||
setSel(null);
|
||||
setToast({ key: Date.now(), text: '섞었어요!', bad: false });
|
||||
sfx.shuffle();
|
||||
setAnnounce('이을 수 있는 쌍이 없어서 남은 패를 섞었어요.');
|
||||
}, [b?.shuffles]);
|
||||
|
||||
// A new hint: announce the pair.
|
||||
useEffect(() => {
|
||||
const h = b?.hint ? `${b.hint[0]}-${b.hint[1]}` : null;
|
||||
if (h && h !== seenHint.current && b?.hint) {
|
||||
sfx.pop();
|
||||
setAnnounce(`힌트: 빛나는 ${tileName(b.cells[b.hint[0]]!)} 두 장을 이을 수 있어요.`);
|
||||
}
|
||||
seenHint.current = h;
|
||||
}, [b?.hint?.[0], b?.hint?.[1]]);
|
||||
|
||||
// The selected tile went away (removed, reshuffled): drop the selection.
|
||||
useEffect(() => {
|
||||
if (sel !== null && b && b.cells[sel] == null) setSel(null);
|
||||
}, [b?.cells, sel]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!flash) return;
|
||||
const t = setTimeout(() => setFlash(null), fxMs(350));
|
||||
return () => clearTimeout(t);
|
||||
}, [flash?.key]);
|
||||
useEffect(() => {
|
||||
if (!shake) return;
|
||||
const t = setTimeout(() => setShake(null), fxMs(400));
|
||||
return () => clearTimeout(t);
|
||||
}, [shake?.key]);
|
||||
useEffect(() => {
|
||||
if (!toast) return;
|
||||
const t = setTimeout(() => setToast(null), fxMs(1200));
|
||||
return () => clearTimeout(t);
|
||||
}, [toast?.key]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="같은 패 두 장을 두 번 이하로 꺾인 선으로 이어요!" />
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
<div ref={fitRef} className="ss-fit">
|
||||
<div className="ss-probe-box">
|
||||
<div ref={probeRef} className="ss-probe" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const g = geom(tw, dR, dC);
|
||||
const toDisp = (r: number, c: number): Point => (turn ? [c, rows - 1 - r] : [r, c]);
|
||||
const dispOf = (i: number) => toDisp(Math.floor(i / cols), i % cols);
|
||||
const toIndex = (dr: number, dc: number) => (turn ? (rows - 1 - dc) * cols + dr : dr * cols + dc);
|
||||
const cellAt = (e: { clientX: number; clientY: number }): number | null => {
|
||||
const box = boardRef.current!.getBoundingClientRect();
|
||||
const dc = Math.floor((e.clientX - box.left - g.m) / g.tw);
|
||||
const dr = Math.floor((e.clientY - box.top - g.m) / g.th);
|
||||
return dr < 0 || dc < 0 || dr >= dR || dc >= dC ? null : toIndex(dr, dc);
|
||||
};
|
||||
const tilesLeft = b.cells.filter((k) => k !== null).length;
|
||||
const describe = (i: number) => {
|
||||
const [dr, dc] = dispOf(i);
|
||||
const k = b.cells[i];
|
||||
return `${dr + 1}줄 ${dc + 1}칸, ${k ? tileName(k) : '빈 칸'}${i === sel ? '(고름)' : ''}`;
|
||||
};
|
||||
|
||||
const tap = (i: number) => {
|
||||
if (!playing) return;
|
||||
setCursor(i);
|
||||
const k = b.cells[i];
|
||||
if (k == null) return;
|
||||
if (sel === null || b.cells[sel] == null) {
|
||||
setSel(i);
|
||||
sfx.select();
|
||||
setAnnounce(`골랐어요: ${describe(i)}. 같은 패를 하나 더 골라요.`);
|
||||
return;
|
||||
}
|
||||
if (sel === i) {
|
||||
setSel(null);
|
||||
sfx.click();
|
||||
setAnnounce('고르기를 취소했어요.');
|
||||
return;
|
||||
}
|
||||
const pts = b.cells[sel] === k ? findPath(b.cells, b.rows, b.cols, sel, i) : null;
|
||||
if (!pts) {
|
||||
// Not a pair: shake both, say why, and start again from the tile just picked.
|
||||
const why = b.cells[sel] === k ? TOO_MANY_TURNS : NOT_SAME;
|
||||
setShake({ key: Date.now(), ids: [sel, i] });
|
||||
setToast({ key: Date.now(), text: why, bad: true });
|
||||
setSel(i);
|
||||
tone(220, 120, 'square', 0.05);
|
||||
haptic(30);
|
||||
setAnnounce(`${why}. 새로 고른 패: ${describe(i)}.`);
|
||||
return;
|
||||
}
|
||||
act({ type: 'pair', a: sel, b: i });
|
||||
setFlash({ key: Date.now(), pts, a: sel, b: i, kind: k });
|
||||
setSel(null);
|
||||
tone(880, 60, 'triangle', 0.12);
|
||||
tone(1320, 110, 'triangle', 0.1, 60);
|
||||
haptic(12);
|
||||
setAnnounce(`${tileName(k)} 한 쌍을 없앴어요. 남은 패 ${tilesLeft - 2}장.`);
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
if (!playing || (e.pointerType === 'mouse' && e.button !== 0)) return;
|
||||
setKeyCursor(false);
|
||||
press.current = cellAt(e);
|
||||
};
|
||||
const onUp = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const p = press.current;
|
||||
press.current = null;
|
||||
if (p !== null && cellAt(e) === p) tap(p);
|
||||
};
|
||||
const onKey = (e: ReactKeyboardEvent<HTMLDivElement>) => {
|
||||
const step: Record<string, Point> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
setKeyCursor(true);
|
||||
const [dr, dc] = dispOf(cursor);
|
||||
const next = toIndex(clamp(dr + m[0], 0, dR - 1), clamp(dc + m[1], 0, dC - 1));
|
||||
setCursor(next);
|
||||
setAnnounce(describe(next));
|
||||
} else if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
setKeyCursor(true);
|
||||
if (!e.repeat) tap(cursor);
|
||||
} else if (e.key === 'Escape' && sel !== null) {
|
||||
setSel(null);
|
||||
setAnnounce('고르기를 취소했어요.');
|
||||
}
|
||||
};
|
||||
|
||||
const hint: number[] = b.hint ?? [];
|
||||
const msVar = { '--ss-ms': `${fxMs(350)}ms` } as CSSProperties;
|
||||
const showHint = !!mine && v.phase === 'playing' && v.options.hints;
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill" aria-label={`남은 패 ${tilesLeft}장`}>
|
||||
🀄 <b>{tilesLeft}</b>
|
||||
</span>
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div ref={fitRef} className="ss-fit">
|
||||
<div className="ss-probe-box">
|
||||
<div ref={probeRef} className="ss-probe" />
|
||||
</div>
|
||||
<div className="rc-wrap" style={{ width: g.w }}>
|
||||
<div
|
||||
ref={boardRef}
|
||||
className="ss-board"
|
||||
data-off={!playing}
|
||||
data-rows={rows}
|
||||
data-cols={cols}
|
||||
style={{ width: g.w, height: g.h, ...msVar }}
|
||||
role="application"
|
||||
aria-roledescription="사천성 판"
|
||||
aria-label={playing ? `사천성 판 ${dR}줄 ${dC}칸. 화살표로 옮기고 스페이스로 패 고르기. 지금 ${describe(cursor)}` : '사천성 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={() => (press.current = null)}
|
||||
onKeyDown={onKey}
|
||||
onFocus={(e) => setKeyCursor(e.currentTarget.matches(':focus-visible'))}
|
||||
onBlur={() => setKeyCursor(false)}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{b.cells.map((k, i) => {
|
||||
if (k == null || (flash && (i === flash.a || i === flash.b))) return null;
|
||||
const [dr, dc] = dispOf(i);
|
||||
const cls = ['ss-cell', i === sel && 'sel', hint.includes(i) && 'hint', keyCursor && playing && i === cursor && 'cur', shake?.ids.includes(i) && 'ss-shake'].filter(Boolean).join(' ');
|
||||
return (
|
||||
<div key={i} className={cls} data-i={i} data-k={k} style={{ left: g.left(dc), top: g.top(dr) }}>
|
||||
<Tile code={k} w={tw} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{keyCursor && playing && b.cells[cursor] == null && (
|
||||
<div className="ss-cell cur" style={{ left: g.left(dispOf(cursor)[1]), top: g.top(dispOf(cursor)[0]), width: g.tw, height: g.th }} />
|
||||
)}
|
||||
{flash &&
|
||||
[flash.a, flash.b].map((i) => {
|
||||
const [dr, dc] = dispOf(i);
|
||||
return (
|
||||
<div key={`g${flash.key}-${i}`} className="ss-cell ss-gone" style={{ left: g.left(dc), top: g.top(dr) }}>
|
||||
<Tile code={flash.kind} w={tw} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{flash && (
|
||||
<svg key={flash.key} className="ss-line" width={g.w} height={g.h} aria-hidden>
|
||||
<polyline
|
||||
points={flash.pts.map(([r, c]) => toDisp(r, c)).map(([dr, dc]) => `${g.x(dc)},${g.y(dr)}`).join(' ')}
|
||||
fill="none"
|
||||
stroke={LINE}
|
||||
strokeWidth={Math.max(3, tw / 10)}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
{toast && (
|
||||
<div key={toast.key} className={`ss-toast${toast.bad ? ' bad' : ''}`} aria-hidden>
|
||||
{toast.text}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
{showHint && (
|
||||
<button type="button" className="btn btn-secondary" disabled={!!b.hint} onClick={() => act({ type: 'hint' })}>
|
||||
💡 힌트{b.hints ? ` (${b.hints}번 씀)` : ''}
|
||||
</button>
|
||||
)}
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">같은 패 두 장을 차례로 클릭 · 고른 패를 다시 누르면 취소 · 키보드: 화살표 + 스페이스, Esc 취소</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">같은 패 두 장을 차례로 눌러요 · 고른 패를 다시 누르면 취소</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ShisenSide(props: BoardProps<ShisenView>) {
|
||||
const o = props.view.options;
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="사천성" info={`${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'}`} />;
|
||||
}
|
||||
|
||||
function statusText(v: ShisenView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 같은 패 두 장을 이어서 없애요', playing: '같은 패 두 장을 두 번 이하로 꺾인 선으로 이으면 없어져요', failed: '' });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<ShisenOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>판 크기</strong>
|
||||
<Seg label="판 크기" value={o.size} options={(Object.keys(SIZES) as Size[]).map((s) => [s, SIZES[s].name])} onChange={(size) => onChange({ ...o, size })} />
|
||||
<span className="small muted">{sizeInfo(o.size)}</span>
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>힌트</strong>
|
||||
<Seg
|
||||
label="힌트"
|
||||
value={o.hints}
|
||||
options={[
|
||||
[true, '쓰기'],
|
||||
[false, '안 쓰기'],
|
||||
]}
|
||||
onChange={(hints) => onChange({ ...o, hints })}
|
||||
/>
|
||||
<span className="small muted">{o.hints ? '[💡 힌트]를 누르면 이을 수 있는 쌍 하나를 보여 줘요. 쓴 횟수는 결과에 나와요.' : '힌트 없이 풀어요.'}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[300, 600, 900, 1200]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as ShisenOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: ShisenOptions): string {
|
||||
return `${sizeInfo(o.size)} · 힌트 ${o.hints ? '켬' : '끔'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: ShisenOptions }) {
|
||||
const size = options?.size ?? 'normal';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
마작패가 깔린 판에서 <strong>같은 그림의 패 두 장</strong>을 골라 없애요. 패를 모두 없애면 이겨요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수
|
||||
있어요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['7z', '1m', '7z'],
|
||||
['2s', '4p', '9m'],
|
||||
]}
|
||||
path={[
|
||||
[0, 0],
|
||||
[-1, 0],
|
||||
[-1, 2],
|
||||
[0, 2],
|
||||
]}
|
||||
/>
|
||||
<span>두 패를 잇는 선이 빈 칸으로만 지나고 두 번까지만 꺾이면 돼요. 판 바깥 테두리로 돌아가도 돼요.</span>
|
||||
</div>
|
||||
<p>
|
||||
이을 수 있는 쌍이 하나도 없으면 남은 패가 같은 자리에서 저절로 섞여요(언제나 다 풀 수 있게). 판은 처음부터 끝까지 풀 수 있게 만들어져요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못
|
||||
풀면 없앤 쌍이 많은 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 900)}이고, 지금 판은 {sizeInfo(size)}이에요.
|
||||
</p>
|
||||
<p>PC: 패를 차례로 클릭. 휴대폰: 패를 차례로 눌러요(넓은 판은 세로로 돌려 보여 줘요). 키보드: 화살표로 옮기고 스페이스로 골라요. 힌트를 쓰는 방이면 [💡 힌트]로 한 쌍을 볼 수 있어요.</p>
|
||||
<p className="small muted">{MAHJONG_TILE_CREDIT}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<ShisenView, ShisenOptions> = {
|
||||
Board: ShisenBoard,
|
||||
Side: ShisenSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
60
apps/web/src/games/shisen/quick.tsx
Normal file
60
apps/web/src/games/shisen/quick.tsx
Normal file
@@ -0,0 +1,60 @@
|
||||
/** 사천성 30초 규칙 요약 (docs/07 §5). Small boards drawn with the mahjong tiles. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniBoard } from './art';
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['3p', '', '3p'],
|
||||
['1z', '5s', '2m'],
|
||||
]}
|
||||
path={[
|
||||
[0, 0],
|
||||
[0, 2],
|
||||
]}
|
||||
/>
|
||||
),
|
||||
alt: '같은 통수 3 두 장이 빈 칸을 지나는 곧은 선으로 이어져 있어요',
|
||||
title: '같은 패 두 장을 이어요',
|
||||
text: '같은 그림의 패 두 장을 차례로 누르면 없어져요. 모두 똑같은 판을 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['7z', '1m', '7z'],
|
||||
['2s', '4p', '9m'],
|
||||
]}
|
||||
path={[
|
||||
[0, 0],
|
||||
[-1, 0],
|
||||
[-1, 2],
|
||||
[0, 2],
|
||||
]}
|
||||
/>
|
||||
),
|
||||
alt: '가운데가 막힌 중 두 장이 판 바깥을 돌아 두 번 꺾인 선으로 이어져 있어요',
|
||||
title: '두 번까지 꺾여도 돼요',
|
||||
text: '빈 칸으로만 지나는 선이 두 번 이하로 꺾이면 이어져요. 판 바깥 테두리로 돌아가도 돼요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<MiniBoard
|
||||
rows={[
|
||||
['', '5z', ''],
|
||||
['', '', '5z'],
|
||||
]}
|
||||
path={[
|
||||
[0, 1],
|
||||
[1, 1],
|
||||
[1, 2],
|
||||
]}
|
||||
/>
|
||||
),
|
||||
alt: '판에 백 두 장만 남아 한 번 꺾인 선으로 이어져 있어요',
|
||||
title: '모두 없애면 승리',
|
||||
text: '패를 모두 없애면 다 푼 거예요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 이을 쌍이 없으면 저절로 섞여요.',
|
||||
},
|
||||
];
|
||||
29
apps/web/src/games/solitaire/help.ts
Normal file
29
apps/web/src/games/solitaire/help.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
/** 솔리테어 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
|
||||
import type { Mode, SolitaireView } from '@bg/games/solitaire';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
const HOW: Record<Mode, string[]> = {
|
||||
klondike: [
|
||||
'클론다이크: 줄에는 색을 번갈아 하나씩 작은 수를 쌓고, 빈 줄에는 K만 놓아요. 카드를 옮기면 아래 뒤집힌 카드가 열려요.',
|
||||
'더미를 누르면 카드를 넘겨요. 더미가 비면 버린 카드를 다시 뒤집어 써요. A부터 무늬별로 52장을 모두 파운데이션에 올리면 다 푼 거예요.',
|
||||
],
|
||||
freecell: [
|
||||
'프리셀: 모든 카드가 앞면이에요. 줄에는 색을 번갈아 하나씩 작은 수를 쌓고, 빈 칸 4개에는 카드를 한 장씩 잠깐 둘 수 있어요.',
|
||||
'여러 장은 (빈 칸 수 + 1) × 2^(빈 줄 수)장까지 한 번에 옮겨요. 52장을 모두 파운데이션에 올리면 다 푼 거예요.',
|
||||
],
|
||||
spider: [
|
||||
'스파이더: 무늬와 상관없이 하나 작은 수를 쌓지만, 함께 옮길 수 있는 건 같은 무늬로 이어진 카드뿐이에요.',
|
||||
'K부터 A까지 같은 무늬 한 줄이 되면 저절로 빠져요. 8줄을 모두 빼면 다 푼 거예요. 더미를 누르면 열 줄에 한 장씩 나눠요(빈 줄이 있으면 못 나눠요).',
|
||||
],
|
||||
};
|
||||
const COMMON = ['카드를 눌러 고르고 놓을 곳을 눌러요. 두 번 누르면 파운데이션으로 올라가요. [되돌리기]로 한 수씩 되돌릴 수 있어요(횟수가 결과에 적혀요).'];
|
||||
|
||||
export function helpNow(v: SolitaireView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, [...HOW[v.options.mode], ...COMMON], '실패했어요.');
|
||||
const b = v.board;
|
||||
if (!b || v.phase !== 'playing') return lines;
|
||||
if (b.mode === 'spider') return `${lines}\n더미에서 ${b.stock / 10}번 더 나눌 수 있어요.`;
|
||||
if (b.mode === 'klondike') return `${lines}\n더미에 ${b.stock}장, 버린 카드 ${b.waste.length}장이 있어요.`;
|
||||
return `${lines}\n빈 칸 ${b.cells.filter((c) => !c).length}개가 비어 있어요.`;
|
||||
}
|
||||
510
apps/web/src/games/solitaire/index.tsx
Normal file
510
apps/web/src/games/solitaire/index.tsx
Normal file
@@ -0,0 +1,510 @@
|
||||
/** 솔리테어 화면 (docs/games/solitaire.md §9). */
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import {
|
||||
MODE_NAME,
|
||||
TIME_CHOICES,
|
||||
canAuto,
|
||||
freecellCapacity,
|
||||
isRun,
|
||||
moveProblem,
|
||||
rankOf,
|
||||
type Mode,
|
||||
type SolitaireBoardView,
|
||||
type SolitaireMove,
|
||||
type SolitaireOptions,
|
||||
type SolitaireView,
|
||||
} from '@bg/games/solitaire';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { PLAYING_CARD_CREDIT, PlayingCard, cardAria } from '../../components/cards/PlayingCard';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const FAIL = '실패했어요.';
|
||||
const DOUBLE_TAP_MS = 380;
|
||||
|
||||
const CSS = `
|
||||
.sl-felt { width: 100%; border-radius: 14px; background: var(--felt); box-shadow: inset 0 0 40px rgba(0,0,0,.25), var(--shadow); color: #fff;
|
||||
user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation; }
|
||||
.sl-row { display: grid; justify-content: center; align-items: start; }
|
||||
.sl-pile { position: relative; }
|
||||
.sl-slot { display: flex; align-items: center; justify-content: center; border-radius: 8%/6%; border: 2px dashed rgba(255,255,255,.45); background: rgba(0,0,0,.12);
|
||||
color: rgba(255,255,255,.7); font-weight: 900; padding: 0; cursor: pointer; font-family: inherit; }
|
||||
.sl-slot[data-hint='true'] { border-color: #fbbf24; border-style: solid; background: rgba(251,191,36,.18); }
|
||||
.sl-slot:disabled { cursor: default; }
|
||||
.sl-card { position: absolute; left: 0; padding: 0; border: 0; background: none; cursor: pointer; display: block; border-radius: 9%/6%; }
|
||||
.sl-card:disabled, span.sl-card { cursor: default; }
|
||||
.sl-card:focus-visible, .sl-slot:focus-visible, .sl-stock:focus-visible { outline: 3px solid #fbbf24; outline-offset: 2px; z-index: 50; }
|
||||
.sl-stock { position: relative; padding: 0; border: 0; background: none; cursor: pointer; display: block; }
|
||||
.sl-stock:disabled { cursor: default; }
|
||||
.sl-badge { position: absolute; right: -4px; bottom: -6px; min-width: 22px; padding: 1px 5px; border-radius: 999px; background: #111827; color: #fff; font-size: .72rem;
|
||||
font-weight: 800; font-variant-numeric: tabular-nums; box-shadow: 0 1px 3px rgba(0,0,0,.4); pointer-events: none; }
|
||||
.sl-in { animation: sl-in .26s ease-out both; }
|
||||
.sl-shake { animation: sl-shake .3s ease-in-out; }
|
||||
@keyframes sl-in { from { transform: translateY(-14px) scale(1.06); opacity: .5; } }
|
||||
@keyframes sl-shake { 25% { transform: translateX(-5px); } 75% { transform: translateX(5px); } }
|
||||
@media (prefers-reduced-motion: reduce) { .sl-in, .sl-shake { animation: none; } }
|
||||
`;
|
||||
|
||||
interface Sel {
|
||||
from: string;
|
||||
n: number;
|
||||
}
|
||||
|
||||
const colsOf = (mode: Mode) => (mode === 'klondike' ? 7 : mode === 'freecell' ? 8 : 10);
|
||||
const fTotal = (f: string[]) => f.reduce((n, c) => n + (c ? rankOf(c) : 0), 0);
|
||||
const pileName = (id: string) =>
|
||||
id === 'w' ? '버린 카드' : id === 'f' ? '파운데이션' : id[0] === 't' ? `${Number(id.slice(1)) + 1}번째 줄` : id[0] === 'c' ? `빈 칸 ${Number(id.slice(1)) + 1}` : `파운데이션 ${Number(id.slice(1)) + 1}`;
|
||||
|
||||
/** Every visible card on its pile ("t3:4" → "KS"), to spot cards that just arrived. */
|
||||
function cardSpots(b: SolitaireBoardView): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
b.t.forEach((c, i) => c.forEach((x, k) => out.set(`t${i}:${k}`, x ?? '')));
|
||||
b.waste.forEach((x, k) => out.set(`w:${k}`, x));
|
||||
b.cells.forEach((x, i) => x && out.set(`c${i}:0`, x));
|
||||
b.f.forEach((x, i) => x && out.set(`f${i}:0`, x));
|
||||
return out;
|
||||
}
|
||||
|
||||
function SolBoard({ view: v, me, players, act }: BoardProps<SolitaireView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [sel, setSel] = useState<Sel | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [fresh, setFresh] = useState<Set<string>>(new Set());
|
||||
const [shake, setShake] = useState(0);
|
||||
const [box, setBox] = useState({ w: 0, h: 800 });
|
||||
const wrapRef = useRef<HTMLDivElement>(null);
|
||||
const lastTap = useRef<{ key: string; at: number } | null>(null);
|
||||
const prev = useRef<SolitaireBoardView | null>(null);
|
||||
const bKey = b ? JSON.stringify(b) : '';
|
||||
const playing = canPlayNow(v, me, now);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = wrapRef.current;
|
||||
if (!el) return;
|
||||
const update = () => {
|
||||
const playH = parseFloat(getComputedStyle(el).getPropertyValue('--play-h'));
|
||||
setBox({ w: el.clientWidth, h: Number.isFinite(playH) && playH > 0 ? playH : window.innerHeight });
|
||||
};
|
||||
update();
|
||||
const ro = new ResizeObserver(update);
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, [!!b]);
|
||||
|
||||
// Cards that just arrived slide in; sounds for what changed. Any change ends the current selection.
|
||||
useEffect(() => {
|
||||
const was = prev.current;
|
||||
prev.current = b;
|
||||
setSel(null);
|
||||
if (!b || !was) return;
|
||||
const before = cardSpots(was);
|
||||
const added = new Set<string>();
|
||||
for (const [k, c] of cardSpots(b)) if (c && before.get(k) !== c) added.add(k);
|
||||
const up = fTotal(b.f) - fTotal(was.f);
|
||||
if (b.done.length > was.done.length) {
|
||||
sfx.good();
|
||||
haptic([20, 30, 20]);
|
||||
setAnnounce(`K부터 A까지 한 줄을 완성해서 뺐어요. 완성 ${b.done.length}/8줄`);
|
||||
} else if (up > 0) {
|
||||
[1046, 1318].forEach((f, i) => tone(f, 70, 'triangle', 0.1, i * 60));
|
||||
setAnnounce(`파운데이션에 올렸어요. 올린 카드 ${fTotal(b.f)}/52`);
|
||||
} else if (b.stock < was.stock && b.mode === 'spider') sfx.deal(10, 35);
|
||||
else if (b.stock !== was.stock || b.waste.length !== was.waste.length) sfx.cardFlip();
|
||||
else if (added.size) sfx.cardPlay();
|
||||
if (b.undos > was.undos) setAnnounce('한 수 되돌렸어요.');
|
||||
if (added.size) {
|
||||
setFresh(added);
|
||||
const t = setTimeout(() => setFresh(new Set()), fxMs(300));
|
||||
return () => clearTimeout(t);
|
||||
}
|
||||
}, [bKey]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text={`${MODE_NAME[v.options.mode]} · 모두 같은 패예요!`} />
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Card size: the columns fill the width (phones: 7–8 columns ≈ 47 px, 10 columns ≈ 34 px).
|
||||
const N = colsOf(b.mode);
|
||||
const gap = phone ? (N >= 10 ? 2 : 4) : N >= 10 ? 8 : 12;
|
||||
const pad = phone ? 4 : 14;
|
||||
const w = Math.max(24, Math.min(N >= 10 ? 78 : 96, Math.floor((box.w - 2 * pad - gap * (N - 1)) / N)));
|
||||
const h = Math.round(w * 1.4);
|
||||
const colMax = phone ? Infinity : Math.max(h * 3, box.h - h - 230);
|
||||
const offsets = (col: (string | null)[]) => {
|
||||
const downs = col.filter((x) => x === null).length;
|
||||
const ups = col.length - downs;
|
||||
let dOff = Math.round(h * 0.11);
|
||||
let uOff = Math.round(h * (phone ? 0.3 : 0.38));
|
||||
if (h + downs * dOff + Math.max(0, ups - 1) * uOff > colMax) {
|
||||
dOff = Math.max(3, Math.round(h * 0.05));
|
||||
uOff = Math.max(Math.round(h * 0.24), Math.floor((colMax - h - downs * dOff) / Math.max(1, ups - 1)));
|
||||
}
|
||||
let y = 0;
|
||||
return col.map((x) => {
|
||||
const top = y;
|
||||
y += x === null ? dOff : uOff;
|
||||
return top;
|
||||
});
|
||||
};
|
||||
const grid: CSSProperties = { gridTemplateColumns: `repeat(${N}, ${w}px)`, gap, padding: `${pad}px ${pad}px 0` };
|
||||
|
||||
const tops = (pile: string): number => {
|
||||
if (pile === 'w') return b.waste.length - 1;
|
||||
if (pile[0] === 't') return b.t[Number(pile.slice(1))]!.length - 1;
|
||||
return 0;
|
||||
};
|
||||
const cardAt = (pile: string, i: number): string | null => {
|
||||
if (pile === 'w') return b.waste[i] ?? null;
|
||||
if (pile[0] === 't') return b.t[Number(pile.slice(1))]![i] ?? null;
|
||||
if (pile[0] === 'c') return b.cells[Number(pile.slice(1))] || null;
|
||||
return b.f[Number(pile.slice(1))] || null;
|
||||
};
|
||||
const nope = (why: string) => {
|
||||
setAnnounce(why);
|
||||
setShake((x) => x + 1);
|
||||
tone(220, 110, 'sine', 0.07);
|
||||
haptic(15);
|
||||
};
|
||||
const send = (m: SolitaireMove) => {
|
||||
const why = moveProblem(b, m);
|
||||
if (why) return nope(why);
|
||||
act(m);
|
||||
};
|
||||
const dropOn = (pile: string) => {
|
||||
if (!sel) return;
|
||||
setSel(null);
|
||||
const m: SolitaireMove = { type: 'move', from: sel.from, n: sel.n, to: pile };
|
||||
// A foundation tap means "up there": use the slot that fits when the tapped one does not.
|
||||
if (pile[0] === 'f' && moveProblem(b, m)) m.to = 'f';
|
||||
send(m);
|
||||
};
|
||||
const toFoundation = (pile: string) => {
|
||||
const m: SolitaireMove = { type: 'move', from: pile, n: 1, to: 'f' };
|
||||
setSel(null);
|
||||
send(m);
|
||||
};
|
||||
|
||||
const tapCard = (pile: string, i: number) => {
|
||||
if (!playing) return;
|
||||
const t = performance.now();
|
||||
const key = `${pile}:${i}`;
|
||||
const dbl = lastTap.current?.key === key && t - lastTap.current.at < DOUBLE_TAP_MS;
|
||||
lastTap.current = dbl ? null : { key, at: t };
|
||||
const card = cardAt(pile, i);
|
||||
if (dbl && pile[0] !== 'f' && i === tops(pile) && !moveProblem(b, { type: 'move', from: pile, n: 1, to: 'f' })) return toFoundation(pile);
|
||||
if (sel && sel.from !== pile && pile !== 'w') return dropOn(pile);
|
||||
if (!card) return;
|
||||
const n = pile[0] === 't' ? b.t[Number(pile.slice(1))]!.length - i : 1;
|
||||
if (sel && sel.n === n) {
|
||||
setSel(null);
|
||||
setAnnounce('고른 카드를 내려놓았어요.');
|
||||
return;
|
||||
}
|
||||
if (pile[0] === 'f' && b.mode !== 'klondike') return nope('올린 카드는 내릴 수 없어요.');
|
||||
if (pile[0] === 't' && !isRun(b.mode, b.t[Number(pile.slice(1))]!.slice(i)))
|
||||
return nope(b.mode === 'spider' ? '같은 무늬로 이어진 카드만 함께 옮길 수 있어요.' : '색이 번갈아 하나씩 작아지게 이어진 카드만 함께 옮길 수 있어요.');
|
||||
setSel({ from: pile, n });
|
||||
sfx.select();
|
||||
setAnnounce(`${cardAria(card)}${n > 1 ? `부터 ${n}장` : ''}을 골랐어요. 놓을 곳을 눌러요.`);
|
||||
};
|
||||
const onCardKey = (pile: string, i: number) => (e: ReactKeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
setSel(null);
|
||||
setAnnounce('고르기를 그만뒀어요.');
|
||||
} else if ((e.key === 'f' || e.key === 'F' || e.key === 'ㄹ') && i === tops(pile) && pile[0] !== 'f') {
|
||||
e.preventDefault();
|
||||
if (playing) toFoundation(pile);
|
||||
}
|
||||
};
|
||||
const tapStock = () => {
|
||||
if (!playing) return;
|
||||
setSel(null);
|
||||
send(b.mode === 'spider' ? { type: 'deal' } : { type: 'draw' });
|
||||
};
|
||||
|
||||
/** Piles the selected cards may go to (a soft glow helps beginners). */
|
||||
const fits = (to: string) => !!sel && sel.from !== to && moveProblem(b, { type: 'move', from: sel.from, n: sel.n, to }) === null;
|
||||
const isSel = (pile: string, i: number) => !!sel && sel.from === pile && i >= tops(pile) - sel.n + 1;
|
||||
|
||||
const cardButton = (pile: string, i: number, card: string, style: CSSProperties, label: string) => (
|
||||
<button
|
||||
key={`${pile}-${i}`}
|
||||
type="button"
|
||||
className={`sl-card${fresh.has(`${pile}:${i}`) ? ' sl-in' : ''}`}
|
||||
style={{ ...style, zIndex: i + 1 }}
|
||||
data-card={card}
|
||||
aria-label={label}
|
||||
aria-pressed={isSel(pile, i)}
|
||||
tabIndex={playing ? 0 : -1}
|
||||
onClick={() => tapCard(pile, i)}
|
||||
onKeyDown={onCardKey(pile, i)}
|
||||
>
|
||||
<PlayingCard card={card} width={w} selected={isSel(pile, i)} highlight={i === tops(pile) && fits(pile)} />
|
||||
</button>
|
||||
);
|
||||
const slot = (pile: string, text: string, label: string, onClick?: () => void) => (
|
||||
<button
|
||||
key={`${pile}-slot`}
|
||||
type="button"
|
||||
className="sl-slot"
|
||||
style={{ width: w, height: h, fontSize: Math.max(11, w * 0.32) }}
|
||||
data-hint={fits(pile)}
|
||||
aria-label={label}
|
||||
tabIndex={playing ? 0 : -1}
|
||||
disabled={!playing}
|
||||
onClick={onClick ?? (() => dropOn(pile))}
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
);
|
||||
|
||||
// Top row: stock / waste / foundations (Klondike), free cells / foundations (FreeCell), stock / completed runs (Spider).
|
||||
const stockLeft = b.mode === 'spider' ? b.stock / 10 : b.stock;
|
||||
const stock = (
|
||||
<div className="sl-pile" data-pile="s" data-count={b.stock} style={{ gridColumn: 1 }}>
|
||||
{b.stock > 0 || b.mode === 'spider' ? (
|
||||
<button
|
||||
type="button"
|
||||
className="sl-stock"
|
||||
disabled={!playing || b.stock === 0}
|
||||
onClick={tapStock}
|
||||
aria-label={b.mode === 'spider' ? (b.stock ? `카드 나누기, ${stockLeft}번 남음` : '나눌 카드가 없어요') : `더미에서 카드 넘기기, ${b.stock}장 남음`}
|
||||
style={{ width: w, height: h }}
|
||||
>
|
||||
{b.stock > 0 ? (
|
||||
Array.from({ length: Math.min(b.mode === 'spider' ? stockLeft : 3, 5) }, (_, k) => (
|
||||
<span key={k} style={{ position: 'absolute', left: k * Math.max(2, w * 0.06), top: 0 }}>
|
||||
<PlayingCard card={null} width={w} />
|
||||
</span>
|
||||
))
|
||||
) : (
|
||||
<span className="sl-slot" style={{ width: w, height: h, cursor: 'default' }} aria-hidden />
|
||||
)}
|
||||
{b.stock > 0 && <span className="sl-badge">{b.mode === 'spider' ? `${stockLeft}번` : b.stock}</span>}
|
||||
</button>
|
||||
) : (
|
||||
slot('s', b.waste.length ? '↻' : '', b.waste.length ? '버린 카드를 다시 더미로 뒤집기' : '더미가 비었어요', tapStock)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
const fan = b.draw === 3 ? Math.round(w * 0.32) : 0;
|
||||
const shownWaste = b.waste.slice(-(b.draw === 3 ? 3 : 2));
|
||||
const waste = (
|
||||
<div className="sl-pile" data-pile="w" style={{ gridColumn: 2, width: w, height: h }}>
|
||||
{!b.waste.length && <span className="sl-slot" style={{ width: w, height: h, cursor: 'default' }} aria-hidden />}
|
||||
{shownWaste.map((c, k) => {
|
||||
const i = b.waste.length - shownWaste.length + k;
|
||||
const x = b.draw === 3 ? k * fan : 0;
|
||||
return i === b.waste.length - 1 ? (
|
||||
cardButton('w', i, c, { left: x, top: 0 }, `버린 카드 맨 위 ${cardAria(c)}. 두 번 누르면 파운데이션으로`)
|
||||
) : (
|
||||
<span key={`w-${i}`} className="sl-card" style={{ left: x, top: 0, zIndex: k }} aria-hidden>
|
||||
<PlayingCard card={c} width={w} />
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
const foundations = b.f.map((c, i) => (
|
||||
<div key={`f${i}`} className="sl-pile" data-pile={`f${i}`} data-top={c} style={{ gridColumn: N - 3 + i, width: w, height: h }}>
|
||||
{c ? cardButton(`f${i}`, 0, c, { top: 0 }, `파운데이션 ${i + 1}, 맨 위 ${cardAria(c)}`) : slot(`f${i}`, 'A', `파운데이션 ${i + 1}, 비었어요`)}
|
||||
</div>
|
||||
));
|
||||
const cells = b.cells.map((c, i) => (
|
||||
<div key={`c${i}`} className="sl-pile" data-pile={`c${i}`} style={{ gridColumn: 1 + i, width: w, height: h }}>
|
||||
{c ? cardButton(`c${i}`, 0, c, { top: 0 }, `빈 칸 ${i + 1}의 ${cardAria(c)}`) : slot(`c${i}`, '', `빈 칸 ${i + 1}, 비었어요`)}
|
||||
</div>
|
||||
));
|
||||
const done = Array.from({ length: 8 }, (_, i) => (
|
||||
<div key={`d${i}`} className="sl-pile" style={{ gridColumn: 3 + i, width: w, height: h }} aria-hidden>
|
||||
{b.done[i] ? <span className="sl-done-card"><PlayingCard card={`K${b.done[i]}`} width={w} /></span> : <span className="sl-slot" style={{ width: w, height: h, cursor: 'default', opacity: 0.6 }} />}
|
||||
</div>
|
||||
));
|
||||
|
||||
const columns = b.t.map((col, i) => {
|
||||
const pile = `t${i}`;
|
||||
const ys = offsets(col);
|
||||
const height = (ys.at(-1) ?? 0) + h;
|
||||
return (
|
||||
<div key={pile} className="sl-pile" data-pile={pile} role="group" aria-label={`${i + 1}번째 줄, ${col.length}장`} style={{ width: w, height: height + Math.round(w * 0.25) }}>
|
||||
{!col.length && slot(pile, b.mode === 'klondike' ? 'K' : '', `${i + 1}번째 줄, 비었어요${b.mode === 'klondike' ? '. K만 놓을 수 있어요' : ''}`)}
|
||||
{col.map((c, k) =>
|
||||
c === null ? (
|
||||
<span key={`${pile}-${k}`} className="sl-card" style={{ top: ys[k], zIndex: k + 1 }} data-card="">
|
||||
<PlayingCard card={null} width={w} title="뒤집힌 카드" />
|
||||
</span>
|
||||
) : (
|
||||
cardButton(pile, k, c, { top: ys[k] }, `${i + 1}번째 줄 ${k + 1}번째 ${cardAria(c)}${k === col.length - 1 ? ', 맨 위' : ''}`)
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
const autoOk = b.mode !== 'spider' && canAuto(b);
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
<span className="rc-pill">{MODE_NAME[b.mode]}</span>
|
||||
<span className="rc-pill" aria-label={b.mode === 'spider' ? `완성 ${b.done.length}/8줄` : `올린 카드 ${fTotal(b.f)}/52`}>
|
||||
{b.mode === 'spider' ? '🂮' : '🂡'} <b>{b.mode === 'spider' ? `${b.done.length}/8` : `${fTotal(b.f)}/52`}</b>
|
||||
</span>
|
||||
{b.mode === 'freecell' && (
|
||||
<span className="rc-pill" aria-label={`한 번에 ${freecellCapacity(b, false)}장까지 옮길 수 있어요`}>
|
||||
⇅ <b>{freecellCapacity(b, false)}장</b>
|
||||
</span>
|
||||
)}
|
||||
{b.undos > 0 && <span className="rc-pill" aria-label={`되돌리기 ${b.undos}번`}>↶ {b.undos}</span>}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap" style={{ width: '100%' }} ref={wrapRef}>
|
||||
<div key={shake} className={`sl-felt${shake ? ' sl-shake' : ''}`} data-mode={b.mode} style={{ paddingBottom: pad }}>
|
||||
<div className="sl-row" style={grid} role="group" aria-label={b.mode === 'freecell' ? '빈 칸과 파운데이션' : b.mode === 'spider' ? '더미와 완성한 줄' : '더미, 버린 카드, 파운데이션'}>
|
||||
{b.mode === 'klondike' && [stock, waste, ...foundations]}
|
||||
{b.mode === 'freecell' && [...cells, ...foundations]}
|
||||
{b.mode === 'spider' && [stock, ...done]}
|
||||
</div>
|
||||
<div className="sl-row" style={{ ...grid, paddingTop: Math.max(8, Math.round(h * 0.18)) }}>
|
||||
{columns}
|
||||
</div>
|
||||
</div>
|
||||
<RaceNotes v={v} mine={mine} failText={FAIL} />
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<button type="button" className="btn btn-secondary" disabled={!b.canUndo} onClick={() => send({ type: 'undo' })}>
|
||||
↶ 되돌리기
|
||||
</button>
|
||||
{b.mode !== 'spider' && (
|
||||
<button type="button" className="btn btn-secondary" disabled={!autoOk} onClick={() => send({ type: 'auto' })}>
|
||||
자동 정리
|
||||
</button>
|
||||
)}
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && mine && v.phase !== 'ended' && <p className="rc-keys">카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로 · 키보드: Tab으로 옮기고 Enter로 고르기·놓기, F 파운데이션, Esc 취소</p>}
|
||||
{phone && mine && playing && <p className="rc-keys">카드를 눌러 고르고 놓을 곳을 눌러요 · 두 번 누르면 파운데이션으로</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const modeInfo = (o: SolitaireOptions) =>
|
||||
o.mode === 'klondike' ? `클론다이크 · ${o.draw}장씩 넘기기` : o.mode === 'spider' ? `스파이더 · 무늬 ${o.suits}가지` : '프리셀 · 빈 칸 4개';
|
||||
|
||||
function SolSide(props: BoardProps<SolitaireView>) {
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="솔리테어" info={modeInfo(props.view.options)} />;
|
||||
}
|
||||
|
||||
const PLAYING_LINE: Record<Mode, string> = {
|
||||
klondike: '색을 번갈아 하나씩 작게 쌓고, A부터 무늬별로 파운데이션에 올려요',
|
||||
freecell: '빈 칸 4개를 잘 써서 모든 카드를 A부터 무늬별로 올려요',
|
||||
spider: '하나 작은 수 위에 쌓아 K부터 A까지 같은 무늬 한 줄을 만들어요',
|
||||
};
|
||||
|
||||
function statusText(v: SolitaireView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: `곧 시작해요! ${MODE_NAME[v.options.mode]} · 모두 같은 패예요`, playing: PLAYING_LINE[v.options.mode], failed: FAIL });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<SolitaireOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>종류</strong>
|
||||
<Seg label="종류" value={o.mode} options={(Object.keys(MODE_NAME) as Mode[]).map((m) => [m, MODE_NAME[m]])} onChange={(mode) => onChange({ ...o, mode })} />
|
||||
<span className="small muted">
|
||||
{o.mode === 'klondike'
|
||||
? '일곱 줄, 더미에서 카드를 넘겨 가며 풀어요.'
|
||||
: o.mode === 'freecell'
|
||||
? '모든 카드가 앞면으로 여덟 줄. 빈 칸 4개를 잠깐 쓸 수 있어요.'
|
||||
: '카드 두 벌로 열 줄. K부터 A까지 같은 무늬 한 줄을 만들면 빠져요.'}
|
||||
</span>
|
||||
</div>
|
||||
{o.mode === 'klondike' && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>한 번에 넘기는 카드</strong>
|
||||
<Seg label="한 번에 넘기는 카드" value={o.draw} options={[[1, '1장(쉬움)'], [3, '3장(어려움)']]} onChange={(draw) => onChange({ ...o, draw })} />
|
||||
</div>
|
||||
)}
|
||||
{o.mode === 'spider' && (
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>무늬 수</strong>
|
||||
<Seg label="무늬 수" value={o.suits} options={[[1, '1가지(쉬움)'], [2, '2가지(보통)'], [4, '4가지(어려움)']]} onChange={(suits) => onChange({ ...o, suits })} />
|
||||
</div>
|
||||
)}
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[...TIME_CHOICES]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as SolitaireOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: SolitaireOptions): string {
|
||||
return `${modeInfo(o)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: SolitaireOptions }) {
|
||||
const o = options ?? { mode: 'klondike', draw: 1, suits: 1, timeLimitSec: 900 };
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
윈도우에 있던 그 카드놀이예요. 모두 <strong>똑같은 패</strong>를 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요. 지금은 {modeInfo(o)}, 제한 시간 {limitLabel(o.timeLimitSec)}이에요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 4, alignItems: 'center' }}>
|
||||
<PlayingCard card="8S" width={40} />
|
||||
<PlayingCard card="7H" width={40} style={{ marginLeft: -22, marginTop: 14 }} />
|
||||
<PlayingCard card="6C" width={40} style={{ marginLeft: -22, marginTop: 28 }} />
|
||||
<span style={{ marginLeft: 8 }}>줄에는 색을 번갈아 하나씩 작은 수를 쌓아요(스파이더는 색 상관없이).</span>
|
||||
</div>
|
||||
<p>
|
||||
<strong>클론다이크</strong>: 일곱 줄 가운데 맨 위만 앞면이에요. 아래 카드를 옮기면 뒤집힌 카드가 저절로 열려요. 빈 줄에는 K만 놓을 수 있어요. 더미를 누르면 카드를 1장(또는 3장)씩 넘기고,
|
||||
더미가 비면 버린 카드를 다시 뒤집어 써요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>프리셀</strong>: 모든 카드가 앞면이에요. 빈 칸 4개에 카드를 한 장씩 잠깐 둘 수 있고, 빈 줄에는 아무 카드나 놓아요. 여러 장은 (빈 칸 수 + 1) × 2^(빈 줄 수)장까지 한 번에 옮겨요.
|
||||
</p>
|
||||
<p>
|
||||
<strong>스파이더</strong>: 카드 두 벌로 열 줄이에요. 무늬와 상관없이 하나 작은 수를 쌓지만, 함께 옮길 수 있는 건 같은 무늬로 이어진 카드뿐이에요. K부터 A까지 같은 무늬 한 줄이 되면 저절로
|
||||
빠져요. 더미를 누르면 열 줄에 한 장씩 나눠 주는데, 빈 줄이 있으면 나눌 수 없어요.
|
||||
</p>
|
||||
<p>
|
||||
카드를 눌러 고르고(위에 얹힌 카드까지 함께) 놓을 곳을 눌러요. 두 번 누르면 파운데이션으로 올라가요. [자동 정리]는 올릴 수 있는 카드를 모두 올려요. [되돌리기]는 몇 번이든 쓸 수 있지만 결과에 횟수가
|
||||
적혀요. 여럿이면 가장 먼저 다 푼 사람이 이기고, 아무도 못 풀면 가장 많이 올린(스파이더는 많이 완성한) 사람이 이겨요. 클론다이크는 가끔 풀 수 없는 패도 나와요.
|
||||
</p>
|
||||
<p className="small muted">{PLAYING_CARD_CREDIT}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<SolitaireView, SolitaireOptions> = {
|
||||
Board: SolBoard,
|
||||
Side: SolSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
63
apps/web/src/games/solitaire/quick.tsx
Normal file
63
apps/web/src/games/solitaire/quick.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
/** 솔리테어 30초 규칙 요약 (docs/07 §5). Small tables drawn with the real playing cards. */
|
||||
import { PlayingCard } from '../../components/cards/PlayingCard';
|
||||
import type { QuickCard } from '../types';
|
||||
|
||||
/** A fanned column: face-down cards (null) then face-up ones. */
|
||||
function Fan({ cards, w = 34 }: { cards: (string | null)[]; w?: number }) {
|
||||
const h = Math.round(w * 1.4);
|
||||
let y = 0;
|
||||
const ys = cards.map((c) => {
|
||||
const top = y;
|
||||
y += c === null ? h * 0.12 : h * 0.3;
|
||||
return top;
|
||||
});
|
||||
return (
|
||||
<span style={{ position: 'relative', display: 'inline-block', width: w, height: (ys.at(-1) ?? 0) + h }}>
|
||||
{cards.map((c, i) => (
|
||||
<span key={i} style={{ position: 'absolute', left: 0, top: ys[i] }}>
|
||||
<PlayingCard card={c} width={w} />
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const row = { display: 'inline-flex', gap: 6, alignItems: 'flex-start' } as const;
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: (
|
||||
<span style={row} aria-hidden>
|
||||
<Fan cards={[null, null, 'KS', 'QH', 'JC']} />
|
||||
<Fan cards={[null, '8D', '7S', '6H']} />
|
||||
</span>
|
||||
),
|
||||
alt: '두 줄에 카드가 색을 번갈아 하나씩 작은 수로 쌓여 있어요',
|
||||
title: '색을 번갈아 내려 쌓기',
|
||||
text: '줄에는 색을 번갈아 하나씩 작은 수를 쌓아요. 모두 똑같은 패를 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<span style={row} aria-hidden>
|
||||
<PlayingCard card="AH" width={34} />
|
||||
<PlayingCard card="2H" width={34} />
|
||||
<PlayingCard card="3H" width={34} />
|
||||
</span>
|
||||
),
|
||||
alt: '하트 A, 2, 3이 차례로 놓여 있어요',
|
||||
title: 'A부터 무늬별로 올리기',
|
||||
text: '파운데이션에 A부터 같은 무늬로 차례대로 올려요. 두 번 누르면 바로 올라가요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<span style={row} aria-hidden>
|
||||
<Fan cards={[null, 'KS', 'QS', 'JS', 'TS']} w={30} />
|
||||
<PlayingCard card="KS" width={30} />
|
||||
<PlayingCard card="KS" width={30} />
|
||||
</span>
|
||||
),
|
||||
alt: '스페이드가 K부터 차례로 이어진 줄과 완성한 줄이에요',
|
||||
title: '세 가지 솔리테어',
|
||||
text: '클론다이크·프리셀은 52장을 다 올리면, 스파이더는 K→A 같은 무늬 8줄을 빼면 다 풀어요.',
|
||||
},
|
||||
];
|
||||
53
apps/web/src/games/sudoku/art.tsx
Normal file
53
apps/web/src/games/sudoku/art.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
/** 스도쿠 small pictures for the rules and the summary cards (SVG, no image files). */
|
||||
|
||||
const U = 32;
|
||||
|
||||
/**
|
||||
* A few rows of cells. Per char: '1'..'9' given (bold), 'a'..'i' my number 1..9 (blue), '.' empty, '*' the selected
|
||||
* empty cell. `bad` cells are red (a digit twice), `notes` puts small pencil marks in empty cells, `box` draws thick
|
||||
* lines every 3 cells.
|
||||
*/
|
||||
export function MiniSudoku({ rows, bad = [], notes = {}, box = true, size = 28 }: { rows: string[]; bad?: number[]; notes?: Record<number, string>; box?: boolean; size?: number }) {
|
||||
const cols = rows[0]!.length;
|
||||
const w = cols * U;
|
||||
const h = rows.length * U;
|
||||
return (
|
||||
<svg viewBox={`-2 -2 ${w + 4} ${h + 4}`} width={cols * size} height={rows.length * size} aria-hidden style={{ verticalAlign: 'middle', maxWidth: '100%' }}>
|
||||
{rows.flatMap((row, r) =>
|
||||
[...row].map((ch, c) => {
|
||||
const i = r * cols + c;
|
||||
const x = c * U;
|
||||
const y = r * U;
|
||||
const mine = ch >= 'a' && ch <= 'i';
|
||||
const d = mine ? String(ch.charCodeAt(0) - 96) : ch >= '1' && ch <= '9' ? ch : '';
|
||||
const red = bad.includes(i);
|
||||
return (
|
||||
<g key={i}>
|
||||
<rect x={x} y={y} width={U} height={U} fill={red ? '#fee2e2' : ch === '*' ? '#dbe7ff' : '#ffffff'} stroke="#cbd5e1" strokeWidth={1} />
|
||||
{ch === '*' && <rect x={x + 2} y={y + 2} width={U - 4} height={U - 4} fill="none" stroke="#2563eb" strokeWidth={3} />}
|
||||
{d && (
|
||||
<text x={x + U / 2} y={y + 23} textAnchor="middle" fontSize={20} fontWeight={mine ? 600 : 900} fill={red ? '#dc2626' : mine ? '#2563eb' : '#111827'}>
|
||||
{d}
|
||||
</text>
|
||||
)}
|
||||
{!d &&
|
||||
[...(notes[i] ?? '')].map((n) => {
|
||||
const k = Number(n) - 1;
|
||||
return (
|
||||
<text key={n} x={x + 6 + (k % 3) * 10} y={y + 10 + Math.floor(k / 3) * 10} textAnchor="middle" fontSize={8.5} fontWeight={700} fill="#64748b">
|
||||
{n}
|
||||
</text>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
);
|
||||
}),
|
||||
)}
|
||||
{box &&
|
||||
Array.from({ length: Math.floor(cols / 3) + 1 }, (_, k) => <line key={`v${k}`} x1={k * 3 * U} y1={0} x2={k * 3 * U} y2={h} stroke="#111827" strokeWidth={2.5} />)}
|
||||
{box &&
|
||||
Array.from({ length: Math.floor(rows.length / 3) + 1 }, (_, k) => <line key={`h${k}`} x1={0} y1={k * 3 * U} x2={w} y2={k * 3 * U} stroke="#111827" strokeWidth={2.5} />)}
|
||||
{!box && <rect x={0} y={0} width={w} height={h} fill="none" stroke="#111827" strokeWidth={2.5} />}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
41
apps/web/src/games/sudoku/help.ts
Normal file
41
apps/web/src/games/sudoku/help.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/** 스도쿠 [?] "지금 할 수 있는 것" (docs/07 §5) and the conflict check the board uses. Pure: only reads the client view. */
|
||||
import type { SudokuView } from '@bg/games/sudoku';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { raceHelp } from '../race/text';
|
||||
|
||||
/** Cells whose digit shows up twice in a row, column or box (visible numbers only, no answer). */
|
||||
export function conflicts(values: string): Set<number> {
|
||||
const out = new Set<number>();
|
||||
const units: number[][] = [];
|
||||
for (let k = 0; k < 9; k++) {
|
||||
units.push(Array.from({ length: 9 }, (_, c) => k * 9 + c));
|
||||
units.push(Array.from({ length: 9 }, (_, r) => r * 9 + k));
|
||||
units.push(Array.from({ length: 9 }, (_, j) => (Math.floor(k / 3) * 3 + Math.floor(j / 3)) * 9 + (k % 3) * 3 + (j % 3)));
|
||||
}
|
||||
for (const u of units) {
|
||||
const seen = new Map<string, number[]>();
|
||||
for (const i of u) if (values[i] !== '0') seen.set(values[i]!, [...(seen.get(values[i]!) ?? []), i]);
|
||||
for (const cells of seen.values()) if (cells.length > 1) for (const i of cells) out.add(i);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const HOW = [
|
||||
'가로줄·세로줄·굵은 선 3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채워요. 다 맞게 채우면 다 푼 거예요.',
|
||||
'칸을 고르고 아래 숫자를 누르거나 키보드로 숫자를 쳐요. 맞는지는 알려 주지 않아요(종이처럼). 같은 줄·상자에 같은 숫자가 겹치면 빨갛게 보여요.',
|
||||
'[메모]를 켜면 숫자가 작은 후보 메모로 들어가요. 숫자를 넣으면 같은 줄·칸·상자의 그 숫자 메모는 지워져요.',
|
||||
'키보드: 화살표로 칸을 옮기고 1~9 넣기, Backspace·Delete·0 지우기, N이나 스페이스로 메모 켜고 끄기예요.',
|
||||
];
|
||||
|
||||
export function helpNow(v: SudokuView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
const lines = raceHelp(v, me, players, HOW, '');
|
||||
const b = v.board;
|
||||
const mine = v.seats.find((s) => s.id === me);
|
||||
if (!b || v.phase !== 'playing' || mine?.status !== 'playing') return lines;
|
||||
const extra: string[] = [];
|
||||
const bad = conflicts(b.values).size;
|
||||
if (bad) extra.push(`지금 숫자가 겹친 빨간 칸이 ${bad}개 있어요. 둘 중 하나는 틀렸어요.`);
|
||||
if (v.options.hints) extra.push(`막히면 [💡 힌트]를 눌러요. 빈칸이나 틀린 칸 하나를 맞는 숫자로 채워 줘요(지금까지 ${b.hints}번, 결과에 남아요).`);
|
||||
else extra.push('이 방은 힌트를 쓸 수 없어요.');
|
||||
return [lines, ...extra].join('\n');
|
||||
}
|
||||
428
apps/web/src/games/sudoku/index.tsx
Normal file
428
apps/web/src/games/sudoku/index.tsx
Normal file
@@ -0,0 +1,428 @@
|
||||
/** 스도쿠 화면 (docs/games/sudoku.md §9). */
|
||||
import { useEffect, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type PointerEvent as ReactPointerEvent } from 'react';
|
||||
import { DIFFICULTIES, type Difficulty, type SudokuOptions, type SudokuView } from '@bg/games/sudoku';
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { haptic, sfx, tone } from '../../lib/feedback';
|
||||
import { fxMs } from '../../lib/motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { GiveUp, RACE_CSS, RaceCountdown, RaceNotes, RaceSeats, RaceSide, RaceTop, Seg, TimeLimitOption, canPlay as canPlayNow, limitLabel, raceIsMyTurn, raceStatusText, useNarrow, useRaceClock } from '../race/kit';
|
||||
import { conflicts, helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { MiniSudoku } from './art';
|
||||
|
||||
const DIGITS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
|
||||
const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));
|
||||
const rowOf = (i: number) => Math.floor(i / 9);
|
||||
const colOf = (i: number) => i % 9;
|
||||
const boxOf = (i: number) => Math.floor(rowOf(i) / 3) * 3 + Math.floor(colOf(i) / 3);
|
||||
|
||||
const CSS = `
|
||||
.sd-main { display: flex; gap: 18px; align-items: flex-start; justify-content: center; width: 100%; }
|
||||
.sd-main.phone { flex-direction: column; align-items: stretch; gap: 10px; }
|
||||
.sd-grid { display: grid; grid-template-columns: repeat(9, 1fr); grid-template-rows: repeat(9, 1fr); aspect-ratio: 1; width: 100%;
|
||||
background: var(--surface); border: 3px solid var(--text); border-radius: 8px; overflow: hidden; box-shadow: var(--shadow);
|
||||
user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; touch-action: manipulation; outline: none; cursor: pointer; }
|
||||
.sd-grid:focus-visible { box-shadow: var(--shadow), 0 0 0 4px var(--focus); }
|
||||
.sd-grid[data-off='true'] { cursor: default; }
|
||||
.sd-cell { position: relative; display: flex; align-items: center; justify-content: center; min-width: 0; min-height: 0;
|
||||
border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); font-variant-numeric: tabular-nums;
|
||||
font-size: clamp(1.15rem, 6vw, 2rem); line-height: 1; transition: background-color .12s; }
|
||||
.sd-cell[data-c='2'], .sd-cell[data-c='5'] { border-right: 2px solid var(--text); }
|
||||
.sd-cell[data-c='8'] { border-right: 0; }
|
||||
.sd-cell[data-r='2'], .sd-cell[data-r='5'] { border-bottom: 2px solid var(--text); }
|
||||
.sd-cell[data-r='8'] { border-bottom: 0; }
|
||||
.sd-cell.peer { background: var(--surface-2); }
|
||||
.sd-cell.same { background: var(--primary-soft); }
|
||||
.sd-cell.hint { background: var(--warning-soft); }
|
||||
.sd-cell.sel { background: var(--primary-soft); box-shadow: inset 0 0 0 3px var(--primary); }
|
||||
.sd-cell .d { font-weight: 600; color: var(--primary); }
|
||||
.sd-cell[data-given='true'] .d { font-weight: 900; color: var(--text); }
|
||||
.sd-cell.same .d { text-decoration: underline; text-decoration-thickness: 2px; text-underline-offset: 3px; }
|
||||
.sd-cell.bad { background: var(--danger-soft); }
|
||||
.sd-cell.bad .d { color: var(--danger); }
|
||||
.sd-cell.sol .d { color: var(--success); font-weight: 600; opacity: .85; }
|
||||
.sd-cell.wrong { background: var(--danger-soft); }
|
||||
.sd-cell.wrong .d { color: var(--success); }
|
||||
.sd-notes { position: absolute; inset: 2px; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 1fr);
|
||||
font-size: clamp(.55rem, 2.6vw, .78rem); font-weight: 700; color: var(--text-sub); line-height: 1; }
|
||||
.sd-notes span { display: flex; align-items: center; justify-content: center; }
|
||||
.sd-notes span.on { color: var(--primary); }
|
||||
.sd-pop .d { animation: sd-pop .3s ease-out both; }
|
||||
.sd-glow { animation: sd-glow .9s ease-out both; }
|
||||
@keyframes sd-pop { from { transform: scale(.4); opacity: .3; } 60% { transform: scale(1.18); } to { transform: scale(1); opacity: 1; } }
|
||||
@keyframes sd-glow { 0% { box-shadow: inset 0 0 0 0 var(--warning); } 40% { box-shadow: inset 0 0 0 5px var(--warning); } 100% { box-shadow: inset 0 0 0 0 var(--warning); } }
|
||||
.sd-pad { display: flex; flex-direction: column; gap: 8px; width: 216px; flex: none; }
|
||||
.sd-digits { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
|
||||
.sd-tools { display: grid; grid-template-columns: 1fr; gap: 6px; }
|
||||
.sd-main.phone .sd-pad { width: 100%; }
|
||||
.sd-main.phone .sd-digits { grid-template-columns: repeat(9, 1fr); gap: 4px; }
|
||||
.sd-main.phone .sd-tools { grid-template-columns: repeat(3, 1fr); }
|
||||
.sd-key { position: relative; border: 0; border-radius: 10px; background: var(--surface); color: var(--primary); box-shadow: var(--shadow); cursor: pointer;
|
||||
font-size: 1.7rem; font-weight: 800; min-height: 64px; padding: 0; font-variant-numeric: tabular-nums; touch-action: manipulation; }
|
||||
.sd-main.phone .sd-key { min-height: 54px; font-size: 1.45rem; border-radius: 8px; }
|
||||
.sd-key small { position: absolute; right: 6px; bottom: 4px; font-size: .7rem; font-weight: 700; color: var(--text-sub); }
|
||||
.sd-main.phone .sd-key small { right: 0; left: 0; bottom: 2px; text-align: center; font-size: .62rem; }
|
||||
.sd-key[data-done='true'] { opacity: .35; }
|
||||
.sd-key[data-memo='true'] { color: var(--text-sub); font-size: 1.15rem; }
|
||||
.sd-key:active { transform: scale(.95); }
|
||||
.sd-key:disabled { cursor: default; }
|
||||
.sd-tool { min-height: 44px; border: 0; border-radius: 10px; background: var(--surface-2); color: var(--text); font-weight: 800; font-size: .98rem; cursor: pointer; padding: 0 8px; touch-action: manipulation; }
|
||||
.sd-tool[aria-pressed='true'] { background: var(--primary); color: var(--primary-text); }
|
||||
.sd-tool:disabled { opacity: .5; cursor: default; }
|
||||
@media (prefers-reduced-motion: reduce) { .sd-pop .d, .sd-glow { animation: none; } .sd-key:active { transform: none; } }
|
||||
`;
|
||||
|
||||
const notesOf = (mask: number) => DIGITS.filter((n) => mask & (1 << n));
|
||||
|
||||
function SudokuBoardView({ view: v, me, players, act }: BoardProps<SudokuView>) {
|
||||
const { now, left, elapsed, countdown, mine } = useRaceClock(v, me);
|
||||
const phone = useNarrow();
|
||||
const b = v.board;
|
||||
const [sel, setSel] = useState(40);
|
||||
const [memo, setMemo] = useState(false);
|
||||
const [fresh, setFresh] = useState<Set<number>>(new Set());
|
||||
const [glow, setGlow] = useState<number | null>(null);
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const gridRef = useRef<HTMLDivElement>(null);
|
||||
const prev = useRef<{ values: string; notes: string; hints: number; bad: number } | null>(null);
|
||||
const playing = canPlayNow(v, me, now);
|
||||
const bad = b ? conflicts(b.values) : new Set<number>();
|
||||
|
||||
// Pop-in for new numbers, a glow on the hinted cell, sounds for what changed.
|
||||
useEffect(() => {
|
||||
if (!b) return;
|
||||
const cur = { values: b.values, notes: b.notes.join(','), hints: b.hints, bad: bad.size };
|
||||
const was = prev.current;
|
||||
prev.current = cur;
|
||||
if (!was || was.values.length !== cur.values.length) return;
|
||||
const added = new Set<number>();
|
||||
let cleared = 0;
|
||||
for (let i = 0; i < 81; i++) {
|
||||
if (was.values[i] === cur.values[i]) continue;
|
||||
if (cur.values[i] === '0') cleared++;
|
||||
else added.add(i);
|
||||
}
|
||||
if (cur.hints > was.hints) {
|
||||
sfx.good();
|
||||
setGlow(b.hintAt);
|
||||
} else if (cur.bad > was.bad) {
|
||||
tone(240, 120, 'square', 0.05);
|
||||
haptic([20, 30, 20]);
|
||||
} else if (added.size) tone(880 + Number(b.values[[...added][0]!]) * 40, 60, 'triangle', 0.1);
|
||||
else if (cleared) tone(420, 50, 'triangle', 0.07);
|
||||
else if (cur.notes !== was.notes) tone(1300, 25, 'triangle', 0.05);
|
||||
const timers: ReturnType<typeof setTimeout>[] = [];
|
||||
if (added.size) {
|
||||
setFresh(added);
|
||||
timers.push(setTimeout(() => setFresh(new Set()), fxMs(320)));
|
||||
}
|
||||
if (cur.hints > was.hints) timers.push(setTimeout(() => setGlow(null), fxMs(900)));
|
||||
return () => timers.forEach(clearTimeout);
|
||||
}, [b?.values, b?.notes.join(','), b?.hints]);
|
||||
|
||||
if (!b) {
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed} />
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className="rc-wrap rc-wait">
|
||||
<RaceCountdown countdown={countdown} text="가로·세로·상자에 1~9를 한 번씩!" />
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const given = (i: number) => b.givens[i] === '1';
|
||||
const reveal = b.solution;
|
||||
const counts = DIGITS.map((n) => [...b.values].filter((ch) => ch === String(n)).length);
|
||||
const describe = (i: number) => {
|
||||
const where = `${rowOf(i) + 1}줄 ${colOf(i) + 1}칸`;
|
||||
const ch = b.values[i]!;
|
||||
if (given(i)) return `${where}, 처음 숫자 ${ch}`;
|
||||
if (ch !== '0') return `${where}, 내 숫자 ${ch}${bad.has(i) ? ', 겹침' : ''}`;
|
||||
const ns = notesOf(b.notes[i]!);
|
||||
return `${where}, 빈칸${ns.length ? `, 메모 ${ns.join(' ')}` : ''}`;
|
||||
};
|
||||
|
||||
const select = (i: number, speak: boolean) => {
|
||||
setSel(i);
|
||||
if (speak) setAnnounce(describe(i));
|
||||
};
|
||||
const enter = (n: number) => {
|
||||
if (!playing) return;
|
||||
const ch = b.values[sel]!;
|
||||
if (given(sel)) return setAnnounce('처음부터 있던 숫자는 바꿀 수 없어요.');
|
||||
if (memo) {
|
||||
if (ch !== '0') return setAnnounce('숫자가 있는 칸에는 메모할 수 없어요. 먼저 지워 주세요.');
|
||||
act({ type: 'note', i: sel, n });
|
||||
setAnnounce(b.notes[sel]! & (1 << n) ? `메모 ${n}을(를) 지웠어요.` : `메모 ${n}을(를) 적었어요.`);
|
||||
return;
|
||||
}
|
||||
haptic(8);
|
||||
if (ch === String(n)) {
|
||||
act({ type: 'clear', i: sel });
|
||||
setAnnounce(`${n}을(를) 지웠어요.`);
|
||||
return;
|
||||
}
|
||||
act({ type: 'set', i: sel, n });
|
||||
const dup = [...b.values].some((c, j) => j !== sel && c === String(n) && (rowOf(j) === rowOf(sel) || colOf(j) === colOf(sel) || boxOf(j) === boxOf(sel)));
|
||||
setAnnounce(`${n}을(를) 넣었어요.${dup ? ' 같은 줄·칸·상자에 이미 있는 숫자예요.' : ''}`);
|
||||
};
|
||||
const erase = () => {
|
||||
if (!playing) return;
|
||||
if (given(sel)) return setAnnounce('처음부터 있던 숫자는 지울 수 없어요.');
|
||||
if (b.values[sel] === '0' && !b.notes[sel]) return setAnnounce('지울 것이 없어요.');
|
||||
act({ type: 'clear', i: sel });
|
||||
setAnnounce('지웠어요.');
|
||||
};
|
||||
const toggleMemo = () => {
|
||||
setMemo((m) => !m);
|
||||
setAnnounce(memo ? '메모 모드를 껐어요. 숫자를 넣어요.' : '메모 모드를 켰어요. 숫자가 작은 메모로 들어가요.');
|
||||
};
|
||||
const hint = () => {
|
||||
if (!playing || !v.options.hints) return;
|
||||
act({ type: 'hint' });
|
||||
setAnnounce('힌트로 한 칸을 맞는 숫자로 채웠어요.');
|
||||
};
|
||||
|
||||
const onDown = (e: ReactPointerEvent<HTMLDivElement>) => {
|
||||
const box = gridRef.current!.getBoundingClientRect();
|
||||
const c = clamp(Math.floor(((e.clientX - box.left) / box.width) * 9), 0, 8);
|
||||
const r = clamp(Math.floor(((e.clientY - box.top) / box.height) * 9), 0, 8);
|
||||
select(r * 9 + c, false);
|
||||
if (e.pointerType === 'mouse') gridRef.current!.focus({ preventScroll: true });
|
||||
};
|
||||
|
||||
const onKey = (e: ReactKeyboardEvent<HTMLDivElement>) => {
|
||||
const step: Record<string, [number, number]> = { ArrowUp: [-1, 0], ArrowDown: [1, 0], ArrowLeft: [0, -1], ArrowRight: [0, 1] };
|
||||
const m = step[e.key];
|
||||
const onButton = (e.target as HTMLElement).tagName === 'BUTTON';
|
||||
if (m) {
|
||||
e.preventDefault();
|
||||
select(clamp(rowOf(sel) + m[0], 0, 8) * 9 + clamp(colOf(sel) + m[1], 0, 8), true);
|
||||
return;
|
||||
}
|
||||
const num = /^(Digit|Numpad)([0-9])$/.exec(e.code)?.[2] ?? (/^[0-9]$/.test(e.key) ? e.key : null);
|
||||
if (num !== null) {
|
||||
e.preventDefault();
|
||||
if (num === '0') erase();
|
||||
else enter(Number(num));
|
||||
} else if (e.key === 'Backspace' || e.key === 'Delete') {
|
||||
e.preventDefault();
|
||||
erase();
|
||||
} else if ((e.key === ' ' && !onButton) || e.key === 'n' || e.key === 'N' || e.key === 'ㅜ') {
|
||||
e.preventDefault();
|
||||
if (!e.repeat) toggleMemo();
|
||||
}
|
||||
};
|
||||
|
||||
const wrapStyle: CSSProperties = phone ? { width: '100%' } : { width: 'min(100%, 600px, calc(var(--play-h, 100vh) - 150px))', minWidth: 300, flex: '0 1 auto' };
|
||||
const showPad = !!mine && mine.status === 'playing' && v.phase === 'playing';
|
||||
|
||||
return (
|
||||
<div className="rc">
|
||||
<style>{RACE_CSS + CSS}</style>
|
||||
<RaceTop v={v} left={left} elapsed={elapsed}>
|
||||
{mine && (
|
||||
<span className="rc-pill" aria-label={mine.progressText}>
|
||||
✏️ <b>{mine.progressText.replace(/^[^\d]*/, '')}</b>
|
||||
</span>
|
||||
)}
|
||||
{b.hints > 0 && (
|
||||
<span className="rc-pill" aria-label={`힌트 ${b.hints}번`}>
|
||||
💡 <b>{b.hints}</b>
|
||||
</span>
|
||||
)}
|
||||
</RaceTop>
|
||||
<RaceSeats v={v} me={me} players={players} />
|
||||
<div className={`sd-main${phone ? ' phone' : ''}`} onKeyDown={onKey}>
|
||||
<div className="rc-wrap" style={wrapStyle}>
|
||||
<div
|
||||
ref={gridRef}
|
||||
className="sd-grid"
|
||||
data-off={!playing}
|
||||
role="application"
|
||||
aria-roledescription="스도쿠 판"
|
||||
aria-label={playing ? `스도쿠 판. 화살표로 옮기고 1~9로 넣기, Backspace로 지우기, N으로 메모. 지금 ${describe(sel)}` : '스도쿠 판'}
|
||||
tabIndex={0}
|
||||
onPointerDown={onDown}
|
||||
onContextMenu={(e) => e.preventDefault()}
|
||||
>
|
||||
{Array.from(b.values, (ch, i) => {
|
||||
const r = rowOf(i);
|
||||
const c = colOf(i);
|
||||
// Selection shading only while I can still play.
|
||||
const s = playing ? b.values[sel]! : '0';
|
||||
const cls = ['sd-cell'];
|
||||
const sol = reveal && ch !== reveal[i] ? reveal[i]! : null;
|
||||
if (sol) cls.push(ch === '0' ? 'sol' : 'wrong');
|
||||
else if (bad.has(i)) cls.push('bad');
|
||||
if (playing && i === sel) cls.push('sel');
|
||||
else if (s !== '0' && ch === s) cls.push('same');
|
||||
else if (glow === i || (b.hintAt === i && playing)) cls.push('hint');
|
||||
else if (playing && (r === rowOf(sel) || c === colOf(sel) || boxOf(i) === boxOf(sel))) cls.push('peer');
|
||||
if (fresh.has(i)) cls.push('sd-pop');
|
||||
if (glow === i) cls.push('sd-glow');
|
||||
const shown = sol ?? (ch !== '0' ? ch : null);
|
||||
return (
|
||||
<div key={i} className={cls.join(' ')} data-i={i} data-v={ch} data-r={r} data-c={c} data-given={given(i)} data-bad={bad.has(i)} aria-hidden>
|
||||
{shown ? (
|
||||
<span className="d">{shown}</span>
|
||||
) : b.notes[i] ? (
|
||||
<span className="sd-notes">
|
||||
{DIGITS.map((n) => (
|
||||
<span key={n} className={s !== '0' && String(n) === s ? 'on' : undefined}>
|
||||
{b.notes[i]! & (1 << n) ? n : ''}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<RaceNotes v={v} mine={mine} failText="" />
|
||||
</div>
|
||||
{showPad && (
|
||||
<div className="sd-pad" role="group" aria-label="숫자 패드">
|
||||
<div className="sd-digits">
|
||||
{DIGITS.map((n, k) => {
|
||||
const rest = 9 - counts[k]!;
|
||||
return (
|
||||
<button
|
||||
key={n}
|
||||
type="button"
|
||||
className="sd-key"
|
||||
data-n={n}
|
||||
data-done={rest <= 0}
|
||||
data-memo={memo}
|
||||
disabled={!playing}
|
||||
aria-label={`${memo ? '메모 ' : ''}${n}, ${Math.max(0, rest)}개 남음`}
|
||||
onClick={() => enter(n)}
|
||||
>
|
||||
{n}
|
||||
<small aria-hidden>{Math.max(0, rest)}</small>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div className="sd-tools">
|
||||
<button type="button" className="sd-tool" disabled={!playing} onClick={erase}>
|
||||
⌫ 지우기
|
||||
</button>
|
||||
<button type="button" className="sd-tool" aria-pressed={memo} onClick={toggleMemo}>
|
||||
✏️ 메모 {memo ? '켬' : '끔'}
|
||||
</button>
|
||||
{v.options.hints && (
|
||||
<button type="button" className="sd-tool" disabled={!playing} onClick={hint}>
|
||||
💡 힌트
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{mine && playing && (
|
||||
<div className="rc-acts">
|
||||
<GiveUp act={act} />
|
||||
</div>
|
||||
)}
|
||||
{!phone && showPad && <p className="rc-keys">칸 클릭 또는 화살표로 고르고 1~9 넣기 · Backspace·Delete·0 지우기 · N·스페이스 메모 켜고 끄기 · 같은 숫자를 다시 누르면 지워요</p>}
|
||||
{phone && showPad && <p className="rc-keys">칸을 누르고 아래 숫자를 눌러요 · 같은 숫자를 다시 누르면 지워요</p>}
|
||||
{reveal && v.phase === 'ended' && <p className="rc-keys">초록 숫자 = 정답(빈칸이었거나 틀린 칸)</p>}
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const diffInfo = (d: Difficulty) => `${DIFFICULTIES[d].name} · ${DIFFICULTIES[d].givens}`;
|
||||
|
||||
function SudokuSide(props: BoardProps<SudokuView>) {
|
||||
const o = props.view.options;
|
||||
return <RaceSide v={props.view} me={props.me} players={props.players} title="스도쿠" info={`${diffInfo(o.difficulty)} · 힌트 ${o.hints ? '있음' : '없음'}`} />;
|
||||
}
|
||||
|
||||
function statusText(v: SudokuView, me: string | null, players: Record<string, PublicUser>): string {
|
||||
return raceStatusText(v, me, players, { countdown: '곧 시작해요! 가로·세로·상자에 1~9를 한 번씩 넣어요', playing: '가로·세로·3×3 상자마다 1~9가 한 번씩 · 빈칸을 모두 맞게 채워요', failed: '' });
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<SudokuOptions>) {
|
||||
return (
|
||||
<div className="stack" style={{ gap: 16 }}>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>난이도</strong>
|
||||
<Seg
|
||||
label="난이도"
|
||||
value={o.difficulty}
|
||||
options={(Object.keys(DIFFICULTIES) as Difficulty[]).map((d) => [d, DIFFICULTIES[d].name])}
|
||||
onChange={(difficulty) => onChange({ ...o, difficulty })}
|
||||
/>
|
||||
<span className="small muted">
|
||||
처음부터 있는 {DIFFICULTIES[o.difficulty].givens}
|
||||
{o.difficulty === 'easy' ? ' · 차근차근 하나씩 찾으면 풀려요' : ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>힌트</strong>
|
||||
<Seg
|
||||
label="힌트"
|
||||
value={o.hints}
|
||||
options={[
|
||||
[true, '있음'],
|
||||
[false, '없음'],
|
||||
]}
|
||||
onChange={(hints) => onChange({ ...o, hints })}
|
||||
/>
|
||||
<span className="small muted">{o.hints ? '[💡 힌트]로 한 칸씩 맞는 숫자를 받을 수 있어요. 쓴 횟수는 결과에 남아요.' : '힌트 없이 풀어요.'}</span>
|
||||
</div>
|
||||
<TimeLimitOption value={o.timeLimitSec} choices={[600, 1200, 1800, 3600]} onChange={(timeLimitSec) => onChange({ ...o, timeLimitSec: timeLimitSec as SudokuOptions['timeLimitSec'] })} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function optionsSummary(o: SudokuOptions): string {
|
||||
return `${DIFFICULTIES[o.difficulty].name} · 힌트 ${o.hints ? '있음' : '없음'} · 제한 시간 ${limitLabel(o.timeLimitSec)}`;
|
||||
}
|
||||
|
||||
function Rules({ options }: { options?: SudokuOptions }) {
|
||||
const d = options?.difficulty ?? 'easy';
|
||||
return (
|
||||
<div className="stack">
|
||||
<p>
|
||||
9×9 판의 <strong>가로줄·세로줄·굵은 선 3×3 상자</strong>마다 1부터 9까지가 <strong>한 번씩</strong> 들어가게 빈칸을 채워요. 모두 <strong>똑같은 판</strong>을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수
|
||||
있어요. 답은 딱 하나뿐인 판만 나와요.
|
||||
</p>
|
||||
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
|
||||
<MiniSudoku rows={['53.', '6*9', 'b87']} notes={{ 2: '14', 4: '14' }} size={26} />
|
||||
<span>굵은 숫자는 처음부터 있던 것, 파란 숫자는 내가 넣은 것, 작은 숫자는 메모예요.</span>
|
||||
</div>
|
||||
<p>
|
||||
칸을 고르고 숫자를 넣어요. 맞는지는 알려 주지 않지만(종이처럼), 같은 줄·칸·상자에 같은 숫자가 겹치면 빨갛게 보여요. [메모]를 켜면 후보 숫자를 작게 적어 둘 수 있고, 숫자를 넣으면 같은 줄·칸·상자의 그 숫자 메모는
|
||||
저절로 지워져요. {options?.hints === false ? '이 방은 힌트가 없어요.' : '[💡 힌트]를 누르면 빈칸이나 틀린 칸 하나를 맞는 숫자로 채워 줘요(쓴 횟수는 결과에 남아요).'}
|
||||
</p>
|
||||
<p>
|
||||
여럿이면 <strong>가장 먼저 다 맞게 채운 사람</strong>이 이기고, 아무도 못 풀면 많이 채운 사람이 이겨요. 제한 시간은 {limitLabel(options ? options.timeLimitSec : 1800)}이고, 지금 난이도는 {diffInfo(d)}예요.
|
||||
</p>
|
||||
<p>PC: 칸을 클릭하거나 화살표로 고르고 1~9, Backspace로 지우기, N이나 스페이스로 메모. 휴대폰: 칸을 누르고 아래 숫자 버튼을 눌러요.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const ui: GameUI<SudokuView, SudokuOptions> = {
|
||||
Board: SudokuBoardView,
|
||||
Side: SudokuSide,
|
||||
statusText,
|
||||
liveStatus: true,
|
||||
isMyTurn: raceIsMyTurn,
|
||||
Options,
|
||||
optionsSummary,
|
||||
Rules,
|
||||
quickStart,
|
||||
helpNow,
|
||||
};
|
||||
|
||||
export default ui;
|
||||
24
apps/web/src/games/sudoku/quick.tsx
Normal file
24
apps/web/src/games/sudoku/quick.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
/** 스도쿠 30초 규칙 요약 (docs/07 §5). Small grids drawn with the game's own look. */
|
||||
import type { QuickCard } from '../types';
|
||||
import { MiniSudoku } from './art';
|
||||
|
||||
export const quickStart: QuickCard[] = [
|
||||
{
|
||||
pic: <MiniSudoku rows={['53.', '6.9', '.87']} size={30} />,
|
||||
alt: '굵은 선 3×3 상자 하나에 숫자 몇 개가 처음부터 들어 있어요',
|
||||
title: '1~9를 한 번씩',
|
||||
text: '가로줄·세로줄·3×3 상자마다 1~9가 한 번씩 들어가게 빈칸을 채워요. 모두 똑같은 판을 각자 풀어요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniSudoku rows={['53.', '6*9', 'b87']} notes={{ 2: '14', 4: '14' }} size={30} />,
|
||||
alt: '고른 칸이 파랗게 표시되고, 내가 넣은 숫자는 파란색, 빈칸에는 작은 메모가 있어요',
|
||||
title: '칸을 고르고 숫자',
|
||||
text: '칸을 누르고 아래 숫자를 눌러요. [메모]를 켜면 작은 후보 숫자로 적어 둘 수 있어요.',
|
||||
},
|
||||
{
|
||||
pic: <MiniSudoku rows={['53.', '6i9', '.87']} bad={[4, 5]} size={30} />,
|
||||
alt: '같은 줄에 9가 두 번 들어가 두 칸이 빨갛게 보여요',
|
||||
title: '겹치면 빨강',
|
||||
text: '같은 줄·상자에 같은 숫자가 겹치면 빨갛게 보여요. 다 맞게 채우면 끝! 여럿이면 가장 먼저 푼 사람이 이겨요.',
|
||||
},
|
||||
];
|
||||
@@ -36,6 +36,11 @@ export const GAME_ICON: Record<string, string> = {
|
||||
'six-nimmt': '🐮',
|
||||
gemblo: '💠',
|
||||
typing: '⌨️',
|
||||
minesweeper: '💣',
|
||||
shisen: '🀄',
|
||||
solitaire: '♥',
|
||||
sudoku: '🧮',
|
||||
nonogram: '🧩',
|
||||
'hot-streak': '🏁',
|
||||
tichu: '🐉',
|
||||
'case-file': '🔍',
|
||||
@@ -50,4 +55,5 @@ export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
|
||||
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue', 'gemblo', 'castles-of-burgundy'] },
|
||||
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code', 'six-nimmt', 'tichu'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple', 'typing', 'hot-streak', 'case-file'] },
|
||||
{ key: 'solo', label: '혼자·퍼즐', ids: ['minesweeper', 'shisen', 'solitaire', 'sudoku', 'nonogram', 'apple', 'typing', 'yacht', 'blackjack', 'case-file', 'castles-of-burgundy'] },
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user