/** 바둑 화면 (docs/games/baduk.md §9). */ import { useEffect, useMemo, useRef, useState } from 'react'; import type { BadukOptions, BadukView, Pt, ScoreBreakdown } from '@bg/games/baduk'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar, ConfirmSheet, Sheet } from '../../components/ui'; import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; import { BOARD_MOTION_CSS, useAnimOver, useMoveDiff } from '../board-motion'; import { reducedMotion, useBanner } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; type Color = 'black' | 'white'; const COLOR_KO: Record = { black: '흑', white: '백' }; const COLS = 'ABCDEFGHJKLMNOPQRST'; const label = (size: number, p: Pt) => `${COLS[p.x]}${size - p.y}`; const other = (c: Color): Color => (c === 'black' ? 'white' : 'black'); const ILLEGAL_KO = { suicide: '둘 곳의 활로가 없어 둘 수 없어요(자충수).', ko: '패는 바로 되따낼 수 없어요. 다른 곳에 한 수 두고 오세요.', superko: '같은 모양이 반복되어 둘 수 없어요.', } as const; function stars(size: number): Pt[] { if (size === 9) return [{ x: 2, y: 2 }, { x: 6, y: 2 }, { x: 2, y: 6 }, { x: 6, y: 6 }, { x: 4, y: 4 }]; if (size === 13) return [{ x: 3, y: 3 }, { x: 9, y: 3 }, { x: 3, y: 9 }, { x: 9, y: 9 }, { x: 6, y: 6 }]; const s = [3, 9, 15]; return s.flatMap((x) => s.map((y) => ({ x, y }))); } /** Points like "흑 2집 반" (territory) or "1.5점" (area). */ function fmtScore(n: number, method: 'territory' | 'area'): string { if (method === 'area') return String(n); const whole = Math.floor(n); const half = n - whole >= 0.5; return half ? (whole === 0 ? '반' : `${whole}.5`) : String(whole); } /** Stones taken off the board: a few small clicks as they are picked up into the lid. */ function captureSound(count: number) { for (let k = 0; k < Math.min(count, 6); k++) { tone(2100 + (k % 3) * 260, 28, 'triangle', 0.06, 150 + k * 55); noise(25, 0.05, 150 + k * 55, 'highpass', 4500); } } function Stone({ color, cx, cy, r, ghost }: { color: Color; cx: number; cy: number; r: number; ghost?: boolean }) { return ( {!ghost && } {color === 'black' ? ( ) : ( )} ); } type MarkMode = 'dead' | 'seki'; /** Territory marks pop in from the top-left corner outwards when counting starts (scoring / the result). */ const BADUK_CSS = ` .bd-own { transform-box: fill-box; transform-origin: center; animation: bd-own .32s cubic-bezier(.3, 1.5, .5, 1) both; animation-delay: var(--d, 0ms); } @keyframes bd-own { from { opacity: 0; transform: scale(.2); } } `; /** * A number counting up from 0 when `live` (the game ended on screen); the final value right away otherwise or with * reduced motion. Put it inside an aria-hidden element next to the final value for screen readers. */ function CountUp({ to, live }: { to: number; live: boolean }) { const animate = live && !reducedMotion(); const [shown, setShown] = useState(animate ? 0 : null); useEffect(() => { if (!animate) return setShown(null); let raf = 0; const t0 = performance.now(); const step = (t: number) => { const k = Math.min(1, (t - t0) / 1000); setShown(k < 1 ? Math.floor(to * (1 - (1 - k) ** 3)) : null); if (k < 1) raf = requestAnimationFrame(step); }; raf = requestAnimationFrame(step); return () => cancelAnimationFrame(raf); }, [to, animate]); return <>{shown ?? to}; } function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps) { const n = v.size; const myTurn = v.phase === 'playing' && v.myColor === v.turn; const marking = v.phase === 'scoring' && v.myColor !== null; const [mode, setMode] = useState('dead'); const [preview, setPreview] = useState(null); const [hover, setHover] = useState(null); const [cursor, setCursor] = useState({ x: (n - 1) >> 1, y: (n - 1) >> 1 }); const [announce, setAnnounce] = useState(''); const [bubble, setBubble] = useState<{ p: Pt; text: string } | null>(null); const [kbd, setKbd] = useState(false); const [changed, setChanged] = useState>(new Set()); const svgRef = useRef(null); const prevCount = useRef(v.moveCount); const prevDead = useRef | null>(null); const [banner, showBanner] = useBanner(); // When counting started on screen (scoring or the result): the territory marks pop in for a moment after that. const counted = useRef<{ phase: string; at: number }>({ phase: v.phase, at: 0 }); if (counted.current.phase !== v.phase) counted.current = { phase: v.phase, at: v.phase === 'playing' ? 0 : Date.now() }; const ownAnim = counted.current.at > 0; const ownStagger = ownAnim && Date.now() - counted.current.at < 1500; const illegal = useMemo(() => new Map(v.illegalPoints.map((p) => [p.y * n + p.x, p.reason])), [v.illegalPoints, n]); // Dead stones: the live marks while scoring, or (after the game) stones owned by the other colour. const dead = useMemo(() => { if (v.scoring) return new Set(v.scoring.dead.map((p) => p.y * n + p.x)); const own = v.result?.score?.ownership; const out = new Set(); if (own) v.board.forEach((c, i) => c !== 0 && own[i] !== c && out.add(i)); return out; }, [v.scoring, v.result, v.board, n]); const seki = useMemo(() => new Set((v.scoring?.seki ?? []).map((p) => p.y * n + p.x)), [v.scoring?.seki, n]); // Board before the last move: the new stone sets down and captures fade only for moves seen live; // 무르기 lifts the taken-back stone and puts captured stones back. const { before, forward } = useMoveDiff(v.board, v.moveCount); const fresh = !!before && forward; const undone = before && !forward ? before.flatMap((c, i) => (c !== 0 && v.board[i] === 0 ? [{ i, color: (c === 1 ? 'black' : 'white') as Color }] : [])) : []; const [goneOver, goneEnd] = useAnimOver(v.moveCount); const restored = new Set(before && !forward ? v.board.flatMap((c, i) => (c !== 0 && before[i] === 0 ? [i] : [])) : []); // Move sounds and announcements (mine, the opponent's and the computer's). useEffect(() => { if (v.moveCount > prevCount.current) { const m = v.moves[v.moves.length - 1]!; if (m.pt) { sfx.stone(); if (m.captured > 0) { captureSound(m.captured); haptic(30); } setAnnounce(`${COLOR_KO[m.color]}이 ${label(n, m.pt)}에 두었어요.${m.captured ? ` 돌 ${m.captured}개를 따냈어요.` : ''}`); } else { // 패스: a soft knock on the board edge (the second pass shows the counting banner instead). tone(330, 90, 'sine', 0.1); noise(50, 0.05, 0, 'lowpass', 700); setAnnounce(`${COLOR_KO[m.color]}이 패스했어요.`); if (v.phase === 'playing') showBanner('패스', 'dark', `${COLOR_KO[m.color]}이 이번 차례를 쉬어요`); } if (myTurn) haptic(40); } else if (v.moveCount < prevCount.current) sfx.whoosh(); prevCount.current = v.moveCount; setPreview(null); setBubble(null); }, [v.moveCount]); // eslint-disable-line react-hooks/exhaustive-deps // Counting starts / the game ends (for both players and watchers). const prevPhase = useRef(v.phase); useEffect(() => { const before = prevPhase.current; prevPhase.current = v.phase; if (before === v.phase) return; if (v.phase === 'scoring') { showBanner('계가', 'blue', '두 사람 모두 패스했어요. 사석을 확인해요'); sfx.whoosh(); } else if (v.phase === 'finished' && v.result) { const w = v.result.winner; showBanner(w ? `${COLOR_KO[w]} 승리!` : '무승부', w ? (w === v.myColor ? 'gold' : v.myColor ? 'dark' : 'blue') : 'green', v.result.summaryKo); } }, [v.phase]); // eslint-disable-line react-hooks/exhaustive-deps // Highlight groups whose dead/alive mark just changed (e.g. by the opponent). useEffect(() => { if (!v.scoring) { prevDead.current = null; return; } const before = prevDead.current; prevDead.current = dead; if (!before) return; const diff = new Set(); for (const i of dead) if (!before.has(i)) diff.add(i); for (const i of before) if (!dead.has(i)) diff.add(i); if (diff.size === 0) return; sfx.click(); setChanged(diff); const t = setTimeout(() => setChanged(new Set()), 2500); return () => clearTimeout(t); }, [dead]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (!bubble) return; const t = setTimeout(() => setBubble(null), 2500); return () => clearTimeout(t); }, [bubble]); const at = (p: Pt) => v.board[p.y * n + p.x]; const canPlace = (p: Pt) => myTurn && !pending && at(p) === 0 && !illegal.has(p.y * n + p.x); const canMark = (p: Pt) => marking && !pending && (mode === 'dead' ? at(p) !== 0 : at(p) === 0); const place = (p: Pt) => { act({ type: 'place', x: p.x, y: p.y }); setPreview(null); setHover(null); }; const mark = (p: Pt) => act(mode === 'dead' ? { type: 'toggleDead', x: p.x, y: p.y } : { type: 'toggleSeki', x: p.x, y: p.y }); const tap = (p: Pt, mouse: boolean) => { setCursor(p); if (marking) { if (canMark(p)) mark(p); else if (mode === 'dead' && at(p) === 0) setBubble({ p, text: '돌을 눌러 사석/생석을 바꿔요. 빈 곳은 [빅 표시]에서 눌러요.' }); return; } if (!myTurn || at(p) !== 0) return; const why = illegal.get(p.y * n + p.x); if (why) { haptic([30, 30, 30]); sfx.bad(); setBubble({ p, text: ILLEGAL_KO[why] }); setAnnounce(ILLEGAL_KO[why]); return; } if (mouse || !tapConfirm) { if (canPlace(p)) place(p); return; } if (preview && preview.x === p.x && preview.y === p.y) place(p); else setPreview(p); }; const pointToCell = (e: React.PointerEvent): Pt | null => { const svg = svgRef.current; if (!svg) return null; const pt = svg.createSVGPoint(); pt.x = e.clientX; pt.y = e.clientY; const loc = pt.matrixTransform(svg.getScreenCTM()!.inverse()); const x = Math.round(loc.x); const y = Math.round(loc.y); return x >= 0 && y >= 0 && x < n && y < n ? { x, y } : null; }; const onKey = (e: React.KeyboardEvent) => { setKbd(true); const d: Record = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }; if (d[e.key]) { e.preventDefault(); setCursor((c) => ({ x: Math.min(n - 1, Math.max(0, c.x + d[e.key]![0])), y: Math.min(n - 1, Math.max(0, c.y + d[e.key]![1])) })); } else if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); tap(cursor, true); } }; // Ownership marks: live preview while marking, final result after the game. const score: ScoreBreakdown | undefined = v.scoring?.preview ?? v.result?.score; const ghost = preview ?? (hover && canPlace(hover) ? hover : null); const hoverMark = marking && hover && canMark(hover) ? hover : null; const lastColor: Color | null = v.lastMove ? (at(v.lastMove) === 1 ? 'black' : 'white') : null; const pad = 0.95; return (
{ if (e.pointerType !== 'mouse' || !(myTurn || marking)) return; const p = pointToCell(e); if (p?.x !== hover?.x || p?.y !== hover?.y) setHover(p); }} onPointerLeave={() => setHover(null)} onPointerUp={(e) => { setKbd(false); const p = pointToCell(e); if (p) tap(p, e.pointerType === 'mouse'); }} tabIndex={0} role="grid" aria-label={`바둑판 ${n}줄. 방향키로 움직이고 Enter로 ${marking ? '표시를 바꿉니다' : '둡니다'}. 현재 위치 ${label(n, cursor)}`} onKeyDown={onKey} > {Array.from({ length: n }, (_, i) => ( ))} {Array.from({ length: n }, (_, i) => ( {COLS[i]} {COLS[i]} {n - i} {n - i} ))} {stars(n).map((p) => ( ))} {/* Ko / superko points for the mover (suicide points are explained on click only). */} {myTurn && v.illegalPoints .filter((p) => p.reason !== 'suicide') .map((p) => )} {v.board.map((c, i) => { if (c === 0) return null; const color: Color = c === 1 ? 'black' : 'white'; const x = i % n; const y = Math.floor(i / n); const isDead = dead.has(i); const isLast = fresh && v.lastMove !== null && i === v.lastMove.y * n + v.lastMove.x; return ( ); })} {/* Stones just captured are lifted off one by one; a stone taken back by 무르기 fades. */} {fresh && !goneOver && v.phase === 'playing' && v.lastCaptured.map((p, k, all) => ( ))} {!goneOver && undone.map(({ i, color }) => ( ))} {/* Territory / area marks (small squares) and seki marks. */} {score && score.ownership.map((o, i) => { if (o === 0 || (v.board[i] !== 0 && !dead.has(i))) return null; const x = i % n; const y = Math.floor(i / n); return ( ); })} {[...seki].map((i) => ( ))} {[...dead].map((i) => ( ))} {[...changed].map((i) => ( ))} {v.lastMove && lastColor && ( {fresh && } )} {myTurn && v.atariWarnings.map((p) => ( ))} {ghost && v.myColor && } {hoverMark && } {(myTurn || marking) && kbd && } {bubble && }

{announce}

{banner} {bubble && (
{label(n, bubble.p)}: {bubble.text}
)} {marking && (

{mode === 'dead' ? '죽은 돌 묶음을 누르면 사석(✕)으로 바뀌고, 다시 누르면 살아 있는 돌로 돌아와요.' : '빅(세키) 안의 빈 곳을 누르면 ◆로 표시돼요. 한국·일본식 계산에서는 빅 안의 집을 세지 않아요.'}

)} {preview && myTurn && (
)}
); } // ---------------------------------------------------------------- side panel function ScoreTable({ score, heading }: { score: ScoreBreakdown; heading?: boolean }) { const t = score.method === 'territory'; const rows: [string, string | number, string | number][] = t ? [ ['집', score.black.territory, score.white.territory], ['따낸 돌(사석 포함)', score.black.captures, score.white.captures], ['덤', '-', score.white.komi], ] : [ ['판 위 살아 있는 돌', score.black.stones, score.white.stones], ['영역(빈 곳)', score.black.territory, score.white.territory], ['덤', '-', score.white.komi], ...(score.white.handicapComp ? [['치석 보정', '-', score.white.handicapComp] as [string, string, number]] : []), ]; return ( {rows.map(([k, b, w]) => ( ))}
{heading ? (t ? '집 계산' : '영역 계산') : ''} ● 흑 ○ 백
{k} {b} {w}
합계 {score.black.total} {score.white.total}
); } function ScoringPanel({ view: v, act, pending }: { view: BadukView; act: (a: unknown) => void; pending: boolean }) { const [confirmResume, setConfirmResume] = useState(false); const sc = v.scoring!; const p = sc.preview; const lead = p.diff === 0 ? '동점' : `${p.diff > 0 ? '흑' : '백'} ${fmtScore(Math.abs(p.diff), p.method)}${p.method === 'territory' ? '집' : '점'} 앞섬`; const mine = v.myColor; return (
사석 확인

대국이 멈췄어요. 판 위의 죽은 돌을 눌러 ✕ 표시를 맞춘 뒤 두 사람 모두 동의하면 계가가 끝나요. 처음 표시는 컴퓨터의 추정이라 틀릴 수 있어요.

흑 {p.black.total} : 백 {p.white.total}
{lead}
● 흑 {sc.agreed.black ? '✅ 동의함' : '⏳ 확인 중'} ○ 백 {sc.agreed.white ? '✅ 동의함' : '⏳ 확인 중'}
{mine && (
)} {confirmResume && ( act({ type: 'resumePlay' })} onClose={() => setConfirmResume(false)} /> )}
); } function BadukSide({ view: v, me, players, act, pending, deadline }: BoardProps) { const [confirm, setConfirm] = useState(null); const incoming = v.phase === 'playing' && v.myColor ? v.undo.pending && v.undo.pending.by !== v.myColor ? 'undo' : v.draw.pendingBy && v.draw.pendingBy !== v.myColor ? 'draw' : null : null; const outgoing = v.myColor && (v.undo.pending?.by === v.myColor || v.draw.pendingBy === v.myColor); const undoLeft = v.myColor ? v.undo.remaining[v.myColor] : null; const opp: Color = v.myColor === 'white' ? 'black' : 'white'; const mine: Color = v.myColor ?? 'black'; const myTurn = v.phase === 'playing' && v.myColor === v.turn; const last = v.moves[v.moves.length - 1]; const oppPassed = myTurn && last && !last.pt && last.color !== v.myColor; // The final score counts up only when the game ended while this screen was open. const ended = useRef({ phase: v.phase, live: false }); if (ended.current.phase !== v.phase) ended.current = { phase: v.phase, live: v.phase === 'finished' }; return ( <> {oppPassed && (
상대가 패스했어요. 끝내려면 나도 패스하세요. 더 둘 곳이 있으면 계속 둬도 돼요.
)} {v.phase === 'scoring' && } {v.phase === 'finished' && v.result?.score && (
{v.result.summaryKo}
{`흑 ${v.result.score.black.total} : 백 ${v.result.score.white.total}`} 흑 : 백
)} {v.phase === 'playing' && v.myColor && (
{v.undo.allowed && ( )} {v.draw.allowed && ( )}
)} {v.phase === 'scoring' && v.myColor && ( )} {outgoing && (
상대의 답을 기다리는 중…
)} {incoming && ( {}} label="상대의 요청">

{incoming === 'undo' ? `상대가 ${v.undo.pending!.plies}수 무르기를 요청했어요` : '상대가 무승부를 제안했어요'}

{incoming === 'undo' ? '수락하면 돌과 따낸 돌이 그 전으로 돌아가요.' : '수락하면 이 판은 무승부로 끝나요.'}

)} {confirm === 'pass' && ( 0 ? '상대도 패스했으니, 패스하면 대국이 멈추고 사석 확인으로 넘어가요.' : '이번 차례에 돌을 두지 않고 넘겨요.'} confirm="패스하기" onConfirm={() => act({ type: 'pass' })} onClose={() => setConfirm(null)} /> )} {confirm === 'resign' && ( act({ type: 'resign' })} onClose={() => setConfirm(null)} /> )} {confirm === 'draw' && act({ type: 'offerDraw' })} onClose={() => setConfirm(null)} />} ); } function MoveList({ view: v }: { view: BadukView }) { const ref = useRef(null); useEffect(() => { ref.current?.scrollTo({ top: ref.current.scrollHeight }); }, [v.moveCount]); if (v.moveCount === 0) return null; return (
기보 ({v.moveCount}수)
    {v.moves.map((m, i) => (
  1. {i + 1}. {m.color === 'black' ? '●' : '○'} {m.pt ? label(v.size, m.pt) : '패스'} {m.captured ? ×{m.captured} : null}
  2. ))}
); } const mmss = (ms: number) => { const s = Math.max(0, Math.ceil(ms / 1000)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; }; function PlayerBar({ view: v, color, players, deadline, me }: { view: BadukView; color: Color; players: Record; deadline: number | null; me: string | null }) { const id = v.players[color]; const u = players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const }; const active = v.phase === 'playing' && v.turn === color; const now = useServerNow(250); const c = v.clock; const elapsed = active ? Math.max(0, now - c.turnStartedAt) : 0; const mine = id === me; let clock: React.ReactNode = null; let periodSecLeft: number | null = null; if (c.kind === 'byoyomi') { const main = c.mainMs[color]; if (elapsed < main) { clock = {mmss(main - elapsed)}; } else { const periodMs = c.periodSec * 1000; const over = elapsed - main; const used = Math.floor(over / periodMs); const left = Math.max(0, c.periodsLeft[color] - used); periodSecLeft = active ? Math.ceil((periodMs - (over % periodMs)) / 1000) : c.periodSec; const urgent = active && periodSecLeft <= 10; clock = ( {periodSecLeft}초 {Array.from({ length: c.periods }, (_, i) => ( ● ))} ); } } else if (c.kind === 'fischer') { const ms = c.mainMs[color] - elapsed; clock = ( {mmss(ms)} ); } // Byoyomi countdown beeps for my own clock (last 5 seconds of a period). const beeped = useRef(null); useEffect(() => { if (!active || !mine || periodSecLeft === null || periodSecLeft > 5 || beeped.current === periodSecLeft) return; beeped.current = periodSecLeft; sounds.warn(); }, [periodSecLeft, active, mine]); const urgentBorder = active && periodSecLeft !== null && periodSecLeft <= 10; return (
{u.nickname} {mine && (나)}
{COLOR_KO[color]} · 따낸 돌 {v.captures[color]} {color === 'white' && v.rules.komi ? ` · 덤 ${v.rules.komi}` : ''} {active ? ' · 두는 중' : ''} {v.phase === 'scoring' && v.scoring?.agreed[color] ? ' · 동의함' : ''}
{clock}
); } function statusText(v: BadukView, _me: string | null, players: Record): string { if (v.phase === 'finished') return v.result?.summaryKo ?? '대국이 끝났어요'; if (v.phase === 'scoring') { if (v.myColor && !v.scoring!.agreed[v.myColor]) return '사석을 확인하고 [동의]를 눌러 주세요'; if (v.myColor) return '상대가 사석을 확인하고 있어요…'; return '사석 확인 중이에요'; } if (v.myColor && v.undo.pending && v.undo.pending.by !== v.myColor) return '상대가 무르기를 요청했어요'; if (v.myColor && v.draw.pendingBy && v.draw.pendingBy !== v.myColor) return '상대가 무승부를 제안했어요'; if (v.myColor === v.turn) { if (v.consecutivePasses > 0) return '상대가 패스했어요. 끝내려면 패스하세요'; if (v.atariWarnings.length) return `내 차례예요 (${COLOR_KO[v.turn]}). 단수에 몰린 돌이 있어요!`; return `내 차례예요 (${COLOR_KO[v.turn]}). 둘 곳을 눌러 주세요`; } const nick = players[v.players[v.turn]]?.nickname ?? COLOR_KO[v.turn]; return v.myColor ? `${nick}님이 생각 중이에요…` : `${nick}님(${COLOR_KO[v.turn]}) 차례예요`; } // ---------------------------------------------------------------- options function Seg({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) { return (
{options.map(([k, l]) => ( ))}
); } type TC = BadukOptions['timeControl']; const TIME_PRESETS: [string, string, Partial][] = [ ['auto', '판 크기에 맞춤 + 초읽기 30초×3', { kind: 'byoyomi', mainSecAuto: true, periodSec: 30, periods: 3 }], ['b5', '5분 + 30초×3', { kind: 'byoyomi', mainSecAuto: false, mainSec: 300, periodSec: 30, periods: 3 }], ['b10', '10분 + 30초×3', { kind: 'byoyomi', mainSecAuto: false, mainSec: 600, periodSec: 30, periods: 3 }], ['b30', '30분 + 60초×3', { kind: 'byoyomi', mainSecAuto: false, mainSec: 1800, periodSec: 60, periods: 3 }], ['f', '피셔 10분 + 10초', { kind: 'fischer', mainSecAuto: false, mainSec: 600, incSec: 10 }], ['none', '시간 제한 없음', { kind: 'none' }], ]; function timeKey(tc: TC): string { if (tc.kind === 'none') return 'none'; if (tc.kind === 'fischer') return tc.mainSec === 600 && tc.incSec === 10 && !tc.mainSecAuto ? 'f' : 'custom'; if (tc.mainSecAuto && tc.periodSec === 30 && tc.periods === 3) return 'auto'; const hit = TIME_PRESETS.find(([k, , p]) => k.startsWith('b') && !tc.mainSecAuto && p.mainSec === tc.mainSec && p.periodSec === tc.periodSec && p.periods === tc.periods); return hit ? hit[0] : 'custom'; } const DEFAULT_MAIN: Record = { 9: 180, 13: 600, 19: 1200 }; function timeLabel(o: BadukOptions): string { const tc = o.timeControl; if (tc.kind === 'none') return '시간 제한 없음'; const main = tc.mainSecAuto ? DEFAULT_MAIN[o.boardSize]! : tc.mainSec; const m = Math.floor(main / 60); const mainLabel = main === 0 ? '' : `${m ? `${m}분` : ''}${main % 60 ? ` ${main % 60}초` : ''}`.trim(); if (tc.kind === 'fischer') return `${mainLabel} + 수당 ${tc.incSec}초`; return `${mainLabel ? `${mainLabel} + ` : ''}${tc.periodSec}초×${tc.periods}`; } function komiOf(o: BadukOptions): number { if (!o.komiAuto) return o.komi; if (o.handicap > 0) return 0.5; return o.scoring === 'area' ? 7.5 : 6.5; } function Options({ value: o, onChange }: OptionsProps) { const [more, setMore] = useState(false); const set = (patch: Partial) => onChange({ ...o, ...patch }); const setTc = (patch: Partial) => set({ timeControl: { ...o.timeControl, ...patch } }); const maxHandicap = o.boardSize === 9 ? 5 : 9; const handicaps = ([0, 2, 3, 4, 5, 6, 7, 8, 9] as const).filter((h) => h <= maxHandicap); const tk = timeKey(o.timeControl); return (
판 크기 set({ boardSize, handicap: boardSize === 9 && o.handicap > 5 ? 5 : o.handicap })} />
계가 방식 set({ scoring })} />
접바둑 [h, h === 0 ? '맞바둑' : `${h}점`] as [BadukOptions['handicap'], string])} onChange={(handicap) => set({ handicap })} /> {o.handicap > 0 && 흑(하수)이 치석 {o.handicap}개를 미리 놓고, 백이 먼저 둬요. 덤은 0.5집이에요.}
시간 [k, l] as [string, string]), ...(tk === 'custom' ? [['custom', `${timeLabel(o)}(관리자 설정)`] as [string, string]] : []), ]} onChange={(k) => { const preset = TIME_PRESETS.find((p) => p[0] === k); if (preset) setTc(preset[2]); }} />
흑백 정하기 set({ colorAssignment })} />
{more && ( <>
덤 (지금 {komiOf(o)}) set({ komiAuto: k === 'auto' })} /> {!o.komiAuto && ( { const n = Math.round(Number(e.target.value) * 2) / 2; if (Number.isFinite(n)) set({ komi: Math.max(-10, Math.min(10, n)) }); }} aria-label="덤" /> )}
패 규칙 set({ koRule })} />
{o.timeControl.kind === 'byoyomi' && (
초읽기 setTc({ periodSec })} /> setTc({ periods })} />
)}
무르기 set({ undo })} />
무승부 제안 set({ drawOffer: k === 'on' })} />
사석 확인 제한 시간 set({ scoringDeadlineSec })} />
)}
); } function optionsSummary(o: BadukOptions): string { return [ o.scoring === 'territory' ? '집 계산' : '영역 계산', `${o.boardSize}줄`, o.handicap ? `${o.handicap}점 접바둑` : `덤 ${komiOf(o)}`, timeLabel(o), ].join(' · '); } function Rules({ options }: { options?: BadukOptions }) { const scoring = options?.scoring ?? 'territory'; const koRule = options?.koRule ?? 'positionalSuperko'; return (

흑과 백이 번갈아 판의 교차점에 돌을 하나씩 놓아요. 흑이 먼저 둬요(접바둑이면 흑이 치석을 미리 놓고 백이 먼저 둬요). 한 번 놓은 돌은 움직이지 않아요.

따내기: 돌에 상하좌우로 맞닿은 빈 점을 활로라고 해요. 상하좌우로 붙은 같은 색 돌은 한 덩어리로 활로를 함께 써요. 상대 돌 덩어리의 활로를 모두 막으면 그 돌을 판에서 들어내고, 따낸 돌로 세어요. 활로가 하나만 남은 상태를 단수라고 해요.

자충수 금지: 놓는 순간 내 돌의 활로가 없어지는 자리에는 둘 수 없어요. 단, 그 수로 상대 돌을 따내서 활로가 생기면 둘 수 있어요.

패: 돌 하나를 서로 번갈아 따낼 수 있는 모양에서는, 따인 쪽이 바로 되따낼 수 없어요. 다른 곳에 한 수 둔 뒤에 되따낼 수 있어요. {koRule === 'positionalSuperko' ? ' 이 방은 판 전체 모양이 이전과 똑같아지는 수를 모두 금지해요(동형 반복 금지).' : ' 이 방은 한국식이라 같은 국면이 세 번 나오면(삼패 등) 무승부로 끝나요.'} {' '}둘 수 없는 패 자리는 빨간 네모로 보여 줘요.

끝내기: 더 둘 곳이 없으면 패스해요. 두 사람이 연달아 패스하면 대국이 멈추고 사석 확인을 해요. 판에서 죽은 돌을 눌러 ✕ 표시를 맞추고, 두 사람 모두 [동의]하면 점수가 나와요. 의견이 다르면 [이의 – 대국 재개]로 돌아가 직접 둬서 결론을 내요.

{scoring === 'territory' ? (

집 계산(한국·일본식): 내 돌로만 둘러싼 빈 점(집) + 따낸 돌(사석 포함)이 내 점수예요. 백은 먼저 둔 흑의 이득을 메우려고 덤을 더 받아요. 빅(서로 잡을 수 없이 공배를 나눠 사는 모양) 안의 집은 세지 않아요.

) : (

영역 계산(중국식): 판 위의 살아 있는 내 돌 + 내 돌로만 둘러싼 빈 점이 내 점수예요. 따낸 돌은 세지 않으니 끝내기 전에 공배(양쪽 사이의 빈 점)를 메운 뒤 패스하세요. 백은 덤을 더 받고, 접바둑이면 치석 수만큼 더 받아요.

)}

점수가 높은 쪽이 이겨요. 덤이 0.5 단위면 비기는 일이 없어요. 언제든 기권(불계패)할 수 있어요. 처음이라면 9줄 판으로 시작해 보세요.

); } const ui: GameUI = { Board: BadukBoard, Side: BadukSide, statusText, isMyTurn: (v, me) => { if (!v.myColor || v.players[v.myColor] !== me) return false; if (v.phase === 'playing') return v.turn === v.myColor; if (v.phase === 'scoring') return !v.scoring!.agreed[v.myColor]; return false; }, Options, optionsSummary, Rules, quickStart, helpNow, }; export default ui;