Files
joke-app/apps/web/src/games/minesweeper/index.tsx
EJClaw 1b9acb9fc1 새 게임 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>
2026-11-24 14:29:01 +09:00

322 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/** 지뢰찾기 화면 (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;