체스·장기·쿼리도 소리·움직임, 장기 상차림 시간 무제한

- 체스: 기물이 출발 칸에서 미끄러져 와 내려앉음(내가 끌어다 놓은 수는 제외), 캐슬링은 룩도 같이, 잡힌 기물(앙파상 폰 포함) 사라짐, 체크 칸 빛·말풍선 튀어나옴, 마지막 수 칸 살짝 나타남
- 체스 소리: 나무 기물 톡, 잡기, 캐슬링, 승진, 체크, 체크메이트 순간, 무르기, 기물 집기, 안 되는 칸 (fx.ts 순수 함수 + 테스트)
- 장기: 묵직한 기물 미끄러짐·내려앉기, 잡힌 기물 사라짐, 장군 궁 자리 고동, 상차림 마·상 하나씩 튀어나옴
- 장기 소리: 두꺼운 나무 "딱", 잡기, 장군·멍군·빅장, 외통 순간, 한수쉼, 무르기, 상차림 놓기 (fx.ts + 테스트)
- 장기 상차림 고르는 시간에 무제한(0) 추가, 방 설정 "자세한 설정"에서 30초·1분·3분·무제한 (기본 1분 그대로), 무제한이면 상차림 시계 숨김, 끊긴 사람만 접속 유예 뒤 자동 선택
- 쿼리도: 말 한 칸은 살짝 튀며, 점프는 높이 뛰어 넘음, 도착 칸 고리, 벽 내려앉기+먼지, 무르기로 빠진 벽 사라짐, 안 되는 벽 흔들림, 목표 도착 띠 깜빡임·금빛 고리
- 쿼리도 소리: 말 톡, 점프, 벽 끼우기, 안 되는 곳, 목표 도착, 무르기
- 상대·컴퓨터 수도 화면 변화로 같은 소리·움직임, 새로 열면 다시 재생 안 함, 숨은 탭 내 차례 소리는 방 화면에 맡김

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-13 13:08:18 +09:00
parent 5e1e74da18
commit 8175cebd2c
15 changed files with 746 additions and 82 deletions

View File

@@ -0,0 +1,67 @@
import { expect, test } from 'bun:test';
import { SeededRng } from '../../../../../packages/engine/src/rng';
import { applyAction, setupGame } from '../help-kit.test-util';
import { GAMES } from '@bg/games';
import { chessCues, chessMotion } from './fx';
const view = (s: unknown) => GAMES.chess!.view(s, null) as any;
let clock = 1_700_000_000_000;
const move = (s: any, who: string, from: string, to: string) => applyAction('chess', s, who, { type: 'move', from, to }, SeededRng.fromSeed([9, 9, 9, 9]), (clock += 1000));
/** Plays [who, from, to] moves and returns the views before and after the last one. */
function play(moves: [string, string, string][]) {
let s = setupGame('chess', 2, { colorAssignment: 'hostWhite' }).state;
let before = view(s);
for (const [who, from, to] of moves) {
before = view(s);
s = move(s, who, from, to);
}
return { before, after: view(s) };
}
test('체스 소리: 한 번의 변화에 한 묶음, 무르기는 휙', () => {
expect(chessCues(3, [{ san: 'e4' }, { san: 'e5' }, { san: 'Nf3' }])).toEqual([]);
expect(chessCues(0, [{ san: 'e4' }])).toEqual(['move']);
expect(chessCues(0, [{ san: 'Bxf7+' }])).toEqual(['capture', 'check']);
expect(chessCues(0, [{ san: 'O-O-O' }])).toEqual(['castle']);
expect(chessCues(0, [{ san: 'exd8=Q#' }])).toEqual(['capture', 'promote', 'mate']);
expect(chessCues(2, [{ san: 'e4' }])).toEqual(['undo']);
});
test('체스 움직임: 보통 수는 한 기물만 미끄러지고, 잡힌 기물은 그 자리에서 사라짐', () => {
const { before, after } = play([
['A', 'e2', 'e4'],
['B', 'd7', 'd5'],
['A', 'e4', 'd5'],
]);
expect(chessMotion(before.board, after.board, after.lastMove)).toEqual({ slides: [{ sq: 'd5', from: 'e4' }], gone: [{ sq: 'd5', piece: 'p' }] });
// Page load / undo: nothing to replay.
expect(chessMotion(null, after.board, after.lastMove)).toBeNull();
});
test('체스 움직임: 캐슬링은 룩도, 앙파상은 지나간 폰이 사라짐', () => {
const castle = play([
['A', 'e2', 'e4'],
['B', 'e7', 'e5'],
['A', 'g1', 'f3'],
['B', 'b8', 'c6'],
['A', 'f1', 'c4'],
['B', 'f8', 'c5'],
['A', 'e1', 'g1'],
]);
expect(castle.after.moves.at(-1).san).toBe('O-O');
expect(chessMotion(castle.before.board, castle.after.board, castle.after.lastMove)).toEqual({
slides: [
{ sq: 'g1', from: 'e1' },
{ sq: 'f1', from: 'h1' },
],
gone: [],
});
const ep = play([
['A', 'e2', 'e4'],
['B', 'a7', 'a6'],
['A', 'e4', 'e5'],
['B', 'd7', 'd5'],
['A', 'e5', 'd6'],
]);
expect(chessMotion(ep.before.board, ep.after.board, ep.after.lastMove)).toEqual({ slides: [{ sq: 'd6', from: 'e5' }], gone: [{ sq: 'd5', piece: 'p' }] });
});

View File

@@ -0,0 +1,59 @@
/**
* What to play and animate when the chess view changes (pure, so it is unit-tested; no DOM or audio here).
* Everything is derived from two consecutive views, so the opponent's and the computer's moves get the same
* sound and motion as mine, and one change gives exactly one set of cues.
*/
export type ChessCue = 'move' | 'capture' | 'castle' | 'promote' | 'check' | 'mate' | 'undo';
/** Sounds for a change of the move list from `prevCount` moves to `moves`. Empty when nothing changed. */
export function chessCues(prevCount: number, moves: readonly { san: string }[]): ChessCue[] {
const n = moves.length;
if (n === prevCount) return [];
if (n < prevCount) return ['undo'];
const san = moves[n - 1]!.san;
const out: ChessCue[] = [san.startsWith('O-O') ? 'castle' : san.includes('x') ? 'capture' : 'move'];
if (san.includes('=')) out.push('promote');
if (san.endsWith('#')) out.push('mate');
else if (san.endsWith('+')) out.push('check');
return out;
}
export interface ChessMotion {
/** Pieces now on `sq` that slid in from `from` (the moved piece, plus the rook when castling). */
slides: { sq: string; from: string }[];
/** Captured pieces to fade out where they stood (the target square, or the passed pawn for en passant). */
gone: { sq: string; piece: string }[];
}
const FILES = 'abcdefgh';
const idxOf = (sq: string) => (8 - Number(sq[1])) * 8 + FILES.indexOf(sq[0]!);
const sqOfIdx = (i: number) => `${FILES[i % 8]}${8 - Math.floor(i / 8)}`;
const isWhite = (p: string) => p === p.toUpperCase();
/**
* Motion for one step forward: `before` is the board one move earlier (null on page load, after an undo or when
* several moves arrived at once, so nothing is replayed then).
*/
export function chessMotion(before: readonly (string | null)[] | null, board: readonly (string | null)[], lastMove: { from: string; to: string } | null): ChessMotion | null {
if (!before || !lastMove) return null;
const moved = board[idxOf(lastMove.to)];
if (!moved) return null;
const white = isWhite(moved);
const slides: ChessMotion['slides'] = [];
// Chess960: the king may already stand on its castling square.
if (lastMove.from !== lastMove.to) slides.push({ sq: lastMove.to, from: lastMove.from });
const rook = white ? 'R' : 'r';
const king = white ? 'K' : 'k';
if (moved === king) {
// Castling: one of my rooks left a square and one appeared elsewhere (Chess960 rooks may not move at all).
const left = before.findIndex((p, i) => p === rook && board[i] !== rook);
const came = board.findIndex((p, i) => p === rook && before[i] !== rook);
if (left >= 0 && came >= 0) slides.push({ sq: sqOfIdx(came), from: sqOfIdx(left) });
}
const gone: ChessMotion['gone'] = [];
before.forEach((p, i) => {
if (p && isWhite(p) !== white && board[i] !== p) gone.push({ sq: sqOfIdx(i), piece: p });
});
return { slides, gone };
}

View File

@@ -4,9 +4,12 @@ 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, sounds } from '../../lib/feedback';
import { haptic } from '../../lib/feedback';
import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { chessCues, chessMotion } from './fx';
import { helpNow } from './help';
import { nopeSound, pickSound, playChess } from './sound';
import { quickStart } from './quick';
type Color = 'white' | 'black';
@@ -133,6 +136,19 @@ function letterPiece(p: string): { type: PieceType; color: Color } {
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; } }
`;
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);
@@ -147,8 +163,8 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
const [announce, setAnnounce] = useState('');
const svgRef = useRef<SVGSVGElement>(null);
const prevCount = useRef(v.moves.length);
const movedRef = useRef<SVGGElement>(null);
const dropped = useRef(false);
/** 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[]>();
@@ -158,43 +174,55 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
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) {
// Slide the moved piece in (~150ms) unless I just dropped it there myself.
const el = movedRef.current;
if (el && v.lastMove && !dropped.current && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
const a = cellOf(v.lastMove.from, bottom);
const b = cellOf(v.lastMove.to, bottom);
el.animate([{ transform: `translate(${a.x - b.x}px, ${a.y - b.y}px)` }, { transform: 'translate(0px, 0px)' }], { duration: 150, easing: 'ease-out' });
}
sounds.stone();
setAnnounce(`${COLOR_KO[last.color]}: ${last.san}${v.checkSquare ? ', 체크!' : ''}`);
if (myTurn) {
haptic(40);
if (document.visibilityState === 'hidden') sounds.myTurn();
}
if (myTurn) haptic(40);
} else setAnnounce('수를 물렀어요.');
}
prevCount.current = v.moves.length;
dropped.current = false;
setSelected(null);
setPromo(null);
}, [v.moves.length]); // eslint-disable-line react-hooks/exhaustive-deps
const send = (from: string, to: string, promotion?: Promo) => {
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) => {
const attempt = (from: string, to: string, viaDrop = false) => {
const mv = (byFrom.get(from) ?? []).find((m) => m.to === to);
if (!mv || pending) return;
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);
else send(from, to, undefined, viaDrop);
};
const ownMovable = (sq: string) => myTurn && byFrom.has(sq);
@@ -208,14 +236,17 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
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);
};
@@ -260,6 +291,7 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
return (
<div className="board-wrap stack" style={{ gap: 10 }}>
<style>{BOARD_MOTION_CSS + CHESS_CSS}</style>
<svg
ref={svgRef}
viewBox="-0.02 -0.02 8.04 8.04"
@@ -282,6 +314,7 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
// 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);
}}
@@ -300,10 +333,7 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
drag.current = null;
setDragPos(null);
if (d?.moved) {
if (sq && sq !== d.from) {
dropped.current = true;
attempt(d.from, sq);
}
if (sq && sq !== d.from) attempt(d.from, sq, true);
return;
}
if (sq) click(sq, d ? d.wasSelected : false);
@@ -325,14 +355,29 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
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 && <rect x={lastFrom.x} y={lastFrom.y} width={1} height={1} fill="#cdd26a" opacity={0.75} />}
{lastTo && <rect x={lastTo.x} y={lastTo.y} width={1} height={1} fill="#aaa23a" opacity={0.6} />}
{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 x={check.x} y={check.y} width={1} height={1} fill="url(#chess-check)" />}
{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' }}>
@@ -345,17 +390,38 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
</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={sq} transform={`translate(${c.x} ${c.y})`} style={{ pointerEvents: 'none' }}>
<g ref={v.lastMove?.to === sq ? movedRef : undefined}>
<g transform="translate(0.04 0.04) scale(0.0092)">
<PieceShape type={type} color={color} />
<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>
@@ -385,10 +451,12 @@ function ChessBoard({ view: v, act, pending }: BoardProps<ChessView>) {
})}
{check && (
<g transform={`translate(${check.x + 0.5} ${check.y < 1 ? check.y + 1.22 : check.y - 0.22})`} style={{ pointerEvents: 'none' }}>
<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 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 && (

View File

@@ -0,0 +1,48 @@
/** Chess sounds: a light wooden "tok" family (site volume is applied inside feedback.ts). */
import { noise, sfx, tone } from '../../lib/feedback';
import type { ChessCue } from './fx';
/** A Staunton piece set down on a wooden board: short, soft and fairly high. */
function tok(delay = 0, pitch = 1): void {
tone(760 * pitch, 45, 'triangle', 0.15, delay, { slideTo: 520 * pitch });
noise(30, 0.07, delay, 'bandpass', 2200 * pitch, 1.4);
}
/** Each cue starts `d` ms from now (when the sliding piece lands). */
const PLAY: Record<ChessCue, (d: number) => void> = {
move: (d) => tok(d),
// The moving piece, then the taken one knocked off the board.
capture: (d) => {
tok(d, 1.05);
tone(420, 70, 'triangle', 0.11, d + 55, { slideTo: 300 });
noise(60, 0.07, d + 55, 'lowpass', 1100);
},
// King and rook: two quick taps.
castle: (d) => {
tok(d, 1);
tok(d + 110, 0.9);
},
// Like sfx.pop, a moment after the piece lands.
promote: (d) => tone(700, 90, 'sine', 0.16, d + 90, { slideTo: 1400 }),
// A short, light two-note call.
check: (d) => {
tone(988, 80, 'triangle', 0.09, d + 70);
tone(1319, 130, 'triangle', 0.08, d + 150);
},
// The mating move: a low ringing chord (the win / lose jingle comes from the result screen).
mate: (d) => {
tone(392, 320, 'triangle', 0.11, d + 80);
tone(587, 340, 'triangle', 0.08, d + 110);
tone(784, 380, 'sine', 0.07, d + 140);
},
undo: () => sfx.whoosh(),
};
export function playChess(cues: ChessCue[], delayMs = 0): void {
for (const c of cues) PLAY[c](delayMs);
}
/** Picking up one of my pieces: a very quiet tick. */
export const pickSound = () => tone(1150, 25, 'triangle', 0.06);
/** A tap that does nothing (wrong square / piece that cannot move): soft and low. */
export const nopeSound = () => tone(230, 90, 'triangle', 0.06, 0, { slideTo: 180 });