/** 지뢰찾기 화면 (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) { 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>(new Set()); const [announce, setAnnounce] = useState(''); const svgRef = useRef(null); const press = useRef<{ i: number; x: number; y: number; timer: ReturnType | null; long: boolean; button: number } | null>(null); const prev = useRef(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(); 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 (
); } 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) => { if (!playing) return; const i = cellAt(e); setCursor(i); const p = { i, x: e.clientX, y: e.clientY, timer: null as ReturnType | 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) => { 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) => { 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) => { const step: Record = { 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 (
💣 {b.mines - b.flags} {mine && v.phase === 'playing' && ( )}
{ 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 ; })} {focused && playing && }
{mine && playing && (
)} {!phone && mine && v.phase !== 'ended' &&

왼쪽 클릭: 열기(숫자는 주변 한꺼번에) · 오른쪽 클릭: 깃발 · 키보드: 화살표 + 스페이스, F 깃발

} {phone && mine && playing &&

누르기: {flagMode ? '깃발' : '열기'} · 길게 누르기: {flagMode ? '열기' : '깃발'} · 숫자를 누르면 주변을 한꺼번에 열어요

}

{announce}

); } const levelInfo = (l: Level) => `${LEVELS[l].name} ${LEVELS[l].rows}×${LEVELS[l].cols} · 지뢰 ${LEVELS[l].mines}`; function MinesSide(props: BoardProps) { return ; } function statusText(v: MinesweeperView, me: string | null, players: Record): string { return raceStatusText(v, me, players, { countdown: '곧 시작해요! 숫자를 보고 지뢰를 피해 칸을 열어요', playing: '숫자는 주변 8칸의 지뢰 수예요 · 지뢰 없는 칸을 모두 열어요', failed: FAIL }); } function Options({ value: o, onChange }: OptionsProps) { return (
난이도 [l, LEVELS[l].name])} onChange={(level) => onChange({ ...o, level })} /> {levelInfo(o.level)}
onChange({ ...o, timeLimitSec: timeLimitSec as MinesweeperOptions['timeLimitSec'] })} />
); } function optionsSummary(o: MinesweeperOptions): string { return `${levelInfo(o.level)} · 제한 시간 ${limitLabel(o.timeLimitSec)}`; } function Rules({ options }: { options?: MinesweeperOptions }) { const level = options?.level ?? 'beginner'; return (

판 아래에 지뢰가 숨어 있어요. 지뢰가 없는 칸을 모두 열면 이겨요. 모두 똑같은 판을 각자 자기 화면에서 동시에 풀어요. 혼자서도 할 수 있어요.

연 칸의 숫자 = 그 칸을 둘러싼 8칸에 있는 지뢰 수

시작할 때 지뢰가 없는 한 곳이 모두에게 똑같이 열려 있어요. 숫자를 보고 지뢰가 확실한 칸에는 깃발을 꽂고, 안전한 칸을 열어요. 주변이 비어 있는 칸(0)을 열면 이어진 칸이 한꺼번에 열려요. 깃발 수가 숫자와 같아진 숫자 칸을 누르면 남은 주변 칸을 한꺼번에 열어요(깃발이 틀렸으면 지뢰가 터져요).

지뢰를 밟으면 그 판은 끝이에요. 여럿이면 가장 먼저 다 연 사람이 이기고, 아무도 못 열면 연 칸이 많은 사람이 이겨요(지뢰를 밟은 사람도 그때까지 연 칸으로 셈). 제한 시간은{' '} {limitLabel(options ? options.timeLimitSec : 600)}이고, 지금 난이도는 {levelInfo(level)}이에요.

PC: 왼쪽 클릭 열기, 오른쪽 클릭 깃발. 휴대폰: 누르면 열기, 길게 누르면 깃발(위의 [⛏ 칸 열기] 버튼으로 바꿀 수 있어요). 키보드: 화살표로 옮기고 스페이스로 열기, F로 깃발.

); } const ui: GameUI = { Board: MinesBoard, Side: MinesSide, statusText, liveStatus: true, isMyTurn: raceIsMyTurn, Options, optionsSummary, Rules, quickStart, helpNow, }; export default ui;