병합: wt2/g1-board
This commit is contained in:
@@ -4,7 +4,8 @@ import type { BadukOptions, BadukView, Pt, ScoreBreakdown } from '@bg/games/badu
|
||||
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, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS, useAnimOver, useMoveDiff } from '../board-motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -35,9 +36,18 @@ function fmtScore(n: number, method: 'territory' | 'area'): string {
|
||||
return half ? (whole === 0 ? '반' : `${whole}.5`) : String(whole);
|
||||
}
|
||||
|
||||
/** Stones taken off the board: a few small clicks as they are picked up into the lid. */
|
||||
function captureSound(count: number) {
|
||||
for (let k = 0; k < Math.min(count, 6); k++) {
|
||||
tone(2100 + (k % 3) * 260, 28, 'triangle', 0.06, 150 + k * 55);
|
||||
noise(25, 0.05, 150 + k * 55, 'highpass', 4500);
|
||||
}
|
||||
}
|
||||
|
||||
function Stone({ color, cx, cy, r, ghost }: { color: Color; cx: number; cy: number; r: number; ghost?: boolean }) {
|
||||
return (
|
||||
<g opacity={ghost ? 0.5 : 1}>
|
||||
{!ghost && <ellipse cx={cx + r * 0.1} cy={cy + r * 0.16} rx={r} ry={r * 0.96} fill="#000" opacity={0.22} />}
|
||||
<circle cx={cx} cy={cy} r={r} fill={color === 'black' ? '#151515' : '#fbfbf8'} stroke={color === 'black' ? '#000' : '#666'} strokeWidth={0.05} />
|
||||
{color === 'black' ? (
|
||||
<circle cx={cx - r * 0.3} cy={cy - r * 0.3} r={r * 0.28} fill="#fff" opacity={0.15} />
|
||||
@@ -76,21 +86,33 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
return out;
|
||||
}, [v.scoring, v.result, v.board, n]);
|
||||
const seki = useMemo(() => new Set((v.scoring?.seki ?? []).map((p) => p.y * n + p.x)), [v.scoring?.seki, n]);
|
||||
// Board before the last move: the new stone sets down and captures fade only for moves seen live;
|
||||
// 무르기 lifts the taken-back stone and puts captured stones back.
|
||||
const { before, forward } = useMoveDiff(v.board, v.moveCount);
|
||||
const fresh = !!before && forward;
|
||||
const undone = before && !forward ? before.flatMap((c, i) => (c !== 0 && v.board[i] === 0 ? [{ i, color: (c === 1 ? 'black' : 'white') as Color }] : [])) : [];
|
||||
const [goneOver, goneEnd] = useAnimOver(v.moveCount);
|
||||
const restored = new Set(before && !forward ? v.board.flatMap((c, i) => (c !== 0 && before[i] === 0 ? [i] : [])) : []);
|
||||
|
||||
// Move sounds and announcements.
|
||||
// Move sounds and announcements (mine, the opponent's and the computer's).
|
||||
useEffect(() => {
|
||||
if (v.moveCount > prevCount.current) {
|
||||
const m = v.moves[v.moves.length - 1]!;
|
||||
if (m.pt) {
|
||||
sounds.stone();
|
||||
if (m.captured > 0) haptic(30);
|
||||
sfx.stone();
|
||||
if (m.captured > 0) {
|
||||
captureSound(m.captured);
|
||||
haptic(30);
|
||||
}
|
||||
setAnnounce(`${COLOR_KO[m.color]}이 ${label(n, m.pt)}에 두었어요.${m.captured ? ` 돌 ${m.captured}개를 따냈어요.` : ''}`);
|
||||
} else setAnnounce(`${COLOR_KO[m.color]}이 패스했어요.`);
|
||||
if (myTurn) {
|
||||
haptic(40);
|
||||
if (document.visibilityState === 'hidden') sounds.myTurn();
|
||||
} else {
|
||||
// 패스: a soft knock on the board edge.
|
||||
tone(330, 90, 'sine', 0.1);
|
||||
noise(50, 0.05, 0, 'lowpass', 700);
|
||||
setAnnounce(`${COLOR_KO[m.color]}이 패스했어요.`);
|
||||
}
|
||||
}
|
||||
if (myTurn) haptic(40);
|
||||
} else if (v.moveCount < prevCount.current) sfx.whoosh();
|
||||
prevCount.current = v.moveCount;
|
||||
setPreview(null);
|
||||
setBubble(null);
|
||||
@@ -109,6 +131,7 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
for (const i of dead) if (!before.has(i)) diff.add(i);
|
||||
for (const i of before) if (!dead.has(i)) diff.add(i);
|
||||
if (diff.size === 0) return;
|
||||
sfx.click();
|
||||
setChanged(diff);
|
||||
const t = setTimeout(() => setChanged(new Set()), 2500);
|
||||
return () => clearTimeout(t);
|
||||
@@ -142,6 +165,7 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
const why = illegal.get(p.y * n + p.x);
|
||||
if (why) {
|
||||
haptic([30, 30, 30]);
|
||||
sfx.bad();
|
||||
setBubble({ p, text: ILLEGAL_KO[why] });
|
||||
setAnnounce(ILLEGAL_KO[why]);
|
||||
return;
|
||||
@@ -186,6 +210,7 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
const pad = 0.95;
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
<style>{BOARD_MOTION_CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox={`${-pad} ${-pad} ${n - 1 + 2 * pad} ${n - 1 + 2 * pad}`}
|
||||
@@ -242,20 +267,35 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
const x = i % n;
|
||||
const y = Math.floor(i / n);
|
||||
const isDead = dead.has(i);
|
||||
const isLast = fresh && v.lastMove !== null && i === v.lastMove.y * n + v.lastMove.x;
|
||||
return (
|
||||
<g key={i} opacity={isDead ? 0.45 : 1}>
|
||||
<Stone color={color} cx={x} cy={y} r={0.47} />
|
||||
<g key={isLast ? `m${v.moveCount}` : i} opacity={isDead ? 0.45 : 1} style={{ transition: 'opacity 0.25s' }}>
|
||||
<g className={isLast ? 'bm-place' : restored.has(i) ? 'anim-pop' : undefined}>
|
||||
<Stone color={color} cx={x} cy={y} r={0.47} />
|
||||
</g>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{/* Stones just captured fade out. */}
|
||||
{v.phase === 'playing' &&
|
||||
v.lastCaptured.map((p) => (
|
||||
<g key={`cap${v.moveCount}-${p.x}-${p.y}`} opacity={0}>
|
||||
<animate attributeName="opacity" from={0.7} to={0} dur="0.6s" fill="freeze" />
|
||||
{/* Stones just captured are lifted off one by one; a stone taken back by 무르기 fades. */}
|
||||
{fresh &&
|
||||
!goneOver &&
|
||||
v.phase === 'playing' &&
|
||||
v.lastCaptured.map((p, k, all) => (
|
||||
<g
|
||||
key={`cap${v.moveCount}-${p.x}-${p.y}`}
|
||||
className="bm-gone"
|
||||
style={{ animationDelay: `${150 + Math.min(k, 6) * 55}ms` }}
|
||||
onAnimationEnd={k === all.length - 1 ? goneEnd : undefined}
|
||||
>
|
||||
<Stone color={lastColor ? other(lastColor) : 'white'} cx={p.x} cy={p.y} r={0.47} />
|
||||
</g>
|
||||
))}
|
||||
{!goneOver &&
|
||||
undone.map(({ i, color }) => (
|
||||
<g key={`u${v.moveCount}-${i}`} className="bm-gone" onAnimationEnd={goneEnd}>
|
||||
<Stone color={color} cx={i % n} cy={Math.floor(i / n)} r={0.47} />
|
||||
</g>
|
||||
))}
|
||||
{/* Territory / area marks (small squares) and seki marks. */}
|
||||
{score &&
|
||||
score.ownership.map((o, i) => {
|
||||
@@ -277,7 +317,10 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
</circle>
|
||||
))}
|
||||
{v.lastMove && lastColor && (
|
||||
<circle cx={v.lastMove.x} cy={v.lastMove.y} r={0.2} fill="none" stroke={lastColor === 'black' ? '#fff' : '#111'} strokeWidth={0.08} />
|
||||
<g key={`lm${v.moveCount}`}>
|
||||
{fresh && <circle className="bm-ring" cx={v.lastMove.x} cy={v.lastMove.y} r={0.5} fill="none" stroke={lastColor === 'black' ? '#111' : '#fafafa'} strokeWidth={0.06} />}
|
||||
<circle cx={v.lastMove.x} cy={v.lastMove.y} r={0.2} fill="none" stroke={lastColor === 'black' ? '#fff' : '#111'} strokeWidth={0.08} />
|
||||
</g>
|
||||
)}
|
||||
{myTurn &&
|
||||
v.atariWarnings.map((p) => (
|
||||
@@ -787,7 +830,7 @@ function Options({ value: o, onChange }: OptionsProps<BadukOptions>) {
|
||||
</div>
|
||||
<div className="stack" style={{ gap: 6 }}>
|
||||
<strong>사석 확인 제한 시간</strong>
|
||||
<Seg value={o.scoringDeadlineSec} options={[[120, '2분'], [180, '3분'], [300, '5분']]} onChange={(scoringDeadlineSec) => set({ scoringDeadlineSec })} />
|
||||
<Seg value={o.scoringDeadlineSec} options={[[120, '2분'], [180, '3분'], [300, '5분'], [0, '무제한']]} onChange={(scoringDeadlineSec) => set({ scoringDeadlineSec })} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
62
apps/web/src/games/board-motion.ts
Normal file
62
apps/web/src/games/board-motion.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* Shared movement for the two-player board games (오목·사목·오델로·체스·장기·바둑·쿼리도·윷놀이).
|
||||
* Everything reacts to the view changing, so the opponent's (and the computer's) moves get the same sound
|
||||
* and animation as mine. Animations are short and never take pointer events, so clicks are not slowed.
|
||||
* prefers-reduced-motion is handled by the global rule in styles/global.css.
|
||||
*/
|
||||
import { useRef, useState } from 'react';
|
||||
|
||||
/**
|
||||
* The snapshot from before the move counter last changed, and whether that change was a step forward.
|
||||
* `before` is null until the counter changes while the board is on screen, so a page load / reconnect shows
|
||||
* the position without replaying the last move. Computed during render (no extra frame without the piece).
|
||||
*/
|
||||
export function useMoveDiff<T>(snapshot: T, count: number): { before: T | null; forward: boolean } {
|
||||
const r = useRef<{ count: number; cur: T; before: T | null; forward: boolean }>({ count, cur: snapshot, before: null, forward: false });
|
||||
const s = r.current;
|
||||
if (count !== s.count) {
|
||||
s.before = s.cur;
|
||||
s.forward = count > s.count;
|
||||
s.count = count;
|
||||
}
|
||||
s.cur = snapshot;
|
||||
return { before: s.before, forward: s.forward };
|
||||
}
|
||||
|
||||
/**
|
||||
* For things shown only while they animate (captured / taken-back stones): `[over, end]`. Render them while
|
||||
* `over` is false and pass `end` to the last one's onAnimationEnd, so finished ghosts leave the DOM (and do not
|
||||
* count as pieces for tests or screen readers). A new `key` (move number) shows them again.
|
||||
*/
|
||||
export function useAnimOver(key: unknown): [boolean, () => void] {
|
||||
const [ended, setEnded] = useState<unknown>(undefined);
|
||||
return [ended === key, () => setEnded(key)];
|
||||
}
|
||||
|
||||
/**
|
||||
* SVG-friendly classes (scale around the element's own centre). Wrap the moving thing in its own `<g>` without a
|
||||
* `transform` attribute, because a CSS transform replaces the attribute while it runs.
|
||||
* - `bm-place`: a stone / piece set down (lands from a little above, slightly bigger, with a tiny settle).
|
||||
* - `bm-slide`: slides in from `--bm-dx/--bm-dy` (board units, e.g. `-2px` = two cells left) over `--bm-dur`.
|
||||
* - `bm-gone`: a captured piece shrinking and fading (key it by the move number; remove it with useAnimOver).
|
||||
* - `bm-ring`: one ripple ring around the last move.
|
||||
* - `bm-win`: winning line pulsing, staggered with `--bm-delay`.
|
||||
* - `bm-flash`: a quick bright flash (check / 장군).
|
||||
*/
|
||||
export const BOARD_MOTION_CSS = `
|
||||
.bm-place, .bm-gone, .bm-ring, .bm-win, .bm-flash { transform-box: fill-box; transform-origin: center; }
|
||||
.bm-place { animation: bm-place .26s cubic-bezier(.25, .9, .35, 1.25) both; pointer-events: none; }
|
||||
@keyframes bm-place { 0% { transform: translateY(-18%) scale(1.3); opacity: .15; } 70% { transform: translateY(0) scale(.97); opacity: 1; } 100% { transform: none; } }
|
||||
.bm-slide { animation: bm-slide var(--bm-dur, .24s) cubic-bezier(.3, .75, .35, 1) both; }
|
||||
@keyframes bm-slide { from { transform: translate(var(--bm-dx, 0px), var(--bm-dy, 0px)); } }
|
||||
.bm-gone { animation: bm-gone .42s ease-in forwards; pointer-events: none; }
|
||||
@keyframes bm-gone { 0% { opacity: 1; transform: scale(1); } 35% { opacity: .9; transform: scale(1.08); } 100% { opacity: 0; transform: scale(.35); } }
|
||||
.bm-ring { animation: bm-ring .55s ease-out .1s both; pointer-events: none; }
|
||||
@keyframes bm-ring { from { opacity: .85; transform: scale(.5); } to { opacity: 0; transform: scale(1.6); } }
|
||||
.bm-win { animation: bm-win 1.1s ease-in-out infinite; animation-delay: var(--bm-delay, 0ms); pointer-events: none; }
|
||||
@keyframes bm-win { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .45; transform: scale(1.12); } }
|
||||
.bm-flash { animation: bm-flash .7s ease-out both; pointer-events: none; }
|
||||
@keyframes bm-flash { 0% { opacity: 0; } 20% { opacity: 1; } 100% { opacity: .55; } }
|
||||
/* The global reduced-motion rule makes animations 0.01ms long; an endless pulse would then flicker. */
|
||||
@media (prefers-reduced-motion: reduce) { .bm-win { animation: none; } }
|
||||
`;
|
||||
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 });
|
||||
@@ -4,7 +4,7 @@ import type { Color, ConnectFourOptions, ConnectFourView } from '@bg/games/conne
|
||||
import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar, ConfirmSheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sounds } from '../../lib/feedback';
|
||||
import { haptic, noise, sfx, tone } from '../../lib/feedback';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -15,11 +15,20 @@ const SIZE_KO: Record<ConnectFourOptions['boardSize'], string> = { '7x6': '7×6'
|
||||
/** Row counted from the bottom, 1-based (what people say: "아래에서 두 번째 줄"). */
|
||||
const rowFromBottom = (v: ConnectFourView, y: number) => v.rows - y;
|
||||
|
||||
/** Falls with gravity, hits the bottom at LAND (fraction of the animation), bounces once a little and settles. */
|
||||
const LAND = 0.78;
|
||||
/** Fall time for a disc that lands in row `y` (0 = top). */
|
||||
const fallSec = (y: number) => (0.16 + 0.06 * (y + 1)) / LAND;
|
||||
const CSS = `
|
||||
@keyframes c4drop { from { transform: translateY(var(--c4-from)); } to { transform: translateY(0); } }
|
||||
.c4-drop { animation: c4drop var(--c4-dur) cubic-bezier(.5, 0, 1, 1) both; }
|
||||
@keyframes c4drop {
|
||||
0% { transform: translateY(var(--c4-from)); animation-timing-function: cubic-bezier(.5, 0, 1, 1); }
|
||||
${LAND * 100}% { transform: translateY(0); animation-timing-function: ease-out; }
|
||||
89% { transform: translateY(-0.13px); animation-timing-function: ease-in; }
|
||||
100% { transform: translateY(0); }
|
||||
}
|
||||
.c4-drop { animation: c4drop var(--c4-dur) linear both; }
|
||||
@keyframes c4glow { 50% { opacity: .35; } }
|
||||
.c4-win { animation: c4glow 1.1s ease-in-out infinite; }
|
||||
.c4-win { animation: c4glow 1.1s ease-in-out infinite; animation-delay: var(--c4-delay, 0ms); }
|
||||
.c4-svg { --c4-frame: #1d4ed8; --c4-frame-edge: #1e3a8a; }
|
||||
:root[data-theme='dark'] .c4-svg { --c4-frame: #1e40af; --c4-frame-edge: #172554; }
|
||||
@media (prefers-color-scheme: dark) { :root[data-theme='auto'] .c4-svg { --c4-frame: #1e40af; --c4-frame-edge: #172554; } }
|
||||
@@ -55,14 +64,16 @@ function C4Board({ view: v, act, pending, tapConfirm }: BoardProps<ConnectFourVi
|
||||
|
||||
useEffect(() => {
|
||||
if (v.moveCount > prevCount.current && v.lastMove) {
|
||||
sounds.stone();
|
||||
// A light rattle as it leaves the hand, then the plastic clack when it hits the bottom (and a small second tap).
|
||||
const land = fallSec(v.lastMove.y) * LAND * 1000;
|
||||
noise(Math.min(160, land), 0.04, 0, 'bandpass', 1800, 0.7);
|
||||
tone(620, 70, 'triangle', 0.2, land);
|
||||
noise(45, 0.12, land, 'lowpass', 1400);
|
||||
tone(760, 40, 'triangle', 0.07, land + 110);
|
||||
const m = v.moves[v.moves.length - 1]!;
|
||||
setAnnounce(`${COLOR_KO[m.color]}이 ${m.x + 1}열에 넣었어요. 아래에서 ${rowFromBottom(v, m.y)}번째 칸이에요.${m.auto ? ' (시간이 다 돼서 자동으로)' : ''}`);
|
||||
}
|
||||
if (v.phase === 'playing' && myTurn && prevTurn.current !== v.turn && v.moveCount !== prevCount.current) {
|
||||
haptic(40);
|
||||
if (document.visibilityState === 'hidden') sounds.myTurn();
|
||||
}
|
||||
if (v.phase === 'playing' && myTurn && prevTurn.current !== v.turn && v.moveCount !== prevCount.current) haptic(40);
|
||||
prevCount.current = v.moveCount;
|
||||
prevTurn.current = v.turn;
|
||||
setPreview(null);
|
||||
@@ -87,6 +98,7 @@ function C4Board({ view: v, act, pending, tapConfirm }: BoardProps<ConnectFourVi
|
||||
if (!myTurn) return;
|
||||
if (!open(c)) {
|
||||
haptic([30, 30, 30]);
|
||||
sfx.bad();
|
||||
setAnnounce(`${c + 1}열은 꽉 찼어요. 다른 열을 골라 주세요.`);
|
||||
return;
|
||||
}
|
||||
@@ -157,16 +169,38 @@ function C4Board({ view: v, act, pending, tapConfirm }: BoardProps<ConnectFourVi
|
||||
<g
|
||||
key={i}
|
||||
className={anim ? 'c4-drop' : undefined}
|
||||
style={anim ? ({ '--c4-from': `${-(y + 1.5)}px`, '--c4-dur': `${0.16 + 0.06 * (y + 1)}s` } as React.CSSProperties) : undefined}
|
||||
style={anim ? ({ '--c4-from': `${-(y + 1.5)}px`, '--c4-dur': `${fallSec(y)}s` } as React.CSSProperties) : undefined}
|
||||
>
|
||||
<Disc color={c === 1 ? 'red' : 'yellow'} cx={x + 0.5} cy={y + 0.5} r={0.41} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
<rect x={-pad} y={-pad} width={cols + 2 * pad} height={rows + 2 * pad} rx={0.3} fill="var(--c4-frame)" stroke="var(--c4-frame-edge)" strokeWidth={0.05} mask={`url(#${maskId})`} />
|
||||
{last >= 0 && !winSet.size && <circle cx={(last % cols) + 0.5} cy={Math.floor(last / cols) + 0.5} r={0.09} fill="#fff" opacity={0.85} />}
|
||||
{[...winSet].map((i) => (
|
||||
<circle key={`w${i}`} className="c4-win" cx={(i % cols) + 0.5} cy={Math.floor(i / cols) + 0.5} r={0.36} fill="none" stroke="#fff" strokeWidth={0.1} />
|
||||
{last >= 0 && !winSet.size && (
|
||||
// Shown once the falling disc has landed.
|
||||
<circle
|
||||
key={`lm${v.moveCount}`}
|
||||
className={falling.current === v.moveCount ? 'anim-pop' : undefined}
|
||||
style={{ '--anim-delay': `${fallSec(Math.floor(last / cols)) * 1000}ms`, transformBox: 'fill-box', transformOrigin: 'center' } as React.CSSProperties}
|
||||
cx={(last % cols) + 0.5}
|
||||
cy={Math.floor(last / cols) + 0.5}
|
||||
r={0.09}
|
||||
fill="#fff"
|
||||
opacity={0.85}
|
||||
/>
|
||||
)}
|
||||
{(v.winLine ?? []).map((p, k) => (
|
||||
<circle
|
||||
key={`w${p.x}-${p.y}`}
|
||||
className="c4-win"
|
||||
style={{ '--c4-delay': `${k * 120}ms` } as React.CSSProperties}
|
||||
cx={p.x + 0.5}
|
||||
cy={p.y + 0.5}
|
||||
r={0.36}
|
||||
fill="none"
|
||||
stroke="#fff"
|
||||
strokeWidth={0.1}
|
||||
/>
|
||||
))}
|
||||
{ghostCol !== null && v.myColor && <Disc color={v.myColor} cx={ghostCol + 0.5} cy={-0.55} r={0.41} ghost={preview === null} />}
|
||||
{myTurn && kbd && <rect x={cursor + 0.04} y={-1.08} width={0.92} height={rows + 1.04} rx={0.12} fill="none" stroke="var(--focus)" strokeWidth={0.07} />}
|
||||
|
||||
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,7 +4,8 @@ import type { OmokOptions, OmokView, Pt } from '@bg/games/omok';
|
||||
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, sfx } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS, useAnimOver, useMoveDiff } from '../board-motion';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -23,6 +24,7 @@ function stars(size: number): Pt[] {
|
||||
function Stone({ color, cx, cy, r, ghost }: { color: Color; cx: number; cy: number; r: number; ghost?: boolean }) {
|
||||
return (
|
||||
<g opacity={ghost ? 0.55 : 1}>
|
||||
{!ghost && <ellipse cx={cx + r * 0.1} cy={cy + r * 0.16} rx={r} ry={r * 0.96} fill="#000" opacity={0.22} />}
|
||||
<circle cx={cx} cy={cy} r={r} fill={color === 'black' ? '#151515' : '#fbfbf8'} stroke={color === 'black' ? '#000' : '#666'} strokeWidth={0.06} />
|
||||
{color === 'black' ? (
|
||||
<circle cx={cx - r * 0.3} cy={cy - r * 0.3} r={r * 0.28} fill="#fff" opacity={0.15} />
|
||||
@@ -46,18 +48,20 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
const prevTurn = useRef(v.turn);
|
||||
|
||||
const forbidden = useMemo(() => new Set(v.forbidden.map((p) => p.y * n + p.x)), [v.forbidden, n]);
|
||||
// What the board was before the last change: a new stone sets down, stones taken back by 무르기 fade away.
|
||||
const { before, forward } = useMoveDiff(v.board, v.moveCount);
|
||||
const lifted = before && !forward ? before.flatMap((c, i) => (c !== 0 && v.board[i] === 0 ? [{ i, color: (c === 1 ? 'black' : 'white') as Color }] : [])) : [];
|
||||
const fresh = !!before && forward;
|
||||
const [liftedOver, liftedEnd] = useAnimOver(v.moveCount);
|
||||
|
||||
// Sounds, vibration and screen-reader announcements on new moves.
|
||||
// Sounds, vibration and screen-reader announcements on new moves (mine, the opponent's and the computer's).
|
||||
useEffect(() => {
|
||||
if (v.moveCount > prevCount.current && v.lastMove) {
|
||||
sounds.stone();
|
||||
sfx.stone();
|
||||
const who = v.moves[v.moves.length - 1]!.color;
|
||||
setAnnounce(`${COLOR_KO[who]}이 ${label(n, v.lastMove)}에 두었어요.`);
|
||||
}
|
||||
if (v.phase === 'playing' && myTurn && (prevTurn.current !== v.turn || v.moveCount === 0) && v.moveCount !== prevCount.current) {
|
||||
haptic(40);
|
||||
if (document.visibilityState === 'hidden') sounds.myTurn();
|
||||
}
|
||||
} else if (v.moveCount < prevCount.current) sfx.whoosh();
|
||||
if (v.phase === 'playing' && myTurn && (prevTurn.current !== v.turn || v.moveCount === 0) && v.moveCount !== prevCount.current) haptic(40);
|
||||
prevCount.current = v.moveCount;
|
||||
prevTurn.current = v.turn;
|
||||
setPreview(null);
|
||||
@@ -77,6 +81,7 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
if (!myTurn || v.board[p.y * n + p.x] !== 0) return;
|
||||
if (forbidden.has(p.y * n + p.x)) {
|
||||
haptic([30, 30, 30]);
|
||||
sfx.bad();
|
||||
setAnnounce('여기는 금수 자리라 둘 수 없어요.');
|
||||
return;
|
||||
}
|
||||
@@ -113,11 +118,11 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
}
|
||||
};
|
||||
|
||||
const winSet = new Set((v.winLine ?? []).map((p) => p.y * n + p.x));
|
||||
const ghost = preview ?? (hover && canPlace(hover) ? hover : null);
|
||||
const pad = 0.9;
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
<style>{BOARD_MOTION_CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox={`${-pad} ${-pad} ${n - 1 + 2 * pad} ${n - 1 + 2 * pad}`}
|
||||
@@ -165,10 +170,40 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
<line x1={p.x + 0.2} y1={p.y - 0.2} x2={p.x - 0.2} y2={p.y + 0.2} />
|
||||
</g>
|
||||
))}
|
||||
{v.board.map((c, i) => (c === 0 ? null : <Stone key={i} color={c === 1 ? 'black' : 'white'} cx={i % n} cy={Math.floor(i / n)} r={0.46} />))}
|
||||
{v.lastMove && <circle cx={v.lastMove.x} cy={v.lastMove.y} r={0.13} fill="#ef4444" />}
|
||||
{[...winSet].map((i) => (
|
||||
<circle key={`win${i}`} cx={i % n} cy={Math.floor(i / n)} r={0.5} fill="none" stroke="#22c55e" strokeWidth={0.1} />
|
||||
{v.board.map((c, i) => {
|
||||
if (c === 0) return null;
|
||||
// The newest stone is keyed by the move number so it sets down again even on a re-used point (after 무르기).
|
||||
const isLast = fresh && v.lastMove !== null && i === v.lastMove.y * n + v.lastMove.x;
|
||||
return (
|
||||
<g key={isLast ? `m${v.moveCount}` : i} className={isLast ? 'bm-place' : undefined}>
|
||||
<Stone color={c === 1 ? 'black' : 'white'} cx={i % n} cy={Math.floor(i / n)} r={0.46} />
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{!liftedOver &&
|
||||
lifted.map(({ i, color }) => (
|
||||
<g key={`u${v.moveCount}-${i}`} className="bm-gone" onAnimationEnd={liftedEnd}>
|
||||
<Stone color={color} cx={i % n} cy={Math.floor(i / n)} r={0.46} />
|
||||
</g>
|
||||
))}
|
||||
{v.lastMove && (
|
||||
<g key={`lm${v.moveCount}`}>
|
||||
{fresh && <circle className="bm-ring" cx={v.lastMove.x} cy={v.lastMove.y} r={0.5} fill="none" stroke="#ef4444" strokeWidth={0.06} />}
|
||||
<circle className={fresh ? 'anim-pop' : undefined} style={{ animationDelay: '0.2s', transformBox: 'fill-box', transformOrigin: 'center' }} cx={v.lastMove.x} cy={v.lastMove.y} r={0.13} fill="#ef4444" />
|
||||
</g>
|
||||
)}
|
||||
{(v.winLine ?? []).map((p, k) => (
|
||||
<circle
|
||||
key={`win${p.x}-${p.y}`}
|
||||
className="bm-win"
|
||||
style={{ '--bm-delay': `${k * 110}ms` } as React.CSSProperties}
|
||||
cx={p.x}
|
||||
cy={p.y}
|
||||
r={0.5}
|
||||
fill="none"
|
||||
stroke="#22c55e"
|
||||
strokeWidth={0.1}
|
||||
/>
|
||||
))}
|
||||
{ghost && v.myColor && <Stone color={v.myColor} cx={ghost.x} cy={ghost.y} r={0.46} ghost />}
|
||||
{myTurn && kbd && <rect x={cursor.x - 0.5} y={cursor.y - 0.5} width={1} height={1} fill="none" stroke="var(--focus)" strokeWidth={0.06} />}
|
||||
|
||||
@@ -4,7 +4,8 @@ import type { OthelloLegalMove, OthelloOptions, OthelloView } from '@bg/games/ot
|
||||
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, sfx, tone } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS } from '../board-motion';
|
||||
import { toast } from '../../store/toast';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
@@ -20,19 +21,29 @@ const COLOR_KO: Record<Color, string> = { black: '흑', white: '백' };
|
||||
const other = (c: Color): Color => (c === 'black' ? 'white' : 'black');
|
||||
const label = (p: Pt) => `${'abcdefgh'[p.x]}${p.y + 1}`;
|
||||
const FLIP_MS = 240;
|
||||
/** The placed disc lands first; the flips start right after. */
|
||||
const PLACE_MS = 140;
|
||||
|
||||
const CSS = `
|
||||
@keyframes oth-flip { 0% { transform: scaleX(1); } 50% { transform: scaleX(0.05); } 100% { transform: scaleX(1); } }
|
||||
/* A disc is lifted a little while it turns over (edge-on in the middle), then set back down. */
|
||||
@keyframes oth-flip { 0% { transform: scale(1); } 50% { transform: scale(0.05, 1.14) translateY(-6%); } 100% { transform: scale(1); } }
|
||||
@keyframes oth-old { 0%, 50% { opacity: 1; } 50.01%, 100% { opacity: 0; } }
|
||||
@keyframes oth-drop { 0% { transform: scale(0.4); opacity: 0.4; } 100% { transform: scale(1); opacity: 1; } }
|
||||
.oth-flip { transform-box: fill-box; transform-origin: center; animation: oth-flip ${FLIP_MS}ms ease-in-out both; }
|
||||
.oth-old { animation: oth-old ${FLIP_MS}ms linear both; }
|
||||
.oth-drop { transform-box: fill-box; transform-origin: center; animation: oth-drop 160ms ease-out both; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.oth-flip, .oth-drop { animation: none; }
|
||||
.oth-flip { animation: none; }
|
||||
.oth-old { display: none; }
|
||||
}`;
|
||||
|
||||
/** Disc set down, then one light click per disc as it turns over (staggered like the animation). */
|
||||
function placeSound(flipDelays: number[]) {
|
||||
sfx.stone();
|
||||
flipDelays
|
||||
.sort((a, b) => a - b)
|
||||
.slice(0, 10)
|
||||
.forEach((d, k) => tone(1500 + (k % 4) * 90, 30, 'triangle', 0.06, d + FLIP_MS / 2));
|
||||
}
|
||||
|
||||
function Disc({ color, cx, cy, r = 0.4, ghost }: { color: Color; cx: number; cy: number; r?: number; ghost?: boolean }) {
|
||||
const black = color === 'black';
|
||||
return (
|
||||
@@ -74,6 +85,7 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
prevCount.current = v.moveCount;
|
||||
setPreview(null);
|
||||
if (v.moveCount <= prev) {
|
||||
if (v.moveCount < prev) sfx.whoosh();
|
||||
setAnim(null);
|
||||
return;
|
||||
}
|
||||
@@ -95,16 +107,17 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
setAnnounce(texts.join(' '));
|
||||
const lm = v.lastMove;
|
||||
if (lm && added.some((m) => m.kind === 'place')) {
|
||||
sounds.stone();
|
||||
const dist = (i: number) => Math.max(Math.abs((i % N) - lm.x), Math.abs(Math.floor(i / N) - lm.y));
|
||||
const maxD = Math.max(1, ...lm.flipped.map(dist));
|
||||
const step = maxD > 1 ? Math.min(60, (400 - FLIP_MS) / (maxD - 1)) : 0;
|
||||
setAnim({ key: v.moveCount, at: lm.y * N + lm.x, from: other(lm.color), delay: new Map(lm.flipped.map((i) => [i, (dist(i) - 1) * step])) });
|
||||
} else setAnim(null);
|
||||
if (v.phase === 'playing' && v.myColor === v.turn) {
|
||||
haptic(40);
|
||||
if (document.visibilityState === 'hidden') sounds.myTurn();
|
||||
const delay = new Map(lm.flipped.map((i) => [i, PLACE_MS + (dist(i) - 1) * step]));
|
||||
placeSound([...delay.values()]);
|
||||
setAnim({ key: v.moveCount, at: lm.y * N + lm.x, from: other(lm.color), delay });
|
||||
} else {
|
||||
if (added.length) sfx.whoosh();
|
||||
setAnim(null);
|
||||
}
|
||||
if (v.phase === 'playing' && v.myColor === v.turn) haptic(40);
|
||||
}, [v.moveCount]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const canPlace = (p: Pt) => myTurn && !pending && legal.has(p.y * N + p.x);
|
||||
@@ -178,7 +191,7 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
<style>{CSS}</style>
|
||||
<style>{BOARD_MOTION_CSS + CSS}</style>
|
||||
<div
|
||||
aria-label={`돌 수: 흑 ${v.discs.black}개, 백 ${v.discs.white}개`}
|
||||
role="img"
|
||||
@@ -263,7 +276,7 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
}
|
||||
if (anim && anim.at === i) {
|
||||
return (
|
||||
<g key={`a${anim.key}-${i}`} className="oth-drop">
|
||||
<g key={`a${anim.key}-${i}`} className="bm-place">
|
||||
<Disc color={color} cx={cx} cy={cy} />
|
||||
</g>
|
||||
);
|
||||
@@ -273,7 +286,12 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps<OthelloV
|
||||
{[...flipSet].map((i) => (
|
||||
<circle key={`h${i}`} cx={(i % N) + 0.5} cy={Math.floor(i / N) + 0.5} r={0.44} fill="rgba(255, 224, 102, 0.45)" stroke="#ffd84d" strokeWidth={0.05} />
|
||||
))}
|
||||
{v.lastMove && <circle cx={v.lastMove.x + 0.5} cy={v.lastMove.y + 0.5} r={0.1} fill="#ef4444" stroke="#fff" strokeWidth={0.025} />}
|
||||
{v.lastMove && (
|
||||
<g key={`lm${v.moveCount}`}>
|
||||
{anim && anim.at === v.lastMove.y * N + v.lastMove.x && <circle className="bm-ring" cx={v.lastMove.x + 0.5} cy={v.lastMove.y + 0.5} r={0.48} fill="none" stroke="#ffd84d" strokeWidth={0.05} />}
|
||||
<circle cx={v.lastMove.x + 0.5} cy={v.lastMove.y + 0.5} r={0.1} fill="#ef4444" stroke="#fff" strokeWidth={0.025} />
|
||||
</g>
|
||||
)}
|
||||
{showGhost && target && v.myColor && <Disc color={v.myColor} cx={target.x + 0.5} cy={target.y + 0.5} ghost />}
|
||||
{myTurn && kbd && <rect x={cursor.x + 0.04} y={cursor.y + 0.04} width={0.92} height={0.92} rx={0.08} fill="none" stroke="var(--focus)" strokeWidth={0.07} />}
|
||||
</svg>
|
||||
|
||||
@@ -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(),
|
||||
};
|
||||
@@ -9,6 +9,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { houseRules, optionsSummary } from './house-rules';
|
||||
import { quickStart } from './quick';
|
||||
import { HOP_MS, moveSound, throwSound } from './sound';
|
||||
|
||||
type From = number | 'home';
|
||||
/** A source the player can pick: a stack (`"7"`, or `"7#2"` when stacks stand apart on 7) or the waiting pieces (`"home"`). */
|
||||
@@ -110,13 +111,21 @@ const CSS = `
|
||||
.yut-sticks { width: 120px; height: 80px; flex: none; overflow: visible; }
|
||||
.yut-result { font-size: 2rem; font-weight: 900; min-width: 3ch; }
|
||||
.yut-toss .yut-stick { transform-box: fill-box; transform-origin: center; animation: yut-toss .8s cubic-bezier(.25,.7,.35,1) both; animation-delay: var(--d, 0ms); }
|
||||
@keyframes yut-toss { 0% { transform: translateY(0) rotate(0deg); } 45% { transform: translateY(-34px) rotate(260deg); } 75% { transform: translateY(2px) rotate(350deg); } 100% { transform: translateY(0) rotate(360deg); } }
|
||||
@keyframes yut-toss { 0% { transform: translateY(0) rotate(0deg); } 45% { transform: translateY(-34px) rotate(calc(var(--spin, 360deg) * .72)); } 75% { transform: translateY(2px) rotate(calc(var(--spin, 360deg) * .97)); } 88% { transform: translateY(-3px) rotate(var(--spin, 360deg)); } 100% { transform: translateY(0) rotate(var(--spin, 360deg)); } }
|
||||
.yut-nak { animation: anim-shake .45s ease both; }
|
||||
.yut-result.big { color: var(--danger); }
|
||||
/* Caught pieces stay put until the mover lands on them, then jump off and vanish. */
|
||||
.yut-caught { transform-box: fill-box; transform-origin: center; animation: yut-caught .5s ease-in both; animation-delay: var(--d, 0ms); pointer-events: none; }
|
||||
@keyframes yut-caught { 0% { transform: none; opacity: 1; } 35% { transform: translateY(-6px) rotate(-25deg) scale(1.1); opacity: 1; } 100% { transform: translateY(4px) rotate(-70deg) scale(.3); opacity: 0; } }
|
||||
/* One ripple where the piece landed (a bigger golden one when it went home). */
|
||||
.yut-ring { transform-box: fill-box; transform-origin: center; animation: yut-ring .55s ease-out both; animation-delay: var(--d, 0ms); pointer-events: none; }
|
||||
@keyframes yut-ring { 0% { opacity: 0; transform: scale(.5); } 10% { opacity: .9; } 100% { opacity: 0; transform: scale(1.7); } }
|
||||
@keyframes yut-glow { 0%, 100% { box-shadow: 0 0 0 0 rgba(245, 158, 11, .0); } 50% { box-shadow: 0 0 0 5px rgba(245, 158, 11, .35); } }
|
||||
@keyframes yut-pulse { 0%, 100% { opacity: .35; } 50% { opacity: 1; } }
|
||||
@keyframes yut-hop { 0% { transform: translateY(0); } 50% { transform: translateY(-5px); } 100% { transform: translateY(0); } }
|
||||
@keyframes yut-pop { from { transform: scale(.4); opacity: 0; } to { transform: scale(1); opacity: 1; } }
|
||||
.yut-can { animation: yut-pulse 1s ease-in-out infinite; }
|
||||
.yut-hop { transform-box: fill-box; transform-origin: center bottom; animation: yut-hop .17s ease-out; }
|
||||
.yut-hop { transform-box: fill-box; transform-origin: center bottom; animation: yut-hop .17s ease-out; pointer-events: none; }
|
||||
.yut-pop { transform-box: fill-box; transform-origin: center; animation: yut-pop .25s ease-out both; }
|
||||
.yut-hit { cursor: pointer; outline: none; }
|
||||
.yut-hit .yut-focus { opacity: 0; }
|
||||
@@ -127,6 +136,7 @@ const CSS = `
|
||||
.yut-badge { display: inline-block; border-radius: 999px; padding: 0 8px; font-weight: 800; font-size: .78rem; color: #fff; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.yut-toss .yut-stick, .yut-can, .yut-hop, .yut-pop, .yut-tray-btn.can { animation: none; }
|
||||
.yut-caught, .yut-ring { display: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -175,9 +185,9 @@ function TokenIcon({ side, team, size = 22 }: { side: number; team: boolean; siz
|
||||
}
|
||||
|
||||
/** One 윷가락: 배(flat side, light) or 등(round side, dark with marks). Stick 0 carries the 빽도 mark on its flat side. */
|
||||
function Stick({ x, flat, marked, delay }: { x: number; flat: boolean; marked: boolean; delay: number }) {
|
||||
function Stick({ x, flat, marked, delay, spin = 360 }: { x: number; flat: boolean; marked: boolean; delay: number; spin?: number }) {
|
||||
return (
|
||||
<g className="yut-stick" style={{ ['--d' as string]: `${delay}ms` }}>
|
||||
<g className="yut-stick" style={{ ['--d' as string]: `${delay}ms`, ['--spin' as string]: `${spin}deg` }}>
|
||||
<rect x={x} y={8} width={18} height={64} rx={9} fill={flat ? '#f6e4b8' : '#a86b2d'} stroke={flat ? '#9a7432' : '#5c3713'} strokeWidth={2} />
|
||||
{flat ? (
|
||||
<>
|
||||
@@ -195,6 +205,9 @@ function Stick({ x, flat, marked, delay }: { x: number; flat: boolean; marked: b
|
||||
);
|
||||
}
|
||||
|
||||
/** Each stick turns a different amount in the air (whole turns, so the face shown is the one thrown). */
|
||||
const SPINS = [360, -360, 720, -360];
|
||||
|
||||
function Sticks({ view: v, players }: { view: YutView; players: Record<string, PublicUser> }) {
|
||||
const lt = v.lastThrow;
|
||||
const [tossing, setTossing] = useState(false);
|
||||
@@ -213,17 +226,19 @@ function Sticks({ view: v, players }: { view: YutView; players: Record<string, P
|
||||
<div className="yut-sticks-box">
|
||||
<svg className={`yut-sticks${tossing ? ' yut-toss' : ''}`} viewBox="0 0 120 80" role="img" aria-label={lt ? `${nick(players, lt.player)}님이 던진 윷: ${lt.result === 'nak' ? '낙' : THROW_KO[lt.result]}` : '윷가락 네 개'}>
|
||||
{lt?.result === 'nak' ? (
|
||||
<g opacity={0.45} transform="rotate(-18 60 40)">
|
||||
{[0, 1, 2, 3].map((i) => (
|
||||
<Stick key={i} x={8 + i * 27} flat={i % 2 === 0} marked={false} delay={i * 40} />
|
||||
))}
|
||||
<g key={`nak${lt.no}`} className={tossing ? undefined : 'yut-nak'}>
|
||||
<g opacity={0.45} transform="rotate(-18 60 40)">
|
||||
{[0, 1, 2, 3].map((i) => (
|
||||
<Stick key={i} x={8 + i * 27} flat={i % 2 === 0} marked={false} delay={i * 40} spin={SPINS[i]!} />
|
||||
))}
|
||||
</g>
|
||||
</g>
|
||||
) : (
|
||||
sticks.map((f, i) => <Stick key={i} x={8 + i * 27} flat={f} marked={i === 0 && v.options.backdo} delay={i * 40} />)
|
||||
sticks.map((f, i) => <Stick key={i} x={8 + i * 27} flat={f} marked={i === 0 && v.options.backdo} delay={i * 40} spin={SPINS[i]!} />)
|
||||
)}
|
||||
</svg>
|
||||
<div>
|
||||
<div className="yut-result" aria-hidden>
|
||||
<div key={tossing ? 'toss' : `r${lt?.no ?? 0}`} className={`yut-result${lt && !tossing ? ' anim-pop' : ''}${lt && (lt.result === 'yut' || lt.result === 'mo') ? ' big' : ''}`} aria-hidden>
|
||||
{label}
|
||||
</div>
|
||||
{lt && !tossing && <div className="small muted">{nick(players, lt.player)}님</div>}
|
||||
@@ -255,6 +270,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const [anim, setAnim] = useState<Anim | null>(null);
|
||||
const [flash, setFlash] = useState<{ text: string; at: [number, number]; key: number } | null>(null);
|
||||
const [landing, setLanding] = useState<{ no: number; at: [number, number]; delayMs: number; goal: boolean; victims: { side: number; count: number }[] } | null>(null);
|
||||
const lastMoveNo = useRef(v.lastMove?.no ?? 0);
|
||||
const lastThrowNo = useRef(v.lastThrow?.no ?? 0);
|
||||
const prevCurrent = useRef(v.current);
|
||||
@@ -289,7 +305,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
lastThrowNo.current = lt.no;
|
||||
const who = lt.player === me ? '내가' : `${nick(players, lt.player)}님이`;
|
||||
setAnnounce(lt.result === 'nak' ? `${who} 던진 윷이 판 밖으로 떨어졌어요(낙).` : `${who} ${THROW_KO[lt.result]}를 던졌어요.`);
|
||||
sounds.stone();
|
||||
throwSound(lt.result, !reducedMotion());
|
||||
}
|
||||
}, [v.lastThrow?.no]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
@@ -309,9 +325,13 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
const text = caught ? '잡았다!' : m.to === 'goal' ? '났다!' : m.stacked ? '업었다!' : null;
|
||||
if (text) setFlash({ text, at: end, key: m.no });
|
||||
if (caught) haptic([40, 30, 40]);
|
||||
if (reducedMotion()) return;
|
||||
const pts: [number, number][] = [m.from === 'home' ? HOME_PT : POS[m.from]!, ...m.path.map((n) => POS[n]!)];
|
||||
if (m.to === 'goal') pts.push(HOME_PT);
|
||||
const still = reducedMotion();
|
||||
moveSound(pts.length - 1, caught ? 'capture' : m.to === 'goal' ? 'goal' : m.stacked ? 'stack' : 'plain', !still);
|
||||
// Landing effects (ripple, caught pieces jumping off) wait for the hopping piece.
|
||||
setLanding({ no: m.no, at: end, delayMs: still ? 0 : (pts.length - 1) * HOP_MS, goal: m.to === 'goal', victims: m.captured });
|
||||
if (still) return;
|
||||
setAnim({ no: m.no, pts, i: 0, side: m.side, count: m.count, to: m.to, caught: caught > 0 });
|
||||
}, [v.lastMove?.no]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
@@ -325,6 +345,12 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
return () => clearTimeout(t);
|
||||
}, [anim]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!landing) return;
|
||||
const t = setTimeout(() => setLanding((l) => (l && l.no === landing.no ? null : l)), landing.delayMs + 700);
|
||||
return () => clearTimeout(t);
|
||||
}, [landing]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!flash) return;
|
||||
const t = setTimeout(() => setFlash(null), 1100);
|
||||
@@ -334,7 +360,8 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
useEffect(() => {
|
||||
if (v.current !== prevCurrent.current && v.current === me && v.phase !== 'finished') {
|
||||
haptic(40);
|
||||
sounds.myTurn();
|
||||
// A hidden tab gets the chime from the room page.
|
||||
if (document.visibilityState !== 'hidden') sounds.myTurn();
|
||||
}
|
||||
prevCurrent.current = v.current;
|
||||
}, [v.current]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
@@ -462,6 +489,25 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
|
||||
)}
|
||||
</g>
|
||||
)}
|
||||
{landing &&
|
||||
landing.victims.map((c, k) => (
|
||||
<g key={`c${landing.no}-${k}`} className="yut-caught" style={{ ['--d' as string]: `${landing.delayMs}ms` }}>
|
||||
<Token side={c.side} team={v.team} x={landing.at[0] + (k - (landing.victims.length - 1) / 2) * 5} y={landing.at[1]} r={4.2} count={c.count} />
|
||||
</g>
|
||||
))}
|
||||
{landing && (
|
||||
<circle
|
||||
key={`r${landing.no}`}
|
||||
className="yut-ring"
|
||||
style={{ ['--d' as string]: `${landing.delayMs}ms` }}
|
||||
cx={landing.at[0]}
|
||||
cy={landing.at[1]}
|
||||
r={landing.goal ? 8 : 6}
|
||||
fill="none"
|
||||
stroke={landing.goal ? '#fbbf24' : landing.victims.length ? 'var(--danger)' : 'var(--focus)'}
|
||||
strokeWidth={landing.goal ? 1.6 : 1.1}
|
||||
/>
|
||||
)}
|
||||
{anim && (
|
||||
<g key={`${anim.no}-${anim.i}`} className="yut-hop">
|
||||
<Token side={anim.side} team={v.team} x={anim.pts[anim.i]![0]} y={anim.pts[anim.i]![1]} r={4.4} count={anim.count} />
|
||||
|
||||
72
apps/web/src/games/yut/sound.ts
Normal file
72
apps/web/src/games/yut/sound.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* 윷놀이 소리: 나무 윷가락이 멍석에 떨어지는 소리, 말 한 칸씩 콩콩, 잡기·업기·나기.
|
||||
* Everything is played from view changes (mine, other players' and the computer's turns alike);
|
||||
* the site volume is applied inside feedback.ts.
|
||||
*/
|
||||
import type { Throw } from '@bg/games/yut';
|
||||
import { noise, tone } from '../../lib/feedback';
|
||||
|
||||
/** When the tossed sticks hit the mat (ms), matching `yut-toss` in index.tsx (bounce at 75% of 0.8s). */
|
||||
export const STICKS_LAND_MS = 600;
|
||||
/** One hop of a piece along its path (ms), matching the board animation. */
|
||||
export const HOP_MS = 170;
|
||||
|
||||
/** One wooden stick hitting the mat: a short dry knock. */
|
||||
function knock(delay: number, pitch: number, gain = 1): void {
|
||||
tone(420 * pitch, 40, 'triangle', 0.12 * gain, delay, { slideTo: 300 * pitch });
|
||||
noise(32, 0.09 * gain, delay, 'bandpass', 1700 * pitch, 1.2);
|
||||
}
|
||||
|
||||
/** A small piece hopping one node: soft "콩". */
|
||||
function hop(delay: number, gain = 1): void {
|
||||
tone(640, 35, 'triangle', 0.07 * gain, delay, { slideTo: 520 });
|
||||
noise(20, 0.035 * gain, delay, 'bandpass', 2200, 1.4);
|
||||
}
|
||||
|
||||
/**
|
||||
* The sticks: a swish as they leave the hand, four knocks as they land (staggered like the animation), then a
|
||||
* short call for the result. `toss` = false when the animation is off (reduced motion): no swish, no wait.
|
||||
*/
|
||||
export function throwSound(result: Throw | 'nak', toss: boolean): void {
|
||||
const land = toss ? STICKS_LAND_MS : 0;
|
||||
if (toss) noise(260, 0.05, 0, 'bandpass', 700, 0.7);
|
||||
if (result === 'nak') {
|
||||
// Off the mat: one dull thud and a sorry low note.
|
||||
noise(120, 0.12, land, 'lowpass', 500);
|
||||
tone(220, 260, 'triangle', 0.07, land + 120, { slideTo: 150 });
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < 4; i++) knock(land + i * 40 + (i % 2) * 12, 1 + ((i * 7) % 5) * 0.05, 0.8 + (i % 2) * 0.2);
|
||||
const call = land + 220;
|
||||
if (result === 'yut' || result === 'mo') {
|
||||
// 한 번 더! a bright rising run (모 a step higher).
|
||||
const base = result === 'mo' ? [659, 880, 1046, 1318] : [587, 784, 988];
|
||||
base.forEach((f, i) => tone(f, 110, 'triangle', 0.08, call + i * 70));
|
||||
} else if (result === 'backdo') {
|
||||
// 빽도: a little slide back down.
|
||||
tone(700, 220, 'sine', 0.08, call, { slideTo: 350 });
|
||||
}
|
||||
}
|
||||
|
||||
/** A piece moved `steps` nodes: one hop each, then the landing (capture / 업기 / 나기 on the last one). */
|
||||
export function moveSound(steps: number, landing: 'plain' | 'capture' | 'stack' | 'goal', animated: boolean): void {
|
||||
const gap = animated ? HOP_MS : 0;
|
||||
const n = animated ? Math.max(1, steps) : 1;
|
||||
for (let i = 1; i < n; i++) hop(i * gap, 0.8);
|
||||
const at = animated ? n * gap : 0;
|
||||
if (landing === 'capture') {
|
||||
// Landing on them, then the caught pieces knocked off the board.
|
||||
hop(at, 1.3);
|
||||
tone(560, 70, 'square', 0.05, at + 40);
|
||||
tone(280, 150, 'triangle', 0.11, at + 90);
|
||||
noise(140, 0.06, at + 110, 'bandpass', 900, 0.6);
|
||||
} else if (landing === 'stack') {
|
||||
// 업기: two pieces clicking together.
|
||||
hop(at, 1.2);
|
||||
hop(at + 80, 1);
|
||||
tone(988, 60, 'triangle', 0.06, at + 80);
|
||||
} else if (landing === 'goal') {
|
||||
hop(at, 1);
|
||||
[523, 659, 784, 1046].forEach((f, i) => tone(f, 120, 'triangle', 0.08, at + 60 + i * 65));
|
||||
} else hop(at, 1.3);
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
| `undo` | 무르기 허용 횟수(1인당, 상대 동의) | `off` / `1` / `3` / `unlimited` | `3` |
|
||||
| `drawOffer` | 무승부(빅) 합의 제안 허용 | `true` / `false` | `true` |
|
||||
| `atariWarning` | **관리자 전용** 위협 가이드: 단수에 몰린 내 돌 표시(방장은 못 바꿈) | `true` / `false` | `false` |
|
||||
| `scoringDeadlineSec` | 사석 확인 단계 제한 시간 | 120 / 180 / 300 | 180 |
|
||||
| `scoringDeadlineSec` | 사석 확인 단계 제한 시간 | 120 / 180 / 300 / 0(무제한) | 180 |
|
||||
| `disconnectGraceSec` | 연결 끊김 유예 | 60 / 120 / 300 | 120 |
|
||||
|
||||
## 3. 구성물
|
||||
@@ -84,7 +84,7 @@
|
||||
3. 표시가 바뀌면 양쪽 `agreed`가 모두 해제된다. 현재 표시를 기준으로 계가 미리보기가 실시간으로 갱신된다.
|
||||
4. 두 플레이어가 같은 표시 상태에 대해 모두 "동의"하면 계가 확정 → 종료.
|
||||
5. 어느 한쪽이 "이의 – 대국 재개"를 누르면 표시를 모두 버리고 `playing`으로 복귀한다. 재개 후 첫 수는 재개를 요청한 사람의 상대가 둔다(일본기원 규약 제9조와 같은 방식). 재개 후 다시 연속 2패스가 나오면 5.5를 다시 진행한다.
|
||||
6. 사석 확인 단계에서 시계는 멈춘다. 대신 `scoringDeadlineSec` 제한이 있다(8.5).
|
||||
6. 사석 확인 단계에서 시계는 멈춘다. 대신 `scoringDeadlineSec` 제한이 있다(8.5). `0`(무제한)이면 마감 없이 두 사람이 동의할 때까지 기다린다(타이머 숨김, 자리를 떠난 사람은 `onLeave`로 처리).
|
||||
- 자동 제안 휴리스틱(단순·결정적): (a) 활로 1개인 연결 중 그 활로에 상대가 두면 따내지고 되따기도 불가능한 것, (b) 상대 영역(상대 돌로만 둘러싸인 빈 영역)에 완전히 갇혀 있고 그 영역 안에서 두 눈(서로 떨어진 두 개 이상의 단독 빈 영역)이 없는 연결. 오판이 있어도 플레이어가 고치면 되므로 단순하게 둔다. 향후 KataGo 같은 엔진 기반 추정은 별도 작업으로 분리.
|
||||
|
||||
### 5.6 공배와 빅(세키)
|
||||
@@ -202,7 +202,7 @@ interface BadukState {
|
||||
- `playing` + `byoyomi`: `turnStartedAt + mainMs[turn] + periodsLeft[turn] * periodSec*1000` (현재 회차를 다 쓰면 다음 회차가 이어지므로 이 합이 최종 시간패 시각)
|
||||
- `playing` + `fischer`: `turnStartedAt + mainMs[turn]`
|
||||
- `playing` + `none`: `null` — 시간 제한 없음은 정말 마감이 없다(무응답 시간패 없음). 연결이 끊긴 사람만 방의 접속 유예(`graceSec`) 뒤에 처리한다.
|
||||
- `scoring`: `scoringMarks.startedAt + scoringDeadlineSec*1000`
|
||||
- `scoring`: `scoringMarks.startedAt + scoringDeadlineSec*1000` (`0`이면 `null`)
|
||||
- `finished`: `null`
|
||||
- `activePlayers`: `playing`이면 차례인 1명. `scoring`이면 아직 `agreed`하지 않은 플레이어 전원(동시 행동 단계).
|
||||
- `onTimeout(state, player)` → `{ type: 'timeout' }`. `apply` 처리:
|
||||
@@ -231,6 +231,7 @@ interface BadukResult {
|
||||
- 모바일 세로: 상단 상대 정보(따낸 돌, 시계 + 초읽기 남은 횟수 점 3개), 가운데 정사각 판, 하단 내 정보와 버튼(패스, 무르기, 무승부, 기권, 규칙 보기).
|
||||
- 19줄은 교차점 간격이 약 18px라 "탭 → 미리보기 돌 + 확대 돋보기 → 확인 버튼" 2단계 착수가 기본. 9줄은 한 번 탭 착수 옵션 제공.
|
||||
- 마지막 수 표시, 따낸 돌 사라지는 애니메이션과 효과음(끌 수 있음), 단수 경고(옵션) 시 해당 연결 테두리 깜빡임.
|
||||
- 소리·움직임(2026-10-13): 새 돌은 살짝 위에서 내려앉고 마지막 수에 고리가 한 번 퍼진다("딱" = `sfx.stone`). 따낸 돌은 한 알씩 들어 올리듯 작아지며 사라지고, 그 수만큼(최대 6) 작은 "딸깍" 소리가 이어진다. 패스는 낮은 "톡", 무르기는 물린 돌이 사라지고 따냈던 돌이 다시 나타나며 `sfx.whoosh`. 사석 확인에서 표시가 바뀌면 `sfx.click`. 상대·컴퓨터의 수에도 똑같이 나오고, 새로 고침했을 땐 움직이지 않는다.
|
||||
- 패/자충 금지점을 탭하면 이유 말풍선.
|
||||
- 초읽기 진입 시 음성/효과음 카운트("10, 9, …")와 화면 테두리 색 변화(어르신 배려: 큰 숫자).
|
||||
- 패스 버튼은 실수 방지를 위해 확인 모달. 상대가 패스하면 "상대가 패스했어요. 끝내려면 패스하세요" 안내.
|
||||
|
||||
@@ -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초 이하 시 빨간색 + 효과음(끌 수 있음).
|
||||
- 관전자: 판 방향 전환 버튼, 기보 탐색(로컬).
|
||||
|
||||
@@ -111,7 +111,8 @@ interface ConnectFourState {
|
||||
- 떨어지는 애니메이션: 새 원반만, 떨어지는 높이에 비례해 0.2~0.6초. `prefers-reduced-motion`이면 애니메이션 없음(이긴 줄 깜빡임도 끔). 처음 들어오거나 새로 고침했을 땐 애니메이션 없음.
|
||||
- 열 전체(미리 보기 줄 포함)가 터치 영역 — 7×6 판이 휴대폰 390px에서 열 너비 약 50px. 마우스는 한 번 누르면 바로 넣기(올려 두면 미리 보기). 터치는 "한 번 더 누르기 확인" 설정이 켜져 있으면 처음 누르면 미리 보기, 같은 열을 다시 누르거나 [N열에 넣기]로 확정.
|
||||
- 키보드: 판(`role="grid"`)에 초점 → ←·→로 열 고르기, Home·End로 끝 열, Enter·Space로 넣기. 꽉 찬 열이면 스크린리더에 "N열은 꽉 찼어요" 안내. 둘 때마다 "빨강이 4열에 넣었어요. 아래에서 2번째 칸이에요." 읽어 줌.
|
||||
- 마지막 수에 흰 점, 이긴 줄은 흰 고리로 강조(깜빡임).
|
||||
- 마지막 수에 흰 점(원반이 닿은 뒤 나타남), 이긴 줄은 흰 고리로 강조(줄 순서대로 번갈아 깜빡임).
|
||||
- 소리·움직임(2026-10-13): 원반은 떨어져 바닥에 닿은 뒤 한 번 살짝 튀고 멈춘다. 소리는 손을 떠날 때 작은 달그락, 바닥에 닿는 순간 플라스틱 "탁"과 작은 두 번째 탁(떨어지는 시간에 맞춤). 꽉 찬 열을 누르면 작은 `sfx.bad`. 상대·컴퓨터의 수에도 똑같이 나온다.
|
||||
- 오른쪽 패널(휴대폰은 판 아래): 두 사람(색, 먼저/나중, 남은 시간), 기권 버튼(확인 창), 기보("1. 🔴 4열", 자동 두기는 *).
|
||||
- 다크 모드: 틀 색을 조금 어둡게, 구멍은 배경색.
|
||||
- 30초 요약 3장: 열 골라 넣기 / 4개 이으면 승리 / 3개면 꼭 막기. [?] 도움말: 차례, 꽉 찬 열, 첫 수 가운데 팁, 3개 막기 팁.
|
||||
|
||||
@@ -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) 상시 표시 → 판정 상황 이해 도움.
|
||||
- 한수쉼 버튼은 확인 모달. 반복 경고 배너.
|
||||
- 규칙 보기: 기물별 행마 애니메이션, 멱(막힘) 예시, 포다리 예시, 빅장 설명.
|
||||
|
||||
@@ -289,6 +289,7 @@ interface OmokResult {
|
||||
- 모바일 세로: 상단에 상대 정보(닉네임, 돌 색, 남은 시간 바), 가운데 정사각 판(화면 폭 100%), 하단에 내 정보와 버튼 줄(무르기, 무승부, 기권, 규칙 보기). 15줄 판은 폰 폭 360px에서 교차점 간격이 약 23px라 48px 터치 기준을 못 맞추므로, 착수는 "탭 → 확대 미리보기 돌 표시 → 확인 버튼(48px 이상)" 2단계로 한다. 옵션으로 "한 번 탭으로 바로 두기"(PC 기본값).
|
||||
- 판 핀치 줌/드래그 지원(19줄 필수).
|
||||
- 마지막 수 표시(빨간 점), 승리 줄 강조 애니메이션.
|
||||
- 소리·움직임(2026-10-13): 새 돌은 살짝 위에서 내려앉고(0.26초) 마지막 수 자리에 고리가 한 번 퍼진다. 착수 소리는 공통 `sfx.stone`("딱"), 무르기는 물린 돌이 작아지며 사라지고 `sfx.whoosh`, 금수 자리를 누르면 작은 `sfx.bad`. 이긴 다섯 돌의 초록 고리는 줄 순서대로 번갈아 반짝인다. 상대·컴퓨터의 수에도 똑같이 나오고, 처음 들어오거나 새로 고침했을 땐 움직이지 않는다. 승패 소리는 결과 화면(공통)이 낸다.
|
||||
- 금수 자리는 흑 차례일 때 작은 ×표. 금수 자리 탭 시 이유를 말풍선으로 설명("여기는 쌍삼이라 둘 수 없어요").
|
||||
- 힌트 켜짐: 상대가 열린 삼/사를 만들면 해당 줄을 노란색으로 잠깐 표시.
|
||||
- 무르기/무승부 요청은 상대 화면에 큰 모달(수락/거절 버튼 각 48px 이상).
|
||||
|
||||
@@ -122,7 +122,8 @@ interface OthelloResult {
|
||||
## 9. UI/UX
|
||||
- 모바일 세로: 상단 상대(돌 수, 시계), 가운데 8×8 판(폰 360px에서 칸 약 44px — 칸 전체가 터치 영역, 48px에 근접하므로 한 번 탭 착수 허용), 하단 내 정보와 버튼.
|
||||
- 둘 수 있는 칸은 작은 반투명 점. `showFlipCount`면 숫자.
|
||||
- 착수 시 뒤집히는 돌을 놓은 돌에서 가까운 순서로 순차 회전 애니메이션(전체 400ms 이내).
|
||||
- 착수 시 뒤집히는 돌을 놓은 돌에서 가까운 순서로 순차 회전 애니메이션(전체 400ms 이내). 놓은 돌이 먼저 내려앉고(0.14초) 그다음 뒤집기가 시작되며, 뒤집히는 돌은 옆으로 서는 순간 살짝 들린다.
|
||||
- 소리(2026-10-13): 놓을 때 `sfx.stone`, 돌이 하나 뒤집힐 때마다 작은 "딸깍"(최대 10번, 애니메이션 순서에 맞춤), 패스·무르기는 `sfx.whoosh`. 마지막 수 자리에 노란 고리가 한 번 퍼진다. 상대·컴퓨터의 수에도 똑같이 나온다.
|
||||
- 자동 패스 시 "둘 곳이 없어서 차례가 넘어갔어요" 토스트(상대 화면에도).
|
||||
- 돌 수 막대(흑/백 비율)를 상단에 상시 표시.
|
||||
- 규칙 보기: 끼워서 뒤집기 3단계 그림, 패스 설명, 모서리 팁(선택).
|
||||
|
||||
@@ -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인 시작 거부.
|
||||
|
||||
@@ -241,7 +241,8 @@ interface YutResult {
|
||||
- 조작: 결과 칩을 먼저 누르고 → 움직일 수 있는 말이 반짝이고 → 말을 누르면 도착 자리가 표시되고 → 다시 누르면 확정(오조작 방지 2단계). 결과가 1개이고 움직일 말이 1가지면 "자동 이동" 버튼 강조.
|
||||
- 지역 룰 선택(7.1): 고른 말에 다른 길이나 따로 두기가 있으면 [이동하기] 위에 "갈 길 고르기"(지름길/바깥 길, 방에서는 참먹이 쪽/찌모 쪽, 도착 자리와 잡기 표시)와 "업기(함께 움직임)/따로 두기" 버튼이 나오고, 점선 미리보기가 고른 대로 바뀐다. 말을 한 번 더 누르면 고른 대로 움직인다. 따로 선 무더기는 한 자리에 나란히 작게 그린다. 던진 순서대로(`useOrder = thrown`)면 맨 앞 결과 칩만 눌린다.
|
||||
- 합법 수 하이라이트: 도착 자리에 점선 경로 미리보기. 잡을 수 있으면 빨간 테두리 "잡기!", 업기면 "업기", 나면 "날!" 배지.
|
||||
- 애니메이션: 윷가락 4개가 공중에서 돌다 떨어지는 0.8초 애니메이션(서버 결과를 받은 뒤 재생, 결과 조작 불가). 말은 칸마다 통통 튀며 이동. 잡힌 말은 대기 자리로 날아감.
|
||||
- 애니메이션: 윷가락 4개가 공중에서 가락마다 다르게 돌다 떨어져 한 번 튀는 0.8초 애니메이션(서버 결과를 받은 뒤 재생, 결과 조작 불가), 결과 글자는 톡 튀어나오고 윷·모는 빨간 글씨, 낙이면 가락이 흔들린다. 말은 칸마다 통통 튀며 이동하고(한 칸 0.17초), 도착하면 자리에 고리가 한 번 퍼진다(잡기 빨강, 나기 금색). 잡힌 말은 움직이는 말이 도착할 때까지 그 자리에 있다가 튀어 오르며 돌아 사라진다. 상대·컴퓨터 차례도 똑같이 움직인다.
|
||||
- 효과음(화면 변화 기준, 한 번만, 사이트 음량을 따름, `apps/web/src/games/yut/sound.ts`): 던질 때 휙 + 가락 4개가 멍석에 떨어지는 딱딱 소리(애니메이션과 같은 때), 윷·모는 밝게 올라가는 음(한 번 더), 빽도는 미끄러져 내려가는 음, 낙은 둔탁한 소리. 말이 한 칸 갈 때마다 작은 "콩", 도착할 때 잡기(부딪히고 떨어지는 소리)·업기(두 번 딸깍)·나기(짧게 올라가는 음). 내 차례 알림은 보이는 화면에서만 게임이 내고, 숨은 탭은 방 화면이 낸다.
|
||||
- 초보자 도움말: "규칙 보기"에 그림으로 도~모, 지름길(모서리·방에 멈추면 꺾임), 업기, 잡기 설명. 힌트 옵션을 켜면 추천 수(8.5 우선순위)를 연하게 표시.
|
||||
- 접근성: 결과 칩에 글자(도/개/걸/윷/모/빽도)와 이동 칸 수(1~5, −1)를 함께. 색약 대비로 편마다 모양(원·세모·네모·별) 구분.
|
||||
|
||||
|
||||
@@ -1486,6 +1486,10 @@ const PLANS: Record<string, Plan> = {
|
||||
await finishHand(pages);
|
||||
},
|
||||
},
|
||||
omok: {
|
||||
// cursor starts at the centre: black plays there, white one point to the left (the full omok flow is e2e/omok.e2e.ts)
|
||||
moves: [['Enter'], ['ArrowLeft', 'Enter']],
|
||||
},
|
||||
othello: {
|
||||
// cursor starts at d4 (3,3): black d3 = up; then white c3 = up, left
|
||||
moves: [['ArrowUp', 'Enter'], ['ArrowUp', 'ArrowLeft', 'Enter']],
|
||||
|
||||
@@ -160,6 +160,17 @@ describe('passing and scoring phase (§5.4–5.5)', () => {
|
||||
expect(baduk.deadline!(s)).toBe(1000 + 180_000);
|
||||
});
|
||||
|
||||
test('사석 확인 무제한(scoringDeadlineSec 0): no deadline, no timer in the view, agreeing still finishes', () => {
|
||||
let s = playAll(make({ scoringDeadlineSec: 0, timeControl: { kind: 'none' } as BadukOptions['timeControl'] }), ['pass', 'pass']);
|
||||
expect(s.phase).toBe('scoring');
|
||||
expect(baduk.deadline!(s)).toBeNull();
|
||||
expect(baduk.view(s, 'A').scoring!.deadlineAt).toBeNull();
|
||||
expect(badukOptionsSchema.safeParse({ scoringDeadlineSec: 0 }).success).toBe(true);
|
||||
s = act(s, 'black', { type: 'agreeScore' });
|
||||
s = act(s, 'white', { type: 'agreeScore' });
|
||||
expect(s.phase).toBe('finished');
|
||||
});
|
||||
|
||||
test('toggling dead stones clears agreement; both agreeing finishes', () => {
|
||||
let s = playAll(make({}, { black: ['E4'], white: ['E6'] }), ['pass', 'pass']);
|
||||
s = act(s, 'black', { type: 'agreeScore' });
|
||||
|
||||
@@ -77,9 +77,9 @@ export const badukOptionsSchema = z
|
||||
drawReofferMoves: z.number().int().min(0).max(50).default(5).meta({ title: '무승부 다시 제안까지 둬야 하는 수' }),
|
||||
atariWarning: z.boolean().default(false).meta({ title: '위협 가이드(관리자 전용): 단수에 몰린 내 돌 표시' }),
|
||||
scoringDeadlineSec: z
|
||||
.union([z.literal(120), z.literal(180), z.literal(300)])
|
||||
.union([z.literal(120), z.literal(180), z.literal(300), z.literal(0)])
|
||||
.default(180)
|
||||
.meta({ title: '사석 확인 제한 시간', labels: { 120: '2분', 180: '3분', 300: '5분' } }),
|
||||
.meta({ title: '사석 확인 제한 시간', labels: { 120: '2분', 180: '3분', 300: '5분', 0: '무제한' } }),
|
||||
})
|
||||
.superRefine((o, ctx) => {
|
||||
if (o.boardSize === 9 && o.handicap > 5) ctx.addIssue({ code: 'custom', path: ['handicap'], message: '9줄 판은 접바둑 5점까지만 둘 수 있어요.' });
|
||||
@@ -202,7 +202,8 @@ export interface BadukView {
|
||||
/** Every point of seki-marked regions. */
|
||||
seki: Pt[];
|
||||
agreed: Record<Color, boolean>;
|
||||
deadlineAt: number;
|
||||
/** null = 무제한 (scoringDeadlineSec 0). */
|
||||
deadlineAt: number | null;
|
||||
durationMs: number;
|
||||
preview: ScoreBreakdown;
|
||||
} | null;
|
||||
@@ -788,7 +789,7 @@ export const baduk: GameDefinition<BadukState, BadukAction, BadukView, BadukOpti
|
||||
dead: m.dead.map((i) => toPt(i, s.size)),
|
||||
seki: sekiPoints(s).map((i) => toPt(i, s.size)),
|
||||
agreed: m.agreed,
|
||||
deadlineAt: m.startedAt + s.options.scoringDeadlineSec * 1000,
|
||||
deadlineAt: s.options.scoringDeadlineSec ? m.startedAt + s.options.scoringDeadlineSec * 1000 : null,
|
||||
durationMs: s.options.scoringDeadlineSec * 1000,
|
||||
preview: scoreOf(s),
|
||||
}
|
||||
@@ -807,7 +808,7 @@ export const baduk: GameDefinition<BadukState, BadukAction, BadukView, BadukOpti
|
||||
},
|
||||
|
||||
deadline(s) {
|
||||
if (s.phase === 'scoring') return s.scoringMarks!.startedAt + s.options.scoringDeadlineSec * 1000;
|
||||
if (s.phase === 'scoring') return s.options.scoringDeadlineSec ? s.scoringMarks!.startedAt + s.options.scoringDeadlineSec * 1000 : null;
|
||||
if (s.phase !== 'playing') return null;
|
||||
const tc = s.options.timeControl;
|
||||
const start = s.clock.turnStartedAt;
|
||||
|
||||
@@ -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<JanggiState, JanggiAction, JanggiView, Jangg
|
||||
},
|
||||
|
||||
deadline(s) {
|
||||
if (s.phase === 'setup') return s.setup.startedAt + s.options.setupTimeSec * 1000;
|
||||
// 상차림 시간 0 = 무제한 (연결이 끊긴 사람만 방의 접속 유예 뒤에 자동으로 골라 줌)
|
||||
if (s.phase === 'setup') return s.options.setupTimeSec > 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;
|
||||
|
||||
@@ -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' });
|
||||
|
||||
Reference in New Issue
Block a user