diff --git a/apps/web/src/games/apple/index.tsx b/apps/web/src/games/apple/index.tsx index 25270b5..8273dc3 100644 --- a/apps/web/src/games/apple/index.tsx +++ b/apps/web/src/games/apple/index.tsx @@ -9,7 +9,7 @@ import { socket } from '../../net/socket'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { AfterMotion, fxMs } from '../../lib/motion'; /** Canonical board: 10 rows × 17 columns (phones show it turned: 17 rows × 10 columns). */ const ROWS = 10; @@ -553,16 +553,17 @@ function AppleBoard({ view: v, me, players, act }: BoardProps) { 합이 10이 되게 사과를 묶어요! )} - {mine && mine.status === 'stuck' && v.phase === 'playing' && ( + {/* My final count shows after the last apples have popped. */} +
- 더 지울 수 있는 사과가 없어요! 사과 {mine.score}개{extraText(mine)} · 끝날 때까지 기다려요 + 더 지울 수 있는 사과가 없어요! 사과 {mine?.score}개{mine ? extraText(mine) : ''} · 끝날 때까지 기다려요
- )} - {mine && mine.status === 'done' && v.phase === 'playing' && ( +
+
- 여기까지 했어요! 사과 {mine.score}개{extraText(mine)} · 모두 끝날 때까지 기다려요 + 여기까지 했어요! 사과 {mine?.score}개{mine ? extraText(mine) : ''} · 모두 끝날 때까지 기다려요
- )} +
{mine && mine.status === 'left' && v.phase !== 'ended' &&
게임에서 나갔어요.
} {!mine && v.phase !== 'ended' &&
관전 중이에요 · 위에서 점수를 볼 수 있어요
} @@ -635,22 +636,24 @@ function AppleSide({ view: v, me, players }: BoardProps) { ))} - {v.result && ( -
- 최종 순위 - {v.result.ranking.map((r) => ( - - {r.rank}등 {nick(players, r.id)} - - {' '} - · 사과 {r.score}개 · {r.clears}번{r.left ? ' · 나감' : ''} - {extraText(r)} + + {v.result && ( +
+ 최종 순위 + {v.result.ranking.map((r) => ( + + {r.rank}등 {nick(players, r.id)} + + {' '} + · 사과 {r.score}개 · {r.clears}번{r.left ? ' · 나감' : ''} + {extraText(r)} + - - ))} - {v.result.summary} -
- )} + ))} + {v.result.summary} +
+ )} + ); } @@ -756,6 +759,7 @@ const ui: GameUI = { Board: AppleBoard, Side: AppleSide, statusText, + liveStatus: true, isMyTurn, Options, optionsSummary, diff --git a/apps/web/src/games/baduk/index.tsx b/apps/web/src/games/baduk/index.tsx index 66f936e..7b4168a 100644 --- a/apps/web/src/games/baduk/index.tsx +++ b/apps/web/src/games/baduk/index.tsx @@ -10,7 +10,7 @@ import { reducedMotion, useBanner } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion'; type Color = 'black' | 'white'; const COLOR_KO: Record = { black: '흑', white: '백' }; @@ -160,6 +160,9 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps // Counting starts / the game ends (for both players and watchers). const prevPhase = useRef(v.phase); + // The winner banner waits for the territory marks to finish popping in (held, so the result window waits too). + const [endWait, setEndWait] = useState(false); + useMotionHold(endWait); useEffect(() => { const before = prevPhase.current; prevPhase.current = v.phase; @@ -168,8 +171,21 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps showBanner('계가', 'blue', '두 사람 모두 패스했어요. 사석을 확인해요'); sfx.whoosh(); } else if (v.phase === 'finished' && v.result) { - const w = v.result.winner; - showBanner(w ? `${COLOR_KO[w]} 승리!` : '무승부', w ? (w === v.myColor ? 'gold' : v.myColor ? 'dark' : 'blue') : 'green', v.result.summaryKo); + const r = v.result; + const w = r.winner; + setEndWait(true); + // Marks pop in staggered from the corner (up to 0.9 s) and take 0.32 s each. + const t = setTimeout( + () => { + setEndWait(false); + showBanner(w ? `${COLOR_KO[w]} 승리!` : '무승부', w ? (w === v.myColor ? 'gold' : v.myColor ? 'dark' : 'blue') : 'green', r.summaryKo); + }, + r.score && !reducedMotion() ? fxMs(1250) : 0, + ); + return () => { + clearTimeout(t); + setEndWait(false); + }; } }, [v.phase]); // eslint-disable-line react-hooks/exhaustive-deps @@ -566,18 +582,25 @@ function BadukSide({ view: v, me, players, act, pending, deadline }: BoardProps< 상대가 패스했어요. 끝내려면 나도 패스하세요. 더 둘 곳이 있으면 계속 둬도 돼요. )} - {v.phase === 'scoring' && } + {/* The counted score and the result show once the 계가 banner / territory marks / winner banner have played. */} + {v.phase === 'scoring' && ( + + + + )} {v.phase === 'finished' && v.result?.score && ( -
- {v.result.summaryKo} -
- {`흑 ${v.result.score.black.total} : 백 ${v.result.score.white.total}`} - - 흑 : 백 - + +
+ {v.result.summaryKo} +
+ {`흑 ${v.result.score.black.total} : 백 ${v.result.score.white.total}`} + + 흑 : 백 + +
+
- -
+ )} {v.phase === 'playing' && v.myColor && (
@@ -685,6 +708,8 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: BadukView; const c = v.clock; const elapsed = active ? Math.max(0, now - c.turnStartedAt) : 0; const mine = id === me; + // The capture count goes up once the captured stones have been lifted off the board. + const captures = useAfterMotionValue(v.captures[color]); let clock: React.ReactNode = null; let periodSecLeft: number | null = null; if (c.kind === 'byoyomi') { @@ -742,7 +767,7 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: BadukView; {mine && (나)}
- {COLOR_KO[color]} · 따낸 돌 {v.captures[color]} + {COLOR_KO[color]} · 따낸 돌 {captures} {color === 'white' && v.rules.komi ? ` · 덤 ${v.rules.komi}` : ''} {active ? ' · 두는 중' : ''} {v.phase === 'scoring' && v.scoring?.agreed[color] ? ' · 동의함' : ''} diff --git a/apps/web/src/games/bang/index.tsx b/apps/web/src/games/bang/index.tsx index 8715fe5..341cd5e 100644 --- a/apps/web/src/games/bang/index.tsx +++ b/apps/web/src/games/bang/index.tsx @@ -9,7 +9,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxAnim, fxMs } from '../../lib/motion'; +import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion'; // ---------------------------------------------------------------- names (display names live only here, docs §12) @@ -295,7 +295,8 @@ function CardFaceInner({ card, info }: { card: CardFace; info: (typeof CARD_INFO } function Hp({ life, max }: { life: number; max: number }) { - const n = Math.max(0, life); + // Life changes once the shot / beer that caused it has played. + const n = Math.max(0, useAfterMotionValue(life)); return ( {Array.from({ length: max }, (_, i) => ( @@ -384,12 +385,15 @@ function Seat({ }) { const u = userOf(players, p.id); const r = v.reactions.find((x) => x.who === p.id); + // A player falls once the shot that downed them has played (the role badge has its own flip, see useBangFx 'dead'). + const alive = useAfterMotionValue(p.alive); + const role = shownRole(p, v, me); const timer = r ? ( ) : p.isTurn && !v.reactions.length && !v.winner ? ( ) : null; - const cls = `bg-seat${p.isTurn ? ` turn${v.winner ? '' : ' anim-glow'}` : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}`; + const cls = `bg-seat${p.isTurn ? ` turn${v.winner ? '' : ' anim-glow'}` : ''}${r ? ' react' : ''}${p.id === me ? ' me' : ''}${!alive ? ' dead' : ''}`; const body = ( <> @@ -401,10 +405,10 @@ function Seat({ {timer} - + {p.character ? CHAR_INFO[p.character].name : '캐릭터 고르는 중'} - {p.alive ? ( + {alive ? ( @@ -438,7 +442,7 @@ function Seat({ data-player={p.id} data-fx-seat={p.id} aria-pressed={mark.selected} - aria-label={`${seatLabel(p, players, me, shownRole(p, v, me))}. 대상으로 고르기`} + aria-label={`${seatLabel(p, players, me, role)}. 대상으로 고르기`} onClick={() => onPick(p.id)} > {body} @@ -446,7 +450,7 @@ function Seat({ ); } return ( -
+
{body}
); @@ -467,6 +471,8 @@ function Center({ v, players }: { v: BangView; players: Record = { dynamite: '다이너마이트', jail: '감옥', barrel: '술통', jourdonnais: '주르도네' }; const waitingFor = v.reactions.length ? [...new Set(v.reactions.map((r) => r.who))] : []; const last = v.log[v.log.length - 1]; + // The latest event's text changes once its animation has played. + const lastText = useAfterMotionValue(last ? logText(last, players) : ''); return (
@@ -482,7 +488,7 @@ function Center({ v, players }: { v: BangView; players: Record )} {waitingFor.length > 0 && {waitingFor.map((id) => `${nick(players, id)}님`).join(', ')} 기다리는 중…} - {last && {logText(last, players)}} + {lastText && {lastText}}
); } @@ -624,6 +630,8 @@ function MyArea({ }) { const my = v.my!; const meP = v.players.find((p) => p.id === v.me); + // "쓰러졌어요" waits for the shot that downed me. + const meAlive = useAfterMotionValue(meP?.alive ?? false); const [multi, setMulti] = useState([]); const [sidMode, setSidMode] = useState(false); const [note, setNote] = useState(''); @@ -692,7 +700,7 @@ function MyArea({ {my.character ? CHAR_INFO[my.character].name : '캐릭터를 고르는 중'} - {meP && meP.alive && ( + {meP && meAlive && ( <> {' '} @@ -707,7 +715,7 @@ function MyArea({ {meP && }
- {meP && !meP.alive && !v.winner && 쓰러졌어요. 남은 게임을 지켜봐요.} + {meP && !meAlive && !v.winner && 쓰러졌어요. 남은 게임을 지켜봐요.} {prompt?.kind === 'draw' && } {meP?.alive && ( )
{v.my && } - {v.my && } + {/* A reaction / choice window opens once the card that caused it has landed (it mounts then, so focus works). */} + {v.my && ( + + + + )}

{announce}

@@ -1156,6 +1169,11 @@ function useBangFx(v: BangView, me: string | null, players: Record `${nick(players, id)}님`; + // The steps below are staged with timers (shots, banners, bumps): results wait until the last one has played. + const [staging, setStaging] = useState(false); + const stageTimer = useRef | null>(null); + useMotionHold(staging); + useEffect(() => () => void (stageTimer.current && clearTimeout(stageTimer.current)), []); useNewEntries( keyed, @@ -1389,9 +1407,15 @@ function useBangFx(v: BangView, me: string | null, players: Record showBanner(`${TEAM_KO[e.winner]} 승리!`, TEAM_TONE[e.winner])); + t += 300; break; } } + if (t > 0) { + setStaging(true); + if (stageTimer.current) clearTimeout(stageTimer.current); + stageTimer.current = setTimeout(() => setStaging(false), fxMs(Math.min(t, 3000) + 400)); + } }, 30, ); @@ -1422,6 +1446,24 @@ function useBangFx(v: BangView, me: string | null, players: Record }) { + const alive = useAfterMotionValue(p.alive); + const role = useAfterMotionValue(shownRole(p, v, me)); + return ( +
  • + + + {p.isTurn ? '▶ ' : ''} + {nick(players, p.id)} + {p.id === me ? ' (나)' : ''} + + + {alive ? : 쓰러짐} +
  • + ); +} + function BangSide({ view: v, me, players }: BoardProps) { return ( <> @@ -1436,34 +1478,27 @@ function BangSide({ view: v, me, players }: BoardProps) {
      {v.players.map((p) => ( -
    1. - - - {p.isTurn ? '▶ ' : ''} - {nick(players, p.id)} - {p.id === me ? ' (나)' : ''} - - - {p.alive ? : 쓰러짐} -
    2. + ))}
    {v.result && ( -
    - {TEAM_KO[v.result.winnerTeam]} 승리 - {v.result.ranking.map((id) => { - const r = v.result!.players.find((x) => x.id === id)!; - return ( - - {r.won ? '🏆 ' : ''} - {nick(players, id)} · {ROLE_INFO[r.role].name} · {CHAR_INFO[r.character].name} - {r.alive ? ' · 생존' : ` · ${r.deathOrder}번째로 쓰러짐`} - - ); - })} - {v.result.summary} -
    + +
    + {TEAM_KO[v.result.winnerTeam]} 승리 + {v.result.ranking.map((id) => { + const r = v.result!.players.find((x) => x.id === id)!; + return ( + + {r.won ? '🏆 ' : ''} + {nick(players, id)} · {ROLE_INFO[r.role].name} · {CHAR_INFO[r.character].name} + {r.alive ? ' · 생존' : ` · ${r.deathOrder}번째로 쓰러짐`} + + ); + })} + {v.result.summary} +
    +
    )} {v.log.length > 0 && (
    diff --git a/apps/web/src/games/blackjack/board.tsx b/apps/web/src/games/blackjack/board.tsx index 0250dd8..e9f7586 100644 --- a/apps/web/src/games/blackjack/board.tsx +++ b/apps/web/src/games/blackjack/board.tsx @@ -16,7 +16,7 @@ import { TurnTimer } from '../../components/TurnTimer'; import { Avatar } from '../../components/ui'; import { haptic, sfx, sounds } from '../../lib/feedback'; import { usePhone } from '../../lib/media'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion'; import type { BoardProps } from '../types'; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; @@ -200,6 +200,24 @@ function useDealQueue(v: BlackjackView) { }; } +/** + * The cards of `shown` whose fly-in has finished (the screen stood still since they appeared): totals, bust / 블랙잭 + * tags count only these, so a number never changes while its card is still in the air. + */ +function useLandedCards(shown: string[]): string[] { + const key = shown.join(','); + const settled = useAfterMotionValue(key); + return settled === key ? shown : settled.split(',').filter((k) => k && shown.includes(k)); +} + +/** Everyone's chips as of the last still screen: the chip counts change only after the hand's cards have landed. */ +export function useLandedChips(v: BlackjackView): (id: string) => number { + const key = v.seats.map((s) => `${s.id}:${s.chips}`).join(','); + const settled = useAfterMotionValue(key); + const map = new Map(settled.split(',').filter(Boolean).map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))])); + return (id) => map.get(id) ?? v.seats.find((s) => s.id === id)?.chips ?? 0; +} + // ---------------------------------------------------------------- pieces function totalOf(cards: string[]): { total: number; soft: boolean } { @@ -235,7 +253,8 @@ function DealtCard({ id, width, anim }: { id: string | null; width: number; anim function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean; width: number; q: ReturnType; final: boolean }) { const cards = h.cards.filter((c) => q.shown(c)); - const done = cards.length === h.cards.length; + const landed = useLandedCards(cards); + const done = landed.length === h.cards.length; const tag = final && h.outcome ? OUTCOME_KO[h.outcome] : done ? HAND_KO[h.status] : ''; const color = h.outcome === 'win' || h.outcome === 'blackjack' || h.outcome === 'bonus' ? '#16a34a' : h.outcome === 'lose' || h.status === 'bust' ? '#dc2626' : h.outcome === 'push' ? '#6b7280' : '#b45309'; @@ -247,7 +266,7 @@ function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean; ))}
    - + {h.bet.toLocaleString('ko-KR')} @@ -263,14 +282,14 @@ function HandBox({ h, active, width, q, final }: { h: HandView; active: boolean; ); } -function Seat({ seat, v, me, players, pos, width, rows, maxW, q, final }: { seat: SeatView; v: BlackjackView; me: string | null; players: Record; pos: { x: number; y: number } | null; width: number; rows: number; maxW: number; q: ReturnType; final: boolean }) { +function Seat({ seat, v, me, players, pos, width, rows, maxW, q, final, chips }: { seat: SeatView; v: BlackjackView; me: string | null; players: Record; pos: { x: number; y: number } | null; width: number; rows: number; maxW: number; q: ReturnType; final: boolean; chips: number }) { const u = userOf(players, seat.id); const isTurn = v.phase === 'playing' && v.turn === seat.id; const style = { ...(pos ? { '--x': `${pos.x}%`, '--y': `${pos.y}%` } : {}), '--mw': `${maxW}px` } as CSSProperties; const hands = seat.hands ?? []; const per = Math.ceil(hands.length / rows); return ( -
    +
    {seat.hands ? (
    {Array.from({ length: rows }, (_, r) => ( @@ -294,7 +313,7 @@ function Seat({ seat, v, me, players, pos, width, rows, maxW, q, final }: { seat {u.nickname} {seat.id === me ? ' (나)' : ''} - {seat.chips.toLocaleString('ko-KR')} + {chips.toLocaleString('ko-KR')} {seat.status === 'out' && 칩 소진} {seat.status === 'left' && 나감}
    @@ -528,7 +547,7 @@ function Actions({ v, act, pending }: { v: BlackjackView; act: (a: unknown) => v ); } -function Dock({ v, me, players, act, pending, deadline, mine, final }: { v: BlackjackView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; deadline: number | null; mine: boolean; final: boolean }) { +function Dock({ v, me, players, act, pending, deadline, mine, final, chips }: { v: BlackjackView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; deadline: number | null; mine: boolean; final: boolean; chips: (id: string) => number }) { const seat = me ? v.seats.find((s) => s.id === me) : undefined; const u = seat ? userOf(players, seat.id) : null; let main: ReactNode; @@ -597,7 +616,7 @@ function Dock({ v, me, players, act, pending, deadline, mine, final }: { v: Blac {u.nickname} (나) - {seat.chips.toLocaleString('ko-KR')} + {chips(seat.id).toLocaleString('ko-KR')} {mine && }
    @@ -643,11 +662,16 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }: const mine = isMyTurn(v, me); const phone = usePhone(); const q = useDealQueue(v); - // Results (outcome tags, +/-) wait until every card has landed. - const final = (v.phase === 'handEnd' || v.phase === 'finished') && !q.busy; + // Cards still queued (dealt one by one with timers) hold results; then the last fly-in must finish too. + useMotionHold(q.busy); + const ended = (v.phase === 'handEnd' || v.phase === 'finished') && !q.busy; + // Results (outcome tags, +/-, banner, 다음 판) wait until every card has landed. + const final = useMotionSettled(ended); + const chips = useLandedChips(v); const d = v.dealer; const dealerCards = d.cards.map((c) => c ?? holeKey(v)).filter((k) => q.shown(k)); - const dealerReal = d.cards.filter((c): c is string => !!c && q.shown(c)); + const dealerLanded = useLandedCards(dealerCards); + const dealerReal = dealerLanded.filter((k) => k !== holeKey(v)); const slots = seatLayout(v, me); // Table width for fitting cards into each seat's share (phone: my seat a full row, others two per row). const tableRef = useRef(null); @@ -707,7 +731,7 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }: prevTurn.current = v.turn; }, [v.turn]); // eslint-disable-line react-hooks/exhaustive-deps - const dealerDone = dealerCards.length === d.cards.length; + const dealerDone = dealerLanded.length === d.cards.length; const seatEls = slots.map(({ id, x, y, share }) => { const seat = v.seats.find((s) => s.id === id)!; const hands = seat.hands ?? []; @@ -718,7 +742,7 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }: const roomH = (tableH * y) / 100 - (40 + dealerW * 1.4 + 12) - 64; const capH = phone ? 999 : Math.floor((roomH / rows - 50) / 1.4); const width = Math.max(26, Math.min(capH, fitCardWidth(hands, avail, id === me ? myW : otherW, rows))); - return ; + return ; }); return (
    @@ -761,7 +785,7 @@ export function BlackjackBoard({ view: v, me, players, act, pending, deadline }:
    )}
    - +
    ); } diff --git a/apps/web/src/games/blackjack/index.tsx b/apps/web/src/games/blackjack/index.tsx index 0879b8a..f18d9de 100644 --- a/apps/web/src/games/blackjack/index.tsx +++ b/apps/web/src/games/blackjack/index.tsx @@ -5,7 +5,7 @@ import type { PublicUser } from '@bg/shared/lite'; import { PLAYING_CARD_CREDIT } from '../../components/cards/PlayingCard'; import { PlayChipNotice, formatChips } from '../../components/cards/Chips'; import type { BoardProps, GameUI, OptionsProps } from '../types'; -import { BlackjackBoard, isMyTurn } from './board'; +import { BlackjackBoard, isMyTurn, useLandedChips } from './board'; import { helpNow } from './help'; import { quickStart } from './quick'; @@ -29,7 +29,9 @@ function statusText(v: BlackjackView, me: string | null, players: Record) { - const ranked = [...v.seats].sort((a, b) => b.chips - a.chips); + // Chip counts change only once the hand's cards have landed on the board. + const chips = useLandedChips(v); + const ranked = [...v.seats].sort((a, b) => chips(b.id) - chips(a.id)); return (
    @@ -42,7 +44,7 @@ function Side({ view: v, me, players }: BoardProps) { {s.status === 'out' && ' (칩 소진)'} {s.status === 'left' && ' (나감)'} - {formatChips(s.chips)} + {formatChips(chips(s.id))} ))} diff --git a/apps/web/src/games/castles-of-burgundy/index.tsx b/apps/web/src/games/castles-of-burgundy/index.tsx index b92888d..a1c79b0 100644 --- a/apps/web/src/games/castles-of-burgundy/index.tsx +++ b/apps/web/src/games/castles-of-burgundy/index.tsx @@ -26,6 +26,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { DieFace, FILL, GOODS_FILL, INK, Pips, SPACE, TileHex, axial, goodsName, hexPoints, monasteryText, tileName } from './hex'; import { helpNow } from './help'; import { quickStart } from './quick'; +import { AfterMotion, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; type M = { a: CobAction; cost: number }; type Sel = { kind: 'die'; i: 0 | 1 } | { kind: 'buy' } | { kind: 'pick'; tile: string } | null; @@ -513,7 +514,17 @@ function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: Boar const [ask, setAsk] = useState(null); const [tab, setTab] = useState<'duchy' | 'depots' | 'others'>('duchy'); const [banner, showBanner] = useBanner(); + // Banners (and their sounds) wait until the placed tile has settled: queued here, played once the board is still. + const [due, setDue] = useState<(() => void)[]>([]); + const dueReady = useMotionSettled(due.length > 0); + useEffect(() => { + if (!dueReady) return; + for (const f of due) f(); + setDue([]); + }, [dueReady]); // eslint-disable-line react-hooks/exhaustive-deps + const later = (f: () => void) => setDue((q) => [...q, f]); const myPv = me ? v.players[me] : undefined; + const myVp = useAfterMotionValue(myPv?.vp ?? 0); const moves = useMemo(() => moveList(v), [v]); const top = topOf(v); const mineNow = !!v.my; @@ -547,15 +558,19 @@ function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: Boar sfx.piece(); if (e.p === me) bump(fxEl(`me-${e.space}`)); } else if (e.t === 'region' && e.p === me) { - sfx.good(); - showBanner(`+${e.vp}점`, 'green', '구역 완성!'); + later(() => { + sfx.good(); + showBanner(`+${e.vp}점`, 'green', '구역 완성!'); + }); } else if (e.t === 'colorBonus') { - sfx.good(); - showBanner(e.p === me ? `👑 ${COLOR_KO[e.color]} 색 ${e.size === 'large' ? '첫' : '둘째'} 완성!` : `${nick(players, e.p)}님 ${COLOR_KO[e.color]} 색 완성`, 'gold', `+${e.vp}점`); + later(() => { + sfx.good(); + showBanner(e.p === me ? `👑 ${COLOR_KO[e.color]} 색 ${e.size === 'large' ? '첫' : '둘째'} 완성!` : `${nick(players, e.p)}님 ${COLOR_KO[e.color]} 색 완성`, 'gold', `+${e.vp}점`); + }); } else if (e.t === 'sell') sfx.coin(); else if (e.t === 'ship') sfx.whoosh(); - else if (e.t === 'phase' && e.phase > 0) showBanner(`페이즈 ${PHASE_KO[e.phase]}`, 'blue', '보급소를 새로 채웠어요'); - else if (e.t === 'soloTarget') showBanner('🎯 목표 도달!', 'gold', `다음 목표 ${e.target}점`); + else if (e.t === 'phase' && e.phase > 0) later(() => showBanner(`페이즈 ${PHASE_KO[e.phase]}`, 'blue', '보급소를 새로 채웠어요')); + else if (e.t === 'soloTarget') later(() => showBanner('🎯 목표 도달!', 'gold', `다음 목표 ${e.target}점`)); } }, ); @@ -712,8 +727,8 @@ function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: Boar 🪙 {myPv.silver} - - ⭐ {myPv.vp} + + ⭐ {myVp} {sel?.kind === 'die' && workersMove(sel.i) && (
    - - {pv.vp} + + {vpOf(p)} {turn && v.stage !== 'finished' && } @@ -1092,22 +1110,25 @@ function CobSide({ view: v, me, players, act, deadline }: BoardProps) { ); })} - {rows && ( -
    - 최종 점수 - {rows.map((r) => ( -
    - - {nick(players, r.player)} {r.total}점 - {' '} - = 게임 중 {r.inGame} + 상품 {r.goodsLeft} + 은화 {r.silver} + 일꾼 {r.workers} - {r.monasteries.length ? ` + 수도원 ${r.monasteries.reduce((a, m) => a + m.vp, 0)}` : ''} - {r.shields ? ` + 방패 ${r.shields}` : ''} · 빈칸 {r.emptySpaces} - {r.conceded ? ' · 기권' : ''} -
    - ))} -
    - )} + {/* The final scores wait for the last move to finish animating. */} + + {rows && ( +
    + 최종 점수 + {rows.map((r) => ( +
    + + {nick(players, r.player)} {r.total}점 + {' '} + = 게임 중 {r.inGame} + 상품 {r.goodsLeft} + 은화 {r.silver} + 일꾼 {r.workers} + {r.monasteries.length ? ` + 수도원 ${r.monasteries.reduce((a, m) => a + m.vp, 0)}` : ''} + {r.shields ? ` + 방패 ${r.shields}` : ''} · 빈칸 {r.emptySpaces} + {r.conceded ? ' · 기권' : ''} +
    + ))} +
    + )} +
    {log.length > 0 && (
    기록 diff --git a/apps/web/src/games/catchmind/index.tsx b/apps/web/src/games/catchmind/index.tsx index 6b2784d..b336d92 100644 --- a/apps/web/src/games/catchmind/index.tsx +++ b/apps/web/src/games/catchmind/index.tsx @@ -12,7 +12,7 @@ import { socket } from '../../net/socket'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useMotionSettled } from '../../lib/motion'; // ---------------------------------------------------------------- constants (mirror packages/games/src/catchmind/types.ts) @@ -685,6 +685,23 @@ function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string const prevRole = useRef(v.role); const prevTurn = useRef(v.turnNo); const popTimer = useRef | null>(null); + // The answer screen (and its sound) waits until my "정답!" pop has played. + const over = v.phase === 'reveal' || v.phase === 'ended'; + const overShown = useMotionSettled(over); + const prevPhase = useRef(v.phase); + const revealSound = useRef<(() => void) | null>(null); + useEffect(() => { + if (prevTurn.current === v.turnNo && prevPhase.current === 'drawing' && v.phase === 'reveal') { + revealSound.current = v.endReason === 'report' ? sfx.alarm : v.endReason === 'allSolved' ? sfx.fanfare : v.solvers.length === 0 ? sfx.bad : sfx.cardFlip; + } + prevPhase.current = v.phase; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [v.phase, v.turnNo]); + useEffect(() => { + if (!overShown || !revealSound.current) return; + revealSound.current(); + revealSound.current = null; + }, [overShown]); useEffect(() => { if (prevTurn.current === v.turnNo && prevRole.current === 'guesser' && v.role === 'solver') { setPop(v.solvers.find((s) => s.id === me)?.points ?? 0); @@ -707,7 +724,7 @@ function Overlay({ v, me, act, players, onSave }: { v: CatchmindView; me: string ) : null; return ( <> - + {(!over || overShown) && } {popEl} ); @@ -1061,7 +1078,7 @@ function AwayBanner({ v, me, act }: { v: CatchmindView; me: string | null; act: ); } -/** Sounds for what happens on the table (my own "정답!" is played by the overlay). */ +/** Sounds for what happens on the table (my own "정답!" and the answer reveal are played by the overlay). */ function useTableSounds(v: CatchmindView, me: string | null): void { const prev = useRef(v); useEffect(() => { @@ -1083,12 +1100,6 @@ function useTableSounds(v: CatchmindView, me: string | null): void { if (fresh.some((m) => m.kind === 'correct' && m.from !== me)) cmSound.otherCorrect(); if (v.role !== 'drawer' && fresh.some((m) => m.kind === 'reaction')) cmSound.react(); if (fresh.some((m) => m.kind === 'close' && m.from === me)) cmSound.close(); - if (!turnChanged && p.phase === 'drawing' && v.phase === 'reveal') { - if (v.endReason === 'report') sfx.alarm(); - else if (v.endReason === 'allSolved') sfx.fanfare(); - else if (v.solvers.length === 0) sfx.bad(); - else sfx.cardFlip(); - } }, [v]); // eslint-disable-line react-hooks/exhaustive-deps } @@ -1358,6 +1369,7 @@ const ui: GameUI = { Board: CatchmindBoard, Side: CatchmindSide, statusText, + liveStatus: true, isMyTurn, Options, optionsSummary, diff --git a/apps/web/src/games/chess/index.tsx b/apps/web/src/games/chess/index.tsx index 5904e76..69159d3 100644 --- a/apps/web/src/games/chess/index.tsx +++ b/apps/web/src/games/chess/index.tsx @@ -6,6 +6,7 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui'; import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { haptic } from '../../lib/feedback'; import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion'; +import { AfterMotion, useAfterMotionValue } from '../../lib/motion'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { CHESS_PIECE_CREDIT, pieceSrc } from './art'; import { chessCues, chessMotion } from './fx'; @@ -542,12 +543,15 @@ function ChessSide({ view: v, me, players, act, pending, deadline }: BoardProps< )} - {v.result && REASON_HELP[v.result.reason] && ( -
    - {v.result.summary} -
    {REASON_HELP[v.result.reason]}
    -
    - )} + {/* Checkmate / stalemate explained once the last move has landed. */} + + {v.result && REASON_HELP[v.result.reason] && ( +
    + {v.result.summary} +
    {REASON_HELP[v.result.reason]}
    +
    + )} +
    {incoming && ( {}} label="상대의 요청"> @@ -661,8 +665,9 @@ function PlayerBar({ view: v, color, players, deadline, me }: { view: ChessView; ); } - const caps = [...v.captured[color]].sort((a, b) => 'qrbnp'.indexOf(a) - 'qrbnp'.indexOf(b)); - const adv = color === 'white' ? v.materialDiff : -v.materialDiff; + // A captured piece joins the row (and the material count changes) once the capturing move has landed. + const caps = [...useAfterMotionValue(v.captured[color].join(''))].sort((a, b) => 'qrbnp'.indexOf(a) - 'qrbnp'.indexOf(b)); + const adv = useAfterMotionValue(color === 'white' ? v.materialDiff : -v.materialDiff); return (
    diff --git a/apps/web/src/games/clue/index.tsx b/apps/web/src/games/clue/index.tsx index 0b6c0bc..ac4a285 100644 --- a/apps/web/src/games/clue/index.tsx +++ b/apps/web/src/games/clue/index.tsx @@ -28,7 +28,7 @@ import { cssEsc, flyGhost, reducedMotion } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxAnim, fxMs } from '../../lib/motion'; +import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; export const SUSPECT_COLOR: Record = { scarlet: '#dc2626', @@ -302,6 +302,10 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps) const [landed, setLanded] = useState<{ room: Room; key: number } | null>(null); useEffect(() => setSel(null), [v.phase.kind, v.current, v.turnNo]); + // The dice total (and the rooms it reaches) shows once the dice have stopped rolling. + const diceKey = v.dice ? `${v.turnNo}-${v.dice[0]}-${v.dice[1]}` : ''; + const shownDice = useAfterMotionValue(diceKey); + const rolling = diceKey !== '' && shownDice !== diceKey; // Tokens and weapons slide on the map from where they were (anyone's move, a suggestion pulling them into a room). // Places are kept relative to the map, so scrolling between two moves does not matter. @@ -431,8 +435,8 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps)
    - - + +
    {amPlayer && } {amPlayer && } @@ -635,6 +639,9 @@ function SuggestPanel({ room, act, pending, known, onAccuse }: { room: Room; act function LastResult({ view: v, me, players }: { view: ClueView; me: string | null; players: Record }) { const last = lastOf(v.suggestions); + // The answer shows once the suggested cards have flown into the envelope / the shown card has reached the suggester. + const answerKey = `${v.suggestions.length}|${last?.refuter ?? ''}|${v.phase.kind === 'refute'}`; + const answered = useAfterMotionValue(answerKey) === answerKey; if (!last || last.turnNo !== v.turnNo) return null; const by = last.by === me ? '내' : `${nick(players, last.by)}님의`; return ( @@ -643,7 +650,7 @@ function LastResult({ view: v, me, players }: { view: ClueView; me: string | nul {by} 추리: {triple(last)} {last.passed.length > 0 && · 못 보여 준 사람: {last.passed.map((p) => (p === me ? '나' : nick(players, p))).join(', ')}} - {last.refuter ? ( + {!answered ? null : last.refuter ? ( last.shown ? (
    @@ -674,6 +681,7 @@ function ActionPanel({ myTurn, sel, setSel, + rolling, }: { view: ClueView; me: string | null; @@ -683,6 +691,7 @@ function ActionPanel({ myTurn: boolean; sel: Room | null; setSel: (r: Room | null) => void; + rolling: boolean; }) { const [accusing, setAccusing] = useState(false); const known = useMemo(() => { @@ -694,18 +703,21 @@ function ActionPanel({ const ph = v.phase; if (ph.kind === 'finished') { + // The answer opens after the accusation banner has played. return ( -
    - 게임이 끝났어요 - {v.final?.summary} - {v.solution && ( -
    - {[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => ( - - ))} -
    - )} -
    + +
    + 게임이 끝났어요 + {v.final?.summary} + {v.solution && ( +
    + {[v.solution.suspect, v.solution.weapon, v.solution.room].map((x, i) => ( + + ))} +
    + )} +
    +
    ); } @@ -739,7 +751,7 @@ function ActionPanel({ if (!myTurn) { const doing: Record = { move: '이동하는 중이에요', - moveTo: `주사위를 굴렸어요 (${v.dice ? v.dice[0] + v.dice[1] : 0}). 갈 곳을 고르는 중이에요`, + moveTo: rolling ? '주사위를 굴리는 중이에요' : `주사위를 굴렸어요 (${v.dice ? v.dice[0] + v.dice[1] : 0}). 갈 곳을 고르는 중이에요`, suggest: '추리할 카드를 고르는 중이에요', afterSuggest: '고발할지 차례를 끝낼지 고르는 중이에요', }; @@ -822,13 +834,15 @@ function ActionPanel({ {DICE[v.dice[1]]} - = {sum}칸 + {!rolling && = {sum}칸}
    )} - 지도에서 갈 방을 눌러 주세요. - - {free ? '아무 방이나 바로 들어가요. 지금 있는 방에는 다시 못 들어가요.' : `초록 방은 ${sum}칸 안이라 바로 들어가요. 점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요.`} - + {rolling ? '주사위를 굴리는 중…' : '지도에서 갈 방을 눌러 주세요.'} + {!rolling && ( + + {free ? '아무 방이나 바로 들어가요. 지금 있는 방에는 다시 못 들어가요.' : `초록 방은 ${sum}칸 안이라 바로 들어가요. 점선 방을 고르면 그쪽으로 ${sum}칸 걸어가고 차례가 끝나요.`} + + )}
    {sel && enter && (
    - {v.hands && v.solution && ( + {ended && v.hands && v.solution && (
    정답: {triple(v.solution)} {v.seats.map((p) => ( diff --git a/apps/web/src/games/cockroach-poker/index.tsx b/apps/web/src/games/cockroach-poker/index.tsx index a80e88c..8810cc6 100644 --- a/apps/web/src/games/cockroach-poker/index.tsx +++ b/apps/web/src/games/cockroach-poker/index.tsx @@ -9,7 +9,7 @@ import { bump, flyGhost, seatEl, useBanner } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion'; // Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod. const KINDS: Kind[] = ['cockroach', 'bat', 'fly', 'toad', 'rat', 'scorpion', 'spider', 'stinkbug']; @@ -246,6 +246,9 @@ const CSS = ` .cp-chip.danger .cp-mini:last-child { box-shadow: 0 0 0 3px #ef4444, 0 0 12px rgba(239,68,68,.8); } .cp-chip.danger .cp-n { background: #dc2626; animation: cp-breathe 1s ease-in-out infinite; } .cp-chip.new .cp-mini:last-of-type { animation: cp-land .5s cubic-bezier(.3,.7,.3,1.3) 1.4s both; } +/* The new count shows as the card lands, not before. */ +.cp-chip.new .cp-n { animation: cp-pop .25s ease-out 1.65s both; } +.cp-chip.new.danger .cp-n { animation: cp-pop .25s ease-out 1.65s both, cp-breathe 1s ease-in-out 1.9s infinite; } ${KINDS.map((k) => `.fx-ghost.cp-face-${k} { background: ${KIND_COLOR[k].bg}; color: ${KIND_COLOR[k].ink}; border: 2px solid ${KIND_COLOR[k].ink}; border-radius: 7px; display: flex; align-items: flex-end; justify-content: center; font: 800 9px/1.6 system-ui, sans-serif; box-shadow: 0 3px 8px rgba(0,0,0,.35); }`).join('\n')} .cp-empty { font-size: .8rem; opacity: .75; } .cp-bubble { position: absolute; right: 8px; top: -14px; background: #fff; color: #1c1e21; border-radius: 12px; padding: 3px 10px; font-weight: 800; font-size: .85rem; box-shadow: 0 3px 10px rgba(0,0,0,.3); animation: cp-pop .25s ease-out; z-index: 3; max-width: 80%; } @@ -427,12 +430,13 @@ function HandFan({ n }: { n: number }) { ); } -function Seat({ id, v, me, players, deadline, bubble, fresh }: { id: string; v: CockroachView; me: string | null; players: Record; deadline: number | null; bubble: string | null; fresh: Kind | null }) { +function Seat({ id, v, me, players, deadline, bubble, fresh, final }: { id: string; v: CockroachView; me: string | null; players: Record; deadline: number | null; bubble: string | null; fresh: Kind | null; final: CockroachView['final'] }) { const u = userOf(players, id); const r = v.round; const active = waitingOn(v) === id; - const loser = v.final?.loser === id; + const loser = final?.loser === id; const front = v.fronts[id]!; + const frontTotal = useAfterMotionValue(front.total); const role = v.phase === 'finished' ? null : r.holder === id ? (r.peeked ? '넘기는 중' : '받는 중') : r.holder === null && r.starter === id ? '건네는 중' : null; const label = `${u.nickname}님${id === me ? '(나)' : ''}: 손패 ${v.handCounts[id]}장, ${frontText(front, v.loseCount)}${role ? `, ${role}` : ''}${r.seen.includes(id) && r.holder !== null ? ', 이 카드를 봤어요' : ''}${v.away[id] ? ', 자리 비움' : ''}`; return ( @@ -454,12 +458,12 @@ function Seat({ id, v, me, players, deadline, bubble, fresh }: { id: string; v: {role && {role}} {r.holder !== null && r.seen.includes(id) && 👁 봤어요} {v.away[id] && 자리 비움} - {v.final && {loser ? '패배' : '승리'}} + {final && {loser ? '패배' : '승리'}}
    손패 {v.handCounts[id]}장 - · 앞마당 {front.total}장 + · 앞마당 {frontTotal}장
    @@ -491,6 +495,9 @@ function RevealLine({ rv, players, me, fresh, big }: { rv: LastReveal; players: const truth = rv.kind === rv.claim; const caller = rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`; const taker = rv.takenBy === me ? '내' : `${nick(players, rv.takenBy)}님`; + // A fresh verdict is written out only after the card has turned, been stamped and flown to its taker. + const settled = useMotionSettled(fresh); + const told = !fresh || settled; return (
    @@ -501,7 +508,7 @@ function RevealLine({ rv, players, me, fresh, big }: { rv: LastReveal; players: )} - + "{KIND_KO[rv.claim]}"{hasBatchim(KIND_KO[rv.claim]) ? "이라는" : "라는"} 말에 {caller} "{callWord}"{rv.auto ? '(시간 초과)' : ''} → 실제로는 {KIND_KO[rv.kind]}({truth ? '진짜' : '거짓'})
    {rv.correct ? '맞혔어요!' : '틀렸어요!'} {kj(rv.kind, '은', '는')} {taker} 앞마당으로 @@ -520,9 +527,11 @@ function Who({ id, players, me }: { id: string; players: Record; fresh: { slide: boolean; flip: boolean } }) { +function Table({ v, me, players, fresh, over }: { v: CockroachView; me: string | null; players: Record; fresh: { slide: boolean; flip: boolean }; over: boolean }) { const r = v.round; - if (v.phase === 'finished') { + // The call that ended the game is played out like any other (card turns, stamp, flight) before the end shows. + const lastCall = v.phase === 'finished' && fresh.flip && !over ? v.lastReveal : null; + if (v.phase === 'finished' && !lastCall) { const f = v.final!; return (
    @@ -564,11 +573,11 @@ function Table({ v, me, players, fresh }: { v: CockroachView; me: string | null;
    ); } - const last = v.lastReveal && v.lastReveal.round === r.no - 1 ? v.lastReveal : null; + const last = lastCall ?? (v.lastReveal && v.lastReveal.round === r.no - 1 ? v.lastReveal : null); return (
    {last ? : } - {r.starter === me ? '내가 카드를 건넬 차례예요' : `${nick(players, r.starter)}님의 카드를 기다리는 중`} + {!lastCall && {r.starter === me ? '내가 카드를 건넬 차례예요' : `${nick(players, r.starter)}님의 카드를 기다리는 중`}}
    ); } @@ -760,8 +769,9 @@ function RespondPanel({ v, players, act, pending }: { v: CockroachView; players: ); } -function WaitPanel({ v, players, me }: { v: CockroachView; players: Record; me: string | null }) { +function WaitPanel({ v, players, me, over }: { v: CockroachView; players: Record; me: string | null; over: boolean }) { if (v.phase === 'finished') { + if (!over) return null; const f = v.final!; return (
    @@ -793,21 +803,25 @@ function MyArea({ offering, bubble, fresh, + final, }: { v: CockroachView; me: string; players: Record; deadline: number | null; offering: boolean; + /** The result, once the last call has played out. */ + final: CockroachView['final']; /** What I just said with 빠른 말: shown over my own area too, like everybody else's. */ bubble: string | null; fresh: Kind | null; }) { const front = v.fronts[me]!; + const frontTotal = useAfterMotionValue(front.total); const active = waitingOn(v) === me; const total = v.handCounts[me] ?? 0; return ( -
    +
    {bubble && ( {bubble} @@ -838,7 +852,7 @@ function MyArea({
    - 내 앞마당 {front.total}장 + 내 앞마당 {frontTotal}장
    @@ -856,6 +870,19 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP const [bubbles, setBubbles] = useState>({}); const [fresh, setFresh] = useState({ slide: false, flip: false }); const [banner, showBanner] = useBanner(); + // A call is played out with timers (verdict, flight, the loss): results wait until its last step. + const [staging, setStaging] = useState(false); + const stageTimer = useRef | null>(null); + useMotionHold(staging); + useEffect(() => () => void (stageTimer.current && clearTimeout(stageTimer.current)), []); + const stageFor = (ms: number) => { + if (stageTimer.current) clearTimeout(stageTimer.current); + setStaging(true); + stageTimer.current = setTimeout(() => setStaging(false), ms); + }; + // The end of the game (badges, the table's result, the panel) shows once the last call has played out. + const overShown = useMotionSettled(v.phase === 'finished'); + const final = overShown ? v.final : null; const prev = useRef({ claims: v.round.claims.length + v.round.no * 100, reveal: v.lastReveal?.round ?? 0, @@ -887,8 +914,13 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP if (flip) { const rv = v.lastReveal!; sfx.cardFlip(); - setTimeout(() => (rv.correct ? sfx.good() : cpSfx.wrong()), fxMs(260)); - showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`); + // The verdict comes when the 진짜/거짓 stamp has landed on the turned card (flip .6s, stamp .55s + .45s). + setTimeout(() => { + if (rv.correct) sfx.good(); + else cpSfx.wrong(); + showBanner(rv.call === 'true' ? '진짜!' : '거짓말!', rv.correct ? 'green' : 'red', `${rv.caller === me ? '내가' : `${nick(players, rv.caller)}님이`} ${rv.correct ? '맞혔어요' : '틀렸어요'}`); + }, fxMs(1000)); + stageFor(fxMs(over ? 2600 : 1600)); // After the flip and the stamp, a face-up copy goes to the 앞마당 of whoever takes it. flyGhost(document.querySelector('.cp-revealcard') ?? document.querySelector('.cp-table'), seatEl(rv.takenBy), { delay: 1000, ms: 480, className: `cp-face-${rv.kind}`, label: KIND_KO[rv.kind] }); setTimeout(() => { @@ -904,7 +936,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP showBanner(`${f.loser === me ? '내가' : `${nick(players, f.loser)}님`} 패배!`, 'dark', f.losingKind ? `${KIND_KO[f.losingKind]}${hasBatchim(KIND_KO[f.losingKind]) ? '이' : '가'} 너무 많아요` : undefined); cpSfx.danger(); bump(seatEl(f.loser), 'shake'); - }, flip ? fxMs(1900) : 0); + }, flip ? fxMs(2500) : 0); // after the verdict banner and the card's landing } if (flip) { const rv = v.lastReveal!; @@ -940,8 +972,11 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP const responding = amPlayer && v.round.holder === me && !v.round.peeked && v.phase === 'respond'; const seats = amPlayer ? v.order.slice(v.order.indexOf(me!) + 1).concat(v.order.slice(0, v.order.indexOf(me!))) : v.order; + // A new verdict counts as fresh from its first render (the effect that sets `fresh` runs after it), so the card + // never shows face up or its verdict before the flip. + const freshNow = { slide: fresh.slide, flip: fresh.flip || (v.lastReveal?.round ?? 0) !== prev.current.reveal }; // The card that just went face up lands in front of whoever took it. - const landed = fresh.flip && v.lastReveal ? { id: v.lastReveal.takenBy, kind: v.lastReveal.kind } : null; + const landed = freshNow.flip && v.lastReveal ? { id: v.lastReveal.takenBy, kind: v.lastReveal.kind } : null; const landedFor = (id: string) => (landed?.id === id ? landed.kind : null); return ( @@ -950,11 +985,11 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP
    {seats.map((p) => ( - + ))}
    - - {amPlayer && } +
    + {amPlayer && }
    {offering || passing ? ( @@ -962,7 +997,7 @@ function CockroachBoard({ view: v, me, players, act, pending, deadline }: BoardP ) : responding ? ( ) : ( - + )}

    @@ -1002,12 +1037,15 @@ function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardPr const running = v.phase !== 'finished'; const w = waitingOn(v); const r = v.round; + // Who lost (and the 앞마당 counts) show once the last call has played out on the board. + const final = useMotionSettled(v.phase === 'finished') ? v.final : null; + const fronts = useAfterMotionValue(v.order.map((p) => v.fronts[p]!.total).join(',')).split(','); return ( <>

    - {running ? `${r.no}라운드 · ${nick(players, w!)}님 차례` : '게임 끝'} + {running ? `${r.no}라운드 · ${nick(players, w!)}님 차례` : final ? '게임 끝' : `${r.no}라운드`} {running && }
    {optionsSummary(v.options, v.order.length)} @@ -1018,17 +1056,17 @@ function CockroachSide({ view: v, me, players, act, pending, deadline }: BoardPr {nick(players, p)} {w === p ? ' · 차례' : ''} - {v.final ? (v.final.loser === p ? ' · 패배' : ' · 승리') : ''} + {final ? (final.loser === p ? ' · 패배' : ' · 승리') : ''} - 손 {v.handCounts[p]} · 앞 {v.fronts[p]!.total} + 손 {v.handCounts[p]} · 앞 {fronts[v.order.indexOf(p)] ?? v.fronts[p]!.total} ))} {v.removedCount > 0 && running && 2명 게임이라 카드 {v.removedCount}장을 보지 않고 뺐어요.}
    - {v.final && } + {final && } {running && v.options.claimHistory && r.claims.length > 0 && (
    이번 라운드 주장 diff --git a/apps/web/src/games/connect-four/index.tsx b/apps/web/src/games/connect-four/index.tsx index 7a9b9c3..7d34e4e 100644 --- a/apps/web/src/games/connect-four/index.tsx +++ b/apps/web/src/games/connect-four/index.tsx @@ -5,6 +5,7 @@ import type { PublicUser } from '@bg/shared/lite'; import { Avatar, ConfirmSheet } from '../../components/ui'; import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { haptic, noise, sfx, tone } from '../../lib/feedback'; +import { useMotionSettled } from '../../lib/motion'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; @@ -132,7 +133,10 @@ function C4Board({ view: v, act, pending, tapConfirm }: BoardProps p.y * cols + p.x)); + // The winning four light up only once the last disc has landed. + const winShown = useMotionSettled(!!v.winLine?.length); + const winLine = winShown ? (v.winLine ?? []) : []; + const winSet = new Set(winLine.map((p) => p.y * cols + p.x)); const last = v.lastMove ? v.lastMove.y * cols + v.lastMove.x : -1; const pad = 0.15; const cells = Array.from({ length: cols * rows }, (_, i) => i); @@ -196,7 +200,7 @@ function C4Board({ view: v, act, pending, tapConfirm }: BoardProps )} - {(v.winLine ?? []).map((p, k) => ( + {winLine.map((p, k) => ( { + if (endDone) resumeFx(); + }, [endDone]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (mine && !prevMine.current) { haptic(40); @@ -768,17 +775,27 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro
    - - - {v.phase === 'revolutionCheck' && } - {v.phase === 'taxReturn' && } - {v.phase === 'playing' && } - {v.phase === 'playing' && v.my && } - {v.phase === 'finished' && v.result && ( -
    -

    게임이 끝났어요

    - {v.result.summary} -
    + {showEnd ? ( + <> + {/* The round is over: its last cards land and the 등 banners play before the results and the next round. */} + + + + ) : ( + <> + + + {v.phase === 'revolutionCheck' && } + {v.phase === 'taxReturn' && } + {v.phase === 'playing' && } + {v.phase === 'playing' && v.my && } + +
    +

    게임이 끝났어요

    + {v.result?.summary} +
    +
    + )}

    {announce} @@ -788,10 +805,33 @@ function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardPro ); } +/** + * The table as it stood when the round ended (the last play on top, seats before the new titles), from the moment + * the round-ending view arrives until the next playing phase; null otherwise. Computed during render so the cards + * are on screen in the same frame as their fly-in. + */ +function useRoundEnd(v: DalmutiView): DalmutiView | null { + const r = useRef<{ cur: DalmutiView; end: DalmutiView | null }>({ cur: v, end: null }); + const s = r.current; + if (s.cur !== v) { + const p = s.cur; + s.cur = v; + if (v.phase === 'playing') s.end = null; + else if (p.phase === 'playing') { + const seen = new Set(p.log.map(logKey)); + const play = [...v.log].reverse().find((e): e is Extract => e.t === 'play' && !seen.has(logKey(e))); + const top: PlayView | null = play ? { by: play.p, count: play.count, rank: play.rank, cards: play.cards } : null; + const trick = top ? { leader: p.trick?.leader ?? top.by, top, pile: [...(p.trick?.pile ?? []), top] } : p.trick; + s.end = { ...p, trick, current: null, seats: p.seats.map((x) => ({ ...x, isTurn: false })) }; + } + } + return s.end; +} + const logKey = (e: LogEntry) => `${e.seq}-${e.t}-${'p' in e ? e.p : 'from' in e ? e.from : ''}`; /** Sounds + motion for every change of the table, mine or anyone else's (log entries since the last view). */ -function useDalmutiFx(v: DalmutiView, me: string | null, players: Record, showBanner: ReturnType[1]) { +function useDalmutiFx(v: DalmutiView, me: string | null, players: Record, showBanner: ReturnType[1], roundEnding: boolean): () => void { const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f()); const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`); // A new round (or the very first deal): cards go from the middle to everyone. @@ -802,7 +842,14 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record flyFrom(el, c, { delay: delay + 280 + i * 45, rotate: 10 })); for (const s of v.seats) if (s.id !== me) flyGhost(c, seatEl(s.id), { count: 3, gap: 90, delay: delay + 280 }); }; + // While the ended round is still on screen, the new round's part (the deal, tax flights) waits for `resume`. + const deferred = useRef([]); useNewEntries(v.log, logKey, (fresh) => { + const r = roundEnding ? fresh.findIndex((e) => e.t === 'round') : -1; + if (r >= 0) deferred.current = fresh.slice(r); + run(r >= 0 ? fresh.slice(0, r) : fresh); + }); + function run(fresh: LogEntry[]) { const lastPlay = [...fresh].reverse().find((e) => e.t === 'play'); let t = 0; for (const e of fresh) { @@ -863,7 +910,7 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record { if (started.current) return; @@ -876,6 +923,11 @@ function useDalmutiFx(v: DalmutiView, me: string | null, players: Record e.t === 'tax') && v.taxPending.every((p) => !p.done)); if (fresh) deal(); }, []); // eslint-disable-line react-hooks/exhaustive-deps + return () => { + const d = deferred.current; + deferred.current = []; + if (d.length) run(d); + }; } // ---------------------------------------------------------------- side @@ -896,7 +948,13 @@ function rulesLine(o: DalmutiOptions): string { function DalmutiSide({ view: v, me, players, deadline }: BoardProps) { const phaseKo = v.phase === 'revolutionCheck' ? '손패 확인' : v.phase === 'taxReturn' ? '세금 교환' : v.phase === 'playing' ? '진행 중' : '게임 끝'; - const rounds = v.roundResults; + // Points and round ranks change once the round's last cards and banners have played on the board. + const shownRounds = useAfterMotionValue(v.roundResults.length); + const shownRef = useRef(v); + if (shownRounds === v.roundResults.length) shownRef.current = v; + const sv = shownRef.current; + const totalOf = (id: string) => (sv.seats.find((x) => x.id === id) ?? v.seats.find((x) => x.id === id))?.total ?? 0; + const rounds = sv.roundResults; return ( <> @@ -921,7 +979,7 @@ function DalmutiSide({ view: v, me, players, deadline }: BoardProps {s.id === me ? ' (나)' : ''} {s.title} - {s.total}점 + {totalOf(s.id)}점 @@ -947,7 +1005,7 @@ function DalmutiSide({ view: v, me, players, deadline }: BoardProps

    - {(v.result ? v.result.players.map((p) => p.player) : v.seats.map((s) => s.id)).map((p) => ( + {(sv.result ? sv.result.players.map((p) => p.player) : v.seats.map((s) => s.id)).map((p) => ( ))} ))}
    {nick(players, p)} @@ -956,13 +1014,13 @@ function DalmutiSide({ view: v, me, players, deadline }: BoardProps {r.order.indexOf(p) + 1}등 - {v.seats.find((s) => s.id === p)?.total ?? 0}점 + {totalOf(p)}점
    - {v.result &&

    {v.result.summary}

    } + {sv.result &&

    {sv.result.summary}

    }
    )} {v.log.length > 0 && ( diff --git a/apps/web/src/games/davinci-code/index.tsx b/apps/web/src/games/davinci-code/index.tsx index da8c70f..acd5a7e 100644 --- a/apps/web/src/games/davinci-code/index.tsx +++ b/apps/web/src/games/davinci-code/index.tsx @@ -8,7 +8,7 @@ import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion'; const COLOR_KO: Record = { black: '검은색', white: '흰색' }; const COLOR_SHORT: Record = { black: '검정', white: '흰색' }; @@ -251,6 +251,15 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro const [banner, setBanner] = useTimed<{ text: string; s: number }>(); const [announce, setAnnounce] = useState(''); const seq = useRef(0); + // "○○님 탈락!" waits for the flip of the tile that put them out; meanwhile the screen counts as moving. + const [bannerWait, setBannerWait] = useState(false); + const bannerTimer = useRef | undefined>(undefined); + useMotionHold(bannerWait); + useEffect(() => () => clearTimeout(bannerTimer.current), []); + // A new guess is told (panel, last guess line) only once its tile has turned over; the end panel after the reveal. + const shownHist = useAfterMotionValue(v.history.length); + const endShown = useMotionSettled(v.phase === 'finished'); + const settling = shownHist !== v.history.length ? 'guess' : v.phase === 'finished' && !endShown ? 'end' : null; const snap = useRef<{ hist: number; phase: PhaseKind; pending: boolean; elim: number; picked: number; rows: Record } | null>(null); const prevTurn = useRef(`${v.current}|${v.phase === 'chooseStart'}`); @@ -325,9 +334,16 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro if (now.elim > prev.elim) { const out = v.eliminationOrder[v.eliminationOrder.length - 1]!; if (!v.left[out]) { - setBanner({ text: out === me ? '내 숨은 타일이 다 드러났어요' : `${nick(players, out)}님 탈락!`, s: ++seq.current }, 1700); - // The match result sound itself is played by the room page. - if (v.phase !== 'finished') snd.out(t + 250); + const text = out === me ? '내 숨은 타일이 다 드러났어요' : `${nick(players, out)}님 탈락!`; + const more = v.phase !== 'finished'; + clearTimeout(bannerTimer.current); + setBannerWait(true); + bannerTimer.current = setTimeout(() => { + setBannerWait(false); + setBanner({ text, s: ++seq.current }, 1700); + // The match result sound itself is played by the room page. + if (more) snd.out(0); + }, fxMs(t + 500)); } } if (prev.phase !== 'finished' && v.phase === 'finished') { @@ -377,8 +393,8 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro ))}
    -
    - (setSel(null), setVal(null))} /> +
    + (setSel(null), setVal(null))} />
    {amPlayer && }

    @@ -395,9 +411,11 @@ function DavinciBoard({ view: v, me, players, act, pending, deadline }: BoardPro function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view: DavinciView; me: string | null; players: Record; deadline: number | null }) { const u = userOf(players, id); - const row = v.rows[id] ?? []; - const st = v.stats[id] ?? { guesses: 0, correct: 0 }; - const outRank = v.eliminationOrder.indexOf(id); + // Counts, 탈락 and 승리 change once the tile that changed them has turned over (`r`); the turn is live (`v`). + const r = useAfterMotionValue(v); + const row = r.rows[id] ?? []; + const st = r.stats[id] ?? { guesses: 0, correct: 0 }; + const outRank = r.eliminationOrder.indexOf(id); const isTurn = v.phase !== 'finished' && v.phase !== 'chooseStart' && v.current === id; const choosing = v.phase === 'chooseStart' && v.alive[id] && v.picked && !v.picked[id]; return ( @@ -408,12 +426,12 @@ function PlayerHead({ id, view: v, me, players, deadline }: { id: string; view: {id === me && (나)} {isTurn && 차례} - {v.final?.winner === id && 승리} - {!v.alive[id] && {v.left[id] ? '나감' : '탈락'}{outRank >= 0 ? ` · ${v.seats.length - outRank}위` : ''}} + {r.final?.winner === id && 승리} + {!r.alive[id] && {r.left[id] ? '나감' : '탈락'}{outRank >= 0 ? ` · ${r.seats.length - outRank}위` : ''}} {v.alive[id] && (v.idle[id] ?? 0) >= 3 && 자리 비움} {v.phase === 'chooseStart' && v.alive[id] && {choosing ? '고르는 중' : '다 골랐어요'}} - {v.phase !== 'chooseStart' && ( + {r.phase !== 'chooseStart' && ( <> 숨은 타일 {hiddenLeft(row)}개 ·{' '} @@ -558,6 +576,7 @@ function Center({ pending, myTurn, pendFx, + lastNo, }: { view: DavinciView; me: string | null; @@ -566,10 +585,12 @@ function Center({ pending: boolean; myTurn: boolean; pendFx: Fx | null; + /** How many guesses have been shown so far (the newest one waits for its tile to turn). */ + lastNo: number; }) { const drawing = myTurn && v.phase === 'draw' && !pending; const total = v.pool.black + v.pool.white; - const last = v.history[v.history.length - 1]; + const last = v.history[Math.min(lastNo, v.history.length) - 1]; return (

    {v.options.chooseColors ? ( @@ -643,6 +664,7 @@ function ActionPanel({ act, pending, myTurn, + settling, sel, val, setVal, @@ -654,11 +676,21 @@ function ActionPanel({ act: (a: unknown) => void; pending: boolean; myTurn: boolean; + /** A tile is still turning over: say what was guessed, not yet whether it was right (or who won). */ + settling: 'guess' | 'end' | null; sel: Sel | null; val: TileValue | null; setVal: (v: TileValue | null) => void; onCancel: () => void; }) { + if (settling) { + const g = settling === 'guess' ? v.history[v.history.length - 1] : undefined; + return ( +
    + {g ? `${nick(players, g.by)}님이 ${nick(players, g.target)}님 ${g.index + 1}번째 타일을 ${valueKo(g.said)}(으)로 추리했어요…` : '…'} +
    + ); + } if (v.phase === 'finished') { return (
    @@ -886,7 +918,9 @@ function StartChooser({ view: v, me, act, pending }: { view: DavinciView; me: st // ---------------------------------------------------------------- side -function DavinciSide({ view: v, me, players, deadline }: BoardProps) { +function DavinciSide({ view, me, players, deadline }: BoardProps) { + // The side panel (counts, ranks, the guess log) follows the board once its tiles have turned over. + const v = useAfterMotionValue(view); const running = v.phase !== 'finished'; const ranking = v.final?.ranking ?? null; return ( diff --git a/apps/web/src/games/dobble/index.tsx b/apps/web/src/games/dobble/index.tsx index 1628b3c..038fedb 100644 --- a/apps/web/src/games/dobble/index.tsx +++ b/apps/web/src/games/dobble/index.tsx @@ -11,7 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; import { ICON_NAMES, SymbolArt } from './art'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useMotionSettled } from '../../lib/motion'; /** Taps this soon after one of the two cards changed are dropped as late (they were aimed at the previous card). */ const TAP_GRACE_MS = 250; @@ -283,6 +283,10 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps(null); const [announce, setAnnounce] = useState(''); + // The round result waits until the last find has played (its bubble and the cards changing); the next round's + // countdown is real time and never waits. + const [roundNote, setRoundNote] = useState<{ bubble: Bubble; bad: boolean } | null>(null); + const roundReady = useMotionSettled(roundNote !== null, fxMs(1000)); const prev = useRef(null); const changed = useRef({ sig: '', at: 0 }); @@ -380,10 +384,7 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps (s.status === 'finished' || s.status === 'escaped') && p.seats.find((x) => x.id === s.id)?.status === 'playing'); @@ -392,6 +393,15 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps 0) sfx.select(); }, [v]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { + if (!roundReady || !roundNote) return; + setBubble(roundNote.bubble); + setAnnounce(roundNote.bubble.text); + if (roundNote.bad) sfx.bad(); + else sfx.whoosh(); + setRoundNote(null); + }, [roundReady]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { if (!bubble) return; const t = setTimeout(() => setBubble(null), fxMs(bubble.kind === 'late' ? 1300 : 1700)); @@ -554,7 +564,7 @@ function DobbleBoard({ view: v, me, players, act, pending }: BoardProps )} {countdown > 0 && ( -
    +
    {countdown} {v.phase === 'roundEnd' ? '다음 라운드를 준비해요' : '두 카드에 똑같이 있는 그림을 찾아요!'}
    @@ -903,6 +913,7 @@ const ui: GameUI = { Board: DobbleBoard, Side: DobbleSide, statusText, + liveStatus: true, isMyTurn, Options, optionsSummary, diff --git a/apps/web/src/games/gemblo/index.tsx b/apps/web/src/games/gemblo/index.tsx index 516ae49..f0ebe8d 100644 --- a/apps/web/src/games/gemblo/index.tsx +++ b/apps/web/src/games/gemblo/index.tsx @@ -24,6 +24,7 @@ import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { haptic } from '../../lib/feedback'; import { toast } from '../../store/toast'; import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion'; +import { AfterMotion, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { GEM, GemCell, MiniHex, PieceIcon, SQ3, hexPoints, hx } from './draw'; import { helpNow } from './help'; @@ -302,6 +303,14 @@ function GembloBoard({ view: v, me, players, act, pending }: BoardProps([]); + const toastReady = useMotionSettled(toastQ.length > 0); + useEffect(() => { + if (!toastReady) return; + toastQ.forEach((t) => toast(t)); + setToastQ([]); + }, [toastReady]); // eslint-disable-line react-hooks/exhaustive-deps useLayoutEffect(() => { const prev = prevHist.current; prevHist.current = v.history.length; @@ -316,10 +325,10 @@ function GembloBoard({ view: v, me, players, act, pending }: BoardProps [...q, `${eun(m.color)} 더 놓을 곳이 없어요(남은 ${m.leftCells}칸)`]); gmSound.out(); } else if (m.reason === 'allPlaced') { - toast(`${eun(m.color)} 18개를 모두 놓았어요!`); + setToastQ((q) => [...q, `${eun(m.color)} 18개를 모두 놓았어요!`]); gmSound.allPlaced(); } } @@ -823,7 +832,9 @@ function GembloBoard({ view: v, me, players, act, pending }: BoardProps
    )} - {v.phase === 'finished' && } + + +
    ); @@ -869,7 +880,7 @@ function ColorChip({ v, i }: { v: GembloView; i: number }) { ); } -function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPlayerView; players: Record; deadline: number | null; me: string | null }) { +function PlayerRow({ v, shown, p, players, deadline, me }: { v: GembloView; shown: GembloView; p: GembloPlayerView; players: Record; deadline: number | null; me: string | null }) { const u = players[p.id] ?? { id: p.id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const }; const active = v.phase !== 'finished' && v.turnPlayer === p.id; const now = useServerNow(500); @@ -886,7 +897,7 @@ function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPl } else if (active && (tc.kind === 'perMove' || v.phase !== 'playing')) { clock = ; } - const left = p.colors.reduce((n, i) => n + v.colors[i]!.leftCells, 0); + const left = p.colors.reduce((n, i) => n + shown.colors[i]!.leftCells, 0); const teamColors = p.team !== null && v.teams ? ` · ${p.team + 1}팀` : ''; return (
    @@ -907,7 +918,7 @@ function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPl
    {p.colors.map((i) => ( - + ))}
    @@ -922,10 +933,15 @@ function GembloSide({ view: v, me, players, act, pending, deadline }: BoardProps const incoming = live && u && u.by !== me && !u.accepted.includes(me!) ? u : null; const waiting = live && u && (u.by === me || u.accepted.includes(me!)); const order = mine ? [...v.players.filter((p) => p.id !== me), mine] : v.players; + // Cells left / 끝 per color change once the block has landed on the board. + const shownMoves = useAfterMotionValue(v.history.length); + const shownRef = useRef(v); + if (shownMoves === v.history.length) shownRef.current = v; + const shown = shownRef.current.colors.length === v.colors.length ? shownRef.current : v; return ( <> {order.map((p) => ( - + ))} {live && (
    diff --git a/apps/web/src/games/gostop/index.tsx b/apps/web/src/games/gostop/index.tsx index 22aac0c..7bd08fe 100644 --- a/apps/web/src/games/gostop/index.tsx +++ b/apps/web/src/games/gostop/index.tsx @@ -11,7 +11,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxAnim, fxMs } from '../../lib/motion'; +import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; const nick = (players: Record, id: string | null | undefined) => (id ? (players[id]?.nickname ?? '알 수 없음') : ''); const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; @@ -238,18 +238,21 @@ function CapturedRow({ seat, label }: { seat: SeatView; label: string }) { function Progress({ seat, winScore }: { seat: SeatView; winScore: number }) { const s = seat.score; - const items: [string, boolean][] = [ + const now: [string, boolean][] = [ [`광 ${s.gwang}장`, s.gwang >= 3], [`열끗 ${s.yeol}/5`, s.yeol >= 5], [`띠 ${s.tti}/5`, s.tti >= 5], [`피 ${s.pi}/10`, s.pi >= 10], ]; - if (s.godori) items.push([`고도리 ${s.godori}/3`, s.godori === 3]); - if (s.hong) items.push([`홍단 ${s.hong}/3`, s.hong === 3]); - if (s.cheong) items.push([`청단 ${s.cheong}/3`, s.cheong === 3]); - if (s.cho) items.push([`초단 ${s.cho}/3`, s.cho === 3]); + if (s.godori) now.push([`고도리 ${s.godori}/3`, s.godori === 3]); + if (s.hong) now.push([`홍단 ${s.hong}/3`, s.hong === 3]); + if (s.cheong) now.push([`청단 ${s.cheong}/3`, s.cheong === 3]); + if (s.cho) now.push([`초단 ${s.cho}/3`, s.cho === 3]); + // Progress changes once the taken cards have flown into the pile. + const [total, ...rest] = useAfterMotionValue([String(s.total), ...now.map(([t, d]) => `${d ? 1 : 0}${t}`)].join('|')).split('|'); + const items = rest.map((x): [string, boolean] => [x.slice(1), x[0] === '1']); return ( -
    x[0]).join(', ')}. 지금 ${s.total}점, 기준 ${winScore}점`}> +
    x[0]).join(', ')}. 지금 ${total}점, 기준 ${winScore}점`}> {items.map(([t, done]) => ( {t} @@ -260,9 +263,11 @@ function Progress({ seat, winScore }: { seat: SeatView; winScore: number }) { } function SeatBadges({ seat, v }: { seat: SeatView; v: GostopView }) { + // The score changes once the taken cards have flown into the pile. + const score = useAfterMotionValue(seat.score.total); return (
    - {seat.participant && 지금 {seat.score.total}점} + {seat.participant && 지금 {score}점} {seat.goCount > 0 && {seat.goCount}고} {seat.shakes > 0 && 흔듦 {seat.shakes}} {seat.bombs > 0 && 폭탄 {seat.bombs}} @@ -279,8 +284,10 @@ function SeatBadges({ seat, v }: { seat: SeatView; v: GostopView }) { function SeatBox({ seat, v, players, me, deadline }: { seat: SeatView; v: GostopView; players: Record; me: string | null; deadline: number | null }) { const u = userOf(players, seat.id); const active = actorOf(v) === seat.id; + // Room points change once the round's payments have flown. + const total = useAfterMotionValue(seat.total); return ( -
  • +
  • @@ -289,7 +296,7 @@ function SeatBox({ seat, v, players, me, deadline }: { seat: SeatView; v: Gostop {seat.isDealer && 선} - 합계 {signed(seat.total)} + 합계 {signed(total)} {(seat.participant || v.step === 'sell') && ( @@ -405,7 +412,12 @@ function Floor({ v, glow, narrow, players }: { v: GostopView; glow: Set; } function LastTurn({ v, players }: { v: GostopView; players: Record }) { - const t = v.lastTurn; + // A new turn (what was flipped and taken) shows once its cards have landed; until then the previous one stays. + const key = `${v.roundNo}-${v.lastTurn?.seq ?? 0}`; + const shownKey = useAfterMotionValue(key); + const kept = useRef(v.lastTurn); + if (shownKey === key) kept.current = v.lastTurn; + const t = kept.current; if (!t) return
    ; const tags = t.tags.map((x) => TAG_KO[x]).filter(Boolean); const stolen = t.stolen.reduce((a, s) => a + s.cards.length, 0); @@ -459,7 +471,7 @@ type Ask = { kind: 'target' | 'shake' | 'bomb'; h: HandCardView } | null; function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; onFocusCard: (h: HandCardView | null) => void }) { const [lifted, setLifted] = useState(null); const [ask, setAsk] = useState(null); - const canPlay = v.step === 'play' && v.turn === v.me && !pending; + const canPlay = v.phase === 'playing' && v.step === 'play' && v.turn === v.me && !pending; const hints = v.rules.hints; const cw = useCardW(); useEffect(() => { @@ -578,12 +590,13 @@ function MyHand({ v, act, pending, tapConfirm, onFocusCard }: { v: GostopView; a ); } -function MyArea(props: BoardProps & { onFocusCard: (h: HandCardView | null) => void }) { - const { view: v, me, players, act, pending, deadline, tapConfirm, onFocusCard } = props; +function MyArea(props: BoardProps & { onFocusCard: (h: HandCardView | null) => void; holdOpen: boolean }) { + const { view: v, me, players, act, pending, deadline, tapConfirm, onFocusCard, holdOpen } = props; const seat = v.seats.find((s) => s.id === me); if (!seat || !me) return null; const active = actorOf(v) === me; - if (v.phase !== 'playing') return null; + // After the round ends my area stays until the result panel shows, so the last cards can still fly into my pile. + if (v.phase !== 'playing' && !(v.outcome && holdOpen)) return null; return (
    @@ -644,7 +657,13 @@ function SellPanel({ v, me, players, act, pending }: { v: GostopView; me: string // ---------------------------------------------------------------- decisions (sheets) -function Decisions({ view: v, me, players, act, pending }: BoardProps) { +/** A decision sheet (고·스톱, 뒤집은 패, 총통, 국진) opens once the cards that led to it have landed. */ +function Decisions(props: BoardProps) { + const sheet = DecisionSheet(props); + return sheet && {sheet}; +} + +function DecisionSheet({ view: v, me, players, act, pending }: BoardProps): React.ReactElement | null { if (!me || v.phase !== 'playing') return null; const nop = () => {}; if (v.step === 'goStop' && v.goStop && v.turn === me) { @@ -744,11 +763,14 @@ function outcomeTitle(o: OutcomeView, players: Record, me: s function RoundResult({ view: v, me, players, act, pending }: BoardProps) { const o = v.outcome; + // The panel waits (invisible, so the payment chips can still fly to it) until the last cards, the 스톱! banner and + // the chips have played. + const shown = useMotionSettled(!!o && v.phase !== 'playing'); if (!o || v.phase === 'playing') return null; const seat = v.seats.find((s) => s.id === me); const nextMult = v.rules.nagariMultiplier === 'x2' ? Math.min(2 ** v.nagariStreak, v.rules.nagariMaxMultiplier) : 1; return ( -
    +

    {v.roundNo}판 결과 · {outcomeTitle(o, players, me)}

    @@ -1190,11 +1212,12 @@ function GostopBoard(props: BoardProps) { } prevMine.current = mine; }, [mine]); // eslint-disable-line react-hooks/exhaustive-deps + const resultShown = useMotionSettled(!!v.outcome && v.phase !== 'playing'); useEffect(() => { - if (v.outcome && v.phase !== 'playing') { + if (resultShown && v.outcome && v.phase !== 'playing') { setAnnounce(`${v.roundNo}판 결과: ${outcomeTitle(v.outcome, players, me)}`); } - }, [v.roundNo, v.phase]); // eslint-disable-line react-hooks/exhaustive-deps + }, [v.roundNo, v.phase, resultShown]); // eslint-disable-line react-hooks/exhaustive-deps const [banner, showBanner] = useBanner(); useGostopFx(v, me, players, showBanner); const myIdx = v.seats.findIndex((s) => s.id === me); @@ -1212,7 +1235,7 @@ function GostopBoard(props: BoardProps) { - + {banner}

    @@ -1226,8 +1249,14 @@ function GostopBoard(props: BoardProps) { // ---------------------------------------------------------------- side function GostopSide({ view: v, me, players, deadline }: BoardProps) { - const ranked = [...v.seats].sort((a, b) => b.total - a.total); const mySeat = v.seats.find((s) => s.id === me); + // Points change once the cards / payment chips that caused them have landed. + const shownTotals = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.total}`).join(',')); + const totalOf = new Map(shownTotals.split(',').map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))] as const)); + const total = (s: SeatView) => totalOf.get(s.id) ?? s.total; + const ranked = [...v.seats].sort((a, b) => total(b) - total(a)); + const myScore = mySeat ? `${mySeat.score.total}\n${mySeat.score.items.map((x) => `${x.name} ${x.points}점`).join(' · ')}` : ''; + const [myTotal, myItems] = useAfterMotionValue(myScore).split('\n'); return ( <> @@ -1253,7 +1282,7 @@ function GostopSide({ view: v, me, players, deadline }: BoardProps) {s.isDealer ? ' · 선' : ''} {s.left ? ' · 나감' : s.autoPilot ? ' · 자동' : ''} - {signed(s.total)} + {signed(total(s))}

  • ))} @@ -1261,10 +1290,10 @@ function GostopSide({ view: v, me, players, deadline }: BoardProps) {mySeat?.participant && v.phase === 'playing' && (
    - 내 점수 {mySeat.score.total}점 / 기준 {v.rules.winScore}점 + 내 점수 {myTotal}점 / 기준 {v.rules.winScore}점 - {mySeat.score.items.length > 0 ? ( - {mySeat.score.items.map((x) => `${x.name} ${x.points}점`).join(' · ')} + {myItems ? ( + {myItems} ) : ( 아직 점수 족보가 없어요. )} @@ -1285,19 +1314,21 @@ function GostopSide({ view: v, me, players, deadline }: BoardProps)
    )} {v.result && ( -
    - 최종 순위 - {v.result.ranking.map((g, i) => ( - - {v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')} ({signed(v.result!.scores[g[0]!] ?? 0)}) - - ))} - {v.stats.bestRound && ( - - 가장 큰 판: {v.stats.bestRound.roundNo}판 {nick(players, v.stats.bestRound.player)} {pts(v.stats.bestRound.amount)} - - )} -
    + +
    + 최종 순위 + {v.result.ranking.map((g, i) => ( + + {v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')} ({signed(v.result!.scores[g[0]!] ?? 0)}) + + ))} + {v.stats.bestRound && ( + + 가장 큰 판: {v.stats.bestRound.roundNo}판 {nick(players, v.stats.bestRound.player)} {pts(v.stats.bestRound.amount)} + + )} +
    +
    )}
    족보표 diff --git a/apps/web/src/games/halli-galli/index.tsx b/apps/web/src/games/halli-galli/index.tsx index 18064d2..1122c80 100644 --- a/apps/web/src/games/halli-galli/index.tsx +++ b/apps/web/src/games/halli-galli/index.tsx @@ -9,7 +9,7 @@ import { socket, useRoom } from '../../net/socket'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { AfterMotion, fxMs } from '../../lib/motion'; import { useWide } from '../../lib/media'; const FRUITS: Fruit[] = ['strawberry', 'banana', 'lime', 'plum']; @@ -975,21 +975,24 @@ function HalliGalliSide({ view: v, me, players }: BoardProps) { )} - {v.result && ( -
    - 최종 순위 - {v.result.ranking.map((r) => ( - - {r.rank}등 {nick(players, r.id)} - - {' '} - · {r.cards}장 · 정답 {r.correct} · 오답 {r.wrong} + {/* The ranking waits for the last bell's slap and card flights. */} + + {v.result && ( +
    + 최종 순위 + {v.result.ranking.map((r) => ( + + {r.rank}등 {nick(players, r.id)} + + {' '} + · {r.cards}장 · 정답 {r.correct} · 오답 {r.wrong} + - - ))} - {v.result.summary} -
    - )} + ))} + {v.result.summary} +
    + )} + {v.log.length > 0 && (
    기록 @@ -1221,6 +1224,7 @@ const ui: GameUI = { Board: HalliGalliBoard, Side: HalliGalliSide, statusText, + liveStatus: true, isMyTurn, Options, optionsSummary, diff --git a/apps/web/src/games/hot-streak/index.tsx b/apps/web/src/games/hot-streak/index.tsx index d4632b3..ce3c6f0 100644 --- a/apps/web/src/games/hot-streak/index.tsx +++ b/apps/web/src/games/hot-streak/index.tsx @@ -20,6 +20,7 @@ import type { PublicUser } from '@bg/shared/lite'; import { Avatar, ConfirmSheet } from '../../components/ui'; import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { haptic, sfx, sounds } from '../../lib/feedback'; +import { AfterMotion, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { MascotIcon, RaceCard } from './art'; import { helpNow } from './help'; @@ -708,8 +709,9 @@ function Board({ view: v, me, players, act, pending }: BoardProps } }, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps const lastRes = v.results.at(-1); - const showPayout = v.phase === 'payout' && lastRes && !replay.busy; - const answered = v.phase === 'payout' && lastRes && !replay.busy ? lastRes.side.yes : null; + // The payout and the side answer wait until the race has played to the end (its last 1등!/실격! floats included). + const showPayout = useMotionSettled(v.phase === 'payout' && !!lastRes && !replay.busy); + const answered = showPayout && lastRes ? lastRes.side.yes : null; const r = v.race; const house = HOUSE(v); const shownLog = r && line ? r.log.filter((l) => l.n <= line.n) : []; @@ -726,12 +728,14 @@ function Board({ view: v, me, players, act, pending }: BoardProps ))} {v.phase !== 'finished' && } - {v.result && } + + + {v.phase === 'draft' && v.mode === 'tickets' && v.draft && } {v.phase === 'double' && } {v.phase === 'draft' && v.mode === 'pots' && } {v.phase === 'submit' && } - {showPayout && } + {showPayout && lastRes && } {v.faceUp.length > 0 && (v.phase === 'draft' || v.phase === 'double' || v.phase === 'submit') && } {shownLog.length > 0 && ( @@ -779,6 +783,9 @@ function Side({ view: v, me, players, act, deadline, active }: BoardProps v.money[p] ?? 0).join(',')); + const money = Object.fromEntries(v.seats.map((p, i) => [p, Number(moneyKey.split(',')[i] ?? v.money[p] ?? 0)])); return ( <>
    @@ -797,8 +804,8 @@ function Side({ view: v, me, players, act, deadline, active }: BoardProps
    {statusOf(v, p)}
    - - {$(v.money[p]!)} + + {$(money[p]!)} {on && playing && } diff --git a/apps/web/src/games/hot-streak/track.tsx b/apps/web/src/games/hot-streak/track.tsx index f8513ac..353c34d 100644 --- a/apps/web/src/games/hot-streak/track.tsx +++ b/apps/web/src/games/hot-streak/track.tsx @@ -7,7 +7,7 @@ import { useEffect, useRef, useState, type ReactElement } from 'react'; import type { HsRaceView, RaceLine, Racer } from '@bg/games/hot-streak'; import { MASCOTS, MASCOT_IDS, josa, type MascotId } from '@bg/games/hot-streak/cards'; import { noise, sfx, tone } from '../../lib/feedback'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useMotionHold } from '../../lib/motion'; import { MascotFace } from './art'; export const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches; @@ -210,6 +210,8 @@ export function useReplay(r: HsRaceView | null) { q.current.push(...fresh); if (!s.playing) pump(); }, [r?.no, r?.log.at(-1)?.n]); // eslint-disable-line react-hooks/exhaustive-deps + // The lines play with timers (gaps between hops are not animations): results wait until the last line has played. + useMotionHold(busy); return { shown, floats, busy }; } diff --git a/apps/web/src/games/janggi/index.tsx b/apps/web/src/games/janggi/index.tsx index 728014e..ab7cfd9 100644 --- a/apps/web/src/games/janggi/index.tsx +++ b/apps/web/src/games/janggi/index.tsx @@ -11,7 +11,7 @@ import { addedPieces, janggiCues, janggiMotion } from './fx'; import { helpNow } from './help'; import { nopeSound, pickSound, playJanggi, setupSound } from './sound'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; const SIDE_KO: Record = { cho: '초', han: '한' }; const INK: Record = { cho: '#1d4ed8', han: '#c0262d' }; @@ -207,6 +207,9 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps(null); + // 장군!/멍군!/빅장! wait until the piece has landed (and the 장군 pulse has played). + const [dueBubble, setDueBubble] = useState(null); + const bubbleReady = useMotionSettled(dueBubble !== null); const svgRef = useRef(null); const prev = useRef({ count: v.moveCount, inCheck: v.inCheck, bikjang: v.bikjang, phase: v.phase }); @@ -245,8 +248,9 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps { const p = prev.current; - const show = (text: string, color: string) => setBubble({ text, color, id: Date.now() }); - playJanggi(janggiCues(p, v), landSec * 1000); + const show = (text: string, color: string) => setDueBubble({ text, color, id: Date.now() }); + // The slide plays at the game speed, so the landing sounds wait the scaled time. + playJanggi(janggiCues(p, v), fxMs(landSec * 1000)); if (v.moveCount > p.count) { const m = v.moves[v.moves.length - 1]!; if (m.kind === 'move') { @@ -269,6 +273,12 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps { + if (!bubbleReady || !dueBubble) return; + setBubble(dueBubble); + setDueBubble(null); + }, [bubbleReady]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { if (!bubble) return; const t = setTimeout(() => setBubble(null), fxMs(1600)); @@ -361,6 +371,9 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps m.to === hover) ? hover : null)) : null; const vias = new Set(); for (const t of targets) if (t.via !== null && (ghostTo === null || t.to === ghostTo)) vias.add(t.via); + // The 장군 / 빅장 notes under the board show once the move that caused them has landed. + const checkShown = useAfterMotionValue(v.inCheck); + const bikjangShown = useAfterMotionValue(v.bikjang?.calledBy ?? null); const kingInCheck = v.inCheck ? v.board.findIndex((p) => p?.kind === 'king' && p.side === v.inCheck) : -1; const last = v.lastMove; const pad = 0.95; @@ -531,18 +544,18 @@ function JanggiBoard({ view: v, act, pending, tapConfirm }: BoardProps
    - {v.phase === 'playing' && v.inCheck && ( + {v.phase === 'playing' && checkShown && (
    - {v.inCheck === v.mySide ? '장군이에요! 궁을 지켜야 해요.' : `${SIDE_KO[v.inCheck]} 장군!`} + {checkShown === v.mySide ? '장군이에요! 궁을 지켜야 해요.' : `${SIDE_KO[checkShown]} 장군!`}
    )} - {v.phase === 'playing' && v.bikjang && ( + {v.phase === 'playing' && bikjangShown && (
    - {v.bikjang.calledBy === v.mySide + {bikjangShown === v.mySide ? '빅장을 불렀어요. 상대가 막지 못하면 점수로 판정해요.' : v.mySide ? '빅장이에요! 궁 사이를 막거나 궁을 옆으로 옮기지 않으면 점수로 판정해요.' - : `${SIDE_KO[v.bikjang.calledBy]} 빅장!`} + : `${SIDE_KO[bikjangShown]} 빅장!`}
    )} {myTurn && v.repeatWarning && ( @@ -764,7 +777,8 @@ function JanggiSide({ view: v, me, players, act, pending, deadline }: BoardProps } function ScoreBar({ view: v }: { view: JanggiView }) { - const { cho, han } = v.scores; + // A capture changes the score once the capturing piece has landed. + const [cho, han] = useAfterMotionValue(`${v.scores.cho}|${v.scores.han}`).split('|').map(Number) as [number, number]; const pct = (cho / (cho + han)) * 100; return (
    @@ -826,7 +840,10 @@ function PlayerBar({ view: v, side, players, deadline, me }: { view: JanggiView; const id = v.players[side]; const u = players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const }; const active = (v.phase === 'playing' && v.turn === side) || (v.phase === 'setup' && v.setup.waitingFor.includes(side)); - const caps = [...v.captured[side]].sort((a, b) => VALUE[b] - VALUE[a]); + // Captured pieces and the 장군 mark appear once the move has landed. + const capsKey = useAfterMotionValue(v.captured[side].join(',')); + const inCheck = useAfterMotionValue(v.inCheck); + const caps = (capsKey ? (capsKey.split(',') as PieceKind[]) : []).sort((a, b) => VALUE[b] - VALUE[a]); return (
    @@ -842,7 +859,7 @@ function PlayerBar({ view: v, side, players, deadline, me }: { view: JanggiView;
    {SIDE_KO[side]} {side === 'cho' ? '· 선수' : '· 후수 덤 1.5'} {v.phase === 'playing' && v.turn === side ? ' · 두는 중' : ''} - {v.inCheck === side ? ' · 장군!' : ''} + {inCheck === side ? ' · 장군!' : ''}
    diff --git a/apps/web/src/games/las-vegas/index.tsx b/apps/web/src/games/las-vegas/index.tsx index 24be1dd..693bf59 100644 --- a/apps/web/src/games/las-vegas/index.tsx +++ b/apps/web/src/games/las-vegas/index.tsx @@ -8,7 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion'; const ROLL_MS = 650; const HOUSE = 'house'; @@ -309,6 +309,16 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps(null); + const bannerReady = useMotionSettled(!!bannerNext); + useEffect(() => { + if (!bannerReady || !bannerNext) return; + setBanner(bannerNext); + setBannerNext(null); + }, [bannerReady]); // eslint-disable-line react-hooks/exhaustive-deps // New roll: tumble animation + screen-reader text. useLayoutEffect(() => { @@ -387,11 +397,15 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps 0, more); const seated = !!me && v.seats.includes(me) && !v.conceded.includes(me); const got = mineAw.reduce((t, a) => t + (a.note ?? 0), 0); - setBanner({ - text: more ? `${rr.round}라운드 정산` : '최종 정산', - sub: seated ? (mineAw.length ? `+${got}점 (${mineAw.length}장)` : '이번엔 못 받았어요') : undefined, - key: v.roundResults.length, - }); + // The last one only announces the final settlement right away (the room's result window waits for it); the + // amounts are in the final table that follows. + if (more) { + setBannerNext({ + text: `${rr.round}라운드 정산`, + sub: seated ? (mineAw.length ? `+${got}점 (${mineAw.length}장)` : '이번엔 못 받았어요') : undefined, + key: v.roundResults.length, + }); + } else setBanner({ text: '최종 정산', key: v.roundResults.length }); if (more) setDealt(v.round); haptic([50, 30, 50]); } @@ -467,7 +481,9 @@ function LasVegasBoard({ view: v, me, players, act, pending }: BoardProps - + + +
    )} @@ -759,6 +775,8 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps @@ -792,17 +810,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps
    - - - {m.total !== null ? `${m.total}점` : '?'} - -
    - {m.count}장 -
    -
    + {turn && playing && }
    ); @@ -813,7 +821,7 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps 내 지폐 - {mine.count}장 · {mine.total ?? 0}점 + {myCount}장 · {myTotal}점 @@ -843,6 +851,22 @@ function LasVegasSide({ view: v, me, players, act, deadline }: BoardProps + + {total !== null ? `${total}점` : '?'} + +
    + {count}장 +
    + + ); +} + /** My bills; the ones just received fly in (my own amounts are always visible to me). */ function MyBills({ notes }: { notes: number[] }) { const sig = notes.join(','); diff --git a/apps/web/src/games/liar/index.tsx b/apps/web/src/games/liar/index.tsx index 8d041cd..e9abc4d 100644 --- a/apps/web/src/games/liar/index.tsx +++ b/apps/web/src/games/liar/index.tsx @@ -21,7 +21,7 @@ import { BotActivity } from '../../components/BotActivity'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion'; type Kind = LiarView['phase']['kind']; @@ -69,6 +69,15 @@ function josa(word: string, pair: [string, string]): string { return `${word}${c >= 0 && c < 11172 && c % 28 !== 0 ? pair[0] : pair[1]}`; } +/** + * The last event number as of the last still screen, and whether a newer announcement (vote result, accused, the + * liar's answer, the end) is still playing out: what it reveals waits until its vote rows, spotlight and banners are done. + */ +function useShownEvents(v: LiarView): { shownN: number; settling: boolean } { + const shownN = useAfterMotionValue(v.events.at(-1)?.n ?? 0); + return { shownN, settling: v.events.some((e) => e.n > shownN && e.t !== 'phase' && e.t !== 'left') }; +} + function phaseTitle(v: LiarView): string { const ph = v.phase; if (ph.kind === 'describe') return v.rounds > 1 ? `${ph.round}바퀴째 설명` : PHASE_KO.describe; @@ -296,9 +305,10 @@ function latestNews(events: PublicEvent[]): PublicEvent[] { return out; } -function News({ v, players }: { v: LiarView; players: Record }) { - const news = latestNews(v.events); - if (!news.length || v.final) return null; +function News({ v, players, shownN, finalShown }: { v: LiarView; players: Record; shownN: number; finalShown: boolean }) { + // The vote rows are the animation itself; what comes after them (accused, the answer) waits for it. + const news = latestNews(v.events).filter((e) => e.t === 'vote' || e.n <= shownN); + if (!news.length || finalShown) return null; const title = news.some((e) => e.t === 'accused') ? '투표 결과' : news.some((e) => e.t === 'vote') ? '투표 결과' : '알림'; return (
    @@ -356,7 +366,9 @@ type Pick = { ids: string[]; chosen: string | null; onPick: (id: string) => void function Players({ v, players, me, pick, pending, spot }: { v: LiarView; players: Record; me: string | null; pick: Pick; pending: boolean; spot: string | null }) { const ph = v.phase; - const accused = v.final?.accused ?? ph.liar; + // Who was accused / who is the liar shows only after the result has played out. + const accused = useAfterMotionValue(v.final?.accused ?? ph.liar ?? '') || null; + const liars = useAfterMotionValue(v.players.filter((p) => p.liar === true).map((p) => p.id).join(',')).split(','); return (

    @@ -381,7 +393,7 @@ function Players({ v, players, me, pick, pending, spot }: { v: LiarView; players {speaking && 말하는 중} {ph.kind === 'vote' && p.voted && 투표함} - {p.liar === true && 🤥 라이어} + {liars.includes(id) && 🤥 라이어} {p.left && 나감} ); @@ -389,7 +401,7 @@ function Players({ v, players, me, pick, pending, spot }: { v: LiarView; players `${i + 1}번째, ${u.nickname}${id === me ? '(나)' : ''}`, speaking ? '지금 설명하는 사람' : '', ph.kind === 'vote' && p.voted ? '투표함' : '', - p.liar === true ? '라이어' : '', + liars.includes(id) ? '라이어' : '', p.left ? '나감' : '', ] .filter(Boolean) @@ -452,12 +464,12 @@ function Descriptions({ v, players, me }: { v: LiarView; players: Record l && { from: l.k === 'chat' ? l.from : null, at: l.at }; -function ChatBox({ v, players, me, act }: { v: LiarView; players: Record; me: string | null; act: (a: unknown) => void }) { +function ChatBox({ v, players, me, act, shownN }: { v: LiarView; players: Record; me: string | null; act: (a: unknown) => void; shownN: number }) { const [text, setText] = useState(''); const { ref: listRef, pin } = useStickToBottom(); const send = (t: string) => act({ type: 'chat', text: t }); const lines: Line[] = [ - ...v.events.filter((e) => e.t !== 'phase' || e.kind === 'discussion' || e.kind === 'vote' || e.kind === 'guess').map((e) => ({ k: 'sys' as const, e, at: e.at })), + ...v.events.filter((e) => e.n <= shownN && (e.t !== 'phase' || e.kind === 'discussion' || e.kind === 'vote' || e.kind === 'guess')).map((e) => ({ k: 'sys' as const, e, at: e.at })), ...v.chat.map((m) => ({ k: 'chat' as const, text: m.text, from: m.from, key: `c${m.n}`, at: m.at })), // Stable sort: same moment keeps the event order, announcements before chat. ].sort((a, b) => a.at - b.at || (a.k === b.k ? 0 : a.k === 'sys' ? -1 : 1)); @@ -578,12 +590,15 @@ function GuessForm({ v, act, pending }: { v: LiarView; act: (a: unknown) => void ); } -function Actions({ v, players, me, act, pending }: { v: LiarView; players: Record; me: string | null; act: (a: unknown) => void; pending: boolean }) { +function Actions({ v, players, me, act, pending, settling }: { v: LiarView; players: Record; me: string | null; act: (a: unknown) => void; pending: boolean; settling: boolean }) { const my = v.my; const ph = v.phase; const n = (id: string) => `${nick(players, id)}님`; let body: ReactNode = null; - if (!my) { + if (settling) { + // The next step (guess, re-vote, the end) gives the result away: it shows once the result has played out. + body =

    결과를 공개하는 중이에요…

    ; + } else if (!my) { body =

    관전 중이에요. 주제는 {v.topicKo}이고, 제시어는 게임이 끝나면 공개돼요.

    ; } else if (ph.kind === 'ended') { body =

    게임이 끝났어요. 라이어와 제시어가 공개됐어요.

    ; @@ -666,7 +681,7 @@ function Actions({ v, players, me, act, pending }: { v: LiarView; players: Recor } return (
    -

    {ph.kind === 'ended' ? '🏁 결과' : '🎯 할 일'}

    +

    {ph.kind === 'ended' && !settling ? '🏁 결과' : '🎯 할 일'}

    {body}
    ); @@ -742,6 +757,9 @@ function useLiarFx(v: LiarView, me: string | null, players: Record[]>([]); useEffect(() => () => timers.current.forEach(clearTimeout), []); + // The result plays with timers (quiet gaps between the vote rows, spotlight and banners): results wait for it all. + const [staging, setStaging] = useState(false); + useMotionHold(staging); useEffect(() => { const p = prev.current; prev.current = v; @@ -803,6 +821,8 @@ function useLiarFx(v: LiarView, me: string | null, players: Record showBanner(e.winner === 'liar' ? '라이어 승리!' : '시민 승리!', e.winner === 'liar' ? 'red' : 'blue', liar ? `라이어는 ${nick(players, liar)}님` : undefined)); } } + setStaging(true); + later(t, () => setStaging(false)); return; } if (fresh.some((e) => e.t === 'left')) return sfx.whoosh(); @@ -836,41 +856,46 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps) const [banner, showBanner] = useBanner(); const [spot, setSpot] = useState(null); useLiarFx(v, me, players, showBanner, setSpot); + const { shownN, settling } = useShownEvents(v); + const finalShown = useMotionSettled(!!v.final && !settling); - const pick: Pick = my && ph.kind === 'vote' && my.voteTargets.length ? { ids: my.voteTargets, chosen: my.vote, onPick: (id) => act({ type: 'vote', target: id }) } : null; - const hot = ph.kind === 'guess' || (ph.kind === 'describe' && !!my?.canDescribe); - const sub = + const pick: Pick = !settling && my && ph.kind === 'vote' && my.voteTargets.length ? { ids: my.voteTargets, chosen: my.vote, onPick: (id) => act({ type: 'vote', target: id }) } : null; + const hot = !settling && (ph.kind === 'guess' || (ph.kind === 'describe' && !!my?.canDescribe)); + const sub = useAfterMotionValue( ph.kind === 'describe' && ph.speaker ? `${nick(players, ph.speaker)}님 차례 · 주제: ${v.topicKo}` : ph.kind === 'ended' ? (v.final?.summary ?? '') - : `주제: ${v.topicKo}${v.options.foolMode ? ' · 바보 모드' : ''}`; + : `주제: ${v.topicKo}${v.options.foolMode ? ' · 바보 모드' : ''}`, + ); + // The phase title (라이어 맞히기, 게임 끝) would give the result away: it changes once the screen is still. + const title = useAfterMotionValue(phaseTitle(v)); return (
    -
    +
    🤥 라이어 게임 - - {phaseTitle(v)} + + {title} {sub} - {my && } + {my && }
    - - {v.final && } + + {finalShown && }
    - +
    - +

    @@ -885,11 +910,14 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps) // ---------------------------------------------------------------- side function LiarSide({ view: v, players }: BoardProps) { - const log = v.events.filter((e) => e.t !== 'phase'); + // Announcements join the log once the board has played them out. + const { shownN } = useShownEvents(v); + const log = v.events.filter((e) => e.t !== 'phase' && e.n <= shownN); + const title = useAfterMotionValue(phaseTitle(v)); return ( <>

    - 라이어 게임 · {phaseTitle(v)} + 라이어 게임 · {title} 주제: {v.topicKo} {optionsSummary(v.options)}
    diff --git a/apps/web/src/games/mafia/index.tsx b/apps/web/src/games/mafia/index.tsx index c416498..b67a958 100644 --- a/apps/web/src/games/mafia/index.tsx +++ b/apps/web/src/games/mafia/index.tsx @@ -6,7 +6,7 @@ * While the game runs the room chat panel and quick reactions are closed (`ownChat`), so night talk * cannot leak through the room chat; after the game the room chat opens again. */ -import { useEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'; +import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'; import type { Channel, ChatView, MafiaOptions, MafiaView, PlayerView, PrivateResult, PublicEvent, Role, Team } from '@bg/games/mafia'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar } from '../../components/ui'; @@ -19,7 +19,7 @@ import { keepFocus, useTypingSignal } from '../../lib/chat-input'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion'; // ---------------------------------------------------------------- names (original names only, docs §12) @@ -392,15 +392,18 @@ type Pick = { ids: string[]; chosen: string | null; onPick: (id: string) => void /** Tiles animating right now: who just left the game (turns over and greys out), who was spared. */ type TileFx = { dying: string[]; saved: string[] }; -function Players({ v, players, me, pick, pending, fx }: { v: MafiaView; players: Record; me: string | null; pick: Pick; pending: boolean; fx: TileFx | null }) { +function Players({ v, players, me, pick, pending, fx, hiddenDead, hideRoles }: { v: MafiaView; players: Record; me: string | null; pick: Pick; pending: boolean; fx: TileFx | null; hiddenDead: string[]; hideRoles: boolean }) { const mafiaChoice = v.my?.night?.action === 'mafiaTarget' ? v.my.night.choice : null; + // Deaths whose turn-over has not played yet still look alive (the sun is still coming up). + const aliveCount = v.aliveCount + hiddenDead.length; return ( -
    +

    - 사람들 살아 있는 사람 {v.aliveCount}명 + 사람들 살아 있는 사람 {aliveCount}명

    - {v.players.map((p) => { + {v.players.map((q) => { + const p = hiddenDead.includes(q.id) ? { ...q, alive: true, role: q.id === me || v.my?.mates.includes(q.id) ? q.role : null, team: null } : q; const u = userOf(players, p.id); const cls = `mf-tile${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}${p.id === v.phase.accused ? ' accused' : ''}${fx?.dying.includes(p.id) ? ' dying' : fx?.saved.includes(p.id) ? ' saved' : ''}`; const can = pick?.ids.includes(p.id) ?? false; @@ -411,7 +414,7 @@ function Players({ v, players, me, pick, pending, fx }: { v: MafiaView; players: {u.nickname} {p.id === me ? ' (나)' : ''} - + {!hideRoles && } {!p.alive && 탈락 · {p.diedDay}일차} {p.id === v.phase.accused && 지목됨} {mafiaChoice === p.id && !pick && 🎯 오늘 밤 대상} @@ -585,6 +588,9 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco const my = v.my; const ph = v.phase; const n = (id: string) => `${nick(players, id)}님`; + // A night's investigation result shows once the morning has come up on screen. + const resultCount = useAfterMotionValue(my?.results.length ?? 0); + const results = my ? my.results.slice(0, resultCount) : []; let body: ReactNode = null; if (!my) { body =

    관전 중이에요. 낮 채팅과 발표만 볼 수 있어요.

    ; @@ -720,11 +726,11 @@ function Actions({ v, players, me, act, pending }: { v: MafiaView; players: Reco

    {ph.kind === 'night' ? '🌙 오늘 밤' : ph.kind === 'ended' ? '🏁 결과' : '☀️ 할 일'}

    {body} {my?.idleWarning && ph.kind !== 'ended' && 오늘도 아무것도 하지 않으면 자리 비움으로 탈락해요.} - {my && my.results.length > 0 && ( + {my && results.length > 0 && ( <> {my.role === 'medium' ? '영매 결과 (나만 봐요)' : '조사 결과 (나만 봐요)'}
      - {my.results.map((r) => ( + {results.map((r) => (
    • {resultText(r, players)}
    • ))}
    @@ -792,11 +798,16 @@ type ShowBanner = (text: string, tone?: BannerTone, sub?: string) => void; * Sounds and motion for what anyone did: announcements (votes, deaths, saves, the end), choices, the done count. * Banners come one after another (a morning death, then the winning side); a new announcement cancels queued ones. */ -function useMafiaFx(v: MafiaView, players: Record, showBanner: ShowBanner, setTileFx: (fx: TileFx | null) => void): void { +function useMafiaFx(v: MafiaView, players: Record, showBanner: ShowBanner, setTileFx: (fx: TileFx | null) => void): string[] { const prev = useRef(v); const timers = useRef[]>([]); + // The banners / tile motion still to come (timers): results wait for them. Deaths whose tile has not turned over yet. + const [staging, setStaging] = useState(false); + const [hiddenDead, setHiddenDead] = useState([]); + useMotionHold(staging); useEffect(() => () => timers.current.forEach(clearTimeout), []); - useEffect(() => { + // Layout effect: a new death must not show on its tile for even one frame before its turn. + useLayoutEffect(() => { const p = prev.current; prev.current = v; if (p === v) return; @@ -828,11 +839,18 @@ function useMafiaFx(v: MafiaView, players: Record, showBanne timers.current = []; const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, fxMs(ms))) : f()); const start = isNight(p) && !isNight(v) ? 900 : 0; + setHiddenDead(dying); if (dying.length || saved.length) { - later(start, () => setTileFx({ dying, saved })); + later(start, () => { + setHiddenDead([]); + setTileFx({ dying, saved }); + }); later(start + 1200, () => setTileFx(null)); } banners.forEach(([text, tone, sub], i) => later(start + i * 1500, () => showBanner(text, tone, sub))); + const end = Math.max(dying.length || saved.length ? start + 1200 : 0, banners.length ? start + (banners.length - 1) * 1500 : 0); + setStaging(end > 0); + later(end, () => setStaging(false)); } let played = false; const play = (f: () => void) => { @@ -856,6 +874,13 @@ function useMafiaFx(v: MafiaView, players: Record, showBanne if (my && pm && (my.vote !== pm.vote || my.ballot !== pm.ballot || my.night?.choice !== pm.night?.choice)) return play(sfx.select); if (v.phase.readyCount > p.phase.readyCount && v.phase.kind === p.phase.kind) play(sfx.chip); }, [v]); + return hiddenDead; +} + +/** `v.events` up to the last one whose banners / motion have finished playing. */ +function useShownEvents(v: MafiaView): PublicEvent[] { + const shownN = useAfterMotionValue(v.events.at(-1)?.n ?? 0); + return useMemo(() => (v.events.at(-1)?.n ?? 0) <= shownN ? v.events : v.events.filter((e) => e.n <= shownN), [v.events, shownN]); } function MafiaBoard({ view: v, me, players, act, pending }: BoardProps) { @@ -880,7 +905,14 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps(null); - useMafiaFx(v, players, showBanner, setTileFx); + const hiddenDead = useMafiaFx(v, players, showBanner, setTileFx); + // Announcements (news, chat lines) and the final reveal show once the banners and the sky have played. + const shownEvents = useShownEvents(v); + const shownV = shownEvents === v.events ? v : { ...v, events: shownEvents }; + const endShown = useMotionSettled(ph.kind === 'ended'); + // My own death shows (role card, 탈락 panel) when my tile turns over, like everyone else's. + const meHidden = !!me && !!my && hiddenDead.includes(me); + const actV = meHidden ? { ...v, my: { ...my!, alive: true } } : v; // Night falls / morning comes (for everyone, whoever's button press moved the phase on). const [sky, setSky] = useState<{ kind: 'night' | 'day'; key: string } | null>(null); const wasNight = useRef(isNight(v)); @@ -907,7 +939,9 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps nick(players, id)).join(', ')}` : ph.kind === 'ended' - ? v.final?.summary + ? endShown + ? v.final?.summary + : '' : `살아 있는 사람 ${v.aliveCount}명`; return (
    @@ -923,19 +957,21 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps{sub} - {my && } + {my && }
    - - {v.final && } + + + +
    - +
    - +
    - +

    @@ -960,6 +996,7 @@ function composition(setup: MafiaView['setup']): string { } function MafiaSide({ view: v, players }: BoardProps) { + const events = useShownEvents(v); return ( <> @@ -970,11 +1007,11 @@ function MafiaSide({ view: v, players }: BoardProps) { 이번 판 직업: {composition(v.setup)} {optionsSummary(v.options)}

    - {v.events.length > 0 && ( + {events.length > 0 && (
    발표 기록
      - {[...v.events] + {[...events] .reverse() .filter((e) => e.t !== 'phase') .map((e) => ( diff --git a/apps/web/src/games/magical-athlete/index.tsx b/apps/web/src/games/magical-athlete/index.tsx index 83fc632..eba8f81 100644 --- a/apps/web/src/games/magical-athlete/index.tsx +++ b/apps/web/src/games/magical-athlete/index.tsx @@ -10,7 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; import { itemsOf, type Item } from './replay'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion'; const COLORS = ['#e5484d', '#2f7cf6', '#1f9d55', '#f2a10c', '#8e5cf0', '#0ea5a4']; @@ -692,6 +692,10 @@ function useRaceDrawing(v: MagicalAthleteView, liveStart: boolean, g: Geo) { pump(); }, [r?.no, lastN]); // eslint-disable-line react-hooks/exhaustive-deps + // The drawing replays the race step by step with timers: results (scores, the next race, 결과) wait for it. + const w = d.current; + useMotionHold(!!w.timer || w.q.length > 0 || !!w.walk || !!w.die?.rolling); + return { d: d.current, floats, confetti, banner }; } @@ -1019,7 +1023,13 @@ const STEP_TITLE: Record = { }; function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthleteView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; rolling: boolean }) { - const pr = v.prompt; + // A new choice (it can tell the roll: "다시 굴릴까요?", "4칸 가기") shows once the die and the runners have stopped; + // until then the previous one stays, greyed out. + const key = v.prompt ? `${v.prompt.owner}|${v.prompt.step}|${v.prompt.racer ?? ''}|${v.prompt.options.map((o) => o.key).join(',')}` : ''; + const settling = useAfterMotionValue(key) !== key; + const kept = useRef(v.prompt); + if (!settling) kept.current = v.prompt; + const pr = kept.current; if (v.phase !== 'race') return null; const mine = !!pr && pr.owner === me; return ( @@ -1033,7 +1043,7 @@ function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthlet

    2 ? ' many' : ''}`} role="group" aria-label={STEP_TITLE[pr.step]}> {pr.options.map((o, i) => ( - ))} @@ -1059,7 +1069,8 @@ function RacePanel({ v, me, players, act, pending, rolling }: { v: MagicalAthlet } function Legend({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record }) { - const r = v.race!; + // Positions, falls and places as of the last still screen (the board replays the race behind the view). + const r = JSON.parse(useAfterMotionValue(JSON.stringify({ cur: v.race!.cur, racers: v.race!.racers }))) as { cur: RacerId | null; racers: MaRacerView[] }; return (

    이번 경주 선수

    @@ -1155,7 +1166,9 @@ function Select({ v, me, players, act, pending }: { v: MagicalAthleteView; me: s } function Results({ v, me, players }: { v: MagicalAthleteView; me: string | null; players: Record }) { - if (!v.results.length) return null; + // A race's result row shows once its finish has been drawn. + const results = v.results.slice(0, useAfterMotionValue(v.results.length)); + if (!results.length) return null; const cell = (id: RacerId | null, rr: RaceResult) => { if (!id) return '—'; const o = rr.field.find((x) => x.id === id)!.owner; @@ -1178,7 +1191,7 @@ function Results({ v, me, players }: { v: MagicalAthleteView; me: string | null; - {v.results.map((rr) => ( + {results.map((rr) => ( {rr.no} @@ -1243,6 +1256,9 @@ function Board({ view: v, me, players, act, pending }: BoardProps(v.race?.log.at(-1)?.n ?? 0); const prevRace = useRef(v.race?.no ?? 0); const prevTurn = useRef(v.turnSeq); + // The race log lists new lines once the board has drawn them. + const [logRace, logN] = useAfterMotionValue(`${v.race?.no ?? 0}:${v.race?.log.at(-1)?.n ?? 0}`).split(':').map(Number); + const logShown = { race: logRace!, n: logN! }; // New log lines → screen-reader announcement (the board draws and sounds them). useEffect(() => { @@ -1282,22 +1298,29 @@ function Board({ view: v, me, players, act, pending }: BoardProps
    - {v.phase === 'finished' ? '게임 끝' : v.phase === 'draft' ? '선수 뽑기' : `${v.raceNo} / ${v.races} 경주`} - {r && v.phase === 'race' && {r.side === 'wild' ? '거친 판' : '순한 판'}} + {phase === 'finished' ? '게임 끝' : phase === 'draft' ? '선수 뽑기' : `${raceNo} / ${v.races} 경주`} + {r && phase === 'race' && {r.side === 'wild' ? '거친 판' : '순한 판'}} - {v.perRace === 2 ? '경주마다 선수 둘씩 · ' : ''}1등 {v.medals[Math.min(v.raceNo, v.races) - 1]!.gold}점 · 2등 {v.medals[Math.min(v.raceNo, v.races) - 1]!.silver}점 + {v.perRace === 2 ? '경주마다 선수 둘씩 · ' : ''}1등 {medal.gold}점 · 2등 {medal.silver}점
    - {v.result && } + {v.result && ready && } {v.phase === 'draft' && v.draft && } - {v.phase === 'select' && } {r && ( <> - {v.phase !== 'race' && ( + {v.phase !== 'race' && ready && (

    {r.no}번째 경주가 끝났을 때 모습이에요.

    @@ -1307,7 +1330,7 @@ function Board({ view: v, me, players, act, pending }: BoardProps

    경주 기록

      - {[...r.log].reverse().map((l) => ( + {[...r.log.filter((l) => logShown.race === r.no && l.n <= logShown.n)].reverse().map((l) => (
    • {ICON[l.kind]} {l.text}
    • @@ -1332,11 +1355,15 @@ function Side({ view: v, me, players, act, deadline, active }: BoardProps [v.scores[p]!.gold, v.scores[p]!.silver, v.scores[p]!.bonus, v.scores[p]!.total].join(',')).join('|'); + const shownScores = useAfterMotionValue(scoreKey).split('|'); return ( <>
      - {v.seats.map((p) => { - const sc = v.scores[p]!; + {v.seats.map((p, i) => { + const [gold, silver, bonus, tot] = (shownScores[i] ?? '').split(',').map(Number); + const sc = shownScores.length === v.seats.length ? { gold: gold!, silver: silver!, bonus: bonus!, total: tot! } : v.scores[p]!; const on = active.includes(p); return (
      diff --git a/apps/web/src/games/mahjong/index.tsx b/apps/web/src/games/mahjong/index.tsx index 2e4b85a..73e5760 100644 --- a/apps/web/src/games/mahjong/index.tsx +++ b/apps/web/src/games/mahjong/index.tsx @@ -9,7 +9,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; import { MAHJONG_TILE_CREDIT, Tile, tileName, tileOrder, tileShort } from './Tile'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; const WIND = ['동', '남', '서', '북']; const POS_KO = ['나', '오른쪽', '맞은편', '왼쪽']; @@ -141,8 +141,9 @@ function useSeen(v: MahjongView): Seen | null { return s.hand === handId(v) ? s : null; } -/** A number that pops when it changes (not on the first render). */ -function Bump({ value, children }: { value: number; children?: ReactNode }) { +/** A number that pops when it changes (not on the first render), once the move that changed it has played. */ +function Bump({ value: live, children }: { value: number; children?: ReactNode }) { + const value = useAfterMotionValue(live); const prev = useRef(value); const moved = useRef(false); if (prev.current !== value) { @@ -1155,7 +1156,10 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm const wide = width >= 900; const reserve = v.my ? 300 : 20; const tableWidth = wide ? Math.max(380, Math.min(width - 330, mainH > 0 && wide ? mainH - reserve : 560)) : width || 360; - const showTable = v.phase === 'playing' || (v.phase === 'handResult' && !wide); + // The hand's result (and the final ranking) shows once the 론·쯔모·유국 banner and the last tiles have finished. + const resultShown = useMotionSettled(v.phase === 'handResult' && !!v.result); + const finalShown = useMotionSettled(v.phase === 'finished'); + const showTable = v.phase === 'playing' || (v.phase === 'handResult' && (!wide || !resultShown)); return (
      @@ -1165,8 +1169,8 @@ function MahjongBoard({ view: v, me, players, act, pending, deadline, tapConfirm ))}
    0 ? mainH - 12 : undefined } : undefined}> - {v.phase === 'handResult' && v.result && } - {v.phase === 'finished' && } + {resultShown && v.phase === 'handResult' && v.result && } + {finalShown && v.phase === 'finished' && } {showTable && (
    {callout.text} : null} seen={seen} /> @@ -1217,6 +1221,8 @@ function Toggles({ v, act, pending }: { v: MahjongView; act: (a: unknown) => voi } function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProps) { + // A hand's score change is listed once its result has played on the board. + const history = v.history.slice(0, useAfterMotionValue(v.history.length)); const turnSeat = v.phase === 'playing' && v.stage !== 'claim' ? v.turn : null; return ( <> @@ -1257,11 +1263,11 @@ function MahjongSide({ view: v, me, players, deadline, act, pending }: BoardProp - {v.history.length > 0 && ( + {history.length > 0 && (
    국별 점수 변화
      - {[...v.history].reverse().map((h, i) => ( + {[...history].reverse().map((h, i) => (
    1. {h.label} {h.kind === 'agari' ? '화료' : h.kind === 'exhaustive' ? '유국' : '도중유국'} ·{' '} {v.seats.map((s) => `${nick(players, s.id)} ${signed(h.deltas[s.seat]!)}`).join(' / ')} diff --git a/apps/web/src/games/marble/index.tsx b/apps/web/src/games/marble/index.tsx index b42b907..5c7f8b4 100644 --- a/apps/web/src/games/marble/index.tsx +++ b/apps/web/src/games/marble/index.tsx @@ -10,7 +10,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { newEvents, toSegments, type Seg } from './events'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion'; type GameEvent = MarbleView['log'][number]; @@ -514,10 +514,9 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps x + 1); - } + // Always re-render at the end of the queue: the motion hold below is read from the walker while rendering. + w.cur = null; + rerender((x) => x + 1); return; } const wait = w.hold - Date.now(); @@ -626,19 +625,28 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps 0; + useMotionHold(walking); + // What the view says now shows once the board has caught up (the prompt, new owners). `v.owned` / `v.log` come + // straight from the view state, so their identity only changes with a new view. + const owned = useAfterMotionValue(v.owned); + const stepKey = [v.phase, v.current, v.lastRoll?.seq ?? 0, JSON.stringify(v.log[v.log.length - 1] ?? null)].join('|'); + const settled = useAfterMotionValue(stepKey) === stepKey; + // Newly bought land / new building: pop in once (not on the first render). - const ownSeen = useRef(new Map(v.owned.map((o) => [o.pos, o]))); + const ownSeen = useRef(new Map(owned.map((o) => [o.pos, o]))); const [fresh, setFresh] = useState>({}); useLayoutEffect(() => { const upd: Record = {}; - for (const o of v.owned) { + for (const o of owned) { const was = ownSeen.current.get(o.pos); if (!was || was.owner !== o.owner) upd[o.pos] = { claim: o.owner }; else if (o.level > was.level) upd[o.pos] = { level: o.level }; } - ownSeen.current = new Map(v.owned.map((o) => [o.pos, o])); + ownSeen.current = new Map(owned.map((o) => [o.pos, o])); if (Object.keys(upd).length) setFresh((f) => ({ ...f, ...upd })); - }, [v.owned]); + }, [owned]); const moveCell = (to: number) => { const n = (to + 40) % 40; @@ -664,9 +672,9 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps { const m = new Map(); - for (const o of v.owned) m.set(o.pos, o); + for (const o of owned) m.set(o.pos, o); return m; - }, [v.owned]); + }, [owned]); const seatOf = (id: string) => v.players.find((p) => p.id === id)?.seat ?? 0; const walk = walker.current.cur; const trail = walk && walk.seg.walk ? new Set(walk.seg.path.slice(1, walk.i + 1)) : null; @@ -786,7 +794,7 @@ function MarbleBoard({ view: v, me, players, act, pending }: BoardProps
      -
      setCard(null)} /> +
      setCard(null)} />
      {banner && (
      @@ -835,6 +843,7 @@ function Center({ act, pending, rolling, + settled, card, onCardClose, }: { @@ -844,6 +853,8 @@ function Center({ act: (a: unknown) => void; pending: boolean; rolling: boolean; + /** The dice and tokens have finished showing the latest move: the prompt and the result may show. */ + settled: boolean; card: { id: CardId; player: string; seq: number } | null; onCardClose: () => void; }) { @@ -894,8 +905,15 @@ function Center({ )}
      )} - {v.phase !== 'finished' && } - {v.phase === 'finished' && v.result && ( + {v.phase !== 'finished' && + (settled ? ( + + ) : ( +
      +

      …

      +
      + ))} + {settled && v.phase === 'finished' && v.result && (

      {v.result.summary}

      @@ -1189,7 +1207,9 @@ function SpaceSheet({ // ---------------------------------------------------------------- side panel -function PlayerCard({ p, v, me, players, deadline }: { p: MarblePlayerView; v: MarbleView; me: string | null; players: Record; deadline: number | null }) { +function PlayerCard({ p: live, v, me, players, deadline }: { p: MarblePlayerView; v: MarbleView; me: string | null; players: Record; deadline: number | null }) { + // Points, lands and 파산 / 무인도 change once the token has got there (the view's player object is stable per view). + const p = useAfterMotionValue(live); const active = v.phase !== 'finished' && ((v.phase === 'debt' && v.debt?.debtor === p.id) || (v.phase === 'tradeResponse' && v.trade?.to === p.id) || (v.phase !== 'debt' && v.phase !== 'tradeResponse' && v.current === p.id)); const prev = useRef(p.cash); const [delta, setDelta] = useState<{ n: number; k: number } | null>(null); @@ -1447,7 +1467,9 @@ function MarbleSide({ view: v, me, players, act, pending, deadline }: BoardProps const [confirm, setConfirm] = useState(false); const [trade, setTrade] = useState(false); const ref = useRef(null); - const lines = v.log.map((e) => logLine(e, players)).filter((x): x is string => !!x); + // A move is written down once the board has played it. + const log = useAfterMotionValue(v.log); + const lines = log.map((e) => logLine(e, players)).filter((x): x is string => !!x); useEffect(() => { ref.current?.scrollTo({ top: ref.current.scrollHeight }); }, [v.turnSeq]); diff --git a/apps/web/src/games/ninety-nine/index.tsx b/apps/web/src/games/ninety-nine/index.tsx index 8dda70e..8b05d7e 100644 --- a/apps/web/src/games/ninety-nine/index.tsx +++ b/apps/web/src/games/ninety-nine/index.tsx @@ -11,7 +11,7 @@ import { useSeatRows } from '../../lib/seat-rows'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow, resolvedHandSize } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; const MODE_KO: Record = { 'kr-product': '전용 카드', classic: '트럼프 카드' }; const SUIT_KO: Record = { S: '스페이드', H: '하트', D: '다이아', C: '클로버' }; @@ -68,6 +68,42 @@ function useCountUp(target: number): number { return shown; } +/** + * The table as of the last still screen: the total, the recent plays, lives / 탈락, the round and the final ranking + * change only after the card that caused them has flown to the dial (and its banners have played). + */ +function useShownTable(v: NinetyNineView) { + const total = useAfterMotionValue(v.total); + const round = useAfterMotionValue(v.round); + const recentKey = useAfterMotionValue(v.recent.map((e) => `${e.seq}-${e.p}`).join(',')); + const seatKey = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.lives}:${s.alive ? 1 : 0}`).join(',')); + const lastKey = v.log.length ? nnLogKey(v.log[v.log.length - 1]!) : ''; + const shownLastKey = useAfterMotionValue(lastKey); + const result = useMotionSettled(!!v.result) ? v.result : null; + const seatSnap = new Map( + seatKey + .split(',') + .filter(Boolean) + .map((x) => { + const [lives, alive] = x.split(':').slice(-2); + return [x.split(':').slice(0, -2).join(':'), { lives: Number(lives), alive: alive === '1' }]; + }), + ); + const recentShown = new Set(recentKey.split(',')); + const logEnd = v.log.findIndex((e) => nnLogKey(e) === shownLastKey); + return { + total, + round, + result, + /** The total has not caught up with the last play yet (the card is still in the air). */ + settling: total !== v.total, + recent: v.recent.filter((e) => recentShown.has(`${e.seq}-${e.p}`)), + seat: (x: SeatView): SeatView => ({ ...x, ...seatSnap.get(x.id) }), + log: logEnd < 0 ? v.log : v.log.slice(0, logEnd + 1), + }; +} +type ShownTable = ReturnType; + /** Green → yellow → red as the total nears 99. */ const gaugeColor = (t: number) => `hsl(${Math.max(0, 130 - (t / 99) * 130)} 78% 46%)`; @@ -251,9 +287,9 @@ function seatLabel(s: SeatView, v: NinetyNineView, players: Record; me: string | null; deadline: number | null }) { +function SeatChip({ s, v, players, me, deadline, result }: { s: SeatView; v: NinetyNineView; players: Record; me: string | null; deadline: number | null; result: NinetyNineView['result'] }) { const u = userOf(players, s.id); - const rank = v.result?.ranking.find((r) => r.player === s.id)?.rank; + const rank = result?.ranking.find((r) => r.player === s.id)?.rank; return (
    2. @@ -283,12 +319,13 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: NinetyNineV // ---------------------------------------------------------------- table -function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Record; me: string | null; deadline: number | null }) { - const shown = useCountUp(v.total); +function Table({ v, players, me, deadline, st }: { v: NinetyNineView; players: Record; me: string | null; deadline: number | null; st: ShownTable }) { + const total = st.total; + const shown = useCountUp(total); const dial = 'max(clamp(150px, 20vw, 196px), var(--nn-dial, 0px))'; const r = 44; const c = 2 * Math.PI * r; - const frac = Math.min(1, v.total / 99); + const frac = Math.min(1, total / 99); const cur = v.current; return (
      @@ -306,12 +343,12 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor 더미 {v.drawPileCount}장 - {v.livesStart > 0 && {v.round}판째} + {v.livesStart > 0 && {st.round}판째}
      -
      +
      - + {shown} @@ -322,9 +359,9 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor
      99를 넘기면 안 돼요! - {v.recent.length > 0 ? ( + {st.recent.length > 0 ? (
        - {v.recent.slice(-4).map((e) => ( + {st.recent.slice(-4).map((e) => (
      1. {nick(players, e.p)} @@ -335,7 +372,7 @@ function Table({ v, players, me, deadline }: { v: NinetyNineView; players: Recor ))}
      ) : ( - {v.round > 1 ? `${v.round}판 시작! 합계 ${v.total}` : v.total > 0 ? `시작 숫자 ${v.total} · 첫 카드를 기다려요` : '첫 카드를 기다려요'} + {st.round > 1 ? `${st.round}판 시작! 합계 ${total}` : total > 0 ? `시작 숫자 ${total} · 첫 카드를 기다려요` : '첫 카드를 기다려요'} )}
      @@ -402,11 +439,12 @@ function JokerDial({ c, total, pending, onPlay }: { c: HandCardView; total: numb ); } -function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => void; pending: boolean }) { +function MyHand({ v, act, pending, st }: { v: NinetyNineView; act: (a: unknown) => void; pending: boolean; st: ShownTable }) { const my = v.my!; const [sel, setSel] = useState(null); const [note, setNote] = useState(''); - const myTurn = my.myTurn; + // The previews (→ new total) and legality give the new total away: they show once the last card has landed. + const myTurn = my.myTurn && !st.settling; useEffect(() => { setSel(null); setNote(''); @@ -425,6 +463,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v }; const single = (c: HandCardView) => c.choices.length === 1 && !c.joker; const tap = (c: HandCardView) => { + if (st.settling) return; if (!myTurn) { setNote('지금은 내 차례가 아니에요. 카드를 누르면 낼 때 합계를 미리 볼 수 있어요.'); setSel(sel === c.id ? null : c.id); @@ -458,7 +497,8 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v }; const n = my.hand.length; const cw = `max(${n <= 3 ? 'clamp(84px, 24vw, 104px)' : n === 4 ? 'clamp(72px, 20vw, 96px)' : 'clamp(62px, 16.5vw, 90px)'}, var(--nn-cw, 0px))`; - const meSeat = v.seats.find((s) => s.id === v.me); + const meSeatNow = v.seats.find((s) => s.id === v.me); + const meSeat = meSeatNow && st.seat(meSeatNow); const legalCount = my.hand.filter((c) => c.legal).length; return (
      @@ -487,7 +527,7 @@ function MyHand({ v, act, pending }: { v: NinetyNineView; act: (a: unknown) => v onClick={() => tap(c)} > - {p.text} + {st.settling ? '…' : p.text} @@ -582,7 +622,9 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps s.id === me); const others = myIdx < 0 ? v.seats : [...v.seats.slice(myIdx + 1), ...v.seats.slice(0, myIdx)]; const opps = useSeatRows(others.length); - const meSeat = v.seats.find((s) => s.id === me); + const st = useShownTable(v); + const meSeatNow = v.seats.find((s) => s.id === me); + const meSeat = meSeatNow && st.seat(meSeatNow); const [banner, showBanner] = useBanner(); useNinetyNineFx(v, me, players, showBanner); return ( @@ -590,11 +632,11 @@ function Board({ view: v, me, players, act, pending, deadline }: BoardProps{CSS}
        {others.map((s) => ( - + ))}
      -
    - {v.my && meSeat?.alive && v.phase === 'playing' && } +
    + {v.my && meSeat?.alive && v.phase === 'playing' && } {meSeat && !meSeat.alive && v.phase === 'playing' && (
    {meSeat.left ? '게임에서 나갔어요.' : '탈락했어요. 남은 게임을 지켜봐요.'} @@ -659,8 +701,10 @@ function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record { let t = 0; + // When the last played card reaches the dial: what it caused (no card, a life, 탈락) shows after that. + let landed = 0; for (const e of fresh) { - const at = t; + const at = e.t === 'play' ? t : Math.max(t, landed); switch (e.t) { case 'play': { const from = e.p === me ? (myPlayRect ?? fxEl('nn-hand')) : seatEl(e.p); @@ -676,26 +720,32 @@ function useNinetyNineFx(v: NinetyNineView, me: string | null, players: Record showBanner('99!', 'red', `${who(e.p)} 바로 99`)); // Refill: the player takes one card from the pile (mine flies in from MyHand). if (v.options.refill && e.p !== me) flyGhost(fxEl('nn-deck'), seatEl(e.p), { delay: at + 420, ms: 380 }); + landed = at + 400; t += 160; break; } case 'noCard': - showBanner('낼 카드가 없어요!', 'red', who(e.p)); - later(at, sfx.bad); - bump(seatEl(e.p), 'shake'); - t += 200; + later(at, () => { + showBanner('낼 카드가 없어요!', 'red', who(e.p)); + sfx.bad(); + bump(seatEl(e.p), 'shake'); + }); + t = at + 200; break; case 'life': - later(at, nnSfx.heart); - bump(seatEl(e.p), 'shake'); - t += 200; + later(at, () => { + nnSfx.heart(); + bump(seatEl(e.p), 'shake'); + }); + t = at + 200; break; case 'out': - if (e.why === 'noCard') { - showBanner('탈락!', 'dark', who(e.p)); - later(at + 120, sfx.bad); - } - t += 200; + if (e.why === 'noCard') + later(at, () => { + showBanner('탈락!', 'dark', who(e.p)); + later(120, sfx.bad); + }); + t = at + 200; break; case 'round': if (e.round > 1) { @@ -760,6 +810,7 @@ function rulesLine(o: NNOptions): string { } function Side({ view: v, me, players, deadline }: BoardProps) { + const st = useShownTable(v); return ( <> @@ -767,14 +818,14 @@ function Side({ view: v, me, players, deadline }: BoardProps) {
    구십구 · {MODE_KO[v.mode]} - {v.livesStart > 0 ? ` · ${v.round}판` : ''} - {v.phase === 'finished' ? ' · 게임 끝' : ''} + {v.livesStart > 0 ? ` · ${st.round}판` : ''} + {st.result ? ' · 게임 끝' : ''} {v.current && }
    {rulesLine(v.options)}
      - {v.seats.map((s) => ( + {v.seats.map(st.seat).map((s) => (
    1. @@ -796,10 +847,10 @@ function Side({ view: v, me, players, deadline }: BoardProps) { ))}
    - {v.result && ( + {st.result && (
    최종 순위 - {v.result.ranking.map((r) => ( + {st.result.ranking.map((r) => ( {r.rank}등 {nick(players, r.player)} @@ -808,14 +859,14 @@ function Side({ view: v, me, players, deadline }: BoardProps) { ))} - {v.result.summary} + {st.result.summary}
    )} - {v.log.length > 0 && ( + {st.log.length > 0 && (
    기록
      - {[...v.log].reverse().map((e, i) => ( + {[...st.log].reverse().map((e, i) => (
    1. {logText(e, players)}
    2. diff --git a/apps/web/src/games/old-maid/index.tsx b/apps/web/src/games/old-maid/index.tsx index 7ebed0d..93348be 100644 --- a/apps/web/src/games/old-maid/index.tsx +++ b/apps/web/src/games/old-maid/index.tsx @@ -12,7 +12,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner import { fanCard, fanLayout, type FanLayout } from './fan'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxAnim, fxMs } from '../../lib/motion'; +import { fxAnim, fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion'; // Kept local (type-only import above) so the screen chunk does not pull in the rules module + zod. const JOKER = 'X1'; @@ -196,7 +196,8 @@ button.om-back[aria-pressed='true'] > .om-face { box-shadow: 0 0 0 3px #fde047, box-shadow: 0 6px 16px rgba(0,0,0,.4), inset 0 0 0 4px #1e3a8a, inset 0 0 0 6px #93c5fd; will-change: transform, opacity; } .om-ghost::after { content: ''; position: absolute; left: 50%; top: 50%; width: 34%; height: 24%; background: #3b82f6; transform: translate(-50%, -50%) rotate(45deg); border-radius: 2px; } .om-last { display: flex; align-items: center; gap: 12px; background: rgba(0,0,0,.24); border: 1px solid rgba(255,255,255,.1); border-radius: 14px; padding: 8px 14px; width: 100%; max-width: 620px; justify-content: center; } -.om-last .cards { display: flex; flex: none; padding: 2px 4px; } +.om-thief-joker { animation: om-pop .45s ease-out; } +.om-last .cards { display: flex; flex: none; padding: 2px 4px; animation: om-pop .3s ease-out; } .om-last .cards .om-card { --cw: 40px; transform-origin: 50% 100%; filter: drop-shadow(-1px 2px 2px rgba(0,0,0,.3)); } .om-last .cards .om-card:first-child:not(:last-child) { transform: rotate(-7deg); } .om-last .cards .om-card + .om-card { margin-left: -12px; transform: rotate(7deg); } @@ -235,7 +236,7 @@ button.om-back[aria-pressed='true'] > .om-face { box-shadow: 0 0 0 3px #fde047, .om-last .cards .om-card { --cw: 36px; } } @media (prefers-reduced-motion: reduce) { - .om-fan.riffle .om-face, .om-bubble, .om-hand .om-card.fresh > .om-face, .om-arrow, .om-badge.turn { animation: none; } + .om-fan.riffle .om-face, .om-bubble, .om-hand .om-card.fresh > .om-face, .om-arrow, .om-badge.turn, .om-last .cards, .om-thief-joker { animation: none; } .om-strip { transition: none; } } `; @@ -330,13 +331,14 @@ function seatLabel(v: OldMaidView, id: string, me: string | null, players: Recor return parts.join(', '); } -function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaidView; me: string | null; players: Record; deadline: number | null; bubble: string | null }) { +/** `r`: the view as of the last time the table stood still (counts, places, the thief), `v`: the live view (whose turn). */ +function Seat({ id, v, r, me, players, deadline, bubble }: { id: string; v: OldMaidView; r: OldMaidView; me: string | null; players: Record; deadline: number | null; bubble: string | null }) { const u = userOf(players, id); - const st = v.status[id]; - const thief = v.final?.thief === id; + const st = r.status[id]; + const thief = r.final?.thief === id; const cls = ['om-seat', v.turn === id ? 'turn anim-glow' : '', v.target === id ? 'target' : '', st !== 'playing' && !thief ? 'done' : '', thief ? 'thief' : ''].filter(Boolean).join(' '); return ( -
      +
      {bubble && ( {bubble} @@ -350,7 +352,7 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaid
      {v.turn === id && {v.target === me ? '내 카드 뽑는 중' : '뽑는 중'}} {v.target === id && {v.turn === me ? '내가 여기서 뽑아요' : '뽑히는 중'}} - {st === 'out' && 🎉 {v.places[id]}등} + {st === 'out' && 🎉 {r.places[id]}등} {st === 'left' && 나감} {thief && 🃏 도둑} {v.away[id] && 자리 비움} @@ -358,15 +360,15 @@ function Seat({ id, v, me, players, deadline, bubble }: { id: string; v: OldMaid
      {st === 'playing' || thief ? ( <> - + - {v.handCounts[id]}장 + {r.handCounts[id]}장 ) : ( {st === 'out' ? '다 털었어요' : '나갔어요'} )} - · 짝 {v.pairCounts[id]} + · 짝 {r.pairCounts[id]}
      ); @@ -515,7 +517,11 @@ function Fan({ v, me, players, act, pending, tapConfirm, riffle }: { v: OldMaidV } function LastDraw({ v, me, players }: { v: OldMaidView; me: string | null; players: Record }) { - const d = v.lastDraw; + // A new draw (the card drawn, the pair thrown away) is told only once its card has landed. + const shownNo = useAfterMotionValue(v.lastDraw?.no ?? 0); + const kept = useRef(v.lastDraw); + if ((v.lastDraw?.no ?? 0) === shownNo) kept.current = v.lastDraw; + const d = kept.current; if (!d) return null; const mineDraw = d.drawer === me; const text = `${drawerSubj(players, d.drawer, me)} ${whose(players, d.from, me)} ${d.index + 1}번째 카드를 뽑았어요${d.auto ? '(시간 초과)' : ''}`; @@ -524,7 +530,7 @@ function LastDraw({ v, me, players }: { v: OldMaidView; me: string | null; playe else if (mineDraw && d.card) tail = d.card === JOKER ? '앗, 조커를 뽑았어요!' : `뽑은 카드 ${cardName(d.card)} · 짝이 없어서 손에 넣었어요`; else tail = '짝이 없어서 손에 넣었어요'; return ( -
      +
      {(d.pair || (mineDraw && d.card)) && ( {d.pair ? d.pair.map((c) => ) : } @@ -559,8 +565,17 @@ function Pile({ v }: { v: OldMaidView }) { ); } -function Table(props: { v: OldMaidView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; riffle: boolean }) { +function Table(props: { v: OldMaidView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; tapConfirm: boolean; riffle: boolean; revealed: boolean }) { const { v, me, players } = props; + if (v.phase === 'finished' && !props.revealed) { + // The last card is still flying (or the thief banner is up): the thief is unmasked after that. + return ( +
      + + +
      + ); + } if (v.phase === 'finished') { const f = v.final!; return ( @@ -607,7 +622,7 @@ function Table(props: { v: OldMaidView; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) { +function MyArea({ v, r, me, players, act, pending, deadline, fresh, bubble }: { v: OldMaidView; r: OldMaidView; me: string; players: Record; act: (a: unknown) => void; pending: boolean; deadline: number | null; fresh: string | null; bubble: string | null }) { const hand = v.myHand ?? []; const st = v.status[me]; const cls = ['om-me', v.turn === me ? 'turn anim-glow' : '', v.target === me ? 'target' : ''].filter(Boolean).join(' '); @@ -668,8 +683,8 @@ function MyArea({ v, me, players, act, pending, deadline, fresh, bubble }: { v:
      )} {v.away[me] && 자리 비움} - {st === 'out' && 🎉 {v.places[me]}등} - {v.final?.thief === me && 🃏 도둑} + {r.status[me] === 'out' && 🎉 {r.places[me]}등} + {r.final?.thief === me && 🃏 도둑} {v.turn === me && }
      @@ -715,6 +730,29 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm const prev = useRef({ logCount: v.logCount, hand: v.myHand ?? [], turn: v.turn }); const [banner, showBanner] = useBanner(); useOldMaidFx(v, me, players, showBanner); + // "조커를 뽑았어요!" tells what the card is: only once it has landed in my hand. + const [note, setNote] = useState<{ text: string; buzz: number | number[] } | null>(null); + const noteReady = useMotionSettled(!!note); + useEffect(() => { + if (!noteReady || !note) return; + toast(note.text); + haptic(note.buzz); + setNote(null); + }, [noteReady]); // eslint-disable-line react-hooks/exhaustive-deps + // Places, counts and the thief change on screen once the cards have landed; the end table after the thief banner. + const shown = useAfterMotionValue(v); + const revealed = useMotionSettled(v.phase === 'finished'); + const popBubbles = (bub: Record) => { + setBubbles((b) => ({ ...b, ...bub })); + setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), fxMs(2500)); + }; + const [bubQ, setBubQ] = useState | null>(null); + const bubReady = useMotionSettled(!!bubQ); + useEffect(() => { + if (!bubReady || !bubQ) return; + popBubbles(bubQ); + setBubQ(null); + }, [bubReady]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { const p = prev.current; @@ -735,13 +773,8 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm const hand = v.myHand ?? []; const ld = v.lastDraw; if (amPlayer && ld && added.some((e) => e.t === 'draw')) { - if (ld.drawer === me && ld.card === JOKER) { - toast('앗, 조커를 뽑았어요! 다른 사람이 가져가게 섞어 보세요.'); - haptic([40, 30, 40]); - } else if (ld.from === me && p.hand.includes(JOKER) && !hand.includes(JOKER)) { - toast('조커를 넘겼어요! 😆'); - haptic(40); - } + if (ld.drawer === me && ld.card === JOKER) setNote({ text: '앗, 조커를 뽑았어요! 다른 사람이 가져가게 섞어 보세요.', buzz: [40, 30, 40] }); + else if (ld.from === me && p.hand.includes(JOKER) && !hand.includes(JOKER)) setNote({ text: '조커를 넘겼어요! 😆', buzz: 40 }); setFresh(ld.drawer === me && !ld.pair ? ld.card : null); } if (amPlayer && v.turn === me && p.turn !== me && v.phase === 'playing') { @@ -751,8 +784,9 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm } if (msgs.length) setAnnounce(msgs.join(' ')); if (Object.keys(bub).length) { - setBubbles((b) => ({ ...b, ...bub })); - setTimeout(() => setBubbles((b) => Object.fromEntries(Object.entries(b).filter(([k]) => !(k in bub)))), fxMs(2500)); + // "짝!" / "다 털었어요" once the drawn card has landed; "섞었어요" right away (it goes with the riffle). + if (added.some((e) => e.t !== 'shuffle')) setBubQ((q) => ({ ...q, ...bub })); + else popBubbles(bub); } prev.current = { logCount: v.logCount, hand, turn: v.turn }; if (shuffled) { @@ -769,11 +803,11 @@ function OldMaidBoard({ view: v, me, players, act, pending, deadline, tapConfirm
      {seats.map((p) => ( - + ))}
      -
    - {amPlayer && } +
    + {amPlayer && }

    {announce}

    @@ -791,11 +825,32 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record void) => (ms ? setTimeout(f, fxMs(ms)) : f()); + // Banners ("1등!", "도둑!") wait until the card that caused them has landed; the screen counts as moving meanwhile, + // so the room's result window opens only after the banner. + const flightEnd = useRef(0); + const bannerTimer = useRef | undefined>(undefined); + const [bannerWait, setBannerWait] = useState(false); + useMotionHold(bannerWait); + useEffect(() => () => clearTimeout(bannerTimer.current), []); + const bannerAfterFlight = (...args: Parameters) => { + clearTimeout(bannerTimer.current); + const wait = flightEnd.current - performance.now(); + if (wait <= 0) { + setBannerWait(false); + return showBanner(...args); + } + setBannerWait(true); + bannerTimer.current = setTimeout(() => { + setBannerWait(false); + showBanner(...args); + }, wait); + }; /** My seat is my own area; the hand inside it is a better spot for cards leaving / arriving. */ const spot = (p: string) => (p === me ? (fxEl('om-hand') ?? seatEl(p)) : seatEl(p)); const entries = v.log.map((e, i) => ({ e, n: v.logCount - v.log.length + i })); useNewEntries(entries, (x) => x.n, (fresh) => { let t = 0; + let end = 0; // when the last flying card lands (written ms) const ld = v.lastDraw; const pile = (pairs: [string, string][], from: Element | null, delay: number) => { for (const p of pairs) flyFrom(document.querySelector(`.om-pile [data-pair="${cssEsc(pairKey(p))}"]`), from, { delay, ms: 420, rotate: 14 }); @@ -814,6 +869,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record { if (e.auto) sfx.tick(); sfx.draw(); @@ -821,7 +877,7 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record bump(document.querySelector('.om-last .cards'), 'pop')); + end = Math.max(end, at + land + 420); t += land + 120; } else t += 160; break; @@ -831,7 +887,8 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record { prevHand.current = hand; @@ -877,11 +937,9 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record { const thief = v.final?.thief; if (now !== 'finished' || !thief) return; - showBanner('🃏 도둑!', 'dark', thief === me ? '내가 조커를 들고 있었어요' : `${nick(players, thief)}님`); - setTimeout(() => { - bump(seatEl(thief), 'shake'); - bump(fxEl('om-table')?.querySelector('.om-thief-joker'), 'pop'); - }, fxMs(200)); + bannerAfterFlight('🃏 도둑!', 'dark', thief === me ? '내가 조커를 들고 있었어요' : `${nick(players, thief)}님`); + // (The joker on the end table pops by itself when it shows, after the banner.) + setTimeout(() => bump(seatEl(thief), 'shake'), Math.max(0, flightEnd.current - performance.now()) + fxMs(200)); }); const started = useRef(false); useLayoutEffect(() => { @@ -902,7 +960,9 @@ function useOldMaidFx(v: OldMaidView, me: string | null, players: Record) { +function OldMaidSide({ view, me, players, deadline }: BoardProps) { + // The side panel (places, the thief, the log) follows the board once its cards have landed. + const v = useAfterMotionValue(view); const running = v.phase === 'playing'; const log = v.log.filter((e) => e.t !== 'shuffle').slice(-8).reverse(); return ( diff --git a/apps/web/src/games/omok/index.tsx b/apps/web/src/games/omok/index.tsx index 7732474..e591930 100644 --- a/apps/web/src/games/omok/index.tsx +++ b/apps/web/src/games/omok/index.tsx @@ -6,11 +6,11 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui'; import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { haptic, sfx } from '../../lib/feedback'; import { BOARD_MOTION_CSS, useAnimOver, useMoveDiff } from '../board-motion'; -import { bump, useBanner } from '../card-fx'; +import { bump, useBanner, type BannerTone } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useMotionSettled } from '../../lib/motion'; type Color = 'black' | 'white'; const COLOR_KO: Record = { black: '흑', white: '백' }; @@ -67,16 +67,26 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps) }, [refused]); // The game is over: "오목!" for five in a row (who won underneath), otherwise just who won. + // Shown once the last stone has set down (it waits in `endBanner` until the board is still). const prevPhase = useRef(v.phase); + const [endBanner, setEndBanner] = useState<[string, BannerTone, string | undefined] | null>(null); + const endReady = useMotionSettled(!!endBanner); useEffect(() => { const before = prevPhase.current; prevPhase.current = v.phase; if (before === v.phase || v.phase !== 'finished' || !v.result) return; const w = v.result.winner; - const tone = w && w === v.myColor ? 'gold' : v.myColor && w ? 'dark' : 'blue'; - if (v.winLine?.length) showBanner('오목!', tone, w ? `${COLOR_KO[w]} 승리` : undefined); - else showBanner(w ? `${COLOR_KO[w]} 승리` : '무승부', w ? tone : 'green', v.result.summary); + const tone: BannerTone = w && w === v.myColor ? 'gold' : v.myColor && w ? 'dark' : 'blue'; + if (v.winLine?.length) setEndBanner(['오목!', tone, w ? `${COLOR_KO[w]} 승리` : undefined]); + else setEndBanner([w ? `${COLOR_KO[w]} 승리` : '무승부', w ? tone : 'green', v.result.summary]); }, [v.phase]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { + if (!endReady || !endBanner) return; + showBanner(...endBanner); + setEndBanner(null); + }, [endReady]); // eslint-disable-line react-hooks/exhaustive-deps + // The winning five light up only after the last stone has landed. + const winShown = useMotionSettled(!!v.winLine?.length); 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. @@ -227,7 +237,7 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps) )} - {(v.winLine ?? []).map((p, k) => ( + {(winShown ? (v.winLine ?? []) : []).map((p, k) => ( ([]); + // Results (등수, 파산, 의심 결과, 판 끝) wait until the card that caused them has landed. + const [late, setLate] = useState<{ banners: Banner[]; sounds: string[] }>({ banners: [], sounds: [] }); + const lateReady = useMotionSettled(late.banners.length > 0); useLayoutEffect(() => () => timers.current.forEach((t) => clearTimeout(t)), []); + const showBanners = (banners: Banner[], next: Partial = {}) => { + setFx((f) => ({ ...f, ...next, banners: [...f.banners, ...banners].slice(-3) })); + for (const b of banners) { + const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), fxMs(1700)); + timers.current.push(t); + } + timers.current = timers.current.slice(-20); + }; + + useEffect(() => { + if (!lateReady) return; + const q = late; + setLate({ banners: [], sounds: [] }); + if (q.sounds.includes('out')) sfx.fanfare(); + if (q.sounds.includes('good')) sfx.good(); + if (q.sounds.includes('bad')) sfx.bad(); + showBanners(q.banners); + }, [lateReady]); // eslint-disable-line react-hooks/exhaustive-deps + useLayoutEffect(() => { const lastSeq = v.log.length ? v.log[v.log.length - 1]!.seq : 0; const myHand = v.my?.hand ?? []; @@ -197,6 +219,12 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject) => banners.push({ ...b, key: keyRef.current++ }); + const lateBanners: Banner[] = []; + const lateSounds: string[] = []; + const later = (b: Omit, sound?: string) => { + lateBanners.push({ ...b, key: keyRef.current++ }); + if (sound) lateSounds.push(sound); + }; const who = (p: string) => (p === me ? '내가' : `${nick(p)}님이`); const rootEl = root.current; const layerEl = layer.current; @@ -283,19 +311,16 @@ export function useOneCardFx({ view: v, me, nick }: Ctx, root: RefObject= 2) haptic([30, 30, 30]); - if (banners.length || Object.keys(next).length) { - setFx((f) => ({ ...f, ...next, banners: [...f.banners, ...banners].slice(-3) })); - for (const b of banners) { - const t = window.setTimeout(() => setFx((f) => ({ ...f, banners: f.banners.filter((x) => x.key !== b.key) })), fxMs(1700)); - timers.current.push(t); - } - } - timers.current = timers.current.slice(-20); + if (banners.length || Object.keys(next).length) showBanners(banners, next); + if (lateBanners.length) setLate((q) => ({ banners: [...q.banners, ...lateBanners], sounds: [...q.sounds, ...lateSounds] })); }, [v.log.length ? v.log[v.log.length - 1]!.seq : 0, v.round, v.my?.hand.length]); // eslint-disable-line react-hooks/exhaustive-deps return fx; diff --git a/apps/web/src/games/one-card/index.tsx b/apps/web/src/games/one-card/index.tsx index b3a7756..7533517 100644 --- a/apps/web/src/games/one-card/index.tsx +++ b/apps/web/src/games/one-card/index.tsx @@ -12,7 +12,7 @@ import { helpNow } from './help'; import { quickStart } from './quick'; import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, colorCardLabel, patternName } from './ColorCard'; import { FX_CSS, useOneCardFx, type Fx } from './fx'; -import { fxMs } from '../../lib/motion'; +import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion'; const SUITS: Suit[] = ['S', 'H', 'D', 'C']; const COLORS: Color[] = ['R', 'Y', 'G', 'B']; @@ -173,8 +173,11 @@ function seatLabel(s: SeatView, players: Record, me: string function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView; players: Record; me: string | null; deadline: number | null }) { const u = userOf(players, s.id); const place = v.result?.players.find((p) => p.player === s.id)?.rank; + // 다 냄 / 파산 and points change once the last card has landed. + const status = useAfterMotionValue(s.status); + const score = useAfterMotionValue(s.score); return ( -
  • +
  • {u.nickname} @@ -190,11 +193,11 @@ function SeatChip({ s, v, players, me, deadline }: { s: SeatView; v: OneCardView {s.oneCard === 'declared' ? '원카드!' : '1장!'} )} - {s.status === 'out' && {place ? `${place}등` : '다 냄'}} - {s.status === 'bankrupt' && 파산} + {status === 'out' && {place ? `${place}등` : '다 냄'}} + {status === 'bankrupt' && 파산} {s.status === 'left' && 나감} {s.away && 자리 비움} - {v.mode === 'uno-style' && v.options.unoTargetScore > 0 && {s.score}점} + {v.mode === 'uno-style' && v.options.unoTargetScore > 0 && {score}점}
  • ); @@ -227,6 +230,8 @@ function AttackCount({ n, uno }: { n: number; uno: boolean }) { ); return () => window.clearInterval(id); }, [n]); + // Counting up card by card (timer steps): results wait for the count. + useMotionHold(shown < n); if (n <= 0) return null; return ( @@ -807,8 +812,12 @@ function OneCardBoard({ view: v, me, players, act, pending, deadline }: BoardPro }} /> - - + + + + + + {v.my && meSeat && meSeat.status === 'playing' && v.phase !== 'roundEnd' && v.phase !== 'finished' && } {meSeat && meSeat.status !== 'playing' && v.phase !== 'finished' && v.phase !== 'roundEnd' && (
    @@ -840,6 +849,12 @@ function rulesLine(v: Pick) { const scoreMode = v.mode === 'uno-style' && v.options.unoTargetScore > 0; const waitingId = v.current; + // Seats, the 기록 and the final ranking show what happened only after it has played on the table. + const lastSeq = v.log.length ? v.log[v.log.length - 1]!.seq : 0; + const shownSeq = useAfterMotionValue(lastSeq); + const seatKey = useAfterMotionValue(v.seats.map((s) => `${s.status}:${s.score}`).join(',')); + const seatShown = seatKey.split(','); + const showResult = useAfterMotionValue(!!v.result); return ( <> @@ -854,25 +869,28 @@ function OneCardSide({ view: v, me, players, deadline }: BoardProps
    {rulesLine(v)}
      - {v.seats.map((s) => ( -
    1. + {v.seats.map((s, i) => { + const [status, score] = (seatShown[i] ?? `${s.status}:${s.score}`).split(':') as [SeatView['status'], string]; + return ( +
    2. {s.isTurn ? '▶ ' : ''} {nick(players, s.id)} {s.id === me ? ' (나)' : ''} - {s.status === 'out' ? ' · 다 냄' : s.status === 'bankrupt' ? ' · 파산' : s.status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''} + {status === 'out' ? ' · 다 냄' : status === 'bankrupt' ? ' · 파산' : status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''} - {scoreMode && {s.score}점} + {scoreMode && {score}점} {s.cards}
    3. - ))} + ); + })}
    - {v.result && ( + {showResult && v.result && (
    최종 순위 {v.result.players.map((p) => ( @@ -892,7 +910,7 @@ function OneCardSide({ view: v, me, players, deadline }: BoardProps
    기록
      - {[...v.log].reverse().map((e) => ( + {v.log.filter((e) => e.seq <= shownSeq).reverse().map((e) => (
    1. {logText(e, players)}
    2. diff --git a/apps/web/src/games/othello/index.tsx b/apps/web/src/games/othello/index.tsx index 2a84fe8..fb53657 100644 --- a/apps/web/src/games/othello/index.tsx +++ b/apps/web/src/games/othello/index.tsx @@ -6,6 +6,7 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui'; import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { haptic, sfx, tone } from '../../lib/feedback'; import { BOARD_MOTION_CSS } from '../board-motion'; +import { useAfterMotionValue, useMotionSettled } from '../../lib/motion'; import { toast } from '../../store/toast'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; @@ -74,6 +75,16 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps(null); const svgRef = useRef(null); const prevCount = useRef(v.moveCount); + // Pass notices wait until the flips of the move before them have played. + const [passMsgs, setPassMsgs] = useState([]); + const passReady = useMotionSettled(passMsgs.length > 0); + useEffect(() => { + if (!passReady) return; + for (const m of passMsgs) toast(m); + setPassMsgs([]); + }, [passReady]); // eslint-disable-line react-hooks/exhaustive-deps + // The disc counts change once the discs have finished turning over. + const [black, white] = useAfterMotionValue(`${v.discs.black},${v.discs.white}`).split(',').map(Number) as [number, number]; const legal = useMemo(() => { const m = new Map(); @@ -93,6 +104,7 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps [...q, ...passes]); setAnnounce(texts.join(' ')); const lm = v.lastMove; if (lm && added.some((m) => m.kind === 'place')) { @@ -188,7 +201,7 @@ function OthelloBoard({ view: v, act, pending, tapConfirm }: BoardProps
      -
      - ● {v.discs.black} +
      + ● {black}
      - {v.discs.white} ○ + {white} ○
      ; } - const score = v.result ? v.result.displayScore[color] : v.discs[color]; + // Shown once the discs of the last move have turned over. + const score = useAfterMotionValue(v.result ? v.result.displayScore[color] : v.discs[color]); return (
      diff --git a/apps/web/src/games/poker/index.tsx b/apps/web/src/games/poker/index.tsx index 98bed51..99c1f7f 100644 --- a/apps/web/src/games/poker/index.tsx +++ b/apps/web/src/games/poker/index.tsx @@ -12,7 +12,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxAnim, fxMs } from '../../lib/motion'; +import { AfterMotion, fxAnim, fxMs, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; const MODE_KO: Record = { holdem: '텍사스 홀덤', @@ -123,8 +123,8 @@ function seatBadges(seat: SeatView, v: PokerView): [string, string][] { return b; } -function SeatCards({ seat, v, me, k }: { seat: SeatView; v: PokerView; me: string | null; k: number }) { - const sd = v.showdown?.find((e) => e.id === seat.id); +function SeatCards({ seat, v, me, k, endShown }: { seat: SeatView; v: PokerView; me: string | null; k: number; endShown: boolean }) { + const sd = endShown ? v.showdown?.find((e) => e.id === seat.id) : undefined; const cards: { c: ViewCard; key: string; title?: string }[] = []; if (seat.forehead !== undefined) cards.push({ c: seat.forehead, key: 'f', title: seat.forehead ? undefined : seat.id === me ? '내 이마 카드(나만 못 봐요)' : '이마 카드' }); // Hidden cards arrive as null; at showdown the view already reveals them. @@ -149,13 +149,16 @@ function SeatCards({ seat, v, me, k }: { seat: SeatView; v: PokerView; me: strin ); } -function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView; v: PokerView; players: Record; me: string | null; deadline: number | null; x: number; y: number; k: number }) { +function SeatBox({ seat, v, players, me, deadline, x, y, k, endShown }: { seat: SeatView; v: PokerView; players: Record; me: string | null; deadline: number | null; x: number; y: number; k: number; endShown: boolean }) { const u = userOf(players, seat.id); + // Chips change once the flying chips have landed. + const stack = useAfterMotionValue(seat.stack); const badges = seatBadges(seat, v); const waiting = v.waiting.includes(seat.id) && v.handPhase !== 'handEnd'; const out = seat.status === 'eliminated' || seat.folded || (!seat.inHand && v.handPhase !== null); - const won = v.handPhase === 'handEnd' && v.winners.includes(seat.id); - const sd = v.showdown?.find((e) => e.id === seat.id); + // Winner, hand names and best cards show once the cards have been turned over (endShown). + const won = endShown && v.handPhase === 'handEnd' && v.winners.includes(seat.id); + const sd = endShown ? v.showdown?.find((e) => e.id === seat.id) : undefined; const marks: [string, string, string][] = []; if (seat.dealer) marks.push(['D', '#facc15', '딜러']); if (seat.sb) marks.push(['SB', '#93c5fd', '스몰 블라인드']); @@ -166,7 +169,7 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView; className={`pk-seat${waiting ? ' turn anim-glow' : ''}${seat.id === me ? ' me' : ''}${won ? ' win' : ''}${out ? ' out' : ''}`} style={{ '--x': `${x}%`, '--y': `${y}%` } as React.CSSProperties} data-fx-seat={seat.id} - aria-label={`${u.nickname} ${formatChips(seat.stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`} + aria-label={`${u.nickname} ${formatChips(stack)}${marks.length ? `, ${marks.map((m) => m[2]).join(', ')}` : ''}${badges.length ? `, ${badges.map((b) => b[0]).join(', ')}` : ''}`} >
      @@ -182,7 +185,7 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView; {waiting && }
      - + {seat.roundBet > 0 && +{seat.roundBet.toLocaleString('ko-KR')}}
      {seat.lastAction && !seat.folded && {seat.lastAction}} @@ -196,8 +199,8 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView; ))}
      )} - - {!sd && v.foldShown?.id === seat.id && {v.foldShown.handName}} + + {!sd && endShown && v.foldShown?.id === seat.id && {v.foldShown.handName}} {sd && ( {sd.handName} @@ -211,6 +214,8 @@ function SeatBox({ seat, v, players, me, deadline, x, y, k }: { seat: SeatView; function CenterInfo({ v, players, k }: { v: PokerView; players: Record; k: number }) { const limit = v.options.endCondition === 'hands' ? `/${v.options.handLimit}` : ''; const penalty = v.penalties.reduce((a, p) => a + p.amount, 0); + // The pot changes once the chips have flown in (or out to the winner). + const pot = useAfterMotionValue(v.pot); return (
      {v.streetName &&
      {v.streetName}
      } @@ -221,7 +226,7 @@ function CenterInfo({ v, players, k }: { v: PokerView; players: Record모인 칩
      - {formatChips(v.pot)} + {formatChips(pot)}
      {v.pots.length > 1 && (
      @@ -258,6 +263,8 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps const showKey = `${v.handNo}-${v.handPhase}`; const [banner, showBanner] = useBanner(); usePokerFx(v, me, players, showBanner); + // The hand's outcome (winner, hand names, 이번 판 결과, 다음 판으로) waits until the showdown flips and chips are done. + const endShown = useMotionSettled(v.handPhase === 'handEnd'); // PC: seats, cards and the pot grow with the table (1 at the old 890×600 table, up to 1.6×). const wide = useWide(); const tableRef = useRef(null); @@ -287,10 +294,10 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps }, [mine, v.toAct]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { - if (v.handPhase !== 'handEnd') return; + if (!endShown || v.handPhase !== 'handEnd') return; setAnnounce(resultLine(v, players)); if (me && v.winners.includes(me)) sounds.win(); - }, [showKey]); // eslint-disable-line react-hooks/exhaustive-deps + }, [showKey, endShown]); // eslint-disable-line react-hooks/exhaustive-deps return ( @@ -311,11 +318,11 @@ function PokerBoard({ view: v, me, players, act, pending, deadline }: BoardProps const sn = Math.sin(ang); const cx = wide ? Math.sign(c) * Math.abs(c) ** 0.7 : c; const sy = wide ? Math.sign(sn) * Math.abs(sn) ** 0.7 : sn; - return ; + return ; })}
      - +

      {announce}

      @@ -663,9 +670,11 @@ interface AreaProps { pending: boolean; } -function MyArea({ v, me, players, act, pending }: AreaProps) { +function MyArea({ v, me, players, act, pending, endShown }: AreaProps & { endShown: boolean }) { const seat = v.seats.find((s) => s.id === me); - if (!me || !seat) return v.handPhase === 'handEnd' ? : null; + // My hand's name changes once the new card has flown in. + const [handName, lowName] = useAfterMotionValue(`${v.my.handName ?? ''}\n${v.my.lowName ?? ''}`).split('\n'); + if (!me || !seat) return v.handPhase === 'handEnd' && endShown ? : null; const m = v.my; return (
      @@ -678,10 +687,10 @@ function MyArea({ v, me, players, act, pending }: AreaProps) { ) : ( )} - {(m.handName || m.lowName) && ( + {(handName || lowName) && (
      - 지금: {m.handName} - {m.lowName && 로우 {m.lowName}} + 지금: {handName} + {lowName && 로우 {lowName}}
      )} {seat.folded &&

      이번 판은 포기했어요. 내 카드는 나만 볼 수 있어요.

      } @@ -702,13 +711,13 @@ function MyArea({ v, me, players, act, pending }: AreaProps) {

      )} {seat.inHand && v.handPhase === 'betting' && !seat.folded && !seat.allIn && } - {v.handPhase === 'handEnd' && } - {m.canReady && ( + {v.handPhase === 'handEnd' && endShown && } + {m.canReady && endShown && ( )} - {v.handPhase === 'handEnd' && seat.inHand && seat.ready && seat.status !== 'left' &&

      다른 사람을 기다리는 중…

      } + {v.handPhase === 'handEnd' && endShown && seat.inHand && seat.ready && seat.status !== 'left' &&

      다른 사람을 기다리는 중…

      }
      ); } @@ -1049,7 +1058,11 @@ function HandRanks({ mode, o }: { mode: PokerMode; o: Pick) { const [confirmQuit, setConfirmQuit] = useState(false); - const ranked = [...v.seats].sort((a, b) => b.stack - a.stack); + // Chip counts change once the chips have landed on the table. + const shownStacks = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.stack}`).join(',')); + const stackOf = new Map(shownStacks.split(',').map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))] as const)); + const stack = (s: SeatView) => stackOf.get(s.id) ?? s.stack; + const ranked = [...v.seats].sort((a, b) => stack(b) - stack(a)); const scoreBy = v.options.endCondition === 'hands' || v.handsPlayed >= 300; return ( <> @@ -1074,31 +1087,33 @@ function PokerSide({ view: v, me, players, act, pending, deadline }: BoardProps< {s.rebuys > 0 ? ` · 리바이 ${s.rebuys}` : ''} {s.status === 'eliminated' ? ' · 탈락' : s.status === 'left' ? ' · 나감' : s.away ? ' · 자리 비움' : ''} - + ))}
    {v.result && ( -
    - 최종 순위 - {v.result.ranking.map((g, i) => { - const sc = v.result!.scores[g[0]!] ?? 0; - return ( - - {v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')} - {scoreBy ? ` (${sc < 0 ? '-' : ''}${Math.abs(sc).toLocaleString('ko-KR')} 칩)` : ''} + +
    + 최종 순위 + {v.result.ranking.map((g, i) => { + const sc = v.result!.scores[g[0]!] ?? 0; + return ( + + {v.result!.ranking.slice(0, i).reduce((a, x) => a + x.length, 1)}위 {g.map((id) => nick(players, id)).join(', ')} + {scoreBy ? ` (${sc < 0 ? '-' : ''}${Math.abs(sc).toLocaleString('ko-KR')} 칩)` : ''} + + ); + })} + {scoreBy && 점수 = 마지막 칩 − 시작 칩 × 리바이 횟수} + {v.stats.bestHand && ( + + 최고 족보: {nick(players, v.stats.bestHand.playerId)} · {v.stats.bestHand.handName} ({v.stats.bestHand.handNo}판) - ); - })} - {scoreBy && 점수 = 마지막 칩 − 시작 칩 × 리바이 횟수} - {v.stats.bestHand && ( - - 최고 족보: {nick(players, v.stats.bestHand.playerId)} · {v.stats.bestHand.handName} ({v.stats.bestHand.handNo}판) - - )} - {v.stats.biggestPot && 가장 큰 판: {formatChips(v.stats.biggestPot.amount)} ({v.stats.biggestPot.handNo}판)} -
    + )} + {v.stats.biggestPot && 가장 큰 판: {formatChips(v.stats.biggestPot.amount)} ({v.stats.biggestPot.handNo}판)} +
    + )}
    족보 @@ -1128,20 +1143,22 @@ function PokerSide({ view: v, me, players, act, pending, deadline }: BoardProps<
    )} {v.my.canRebuy && !confirmQuit && ( - {}} label="칩 다시 받기"> -

    칩을 모두 잃었어요

    -

    - 놀이용 칩 {formatChips(v.options.startingChips)}을 다시 받고 계속할 수 있어요{v.my.rebuysLeft !== null ? ` (남은 횟수 ${v.my.rebuysLeft}번)` : ''}. 점수에서는 다시 받은 만큼 빠져요. -

    -
    - - -
    -
    + + {}} label="칩 다시 받기"> +

    칩을 모두 잃었어요

    +

    + 놀이용 칩 {formatChips(v.options.startingChips)}을 다시 받고 계속할 수 있어요{v.my.rebuysLeft !== null ? ` (남은 횟수 ${v.my.rebuysLeft}번)` : ''}. 점수에서는 다시 받은 만큼 빠져요. +

    +
    + + +
    +
    +
    )} {confirmQuit && v.my.canRebuy && ( !v.walls.some((x) => wallKey(x) === wallKey(w))) : []; + // Who has reached their goal, as shown: the winner's ring only once the pawn has landed on the goal row. + const arrived = useAfterMotionValue(v.seats.filter((x) => x.status === 'finished').map((x) => x.seat).join('')); const legalCells = useMemo(() => { const m = new Set(); @@ -562,7 +565,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp return ( {turn && } - {x.status === 'finished' && } + {x.status === 'finished' && arrived.includes(x.seat) && } @@ -645,7 +648,7 @@ function QuoridorBoard({ view: v, players, act, pending, tapConfirm }: BoardProp )} {me && v.phase === 'playing' && !(myTurn && mode === 'wall') && (

    - {me.status === 'playing' + {me.status === 'playing' || (me.status === 'finished' && !arrived.includes(me.seat)) ? `내 말은 ${COLOR_KO[me.seat]}(${SEAT_KO[me.seat]})이에요. ${myGoal} 줄(${COLOR_KO[me.seat]} 띠)에 먼저 닿으면 이겨요.` : me.status === 'finished' ? '목표에 도착했어요! 남은 사람들의 순위가 정해질 때까지 지켜봐요.' @@ -691,7 +694,7 @@ function PlayerRow({ v, x, players, deadline, me }: { v: QuoridorView; x: Quorid } else if (active && tc.kind === 'perMove') { clock = ; } - const state = + const stateNow = x.status === 'finished' ? `${x.finishOrder}등 도착` : x.status === 'resigned' @@ -699,6 +702,8 @@ function PlayerRow({ v, x, players, deadline, me }: { v: QuoridorView; x: Quorid : x.status === 'timedOut' ? '시간패' : `남은 길 ${x.distance}칸${x.autoMoveStreak > 0 ? ` · 자리 비움 ${x.autoMoveStreak}번` : ''}`; + // "1등 도착" and the path length change once the move has played on the board. + const state = useAfterMotionValue(stateNow); return (

    , id: string) => players[id]?.nickname ?? '알 수 없음'; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; @@ -351,8 +351,11 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr const movedFrom = useRef | null>(null); /** Who had the turn on the previous render: tiles that newly show up on the table come from that seat. */ const prevCurrent = useRef(v.current); - const winTimer = useRef | undefined>(undefined); - useEffect(() => () => clearTimeout(winTimer.current), []); + // The round / match end banners are staged with timers (after the last tiles have landed): results wait for them. + const endTimers = useRef[]>([]); + const [ending, setEnding] = useState(false); + useMotionHold(ending); + useEffect(() => () => endTimers.current.forEach(clearTimeout), []); const snap = useRef<{ log: string; gameNo: number; phase: string; turnNo: number; edits: number; melded: Record; table: Set } | null>(null); const boxRef = useRef(null); const boardRef = useRef(null); @@ -485,23 +488,42 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr // Somebody else is moving tiles around in their turn. snd.shuffleQuiet(); } + const endSteps: (() => void)[] = []; // The round is over: "루미큐브!" when somebody emptied the rack (the match result sound itself is played by the room page). if (prev.phase === 'playing' && v.phase !== 'playing' && v.round) { const w = v.round.winners; const who = w.includes(me ?? '') ? '내가' : `${w.map((p) => nick(players, p)).join(', ')}님이`; - if (v.round.endReason === 'rackEmpty') { - showBanner('루미큐브!', 'gold', `${who} 타일을 다 냈어요`); - for (const p of w) bump(seatEl(p)); - if (v.phase === 'roundEnd') sfx.fanfare(); - } else if (v.round.endReason === 'stalemate') showBanner('판 끝', 'dark', '더 낼 수 있는 사람이 없어요'); + const roundEnd = v.phase === 'roundEnd'; + if (v.round.endReason === 'rackEmpty') + endSteps.push(() => { + showBanner('루미큐브!', 'gold', `${who} 타일을 다 냈어요`); + for (const p of w) bump(seatEl(p)); + if (roundEnd) sfx.fanfare(); + }); + else if (v.round.endReason === 'stalemate') endSteps.push(() => showBanner('판 끝', 'dark', '더 낼 수 있는 사람이 없어요')); } // The match is over: who won (after the round banner, if there was one). if (prev.phase !== 'finished' && v.phase === 'finished' && v.result?.reason === 'normal') { const top = v.result.ranking[0] ?? []; const iWon = top.includes(me ?? ''); const text = iWon ? '승리!' : top.length ? `${top.map((p) => nick(players, p)).join(', ')}님 승리` : '게임 끝'; - clearTimeout(winTimer.current); - winTimer.current = setTimeout(() => showBanner(text, iWon ? 'gold' : 'blue', v.match.total > 1 ? `${v.match.total}판 합계` : undefined), prev.phase === 'playing' ? fxMs(1500) : 0); + const sub = v.match.total > 1 ? `${v.match.total}판 합계` : undefined; + endSteps.push(() => showBanner(text, iWon ? 'gold' : 'blue', sub)); + } + if (endSteps.length) { + // The last tiles put down (new on the screen: they fly in from the seat, see below) land first, then the banners + // one by one. `prevCells` (declared below) still holds the previous render's board here. + const before = prevCells.current; + const landed = before ? cells.filter((x) => !before.has(x.id)).length : 0; + const lead = prev.phase === 'playing' && landed ? fxMs(380 + Math.min(landed, 20) * 60) : 0; + endTimers.current.forEach(clearTimeout); + setEnding(true); + endTimers.current = endSteps.map((f, i) => + setTimeout(() => { + f(); + if (i === endSteps.length - 1) setEnding(false); + }, lead + i * fxMs(1500)), + ); } }, [v]); // eslint-disable-line react-hooks/exhaustive-deps @@ -1004,7 +1026,9 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr )} - {v.phase !== 'playing' && v.round && } + + + {my && v.phase === 'playing' && (
    @@ -1210,14 +1234,24 @@ function logText(e: LogEntry, players: Record, me: string | // ---------------------------------------------------------------- side function RummikubSide({ view: v, me, players }: BoardProps) { - const order = [...v.seats].sort((a, b) => b.wins - a.wins || b.total - a.total); + // Wins / points (and 게임 끝) change when a round ends: they show once the board has played the end of the round. + const scoreKey = useAfterMotionValue(`${v.phase === 'finished' ? 'f' : ''}|${v.seats.map((s) => `${s.id}:${s.wins}:${s.total}`).join(',')}`); + const [shownEnd, shownScores] = scoreKey.split('|') as [string, string]; + const score = new Map( + shownScores.split(',').map((x) => { + const [id, w, t] = x.split(':'); + return [id!, { wins: Number(w), total: Number(t) }]; + }), + ); + const sc = (s: RummikubView['seats'][number]) => score.get(s.id) ?? { wins: s.wins, total: s.total }; + const order = [...v.seats].sort((a, b) => sc(b).wins - sc(a).wins || sc(b).total - sc(a).total); const lastRound = v.opening.length ? Math.max(...v.opening.map((o) => o.round)) : 0; return ( <>
    - {v.phase === 'finished' ? '게임 끝' : v.match.total > 1 ? `${v.match.gameNo}판 / ${v.match.total}판` : '루미큐브'} + {shownEnd ? '게임 끝' : v.match.total > 1 ? `${v.match.gameNo}판 / ${v.match.total}판` : '루미큐브'} 남은 타일 {v.poolCount}장
      @@ -1231,8 +1265,8 @@ function RummikubSide({ view: v, me, players }: BoardProps) { {s.tiles}장 {v.match.total > 1 && ( - {s.wins}승 · {s.total > 0 ? '+' : ''} - {s.total}점 + {sc(s).wins}승 · {sc(s).total > 0 ? '+' : ''} + {sc(s).total}점 )} diff --git a/apps/web/src/games/seotda/board.tsx b/apps/web/src/games/seotda/board.tsx index 67eb035..e21dca7 100644 --- a/apps/web/src/games/seotda/board.tsx +++ b/apps/web/src/games/seotda/board.tsx @@ -14,7 +14,7 @@ import { HWATU_RATIO, HwatuBack, HwatuCard } from '../../components/cards/HwatuC import { haptic, sfx, sounds } from '../../lib/feedback'; import { usePhone } from '../../lib/media'; import type { BoardProps } from '../types'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion'; import { JokboBoard } from './jokbo'; export const BET_KO: Record = { check: '체크', ping: '삥', call: '콜', ddadang: '따당', quarter: '쿼터', half: '하프', full: '풀', die: '다이' }; @@ -319,6 +319,10 @@ function ActBubble({ seat }: { seat: SeotdaSeatView }) { interface SeatProps { seat: SeotdaSeatView; view: SeotdaView; + /** The cards have finished turning over: 족보 seals may show. */ + revealed: boolean; + /** The payout has finished: the hand's +/- may show. */ + settled: boolean; players: Record; me: string | null; deadline: number | null; @@ -328,8 +332,10 @@ interface SeatProps { setRef: (id: string, el: HTMLElement | null) => void; } -function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef }: SeatProps) { +function Seat({ seat, view: v, revealed, settled, players, me, deadline, pos, cardW, winner, setRef }: SeatProps) { const u = userOf(players, seat.id); + // The money changes once the coins have flown (bets to the 판돈, the 판돈 to the winner). + const stack = useAfterMotionValue(seat.stack); const out = seat.status === 'eliminated' || seat.folded || (!seat.inHand && v.handPhase !== null); const tags: [string, string][] = []; if (seat.left) tags.push(['나감', '#b91c1c']); @@ -367,7 +373,7 @@ function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef
    - {formatWonShort(seat.stack)}원 + {formatWonShort(stack)}원 {seat.matchBet > 0 && ( @@ -375,8 +381,8 @@ function Seat({ seat, view: v, players, me, deadline, pos, cardW, winner, setRef )}
    - {seat.handName &&
    {seat.handName}
    } - {seat.handDelta !== null && seat.handDelta !== 0 && ( + {revealed && seat.handName &&
    {seat.handName}
    } + {settled && seat.handDelta !== null && seat.handDelta !== 0 && (
    0 ? 'plus' : 'minus'}`}>{formatWonDelta(seat.handDelta)}
    )} {tags.length > 0 && ( @@ -449,6 +455,14 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb const [banner, setBanner] = useState<{ text: string; key: number } | null>(null); const seen = useRef<{ match: string; log: number; cards: number; phase: string | null } | null>(null); const flyId = useRef(0); + const match = `${v.handNo}-${v.rematchNo}`; + // Bet coins still to fly (staged with timers): results wait for them. + const [queued, setQueued] = useState(0); + useMotionHold(queued > 0); + // The hand's result waits until the cards have turned over; `revealedAt` = the (re)match whose payout has started. + const [payout, setPayout] = useState<{ winners: Set; banner: string | null } | null>(null); + const cardsTurned = useMotionSettled(!!payout); + const [revealedAt, setRevealedAt] = useState(() => (v.handPhase === 'handEnd' ? match : null)); const center = (el: HTMLElement | null | undefined) => { const t = tableRef.current?.getBoundingClientRect(); @@ -467,7 +481,6 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb }; useEffect(() => { - const match = `${v.handNo}-${v.rematchNo}`; const cards = v.seats.reduce((a, s) => a + s.cards.length, 0); const prev = seen.current; seen.current = { match, log: v.betLog.length, cards, phase: v.handPhase }; @@ -481,8 +494,10 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb } // Bets since last time (anyone's): coins fly from the seat to the 판돈. const fresh: BetLogEntry[] = sameMatch ? v.betLog.slice(prev.log) : v.betLog; + if (fresh.length) setQueued((q) => q + fresh.length); fresh.forEach((e, i) => { setTimeout(() => { + setQueued((q) => q - 1); if (e.t === 'die') sfx.whoosh(); else if (e.amount <= 0) sfx.tick(); else { @@ -492,36 +507,41 @@ function useTableEffects(v: SeotdaView, me: string | null, tableRef: React.RefOb } }, fxMs(i * 220)); }); - // Result: reveal, payout, banner. + // Result: the cards turn over, then (once they have) the payout and the banner. if (v.handPhase === 'handEnd' && prev.phase !== 'handEnd') { if (v.showdown || v.foldWin?.shown) sfx.cardFlip(); const winners = new Set(); if (v.foldWin) winners.add(v.foldWin.winner); for (const p of v.showdown?.pots ?? []) if (p.type !== 'rematch') for (const w of p.winners) winners.add(w); - const b = bannerOf(v); - setTimeout(() => { - for (const w of winners) launch('pot', w, 5); - if (winners.size) sfx.collect(); - if (b) { - setBanner({ text: b, key: Date.now() }); - if (/땡잡이|암행어사|광땡|장땡/.test(b)) sfx.fanfare(); - else sfx.pop(); - } - if (me && winners.has(me)) { - sounds.win(); - haptic([40, 30, 80]); - } else if (me && v.showdown?.hands.some((h) => h.id === me) && !v.showdown.pots.some((p) => p.type === 'rematch' && p.winners.includes(me))) sounds.lose(); - }, fxMs(v.showdown ? 450 : 150)); + setPayout({ winners, banner: bannerOf(v) }); } }); // every render: cheap comparisons against the refs + useEffect(() => { + if (!cardsTurned || !payout) return; + const { winners, banner: b } = payout; + setPayout(null); + setRevealedAt(match); + for (const w of winners) launch('pot', w, 5); + if (winners.size) sfx.collect(); + if (b) { + setBanner({ text: b, key: Date.now() }); + if (/땡잡이|암행어사|광땡|장땡/.test(b)) sfx.fanfare(); + else sfx.pop(); + } + if (me && winners.has(me)) { + sounds.win(); + haptic([40, 30, 80]); + } else if (me && v.showdown?.hands.some((h) => h.id === me) && !v.showdown.pots.some((p) => p.type === 'rematch' && p.winners.includes(me))) sounds.lose(); + }, [cardsTurned]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { if (!banner) return undefined; const t = setTimeout(() => setBanner(null), fxMs(1700)); return () => clearTimeout(t); }, [banner]); - return { flies, banner }; + return { flies, banner, revealed: v.handPhase === 'handEnd' && revealedAt === match && !payout }; } // ---------------------------------------------------------------- bottom bar (한게임 섯다처럼: 족보 · 내 얼굴 · 내 패 · 베팅 버튼) @@ -657,6 +677,8 @@ interface DockProps { pending: boolean; deadline: number | null; winner: boolean; + revealed: boolean; + settled: boolean; setRef: SeatProps['setRef']; phone: boolean; /** My card size factor (PC: grows with the table width). */ @@ -668,7 +690,7 @@ interface DockProps { * them, then the number-key bet buttons. In 3장 섯다 the cards themselves are clicked to pick the open card / the two * cards to use, and the bet buttons make room for that step's button. */ -function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef, phone, scale }: DockProps) { +function Dock({ view: v, seat, players, act, pending, deadline, winner, revealed, settled, setRef, phone, scale }: DockProps) { const [pick, setPick] = useState([]); useEffect(() => setPick([]), [v.handNo, v.rematchNo, v.handPhase]); const [hover, setHover] = useState(null); @@ -679,7 +701,11 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef, const myKeys = (seat?.cards ?? []).filter(isCard).map((c) => c.key); if (myKeys.length && first.current?.tag !== matchTag) first.current = { tag: matchTag, keys: new Set(myKeys) }; const squeezing = (key: string) => !!first.current && first.current.tag === matchTag && !first.current.keys.has(key) && !peeked.has(key) && !seat?.handName; - const peeking = myKeys.some(squeezing); + // Cards still being dealt in: the 족보 they make shows once they have landed. + const cardKey = myKeys.join(','); + const dealing = useAfterMotionValue(cardKey) !== cardKey; + const peeking = myKeys.some(squeezing) || dealing; + const stack = useAfterMotionValue(seat?.stack ?? 0); const u = seat ? userOf(players, seat.id) : null; const cards = seat?.cards ?? []; const opening = !!seat && v.handPhase === 'open' && seat.opening === false; @@ -702,7 +728,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef, // Under my cards: the 족보 (or, with 3 cards, every pair's 족보 like 한게임; clickable while choosing). let under: ReactNode = null; - if (seat?.handName) under = {seat.handName}; + if (seat?.handName && revealed) under = {seat.handName}; else if (seat?.folded) under = 다이; else if (playing && hints && v.myCombos && !v.myChosen && !peeking) under = ( @@ -766,7 +792,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef, else if (v.handPhase === 'handEnd') actions = ( <> - + {settled ? :

    결과를 확인하는 중이에요…

    } {seat && seat.status === 'playing' && !seat.left && (
    )}
    @@ -838,7 +864,7 @@ function Dock({ view: v, seat, players, act, pending, deadline, winner, setRef, )}
    {under &&
    {under}
    } - {playing && h && hints && !seat.handName && {h.hint}} + {playing && h && hints && !(seat.handName && revealed) && {h.hint}} {seat.folded && !seat.handName && 다이했어요. 내 패는 나만 볼 수 있어요.}
    )} @@ -923,7 +949,9 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo if (el) seatEls.current.set(id, el); else seatEls.current.delete(id); }; - const { flies, banner } = useTableEffects(v, me, tableRef, seatEls, potEl); + const { flies, banner, revealed } = useTableEffects(v, me, tableRef, seatEls, potEl); + // Result panel, winners' glow and +/- wait for the payout coins and the banner. + const settled = useMotionSettled(revealed); const [announce, setAnnounce] = useState(''); const prevToAct = useRef(v.toAct); useLayoutEffect(() => { @@ -937,7 +965,7 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo prevToAct.current = v.toAct; }, [v.toAct]); // eslint-disable-line react-hooks/exhaustive-deps const winners = new Set(); - if (v.handPhase === 'handEnd') { + if (v.handPhase === 'handEnd' && settled) { if (v.foldWin) winners.add(v.foldWin.winner); for (const p of v.showdown?.pots ?? []) if (p.type !== 'rematch') for (const w of p.winners) winners.add(w); } @@ -966,6 +994,8 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo key={s.id} seat={s} view={v} + revealed={revealed} + settled={settled} players={players} me={me} deadline={deadline} @@ -996,7 +1026,7 @@ export function SeotdaBoard({ view: v, me, players, act, pending, deadline }: Bo )} - +

    {announce}

    diff --git a/apps/web/src/games/seotda/index.tsx b/apps/web/src/games/seotda/index.tsx index 7bff391..c9a73dc 100644 --- a/apps/web/src/games/seotda/index.tsx +++ b/apps/web/src/games/seotda/index.tsx @@ -8,6 +8,7 @@ import { formatWon, formatWonDelta, formatWonShort } from '@bg/games/seotda/mone import type { PublicUser } from '@bg/shared/lite'; import { Avatar, ConfirmSheet, Sheet } from '../../components/ui'; import { TurnTimer } from '../../components/TurnTimer'; +import { useAfterMotionValue, useMotionSettled } from '../../lib/motion'; import { HWATU_CREDIT } from '../../components/cards/HwatuCard'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { BET_KO, SeotdaBoard, nick, resultLine, totalMsOf, userOf } from './board'; @@ -21,7 +22,14 @@ const PLAY_MONEY_NOTICE = '여기 나오는 원과 판돈은 이 방 안에서 function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps) { const [confirmQuit, setConfirmQuit] = useState(false); - const ranked = [...v.seats].sort((a, b) => b.stack - a.stack); + // Money, 판 기록 and the popups below change only after the table has finished animating (coins, cards). + const stacks = useAfterMotionValue(v.seats.map((s) => `${s.id}:${s.stack}`).join(',')); + const stackOf = new Map(stacks.split(',').map((x) => [x.slice(0, x.lastIndexOf(':')), Number(x.slice(x.lastIndexOf(':') + 1))])); + const ranked = v.seats.map((s) => ({ ...s, stack: stackOf.get(s.id) ?? s.stack })).sort((a, b) => b.stack - a.stack); + const history = v.history.slice(0, useAfterMotionValue(v.history.length)); + const showResult = useMotionSettled(!!v.result); + const showRejoin = useMotionSettled(!!v.rejoin?.mine); + const showRebuy = useMotionSettled(!!v.rebuy?.mine); const log = v.betLog; return ( <> @@ -55,7 +63,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps ))} - {v.result && ( + {showResult && v.result && (
    최종 순위 {v.result.ranking.map((g, i) => ( @@ -80,11 +88,11 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps )} - {v.history.length > 0 && ( + {history.length > 0 && (
    판 기록
      - {[...v.history].reverse().map((r, i) => ( + {[...history].reverse().map((r, i) => (
    1. {r.handNo}판{r.rematchNo ? `(재${r.rematchNo})` : ''} @@ -97,7 +105,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
    )} - {v.rejoin?.mine && ( + {showRejoin && v.rejoin?.mine && ( {}} label="재경기 참가">

    구사 재경기에 다시 들어갈까요?

    판돈에 {formatWon(v.rejoin.cost)}을 더 내면 재경기에 참가할 수 있어요. 시간이 지나면 참가하지 않아요.

    @@ -111,7 +119,7 @@ function SeotdaSide({ view: v, me, players, act, pending, deadline }: BoardProps
    )} - {v.rebuy?.mine && !confirmQuit && ( + {showRebuy && v.rebuy?.mine && !confirmQuit && ( {}} label="시작 금액 다시 받기">

    가진 원을 모두 잃었어요

    diff --git a/apps/web/src/games/six-nimmt/index.tsx b/apps/web/src/games/six-nimmt/index.tsx index 24a12e0..186215c 100644 --- a/apps/web/src/games/six-nimmt/index.tsx +++ b/apps/web/src/games/six-nimmt/index.tsx @@ -6,7 +6,7 @@ import type { PublicUser } from '@bg/shared/lite'; import { Avatar, ConfirmSheet } from '../../components/ui'; import { TurnTimer } from '../../components/TurnTimer'; import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionHold, useMotionSettled } from '../../lib/motion'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; @@ -137,6 +137,26 @@ function usePlayback(v: SixNimmtView): Playback { return { rows: st.rows, marker: st.marker, step: st, waiting, busy: true }; } +/** + * Scores as of the last still screen: totals, this round's bulls and the round columns change only after the replay + * has shown the take that caused them. + */ +function useShownScores(v: SixNimmtView): (p: string) => { total: number; roundBulls: number; roundScores: number[] } { + const now = (p: string) => ({ total: v.players[p]!.total, roundBulls: v.players[p]!.roundBulls, roundScores: v.roundScores[p] ?? [] }); + const key = v.seats.map((p) => `${p}|${now(p).total}|${now(p).roundBulls}|${now(p).roundScores.join('.')}`).join(','); + const shown = useAfterMotionValue(key); + const map = new Map( + shown + .split(',') + .filter(Boolean) + .map((x) => { + const [id, total, roundBulls, rs] = x.split('|') as [string, string, string, string]; + return [id, { total: Number(total), roundBulls: Number(roundBulls), roundScores: rs ? rs.split('.').map(Number) : [] }]; + }), + ); + return (p) => map.get(p) ?? now(p); +} + // ---------------------------------------------------------------- rows function Rows({ v, pb, me, players, act, pending, overlay }: { v: SixNimmtView; pb: Playback; me: string | null; players: Record; act: (a: unknown) => void; pending: boolean; overlay?: ReactNode }) { @@ -223,10 +243,11 @@ function recommendRow(v: SixNimmtView): number { function Strip({ v, me, players, active, deadline }: { v: SixNimmtView; me: string | null; players: Record; active: string[]; deadline: number | null }) { const playing = v.phase !== 'finished'; + const score = useShownScores(v); return (

    {v.seats.map((p) => { - const pv = v.players[p]!; + const pv = { ...v.players[p]!, ...score(p) }; const on = playing && active.includes(p); const state = pv.left ? '나감' : pv.away ? '자리 비움' : v.phase === 'select' ? (pv.picked ? '골랐어요' : '고르는 중') : v.phase === 'choose' && v.pending?.player === p ? '줄 고르는 중' : v.phase === 'draft' && v.draft?.at === p ? '카드 가져가는 중' : ''; return ( @@ -286,7 +307,7 @@ function previewText(p: Preview | undefined): string { return `${p.row + 1}번 줄 ${p.side === 'L' ? '왼쪽' : `${p.pos}번째`}${'tie' in p && p.tie ? '(고름)' : ''}`; } -function Hand({ v, act, pending }: { v: SixNimmtView; act: (a: unknown) => void; pending: boolean }) { +function Hand({ v, act, pending, replaying }: { v: SixNimmtView; act: (a: unknown) => void; pending: boolean; replaying: boolean }) { const my = v.my!; const [pick, setPick] = useState(null); const [flip, setFlip] = useState(false); @@ -324,7 +345,8 @@ function Hand({ v, act, pending }: { v: SixNimmtView; act: (a: unknown) => void;
    {my.hand.map((h) => { const up = chosen === h.n; - const pv = flip && h.flipped ? h.flipped.preview : h.preview; + // The previews use the rows after the turn still being replayed: they show once it has played. + const pv = replaying ? undefined : flip && h.flipped ? h.flipped.preview : h.preview; return (
    {Array.from({ length: rounds }, (_, i) => ( - + ))} - {playing && } + {playing && } ))} @@ -642,11 +673,11 @@ function Side({ view: v, me, players, act }: BoardProps) { - {v.log.length > 0 && ( + {log.length > 0 && (

    기록

      - {[...v.log] + {[...log] .reverse() .slice(0, 30) .map((e) => ( diff --git a/apps/web/src/games/splendor/index.tsx b/apps/web/src/games/splendor/index.tsx index 7d8d581..020aa06 100644 --- a/apps/web/src/games/splendor/index.tsx +++ b/apps/web/src/games/splendor/index.tsx @@ -22,7 +22,7 @@ import { bump, cssEsc, flyFrom, flyGhost, fxEl, useBanner, useChange, useNewEntr import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { AfterMotion, fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion'; // Type-only imports above keep the rules module out of the bundle; the few constants live here. const COLORS: Color[] = ['W', 'U', 'G', 'R', 'K']; @@ -54,6 +54,18 @@ const nick = (players: Record, id: string) => players[id]?.n const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; const emptyTokens = (): Tokens => ({ W: 0, U: 0, G: 0, R: 0, K: 0, gold: 0 }); const sum = (t: Partial>) => TOKEN_COLORS.reduce((a, c) => a + (t[c] ?? 0), 0); + +/** Everyone's points as they were when the board last stood still: a new score shows once the card / noble has landed. */ +function useShownPoints(v: SplendorView): Record { + const key = useAfterMotionValue(v.order.map((p) => `${p}:${v.players[p]?.points ?? 0}`).join(',')); + const out: Record = {}; + for (const p of v.order) out[p] = v.players[p]?.points ?? 0; + for (const x of key ? key.split(',') : []) { + const [p, n] = x.split(':'); + if (p! in out) out[p!] = Number(n); + } + return out; +} const costText = (cost: Partial>) => TOKEN_COLORS.filter((c) => cost[c]) .map((c) => `${SHORT[c]} ${cost[c]}`) @@ -426,6 +438,7 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board const prevLog = useRef(v.log.at(-1)?.n ?? 0); const [banner, showBanner] = useBanner(); useSplendorFx(v, me, players, showBanner); + const pts = useShownPoints(v); // Reset local choices whenever the turn or phase moves on. useEffect(() => { @@ -609,12 +622,12 @@ function SplendorBoard({ view: v, me, players, act, pending, tapConfirm }: Board className={`sp-chip${v.current === p ? ` turn${v.phase !== 'finished' ? ' anim-glow' : ''}` : ''}`} data-fx-seat={p} aria-expanded={openOpp === p} - aria-label={`${nick(players, p)} ${pv.points}점, 보석 ${pv.tokenCount}개, 카드 ${pv.cards.length}장, 예약 ${pv.reservedCount}장${v.current === p ? ', 지금 차례' : ''}. 누르면 자세히 보여요`} + aria-label={`${nick(players, p)} ${pts[p]}점, 보석 ${pv.tokenCount}개, 카드 ${pv.cards.length}장, 예약 ${pv.reservedCount}장${v.current === p ? ', 지금 차례' : ''}. 누르면 자세히 보여요`} onClick={() => setOpenOpp(openOpp === p ? null : p)} > {nick(players, p)} - {pv.points}점 + {pts[p]}점 💎{pv.tokenCount} 🃏{pv.cards.length} {pv.reservedCount ? ` 📌${pv.reservedCount}` : ''} @@ -966,7 +979,22 @@ function gemSpot(p: string, c: TokenColor, me: string | null): Element | null { * previous view). Nothing on the first render (join, reload, replay jump). */ function useSplendorFx(v: SplendorView, me: string | null, players: Record, showBanner: ReturnType[1]) { - const later = (ms: number, f: () => void) => (ms ? setTimeout(f, fxMs(ms)) : f()); + // Staged steps (banners, bumps) wait in timers: results wait for them too (the gaps are not animations). + const [staged, setStaged] = useState(0); + useMotionHold(staged > 0); + const wait = (realMs: number, f: () => void) => { + setStaged((n) => n + 1); + setTimeout(() => { + setStaged((n) => n - 1); + f(); + }, realMs); + }; + const later = (ms: number, f: () => void) => (ms ? wait(fxMs(ms), f) : f()); + // When the flights started by the last view end (performance.now() ms): the game-end banner comes after them. + const flightsEnd = useRef(0); + const till = (ms: number) => { + flightsEnd.current = Math.max(flightsEnd.current, performance.now() + fxMs(ms)); + }; // Board of the previous view (slot key → card id) to know where a bought / reserved card was. const prevBoard = useRef | null>(null); // Nobles and my reserved cards disappear from the DOM with the new view: remember their rects while the DOM still @@ -990,6 +1018,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record bump(to)); spSfx.buy(at); const paid = sum(e.paid); @@ -1040,6 +1070,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record showBanner('👑 귀족 방문!', 'gold', `${NOBLE_NAME[e.nobleId] ?? '귀족'} → ${e.p === me ? '나' : `${nick(players, e.p)}님`} (+3점)`)); spSfx.noble(at2); later(at2 + 560, () => bump(seatOf(e.p, me))); @@ -1094,6 +1126,7 @@ function useSplendorFx(v: SplendorView, me: string | null, players: Record nick(players, p)).join(', ')}님 승리`) : undefined; - later(700, () => showBanner('게임 끝', 'gold', sub)); + // After the last move's flights (cards, gems, a noble) have landed. + wait(Math.max(fxMs(700), flightsEnd.current - performance.now() + fxMs(100)), () => showBanner('게임 끝', 'gold', sub)); }); } @@ -1128,11 +1162,12 @@ function MyArea({ flag: (key: string) => React.ReactNode; }) { const turn = v.current === me; + const pts = useShownPoints(v); return (
      - 나 · {pv.points}점 + 나 · {pts[me] ?? pv.points}점 / {v.options.targetPoints}점 @@ -1239,13 +1274,14 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps [...v.log].reverse(), [v.log]); + const pts = useShownPoints(v); + // 마지막 라운드 / 게임 끝 show once the move that caused them has played on the board. + const head = useAfterMotionValue(v.phase === 'finished' ? '게임 끝' : v.endTriggered ? '🏁 마지막 라운드예요' : `${v.options.targetPoints}점을 먼저 넘기면 그 라운드까지`); return ( <>
      - - {v.phase === 'finished' ? '게임 끝' : v.endTriggered ? '🏁 마지막 라운드예요' : `${v.options.targetPoints}점을 먼저 넘기면 그 라운드까지`} - + {head}
      {v.order.map((p, i) => { const pv = v.players[p]!; @@ -1266,8 +1302,8 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps
      - - {pv.points} + + {pts[p]} {turn && v.phase !== 'finished' && } @@ -1276,21 +1312,23 @@ function SplendorSide({ view: v, me, players, act, deadline }: BoardProps - {v.result && ( -
      - 최종 순위 - {v.result.ranking.map((r) => ( -
      - {r.rank}위 - {nick(players, r.player)} - - {r.points}점 · 카드 {r.cards}장{r.nobles ? ` · 귀족 ${r.nobles}` : ''} - {r.conceded ? ' · 기권' : ''} - -
      - ))} -
      - )} + + {v.result && ( +
      + 최종 순위 + {v.result.ranking.map((r) => ( +
      + {r.rank}위 + {nick(players, r.player)} + + {r.points}점 · 카드 {r.cards}장{r.nobles ? ` · 귀족 ${r.nobles}` : ''} + {r.conceded ? ' · 기권' : ''} + +
      + ))} +
      + )} +
      {log.length > 0 && (
      기록 diff --git a/apps/web/src/games/tichu/index.tsx b/apps/web/src/games/tichu/index.tsx index fa7c97d..4d45455 100644 --- a/apps/web/src/games/tichu/index.tsx +++ b/apps/web/src/games/tichu/index.tsx @@ -8,7 +8,7 @@ import { TurnTimer, useServerNow } from '../../components/TurnTimer'; import { PLAYING_CARD_CREDIT } from '../../components/cards/PlayingCard'; import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; import { bump, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries } from '../card-fx'; -import { fxAnim } from '../../lib/motion'; +import { fxAnim, useAfterMotionValue, useMotionSettled } from '../../lib/motion'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { CardFace, TCard } from './cards'; import { helpNow } from './help'; @@ -767,10 +767,13 @@ function RoundEndPanel({ v, players, me, act, pending }: { v: TichuView; players function Standings({ v, players, me }: { v: TichuView; players: Players; me: string | null }) { const target = v.mode === 'threechu' ? null : v.options.targetScore; - const max = Math.max(target ?? 1, ...v.scores.map((x) => Math.abs(x)), 1); + // New round scores show once the last trick has flown to its winner (and the 원투! banner has played). + const scoreKey = useAfterMotionValue(v.scores.join(',')); + const scores = scoreKey.split(',').length === v.scores.length ? scoreKey.split(',').map(Number) : v.scores; + const max = Math.max(target ?? 1, ...scores.map((x) => Math.abs(x)), 1); return (
      - {v.scores.map((sc, i) => { + {scores.map((sc, i) => { const owners = v.scoreOwners[i]!; const team = v.scoreOwners.length === 2; const label = team ? `${teamName(i)} ${owners.map((p) => (p === me ? '나' : short(nick(players, p)))).join('·')}` : owners[0] === me ? '나' : nick(players, owners[0]!); @@ -866,6 +869,16 @@ function Tip() { ); } +/** + * The round / game result waits until the board has stopped moving (the last trick flying to its winner, 원투!). + * Meanwhile an empty table stays in its place, so the flight still has its start point (`tc-center`). + */ +function AfterTable({ when, children }: { when: boolean; children: ReactNode }) { + const shown = useMotionSettled(when); + if (!when) return null; + return shown ? children :
      ; +} + function useTichuFx(v: TichuView, me: string | null, players: Players, showBanner: ReturnType[1]) { const seatFx = (seat: number) => seatEl(`seat-${seat}`) ?? (v.seats[seat]?.owner === me ? fxEl('tc-hand') : null); useNewEntries( @@ -968,15 +981,17 @@ function TichuBoard({ view: v, me, players, act, pending, deadline }: BoardProps {playingish && } {v.phase === 'grand' && } {v.phase === 'exchange' && } - {v.phase === 'roundEnd' && } - {v.phase === 'finished' && v.result && ( + + + +

      게임이 끝났어요

      - {v.result.summary} + {v.result?.summary} {v.lastRound && }
      - )} +
      {v.mySeat !== null && v.seats[v.mySeat] && (playingish || v.phase === 'roundEnd') && ( @@ -1037,7 +1052,9 @@ function PlayedTable({ cards }: { cards: string[] }) { } function TichuSide({ view: v, me, players, deadline }: BoardProps) { - const phaseKo = { grand: '그랜드 티츄', exchange: '카드 교환', playing: '진행 중', dragonGift: '용 트릭 주기', roundEnd: '라운드 결과', finished: '게임 끝' }[v.phase]; + // 라운드 결과 / 게임 끝 and the new history row show once the end of the round has played on the board. + const phaseKo = useAfterMotionValue({ grand: '그랜드 티츄', exchange: '카드 교환', playing: '진행 중', dragonGift: '용 트릭 주기', roundEnd: '라운드 결과', finished: '게임 끝' }[v.phase]); + const history = v.history.slice(0, useAfterMotionValue(v.history.length)); const [showLast, setShowLast] = useState(false); return ( <> @@ -1052,7 +1069,7 @@ function TichuSide({ view: v, me, players, deadline }: BoardProps) { {optionsSummary(v.options)} - {v.history.length > 0 && ( + {history.length > 0 && (
      라운드 기록
    {who(players, me, p)}{v.roundScores[p]![i] ?? ''}{score(p).roundScores[i] ?? ''}{v.players[p]!.roundBulls ? `+${v.players[p]!.roundBulls}` : ''}{score(p).roundBulls ? `+${score(p).roundBulls}` : ''} - {v.players[p]!.total} + {score(p).total}
    @@ -1067,7 +1084,7 @@ function TichuSide({ view: v, me, players, deadline }: BoardProps) { - {v.history.map((h) => ( + {history.map((h) => (
    {h.round} diff --git a/apps/web/src/games/types.ts b/apps/web/src/games/types.ts index d07152c..c52b231 100644 --- a/apps/web/src/games/types.ts +++ b/apps/web/src/games/types.ts @@ -37,6 +37,11 @@ export interface GameUI { Options: ComponentType>; optionsSummary(options: O): string; Rules: ComponentType<{ options?: O }>; + /** + * Real-time games (할리갈리, 도블, 사과 게임, 그림 맞히기): the turn status changes the moment the state does. Other games show + * a new status only after the board has finished animating the move that caused it (lib/motion `useAfterMotionValue`). + */ + liveStatus?: boolean; /** The board has its own chat channels; the room chat panel is hidden while the game runs (마피아). */ ownChat?: boolean; /** The board's chat box shows who is typing in it ("입력 중…"); the status row then shows only the computers thinking (라이어 게임). */ diff --git a/apps/web/src/games/uno/index.tsx b/apps/web/src/games/uno/index.tsx index 6980bdd..f1def0e 100644 --- a/apps/web/src/games/uno/index.tsx +++ b/apps/web/src/games/uno/index.tsx @@ -11,7 +11,7 @@ import type { BoardProps, GameUI, OptionsProps } from '../types'; import { COLOR_HEX, COLOR_INK, COLOR_KO, ColorCardArt, patternName } from '../one-card/ColorCard'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { AfterMotion, fxMs, useAfterMotionValue } from '../../lib/motion'; const COLORS: Color[] = ['R', 'Y', 'G', 'B']; @@ -193,6 +193,11 @@ function seatLabel(s: SeatView, players: Record, me: string return parts.join(', '); } +/** A score that changes only once the round's last card (and the points flying to the winner) has landed. */ +function Score({ n, className }: { n: number; className?: string }) { + return {useAfterMotionValue(n)}점; +} + function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoView; players: Record; me: string | null; deadline: number | null; next: boolean }) { const u = userOf(players, s.id); return ( @@ -215,7 +220,7 @@ function SeatChip({ s, v, players, me, deadline, next }: { s: SeatView; v: UnoVi {s.left && 나감} {s.away && 자리 비움} {!s.isTurn && next && 다음} - {v.options.scoring === 'to500' && {s.score}점} + {v.options.scoring === 'to500' && } ); @@ -705,8 +710,13 @@ function UnoBoard({ view: v, me, players, act, pending, deadline }: BoardProps - - + {/* Results show once the card that led to them has landed. */} + + + + + + {v.my && meSeat && !meSeat.left && v.phase !== 'roundEnd' && v.phase !== 'finished' && } {meSeat?.left && v.phase !== 'finished' && (
    @@ -853,7 +863,7 @@ function UnoSide({ view: v, me, players, deadline }: BoardProps) { {s.id === me ? ' (나)' : ''} {s.left ? ' · 나감' : s.away ? ' · 자리 비움' : ''} - {multi && {s.score}점} + {multi && } {s.cards} @@ -862,21 +872,23 @@ function UnoSide({ view: v, me, players, deadline }: BoardProps) { ))}
    - {v.result && ( -
    - 최종 순위 - {v.result.players.map((p) => ( - - {p.rank}등 {nick(players, p.player)} - - {' '} - · {p.left ? '나감' : multi ? `${p.points}점` : p.rank === 1 ? `${p.points}점` : `남은 카드 ${p.cardsLeft}장(${p.handPoints}점)`} + + {v.result && ( +
    + 최종 순위 + {v.result.players.map((p) => ( + + {p.rank}등 {nick(players, p.player)} + + {' '} + · {p.left ? '나감' : multi ? `${p.points}점` : p.rank === 1 ? `${p.points}점` : `남은 카드 ${p.cardsLeft}장(${p.handPoints}점)`} + - - ))} - {v.result.summary} -
    - )} + ))} + {v.result.summary} +
    + )} + {v.log.length > 0 && (
    기록 diff --git a/apps/web/src/games/yacht/index.tsx b/apps/web/src/games/yacht/index.tsx index faeeac7..196ba76 100644 --- a/apps/web/src/games/yacht/index.tsx +++ b/apps/web/src/games/yacht/index.tsx @@ -8,7 +8,7 @@ import { haptic, noise, sfx, tone } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useMotionHold } from '../../lib/motion'; // The client draws from the view only; names and hints live here so the rules module isn't bundled. const NAME: Record = { @@ -202,6 +202,8 @@ function DiceRow({ dice, size }: { dice: number[]; size?: number }) { interface RollAnim { key: number; mask: boolean[]; + /** All five the same: the 요트! flash waits until the dice have landed. */ + yacht?: { sub?: string }; } function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardProps) { @@ -225,6 +227,12 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro if (!pending) setHeld(v.held); }, [v.held, v.turnSeq, v.rollSeq, pending]); + const yachtFlash = (sub: string | undefined, key: number) => { + setFlash({ text: '요트!', sub, key }); + sfx.fanfare(); + haptic([80, 40, 80]); + }; + // Roll animation, sound, yacht flash and screen-reader text when a new roll arrives (anyone's roll). useLayoutEffect(() => { if (v.rollSeq <= prevRoll.current || !v.dice) { @@ -237,12 +245,9 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro const mask = v.rollsUsed === 1 ? [true, true, true, true, true] : v.held.map((h) => !h); const animated = !reducedMotion(); rollSound(mask.filter(Boolean).length, animated); - if (v.dice.every((d) => d === v.dice![0])) { - setFlash({ text: '요트!', sub: v.current === me ? undefined : nick(players, v.current ?? ''), key: v.rollSeq }); - sfx.fanfare(); - haptic([80, 40, 80]); - } - if (animated) setAnim({ key: v.rollSeq, mask }); + const yacht = v.dice.every((d) => d === v.dice![0]) ? { sub: v.current === me ? undefined : nick(players, v.current ?? '') } : undefined; + if (animated) setAnim({ key: v.rollSeq, mask, yacht }); + else if (yacht) yachtFlash(yacht.sub, v.rollSeq); }, [v.rollSeq]); // eslint-disable-line react-hooks/exhaustive-deps // Someone else (re)holding dice: the same knock I hear on my own taps. @@ -261,12 +266,15 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro const end = setTimeout(() => { setAnim(null); setFlick(null); + if (anim.yacht) yachtFlash(anim.yacht.sub, anim.key); }, fxMs(ROLL_MS)); return () => { clearInterval(t); clearTimeout(end); }; - }, [anim]); + }, [anim]); // eslint-disable-line react-hooks/exhaustive-deps + // The tumble is staged with timers (flicking faces): results wait for it. + useMotionHold(!!anim); useEffect(() => { if (!flash) return; @@ -382,7 +390,7 @@ function YachtBoard({ view: v, me, players, act, pending, tapConfirm }: BoardPro {myTurn && v.rollsUsed > 0 && v.rollsUsed < 3 &&

    남길 주사위를 누르면 고정돼요. 점수표의 칸을 누르면 기록해요.

    } {v.lastScore && } - +

    {announce}

    @@ -429,6 +437,7 @@ function ScoreSheet({ players, myTurn, pending, + rolling, onScore, pointer, }: { @@ -437,6 +446,8 @@ function ScoreSheet({ players: Record; myTurn: boolean; pending: boolean; + /** Dice still tumbling: the points they make are not shown (or pickable) until they land. */ + rolling: boolean; onScore: (c: Category, points: number, viaMouse: boolean) => void; pointer: React.MutableRefObject; }) { @@ -461,12 +472,12 @@ function ScoreSheet({ const prev = v.current === p ? v.preview?.[c] : undefined; if (p === me && myTurn && v.rollsUsed > 0 && prev !== undefined) { const allowed = v.allowed.includes(c); - const show = v.options.showPreview; + const show = v.options.showPreview && !rolling; return ( ); } - if (prev !== undefined && v.options.showPreview) return {prev}; + if (prev !== undefined && v.options.showPreview && !rolling) return {prev}; return null; }; diff --git a/apps/web/src/games/yut/aug-options.tsx b/apps/web/src/games/yut/aug-options.tsx index 01e68f1..0698e3d 100644 --- a/apps/web/src/games/yut/aug-options.tsx +++ b/apps/web/src/games/yut/aug-options.tsx @@ -1,6 +1,8 @@ /** 증강 윷놀이 방 설정 (docs/games/yut-augmented.md): 혼돈 모드, 고르는 라운드, 후보 수, 나오게 할 증강 목록. */ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; +import { createPortal } from 'react-dom'; import type { YutOptions } from '@bg/games/yut'; +import { Sheet } from '../../components/ui'; import { AugIcon } from './aug-icons'; import { AUGS, AUG_IDS, AUG_ROUNDS, KIND_KO, TIER_KO, selectionTier, type AugId, type AugRoundsKey, type AugTier } from '@bg/games/yut/augments'; @@ -20,10 +22,23 @@ const AUG_CSS = ` .yut-aug-cat { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 10px; border: 1px dashed var(--border); border-radius: 12px; min-width: 0; } .yut-aug-cat-head { display: flex; flex-wrap: wrap; gap: 6px 8px; align-items: center; } .yut-aug-cat-head strong { margin-right: auto; } -.yut-aug-row { display: flex; gap: 10px; align-items: flex-start; min-height: 44px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); cursor: pointer; min-width: 0; } -.yut-aug-row.off { opacity: .6; } -.yut-aug-row input { flex: none; width: 22px; height: 22px; margin: 1px 0 0; accent-color: var(--primary); } -.yut-aug-body { display: flex; flex-direction: column; gap: 2px; min-width: 0; overflow-wrap: anywhere; } +.yut-aug-row { display: flex; gap: 10px; align-items: center; min-height: 56px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); cursor: pointer; min-width: 0; } +.yut-aug-row.off { background: var(--surface-2, var(--surface)); } +.yut-aug-row.off .yut-aug-body, .yut-aug-row.off .aug-icon { opacity: .55; } +.yut-aug-body { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; overflow-wrap: anywhere; } +.yut-aug-switch { flex: none; position: relative; width: 50px; height: 30px; margin: 0; appearance: none; -webkit-appearance: none; border-radius: 999px; + background: var(--border); cursor: pointer; transition: background .15s; } +.yut-aug-switch::after { content: ''; position: absolute; top: 3px; left: 3px; width: 24px; height: 24px; border-radius: 50%; background: #fff; + box-shadow: 0 1px 3px rgba(0, 0, 0, .3); transition: transform .15s; } +.yut-aug-switch:checked { background: var(--primary); } +.yut-aug-switch:checked::after { transform: translateX(20px); } +.yut-aug-switch:focus-visible { outline: 3px solid var(--primary); outline-offset: 2px; } +.yut-aug-switch:disabled { cursor: default; } +.yut-aug-open { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: 48px; } +.sheet:has(.yut-aug-sheet) { width: min(100%, 640px); } +.yut-aug-sheet { display: flex; flex-direction: column; gap: 10px; } +.yut-aug-sheet-head { display: flex; flex-direction: column; gap: 8px; } +.yut-aug-sheet-foot { position: sticky; bottom: calc(-20px - env(safe-area-inset-bottom)); background: var(--surface); padding: 8px 0 4px; border-top: 1px solid var(--border); } .yut-aug-name { display: flex; flex-wrap: wrap; gap: 4px 6px; align-items: center; font-weight: 700; } .yut-aug-badge { border-radius: 999px; padding: 0 7px; font-size: .75rem; font-weight: 700; background: var(--primary-soft); color: var(--text); white-space: nowrap; } .yut-aug-badge.win { background: var(--warning-soft, var(--primary-soft)); } @@ -54,7 +69,10 @@ function Field({ label, hint, children }: { label: string; hint?: string; childr export function AugOptions({ value: o, onChange }: { value: YutOptions; onChange: (patch: Partial) => void }) { const [query, setQuery] = useState(''); - const [open, setOpen] = useState>({}); + const [listOpen, setListOpen] = useState(false); + // Inside the room's read-only settings view (not the host) the list can be read but not changed. + const openBtn = useRef(null); + const [readOnly, setReadOnly] = useState(false); const off = new Set(o.augOff ?? []); /** Keep `augOff` in AUG_IDS order so the value is stable. */ const setOff = (next: Set) => onChange({ augOff: AUG_IDS.filter((id) => next.has(id)) }); @@ -97,84 +115,156 @@ export function AugOptions({ value: o, onChange }: { value: YutOptions; onChange onChange({ augOffers })} /> -
    - - 나오게 할 증강 켜진 증강 {onCount}/{AUG_IDS.length} - +
    + 나오게 할 증강 + 끈 증강은 후보에 나오지 않아요. 이 사이트에서 만든 추가 증강 {CUSTOM_IDS.length}개는 처음에 꺼져 있어요. - setQuery(e.target.value)} /> -
    - - - {CUSTOM_IDS.every((id) => off.has(id)) ? ( - - ) : ( - - )} -
    {warnings.map((w) => ( ⚠ {w} ))} - {CATS.map((cat) => { - const shown = cat.ids.filter(match); - if (!shown.length) return null; - const on = cat.ids.filter((id) => !off.has(id)).length; - const showRows = !!q || !!open[cat.key]; - return ( -
    -
    - - - +
    + {listOpen && + createPortal( + setListOpen(false)}> +
    +
    +

    + 나오게 할 증강 켜짐 {onCount}/{AUG_IDS.length} +

    + {readOnly ? ( + 👑 방장만 바꿀 수 있어요. 여기서는 볼 수만 있어요. + ) : ( + 오른쪽 스위치로 켜고 꺼요. 끈 증강은 후보에 나오지 않아요. + )} + setQuery(e.target.value)} /> + {!readOnly && ( +
    + + + {CUSTOM_IDS.every((id) => off.has(id)) ? ( + + ) : ( + + )} +
    + )} + {warnings.map((w) => ( + + ⚠ {w} + + ))}
    - {showRows && shown.map((id) => { - const a = AUGS[id]; - const enabled = !off.has(id); + {CATS.map((cat) => { + const shown = cat.ids.filter(match); + if (!shown.length) return null; + const on = cat.ids.filter((id) => !off.has(id)).length; return ( - +
    +
    + + {cat.title} 켜짐 {on}/{cat.ids.length} + + {!readOnly && ( + <> + + + + )} +
    + {shown.map((id) => { + const a = AUGS[id]; + const enabled = !off.has(id); + return ( + + ); + })} +
    ); })} -
    - ); - })} - {q && CATS.every((c) => !c.ids.some(match)) && '{query.trim()}'에 맞는 증강이 없어요.} -
    + {q && CATS.every((c) => !c.ids.some(match)) && '{query.trim()}'에 맞는 증강이 없어요.} +
    + +
    +
    + , + document.body, + )} ); } + +/** + * The augment list popup. It is opened from the room settings, which on phones are already a popup: Esc closes only + * this one (the settings popup underneath stays open). + */ +function AugListSheet({ onClose, readOnly, children }: { onClose: () => void; readOnly: boolean; children: React.ReactNode }) { + const close = useRef(onClose); + close.current = onClose; + useEffect(() => { + const key = (e: KeyboardEvent) => { + if (e.key !== 'Escape') return; + e.stopPropagation(); + close.current(); + }; + document.addEventListener('keydown', key, true); + return () => document.removeEventListener('keydown', key, true); + }, []); + return ( + + {children} + + ); +} diff --git a/apps/web/src/games/yut/aug-ui.tsx b/apps/web/src/games/yut/aug-ui.tsx index 4f18440..4420b8d 100644 --- a/apps/web/src/games/yut/aug-ui.tsx +++ b/apps/web/src/games/yut/aug-ui.tsx @@ -10,7 +10,7 @@ import { NODE_NAMES, NODE_POS } from '@bg/games/yut/board'; import type { PublicUser } from '@bg/shared/lite'; import { Sheet } from '../../components/ui'; import { haptic, sounds } from '../../lib/feedback'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useMotionSettled } from '../../lib/motion'; import { AugIcon } from './aug-icons'; type Act = (a: unknown) => void; @@ -64,6 +64,19 @@ export const AUG_CSS = ` .aug-board-wrap { position: relative; } .aug-aim { touch-action: none; cursor: crosshair; } .sheet:has(.aug-cards) { width: min(100%, 780px); } +.aug-list { display: flex; flex-direction: column; gap: 8px; } +.aug-list.scroll { max-height: min(52vh, 460px); overflow: auto; padding: 2px; } +.aug-row { display: flex; gap: 10px; align-items: flex-start; width: 100%; text-align: left; border: 2px solid var(--border); border-radius: 12px; background: var(--surface); + color: var(--text); padding: 8px 10px; font: inherit; min-height: 56px; flex: none; } +button.aug-row { cursor: pointer; } +.aug-row[aria-pressed='true'] { border-color: var(--primary); background: var(--primary-soft); } +.aug-row.win { border-color: #f59e0b; } +.aug-row.win[aria-pressed='true'] { border-color: var(--primary); } +.aug-row-body { display: flex; flex-direction: column; gap: 3px; min-width: 0; flex: 1; overflow-wrap: anywhere; } +.aug-row-body strong { font-size: 1rem; } +.aug-row-body p { margin: 0; font-size: .88rem; } +.aug-row-who { font-size: .8rem; font-weight: 800; color: var(--text-sub); } +.aug-row-check { flex: none; align-self: center; font-size: 1.2rem; font-weight: 900; color: var(--primary); width: 22px; text-align: center; } .aug-pop { position: fixed; z-index: 1000; width: max-content; max-width: min(300px, calc(100vw - 16px)); pointer-events: none; text-align: left; border: 3px solid var(--border); border-radius: 14px; background: var(--surface); color: var(--text); padding: 10px 12px; display: flex; flex-direction: column; gap: 6px; box-shadow: 0 10px 28px rgba(0, 0, 0, .28); animation: aug-pop .12s ease both; } @@ -259,6 +272,46 @@ export function AugSlots({ v, side }: { v: YutView; side: number }) { ); } +// ---------------------------------------------------------------- augment list rows (icon + full description) + +export function AugTags({ id }: { id: AugId }) { + const m = AUGS[id]; + return ( + + {TIER_KO[m.tier]} + {KIND_KO[m.kind]} + {m.once && 1회} + {m.win && m.kind !== 'win' && 승리 조건} + {m.custom && 추가} + + ); +} + +/** One augment in a list: icon, name, tags, the whole description; a button when `onPick` is given. */ +export function AugRow({ id, who, picked, onPick }: { id: AugId; who?: string; picked?: boolean; onPick?: () => void }) { + const m = AUGS[id]; + const body = ( + <> + + + {who && {who}} + {m.name} + +

    {m.text}

    + {m.note &&

    {m.note}

    } +
    + {onPick && {picked ? '✓' : ''}} + + ); + return onPick ? ( + + ) : ( +
    {body}
    + ); +} + // ---------------------------------------------------------------- selection function AugCard({ id, picked, onPick, disabled }: { id: AugId; picked: boolean; onPick: () => void; disabled?: boolean }) { @@ -269,31 +322,34 @@ function AugCard({ id, picked, onPick, disabled }: { id: AugId; picked: boolean;

    {m.name}

    - - {TIER_KO[m.tier]} - {KIND_KO[m.kind]} - {m.once && 1회} - {m.win && m.kind !== 'win' && 승리 조건} - {m.custom && 추가} - +

    {m.text}

    {m.note &&

    {m.note}

    } ); } -export function AugSelect({ v, act, pending, players }: { v: YutView; act: Act; pending: boolean; players: Record }) { +export function AugSelect({ v, act, pending, players, blocked = false }: { v: YutView; act: Act; pending: boolean; players: Record; blocked?: boolean }) { const sel = v.aug!.select!; const [choice, setChoice] = useState(null); const [target, setTarget] = useState(''); - const [open, setOpen] = useState(true); + const [open, setOpen] = useState(false); const mine = sel.offers.length > 0 && sel.picksLeft > 0; const key = sel.offers.join(','); + // New offers open the window by themselves, but only after the board has stopped moving (the last move's hop, + // the 이의있음! call, `blocked`) so nothing pops up over an animation. + const [autoOpen, setAutoOpen] = useState(mine); + const ready = useMotionSettled(autoOpen && mine && !blocked); useEffect(() => { setChoice(sel.forced); setTarget(''); - if (mine) setOpen(true); + if (mine) setAutoOpen(true); }, [key]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { + if (!ready) return; + setOpen(true); + setAutoOpen(false); + }, [ready]); const tierText = { start: '범용 + 시작 전용', mid: '범용 + 중간 전용', final: '범용 + 마무리 전용' }[sel.tier]; const targets = choice === 'detective' ? sel.detectiveTargets : choice === 'delivery' ? sel.deliveryTargets : []; const needTarget = choice === 'detective' || (choice === 'delivery' && targets.length > 0); @@ -334,17 +390,17 @@ export function AugSelect({ v, act, pending, players }: { v: YutView; act: Act; ))} {needTarget && ( - + + )}
    +
    + {open && ( + setOpen(false)} label={title}> +

    {title}

    +
    + {choices.map((c) => { + const o = owner.get(c.value); + return o ? ( + setPick(c.value)} /> + ) : ( + + ); + })} +
    +
    + + +
    +
    + )} + + ); +} + // ---------------------------------------------------------------- popups & toasts -/** Shows each new effect once: a dialog for victories / going out, a short toast for the rest. */ -export function AugFxLayer({ v, players, me }: { v: YutView; players: Record; me: string | null }) { +/** + * Shows each new effect once: a dialog for victories / going out, a short toast for the rest, 이의있음! full screen. + * New effects wait until the board has stopped moving (a piece still hopping to the square that caused them). + * `onBlocking` is true while an 이의있음! call is waiting or on screen, so the new selection opens after it. + */ +export function AugFxLayer({ v, players, me, onBlocking }: { v: YutView; players: Record; me: string | null; onBlocking?: (on: boolean) => void }) { const fx = v.aug?.fx ?? []; const seen = useRef(fx.reduce((m, f) => Math.max(m, f.no), 0)); + const [queue, setQueue] = useState([]); + const ready = useMotionSettled(queue.length > 0); const [popup, setPopup] = useState(null); const [toast, setToast] = useState<{ key: number; text: string } | null>(null); const [objection, setObjection] = useState(null); @@ -454,7 +588,13 @@ export function AugFxLayer({ v, players, me }: { v: YutView; players: Record f.no > seen.current); if (!fresh.length) return; seen.current = Math.max(...fresh.map((f) => f.no)); - // 이의있음!: a big full-screen call, then the (already open) new selection shows underneath + setQueue((q) => [...q, ...fresh]); + }, [fx.map((f) => f.no).join(',')]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(() => { + if (!ready) return; + const fresh = queue; + setQueue([]); + // 이의있음!: a big full-screen call, then the new selection opens underneath const obj = fresh.find((f) => f.kind === 'objection'); if (obj) { setObjection(obj); @@ -471,7 +611,9 @@ export function AugFxLayer({ v, players, me }: { v: YutView; players: Record f !== big && f !== obj && f.kind !== 'flick'); if (small.length) setToast({ key: small[small.length - 1]!.no, text: small.map((f) => f.text).join(' · ') }); - }, [fx.map((f) => f.no).join(',')]); // eslint-disable-line react-hooks/exhaustive-deps + }, [ready]); // eslint-disable-line react-hooks/exhaustive-deps + const blocking = !!objection || queue.some((f) => f.kind === 'objection'); + useEffect(() => onBlocking?.(blocking), [blocking]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (!toast) return; const t = setTimeout(() => setToast(null), fxMs(3200)); diff --git a/apps/web/src/games/yut/index.tsx b/apps/web/src/games/yut/index.tsx index d2dc87e..0805b92 100644 --- a/apps/web/src/games/yut/index.tsx +++ b/apps/web/src/games/yut/index.tsx @@ -32,7 +32,7 @@ import { helpNow } from './help'; import { houseRules, optionsSummary } from './house-rules'; import { quickStart } from './quick'; import { HOP_MS, moveSound, throwSound } from './sound'; -import { fxMs } from '../../lib/motion'; +import { fxMs, useAfterMotionValue, useMotionHold } from '../../lib/motion'; import { AugIcon } from './aug-icons'; type From = number | 'home'; @@ -241,6 +241,7 @@ function Sticks({ view: v, players }: { view: YutView; players: Record setTossing(false), fxMs(820)); return () => clearTimeout(t); }, [lt?.no]); // eslint-disable-line react-hooks/exhaustive-deps + useMotionHold(tossing); const sticks = lt?.sticks ?? (v.aug ? Array.from({ length: v.aug.sides.find((x) => x.id === v.mySide)?.sticks ?? 4 }, (_, i) => i % 2 === 1) : [false, true, false, true]); const vbW = Math.max(120, 14 + sticks.length * 27); const label = !lt ? '' : tossing ? '…' : lt.result === 'nak' ? '낙!' : lt.results ? `${lt.results.map((r) => THROW_KO[r]).join('·')}!` : `${THROW_KO[lt.result]}!`; @@ -299,6 +300,8 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps(null); const aug = v.aug ?? null; const [aim, setAim] = useState(null); + // An 이의있음! call is waiting or on screen: the new selection opens after it. + const [fxBlock, setFxBlock] = useState(false); const [targetUid, setTargetUid] = useState(null); const svgRef = useRef(null); useEffect(() => { @@ -306,6 +309,14 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps u.uid === targetUid) : []; + // Pieces hopping square by square (timers) and their landing effects: results wait for them. + useMotionHold(!!anim || !!landing); + // A new throw shows up in 모아 둔 결과 (and the move buttons) only once the sticks have landed; a used result + // stays (greyed) until the piece has finished moving. + const pendingKey = v.pending.join(','); + const shownPendingKey = useAfterMotionValue(pendingKey); + const settling = shownPendingKey !== pendingKey; + const shownPending = settling ? (shownPendingKey ? (shownPendingKey.split(',') as Throw[]) : []) : v.pending; const lastMoveNo = useRef(v.lastMove?.no ?? 0); const lastThrowNo = useRef(v.lastThrow?.no ?? 0); const prevCurrent = useRef(v.current); @@ -448,7 +459,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps{CSS} {aug && }
    - {aug && } + {aug && } {LINES.map(([a, b]) => ( @@ -583,7 +594,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps {aug && } - {aug && v.phase === 'aug' && aug.select && } + {aug && v.phase === 'aug' && aug.select && } {aug && v.phase === 'prompt' && aug.prompt && }
    @@ -592,11 +603,11 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps 모아 둔 결과{v.current !== me && v.phase !== 'finished' ? ` · ${nick(players, v.current)}님` : ''} - {v.pending.length === 0 ? ( - {v.phase === 'throw' ? '윷을 던지면 여기에 모여요.' : '없음'} + {shownPending.length === 0 ? ( + {v.phase === 'throw' || settling ? '윷을 던지면 여기에 모여요.' : '없음'} ) : (
    - {v.pending.map((t, i) => { + {shownPending.map((t, i) => { const usable = moves.some((m) => m.throw === t) && (!ordered || i === 0); return (