체스·장기·쿼리도 소리·움직임, 장기 상차림 시간 무제한
- 체스: 기물이 출발 칸에서 미끄러져 와 내려앉음(내가 끌어다 놓은 수는 제외), 캐슬링은 룩도 같이, 잡힌 기물(앙파상 폰 포함) 사라짐, 체크 칸 빛·말풍선 튀어나옴, 마지막 수 칸 살짝 나타남 - 체스 소리: 나무 기물 톡, 잡기, 캐슬링, 승진, 체크, 체크메이트 순간, 무르기, 기물 집기, 안 되는 칸 (fx.ts 순수 함수 + 테스트) - 장기: 묵직한 기물 미끄러짐·내려앉기, 잡힌 기물 사라짐, 장군 궁 자리 고동, 상차림 마·상 하나씩 튀어나옴 - 장기 소리: 두꺼운 나무 "딱", 잡기, 장군·멍군·빅장, 외통 순간, 한수쉼, 무르기, 상차림 놓기 (fx.ts + 테스트) - 장기 상차림 고르는 시간에 무제한(0) 추가, 방 설정 "자세한 설정"에서 30초·1분·3분·무제한 (기본 1분 그대로), 무제한이면 상차림 시계 숨김, 끊긴 사람만 접속 유예 뒤 자동 선택 - 쿼리도: 말 한 칸은 살짝 튀며, 점프는 높이 뛰어 넘음, 도착 칸 고리, 벽 내려앉기+먼지, 무르기로 빠진 벽 사라짐, 안 되는 벽 흔들림, 목표 도착 띠 깜빡임·금빛 고리 - 쿼리도 소리: 말 톡, 점프, 벽 끼우기, 안 되는 곳, 목표 도착, 무르기 - 상대·컴퓨터 수도 화면 변화로 같은 소리·움직임, 새로 열면 다시 재생 안 함, 숨은 탭 내 차례 소리는 방 화면에 맡김 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
67
apps/web/src/games/chess/fx.test.ts
Normal file
67
apps/web/src/games/chess/fx.test.ts
Normal 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' }] });
|
||||
});
|
||||
59
apps/web/src/games/chess/fx.ts
Normal file
59
apps/web/src/games/chess/fx.ts
Normal 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 };
|
||||
}
|
||||
@@ -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 && (
|
||||
|
||||
48
apps/web/src/games/chess/sound.ts
Normal file
48
apps/web/src/games/chess/sound.ts
Normal 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 });
|
||||
50
apps/web/src/games/janggi/fx.test.ts
Normal file
50
apps/web/src/games/janggi/fx.test.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { expect, test } from 'bun:test';
|
||||
import { applyAction, setupGame } from '../help-kit.test-util';
|
||||
import { GAMES } from '@bg/games';
|
||||
import { addedPieces, janggiCues, janggiMotion } from './fx';
|
||||
|
||||
const view = (s: unknown) => GAMES.janggi!.view(s, null) as any;
|
||||
const mv = (f1: number, r1: number, f2: number, r2: number) => ({ type: 'move', from: { f: f1, r: r1 }, to: { f: f2, r: r2 } });
|
||||
|
||||
test('장기 소리: 한 번의 변화에 한 묶음 (장군·멍군·빅장·외통·한수쉼·무르기)', () => {
|
||||
const prev = { count: 4, inCheck: null, bikjang: null };
|
||||
const base = { moveCount: 5, inCheck: null, bikjang: null, phase: 'playing' as const, result: null };
|
||||
const move = { kind: 'move', side: 'cho', piece: 'cha', from: { f: 0, r: 0 }, to: { f: 0, r: 3 }, captured: null } as const;
|
||||
const moves = (m: object) => [...Array(4).fill({ kind: 'pass', side: 'cho' }), m] as any;
|
||||
expect(janggiCues(prev, { ...base, moveCount: 4, moves: moves(move).slice(0, 4) })).toEqual([]);
|
||||
expect(janggiCues(prev, { ...base, moves: moves(move) })).toEqual(['move']);
|
||||
expect(janggiCues(prev, { ...base, moves: moves({ ...move, captured: 'po' }), inCheck: 'han' })).toEqual(['capture', 'janggun']);
|
||||
expect(janggiCues({ ...prev, inCheck: 'cho' }, { ...base, moves: moves(move) })).toEqual(['move', 'meonggun']);
|
||||
expect(janggiCues(prev, { ...base, moves: moves(move), bikjang: { calledBy: 'cho' } })).toEqual(['move', 'bikjang']);
|
||||
expect(janggiCues(prev, { ...base, moves: moves(move), inCheck: 'han', phase: 'finished', result: { reason: 'checkmate' } })).toEqual(['move', 'mate']);
|
||||
expect(janggiCues(prev, { ...base, moves: moves({ kind: 'pass', side: 'cho' }) })).toEqual(['pass']);
|
||||
expect(janggiCues(prev, { ...base, moveCount: 2, moves: moves(move).slice(0, 2) })).toEqual(['undo']);
|
||||
});
|
||||
|
||||
test('장기 움직임: 상차림 기물이 나타나고, 수는 미끄러지고, 잡힌 기물은 사라짐', () => {
|
||||
const { state } = setupGame('janggi', 2, { sideAssignment: 'hostCho', setupOrder: 'hanFirst' });
|
||||
const s1 = applyAction('janggi', state, 'B', { type: 'chooseSetup', arrangement: 'MSSM' });
|
||||
const added = addedPieces(view(state).board, view(s1).board);
|
||||
expect(added.length).toBe(4);
|
||||
expect(added.every((i) => view(s1).board[i].side === 'han')).toBe(true);
|
||||
expect(addedPieces(null, view(s1).board)).toEqual([]);
|
||||
const s2 = applyAction('janggi', s1, 'A', { type: 'chooseSetup', arrangement: 'SMMS' });
|
||||
// 초 졸 (0,3) → (1,3).
|
||||
const s3 = applyAction('janggi', s2, 'A', mv(0, 3, 1, 3));
|
||||
const v3 = view(s3);
|
||||
expect(janggiMotion(view(s2).board, v3.board, v3.moves.at(-1))).toEqual({ to: 3 * 9 + 1, from: 3 * 9 + 0, captured: null });
|
||||
// A move (or an undo) is never mistaken for pieces being set up.
|
||||
expect(addedPieces(view(s3).board, view(s2).board)).toEqual([]);
|
||||
expect(janggiMotion(null, v3.board, v3.moves.at(-1))).toBeNull();
|
||||
|
||||
// Capture: 초 차 (0,0) takes 한 졸 on (0,6) once the file is open.
|
||||
const c = structuredClone(s2) as any;
|
||||
c.board[3 * 9 + 0] = null;
|
||||
const before = view(c).board;
|
||||
const after = applyAction('janggi', c, 'A', mv(0, 0, 0, 6));
|
||||
const va = view(after);
|
||||
expect(janggiMotion(before, va.board, va.moves.at(-1))).toEqual({ to: 6 * 9 + 0, from: 0, captured: { side: 'han', kind: 'jol' } });
|
||||
// A pass has nothing to slide.
|
||||
const p = applyAction('janggi', s2, 'A', { type: 'pass' });
|
||||
expect(janggiMotion(view(s2).board, view(p).board, view(p).moves.at(-1))).toBeNull();
|
||||
});
|
||||
68
apps/web/src/games/janggi/fx.ts
Normal file
68
apps/web/src/games/janggi/fx.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* What to play and animate when the janggi 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.
|
||||
*/
|
||||
import type { JanggiMove, JanggiView, Piece } from '@bg/games/janggi';
|
||||
|
||||
export type JanggiCue = 'move' | 'capture' | 'pass' | 'janggun' | 'meonggun' | 'bikjang' | 'mate' | 'undo';
|
||||
|
||||
/** The parts of the previous view the cues compare against. */
|
||||
export interface JanggiPrev {
|
||||
count: number;
|
||||
inCheck: JanggiView['inCheck'];
|
||||
bikjang: JanggiView['bikjang'];
|
||||
}
|
||||
|
||||
type CueView = Pick<JanggiView, 'moveCount' | 'moves' | 'inCheck' | 'bikjang' | 'phase'> & { result: { reason: string } | null };
|
||||
|
||||
/** Sounds for one change of the move list. Empty when no move was added or taken back. */
|
||||
export function janggiCues(p: JanggiPrev, v: CueView): JanggiCue[] {
|
||||
if (v.moveCount === p.count) return [];
|
||||
if (v.moveCount < p.count) return ['undo'];
|
||||
const m = v.moves[v.moves.length - 1];
|
||||
if (!m) return [];
|
||||
const out: JanggiCue[] = [m.kind === 'pass' ? 'pass' : m.captured ? 'capture' : 'move'];
|
||||
// After a ply the mover is never in check, so a side in check now was just checked by that ply.
|
||||
if (v.phase === 'finished' && v.result?.reason === 'checkmate') out.push('mate');
|
||||
else if (v.inCheck) out.push('janggun');
|
||||
else if (p.inCheck && v.phase === 'playing') out.push('meonggun');
|
||||
if (v.bikjang && !p.bikjang) out.push('bikjang');
|
||||
return out;
|
||||
}
|
||||
|
||||
const key = (q: { f: number; r: number }) => q.r * 9 + q.f;
|
||||
const same = (a: Piece | null | undefined, b: Piece | null | undefined) => (!a && !b) || (!!a && !!b && a.side === b.side && a.kind === b.kind);
|
||||
|
||||
export interface JanggiMotion {
|
||||
/** Board index the moved piece now stands on, and where it came from. */
|
||||
to: number;
|
||||
from: number;
|
||||
/** The piece it took (drawn fading on the same point). */
|
||||
captured: Piece | null;
|
||||
}
|
||||
|
||||
/** Motion for one ply forward (`before` = board one ply earlier, null on page load / undo / several plies at once). */
|
||||
export function janggiMotion(before: readonly (Piece | null)[] | null, board: readonly (Piece | null)[], last: JanggiMove | undefined): JanggiMotion | null {
|
||||
if (!before || !last || last.kind !== 'move') return null;
|
||||
const to = key(last.to);
|
||||
const from = key(last.from);
|
||||
if (!board[to] || board[from]) return null;
|
||||
const prev = before[to];
|
||||
return { to, from, captured: prev && prev.side !== board[to]!.side ? prev : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Pieces that appeared during 상차림 (a 마·상 arrangement put on the board). Only a pure addition counts, so an undo
|
||||
* or a move is never mistaken for it.
|
||||
*/
|
||||
export function addedPieces(before: readonly (Piece | null)[] | null, board: readonly (Piece | null)[]): number[] {
|
||||
if (!before) return [];
|
||||
const out: number[] = [];
|
||||
for (let i = 0; i < board.length; i++) {
|
||||
if (before[i]) {
|
||||
if (!same(before[i], board[i])) return [];
|
||||
} else if (board[i]) out.push(i);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -4,9 +4,12 @@ import type { Arrangement, JanggiMove, JanggiOptions, JanggiView, Piece, PieceKi
|
||||
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 { addedPieces, janggiCues, janggiMotion } from './fx';
|
||||
import { helpNow } from './help';
|
||||
import { nopeSound, pickSound, playJanggi, setupSound } from './sound';
|
||||
import { quickStart } from './quick';
|
||||
|
||||
const SIDE_KO: Record<Side, string> = { cho: '초', han: '한' };
|
||||
@@ -151,6 +154,21 @@ function BoardLines() {
|
||||
|
||||
type Bubble = { text: string; color: string; id: number };
|
||||
|
||||
/** Slide time for a piece moving `cells` points. */
|
||||
const slideSec = (cells: number) => Math.min(0.36, 0.2 + cells * 0.02);
|
||||
/** Gap between the 상차림 pieces popping in. */
|
||||
const SETUP_GAP_MS = 80;
|
||||
|
||||
/** Janggi-only motion on top of BOARD_MOTION_CSS: the heavy block settling, 장군 pulse, highlight fade-in. */
|
||||
const JANGGI_CSS = `
|
||||
.jg-land { transform-box: fill-box; transform-origin: center; animation: jg-land .22s ease-out both; animation-delay: var(--jg-delay, 0s); }
|
||||
@keyframes jg-land { 0% { transform: scale(1.07); } 45% { transform: scale(.95); } 100% { transform: scale(1); } }
|
||||
.jg-check { transform-box: fill-box; transform-origin: center; animation: jg-check .7s ease-out both; animation-delay: var(--jg-delay, 0s); }
|
||||
@keyframes jg-check { 0% { opacity: 0; transform: scale(.5); } 30% { opacity: 1; transform: scale(1.22); } 55% { transform: scale(.95); } 78% { transform: scale(1.08); } 100% { opacity: 1; transform: scale(1); } }
|
||||
.jg-fade { animation: jg-fade .3s ease-out both; }
|
||||
@keyframes jg-fade { from { opacity: 0; } }
|
||||
`;
|
||||
|
||||
function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiView>) {
|
||||
const flip = v.mySide === 'han';
|
||||
const toScreen = (q: Sq) => (flip ? { x: 8 - q.f, y: q.r } : { x: q.f, y: 9 - q.r });
|
||||
@@ -178,14 +196,35 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
}, [v.legalMoves]);
|
||||
const showHints = v.rules.hints !== 'off';
|
||||
|
||||
// What moved since the last change (mine, the opponent's or the computer's). Only one ply forward animates;
|
||||
// a page load, an undo or several plies at once just show the position.
|
||||
const n = v.moveCount;
|
||||
const diff = useMoveDiff({ board: v.board, n }, n);
|
||||
const step = diff.forward && diff.before?.n === n - 1;
|
||||
const motion = step ? janggiMotion(diff.before!.board, v.board, v.moves[n - 1]) : null;
|
||||
const slide = (() => {
|
||||
if (!motion) return null;
|
||||
const a = toScreen(fromKey(motion.from));
|
||||
const b = toScreen(fromKey(motion.to));
|
||||
return { dx: a.x - b.x, dy: a.y - b.y, sec: slideSec(Math.hypot(a.x - b.x, a.y - b.y)) };
|
||||
})();
|
||||
const landSec = slide?.sec ?? 0;
|
||||
// 상차림: the 마·상 put on the board pop in (only while no move has been played yet).
|
||||
const setupKey = n === 0 ? v.board.reduce((k, p) => k + (p ? 1 : 0), 0) : -1;
|
||||
const setupDiff = useMoveDiff(v.board, setupKey);
|
||||
const popped = n === 0 && setupDiff.forward ? addedPieces(setupDiff.before, v.board) : [];
|
||||
useEffect(() => {
|
||||
if (popped.length) setupSound(popped.length, SETUP_GAP_MS);
|
||||
}, [setupKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Sounds, bubbles and announcements when the position changes.
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
const show = (text: string, color: string) => setBubble({ text, color, id: Date.now() });
|
||||
playJanggi(janggiCues(p, v), landSec * 1000);
|
||||
if (v.moveCount > p.count) {
|
||||
const m = v.moves[v.moves.length - 1]!;
|
||||
if (m.kind === 'move') {
|
||||
sounds.stone();
|
||||
setAnnounce(`${SIDE_KO[m.side]} ${HANGUL[m.piece][m.side]}이 ${sqCode(m.from)}에서 ${sqCode(m.to)}로 갔어요${m.captured ? ` (${HANGUL[m.captured][other(m.side)]} 잡음)` : ''}.`);
|
||||
} else {
|
||||
setAnnounce(`${SIDE_KO[m.side]}이 한수쉼했어요.`);
|
||||
@@ -197,10 +236,7 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
show('멍군!', '#1d4ed8');
|
||||
}
|
||||
if (v.bikjang && !p.bikjang) show('빅장!', '#7c3aed');
|
||||
if (myTurn) {
|
||||
haptic(40);
|
||||
if (document.visibilityState === 'hidden') sounds.myTurn();
|
||||
}
|
||||
if (myTurn) haptic(40);
|
||||
}
|
||||
if (p.phase === 'setup' && v.phase === 'playing') setAnnounce('상차림이 끝났어요. 초부터 둬요.');
|
||||
prev.current = { count: v.moveCount, inCheck: v.inCheck, bikjang: v.bikjang, phase: v.phase };
|
||||
@@ -233,15 +269,20 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
return;
|
||||
}
|
||||
setSelected(i);
|
||||
const n = legal.get(i)?.length ?? 0;
|
||||
setAnnounce(`${pieceName(piece)} ${sqCode(sq)} 선택. ${n ? `갈 수 있는 곳 ${n}곳` : '지금은 움직일 수 없어요'}`);
|
||||
if (!n) haptic([30, 30, 30]);
|
||||
const count = legal.get(i)?.length ?? 0;
|
||||
setAnnounce(`${pieceName(piece)} ${sqCode(sq)} 선택. ${count ? `갈 수 있는 곳 ${count}곳` : '지금은 움직일 수 없어요'}`);
|
||||
if (count) pickSound();
|
||||
else {
|
||||
haptic([30, 30, 30]);
|
||||
nopeSound();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (selected === null) return;
|
||||
const ok = legal.get(selected)?.some((m) => m.to === i);
|
||||
if (!ok && showHints) {
|
||||
// Targets are drawn, so a click elsewhere just deselects.
|
||||
nopeSound();
|
||||
setSelected(null);
|
||||
setPreview(null);
|
||||
return;
|
||||
@@ -302,6 +343,7 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10, maxWidth: setupMaxW, minWidth: 'min(100%, 300px)' }}>
|
||||
<style>{BOARD_MOTION_CSS + JANGGI_CSS}</style>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
@@ -334,18 +376,60 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps<JanggiVie
|
||||
{(10 - fromScreen(0, y).r) % 10}
|
||||
</text>
|
||||
))}
|
||||
{last &&
|
||||
[last.from, last.to].map((q, k) => {
|
||||
const s = toScreen(q);
|
||||
return <rect key={`lm${k}`} x={s.x - 0.46} y={s.y - 0.46} width={0.92} height={0.92} rx={0.12} fill={k ? 'rgba(250,204,21,0.45)' : 'none'} stroke="#ca8a04" strokeWidth={0.05} strokeDasharray={k ? undefined : '0.12 0.08'} />;
|
||||
})}
|
||||
{last && (
|
||||
<g key={`lm${n}`} className={motion ? 'jg-fade' : undefined}>
|
||||
{[last.from, last.to].map((q, k) => {
|
||||
const s = toScreen(q);
|
||||
return <rect key={k} x={s.x - 0.46} y={s.y - 0.46} width={0.92} height={0.92} rx={0.12} fill={k ? 'rgba(250,204,21,0.45)' : 'none'} stroke="#ca8a04" strokeWidth={0.05} strokeDasharray={k ? undefined : '0.12 0.08'} />;
|
||||
})}
|
||||
</g>
|
||||
)}
|
||||
{kingInCheck >= 0 && (() => {
|
||||
const s = toScreen(fromKey(kingInCheck));
|
||||
return <circle cx={s.x} cy={s.y} r={0.58} fill="rgba(220,38,38,0.25)" stroke="#dc2626" strokeWidth={0.07} />;
|
||||
return (
|
||||
<circle
|
||||
key={`ck${n}`}
|
||||
className={step ? 'jg-check' : undefined}
|
||||
style={{ '--jg-delay': `${landSec}s` } as React.CSSProperties}
|
||||
cx={s.x}
|
||||
cy={s.y}
|
||||
r={0.58}
|
||||
fill="rgba(220,38,38,0.25)"
|
||||
stroke="#dc2626"
|
||||
strokeWidth={0.07}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
{/* The captured piece shrinks away under the piece that took it. */}
|
||||
{motion?.captured && (() => {
|
||||
const s = toScreen(fromKey(motion.to));
|
||||
return (
|
||||
<g key={`x${n}`} className="bm-gone" style={{ animationDelay: `${Math.max(0, landSec - 0.12)}s` }}>
|
||||
<PieceGlyph piece={motion.captured} cx={s.x} cy={s.y} hangul={hangul} />
|
||||
</g>
|
||||
);
|
||||
})()}
|
||||
{v.board.map((p, i) => {
|
||||
if (!p) return null;
|
||||
const s = toScreen(fromKey(i));
|
||||
if (slide && motion?.to === i) {
|
||||
// Keyed by the move number so the slide and the settle run once per move.
|
||||
return (
|
||||
<g key={`${i}-m${n}`} className="bm-slide" style={{ '--bm-dx': `${slide.dx}px`, '--bm-dy': `${slide.dy}px`, '--bm-dur': `${slide.sec}s` } as React.CSSProperties}>
|
||||
<g className="jg-land" style={{ '--jg-delay': `${slide.sec}s` } as React.CSSProperties}>
|
||||
<PieceGlyph piece={p} cx={s.x} cy={s.y} hangul={hangul} />
|
||||
</g>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
const pop = popped.indexOf(i);
|
||||
if (pop >= 0) {
|
||||
return (
|
||||
<g key={`${i}-p${setupKey}`} className="anim-pop" style={{ animationDelay: `${pop * SETUP_GAP_MS}ms`, transformBox: 'fill-box', transformOrigin: 'center' }}>
|
||||
<PieceGlyph piece={p} cx={s.x} cy={s.y} hangul={hangul} />
|
||||
</g>
|
||||
);
|
||||
}
|
||||
return <PieceGlyph key={i} piece={p} cx={s.x} cy={s.y} hangul={hangul} />;
|
||||
})}
|
||||
{setupGhost &&
|
||||
@@ -668,7 +752,8 @@ function Clock({ view: v, side, deadline, mine }: { view: JanggiView; side: Side
|
||||
const now = useServerNow(250);
|
||||
const tc = v.rules.timeControl;
|
||||
if (v.phase === 'setup') {
|
||||
return v.setup.waitingFor.includes(side) ? <TurnTimer deadline={deadline} totalMs={v.rules.setupTimeSec * 1000} mine={mine} /> : null;
|
||||
// 상차림 시간 0 = 무제한: no countdown.
|
||||
return v.setup.waitingFor.includes(side) && v.rules.setupTimeSec > 0 ? <TurnTimer deadline={deadline} totalMs={v.rules.setupTimeSec * 1000} mine={mine} /> : null;
|
||||
}
|
||||
const active = v.phase === 'playing' && v.turn === side;
|
||||
if (tc.kind === 'none') return null;
|
||||
@@ -825,6 +910,17 @@ function timeLabel(tc: JanggiOptions['timeControl']): string {
|
||||
return `${m ? `${m}분` : ''}${s ? ` ${s}초` : ''}${tc.mainSec === 0 ? '0분' : ''} + 초읽기 ${tc.periodSec}초×${tc.periods}`;
|
||||
}
|
||||
|
||||
/** 상차림 시간 choices (0 = 무제한); a value set by the admin screen is kept as an extra choice. */
|
||||
function setupTimePresets(cur: number): [number, string][] {
|
||||
const p: [number, string][] = [
|
||||
[30, '30초'],
|
||||
[60, '1분'],
|
||||
[180, '3분'],
|
||||
[0, '무제한'],
|
||||
];
|
||||
return p.some((x) => x[0] === cur) ? p : [[cur, `${cur}초(관리자 설정)`], ...p];
|
||||
}
|
||||
|
||||
function Options({ value: o, onChange }: OptionsProps<JanggiOptions>) {
|
||||
const [more, setMore] = useState(false);
|
||||
const set = (patch: Partial<JanggiOptions>) => onChange({ ...o, ...patch });
|
||||
@@ -880,6 +976,9 @@ function Options({ value: o, onChange }: OptionsProps<JanggiOptions>) {
|
||||
<Field title="상차림 순서">
|
||||
<Seg value={o.setupOrder} options={[['hanFirst', '한이 먼저 공개(연맹식)'], ['simultaneous', '동시에 몰래 고르기']]} onChange={(setupOrder) => set({ setupOrder })} />
|
||||
</Field>
|
||||
<Field title="상차림 고르는 시간">
|
||||
<Seg value={o.setupTimeSec} options={setupTimePresets(o.setupTimeSec)} onChange={(setupTimeSec) => set({ setupTimeSec })} />
|
||||
</Field>
|
||||
<Field title="같은 국면 4번째">
|
||||
<Seg value={o.repetition} options={[['forbid', '그 수를 못 둠'], ['lose', '만든 쪽 실격패'], ['scoreEnd', '점수로 판정']]} onChange={(repetition) => set({ repetition })} />
|
||||
</Field>
|
||||
|
||||
62
apps/web/src/games/janggi/sound.ts
Normal file
62
apps/web/src/games/janggi/sound.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Janggi sounds: thick octagonal wooden blocks, so a lower, heavier "clack" than the chess "tok"
|
||||
* (site volume is applied inside feedback.ts).
|
||||
*/
|
||||
import { noise, sfx, tone } from '../../lib/feedback';
|
||||
import type { JanggiCue } from './fx';
|
||||
|
||||
/** A heavy wooden block put down on the board: a low knock plus a short dry crack. */
|
||||
function clack(delay = 0, pitch = 1, gain = 1): void {
|
||||
tone(330 * pitch, 80, 'triangle', 0.2 * gain, delay, { slideTo: 220 * pitch });
|
||||
noise(50, 0.11 * gain, delay, 'bandpass', 1250 * pitch, 1.1);
|
||||
noise(18, 0.05 * gain, delay, 'highpass', 3200);
|
||||
}
|
||||
|
||||
/** Each cue starts `d` ms from now (when the sliding piece lands). */
|
||||
const PLAY: Record<JanggiCue, (d: number) => void> = {
|
||||
move: (d) => clack(d),
|
||||
// The piece lands, then the taken block is knocked against it.
|
||||
capture: (d) => {
|
||||
clack(d, 1.08);
|
||||
clack(d + 60, 0.82, 0.75);
|
||||
noise(70, 0.06, d + 70, 'lowpass', 700);
|
||||
},
|
||||
// 한수쉼: just a light tap on the board edge.
|
||||
pass: (d) => {
|
||||
tone(520, 40, 'triangle', 0.06, d, { slideTo: 420 });
|
||||
noise(40, 0.03, d, 'bandpass', 1800, 0.8);
|
||||
},
|
||||
// "장군!": a short rising call.
|
||||
janggun: (d) => {
|
||||
tone(659, 90, 'triangle', 0.1, d + 70);
|
||||
tone(880, 150, 'triangle', 0.09, d + 160);
|
||||
},
|
||||
// "멍군!": the answer, falling back down.
|
||||
meonggun: (d) => {
|
||||
tone(880, 90, 'triangle', 0.08, d + 70);
|
||||
tone(659, 150, 'triangle', 0.07, d + 160);
|
||||
},
|
||||
// 빅장: the two 궁 face each other; a small "standoff" figure.
|
||||
bikjang: (d) => [587, 698, 587].forEach((f, i) => tone(f, 110, 'sine', 0.09, d + 260 + i * 100)),
|
||||
// 외통: a low ringing chord as the last move lands (the win / lose jingle comes from the result screen).
|
||||
mate: (d) => {
|
||||
tone(294, 360, 'triangle', 0.12, d + 80);
|
||||
tone(440, 380, 'triangle', 0.08, d + 110);
|
||||
tone(587, 420, 'sine', 0.07, d + 140);
|
||||
},
|
||||
undo: () => sfx.whoosh(),
|
||||
};
|
||||
|
||||
export function playJanggi(cues: JanggiCue[], delayMs = 0): void {
|
||||
for (const c of cues) PLAY[c](delayMs);
|
||||
}
|
||||
|
||||
/** 상차림 pieces put down one after another. */
|
||||
export function setupSound(n: number, gapMs: number): void {
|
||||
for (let i = 0; i < Math.min(n, 8); i++) clack(i * gapMs, 1.05 + (i % 2) * 0.06, 0.6);
|
||||
}
|
||||
|
||||
/** Picking up one of my pieces: a very quiet low tick (lower than chess). */
|
||||
export const pickSound = () => tone(820, 28, 'triangle', 0.06);
|
||||
/** A tap that does nothing: soft and low. */
|
||||
export const nopeSound = () => tone(200, 90, 'triangle', 0.06, 0, { slideTo: 160 });
|
||||
@@ -4,11 +4,13 @@ import type { Cell, QuoridorLegalWall, QuoridorMove, QuoridorOptions, QuoridorSe
|
||||
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 { toast } from '../../store/toast';
|
||||
import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
import { JUMP_LAND_MS, qdSound } from './sound';
|
||||
|
||||
type O = 'h' | 'v';
|
||||
interface Pt {
|
||||
@@ -31,9 +33,23 @@ const swapFor = (seat: Seat | null) => seat === 'W' || seat === 'E';
|
||||
|
||||
const CSS = `
|
||||
.qd-pawn { transition: transform 220ms ease-out; }
|
||||
.qd-wall-new { animation: qd-drop 260ms ease-out both; transform-box: fill-box; transform-origin: center; }
|
||||
.qd-pawn.jump { transition: transform ${JUMP_LAND_MS}ms cubic-bezier(.35, .1, .3, 1); }
|
||||
.qd-step, .qd-hop, .qd-wall-dust, .qd-goal-burst { transform-box: fill-box; transform-origin: center; }
|
||||
.qd-step { animation: qd-step 220ms ease-out both; }
|
||||
@keyframes qd-step { 50% { transform: translateY(-0.1px) scale(1.06); } }
|
||||
.qd-hop { animation: qd-hop ${JUMP_LAND_MS + 60}ms cubic-bezier(.3, .6, .4, 1) both; }
|
||||
@keyframes qd-hop { 45% { transform: translateY(-0.5px) scale(1.22); } 82% { transform: translateY(0) scale(.94); } 100% { transform: none; } }
|
||||
.qd-wall-new { animation: qd-drop 300ms cubic-bezier(.3, .8, .4, 1.2) both; transform-box: fill-box; transform-origin: center; }
|
||||
.qd-wall-dust { animation: qd-dust 420ms ease-out 170ms both; pointer-events: none; }
|
||||
@keyframes qd-dust { 0% { opacity: .7; transform: scale(1); } 100% { opacity: 0; transform: scale(var(--sx, 1.2), var(--sy, 1.2)); } }
|
||||
.qd-shake { animation: qd-shake 360ms ease both; }
|
||||
@keyframes qd-shake { 20%, 60% { transform: translateX(-0.08px); } 40%, 80% { transform: translateX(0.08px); } }
|
||||
.qd-goal-burst { animation: qd-goal 0.9s ease-out both; pointer-events: none; }
|
||||
@keyframes qd-goal { 0% { opacity: .95; transform: scale(.6); } 100% { opacity: 0; transform: scale(2.4); } }
|
||||
.qd-band-glow { animation: qd-band 0.45s ease-in-out 3; }
|
||||
@keyframes qd-band { 50% { opacity: .3; } }
|
||||
.qd-turn-ring { animation: qd-pulse 1.4s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
|
||||
@keyframes qd-drop { 0% { transform: scale(1.35); opacity: 0; } 100% { transform: scale(1); opacity: 1; } }
|
||||
@keyframes qd-drop { 0% { transform: scale(1.3); opacity: 0; } 60% { transform: scale(.97); opacity: 1; } 100% { transform: none; opacity: 1; } }
|
||||
@keyframes qd-pulse { 0%, 100% { opacity: 0.95; } 50% { opacity: 0.35; } }
|
||||
.qd-board * { pointer-events: none; }
|
||||
.qd-board [data-cell], .qd-board [data-anchor] { pointer-events: auto; }
|
||||
@@ -93,6 +109,19 @@ function overlapsAny(walls: Wall[], w: Wall): boolean {
|
||||
return has('v', w.c, w.r - 1) || has('v', w.c, w.r) || has('v', w.c, w.r + 1) || has('h', w.c, w.r);
|
||||
}
|
||||
|
||||
/** The last real action (not an automatic pass) among the moves that just arrived. */
|
||||
function lastAction(added: QuoridorMove[]): Exclude<QuoridorMove, { kind: 'pass' }> | undefined {
|
||||
for (let i = added.length - 1; i >= 0; i--) {
|
||||
const m = added[i]!;
|
||||
if (m.kind !== 'pass') return m;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
const isJump = (m: { from: Cell; to: Cell }) => Math.abs(m.to.c - m.from.c) + Math.abs(m.to.r - m.from.r) > 1;
|
||||
/** The seat finished with this update (it was still playing before). */
|
||||
const reachedGoal = (seat: Seat, before: QuoridorSeatView[], now: QuoridorSeatView[]) =>
|
||||
before.find((x) => x.seat === seat)?.status === 'playing' && now.find((x) => x.seat === seat)?.status === 'finished';
|
||||
|
||||
function wallRect(a: Pt, o: O) {
|
||||
return o === 'h' ? { x: a.x + 0.05, y: a.y + 1 - G / 2, width: 2 - 0.1, height: G } : { x: a.x + 1 - G / 2, y: a.y + 0.05, width: G, height: 2 - 0.1 };
|
||||
}
|
||||
@@ -132,8 +161,15 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prevCount = useRef(v.moveCount);
|
||||
const prevWalls = useRef(v.walls.length);
|
||||
const [newWall, setNewWall] = useState<string | null>(null);
|
||||
const [shake, setShake] = useState(0);
|
||||
|
||||
// What changed with the last view update (null on page load, so nothing replays on reconnect).
|
||||
const { before, forward } = useMoveDiff({ walls: v.walls, seats: v.seats, count: v.moveCount }, v.moveCount);
|
||||
const recent = before && forward ? (lastAction(v.moves.slice(before.count)) ?? null) : null;
|
||||
const jumped = recent?.kind === 'move' && isJump(recent);
|
||||
const newWall = recent?.kind === 'wall' ? wallKey(recent.wall) : null;
|
||||
const goalSeat = recent?.kind === 'move' && reachedGoal(recent.seat, before?.seats ?? [], v.seats) ? recent.seat : null;
|
||||
const takenBack = before && !forward ? before.walls.filter((w) => !v.walls.some((x) => wallKey(x) === wallKey(w))) : [];
|
||||
|
||||
const legalCells = useMemo(() => {
|
||||
const m = new Set<string>();
|
||||
@@ -155,19 +191,23 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
prevCount.current = v.moveCount;
|
||||
setMovePreview(null);
|
||||
setWallAt(null);
|
||||
if (v.walls.length > prevWalls.current) setNewWall(wallKey(v.walls[v.walls.length - 1]!));
|
||||
else setNewWall(null);
|
||||
prevWalls.current = v.walls.length;
|
||||
if (v.moveCount < prev) qdSound.undo();
|
||||
if (v.moveCount <= prev) return;
|
||||
const added = v.moves.slice(prev);
|
||||
const texts = added.map((m) => (m.kind === 'pass' ? `${SEAT_KO[m.seat]}은 움직일 곳이 없어 차례를 넘겼어요.` : `${moveText(m, t.swap)}.`));
|
||||
for (const m of added) if (m.kind === 'pass' && m.seat === v.mySeat) toast('움직일 곳도 세울 벽도 없어서 차례를 넘겼어요');
|
||||
setAnnounce(texts.join(' '));
|
||||
if (added.some((m) => m.kind !== 'pass')) sounds.stone();
|
||||
if (v.phase === 'playing' && v.mySeat === v.turn) {
|
||||
haptic(40);
|
||||
if (document.visibilityState === 'hidden') sounds.myTurn();
|
||||
// One sound per update (mine, the opponent's and the computer's moves alike).
|
||||
const last = lastAction(added);
|
||||
if (last?.kind === 'wall') qdSound.wall();
|
||||
else if (last?.kind === 'move') {
|
||||
const jump = isJump(last);
|
||||
if (jump) qdSound.jump();
|
||||
else qdSound.step();
|
||||
if (v.seats.find((x) => x.seat === last.seat)?.status === 'finished') qdSound.goal(jump ? JUMP_LAND_MS : 0);
|
||||
}
|
||||
// The "your turn" chime for a hidden tab is played by the room page.
|
||||
if (v.phase === 'playing' && v.mySeat === v.turn) haptic(40);
|
||||
}, [v.moveCount]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
useEffect(() => {
|
||||
@@ -192,9 +232,19 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
setMovePreview(null);
|
||||
setHoverCell(null);
|
||||
};
|
||||
/** A refused wall: subtle sound + the red preview shakes. */
|
||||
const refuseWall = () => {
|
||||
qdSound.refuse();
|
||||
setShake((n) => n + 1);
|
||||
};
|
||||
/** Pin the preview at an anchor/direction the player tapped; say no right away when it cannot go there. */
|
||||
const pinWall = (a: Pt, o: O) => {
|
||||
if (judge(a, o).why) refuseWall();
|
||||
};
|
||||
const doWall = (a: Pt) => {
|
||||
const j = judge(a, orient);
|
||||
if (j.why) {
|
||||
refuseWall();
|
||||
haptic([30, 30, 30]);
|
||||
setAnnounce(j.why);
|
||||
toast(j.why);
|
||||
@@ -208,6 +258,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
const c = t.screenToCell(p);
|
||||
const occupied = v.seats.some((x) => x.pos && x.pos.c === c.c && x.pos.r === c.r);
|
||||
const msg = occupied ? '말이 있는 칸이에요.' : '그 칸으로는 갈 수 없어요. 밝게 표시된 칸으로 움직일 수 있어요.';
|
||||
qdSound.refuse();
|
||||
haptic([30, 30, 30]);
|
||||
setAnnounce(msg);
|
||||
toast(msg);
|
||||
@@ -229,11 +280,14 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
const tapAnchor = (a: Pt) => {
|
||||
if (!canWall) return;
|
||||
if (wallAt && wallAt.x === a.x && wallAt.y === a.y) {
|
||||
setOrient((o) => (o === 'h' ? 'v' : 'h'));
|
||||
const o = orient === 'h' ? 'v' : 'h';
|
||||
setOrient(o);
|
||||
pinWall(a, o);
|
||||
return;
|
||||
}
|
||||
setWallAt(a);
|
||||
setCursor(a);
|
||||
pinWall(a, orient);
|
||||
};
|
||||
|
||||
const pointer = (e: React.PointerEvent<SVGSVGElement>): { x: number; y: number } | null => {
|
||||
@@ -290,6 +344,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
const o = orient === 'h' ? 'v' : 'h';
|
||||
setOrient(o);
|
||||
setWallAt(cursor);
|
||||
pinWall(cursor, o);
|
||||
const j = judge(cursor, o);
|
||||
setAnnounce(`${wallText(j.wall, t.swap)} ${j.why ?? '세울 수 있음'}`);
|
||||
} else if (e.key === 'w' || e.key === 'W') {
|
||||
@@ -330,7 +385,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10, maxWidth: 'min(100%, calc(100vh - 340px))', minWidth: 'min(100%, 300px)' }}>
|
||||
<style>{CSS}</style>
|
||||
<style>{BOARD_MOTION_CSS + CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="qd-board"
|
||||
@@ -375,7 +430,8 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
>
|
||||
{goalSides.map((g, k) => {
|
||||
const sameSide = goalSides.filter((x, j) => j < k && x.side === g.side).length;
|
||||
return <rect key={`g${g.seat}`} {...band(g.side, sameSide)} rx={0.06} fill={SEAT_COLOR[g.seat]} opacity={0.9} />;
|
||||
const glow = g.seat === goalSeat;
|
||||
return <rect key={`g${g.seat}${glow ? v.moveCount : ''}`} className={glow ? 'qd-band-glow' : undefined} {...band(g.side, sameSide)} rx={0.06} fill={SEAT_COLOR[g.seat]} opacity={0.9} />;
|
||||
})}
|
||||
{Array.from({ length: N }, (_, i) => {
|
||||
const bottom = t.screenToCell({ x: i, y: N - 1 });
|
||||
@@ -433,33 +489,53 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
{v.walls.map((w) => {
|
||||
const s = t.wallToScreen(w);
|
||||
const k = wallKey(w);
|
||||
const fall = k === newWall;
|
||||
return (
|
||||
<rect
|
||||
key={k}
|
||||
className={k === newWall ? 'qd-wall-new' : undefined}
|
||||
{...wallRect(s.a, s.o)}
|
||||
rx={0.05}
|
||||
fill="#3b2412"
|
||||
stroke={k === lastWall ? 'var(--focus)' : '#f3e2c0'}
|
||||
strokeWidth={k === lastWall ? 0.05 : 0.025}
|
||||
data-wall={`${w.o}:${label(w)}`}
|
||||
/>
|
||||
<g key={fall ? `${k}@${v.moveCount}` : k}>
|
||||
{fall && <rect className="qd-wall-dust" style={{ '--sx': s.o === 'h' ? 1.12 : 2.6, '--sy': s.o === 'h' ? 2.6 : 1.12 } as React.CSSProperties} {...wallRect(s.a, s.o)} rx={0.05} fill="#fff7e6" />}
|
||||
<rect
|
||||
className={fall ? 'qd-wall-new' : undefined}
|
||||
{...wallRect(s.a, s.o)}
|
||||
rx={0.05}
|
||||
fill="#3b2412"
|
||||
stroke={k === lastWall ? 'var(--focus)' : '#f3e2c0'}
|
||||
strokeWidth={k === lastWall ? 0.05 : 0.025}
|
||||
data-wall={`${w.o}:${label(w)}`}
|
||||
/>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{takenBack.map((w) => {
|
||||
const s = t.wallToScreen(w);
|
||||
return <rect key={`u${v.moveCount}-${wallKey(w)}`} className="bm-gone" {...wallRect(s.a, s.o)} rx={0.05} fill="#3b2412" stroke="#f3e2c0" strokeWidth={0.025} />;
|
||||
})}
|
||||
{recent?.kind === 'move' && (() => {
|
||||
const to = t.cellToScreen(recent.to);
|
||||
return <circle key={`ring${v.moveCount}`} className="bm-ring" style={{ animationDelay: jumped ? `${JUMP_LAND_MS}ms` : undefined }} cx={to.x + 0.5} cy={to.y + 0.5} r={0.42} fill="none" stroke="var(--focus)" strokeWidth={0.05} />;
|
||||
})()}
|
||||
{recent?.kind === 'move' && goalSeat && (() => {
|
||||
const to = t.cellToScreen(recent.to);
|
||||
return <circle key={`goal${v.moveCount}`} className="qd-goal-burst" cx={to.x + 0.5} cy={to.y + 0.5} r={0.45} fill={SEAT_COLOR[goalSeat]} opacity={0.6} stroke="#fde68a" strokeWidth={0.06} />;
|
||||
})()}
|
||||
{v.seats.map((x) => {
|
||||
if (!x.pos) return null;
|
||||
const p = t.cellToScreen(x.pos);
|
||||
const turn = v.phase === 'playing' && v.turn === x.seat;
|
||||
const moved = recent?.kind === 'move' && recent.seat === x.seat;
|
||||
return (
|
||||
<g key={x.seat} className="qd-pawn" style={{ transform: `translate(${p.x + 0.5}px, ${p.y + 0.5}px)` }} data-pawn={x.seat} data-at={label(x.pos)}>
|
||||
<g key={x.seat} className={`qd-pawn${moved && jumped ? ' jump' : ''}`} style={{ transform: `translate(${p.x + 0.5}px, ${p.y + 0.5}px)` }} data-pawn={x.seat} data-at={label(x.pos)}>
|
||||
{turn && <circle className="qd-turn-ring" cx={0} cy={0} r={0.45} fill="none" stroke={SEAT_COLOR[x.seat]} strokeWidth={0.06} />}
|
||||
<PawnMark seat={x.seat} cx={0} cy={0} />
|
||||
{x.status === 'finished' && <circle className="bm-win" cx={0} cy={0} r={0.47} fill="none" stroke="#fbbf24" strokeWidth={0.07} />}
|
||||
<g key={`h${v.moveCount}`} className={moved ? (jumped ? 'qd-hop' : 'qd-step') : undefined}>
|
||||
<PawnMark seat={x.seat} cx={0} cy={0} />
|
||||
</g>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{lastTo && <circle cx={lastTo.x + 0.5 + 0.27} cy={lastTo.y + 0.5 - 0.27} r={0.08} fill="var(--focus)" stroke="#fff" strokeWidth={0.02} />}
|
||||
{ghostCell && me && <PawnMark seat={me.seat} cx={ghostCell.x + 0.5} cy={ghostCell.y + 0.5} ghost />}
|
||||
{preview && previewAnchor && (
|
||||
<g key={`pv${shake}`} className={shake && preview.why ? 'qd-shake' : undefined}>
|
||||
<rect
|
||||
{...wallRect(previewAnchor, orient)}
|
||||
rx={0.05}
|
||||
@@ -469,6 +545,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
strokeWidth={0.04}
|
||||
strokeDasharray={wallAt ? undefined : '0.12 0.08'}
|
||||
/>
|
||||
</g>
|
||||
)}
|
||||
{myTurn && mode === 'wall' && (
|
||||
<g aria-hidden>
|
||||
@@ -509,6 +586,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp
|
||||
<button type="button" className="btn btn-secondary qd-rotate" onClick={() => {
|
||||
const o = orient === 'h' ? 'v' : 'h';
|
||||
setOrient(o);
|
||||
if (wallAt) pinWall(wallAt, o);
|
||||
}} aria-label={`벽 방향 바꾸기, 지금 ${orient === 'h' ? '가로' : '세로'}`}>
|
||||
↻ {orient === 'h' ? '가로' : '세로'}
|
||||
</button>
|
||||
|
||||
34
apps/web/src/games/quoridor/sound.ts
Normal file
34
apps/web/src/games/quoridor/sound.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
/** 쿼리도 소리: 나무 말과 나무 벽. Short and soft; the site volume is applied by feedback.ts. */
|
||||
import { noise, sfx, tone } from '../../lib/feedback';
|
||||
|
||||
/** When the jump sound lands (ms), matching the hop animation in index.tsx. */
|
||||
export const JUMP_LAND_MS = 250;
|
||||
|
||||
/** A soft wooden "tok" (one pawn step). */
|
||||
function tok(delay = 0, gain = 0.14): void {
|
||||
tone(560, 55, 'triangle', gain, delay);
|
||||
noise(26, gain * 0.45, delay, 'bandpass', 1500, 1.6);
|
||||
}
|
||||
|
||||
export const qdSound = {
|
||||
/** Pawn moved one cell. */
|
||||
step: () => tok(),
|
||||
/** Pawn jumped over another: a little hop up, then the tok on landing. */
|
||||
jump: () => {
|
||||
tone(360, 150, 'sine', 0.07, 0, { slideTo: 720 });
|
||||
tok(JUMP_LAND_MS, 0.15);
|
||||
},
|
||||
/** Wall set into the groove: lower and firmer than a pawn, with a short knock as it settles. */
|
||||
wall: () => {
|
||||
noise(45, 0.16, 0, 'bandpass', 850, 1.3);
|
||||
tone(190, 95, 'triangle', 0.17);
|
||||
tone(300, 40, 'square', 0.025, 4);
|
||||
noise(35, 0.07, 75, 'lowpass', 650);
|
||||
},
|
||||
/** A wall that cannot go there (subtle). */
|
||||
refuse: () => tone(175, 120, 'triangle', 0.08, 0, { slideTo: 125 }),
|
||||
/** A pawn reached its goal line: a short rising run (the win/lose jingle is played by the room). */
|
||||
goal: (delay = 0) => [523, 659, 784, 1046].forEach((f, i) => tone(f, 120, 'triangle', 0.08, delay + 60 + i * 65)),
|
||||
/** Moves taken back (무르기). */
|
||||
undo: () => sfx.whoosh(),
|
||||
};
|
||||
Reference in New Issue
Block a user