- 카드 게임: 펠트가 남는 높이를 채우고 손패·가운데 더미·자리 크기가 화면에 따라 커짐 - 판 게임: 체스·바둑·오목 등은 높이를 다 쓰고, 장기·쿼리도·젬블로는 넓은 화면에서 조작판을 판 옆으로 - 섯다: 자리를 판 크기에 맞춘 타원 위에 고르게 두고, 많을 때 자리 크기를 줄여 8명에서도 겹치지 않게 - 바퀴벌레 포커 6명·야단법석 달리기 5명 선수 뽑기가 PC에서 넘치지 않게 - 휴대폰·태블릿(1100px 아래) 배치는 그대로 - layout-survey: 컴퓨터 넣기 버튼 기다림, 넘친 높이(px) 표시 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
927 lines
45 KiB
TypeScript
927 lines
45 KiB
TypeScript
/** 체스 화면 (docs/games/chess.md §9). Legal moves come from the server view; the client has no rule code. */
|
||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||
import type { ChessOptions, ChessView, LegalMove } from '@bg/games/chess';
|
||
import type { PublicUser } from '@bg/shared/lite';
|
||
import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||
import { haptic } from '../../lib/feedback';
|
||
import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion';
|
||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||
import { CHESS_PIECE_CREDIT, pieceSrc } from './art';
|
||
import { chessCues, chessMotion } from './fx';
|
||
import { helpNow } from './help';
|
||
import { nopeSound, pickSound, playChess } from './sound';
|
||
import { quickStart } from './quick';
|
||
|
||
type Color = 'white' | 'black';
|
||
type PieceType = 'k' | 'q' | 'r' | 'b' | 'n' | 'p';
|
||
type Promo = 'q' | 'r' | 'b' | 'n';
|
||
const COLOR_KO: Record<Color, string> = { white: '백', black: '흑' };
|
||
const PIECE_KO: Record<PieceType, string> = { k: '킹', q: '퀸', r: '룩', b: '비숍', n: '나이트', p: '폰' };
|
||
const FILES = 'abcdefgh';
|
||
const other = (c: Color): Color => (c === 'white' ? 'black' : 'white');
|
||
|
||
// ---------------------------------------------------------------- squares
|
||
|
||
/** Board array index (a8 = 0 … h1 = 63) for a square name. */
|
||
const idxOf = (sq: string) => (8 - Number(sq[1])) * 8 + FILES.indexOf(sq[0]!);
|
||
const sqOf = (file: number, rank: number) => `${FILES[file]}${rank + 1}`;
|
||
/** Display cell (0..7 from the top-left) for a square, given which colour sits at the bottom. */
|
||
function cellOf(sq: string, bottom: Color): { x: number; y: number } {
|
||
const f = FILES.indexOf(sq[0]!);
|
||
const r = Number(sq[1]) - 1;
|
||
return bottom === 'white' ? { x: f, y: 7 - r } : { x: 7 - f, y: r };
|
||
}
|
||
function squareAt(x: number, y: number, bottom: Color): string {
|
||
return bottom === 'white' ? sqOf(x, 7 - y) : sqOf(7 - x, y);
|
||
}
|
||
const pieceAt = (v: ChessView, sq: string) => v.board[idxOf(sq)] ?? null;
|
||
const colorOfPiece = (p: string): Color => (p === p.toUpperCase() ? 'white' : 'black');
|
||
|
||
// ---------------------------------------------------------------- pieces (Cburnett artwork, 100×100 box)
|
||
|
||
/**
|
||
* One piece in a 100×100 box. The board draws that box at 0.92 of a square, 0.04 in from the corner; the artwork has
|
||
* its own margin, so the image is grown by that inset and fills exactly one square.
|
||
*/
|
||
function PieceShape({ type, color }: { type: PieceType; color: Color }) {
|
||
return <image href={pieceSrc(type, color)} x={-4.35} y={-4.35} width={108.7} height={108.7} />;
|
||
}
|
||
|
||
/** A piece as a standalone inline icon (player bars, picker, rules). */
|
||
function PieceIcon({ type, color, size = 22 }: { type: PieceType; color: Color; size?: number }) {
|
||
return (
|
||
<svg
|
||
className={color === 'black' ? 'ch-icon-dark' : undefined}
|
||
width={size}
|
||
height={size}
|
||
viewBox="0 0 100 100"
|
||
aria-hidden
|
||
style={{ display: 'inline-block', verticalAlign: 'middle' }}
|
||
>
|
||
<PieceShape type={type} color={color} />
|
||
</svg>
|
||
);
|
||
}
|
||
|
||
function letterPiece(p: string): { type: PieceType; color: Color } {
|
||
return { type: p.toLowerCase() as PieceType, color: colorOfPiece(p) };
|
||
}
|
||
|
||
// ---------------------------------------------------------------- board
|
||
|
||
const LIGHT = '#efd9b4';
|
||
const DARK = '#b38660';
|
||
|
||
/** Slide time for a piece moving `cells` squares (short hops quicker, long ones a little slower). */
|
||
const slideSec = (cells: number) => Math.min(0.34, 0.2 + cells * 0.022);
|
||
|
||
/** Chess-only motion on top of BOARD_MOTION_CSS: the piece settling after it lands, check pulse, highlight fade-in. */
|
||
const CHESS_CSS = `
|
||
.ch-land { transform-box: fill-box; transform-origin: 50% 90%; animation: ch-land .2s ease-out both; animation-delay: var(--ch-delay, 0s); }
|
||
@keyframes ch-land { 0% { transform: scale(1); } 40% { transform: scale(1.07, .95); } 100% { transform: scale(1); } }
|
||
.ch-check { transform-box: fill-box; transform-origin: center; animation: ch-check .5s ease-out both; animation-delay: var(--ch-delay, 0s); }
|
||
@keyframes ch-check { 0% { opacity: 0; transform: scale(.4); } 45% { opacity: 1; transform: scale(1.18); } 70% { transform: scale(.94); } 100% { opacity: 1; transform: scale(1); } }
|
||
.ch-fade { animation: ch-fade .3s ease-out both; }
|
||
@keyframes ch-fade { from { opacity: 0; } }
|
||
:root[data-theme='dark'] .ch-icon-dark { filter: drop-shadow(0 0 .6px #e5e7eb) drop-shadow(0 0 .6px #e5e7eb); }
|
||
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .ch-icon-dark { filter: drop-shadow(0 0 .6px #e5e7eb) drop-shadow(0 0 .6px #e5e7eb); } }
|
||
/* PC: the board takes the whole play-area height minus the row(s) that can show under it (--ch-rows). */
|
||
@media (min-width: 1100px) { .board-wrap.ch-fit { max-width: min(100%, calc(var(--play-h) - var(--ch-rows, 0px))); } }
|
||
`;
|
||
|
||
function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
|
||
const myTurn = v.phase === 'playing' && v.myColor !== null && v.myColor === v.turn;
|
||
const [flip, setFlip] = useState(false);
|
||
const bottom: Color = v.myColor ?? (flip ? 'black' : 'white');
|
||
const [selected, setSelected] = useState<string | null>(null);
|
||
const [hover, setHover] = useState<string | null>(null);
|
||
const [cursor, setCursor] = useState<{ x: number; y: number }>({ x: 4, y: 6 });
|
||
const [kbd, setKbd] = useState(false);
|
||
const [promo, setPromo] = useState<{ from: string; to: string } | null>(null);
|
||
const [dragPos, setDragPos] = useState<{ x: number; y: number } | null>(null);
|
||
const drag = useRef<{ from: string; wasSelected: boolean; sx: number; sy: number; moved: boolean } | null>(null);
|
||
const [announce, setAnnounce] = useState('');
|
||
const svgRef = useRef<SVGSVGElement>(null);
|
||
const prevCount = useRef(v.moves.length);
|
||
/** Move number my drag-and-drop will create: that piece already sits where I let go, so it does not slide. */
|
||
const dropped = useRef(-1);
|
||
|
||
const byFrom = useMemo(() => {
|
||
const m = new Map<string, LegalMove[]>();
|
||
for (const mv of v.legalMoves ?? []) m.set(mv.from, [...(m.get(mv.from) ?? []), mv]);
|
||
return m;
|
||
}, [v.legalMoves]);
|
||
const targets = selected ? (byFrom.get(selected) ?? []) : [];
|
||
const showDots = v.hints !== 'off';
|
||
|
||
// What moved since the last change (mine, the opponent's or the computer's): slides, captured pieces, sounds.
|
||
// Only a single step forward animates; a page load, an undo or several moves at once just show the position.
|
||
const n = v.moves.length;
|
||
const diff = useMoveDiff({ board: v.board, n }, n);
|
||
const step = diff.forward && diff.before?.n === n - 1;
|
||
const motion = step ? chessMotion(diff.before!.board, v.board, v.lastMove) : null;
|
||
const myDrop = step && dropped.current === n;
|
||
const slides = new Map<string, { dx: number; dy: number; sec: number }>();
|
||
if (motion && !myDrop) {
|
||
for (const sl of motion.slides) {
|
||
const a = cellOf(sl.from, bottom);
|
||
const b = cellOf(sl.sq, bottom);
|
||
slides.set(sl.sq, { dx: a.x - b.x, dy: a.y - b.y, sec: slideSec(Math.hypot(a.x - b.x, a.y - b.y)) });
|
||
}
|
||
}
|
||
/** When the moved piece lands (sounds and the settle wait for it). */
|
||
const landSec = v.lastMove ? (slides.get(v.lastMove.to)?.sec ?? (slides.size ? Math.max(...[...slides.values()].map((x) => x.sec)) : 0)) : 0;
|
||
|
||
useEffect(() => {
|
||
if (v.moves.length !== prevCount.current) {
|
||
const last = v.moves[v.moves.length - 1];
|
||
playChess(chessCues(prevCount.current, v.moves), landSec * 1000);
|
||
if (v.moves.length > prevCount.current && last) {
|
||
setAnnounce(`${COLOR_KO[last.color]}: ${last.san}${v.checkSquare ? ', 체크!' : ''}`);
|
||
if (myTurn) haptic(40);
|
||
} else setAnnounce('수를 물렀어요.');
|
||
}
|
||
prevCount.current = v.moves.length;
|
||
setSelected(null);
|
||
setPromo(null);
|
||
}, [v.moves.length]); // eslint-disable-line react-hooks/exhaustive-deps
|
||
|
||
const send = (from: string, to: string, promotion?: Promo, viaDrop = false) => {
|
||
dropped.current = viaDrop ? v.moves.length + 1 : -1;
|
||
act({ type: 'move', from, to, ...(promotion ? { promotion } : {}) });
|
||
setSelected(null);
|
||
setPromo(null);
|
||
setHover(null);
|
||
};
|
||
|
||
const attempt = (from: string, to: string, viaDrop = false) => {
|
||
const mv = (byFrom.get(from) ?? []).find((m) => m.to === to);
|
||
if (!mv || pending) {
|
||
if (!mv && viaDrop) nopeSound();
|
||
return;
|
||
}
|
||
// After the promotion sheet the piece is back on its square, so that move slides normally.
|
||
if (mv.promotion && !v.autoQueen) setPromo({ from, to });
|
||
else send(from, to, undefined, viaDrop);
|
||
};
|
||
|
||
const ownMovable = (sq: string) => myTurn && byFrom.has(sq);
|
||
|
||
const click = (sq: string, wasSelected: boolean) => {
|
||
if (!myTurn) return;
|
||
if (selected && targets.some((m) => m.to === sq)) return attempt(selected, sq);
|
||
const p = pieceAt(v, sq);
|
||
if (p && colorOfPiece(p) === v.myColor) {
|
||
if (!byFrom.has(sq)) {
|
||
setSelected(null);
|
||
setAnnounce(`${PIECE_KO[p.toLowerCase() as PieceType]}은 지금 움직일 수 없어요.`);
|
||
haptic([30, 30, 30]);
|
||
nopeSound();
|
||
return;
|
||
}
|
||
if (!wasSelected && selected !== sq) pickSound();
|
||
setSelected(wasSelected ? null : sq);
|
||
return;
|
||
}
|
||
if (selected) {
|
||
setAnnounce('그 칸으로는 갈 수 없어요.');
|
||
haptic([30, 30, 30]);
|
||
nopeSound();
|
||
}
|
||
setSelected(null);
|
||
};
|
||
|
||
const toSvg = (e: React.PointerEvent<SVGSVGElement>) => {
|
||
const svg = svgRef.current;
|
||
if (!svg) return null;
|
||
const pt = svg.createSVGPoint();
|
||
pt.x = e.clientX;
|
||
pt.y = e.clientY;
|
||
return pt.matrixTransform(svg.getScreenCTM()!.inverse());
|
||
};
|
||
const cellAt = (e: React.PointerEvent<SVGSVGElement>): string | null => {
|
||
const p = toSvg(e);
|
||
if (!p) return null;
|
||
const x = Math.floor(p.x);
|
||
const y = Math.floor(p.y);
|
||
return x >= 0 && y >= 0 && x < 8 && y < 8 ? squareAt(x, y, bottom) : null;
|
||
};
|
||
|
||
const onKey = (e: React.KeyboardEvent) => {
|
||
setKbd(true);
|
||
const d: Record<string, [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] };
|
||
const step = d[e.key];
|
||
if (step) {
|
||
e.preventDefault();
|
||
setCursor((c) => ({ x: Math.min(7, Math.max(0, c.x + step[0])), y: Math.min(7, Math.max(0, c.y + step[1])) }));
|
||
} else if (e.key === 'Enter' || e.key === ' ') {
|
||
e.preventDefault();
|
||
const sq = squareAt(cursor.x, cursor.y, bottom);
|
||
click(sq, selected === sq);
|
||
} else if (e.key === 'Escape') setSelected(null);
|
||
};
|
||
|
||
const cell = (sq: string) => cellOf(sq, bottom);
|
||
const lastFrom = v.lastMove ? cell(v.lastMove.from) : null;
|
||
const lastTo = v.lastMove ? cell(v.lastMove.to) : null;
|
||
const check = v.checkSquare ? cell(v.checkSquare) : null;
|
||
const hoverTarget = hover && selected && targets.some((m) => m.to === hover) ? cell(hover) : null;
|
||
const dragging = drag.current?.moved && dragPos ? drag.current.from : null;
|
||
const cursorSq = squareAt(cursor.x, cursor.y, bottom);
|
||
|
||
return (
|
||
<div
|
||
className="board-wrap stack ch-fit"
|
||
// Room for what can show under the board: the castling hint (2 lines in 960) for players, [판 돌리기] for watchers.
|
||
style={{ gap: 10, '--ch-rows': v.myColor ? (v.chess960Index === null ? 'calc(1.35rem + 10px)' : 'calc(2.7rem + 10px)') : 'calc(var(--tap) + 10px)' } as React.CSSProperties}
|
||
>
|
||
<style>{BOARD_MOTION_CSS + CHESS_CSS}</style>
|
||
<svg
|
||
ref={svgRef}
|
||
viewBox="-0.02 -0.02 8.04 8.04"
|
||
style={{
|
||
width: '100%',
|
||
display: 'block',
|
||
borderRadius: 8,
|
||
boxShadow: 'var(--shadow)',
|
||
touchAction: 'none',
|
||
userSelect: 'none',
|
||
cursor: dragging ? 'grabbing' : hover && (ownMovable(hover) || hoverTarget) ? 'pointer' : 'default',
|
||
}}
|
||
tabIndex={0}
|
||
role="grid"
|
||
aria-label={`체스판. ${v.myColor ? `나는 ${COLOR_KO[v.myColor]}이에요. ` : ''}방향키로 칸을 고르고 Enter로 기물을 집거나 놓아요. 현재 칸 ${cursorSq}${pieceAt(v, cursorSq) ? ` ${COLOR_KO[colorOfPiece(pieceAt(v, cursorSq)!)]} ${PIECE_KO[pieceAt(v, cursorSq)!.toLowerCase() as PieceType]}` : ''}`}
|
||
onKeyDown={onKey}
|
||
onPointerDown={(e) => {
|
||
setKbd(false);
|
||
const sq = cellAt(e);
|
||
// Chess960: with the king picked, my own rook is a castling target, not a new selection.
|
||
if (!sq || !ownMovable(sq) || pending || (selected && targets.some((m) => m.to === sq))) return;
|
||
drag.current = { from: sq, wasSelected: selected === sq, sx: e.clientX, sy: e.clientY, moved: false };
|
||
if (selected !== sq) pickSound();
|
||
setSelected(sq);
|
||
svgRef.current?.setPointerCapture(e.pointerId);
|
||
}}
|
||
onPointerMove={(e) => {
|
||
const sq = cellAt(e);
|
||
if (sq !== hover) setHover(sq);
|
||
const d = drag.current;
|
||
if (!d) return;
|
||
if (!d.moved && Math.hypot(e.clientX - d.sx, e.clientY - d.sy) > 6) d.moved = true;
|
||
if (d.moved) setDragPos(toSvg(e));
|
||
}}
|
||
onPointerLeave={() => setHover(null)}
|
||
onPointerUp={(e) => {
|
||
const sq = cellAt(e);
|
||
const d = drag.current;
|
||
drag.current = null;
|
||
setDragPos(null);
|
||
if (d?.moved) {
|
||
if (sq && sq !== d.from) attempt(d.from, sq, true);
|
||
return;
|
||
}
|
||
if (sq) click(sq, d ? d.wasSelected : false);
|
||
}}
|
||
onPointerCancel={() => {
|
||
drag.current = null;
|
||
setDragPos(null);
|
||
}}
|
||
>
|
||
<defs>
|
||
<radialGradient id="chess-check">
|
||
<stop offset="0%" stopColor="#ff2a2a" stopOpacity={0.95} />
|
||
<stop offset="45%" stopColor="#e11d1d" stopOpacity={0.75} />
|
||
<stop offset="100%" stopColor="#a10000" stopOpacity={0} />
|
||
</radialGradient>
|
||
</defs>
|
||
{Array.from({ length: 64 }, (_, i) => {
|
||
const x = i % 8;
|
||
const y = Math.floor(i / 8);
|
||
return <rect key={i} x={x} y={y} width={1} height={1} fill={(x + y) % 2 === 0 ? LIGHT : DARK} />;
|
||
})}
|
||
{lastFrom && lastTo && (
|
||
<g key={`lm${n}`} className={step ? 'ch-fade' : undefined}>
|
||
<rect x={lastFrom.x} y={lastFrom.y} width={1} height={1} fill="#cdd26a" opacity={0.75} />
|
||
<rect x={lastTo.x} y={lastTo.y} width={1} height={1} fill="#aaa23a" opacity={0.6} />
|
||
</g>
|
||
)}
|
||
{selected && <rect x={cell(selected).x} y={cell(selected).y} width={1} height={1} fill="#4f7a28" opacity={0.55} />}
|
||
{v.threatened?.map((sq) => {
|
||
const c = cell(sq);
|
||
return <rect key={`t${sq}`} x={c.x + 0.04} y={c.y + 0.04} width={0.92} height={0.92} fill="none" stroke="#f59e0b" strokeWidth={0.07} strokeDasharray="0.14 0.08" />;
|
||
})}
|
||
{check && (
|
||
<rect
|
||
key={`ck${n}`}
|
||
className={step ? 'ch-check' : undefined}
|
||
style={{ '--ch-delay': `${landSec}s` } as React.CSSProperties}
|
||
x={check.x}
|
||
y={check.y}
|
||
width={1}
|
||
height={1}
|
||
fill="url(#chess-check)"
|
||
/>
|
||
)}
|
||
{/* Coordinates: files on the bottom row, ranks on the left column. */}
|
||
{Array.from({ length: 8 }, (_, i) => (
|
||
<g key={`c${i}`} fontSize={0.2} fontWeight={700} style={{ pointerEvents: 'none' }}>
|
||
<text x={i + 0.94} y={7.94} textAnchor="end" fill={(i + 7) % 2 === 0 ? DARK : LIGHT}>
|
||
{squareAt(i, 7, bottom)[0]}
|
||
</text>
|
||
<text x={0.06} y={i + 0.22} fill={i % 2 === 0 ? DARK : LIGHT}>
|
||
{squareAt(0, i, bottom)[1]}
|
||
</text>
|
||
</g>
|
||
))}
|
||
{hoverTarget && <rect x={hoverTarget.x} y={hoverTarget.y} width={1} height={1} fill="#4f7a28" opacity={0.35} />}
|
||
{/* Captured pieces (the en passant pawn too) shrink away where they stood, under the piece that took them. */}
|
||
{motion?.gone.map((g) => {
|
||
const c = cell(g.sq);
|
||
return (
|
||
<g key={`x${n}-${g.sq}`} transform={`translate(${c.x} ${c.y})`} style={{ pointerEvents: 'none' }}>
|
||
<g className="bm-gone" style={{ animationDelay: `${Math.max(0, landSec - 0.12)}s` }}>
|
||
<g transform="translate(0.04 0.04) scale(0.0092)">
|
||
<PieceShape {...letterPiece(g.piece)} />
|
||
</g>
|
||
</g>
|
||
</g>
|
||
);
|
||
})}
|
||
{v.board.map((p, i) => {
|
||
if (!p) return null;
|
||
const sq = sqOf(i % 8, 7 - Math.floor(i / 8));
|
||
if (sq === dragging) return null;
|
||
const c = cell(sq);
|
||
const { type, color } = letterPiece(p);
|
||
const sl = slides.get(sq);
|
||
// The moved piece (and the castling rook) is keyed by the move number so its animation runs once per move.
|
||
const moved = step && (!!sl || v.lastMove?.to === sq);
|
||
return (
|
||
<g key={moved ? `${sq}-m${n}` : sq} transform={`translate(${c.x} ${c.y})`} style={{ pointerEvents: 'none' }}>
|
||
<g
|
||
className={sl ? 'bm-slide' : undefined}
|
||
style={sl ? ({ '--bm-dx': `${sl.dx}px`, '--bm-dy': `${sl.dy}px`, '--bm-dur': `${sl.sec}s` } as React.CSSProperties) : undefined}
|
||
>
|
||
<g className={moved ? 'ch-land' : undefined} style={moved ? ({ '--ch-delay': `${sl?.sec ?? 0}s` } as React.CSSProperties) : undefined}>
|
||
<g transform="translate(0.04 0.04) scale(0.0092)">
|
||
<PieceShape type={type} color={color} />
|
||
</g>
|
||
</g>
|
||
</g>
|
||
</g>
|
||
);
|
||
})}
|
||
{showDots &&
|
||
targets.map((m) => {
|
||
const c = cell(m.to);
|
||
if (m.castle) {
|
||
// Castling target (king's square or, in 960, the own rook): gold frame + label, so it is never mistaken for a capture.
|
||
return (
|
||
<g key={`m${m.to}`} style={{ pointerEvents: 'none' }}>
|
||
<rect x={c.x + 0.06} y={c.y + 0.06} width={0.88} height={0.88} rx={0.12} fill="rgba(234,179,8,0.25)" stroke="#a16207" strokeWidth={0.07} />
|
||
<rect x={c.x + 0.1} y={c.y + 0.68} width={0.8} height={0.24} rx={0.08} fill="#a16207" />
|
||
<text x={c.x + 0.5} y={c.y + 0.8} textAnchor="middle" dominantBaseline="central" fontSize={0.16} fontWeight={800} fill="#fff">
|
||
캐슬링
|
||
</text>
|
||
</g>
|
||
);
|
||
}
|
||
const capture = !!pieceAt(v, m.to) || (pieceAt(v, m.from)?.toLowerCase() === 'p' && m.from[0] !== m.to[0]);
|
||
return capture ? (
|
||
<circle key={`m${m.to}`} cx={c.x + 0.5} cy={c.y + 0.5} r={0.45} fill="none" stroke="rgba(20,40,10,0.45)" strokeWidth={0.08} style={{ pointerEvents: 'none' }} />
|
||
) : (
|
||
<circle key={`m${m.to}`} cx={c.x + 0.5} cy={c.y + 0.5} r={0.16} fill="rgba(20,40,10,0.38)" style={{ pointerEvents: 'none' }} />
|
||
);
|
||
})}
|
||
{check && (
|
||
<g transform={`translate(${check.x + 0.5} ${check.y < 1 ? check.y + 1.22 : check.y - 0.22})`} style={{ pointerEvents: 'none' }}>
|
||
<g key={`cl${n}`} className={step ? 'anim-pop' : undefined} style={{ animationDelay: `${landSec + 0.08}s`, transformBox: 'fill-box', transformOrigin: 'center' }}>
|
||
<rect x={-0.42} y={-0.17} width={0.84} height={0.34} rx={0.12} fill="#b91c1c" />
|
||
<text textAnchor="middle" dominantBaseline="central" fontSize={0.2} fontWeight={800} fill="#fff">
|
||
체크!
|
||
</text>
|
||
</g>
|
||
</g>
|
||
)}
|
||
{dragging && dragPos && (
|
||
<g transform={`translate(${dragPos.x - 0.55} ${dragPos.y - 0.6}) scale(0.011)`} style={{ pointerEvents: 'none' }}>
|
||
<PieceShape {...letterPiece(pieceAt(v, dragging)!)} />
|
||
</g>
|
||
)}
|
||
{kbd && <rect x={cursor.x + 0.03} y={cursor.y + 0.03} width={0.94} height={0.94} fill="none" stroke="var(--focus)" strokeWidth={0.06} />}
|
||
</svg>
|
||
<p className="sr-only" aria-live="polite">
|
||
{announce}
|
||
</p>
|
||
{myTurn && selected && targets.some((m) => m.castle) && (showDots || v.chess960Index !== null) && (
|
||
<p className="small" style={{ margin: 0, textAlign: 'center' }}>
|
||
{v.chess960Index === null
|
||
? '캐슬링하려면 노란 테두리 칸을 누르세요.'
|
||
: showDots
|
||
? '캐슬링하려면 노란 테두리 칸(내 룩, 또는 킹이 갈 g·c열 칸)을 누르세요.'
|
||
: '캐슬링하려면 내 룩이나 킹이 갈 g·c열 칸을 누르세요.'}
|
||
</p>
|
||
)}
|
||
{!v.myColor && (
|
||
<div className="row" style={{ justifyContent: 'center' }}>
|
||
<button className="btn btn-secondary btn-sm" onClick={() => setFlip(!flip)}>
|
||
⇅ 판 돌리기
|
||
</button>
|
||
</div>
|
||
)}
|
||
{promo && v.myColor && (
|
||
<Sheet onClose={() => setPromo(null)} label="승진할 기물 고르기">
|
||
<h2>어떤 기물로 바꿀까요?</h2>
|
||
<div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 8 }}>
|
||
{(['q', 'r', 'b', 'n'] as const).map((t) => (
|
||
<button
|
||
key={t}
|
||
className={`btn ${t === 'q' ? 'btn-primary' : 'btn-secondary'}`}
|
||
style={{ flexDirection: 'column', padding: 8, minHeight: 96 }}
|
||
autoFocus={t === 'q'}
|
||
onClick={() => send(promo.from, promo.to, t)}
|
||
>
|
||
<PieceIcon type={t} color={v.myColor!} size={t === 'q' ? 60 : 44} />
|
||
<span>{PIECE_KO[t]}</span>
|
||
</button>
|
||
))}
|
||
</div>
|
||
<button className="btn btn-ghost btn-block" onClick={() => setPromo(null)}>
|
||
취소
|
||
</button>
|
||
</Sheet>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- side panel
|
||
|
||
const REASON_HELP: Partial<Record<NonNullable<ChessView['result']>['reason'], string>> = {
|
||
checkmate: '킹이 공격받고 있는데 피할 곳도, 막을 방법도 없어요.',
|
||
stalemate: '체크는 아니지만 둘 수 있는 수가 하나도 없어서 비겼어요.',
|
||
insufficientMaterial: '남은 기물로는 어느 쪽도 체크메이트할 수 없어서 비겼어요.',
|
||
threefold: '같은 국면이 세 번 나와서 비겼어요.',
|
||
fivefold: '같은 국면이 다섯 번 나와서 비겼어요.',
|
||
fiftyMove: '50수 동안 폰 이동도 잡기도 없어서 비겼어요.',
|
||
seventyFiveMove: '75수 동안 폰 이동도 잡기도 없어서 비겼어요.',
|
||
timeoutVsInsufficient: '시간이 다 됐지만 상대도 체크메이트할 기물이 없어서 비겼어요.',
|
||
aborted: '첫 수를 두지 않아 대국이 취소됐어요. 승패는 기록되지 않아요.',
|
||
};
|
||
|
||
function ChessSide({ view: v, me, players, act, pending, deadline }: BoardProps<ChessView>) {
|
||
const [confirm, setConfirm] = useState<null | 'resign' | 'draw' | 'claim'>(null);
|
||
const mine = v.myColor;
|
||
const incoming =
|
||
v.phase === 'playing' && mine
|
||
? v.undo.pending && v.undo.pending.by !== mine
|
||
? 'undo'
|
||
: v.draw.pendingBy && v.draw.pendingBy !== mine
|
||
? 'draw'
|
||
: null
|
||
: null;
|
||
const outgoing = !!mine && (v.undo.pending?.by === mine || v.draw.pendingBy === mine);
|
||
const undoLeft = mine ? v.undo.remaining[mine] : null;
|
||
const top: Color = mine ? other(mine) : 'black';
|
||
const bottom: Color = mine ?? 'white';
|
||
const beforeFirst = !!mine && !v.started[mine];
|
||
const canClaim = v.drawMode === 'fide' && !!v.claimable && !!mine && v.turn === mine;
|
||
// Chess960: castling also as buttons (the king-onto-rook tap is easy to miss).
|
||
const castles = v.chess960Index !== null ? (['king', 'queen'] as const).filter((side) => v.legalMoves?.some((m) => m.castle === side)) : [];
|
||
return (
|
||
<>
|
||
{v.chess960Index !== null && (
|
||
<div className="card small" style={{ padding: '8px 12px' }}>
|
||
<strong>체스960</strong> · 시작 배치 {v.chess960Index}번
|
||
</div>
|
||
)}
|
||
<PlayerBar view={v} color={top} players={players} deadline={deadline} me={me} />
|
||
<PlayerBar view={v} color={bottom} players={players} deadline={deadline} me={me} />
|
||
{v.phase === 'playing' && mine && (
|
||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
|
||
{v.undo.allowed && (
|
||
<button
|
||
className="btn btn-secondary btn-sm"
|
||
disabled={outgoing || !!v.draw.pendingBy || undoLeft === 0 || !v.moves.some((m) => m.color === mine)}
|
||
onClick={() => act({ type: 'requestUndo' })}
|
||
title={undoLeft !== null ? `${undoLeft}번 남음` : '무제한'}
|
||
>
|
||
↩ 무르기{undoLeft !== null ? ` ${undoLeft}` : ''}
|
||
</button>
|
||
)}
|
||
{v.draw.allowed && (
|
||
<button className="btn btn-secondary btn-sm" disabled={outgoing || !!v.undo.pending} onClick={() => setConfirm('draw')}>
|
||
🤝 무승부
|
||
</button>
|
||
)}
|
||
<button className="btn btn-danger btn-sm" onClick={() => setConfirm('resign')}>
|
||
{beforeFirst ? '✕ 대국 취소' : '🏳 기권'}
|
||
</button>
|
||
</div>
|
||
)}
|
||
{castles.length > 0 && (
|
||
<div className="row" style={{ gap: 8 }}>
|
||
{castles.map((side) => (
|
||
<button key={side} className="btn btn-secondary btn-sm" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'castle', side })}>
|
||
{side === 'king' ? '캐슬링: 킹 쪽 (O-O)' : '캐슬링: 퀸 쪽 (O-O-O)'}
|
||
</button>
|
||
))}
|
||
</div>
|
||
)}
|
||
{canClaim && (
|
||
<button className="btn btn-primary" onClick={() => setConfirm('claim')}>
|
||
⚖ 무승부 주장 ({v.claimable === 'threefold' ? '3회 반복' : '50수 규칙'})
|
||
</button>
|
||
)}
|
||
{outgoing && (
|
||
<div className="card row" style={{ justifyContent: 'space-between', padding: 10 }}>
|
||
<span className="small">상대의 답을 기다리는 중…</span>
|
||
<button className="btn btn-ghost btn-sm" onClick={() => act({ type: 'cancelOffer' })}>
|
||
요청 취소
|
||
</button>
|
||
</div>
|
||
)}
|
||
{v.result && REASON_HELP[v.result.reason] && (
|
||
<div className="card" style={{ padding: 12 }}>
|
||
<strong>{v.result.summary}</strong>
|
||
<div className="muted small">{REASON_HELP[v.result.reason]}</div>
|
||
</div>
|
||
)}
|
||
<MoveList view={v} />
|
||
{incoming && (
|
||
<Sheet onClose={() => {}} label="상대의 요청">
|
||
<h2>{incoming === 'undo' ? `상대가 ${v.undo.pending!.plies}수 무르기를 요청했어요` : '상대가 무승부를 제안했어요'}</h2>
|
||
<p className="muted">{incoming === 'undo' ? '수락하면 기물이 되돌아가요. 시계는 되돌아가지 않아요.' : '수락하면 이 판은 무승부로 끝나요. 거절하거나 내가 수를 두면 제안이 사라져요.'}</p>
|
||
<div className="row">
|
||
<button className="btn btn-primary" style={{ flex: 1 }} disabled={pending} onClick={() => act(incoming === 'undo' ? { type: 'respondUndo', accept: true } : { type: 'respondDraw', accept: true })}>
|
||
수락
|
||
</button>
|
||
<button className="btn btn-secondary" style={{ flex: 1 }} disabled={pending} onClick={() => act(incoming === 'undo' ? { type: 'respondUndo', accept: false } : { type: 'respondDraw', accept: false })}>
|
||
거절
|
||
</button>
|
||
</div>
|
||
</Sheet>
|
||
)}
|
||
{confirm === 'resign' &&
|
||
(beforeFirst ? (
|
||
<ConfirmSheet title="대국을 취소할까요?" body="아직 첫 수를 두기 전이라 승패 없이 끝나요." confirm="대국 취소" danger onConfirm={() => act({ type: 'resign' })} onClose={() => setConfirm(null)} />
|
||
) : (
|
||
<ConfirmSheet title="기권할까요?" body="기권하면 이 판은 상대가 이겨요." confirm="기권하기" danger onConfirm={() => act({ type: 'resign' })} onClose={() => setConfirm(null)} />
|
||
))}
|
||
{confirm === 'draw' && <ConfirmSheet title="무승부를 제안할까요?" body="상대가 수락하면 비겨요." confirm="제안하기" onConfirm={() => act({ type: 'offerDraw' })} onClose={() => setConfirm(null)} />}
|
||
{confirm === 'claim' && (
|
||
<ConfirmSheet title="무승부를 주장할까요?" body="규칙에 따라 상대 동의 없이 바로 비겨요." confirm="무승부 주장" onConfirm={() => act({ type: 'claimDraw' })} onClose={() => setConfirm(null)} />
|
||
)}
|
||
</>
|
||
);
|
||
}
|
||
|
||
function MoveList({ view: v }: { view: ChessView }) {
|
||
const ref = useRef<HTMLDivElement>(null);
|
||
useEffect(() => {
|
||
ref.current?.scrollTo({ top: ref.current.scrollHeight });
|
||
}, [v.moves.length]);
|
||
if (v.moves.length === 0) return null;
|
||
// Rows of [white, black]; a game started by black would show "…" first (not possible in standard chess).
|
||
const rows: { no: number; w?: string; b?: string }[] = [];
|
||
for (const m of v.moves) {
|
||
if (m.color === 'white' || rows.length === 0) rows.push({ no: rows.length + 1 });
|
||
rows[rows.length - 1]![m.color === 'white' ? 'w' : 'b'] = m.san;
|
||
}
|
||
const lastIdx = v.moves.length - 1;
|
||
return (
|
||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기보 ({Math.ceil(v.moves.length / 2)}수)</summary>
|
||
<div ref={ref} style={{ marginTop: 8, maxHeight: 180, overflow: 'auto', display: 'grid', gridTemplateColumns: '2.5em 1fr 1fr', gap: '2px 8px', fontVariantNumeric: 'tabular-nums' }}>
|
||
{rows.map((r, i) => (
|
||
<MoveRow key={i} no={r.no} w={r.w} b={r.b} lastW={i * 2 === lastIdx} lastB={i * 2 + 1 === lastIdx} />
|
||
))}
|
||
</div>
|
||
</details>
|
||
);
|
||
}
|
||
|
||
function MoveRow({ no, w, b, lastW, lastB }: { no: number; w?: string; b?: string; lastW: boolean; lastB: boolean }) {
|
||
const cell = (san: string | undefined, last: boolean) => (
|
||
<span className="small" style={{ fontWeight: last ? 800 : 500, background: last ? 'var(--surface-2)' : undefined, borderRadius: 4, padding: '0 4px' }}>
|
||
{san ?? ''}
|
||
</span>
|
||
);
|
||
return (
|
||
<>
|
||
<span className="small muted">{no}.</span>
|
||
{cell(w, lastW)}
|
||
{cell(b, lastB)}
|
||
</>
|
||
);
|
||
}
|
||
|
||
function fmtClock(ms: number): string {
|
||
const clamped = Math.max(0, ms);
|
||
if (clamped < 20_000) return `${Math.floor(clamped / 1000)}.${Math.floor((clamped % 1000) / 100)}`;
|
||
const s = Math.ceil(clamped / 1000);
|
||
const h = Math.floor(s / 3600);
|
||
const m = Math.floor((s % 3600) / 60);
|
||
return h ? `${h}:${String(m).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}` : `${m}:${String(s % 60).padStart(2, '0')}`;
|
||
}
|
||
|
||
function PlayerBar({ view: v, color, players, deadline, me }: { view: ChessView; color: Color; players: Record<string, PublicUser>; 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(100);
|
||
const tc = v.timeControl;
|
||
let clock: React.ReactNode = null;
|
||
if (tc.kind === 'fischer' && active && !v.started[color]) {
|
||
clock = (
|
||
<span className="row" style={{ gap: 6 }}>
|
||
<span className="small muted">첫 수</span>
|
||
<TurnTimer deadline={deadline} totalMs={v.firstMoveSec * 1000} mine={id === me} />
|
||
</span>
|
||
);
|
||
} else if (tc.kind === 'fischer') {
|
||
const ms = v.remainingMs[color] - (active && v.started[color] ? now - v.turnStartedAt : 0);
|
||
const low = ms <= 10_000;
|
||
clock = (
|
||
<span
|
||
style={{
|
||
fontVariantNumeric: 'tabular-nums',
|
||
fontWeight: 800,
|
||
fontSize: '1.35rem',
|
||
padding: '2px 10px',
|
||
borderRadius: 8,
|
||
background: active ? (low ? 'var(--danger)' : 'var(--text)') : 'var(--surface-2)',
|
||
color: active ? 'var(--surface)' : low ? 'var(--danger)' : undefined,
|
||
}}
|
||
role="timer"
|
||
aria-label={`${COLOR_KO[color]} 남은 시간 ${fmtClock(ms)}`}
|
||
>
|
||
{fmtClock(ms)}
|
||
</span>
|
||
);
|
||
}
|
||
const caps = [...v.captured[color]].sort((a, b) => 'qrbnp'.indexOf(a) - 'qrbnp'.indexOf(b));
|
||
const adv = color === 'white' ? v.materialDiff : -v.materialDiff;
|
||
return (
|
||
<div className="card" style={{ padding: '8px 12px', border: `3px solid ${active ? 'var(--primary)' : 'transparent'}`, transition: 'border-color 0.2s' }}>
|
||
<div className="row" style={{ gap: 10 }}>
|
||
<PieceIcon type="k" color={color} size={30} />
|
||
<Avatar user={u} size={32} />
|
||
<div style={{ flex: 1, minWidth: 0 }}>
|
||
<div style={{ fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||
{u.nickname}
|
||
{id === me && <span className="muted small"> (나)</span>}
|
||
</div>
|
||
<div className="muted small">
|
||
{COLOR_KO[color]}
|
||
{active ? ' · 두는 중' : ''}
|
||
</div>
|
||
</div>
|
||
{clock}
|
||
</div>
|
||
{(caps.length > 0 || adv > 0) && (
|
||
<div className="row" style={{ gap: 0, marginTop: 4, minHeight: 20, flexWrap: 'wrap' }} aria-label={`잡은 기물 ${caps.map((c) => PIECE_KO[c as PieceType]).join(', ')}`}>
|
||
{caps.map((c, i) => (
|
||
<PieceIcon key={i} type={c as PieceType} color={other(color)} size={20} />
|
||
))}
|
||
{adv > 0 && <span className="small muted" style={{ marginLeft: 6, fontWeight: 700 }}>+{adv}</span>}
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function statusText(v: ChessView, _me: string | null, players: Record<string, PublicUser>): string {
|
||
if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요';
|
||
const mine = v.myColor;
|
||
if (mine && v.undo.pending && v.undo.pending.by !== mine) return '상대가 무르기를 요청했어요';
|
||
if (mine && v.draw.pendingBy && v.draw.pendingBy !== mine) return '상대가 무승부를 제안했어요';
|
||
if (mine === v.turn) {
|
||
if (v.checkSquare) return '체크! 킹을 지켜야 해요';
|
||
if (v.timeControl.kind === 'fischer' && !v.started[mine]) return `내 차례예요 (${COLOR_KO[mine]}). 첫 수를 ${v.firstMoveSec}초 안에 둬 주세요`;
|
||
if (v.claimable) return '내 차례예요. 무승부를 주장할 수 있어요';
|
||
return `내 차례예요 (${COLOR_KO[mine]}). 움직일 기물을 눌러 주세요`;
|
||
}
|
||
const nick = players[v.players[v.turn]]?.nickname ?? COLOR_KO[v.turn];
|
||
const check = v.checkSquare ? ' (체크)' : '';
|
||
return mine ? `${nick}님이 생각 중이에요…${check}` : `${nick}님(${COLOR_KO[v.turn]}) 차례예요${check}`;
|
||
}
|
||
|
||
// ---------------------------------------------------------------- options
|
||
|
||
function Seg<T extends string | number>({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
|
||
return (
|
||
<div className="segmented">
|
||
{options.map(([k, l]) => (
|
||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||
{l}
|
||
</button>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const TIME_PRESETS: [string, string, ChessOptions['timeControl']][] = [
|
||
['3+2', '3+2 블리츠', { kind: 'fischer', baseMin: 3, incSec: 2 }],
|
||
['5+0', '5+0', { kind: 'fischer', baseMin: 5, incSec: 0 }],
|
||
['5+3', '5+3', { kind: 'fischer', baseMin: 5, incSec: 3 }],
|
||
['10+0', '10+0 래피드', { kind: 'fischer', baseMin: 10, incSec: 0 }],
|
||
['10+5', '10+5', { kind: 'fischer', baseMin: 10, incSec: 5 }],
|
||
['15+10', '15+10', { kind: 'fischer', baseMin: 15, incSec: 10 }],
|
||
['30+0', '30+0 클래식', { kind: 'fischer', baseMin: 30, incSec: 0 }],
|
||
['none', '시간 제한 없음', { kind: 'none', baseMin: 10, incSec: 5 }],
|
||
];
|
||
const timeKey = (tc: ChessOptions['timeControl']) => (tc.kind === 'none' ? 'none' : `${tc.baseMin}+${tc.incSec}`);
|
||
|
||
function Options({ value: o, onChange }: OptionsProps<ChessOptions>) {
|
||
const [more, setMore] = useState(false);
|
||
const set = (patch: Partial<ChessOptions>) => onChange({ ...o, ...patch });
|
||
const key = timeKey(o.timeControl);
|
||
const isPreset = TIME_PRESETS.some((p) => p[0] === key);
|
||
const num = (val: number, min: number, max: number) => Math.min(max, Math.max(min, Math.round(val) || min));
|
||
return (
|
||
<div className="stack" style={{ gap: 16 }}>
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>규칙</strong>
|
||
<Seg value={o.variant ?? 'standard'} options={[['standard', '일반 체스'], ['chess960', '체스960 (첫 줄 무작위)']]} onChange={(variant) => set({ variant })} />
|
||
{o.variant === 'chess960' && <span className="muted small">뒷줄 기물 배치가 960가지 중 하나로 무작위로 정해져요. 외운 수보다 실력으로 겨뤄요.</span>}
|
||
</div>
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>시간 (기본 분 + 한 수마다 추가 초)</strong>
|
||
<Seg
|
||
value={key}
|
||
options={[...TIME_PRESETS.map(([k, l]) => [k, l] as [string, string]), ...(isPreset ? [] : [[key, `${timeLabel(o.timeControl)} (직접 설정)`] as [string, string]])]}
|
||
onChange={(k) => {
|
||
const preset = TIME_PRESETS.find((p) => p[0] === k);
|
||
if (preset) set({ timeControl: preset[2] });
|
||
}}
|
||
/>
|
||
</div>
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>백(먼저 두는 쪽)</strong>
|
||
<Seg
|
||
value={o.colorAssignment}
|
||
options={[['random', '무작위'], ['hostWhite', '방장이 백'], ['hostBlack', '방장이 흑'], ['alternate', '판마다 번갈아']]}
|
||
onChange={(colorAssignment) => set({ colorAssignment })}
|
||
/>
|
||
</div>
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>초보 도움말</strong>
|
||
<Seg value={o.hints} options={[['moves', '갈 수 있는 칸 표시'], ['off', '끄기']]} onChange={(hints) => set({ hints })} />
|
||
</div>
|
||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||
</button>
|
||
{more && (
|
||
<>
|
||
{o.timeControl.kind === 'fischer' && (
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>시간 직접 정하기</strong>
|
||
<div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
|
||
<label className="row" style={{ gap: 6 }}>
|
||
기본
|
||
<input
|
||
className="input"
|
||
type="number"
|
||
min={1}
|
||
max={90}
|
||
value={o.timeControl.baseMin}
|
||
onChange={(e) => set({ timeControl: { ...o.timeControl, baseMin: num(Number(e.target.value), 1, 90) } })}
|
||
style={{ width: 80 }}
|
||
/>
|
||
분
|
||
</label>
|
||
<label className="row" style={{ gap: 6 }}>
|
||
+ 한 수마다
|
||
<input
|
||
className="input"
|
||
type="number"
|
||
min={0}
|
||
max={60}
|
||
value={o.timeControl.incSec}
|
||
onChange={(e) => set({ timeControl: { ...o.timeControl, incSec: num(Number(e.target.value), 0, 60) } })}
|
||
style={{ width: 80 }}
|
||
/>
|
||
초
|
||
</label>
|
||
</div>
|
||
</div>
|
||
)}
|
||
{o.timeControl.kind === 'fischer' && (
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>첫 수 제한 (넘기면 대국 취소)</strong>
|
||
<Seg value={o.firstMoveSec} options={[[15, '15초'], [30, '30초'], [60, '60초']]} onChange={(firstMoveSec) => set({ firstMoveSec })} />
|
||
</div>
|
||
)}
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>3회 반복 · 50수 무승부</strong>
|
||
<Seg value={o.drawMode} options={[['auto', '자동으로 무승부'], ['fide', 'FIDE (주장해야 무승부)']]} onChange={(drawMode) => set({ drawMode })} />
|
||
</div>
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>무르기 (상대 동의)</strong>
|
||
<Seg value={o.undo} options={[['off', '안 씀'], ['1', '1번'], ['3', '3번'], ['unlimited', '무제한']]} onChange={(undo) => set({ undo })} />
|
||
</div>
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>그 밖에</strong>
|
||
<Seg value={o.autoQueen ? 'on' : 'off'} options={[['off', '승진할 때 기물 고르기'], ['on', '승진하면 바로 퀸']]} onChange={(k) => set({ autoQueen: k === 'on' })} />
|
||
<Seg value={o.drawOffer ? 'on' : 'off'} options={[['on', '무승부 제안 허용'], ['off', '무승부 제안 안 함']]} onChange={(k) => set({ drawOffer: k === 'on' })} />
|
||
</div>
|
||
</>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function timeLabel(tc: ChessOptions['timeControl']): string {
|
||
if (tc.kind === 'none') return '시간 제한 없음';
|
||
return `${tc.baseMin}분 + ${tc.incSec}초`;
|
||
}
|
||
|
||
function optionsSummary(o: ChessOptions): string {
|
||
const undo = o.undo === 'off' ? '무르기 없음' : o.undo === 'unlimited' ? '무르기 무제한' : `무르기 ${o.undo}번`;
|
||
return [o.variant === 'chess960' ? '체스960' : '표준', timeLabel(o.timeControl), undo].join(' · ');
|
||
}
|
||
|
||
// ---------------------------------------------------------------- rules
|
||
|
||
const PIECE_RULES: [PieceType, string][] = [
|
||
['k', '가로·세로·대각선으로 한 칸. 공격받는 칸으로는 갈 수 없어요. 잡히면 안 되는 가장 중요한 기물이에요.'],
|
||
['q', '가로·세로·대각선으로 몇 칸이든. 가장 강한 기물이에요(9점).'],
|
||
['r', '가로·세로로 몇 칸이든(5점).'],
|
||
['b', '대각선으로 몇 칸이든. 처음 칸과 같은 색 칸만 다녀요(3점).'],
|
||
['n', "'ㄱ'자(두 칸 + 옆 한 칸)로 움직이고, 다른 기물을 뛰어넘을 수 있어요(3점)."],
|
||
['p', '앞으로 한 칸(처음 자리에서는 두 칸까지). 잡을 때만 대각선 앞으로 한 칸 가요(1점).'],
|
||
];
|
||
|
||
function Rules({ options }: { options?: ChessOptions }) {
|
||
const fide = options?.drawMode === 'fide';
|
||
const c960 = options?.variant === 'chess960';
|
||
return (
|
||
<div className="stack">
|
||
{c960 && (
|
||
<p>
|
||
<strong>체스960</strong>: 뒷줄 기물(킹·퀸·룩·비숍·나이트) 배치가 960가지 중 하나로 무작위로 정해져요. 흑은 백과 똑같이 마주 보게 놓여요. 두 비숍은 서로 다른 색 칸에, 킹은
|
||
두 룩 사이에 있어요. 그 밖의 규칙은 일반 체스와 같아요.
|
||
</p>
|
||
)}
|
||
<p>
|
||
백과 흑이 번갈아 한 수씩 둬요. 백이 먼저 둬요. 상대 <strong>킹</strong>을 공격해서(체크) 어디로도 피할 수 없게 만들면(<strong>체크메이트</strong>) 이겨요.
|
||
내 킹이 공격받게 되는 수는 둘 수 없어요.
|
||
</p>
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
{PIECE_RULES.map(([t, text]) => (
|
||
<div key={t} className="row" style={{ gap: 10, alignItems: 'flex-start' }}>
|
||
<PieceIcon type={t} color="white" size={34} />
|
||
<div>
|
||
<strong>{PIECE_KO[t]}</strong> <span className="muted">{text}</span>
|
||
</div>
|
||
</div>
|
||
))}
|
||
</div>
|
||
{c960 ? (
|
||
<p>
|
||
<strong>캐슬링(체스960)</strong>: 끝나는 자리는 일반 체스와 같아요. 킹 쪽(O-O)은 킹이 g열, 룩이 f열로, 퀸 쪽(O-O-O)은 킹이 c열, 룩이 d열로 가요. 킹과 그 룩이 한 번도
|
||
움직이지 않았고, 둘이 지나가는 칸이 (둘 자신 말고는) 모두 비어 있어야 해요. 체크 중이거나 킹이 지나가는 칸·도착 칸이 공격받으면 안 돼요. 킹을 누른 뒤 노란 테두리 칸(내 룩이나
|
||
g·c열 칸)을 누르거나, [캐슬링] 버튼을 눌러요.
|
||
</p>
|
||
) : (
|
||
<p>
|
||
<strong>캐슬링</strong>: 킹과 룩이 한 번도 움직이지 않았고 사이가 비어 있으면, 킹을 룩 쪽으로 두 칸 옮기고 룩을 킹 너머로 넘겨요. 체크 중이거나 킹이 지나가는 칸·도착 칸이
|
||
공격받으면 안 돼요. 킹을 누르면 캐슬링할 칸도 표시돼요.
|
||
</p>
|
||
)}
|
||
<p>
|
||
<strong>앙파상</strong>: 상대 폰이 처음 자리에서 두 칸 나와 내 폰 바로 옆에 섰다면, 바로 다음 수에 한해 한 칸만 나온 것처럼 대각선으로 잡을 수 있어요.
|
||
</p>
|
||
<p>
|
||
<strong>승진</strong>: 폰이 끝 줄에 닿으면 퀸·룩·비숍·나이트 중 하나로 바꿔요. 보통은 퀸을 골라요.
|
||
</p>
|
||
<p>
|
||
<strong>비기는 경우</strong>: 체크가 아닌데 둘 수가 없을 때(스테일메이트), 남은 기물로 체크메이트가 불가능할 때(예: 킹 대 킹), 같은 국면이 3번 나오거나 50수 동안 폰 이동과 잡기가
|
||
없을 때{fide ? '(이 방은 차례인 사람이 [무승부 주장]을 눌러야 해요. 5번 반복·75수는 자동)' : '(이 방은 자동으로 비겨요)'}, 그리고 서로 합의했을 때예요.
|
||
</p>
|
||
<p>
|
||
<strong>시간</strong>: 수를 둘 때마다 정해진 초가 더해져요. 시간이 다 되면 져요. 단 상대에게 체크메이트할 기물이 없으면 비겨요. 각자 첫 수는 시계가 줄지 않지만 정해진 시간 안에 두지
|
||
않으면 대국이 취소돼요.
|
||
</p>
|
||
<p>조작: 기물을 누르면 갈 수 있는 칸에 점이 찍혀요(잡을 수 있는 칸은 동그라미). 그 칸을 누르거나 기물을 끌어다 놓으면 둬요.</p>
|
||
<p className="small muted">{CHESS_PIECE_CREDIT}</p>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const ui: GameUI<ChessView, ChessOptions> = {
|
||
Board: ChessBoard,
|
||
Side: ChessSide,
|
||
statusText,
|
||
isMyTurn: (v, me) => v.phase === 'playing' && !!v.myColor && v.players[v.turn] === me,
|
||
Options,
|
||
optionsSummary,
|
||
Rules,
|
||
quickStart,
|
||
helpNow,
|
||
};
|
||
|
||
export default ui;
|