From 8175cebd2c5fb6830dab204c214301d955ae01b2 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Tue, 13 Oct 2026 13:08:18 +0900 Subject: [PATCH] =?UTF-8?q?=EC=B2=B4=EC=8A=A4=C2=B7=EC=9E=A5=EA=B8=B0?= =?UTF-8?q?=C2=B7=EC=BF=BC=EB=A6=AC=EB=8F=84=20=EC=86=8C=EB=A6=AC=C2=B7?= =?UTF-8?q?=EC=9B=80=EC=A7=81=EC=9E=84,=20=EC=9E=A5=EA=B8=B0=20=EC=83=81?= =?UTF-8?q?=EC=B0=A8=EB=A6=BC=20=EC=8B=9C=EA=B0=84=20=EB=AC=B4=EC=A0=9C?= =?UTF-8?q?=ED=95=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 체스: 기물이 출발 칸에서 미끄러져 와 내려앉음(내가 끌어다 놓은 수는 제외), 캐슬링은 룩도 같이, 잡힌 기물(앙파상 폰 포함) 사라짐, 체크 칸 빛·말풍선 튀어나옴, 마지막 수 칸 살짝 나타남 - 체스 소리: 나무 기물 톡, 잡기, 캐슬링, 승진, 체크, 체크메이트 순간, 무르기, 기물 집기, 안 되는 칸 (fx.ts 순수 함수 + 테스트) - 장기: 묵직한 기물 미끄러짐·내려앉기, 잡힌 기물 사라짐, 장군 궁 자리 고동, 상차림 마·상 하나씩 튀어나옴 - 장기 소리: 두꺼운 나무 "딱", 잡기, 장군·멍군·빅장, 외통 순간, 한수쉼, 무르기, 상차림 놓기 (fx.ts + 테스트) - 장기 상차림 고르는 시간에 무제한(0) 추가, 방 설정 "자세한 설정"에서 30초·1분·3분·무제한 (기본 1분 그대로), 무제한이면 상차림 시계 숨김, 끊긴 사람만 접속 유예 뒤 자동 선택 - 쿼리도: 말 한 칸은 살짝 튀며, 점프는 높이 뛰어 넘음, 도착 칸 고리, 벽 내려앉기+먼지, 무르기로 빠진 벽 사라짐, 안 되는 벽 흔들림, 목표 도착 띠 깜빡임·금빛 고리 - 쿼리도 소리: 말 톡, 점프, 벽 끼우기, 안 되는 곳, 목표 도착, 무르기 - 상대·컴퓨터 수도 화면 변화로 같은 소리·움직임, 새로 열면 다시 재생 안 함, 숨은 탭 내 차례 소리는 방 화면에 맡김 Co-Authored-By: Claude Opus 5.5 --- apps/web/src/games/chess/fx.test.ts | 67 +++++++++++ apps/web/src/games/chess/fx.ts | 59 ++++++++++ apps/web/src/games/chess/index.tsx | 138 +++++++++++++++++------ apps/web/src/games/chess/sound.ts | 48 ++++++++ apps/web/src/games/janggi/fx.test.ts | 50 ++++++++ apps/web/src/games/janggi/fx.ts | 68 +++++++++++ apps/web/src/games/janggi/index.tsx | 131 ++++++++++++++++++--- apps/web/src/games/janggi/sound.ts | 62 ++++++++++ apps/web/src/games/quoridor/index.tsx | 132 +++++++++++++++++----- apps/web/src/games/quoridor/sound.ts | 34 ++++++ docs/games/chess.md | 3 +- docs/games/janggi.md | 5 +- docs/games/quoridor.md | 2 + packages/games/src/janggi/index.ts | 5 +- packages/games/src/janggi/janggi.test.ts | 24 ++++ 15 files changed, 746 insertions(+), 82 deletions(-) create mode 100644 apps/web/src/games/chess/fx.test.ts create mode 100644 apps/web/src/games/chess/fx.ts create mode 100644 apps/web/src/games/chess/sound.ts create mode 100644 apps/web/src/games/janggi/fx.test.ts create mode 100644 apps/web/src/games/janggi/fx.ts create mode 100644 apps/web/src/games/janggi/sound.ts create mode 100644 apps/web/src/games/quoridor/sound.ts diff --git a/apps/web/src/games/chess/fx.test.ts b/apps/web/src/games/chess/fx.test.ts new file mode 100644 index 0000000..3f7a783 --- /dev/null +++ b/apps/web/src/games/chess/fx.test.ts @@ -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' }] }); +}); diff --git a/apps/web/src/games/chess/fx.ts b/apps/web/src/games/chess/fx.ts new file mode 100644 index 0000000..26d5ab8 --- /dev/null +++ b/apps/web/src/games/chess/fx.ts @@ -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 }; +} diff --git a/apps/web/src/games/chess/index.tsx b/apps/web/src/games/chess/index.tsx index 71c5528..1621dba 100644 --- a/apps/web/src/games/chess/index.tsx +++ b/apps/web/src/games/chess/index.tsx @@ -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) { 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) { const [announce, setAnnounce] = useState(''); const svgRef = useRef(null); const prevCount = useRef(v.moves.length); - const movedRef = useRef(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(); @@ -158,43 +174,55 @@ function ChessBoard({ view: v, act, pending }: BoardProps) { 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(); + 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) { 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) { return (
+ ) { // 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) { 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) { const y = Math.floor(i / 8); return ; })} - {lastFrom && } - {lastTo && } + {lastFrom && lastTo && ( + + + + + )} {selected && } {v.threatened?.map((sq) => { const c = cell(sq); return ; })} - {check && } + {check && ( + + )} {/* Coordinates: files on the bottom row, ranks on the left column. */} {Array.from({ length: 8 }, (_, i) => ( @@ -345,17 +390,38 @@ function ChessBoard({ view: v, act, pending }: BoardProps) { ))} {hoverTarget && } + {/* 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 ( + + + + + + + + ); + })} {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 ( - - - - + + + + + + @@ -385,10 +451,12 @@ function ChessBoard({ view: v, act, pending }: BoardProps) { })} {check && ( - - - 체크! - + + + + 체크! + + )} {dragging && dragPos && ( diff --git a/apps/web/src/games/chess/sound.ts b/apps/web/src/games/chess/sound.ts new file mode 100644 index 0000000..7977652 --- /dev/null +++ b/apps/web/src/games/chess/sound.ts @@ -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 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 }); diff --git a/apps/web/src/games/janggi/fx.test.ts b/apps/web/src/games/janggi/fx.test.ts new file mode 100644 index 0000000..bc9008d --- /dev/null +++ b/apps/web/src/games/janggi/fx.test.ts @@ -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(); +}); diff --git a/apps/web/src/games/janggi/fx.ts b/apps/web/src/games/janggi/fx.ts new file mode 100644 index 0000000..ec832ef --- /dev/null +++ b/apps/web/src/games/janggi/fx.ts @@ -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 & { 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; +} diff --git a/apps/web/src/games/janggi/index.tsx b/apps/web/src/games/janggi/index.tsx index 0db7d3e..ca2da83 100644 --- a/apps/web/src/games/janggi/index.tsx +++ b/apps/web/src/games/janggi/index.tsx @@ -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 = { 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) { 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 { + 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 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 +
))} - {last && - [last.from, last.to].map((q, k) => { - const s = toScreen(q); - return ; - })} + {last && ( + + {[last.from, last.to].map((q, k) => { + const s = toScreen(q); + return ; + })} + + )} {kingInCheck >= 0 && (() => { const s = toScreen(fromKey(kingInCheck)); - return ; + return ( + + ); + })()} + {/* The captured piece shrinks away under the piece that took it. */} + {motion?.captured && (() => { + const s = toScreen(fromKey(motion.to)); + return ( + + + + ); })()} {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 ( + + + + + + ); + } + const pop = popped.indexOf(i); + if (pop >= 0) { + return ( + + + + ); + } return ; })} {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) ? : null; + // 상차림 시간 0 = 무제한: no countdown. + return v.setup.waitingFor.includes(side) && v.rules.setupTimeSec > 0 ? : 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) { const [more, setMore] = useState(false); const set = (patch: Partial) => onChange({ ...o, ...patch }); @@ -880,6 +976,9 @@ function Options({ value: o, onChange }: OptionsProps) { set({ setupOrder })} /> + + set({ setupTimeSec })} /> + set({ repetition })} /> diff --git a/apps/web/src/games/janggi/sound.ts b/apps/web/src/games/janggi/sound.ts new file mode 100644 index 0000000..8c7845f --- /dev/null +++ b/apps/web/src/games/janggi/sound.ts @@ -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 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 }); diff --git a/apps/web/src/games/quoridor/index.tsx b/apps/web/src/games/quoridor/index.tsx index 1e82b69..272d2ff 100644 --- a/apps/web/src/games/quoridor/index.tsx +++ b/apps/web/src/games/quoridor/index.tsx @@ -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 | 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(null); const prevCount = useRef(v.moveCount); - const prevWalls = useRef(v.walls.length); - const [newWall, setNewWall] = useState(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(); @@ -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): { 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 (
- + {goalSides.map((g, k) => { const sameSide = goalSides.filter((x, j) => j < k && x.side === g.side).length; - return ; + const glow = g.seat === goalSeat; + return ; })} {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 ( - + + {fall && } + + ); })} + {takenBack.map((w) => { + const s = t.wallToScreen(w); + return ; + })} + {recent?.kind === 'move' && (() => { + const to = t.cellToScreen(recent.to); + return ; + })()} + {recent?.kind === 'move' && goalSeat && (() => { + const to = t.cellToScreen(recent.to); + return ; + })()} {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 ( - + {turn && } - + {x.status === 'finished' && } + + + ); })} {lastTo && } {ghostCell && me && } {preview && previewAnchor && ( + + )} {myTurn && mode === 'wall' && ( @@ -509,6 +586,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp diff --git a/apps/web/src/games/quoridor/sound.ts b/apps/web/src/games/quoridor/sound.ts new file mode 100644 index 0000000..074ee72 --- /dev/null +++ b/apps/web/src/games/quoridor/sound.ts @@ -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(), +}; diff --git a/docs/games/chess.md b/docs/games/chess.md index 5a14e8e..816e03f 100644 --- a/docs/games/chess.md +++ b/docs/games/chess.md @@ -183,7 +183,8 @@ interface ChessResult { - 승진: 도착 시 큰 4개 버튼(퀸, 룩, 비숍, 나이트) 모달. - 캐슬링: 킹 선택 시 캐슬링 칸을 노란 테두리 + "캐슬링" 글씨로 표시(잡기 링과 헷갈리지 않게). standard: g1/c1. 960: 내 룩 칸, 그리고 킹이 갈 g/c열 칸(그 칸이 보통 킹 이동과 겹치지 않을 때)을 모두 표시하고, 판 아래에 "노란 테두리 칸을 누르세요" 안내. 960은 옆 패널에 [캐슬링: 킹 쪽 (O-O)] / [캐슬링: 퀸 쪽 (O-O-O)] 버튼도 둔다. 960 대국은 옆 패널에 "체스960 · 시작 배치 n번"을 보여 준다. - 체크 시 킹 칸 빨간 배경 + "체크!" 말풍선, 체크메이트·스테일메이트 결과 모달에 이유 설명(초보용: "킹이 피할 곳이 없어요"). -- 마지막 수 출발·도착 칸 강조, 이동 애니메이션 150ms 내외(저사양 고려). +- 마지막 수 출발·도착 칸 강조(살짝 나타남). 움직인 기물은 출발 칸에서 미끄러져 와 내려앉고(0.2~0.34초, 내가 끌어다 놓은 수는 미끄러지지 않음), 캐슬링은 룩도 같이 미끄러진다. 잡힌 기물(앙파상 폰 포함)은 그 자리에서 작아지며 사라지고, 체크 칸 빨간 빛이 퍼지듯 나타난다. 상대·컴퓨터 수도 똑같이 움직이고, 페이지를 새로 열거나 무르기를 하면 다시 재생하지 않는다(`apps/web/src/games/chess/fx.ts`). +- 효과음(화면 변화 기준, 한 번만): 나무 기물 "톡", 잡기, 캐슬링(두 번 톡톡), 승진, 체크(짧은 두 음), 체크메이트 순간(낮은 화음; 승패 음악은 결과 화면이 따로 냄), 무르기(휙), 내 기물 집기(작은 틱), 안 되는 칸(낮고 작은 소리). 사이트 음량을 따른다. - 규칙 보기: 기물별 움직임 애니메이션 카드, 특수 규칙(앙파상·캐슬링·승진) 그림 설명. - 시계 10초 이하 시 빨간색 + 효과음(끌 수 있음). - 관전자: 판 방향 전환 버튼, 기보 탐색(로컬). diff --git a/docs/games/janggi.md b/docs/games/janggi.md index d57a3fc..79223c1 100644 --- a/docs/games/janggi.md +++ b/docs/games/janggi.md @@ -20,6 +20,7 @@ | `moveLimit` | 수 제한(도달 시 점수 판정) | `0`(없음) / 150 / 200 / 250 (양쪽 합산 수) | `0` | | `timeControl.kind` | 시간 방식 | `none` / `byoyomi` | `byoyomi` | | `timeControl.mainSec` / `periodSec` / `periods` | 기본 시간 / 초읽기 1회 / 횟수 | 5분·10분·20분 / 20·30·60초 / 1~5회 | 10분 / 30초 / 3회 | +| `setupTimeSec` | 상차림 고르는 시간(초). 방 설정 "자세한 설정"에서 30초·1분·3분·무제한 | `0`(무제한) / 10~600 | `60` | | `undo` | 무르기 허용 횟수(상대 동의) | `off` / `1` / `3` / `unlimited` | `3` | | `drawOffer` | 무승부 제안 | `true` / `false` | `true` | | `hints` | 이동 가능 칸 표시 | `off` / `moves` | `moves` | @@ -190,7 +191,7 @@ interface JanggiState { ### 8.5 타이머·시간 초과·연결 끊김 시 자동 행동 - `deadline(state)`: - - `setup`: 단계 시작 + 60초(선택해야 할 사람 기준). + - `setup`: 단계 시작 + `setupTimeSec`초(선택해야 할 사람 기준). `setupTimeSec=0`이면 `null`(무제한, 상차림 시계도 숨김) — 연결이 끊긴 사람만 방의 접속 유예 뒤에 자동으로 골라 준다. - `playing` + `byoyomi`: `turnStartedAt + mainMs[turn] + periodsLeft[turn]*periodSec*1000`. - `playing` + `none`: `null` — 시간 제한 없음은 정말 마감이 없다(무응답 시간패 없음). 연결이 끊긴 사람만 방의 접속 유예(`graceSec`) 뒤에 처리한다. - 종료: `null`. @@ -220,6 +221,8 @@ interface JanggiResult { - 조작: 기물 탭 → 이동 가능 점 표시(잡기 가능 칸은 빨간 링) → 탭. 포는 포다리 기물을 살짝 강조해 이유가 보이게. - 상차림 화면: 4개 큰 카드(그림 + 이름 "안상차림 / 원앙마"), 한 화면에 미리보기. - "장군!" "멍군!" "빅장!" 큰 말풍선과 효과음(목소리 옵션). 외통 시 결과 모달. +- 효과음(화면 변화 기준, 한 번만): 두꺼운 나무 기물 "딱"(체스보다 낮고 묵직함), 잡기(두 번 부딪힘), 장군(올라가는 두 음)·멍군(내려가는 두 음)·빅장, 외통 순간(낮은 화음; 승패 음악은 결과 화면이 따로 냄), 한수쉼(가벼운 톡), 무르기(휙), 상차림 기물 놓기, 내 기물 집기(작은 틱), 안 되는 곳(낮고 작은 소리). +- 움직임: 기물이 출발점에서 미끄러져 와 묵직하게 내려앉고(0.2~0.36초), 잡힌 기물은 그 자리에서 작아지며 사라진다. 장군이면 궁 자리 빨간 원이 두 번 고동치듯 나타나고, 마지막 수 표시는 살짝 나타난다. 상차림으로 놓인 마·상은 하나씩 톡 튀어나온다. 상대·컴퓨터 수도 똑같이 움직이고, 페이지를 새로 열거나 무르기를 하면 다시 재생하지 않는다(`apps/web/src/games/janggi/fx.ts`). - 상단에 양측 점수 바(초 72 : 한 73.5) 상시 표시 → 판정 상황 이해 도움. - 한수쉼 버튼은 확인 모달. 반복 경고 배너. - 규칙 보기: 기물별 행마 애니메이션, 멱(막힘) 예시, 포다리 예시, 빅장 설명. diff --git a/docs/games/quoridor.md b/docs/games/quoridor.md index 08de103..dcedb18 100644 --- a/docs/games/quoridor.md +++ b/docs/games/quoridor.md @@ -179,6 +179,8 @@ interface QuoridorResult { - 힌트: 내 최단 경로를 점선으로, 벽 미리보기 중에는 "이 벽을 놓으면 상대 길이 +4칸" 같은 변화량 표시(초보에게 벽의 효과를 알려줌, 옵션). - 4인: 각 말 색과 목표 줄을 판 가장자리 색 띠로 표시. - 규칙 보기: 점프·대각 점프 그림, "길을 완전히 막으면 안 돼요" 그림. +- 움직임(화면 변화 기준이라 상대·컴퓨터 수도 같음, 새로 열면 다시 재생 안 함): 말은 한 칸이면 살짝 튀며 미끄러지고, 점프면 높이 뛰어 넘어가 내려앉으며 도착 칸에 고리가 한 번 퍼진다. 벽은 위에서 끼워지듯 내려앉고 홈을 따라 먼지가 퍼진다. 무르기로 빠진 벽은 작아지며 사라진다. 놓을 수 없는 벽 미리보기는 좌우로 흔들린다. 목표 줄에 닿으면 그 색 띠가 세 번 깜빡이고 말 주위에 금빛 고리가 퍼진다(`apps/web/src/games/quoridor/index.tsx`). +- 효과음(한 번의 변화에 한 번, 사이트 음량을 따름): 말 한 칸 "톡", 점프(올라가는 소리 뒤 착지 톡), 벽 끼우기(낮고 단단한 나무 소리), 안 되는 벽·칸(작고 낮은 소리), 목표 도착(짧게 올라가는 음, 승패 음악은 결과 화면이 냄), 무르기(휙)(`apps/web/src/games/quoridor/sound.ts`). ## 10. 테스트 체크리스트 - [ ] 2인/4인 시작 위치·목표·차례 순서, 3인 시작 거부. diff --git a/packages/games/src/janggi/index.ts b/packages/games/src/janggi/index.ts index d428bb0..3a6ae0e 100644 --- a/packages/games/src/janggi/index.ts +++ b/packages/games/src/janggi/index.ts @@ -62,7 +62,7 @@ export const janggiOptionsSchema = z.object({ }) .default({ kind: 'byoyomi', mainSec: 600, periodSec: 30, periods: 3 }) .meta({ title: '시간 제한' }), - setupTimeSec: z.number().int().min(10).max(600).default(60).meta({ title: '상차림 고르는 시간(초)' }), + setupTimeSec: z.number().int().min(0).max(600).default(60).meta({ title: '상차림 고르는 시간(초, 0이면 무제한)' }), undo: z .enum(['off', '1', '3', 'unlimited']) .default('3') @@ -722,7 +722,8 @@ export const janggi: GameDefinition 0 ? s.setup.startedAt + s.options.setupTimeSec * 1000 : null; if (s.phase !== 'playing') return null; const tc = s.options.timeControl; const start = s.clock.turnStartedAt; diff --git a/packages/games/src/janggi/janggi.test.ts b/packages/games/src/janggi/janggi.test.ts index cfb27ae..406c2ee 100644 --- a/packages/games/src/janggi/janggi.test.ts +++ b/packages/games/src/janggi/janggi.test.ts @@ -138,6 +138,30 @@ describe('setup (§4)', () => { expect(janggi.validate(fresh(), 'A', { type: 'timeout' }).ok).toBe(false); }); + test('setupTimeSec 0 = no setup deadline; a disconnected chooser can still be auto-picked', () => { + expect(opts().setupTimeSec).toBe(60); + expect(janggi.deadline!(fresh())).toBe(60_000); + expect(janggi.optionsSchema.safeParse({ setupTimeSec: 0 }).success).toBe(true); + expect(janggi.optionsSchema.safeParse({ setupTimeSec: -1 }).success).toBe(false); + const none = { setupTimeSec: 0, timeControl: { kind: 'none' as const, mainSec: 600, periodSec: 30, periods: 3 } }; + let s = fresh(none); + expect(janggi.deadline!(s)).toBeNull(); + // The room only fires the timeout after the disconnect grace (deadline null), so the players stay listed. + expect(janggi.timeoutPlayers!(s)).toEqual(['B']); + s = act(s, 'B', janggi.onTimeout(s, 'B'), 5_000_000); + expect(s.setup.choice.han).not.toBeNull(); + expect(janggi.deadline!(s)).toBeNull(); + s = act(s, 'A', { type: 'chooseSetup', arrangement: 'SMMS' }, 9_000_000); + expect(s.phase).toBe('playing'); + expect(janggi.deadline!(s)).toBeNull(); + // The main clock is independent: unlimited setup with byoyomi play still times the moves. + let t = fresh({ setupTimeSec: 0 }); + t = act(t, 'B', { type: 'chooseSetup', arrangement: 'MSSM' }); + t = act(t, 'A', { type: 'chooseSetup', arrangement: 'MSSM' }, 2000); + expect(janggi.deadline!(t)).toBe(2000 + 600_000 + 3 * 30_000); + expect(janggi.view(t, 'A').rules.setupTimeSec).toBe(0); + }); + test('resign during setup aborts without a result ranking', () => { const s = act(fresh(), 'A', { type: 'resign' }); expect(janggi.result(s)).toMatchObject({ ranking: [], reason: 'abandoned' });