병합: 움직임 더하기 2차(루미큐브·마피아·라이어·바둑·클루·오목·포커)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,6 +6,7 @@ import { Avatar, ConfirmSheet, Sheet } from '../../components/ui';
|
||||
import { TurnTimer, useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { BOARD_MOTION_CSS, useAnimOver, useMoveDiff } from '../board-motion';
|
||||
import { reducedMotion, useBanner } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -60,6 +61,34 @@ function Stone({ color, cx, cy, r, ghost }: { color: Color; cx: number; cy: numb
|
||||
|
||||
type MarkMode = 'dead' | 'seki';
|
||||
|
||||
/** Territory marks pop in from the top-left corner outwards when counting starts (scoring / the result). */
|
||||
const BADUK_CSS = `
|
||||
.bd-own { transform-box: fill-box; transform-origin: center; animation: bd-own .32s cubic-bezier(.3, 1.5, .5, 1) both; animation-delay: var(--d, 0ms); }
|
||||
@keyframes bd-own { from { opacity: 0; transform: scale(.2); } }
|
||||
`;
|
||||
|
||||
/**
|
||||
* A number counting up from 0 when `live` (the game ended on screen); the final value right away otherwise or with
|
||||
* reduced motion. Put it inside an aria-hidden element next to the final value for screen readers.
|
||||
*/
|
||||
function CountUp({ to, live }: { to: number; live: boolean }) {
|
||||
const animate = live && !reducedMotion();
|
||||
const [shown, setShown] = useState<number | null>(animate ? 0 : null);
|
||||
useEffect(() => {
|
||||
if (!animate) return setShown(null);
|
||||
let raf = 0;
|
||||
const t0 = performance.now();
|
||||
const step = (t: number) => {
|
||||
const k = Math.min(1, (t - t0) / 1000);
|
||||
setShown(k < 1 ? Math.floor(to * (1 - (1 - k) ** 3)) : null);
|
||||
if (k < 1) raf = requestAnimationFrame(step);
|
||||
};
|
||||
raf = requestAnimationFrame(step);
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, [to, animate]);
|
||||
return <>{shown ?? to}</>;
|
||||
}
|
||||
|
||||
function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>) {
|
||||
const n = v.size;
|
||||
const myTurn = v.phase === 'playing' && v.myColor === v.turn;
|
||||
@@ -75,6 +104,12 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prevCount = useRef(v.moveCount);
|
||||
const prevDead = useRef<Set<number> | null>(null);
|
||||
const [banner, showBanner] = useBanner();
|
||||
// When counting started on screen (scoring or the result): the territory marks pop in for a moment after that.
|
||||
const counted = useRef<{ phase: string; at: number }>({ phase: v.phase, at: 0 });
|
||||
if (counted.current.phase !== v.phase) counted.current = { phase: v.phase, at: v.phase === 'playing' ? 0 : Date.now() };
|
||||
const ownAnim = counted.current.at > 0;
|
||||
const ownStagger = ownAnim && Date.now() - counted.current.at < 1500;
|
||||
|
||||
const illegal = useMemo(() => new Map(v.illegalPoints.map((p) => [p.y * n + p.x, p.reason])), [v.illegalPoints, n]);
|
||||
// Dead stones: the live marks while scoring, or (after the game) stones owned by the other colour.
|
||||
@@ -106,10 +141,11 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
}
|
||||
setAnnounce(`${COLOR_KO[m.color]}이 ${label(n, m.pt)}에 두었어요.${m.captured ? ` 돌 ${m.captured}개를 따냈어요.` : ''}`);
|
||||
} else {
|
||||
// 패스: a soft knock on the board edge.
|
||||
// 패스: a soft knock on the board edge (the second pass shows the counting banner instead).
|
||||
tone(330, 90, 'sine', 0.1);
|
||||
noise(50, 0.05, 0, 'lowpass', 700);
|
||||
setAnnounce(`${COLOR_KO[m.color]}이 패스했어요.`);
|
||||
if (v.phase === 'playing') showBanner('패스', 'dark', `${COLOR_KO[m.color]}이 이번 차례를 쉬어요`);
|
||||
}
|
||||
if (myTurn) haptic(40);
|
||||
} else if (v.moveCount < prevCount.current) sfx.whoosh();
|
||||
@@ -118,6 +154,21 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
setBubble(null);
|
||||
}, [v.moveCount]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Counting starts / the game ends (for both players and watchers).
|
||||
const prevPhase = useRef(v.phase);
|
||||
useEffect(() => {
|
||||
const before = prevPhase.current;
|
||||
prevPhase.current = v.phase;
|
||||
if (before === v.phase) return;
|
||||
if (v.phase === 'scoring') {
|
||||
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);
|
||||
}
|
||||
}, [v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Highlight groups whose dead/alive mark just changed (e.g. by the opponent).
|
||||
useEffect(() => {
|
||||
if (!v.scoring) {
|
||||
@@ -210,7 +261,7 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
const pad = 0.95;
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
<style>{BOARD_MOTION_CSS}</style>
|
||||
<style>{BOARD_MOTION_CSS + BADUK_CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox={`${-pad} ${-pad} ${n - 1 + 2 * pad} ${n - 1 + 2 * pad}`}
|
||||
@@ -300,7 +351,22 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
{score &&
|
||||
score.ownership.map((o, i) => {
|
||||
if (o === 0 || (v.board[i] !== 0 && !dead.has(i))) return null;
|
||||
return <rect key={`o${i}`} x={(i % n) - 0.17} y={Math.floor(i / n) - 0.17} width={0.34} height={0.34} fill={o === 1 ? '#111' : '#fafafa'} stroke={o === 1 ? '#000' : '#555'} strokeWidth={0.03} />;
|
||||
const x = i % n;
|
||||
const y = Math.floor(i / n);
|
||||
return (
|
||||
<rect
|
||||
key={`o${i}`}
|
||||
className={ownAnim ? 'bd-own' : undefined}
|
||||
style={ownStagger ? ({ '--d': `${Math.min((x + y) * 24, 900)}ms` } as React.CSSProperties) : undefined}
|
||||
x={x - 0.17}
|
||||
y={y - 0.17}
|
||||
width={0.34}
|
||||
height={0.34}
|
||||
fill={o === 1 ? '#111' : '#fafafa'}
|
||||
stroke={o === 1 ? '#000' : '#555'}
|
||||
strokeWidth={0.03}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{[...seki].map((i) => (
|
||||
<path key={`seki${i}`} d={`M ${i % n} ${Math.floor(i / n) - 0.2} l 0.2 0.2 l -0.2 0.2 l -0.2 -0.2 z`} fill="#f59e0b" opacity={0.9} />
|
||||
@@ -336,6 +402,7 @@ function BadukBoard({ view: v, act, pending, tapConfirm }: BoardProps<BadukView>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner}
|
||||
{bubble && (
|
||||
<div className="card" role="status" style={{ padding: '8px 12px', border: '2px solid var(--danger)', fontWeight: 600 }}>
|
||||
{label(n, bubble.p)}: {bubble.text}
|
||||
@@ -479,6 +546,9 @@ function BadukSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
const myTurn = v.phase === 'playing' && v.myColor === v.turn;
|
||||
const last = v.moves[v.moves.length - 1];
|
||||
const oppPassed = myTurn && last && !last.pt && last.color !== v.myColor;
|
||||
// The final score counts up only when the game ended while this screen was open.
|
||||
const ended = useRef({ phase: v.phase, live: false });
|
||||
if (ended.current.phase !== v.phase) ended.current = { phase: v.phase, live: v.phase === 'finished' };
|
||||
return (
|
||||
<>
|
||||
<PlayerBar view={v} color={v.myColor ? opp : 'black'} players={players} deadline={deadline} me={me} />
|
||||
@@ -492,6 +562,12 @@ function BadukSide({ view: v, me, players, act, pending, deadline }: BoardProps<
|
||||
{v.phase === 'finished' && v.result?.score && (
|
||||
<div className="card stack" style={{ padding: 14, gap: 8 }}>
|
||||
<strong style={{ fontSize: '1.15rem' }}>{v.result.summaryKo}</strong>
|
||||
<div style={{ fontSize: '1.5rem', fontWeight: 800, textAlign: 'center', fontVariantNumeric: 'tabular-nums' }}>
|
||||
<span className="sr-only">{`흑 ${v.result.score.black.total} : 백 ${v.result.score.white.total}`}</span>
|
||||
<span aria-hidden>
|
||||
흑 <CountUp to={v.result.score.black.total} live={ended.current.live} /> : 백 <CountUp to={v.result.score.white.total} live={ended.current.live} />
|
||||
</span>
|
||||
</div>
|
||||
<ScoreTable score={v.result.score} heading />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** 클루 화면 (docs/games/clue.md §9). */
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
|
||||
import type { ClueOptions, ClueView, SuggestionView } from '@bg/games/clue';
|
||||
import {
|
||||
PASSAGES,
|
||||
@@ -24,6 +24,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { TurnTimer } from '../../components/TurnTimer';
|
||||
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { cssEsc, flyGhost, reducedMotion } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -191,20 +192,56 @@ button.cl-card.can { box-shadow: 0 0 0 3px var(--primary); }
|
||||
.cl-note { grid-template-columns: minmax(0, 1fr); }
|
||||
.cl-card { width: 66px; min-height: 78px; }
|
||||
}
|
||||
/* Tokens / weapons on the map are lifted above the rooms while they slide (see slideFrom). */
|
||||
.cl-map [data-tok], .cl-map [data-weap] { position: relative; }
|
||||
.fx-ghost.cl-ghost { display: flex; align-items: center; justify-content: center; border-radius: 8px; background: linear-gradient(160deg, #fffaf0, #f1e6cf);
|
||||
border: 2px solid #b79c6b; color: #2b2118; font: 800 1.1rem/1 system-ui, sans-serif; box-shadow: 0 4px 10px rgba(0,0,0,.35); }
|
||||
.fx-ghost.cl-ghost.back { background: repeating-linear-gradient(45deg, #7c2d12 0 6px, #9a3412 6px 12px); border-color: #fff7ed; }
|
||||
@media (prefers-reduced-motion: reduce) { .cl-card.new, .cl-room.landed { animation: none; } }
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- small pieces
|
||||
|
||||
function Token({ x, me, pop }: { x: Suspect; me?: boolean; pop?: boolean }) {
|
||||
/**
|
||||
* Slides an element that just moved from (dx, dy) px away back to its place in a little hop, above the other rooms.
|
||||
* Returns whether it animated (the caller staggers several).
|
||||
*/
|
||||
function slideFrom(el: HTMLElement | null, dx: number, dy: number, delay: number): boolean {
|
||||
const d = Math.hypot(dx, dy);
|
||||
if (!el || d < 4 || reducedMotion() || typeof el.animate !== 'function') return false;
|
||||
// The CSS pop of a freshly mounted token would scale the slide; the slide replaces it.
|
||||
el.getAnimations().forEach((a) => a.cancel());
|
||||
el.style.zIndex = '4';
|
||||
const lift = Math.min(36, 10 + d * 0.15);
|
||||
const anim = el.animate(
|
||||
[
|
||||
{ transform: `translate(${dx}px, ${dy}px)` },
|
||||
{ transform: `translate(${dx / 2}px, ${dy / 2 - lift}px) scale(1.2)`, offset: 0.5 },
|
||||
{ transform: 'translate(0px, 0px)' },
|
||||
],
|
||||
{ duration: Math.min(720, 300 + d * 0.8), delay, easing: 'ease-in-out', fill: 'backwards' },
|
||||
);
|
||||
const done = () => (el.style.zIndex = '');
|
||||
anim.onfinish = done;
|
||||
anim.oncancel = done;
|
||||
return true;
|
||||
}
|
||||
|
||||
function Token({ x, me, pop, onMap }: { x: Suspect; me?: boolean; pop?: boolean; onMap?: boolean }) {
|
||||
return (
|
||||
<span className={`cl-tok${x === 'white' ? ' light' : ''}${me ? ' me' : ''}${pop ? ' anim-pop' : ''}`} style={{ background: SUSPECT_COLOR[x] }} title={SUSPECT_KO[x]} aria-hidden>
|
||||
<span
|
||||
className={`cl-tok${x === 'white' ? ' light' : ''}${me ? ' me' : ''}${pop ? ' anim-pop' : ''}`}
|
||||
style={{ background: SUSPECT_COLOR[x] }}
|
||||
title={SUSPECT_KO[x]}
|
||||
data-tok={onMap ? x : undefined}
|
||||
aria-hidden
|
||||
>
|
||||
{SUSPECT_SHORT[x]}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Card({ id, onClick, can, fresh, label, delay }: { id: string; onClick?: () => void; can?: boolean; fresh?: boolean; label?: string; delay?: number }) {
|
||||
function Card({ id, onClick, can, fresh, flip, label, delay }: { id: string; onClick?: () => void; can?: boolean; fresh?: boolean; flip?: boolean; label?: string; delay?: number }) {
|
||||
const x = itemOf(id);
|
||||
const cat = categoryOf(x);
|
||||
const body = (
|
||||
@@ -224,7 +261,7 @@ function Card({ id, onClick, can, fresh, label, delay }: { id: string; onClick?:
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<span className={`cl-card${fresh ? ' new' : ''}`} role="img" aria-label={aria} style={delay ? ({ '--anim-delay': `${delay}ms` } as CSSProperties) : undefined}>
|
||||
<span className={`cl-card${flip ? ' anim-flip' : fresh ? ' new' : ''}`} role="img" aria-label={aria} style={delay ? ({ '--anim-delay': `${delay}ms` } as CSSProperties) : undefined}>
|
||||
{body}
|
||||
</span>
|
||||
);
|
||||
@@ -245,6 +282,32 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
|
||||
useEffect(() => setSel(null), [v.phase.kind, v.current, v.turnNo]);
|
||||
|
||||
// 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.
|
||||
const placeSig = JSON.stringify([v.pos, v.weaponAt]);
|
||||
const places = useRef<Map<string, { x: number; y: number }> | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
const map = document.querySelector('.cl-map');
|
||||
if (!map) return;
|
||||
const m = map.getBoundingClientRect();
|
||||
const before = places.current;
|
||||
const now = new Map<string, { x: number; y: number }>();
|
||||
map.querySelectorAll<HTMLElement>('[data-tok], [data-weap]').forEach((el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
now.set(el.dataset.tok ? `t:${el.dataset.tok}` : `w:${el.dataset.weap}`, { x: r.left + r.width / 2 - m.left, y: r.top + r.height / 2 - m.top });
|
||||
});
|
||||
places.current = now;
|
||||
if (!before) return;
|
||||
let k = 0;
|
||||
for (const [key, at] of now) {
|
||||
const was = before.get(key);
|
||||
if (!was) continue;
|
||||
const [kind, id] = [key.slice(0, 1), key.slice(2)];
|
||||
const el = map.querySelector<HTMLElement>(kind === 't' ? `[data-tok="${cssEsc(id)}"]` : `[data-weap="${cssEsc(id)}"]`);
|
||||
if (slideFrom(el, was.x - at.x, was.y - at.y, k * 90)) k++;
|
||||
}
|
||||
}, [placeSig]);
|
||||
|
||||
// Sounds and highlights for what anyone just did: dice, moves, passages, suggestions, answers, accusations.
|
||||
useEffect(() => {
|
||||
const p = prevView.current;
|
||||
@@ -270,9 +333,23 @@ function ClueBoard({ view: v, me, players, act, pending }: BoardProps<ClueView>)
|
||||
if (sgNew) clSound.suggest();
|
||||
const lastNow = lastOf(v.suggestions);
|
||||
const lastPrev = lastOf(p.suggestions);
|
||||
const tokOf = (player: string) => {
|
||||
const x = v.suspectOf[player];
|
||||
return x ? document.querySelector(`.cl-map [data-tok="${cssEsc(x)}"]`) : null;
|
||||
};
|
||||
// The three suggested cards fly from the suggester's token into the case file in the middle.
|
||||
if (sgNew && lastNow) {
|
||||
const from = tokOf(lastNow.by);
|
||||
const mid = document.querySelector('.cl-mid');
|
||||
[SUSPECT_SHORT[lastNow.suspect], WEAPON_ICON[lastNow.weapon], ROOM_ICON[lastNow.room]].forEach((label, i) =>
|
||||
flyGhost(from, mid, { label, className: 'cl-ghost', delay: 250 + i * 140, ms: 520 }),
|
||||
);
|
||||
}
|
||||
if (lastNow && !sgNew && lastPrev && v.suggestions.length === p.suggestions.length && !lastPrev.refuter && lastNow.refuter) {
|
||||
if (lastNow.shown && (lastNow.by === me || lastNow.refuter === me)) sfx.cardFlip();
|
||||
else sfx.cardDeal();
|
||||
// Everyone else sees a face-down card going from the refuter to the suggester (mine flips open in the panel).
|
||||
if (lastNow.by !== me) flyGhost(tokOf(lastNow.refuter), tokOf(lastNow.by), { className: 'cl-ghost back', ms: 520 });
|
||||
}
|
||||
if (lastNow && p.phase.kind === 'refute' && v.phase.kind !== 'refute' && !lastNow.refuter) clSound.noneShown();
|
||||
if (lastNow && sgNew && v.phase.kind === 'afterSuggest' && !lastNow.refuter) clSound.noneShown();
|
||||
@@ -404,10 +481,10 @@ function Mansion({
|
||||
{can && !free && d !== undefined && <span className="cl-dist">{d}칸</span>}
|
||||
<span className="cl-things">
|
||||
{toks.map((x) => (
|
||||
<Token key={x} x={x} me={x === mySuspect} pop />
|
||||
<Token key={x} x={x} me={x === mySuspect} pop onMap />
|
||||
))}
|
||||
{weaps.map((w) => (
|
||||
<span key={w} className="cl-weap anim-pop" title={WEAPON_KO[w]} aria-hidden>
|
||||
<span key={w} className="cl-weap anim-pop" title={WEAPON_KO[w]} data-weap={w} aria-hidden>
|
||||
{WEAPON_ICON[w]}
|
||||
</span>
|
||||
))}
|
||||
@@ -439,7 +516,7 @@ function Mansion({
|
||||
const p = owner(x);
|
||||
return (
|
||||
<li key={x} style={p ? undefined : { opacity: 0.6 }} aria-label={`${SUSPECT_KO[x]}${p ? '' : '(맡은 사람 없음)'}: ${hallwayText(v.pos[x])}`}>
|
||||
<Token key={posKey(v.pos[x])} x={x} me={x === mySuspect} pop />
|
||||
<Token key={posKey(v.pos[x])} x={x} me={x === mySuspect} pop onMap />
|
||||
<span aria-hidden>{hallwayText(v.pos[x])}</span>
|
||||
</li>
|
||||
);
|
||||
@@ -548,7 +625,7 @@ function LastResult({ view: v, me, players }: { view: ClueView; me: string | nul
|
||||
{last.refuter ? (
|
||||
last.shown ? (
|
||||
<div className="row" style={{ gap: 10, alignItems: 'center' }}>
|
||||
<Card id={last.shown} fresh label={`${last.refuter === me ? '내가 보여 준' : `${nick(players, last.refuter)}님이 보여 준`} 카드: ${ITEM_KO[itemOf(last.shown)]}`} />
|
||||
<Card id={last.shown} flip label={`${last.refuter === me ? '내가 보여 준' : `${nick(players, last.refuter)}님이 보여 준`} 카드: ${ITEM_KO[itemOf(last.shown)]}`} />
|
||||
<span>
|
||||
<strong>{last.refuter === me ? `내가 ${nick(players, last.by)}님에게 보여 준 카드` : `${nick(players, last.refuter)}님이 보여 준 카드`}</strong>
|
||||
<br />
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { PublicUser } from '@bg/shared/lite';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { cssEsc, useBanner, type BannerTone } from '../card-fx';
|
||||
import { ChatMessage, nameHue, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
|
||||
@@ -134,6 +135,16 @@ button.lg-tile { cursor: pointer; }
|
||||
@keyframes lg-pick { 50% { transform: scale(1.07); } }
|
||||
.lg-card[data-show='true'] { animation: anim-flip .35s ease both; }
|
||||
@keyframes lg-grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }
|
||||
/* Vote results come in one row at a time (--d = the row's delay). */
|
||||
.lg-bar { animation: anim-slide-up .3s ease-out both; animation-delay: var(--d, 0ms); }
|
||||
.lg-bar .tr i { animation-delay: var(--d, 0ms); animation-fill-mode: both; }
|
||||
.lg-bar .ct { animation: anim-pop .32s cubic-bezier(.3, 1.6, .5, 1) both; animation-delay: calc(var(--d, 0ms) + 450ms); }
|
||||
/* Spotlight on the accused: the screen darkens around their tile (never takes clicks), the tile glows and shakes. */
|
||||
.lg-spot { position: fixed; inset: 0; z-index: 55; pointer-events: none; animation: lg-spot 1.8s ease both;
|
||||
background: radial-gradient(circle at var(--x) var(--y), rgba(0,0,0,0) 0, rgba(0,0,0,0) 70px, rgba(8,8,20,.72) 150px); }
|
||||
@keyframes lg-spot { 0% { opacity: 0; } 18% { opacity: 1; } 75% { opacity: 1; } 100% { opacity: 0; } }
|
||||
.lg-tile.spot { z-index: 1; animation: anim-shake .45s ease .25s both, lg-glow 1.5s ease both; }
|
||||
@keyframes lg-glow { 0%, 100% { box-shadow: 0 0 0 3px rgba(220,38,38,.35); } 30%, 70% { box-shadow: 0 0 0 5px #fde047, 0 0 28px 6px rgba(253,224,71,.75); } }
|
||||
@media (max-width: 1099px) {
|
||||
.lg { height: auto; }
|
||||
.lg-grid { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-areas: 'actions players' 'talk talk'; }
|
||||
@@ -151,7 +162,8 @@ button.lg-tile { cursor: pointer; }
|
||||
.lg-msgs { min-height: 160px; max-height: 300px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.lg-news, .lg-bar .tr i, .lg-tile[aria-pressed='true'], .lg-tile.accused, .lg-card[data-show='true'] { animation: none; }
|
||||
.lg-news, .lg-bar, .lg-bar .tr i, .lg-bar .ct, .lg-tile[aria-pressed='true'], .lg-tile.accused, .lg-tile.spot, .lg-card[data-show='true'] { animation: none; }
|
||||
.lg-spot { display: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -274,6 +286,9 @@ function News({ v, players }: { v: LiarView; players: Record<string, PublicUser>
|
||||
);
|
||||
}
|
||||
|
||||
/** Delay between two vote rows appearing (ms). */
|
||||
const BAR_GAP = 350;
|
||||
|
||||
function VoteBars({ e, players }: { e: Extract<PublicEvent, { t: 'vote' }>; players: Record<string, PublicUser> }) {
|
||||
const rows = Object.entries(e.tally).sort((a, b) => b[1] - a[1]);
|
||||
const max = Math.max(1, ...rows.map((r) => r[1]));
|
||||
@@ -282,13 +297,14 @@ function VoteBars({ e, players }: { e: Extract<PublicEvent, { t: 'vote' }>; play
|
||||
<span className="big">{eventText(e, players)}</span>
|
||||
{rows.length > 0 && (
|
||||
<div className="lg-bars" role="list" aria-label="득표">
|
||||
{rows.map(([id, n]) => (
|
||||
<div key={id} className="lg-bar" data-top={id === e.accused} role="listitem" aria-label={`${nick(players, id)} ${n}표`}>
|
||||
{/* Least votes first, so the top one lands last (one row every 0.35 s). */}
|
||||
{rows.map(([id, n], i) => (
|
||||
<div key={id} className="lg-bar" data-top={id === e.accused} role="listitem" aria-label={`${nick(players, id)} ${n}표`} style={{ '--d': `${(rows.length - 1 - i) * BAR_GAP}ms` } as CSSProperties}>
|
||||
<span className="nm">{nick(players, id)}</span>
|
||||
<span className="tr" aria-hidden>
|
||||
<i style={{ width: `${(n / max) * 100}%` }} />
|
||||
</span>
|
||||
<span>{n}표</span>
|
||||
<span className="ct">{n}표</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -308,7 +324,7 @@ function VoteBars({ e, players }: { e: Extract<PublicEvent, { t: 'vote' }>; play
|
||||
|
||||
type Pick = { ids: string[]; chosen: string | null; onPick: (id: string) => void } | null;
|
||||
|
||||
function Players({ v, players, me, pick, pending }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean }) {
|
||||
function Players({ v, players, me, pick, pending, spot }: { v: LiarView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean; spot: string | null }) {
|
||||
const ph = v.phase;
|
||||
const accused = v.final?.accused ?? ph.liar;
|
||||
return (
|
||||
@@ -321,7 +337,7 @@ function Players({ v, players, me, pick, pending }: { v: LiarView; players: Reco
|
||||
const p = v.players.find((x) => x.id === id)!;
|
||||
const u = userOf(players, id);
|
||||
const speaking = ph.speaker === id;
|
||||
const cls = `lg-tile${id === me ? ' me' : ''}${p.left ? ' left' : ''}${speaking ? ' speaking' : ''}${accused === id ? ' accused' : ''}`;
|
||||
const cls = `lg-tile${id === me ? ' me' : ''}${p.left ? ' left' : ''}${speaking ? ' speaking' : ''}${spot === id ? ' spot' : accused === id ? ' accused' : ''}`;
|
||||
const can = pick?.ids.includes(id) ?? false;
|
||||
const body = (
|
||||
<>
|
||||
@@ -677,19 +693,81 @@ const lgSound = {
|
||||
caught: () => [523, 784].forEach((f, i) => tone(f, 140, 'square', 0.07, i * 120)),
|
||||
};
|
||||
|
||||
/** Sounds for what anyone did: descriptions, votes being cast, results (the room plays win / lose at the end). */
|
||||
function useLiarSounds(v: LiarView, me: string | null): void {
|
||||
/** The accused's tile glows; `x/y` (screen px) only when the tile is on screen, for the darkened-room spotlight. */
|
||||
type Spot = { id: string; x: number | null; y: number | null; key: number };
|
||||
|
||||
/**
|
||||
* Sounds and motion for what anyone did: descriptions, votes being cast, results (the room plays win / lose at the end).
|
||||
* A result plays out in order: the vote rows come in one by one, then the spotlight falls on the accused, then the
|
||||
* banners (caught / escaped, the liar's answer, the winner). A newer announcement cancels whatever is still queued.
|
||||
*/
|
||||
function useLiarFx(v: LiarView, me: string | null, players: Record<string, PublicUser>, showBanner: (text: string, tone?: BannerTone, sub?: string) => void, setSpot: (s: Spot | null) => void): void {
|
||||
const prev = useRef(v);
|
||||
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
useEffect(() => () => timers.current.forEach(clearTimeout), []);
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
if (p === v) return;
|
||||
const last = p.events.at(-1)?.n ?? 0;
|
||||
const fresh = v.events.filter((e) => e.n > last);
|
||||
if (fresh.some((e) => e.t === 'end')) return;
|
||||
const acc = fresh.find((e) => e.t === 'accused');
|
||||
if (acc && acc.t === 'accused') return acc.liar ? lgSound.caught() : sfx.bad();
|
||||
if (fresh.some((e) => e.t === 'vote')) return sfx.chips(3);
|
||||
if (fresh.some((e) => e.t !== 'phase' && e.t !== 'left')) {
|
||||
timers.current.forEach(clearTimeout);
|
||||
timers.current = [];
|
||||
const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, ms)) : f());
|
||||
const name = (id: string) => `${nick(players, id)}님`;
|
||||
let t = 0;
|
||||
const vote = fresh.find((e) => e.t === 'vote');
|
||||
if (vote) {
|
||||
const rows = Object.keys(vote.tally).length;
|
||||
// A soft chip per row as it lands (the rows themselves are timed in CSS).
|
||||
for (let i = 0; i < Math.min(rows, 8); i++) sfx.chip(i * BAR_GAP + 300);
|
||||
t = Math.max(1, rows) * BAR_GAP + 350;
|
||||
if (!vote.accused) {
|
||||
later(t, () => (vote.round === 1 ? showBanner('동점!', 'gold', '동점인 사람끼리 다시 투표해요') : showBanner('또 동점!', 'dark', '아무도 지목되지 않았어요')));
|
||||
t += 1500;
|
||||
}
|
||||
}
|
||||
for (const e of fresh) {
|
||||
if (e.t === 'accused') {
|
||||
later(t, () => {
|
||||
const r = document.querySelector(`.lg-tile[data-player="${cssEsc(e.p)}"]`)?.getBoundingClientRect();
|
||||
const seen = !!r && r.bottom > 0 && r.top < innerHeight && r.right > 0 && r.left < innerWidth;
|
||||
setSpot({ id: e.p, x: seen ? r.left + r.width / 2 : null, y: seen ? r.top + r.height / 2 : null, key: e.n });
|
||||
tone(220, 90, 'triangle', 0.08);
|
||||
tone(220, 90, 'triangle', 0.08, 160);
|
||||
});
|
||||
later(t + 1800, () => setSpot(null));
|
||||
t += 750;
|
||||
later(t, () => {
|
||||
if (e.liar) {
|
||||
lgSound.caught();
|
||||
showBanner('잡았다!', 'green', `${josa(name(e.p), ['이', '가'])} 라이어였어요`);
|
||||
} else {
|
||||
sfx.bad();
|
||||
showBanner('헛다리!', 'dark', `${josa(name(e.p), ['은', '는'])} 라이어가 아니에요`);
|
||||
}
|
||||
});
|
||||
t += 1500;
|
||||
} else if (e.t === 'guess') {
|
||||
later(t, () => {
|
||||
if (e.correct) {
|
||||
sfx.alarm();
|
||||
showBanner('정답!', 'red', `라이어의 답: "${e.text ?? ''}"`);
|
||||
} else {
|
||||
sfx.good();
|
||||
showBanner('땡!', 'green', e.text === null ? '라이어가 답하지 못했어요' : `라이어의 답: "${e.text}"`);
|
||||
}
|
||||
});
|
||||
t += 1500;
|
||||
} else if (e.t === 'end') {
|
||||
// The room plays the win / lose sound; this is only the picture.
|
||||
const liar = v.final?.liar;
|
||||
later(t, () => showBanner(e.winner === 'liar' ? '라이어 승리!' : '시민 승리!', e.winner === 'liar' ? 'red' : 'blue', liar ? `라이어는 ${nick(players, liar)}님` : undefined));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (fresh.some((e) => e.t === 'left')) return sfx.whoosh();
|
||||
const newDesc = v.descriptions.slice(p.descriptions.length);
|
||||
if (newDesc.some((d) => d.from !== me)) return newDesc.some((d) => d.text === null) ? sfx.tick() : lgSound.said();
|
||||
@@ -716,7 +794,9 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>)
|
||||
sounds.myTurn();
|
||||
}
|
||||
}, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useLiarSounds(v, me);
|
||||
const [banner, showBanner] = useBanner();
|
||||
const [spot, setSpot] = useState<Spot | null>(null);
|
||||
useLiarFx(v, me, players, showBanner, setSpot);
|
||||
|
||||
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);
|
||||
@@ -744,7 +824,7 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>)
|
||||
{v.final && <FinalReveal v={v} players={players} />}
|
||||
<div className="lg-grid">
|
||||
<div className="lg-col lg-players">
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} />
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} spot={spot?.id ?? null} />
|
||||
</div>
|
||||
<div className="lg-col lg-talk">
|
||||
<Descriptions v={v} players={players} me={me} />
|
||||
@@ -757,6 +837,8 @@ function LiarBoard({ view: v, me, players, act, pending }: BoardProps<LiarView>)
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{spot && spot.x !== null && <div key={spot.key} className="lg-spot" aria-hidden style={{ '--x': `${spot.x}px`, '--y': `${spot.y}px` } as CSSProperties} />}
|
||||
{banner}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,12 +6,13 @@
|
||||
* 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 KeyboardEvent, type ReactNode } from 'react';
|
||||
import { useEffect, 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';
|
||||
import { useServerNow } from '../../components/TurnTimer';
|
||||
import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback';
|
||||
import { useBanner, type BannerTone } from '../card-fx';
|
||||
import { ChatMessage, sameRun } from '../../components/ChatMessage';
|
||||
import { useStickToBottom } from '../../lib/useStickToBottom';
|
||||
import { useChatOutbox, useTypingSignal } from '../../lib/chat-input';
|
||||
@@ -164,6 +165,23 @@ button.mf-tile { cursor: pointer; }
|
||||
@keyframes mf-pick { 50% { transform: scale(1.07); } }
|
||||
.mf-rolecard[data-show='true'] { animation: anim-flip .35s ease both; }
|
||||
@keyframes mf-grow { from { transform: scaleX(0); } to { transform: scaleX(1); } }
|
||||
/* Vote results come in one row at a time (--d = the row's delay). */
|
||||
.mf-bar { animation: anim-slide-up .3s ease-out both; animation-delay: var(--d, 0ms); }
|
||||
.mf-bar .tr i { animation-delay: var(--d, 0ms); animation-fill-mode: both; }
|
||||
.mf-bar .ct { animation: anim-pop .32s cubic-bezier(.3, 1.6, .5, 1) both; animation-delay: calc(var(--d, 0ms) + 450ms); }
|
||||
/* Night falls / morning comes: the whole screen dims to night blue with a moon, or lights up with a sun (never takes clicks). */
|
||||
.mf-sky { position: fixed; inset: 0; z-index: 55; pointer-events: none; display: flex; align-items: center; justify-content: center; animation: mf-sky 1.7s ease both; }
|
||||
.mf-sky.night { background: radial-gradient(circle at 50% 42%, rgba(67,56,202,.4), rgba(15,23,42,.7) 70%); }
|
||||
.mf-sky.day { background: radial-gradient(circle at 50% 38%, rgba(254,240,138,.8), rgba(251,191,36,.35) 40%, rgba(255,247,214,0) 75%); }
|
||||
.mf-sky span { font-size: clamp(4rem, 16vw, 8rem); line-height: 1; animation: mf-sky-icon 1.7s cubic-bezier(.2,.8,.3,1) both; filter: drop-shadow(0 6px 18px rgba(0,0,0,.35)); }
|
||||
.mf-sky.day span { filter: drop-shadow(0 0 28px rgba(251,191,36,.9)); }
|
||||
@keyframes mf-sky { 0% { opacity: 0; } 22% { opacity: 1; } 68% { opacity: 1; } 100% { opacity: 0; } }
|
||||
@keyframes mf-sky-icon { 0% { transform: translateY(60px) scale(.6) rotate(-20deg); opacity: 0; } 35% { transform: none; opacity: 1; } 72% { opacity: 1; } 100% { transform: translateY(-24px) scale(1.05); opacity: 0; } }
|
||||
/* The player who just left the game: the tile turns over and greys out. */
|
||||
.mf-tile.dying { animation: mf-die .9s ease both; }
|
||||
@keyframes mf-die { 0% { transform: perspective(600px) rotateY(0); filter: none; opacity: 1; } 45% { transform: perspective(600px) rotateY(90deg); filter: none; }
|
||||
55% { transform: perspective(600px) rotateY(90deg); filter: grayscale(1); } 100% { transform: perspective(600px) rotateY(0); filter: grayscale(1); opacity: .6; } }
|
||||
.mf-tile.saved { animation: anim-pop .45s cubic-bezier(.3, 1.6, .5, 1) both; box-shadow: 0 0 0 4px rgba(21,128,61,.45); }
|
||||
@media (max-width: 1099px) {
|
||||
.mf { height: auto; }
|
||||
.mf-grid { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-template-areas: 'actions players' 'chat chat'; }
|
||||
@@ -182,7 +200,8 @@ button.mf-tile { cursor: pointer; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.mf-banner { transition: none; }
|
||||
.mf-news, .mf-bar .tr i, .mf-tile[aria-pressed='true'], .mf-rolecard[data-show='true'] { animation: none; }
|
||||
.mf-news, .mf-bar, .mf-bar .tr i, .mf-bar .ct, .mf-tile[aria-pressed='true'], .mf-rolecard[data-show='true'], .mf-tile.dying, .mf-tile.saved { animation: none; }
|
||||
.mf-sky { display: none; }
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -342,13 +361,14 @@ function VoteBars({ e, players }: { e: Extract<PublicEvent, { t: 'vote' }>; play
|
||||
<span className="big">{eventText(e, players)}</span>
|
||||
{rows.length > 0 && (
|
||||
<div className="mf-bars" role="list" aria-label="득표">
|
||||
{rows.map(([id, n]) => (
|
||||
<div key={id} className="mf-bar" data-top={id === e.accused} role="listitem" aria-label={`${nick(players, id)} ${n}표`}>
|
||||
{/* Least votes first, so the top one lands last (one row every 0.35 s). */}
|
||||
{rows.map(([id, n], i) => (
|
||||
<div key={id} className="mf-bar" data-top={id === e.accused} role="listitem" aria-label={`${nick(players, id)} ${n}표`} style={{ '--d': `${(rows.length - 1 - i) * 350}ms` } as CSSProperties}>
|
||||
<span className="nm">{nick(players, id)}</span>
|
||||
<span className="tr" aria-hidden>
|
||||
<i style={{ width: `${(n / max) * 100}%` }} />
|
||||
</span>
|
||||
<span>{n}표</span>
|
||||
<span className="ct">{n}표</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -368,8 +388,10 @@ function VoteBars({ e, players }: { e: Extract<PublicEvent, { t: 'vote' }>; play
|
||||
// ---------------------------------------------------------------- players
|
||||
|
||||
type Pick = { ids: string[]; chosen: string | null; onPick: (id: string) => void } | null;
|
||||
/** 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 }: { v: MafiaView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean }) {
|
||||
function Players({ v, players, me, pick, pending, fx }: { v: MafiaView; players: Record<string, PublicUser>; me: string | null; pick: Pick; pending: boolean; fx: TileFx | null }) {
|
||||
const mafiaChoice = v.my?.night?.action === 'mafiaTarget' ? v.my.night.choice : null;
|
||||
return (
|
||||
<section className="mf-box" aria-label={`사람들. 살아 있는 사람 ${v.aliveCount}명`}>
|
||||
@@ -379,7 +401,7 @@ function Players({ v, players, me, pick, pending }: { v: MafiaView; players: Rec
|
||||
<div className="mf-tiles">
|
||||
{v.players.map((p) => {
|
||||
const u = userOf(players, p.id);
|
||||
const cls = `mf-tile${p.id === me ? ' me' : ''}${!p.alive ? ' dead' : ''}${p.id === v.phase.accused ? ' accused' : ''}`;
|
||||
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;
|
||||
const body = (
|
||||
<>
|
||||
@@ -758,15 +780,54 @@ function FinalReveal({ v, players }: { v: MafiaView; players: Record<string, Pub
|
||||
|
||||
// ---------------------------------------------------------------- board
|
||||
|
||||
/** Sounds for what anyone did: announcements (votes, deaths, saves, the end), choices, the done count. */
|
||||
function useMafiaSounds(v: MafiaView): void {
|
||||
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<string, PublicUser>, showBanner: ShowBanner, setTileFx: (fx: TileFx | null) => void): void {
|
||||
const prev = useRef(v);
|
||||
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
|
||||
useEffect(() => () => timers.current.forEach(clearTimeout), []);
|
||||
useEffect(() => {
|
||||
const p = prev.current;
|
||||
prev.current = v;
|
||||
if (p === v) return;
|
||||
const last = p.events.at(-1)?.n ?? 0;
|
||||
const fresh = v.events.filter((e) => e.n > last);
|
||||
// Banners + tile motion. At daybreak they wait for the sun to come up.
|
||||
const banners: [string, BannerTone, string?][] = [];
|
||||
const dying: string[] = [];
|
||||
const saved: string[] = [];
|
||||
const name = (id: string) => `${nick(players, id)}님`;
|
||||
for (const e of fresh) {
|
||||
if (e.t === 'death') {
|
||||
dying.push(e.p);
|
||||
const role = e.role ? `${ROLE_INFO[e.role].icon} ${ROLE_INFO[e.role].name}였어요` : e.team ? (e.team === 'mafia' ? '마피아였어요!' : '마피아가 아니었어요') : undefined;
|
||||
const how = e.by === 'mafia' ? '밤사이 마피아에게 당했어요' : e.by === 'vote' ? '투표로 탈락했어요' : '자리를 비워 탈락했어요';
|
||||
banners.push([`${name(e.p)} 탈락`, e.by === 'vote' ? 'red' : 'dark', role ? `${how} · ${role}` : how]);
|
||||
} else if (e.t === 'confirm' && e.outcome !== 'executed') {
|
||||
saved.push(e.accused);
|
||||
banners.push(e.outcome === 'politician' ? ['정치인!', 'blue', `${name(e.accused)}은 투표로 탈락하지 않아요`] : ['살아남았다!', 'green', `반대 ${e.no} · 찬성 ${e.yes}`]);
|
||||
} else if (e.t === 'healed') banners.push(['살았다!', 'green', '의사가 지켜 냈어요']);
|
||||
else if (e.t === 'soldier') {
|
||||
saved.push(e.p);
|
||||
banners.push(['버텼다!', 'green', `군인 ${name(e.p)}이 공격을 막았어요`]);
|
||||
} else if (e.t === 'quiet') banners.push(['조용한 밤', 'blue', '아무도 탈락하지 않았어요']);
|
||||
else if (e.t === 'end') banners.push([`${TEAM_KO[e.winner]} 승리!`, e.winner === 'mafia' ? 'red' : 'blue']);
|
||||
}
|
||||
if (fresh.length) {
|
||||
timers.current.forEach(clearTimeout);
|
||||
timers.current = [];
|
||||
const later = (ms: number, f: () => void) => (ms ? void timers.current.push(setTimeout(f, ms)) : f());
|
||||
const start = isNight(p) && !isNight(v) ? 900 : 0;
|
||||
if (dying.length || saved.length) {
|
||||
later(start, () => setTileFx({ dying, saved }));
|
||||
later(start + 1200, () => setTileFx(null));
|
||||
}
|
||||
banners.forEach(([text, tone, sub], i) => later(start + i * 1500, () => showBanner(text, tone, sub)));
|
||||
}
|
||||
let played = false;
|
||||
const play = (f: () => void) => {
|
||||
if (played) return;
|
||||
@@ -809,7 +870,21 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
else if (ph.kind === 'discussion' || ph.kind === 'greeting') mfSound.morning();
|
||||
else if (my?.alive && (ph.kind === 'vote' || (ph.kind === 'confirm' && my.canConfirm) || (ph.kind === 'defense' && ph.accused === me))) sounds.myTurn();
|
||||
}, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
useMafiaSounds(v);
|
||||
const [banner, showBanner] = useBanner();
|
||||
const [tileFx, setTileFx] = useState<TileFx | null>(null);
|
||||
useMafiaFx(v, players, showBanner, setTileFx);
|
||||
// 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));
|
||||
useEffect(() => {
|
||||
const night = isNight(v);
|
||||
const before = wasNight.current;
|
||||
wasNight.current = night;
|
||||
if (night === before || ph.kind === 'ended' || ph.kind === 'roleReveal') return;
|
||||
setSky({ kind: night ? 'night' : 'day', key: phaseKey });
|
||||
const t = setTimeout(() => setSky(null), 1800);
|
||||
return () => clearTimeout(t);
|
||||
}, [phaseKey]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
let pick: Pick = null;
|
||||
if (my?.alive && ph.kind === 'vote') pick = { ids: my.voteTargets, chosen: my.vote === 'abstain' ? null : my.vote, onPick: (id) => act({ type: 'vote', target: id }) };
|
||||
@@ -846,7 +921,7 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
{v.final && <FinalReveal v={v} players={players} />}
|
||||
<div className="mf-grid">
|
||||
<div className="mf-col mf-players">
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} />
|
||||
<Players v={v} players={players} me={me} pick={pick} pending={pending} fx={tileFx} />
|
||||
</div>
|
||||
<div className="mf-col mf-chatwrap">
|
||||
<ChatBox v={v} players={players} me={me} act={act} />
|
||||
@@ -858,6 +933,12 @@ function MafiaBoard({ view: v, me, players, act, pending }: BoardProps<MafiaView
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{sky && (
|
||||
<div key={sky.key} className={`mf-sky ${sky.kind}`} aria-hidden>
|
||||
<span>{sky.kind === 'night' ? '🌙' : '☀️'}</span>
|
||||
</div>
|
||||
)}
|
||||
{banner}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ 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 type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -35,6 +36,14 @@ function Stone({ color, cx, cy, r, ghost }: { color: Color; cx: number; cy: numb
|
||||
);
|
||||
}
|
||||
|
||||
/** A refused forbidden point (금수): a red mark pops up and "금수" floats away; the board gives a small shake. */
|
||||
const OMOK_CSS = `
|
||||
.om-forbid { transform-box: fill-box; transform-origin: center; animation: om-forbid .8s ease-out both; pointer-events: none; }
|
||||
@keyframes om-forbid { 0% { transform: scale(.3); opacity: 0; } 18% { transform: scale(1.25); opacity: 1; } 32% { transform: scale(1); } 75% { opacity: 1; } 100% { opacity: 0; } }
|
||||
.om-forbid-t { animation: om-forbid-t .9s ease-out both; pointer-events: none; }
|
||||
@keyframes om-forbid-t { 0% { transform: translateY(0); opacity: 0; } 20% { opacity: 1; } 100% { transform: translateY(-.9px); opacity: 0; } }
|
||||
`;
|
||||
|
||||
function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>) {
|
||||
const n = v.size;
|
||||
const myTurn = v.phase === 'playing' && v.myColor === v.turn;
|
||||
@@ -46,6 +55,25 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const prevCount = useRef(v.moveCount);
|
||||
const prevTurn = useRef(v.turn);
|
||||
const [refused, setRefused] = useState<{ p: Pt; key: number } | null>(null);
|
||||
const [banner, showBanner] = useBanner();
|
||||
useEffect(() => {
|
||||
if (!refused) return;
|
||||
const t = setTimeout(() => setRefused(null), 950);
|
||||
return () => clearTimeout(t);
|
||||
}, [refused]);
|
||||
|
||||
// The game is over: "오목!" for five in a row (who won underneath), otherwise just who won.
|
||||
const prevPhase = useRef(v.phase);
|
||||
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);
|
||||
}, [v.phase]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
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.
|
||||
@@ -83,6 +111,8 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
haptic([30, 30, 30]);
|
||||
sfx.bad();
|
||||
setAnnounce('여기는 금수 자리라 둘 수 없어요.');
|
||||
setRefused({ p, key: Date.now() });
|
||||
bump(svgRef.current, 'shake');
|
||||
return;
|
||||
}
|
||||
// Mouse: one click places (hover already shows the preview). Touch: optional two-step confirm.
|
||||
@@ -114,7 +144,8 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
setCursor((c) => ({ x: Math.min(n - 1, Math.max(0, c.x + d[e.key]![0])), y: Math.min(n - 1, Math.max(0, c.y + d[e.key]![1])) }));
|
||||
} else if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
if (canPlace(cursor)) place(cursor);
|
||||
// Same as a click: places, or explains a forbidden point.
|
||||
tap(cursor, true);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -122,7 +153,7 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
const pad = 0.9;
|
||||
return (
|
||||
<div className="board-wrap stack" style={{ gap: 10 }}>
|
||||
<style>{BOARD_MOTION_CSS}</style>
|
||||
<style>{BOARD_MOTION_CSS + OMOK_CSS}</style>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox={`${-pad} ${-pad} ${n - 1 + 2 * pad} ${n - 1 + 2 * pad}`}
|
||||
@@ -206,11 +237,34 @@ function OmokBoard({ view: v, act, pending, tapConfirm }: BoardProps<OmokView>)
|
||||
/>
|
||||
))}
|
||||
{ghost && v.myColor && <Stone color={v.myColor} cx={ghost.x} cy={ghost.y} r={0.46} ghost />}
|
||||
{refused && (
|
||||
<g key={refused.key} aria-hidden>
|
||||
<g className="om-forbid">
|
||||
<circle cx={refused.p.x} cy={refused.p.y} r={0.46} fill="rgba(220,38,38,.25)" stroke="#dc2626" strokeWidth={0.08} />
|
||||
<path d={`M ${refused.p.x - 0.22} ${refused.p.y - 0.22} L ${refused.p.x + 0.22} ${refused.p.y + 0.22} M ${refused.p.x + 0.22} ${refused.p.y - 0.22} L ${refused.p.x - 0.22} ${refused.p.y + 0.22}`} stroke="#dc2626" strokeWidth={0.12} strokeLinecap="round" />
|
||||
</g>
|
||||
<text
|
||||
className="om-forbid-t"
|
||||
x={refused.p.x}
|
||||
y={refused.p.y - 0.75}
|
||||
textAnchor="middle"
|
||||
fontSize={0.48}
|
||||
fontWeight={900}
|
||||
fill="#dc2626"
|
||||
stroke="#fff"
|
||||
strokeWidth={0.06}
|
||||
paintOrder="stroke"
|
||||
>
|
||||
금수
|
||||
</text>
|
||||
</g>
|
||||
)}
|
||||
{myTurn && kbd && <rect x={cursor.x - 0.5} y={cursor.y - 0.5} width={1} height={1} fill="none" stroke="var(--focus)" strokeWidth={0.06} />}
|
||||
</svg>
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner}
|
||||
{preview && myTurn && (
|
||||
<div className="row" style={{ justifyContent: 'center' }}>
|
||||
<button className="btn btn-primary" style={{ flex: 2 }} disabled={!canPlace(preview)} onClick={() => place(preview)}>
|
||||
|
||||
@@ -89,6 +89,9 @@ const CSS = `
|
||||
.pk-slot { width: 44px; height: 62px; }
|
||||
.pk-actions { grid-template-columns: repeat(2, 1fr); }
|
||||
}
|
||||
/* The face-down copy that turns away when a card is turned over (see turnOver). */
|
||||
.pk-back { position: fixed; z-index: 60; pointer-events: none; box-sizing: border-box; border-radius: 9% / 6.4%; background: #1e3a8a; border: 2px solid #fff;
|
||||
box-shadow: inset 0 0 0 3px #1e3a8a, inset 0 0 0 5px #93c5fd, 0 1px 3px rgba(0,0,0,.3); backface-visibility: hidden; }
|
||||
`;
|
||||
|
||||
// ---------------------------------------------------------------- seats
|
||||
@@ -320,6 +323,35 @@ function flipIn(el: Element | null | undefined, delay = 0): void {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A face-down card turned face up (showdown, 인디언 forehead): a face-down copy turns away on top of it, then the real
|
||||
* (already face-up) card turns in. The copy is fixed-position, never takes clicks and is removed when done.
|
||||
*/
|
||||
function turnOver(el: Element | null | undefined, delay = 0): void {
|
||||
if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return;
|
||||
const r = el.getBoundingClientRect();
|
||||
if (!r.width || !r.height) return;
|
||||
const half = 180;
|
||||
const back = document.createElement('div');
|
||||
back.className = 'pk-back';
|
||||
back.setAttribute('aria-hidden', 'true');
|
||||
Object.assign(back.style, { left: `${r.left}px`, top: `${r.top}px`, width: `${r.width}px`, height: `${r.height}px` });
|
||||
document.body.appendChild(back);
|
||||
const a = back.animate([{ transform: 'perspective(600px) rotateY(0deg)' }, { transform: 'perspective(600px) rotateY(-90deg)' }], { duration: half, delay, easing: 'ease-in', fill: 'both' });
|
||||
const done = () => back.remove();
|
||||
a.onfinish = done;
|
||||
a.oncancel = done;
|
||||
setTimeout(done, delay + half + 1500);
|
||||
(el as HTMLElement).animate(
|
||||
[
|
||||
{ transform: 'perspective(600px) rotateY(90deg)' },
|
||||
{ transform: 'perspective(600px) rotateY(-12deg)', offset: 0.65 },
|
||||
{ transform: 'perspective(600px) rotateY(0deg)' },
|
||||
],
|
||||
{ duration: 300, delay: delay + half, easing: 'ease-out', fill: 'backwards', composite: 'add' },
|
||||
);
|
||||
}
|
||||
|
||||
/** The card elements of a seat on the table (forehead, hole, choice, up — same order as SeatCards). */
|
||||
const seatCardEls = (id: string): Element[] => [...(seatEl(id)?.querySelector('[data-fx="seat-cards"]')?.children ?? [])];
|
||||
const myCardEl = (slot: string) => document.querySelector(`[data-fx="poker-mine"] [data-slot="${cssEsc(slot)}"]`);
|
||||
@@ -418,20 +450,20 @@ function usePokerFx(v: PokerView, me: string | null, players: Record<string, Pub
|
||||
if (!s || s.id === me) continue;
|
||||
const els = seatCardEls(s.id);
|
||||
const off = s.forehead !== undefined ? 1 : 0;
|
||||
const at = t + n * 160;
|
||||
for (let i = 0; i < s.hole.length; i++) flipIn(els[off + i], at + i * 40);
|
||||
later(at, sfx.cardFlip);
|
||||
const at = t + n * 220;
|
||||
for (let i = 0; i < s.hole.length; i++) turnOver(els[off + i], at + i * 60);
|
||||
later(at + 120, sfx.cardFlip);
|
||||
n++;
|
||||
}
|
||||
t += n * 160 + 100;
|
||||
t += n * 220 + 200;
|
||||
}
|
||||
// 인디언: my own forehead card is shown at the end of the hand.
|
||||
const myNow = v.seats.find((s) => s.id === me);
|
||||
const myBefore = p.seats.find((s) => s.id === me);
|
||||
if (myNow?.forehead && myBefore && !myBefore.forehead) {
|
||||
flipIn(myCardEl('f'), t);
|
||||
later(t, sfx.cardFlip);
|
||||
t += 160;
|
||||
turnOver(myCardEl('f'), t);
|
||||
later(t + 120, sfx.cardFlip);
|
||||
t += 300;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/** 루미큐브 화면 (docs/games/rummikub.md §9). Tap a tile to pick it up, then tap where it goes. */
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties } from 'react';
|
||||
// Pure tile/set helpers only (no zod): keeps this lazy chunk small.
|
||||
import { findMeld, normalizeSet, pickDisjoint, setProblem, sortTiles, tileLabel, tileOf, type DraftSet, type JokerAs, type TileColor } from '@bg/games/rummikub/rules';
|
||||
import type { LogEntry, RummikubOptions, RummikubView } from '@bg/games/rummikub';
|
||||
@@ -7,6 +7,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 { bump, cssEsc, flyFrom, flyGhost, fxEl, seatEl, useBanner, useNewEntries } from '../card-fx';
|
||||
import type { BoardProps, GameUI, OptionsProps } from '../types';
|
||||
import { helpNow } from './help';
|
||||
import { quickStart } from './quick';
|
||||
@@ -74,10 +75,9 @@ function Bump({ value, children }: { value: number; children: React.ReactNode })
|
||||
const CSS = `
|
||||
.rk-root { position: relative; width: 100%; align-self: stretch; flex: 1; min-height: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.rk-bump { display: inline-block; }
|
||||
.rk-banner { position: fixed; z-index: 40; top: 34%; left: 0; right: 0; margin: 0 auto; width: max-content; max-width: 92vw; text-align: center;
|
||||
padding: 12px 26px; border-radius: 18px; font-size: clamp(1.4rem, 5vw, 2.2rem); font-weight: 900; letter-spacing: -.01em;
|
||||
background: linear-gradient(#fffdf7, #f1e7cf); color: #111827; border: 2px solid #c9b98f; box-shadow: 0 4px 0 #b5a172, 0 12px 30px rgba(0,0,0,.35); }
|
||||
.rk-banner.big { background: linear-gradient(#fde68a, #f59e0b); border-color: #b45309; box-shadow: 0 4px 0 #92400e, 0 12px 30px rgba(0,0,0,.35); }
|
||||
/* A face-down tile flying from the pool to someone's seat (card-fx ghost). */
|
||||
.fx-ghost.rk-ghost { width: 30px; height: 42px; border-radius: 6px; background: linear-gradient(#fffdf7, #e8dcbc); border: 1px solid #c9b98f;
|
||||
box-shadow: 0 2px 0 #b5a172, 0 4px 8px rgba(0,0,0,.3); }
|
||||
.rk-players { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.rk-player { display: flex; align-items: center; gap: 6px; background: var(--surface); color: var(--text); border: 3px solid transparent;
|
||||
border-radius: 12px; padding: 4px 10px 4px 6px; box-shadow: var(--shadow); font-size: .9rem; min-height: 44px; }
|
||||
@@ -148,7 +148,6 @@ button.rk-tile:disabled { cursor: default; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.rk-tile { transition: none; }
|
||||
.rk-banner { display: none; }
|
||||
.rk-set.changed { animation: none; box-shadow: 0 0 0 3px #fde047; }
|
||||
}
|
||||
`;
|
||||
@@ -203,13 +202,13 @@ function Tile({ id, size = 'md', as, selected, hint, fresh, anim, style, onClick
|
||||
const dataC = t.kind === 'num' ? t.color : undefined;
|
||||
if (!onClick) {
|
||||
return (
|
||||
<span className={cls} data-c={dataC} role="img" aria-label={label} style={style}>
|
||||
<span className={cls} data-c={dataC} data-tile={id} role="img" aria-label={label} style={style}>
|
||||
{body}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<button type="button" className={cls} data-c={dataC} aria-pressed={!!selected} aria-label={label} onClick={onClick} style={style}>
|
||||
<button type="button" className={cls} data-c={dataC} data-tile={id} aria-pressed={!!selected} aria-label={label} onClick={onClick} style={style}>
|
||||
{body}
|
||||
</button>
|
||||
);
|
||||
@@ -257,13 +256,16 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
const [announce, setAnnounce] = useState('');
|
||||
const wasMine = useRef(false);
|
||||
const lastLog = useRef<string>('');
|
||||
// Animations: tiles flying onto my rack, tiles newly on the table, a shaking area, a big banner.
|
||||
// Animations: tiles dealt onto my rack, a shaking area, a big banner (tile flights use card-fx, see below).
|
||||
const [fly, setFly] = useTimed<{ ids: string[]; gap: number }>();
|
||||
const [pop, setPop] = useTimed<Set<string>>();
|
||||
const [shake, setShake] = useTimed<string>();
|
||||
const [banner, setBanner] = useTimed<{ text: string; big: boolean; seq: number }>();
|
||||
const bannerSeq = useRef(0);
|
||||
const showBanner = (text: string, big = false) => setBanner({ text, big, seq: ++bannerSeq.current }, 1700);
|
||||
const [banner, showBanner] = useBanner();
|
||||
/** Where the tiles I just moved were (captured on the tap), so they fly from there to their new place. */
|
||||
const movedFrom = useRef<Map<string, DOMRect> | 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<ReturnType<typeof setTimeout> | undefined>(undefined);
|
||||
useEffect(() => () => clearTimeout(winTimer.current), []);
|
||||
const snap = useRef<{ log: string; gameNo: number; phase: string; turnNo: number; edits: number; melded: Record<string, boolean>; table: Set<string> } | null>(null);
|
||||
|
||||
const serverSets: DraftSet[] = useMemo(
|
||||
@@ -303,7 +305,8 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
}, [v.log]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Sounds + animations for what everybody did, from view changes only (the first view is just recorded).
|
||||
useEffect(() => {
|
||||
// A layout effect, so tiles that just appeared can still be sent flying before they are painted in place.
|
||||
useLayoutEffect(() => {
|
||||
const e = v.log[v.log.length - 1];
|
||||
const now = {
|
||||
log: e ? `${v.match.gameNo}-${e.turn}-${e.kind}-${e.by}` : '',
|
||||
@@ -331,22 +334,20 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
const name = nick(players, e.by);
|
||||
if (e.kind === 'commit' || e.kind === 'timeoutCommit') {
|
||||
snd.places(e.count);
|
||||
const added = [...now.table].filter((id) => !prev.table.has(id));
|
||||
if (!mineMove && added.length) setPop(new Set(added), 900);
|
||||
const firstMeld = !prev.melded[e.by] && now.melded[e.by];
|
||||
if (mineMove || firstMeld) sfx.good();
|
||||
if (firstMeld && !(v.phase !== 'playing' && v.round?.endReason === 'rackEmpty')) showBanner(mineMove ? '첫 등록 성공!' : `${name}님 첫 등록!`);
|
||||
if (firstMeld && !(v.phase !== 'playing' && v.round?.endReason === 'rackEmpty')) showBanner('첫 등록!', 'green', mineMove ? '바닥에 처음 내려놓았어요' : `${name}님`);
|
||||
} else if (e.kind === 'draw' || e.kind === 'timeoutDraw') {
|
||||
snd.draw();
|
||||
if (mineMove && v.my?.lastDrawn.length) setFly({ ids: v.my.lastDrawn, gap: 90 }, 900);
|
||||
drawFx(e.by, mineMove ? (v.my?.lastDrawn ?? []) : [], e.count || 1, 90);
|
||||
} else if (e.kind === 'penalty') {
|
||||
sfx.bad();
|
||||
for (let i = 0; i < Math.min(e.count, 3); i++) snd.draw(250 + i * 160);
|
||||
setShake(mineMove ? 'rack' : `p:${e.by}`, 500);
|
||||
drawFx(e.by, mineMove ? (v.my?.lastDrawn ?? []) : [], e.count, 120);
|
||||
if (mineMove) {
|
||||
haptic([60, 40, 60]);
|
||||
if (v.my?.lastDrawn.length) setFly({ ids: v.my.lastDrawn, gap: 120 }, 1100);
|
||||
showBanner(`벌칙! ${e.count}장 가져오기`);
|
||||
showBanner(`벌칙! ${e.count}장`, 'red', '묶음을 다 맞추지 못했어요');
|
||||
}
|
||||
} else if (e.kind === 'pass') {
|
||||
sfx.whoosh();
|
||||
@@ -355,14 +356,57 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
// Somebody else is moving tiles around in their turn.
|
||||
snd.shuffleQuiet();
|
||||
}
|
||||
// The round is over: "다 냈다!" (the match result sound itself is played by the room page).
|
||||
if (prev.phase === 'playing' && v.phase !== 'playing' && v.round?.endReason === 'rackEmpty') {
|
||||
// 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;
|
||||
showBanner(w.includes(me ?? '') ? '다 냈다!' : `${w.map((p) => nick(players, p)).join(', ')}님 다 냈다!`, true);
|
||||
if (v.phase === 'roundEnd') sfx.fanfare();
|
||||
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', '더 낼 수 있는 사람이 없어요');
|
||||
}
|
||||
// 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' ? 1500 : 0);
|
||||
}
|
||||
}, [v]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
/** Tiles drawn from the pool: mine fly out of it onto my rack, anyone else's as face-down tiles to their seat. */
|
||||
const drawFx = (by: string, mineIds: string[], n: number, gap: number) => {
|
||||
const pool = fxEl('rk-pool');
|
||||
if (by === me) mineIds.forEach((id, i) => flyFrom(document.querySelector(`.rk-rack [data-tile="${cssEsc(id)}"]`), pool, { delay: i * gap, rotate: 8 }));
|
||||
else flyGhost(pool, seatEl(by), { className: 'rk-ghost', count: Math.min(n, 6), gap });
|
||||
};
|
||||
|
||||
// Tiles I moved (rack ↔ table, between sets) slide from where I tapped them.
|
||||
useLayoutEffect(() => {
|
||||
const from = movedFrom.current;
|
||||
if (!from) return;
|
||||
movedFrom.current = null;
|
||||
[...from].forEach(([id, r], i) => flyFrom(document.querySelector(`.rk-root [data-tile="${cssEsc(id)}"]`), r, { ms: 300, delay: i * 35, scale: 0.9, rotate: 0 }));
|
||||
});
|
||||
// Tiles that newly show up on the table in somebody else's turn (their live draft or their commit) fly from their seat.
|
||||
const tableIds = useMemo(() => (mine ? [] : sets.flatMap((d) => d.tileIds)), [mine, sets]);
|
||||
useNewEntries(
|
||||
tableIds,
|
||||
(id) => id,
|
||||
(fresh) => {
|
||||
const by = prevCurrent.current;
|
||||
if (!by || by === me) return;
|
||||
const seat = seatEl(by);
|
||||
fresh.forEach((id, i) => flyFrom(document.querySelector(`.rk-table [data-tile="${cssEsc(id)}"]`), seat, { delay: i * 60, rotate: -8 }));
|
||||
},
|
||||
20,
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
prevCurrent.current = v.current;
|
||||
});
|
||||
|
||||
// Drop selected tiles that disappeared (e.g. after undo on the server).
|
||||
useEffect(() => {
|
||||
setSel((s) => (s.every((id) => inSets.has(id) || rack.includes(id)) ? s : s.filter((id) => inSets.has(id) || rack.includes(id))));
|
||||
@@ -391,6 +435,12 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
else setMsg('');
|
||||
const next = moveTiles(sets, sel, target, onTable0);
|
||||
if (!next) return;
|
||||
const rects = new Map<string, DOMRect>();
|
||||
for (const id of sel) {
|
||||
const el = document.querySelector(`.rk-root [data-tile="${cssEsc(id)}"]`);
|
||||
if (el) rects.set(id, el.getBoundingClientRect());
|
||||
}
|
||||
movedFrom.current = rects;
|
||||
snd.place();
|
||||
setSel([]);
|
||||
send(next);
|
||||
@@ -458,7 +508,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
{showingDraft && !mine ? `${curName}님이 고민 중인 배치` : mine && my?.changed ? '바닥(확정 전)' : '바닥'}
|
||||
{thinking && !showingDraft ? ` · ${curName}님이 생각 중…` : ''}
|
||||
</span>
|
||||
<span aria-label={`남은 타일 ${v.poolCount}장`}>
|
||||
<span aria-label={`남은 타일 ${v.poolCount}장`} data-fx="rk-pool">
|
||||
남은 타일 <Bump value={v.poolCount}>{v.poolCount}</Bump>장
|
||||
</span>
|
||||
</div>
|
||||
@@ -493,7 +543,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
</button>
|
||||
)}
|
||||
{d.tileIds.map((id) => (
|
||||
<Tile key={id} id={id} size="sm" as={jokerAs[id]} selected={sel.includes(id)} anim={pop?.has(id) ? 'anim-pop' : undefined} onClick={mine ? () => toggle(id) : undefined} />
|
||||
<Tile key={id} id={id} size="sm" as={jokerAs[id]} selected={sel.includes(id)} onClick={mine ? () => toggle(id) : undefined} />
|
||||
))}
|
||||
{mine && sel.length > 0 && (
|
||||
<button type="button" className="rk-slot" aria-label={`묶음 ${i + 1} 뒤에 놓기`} onClick={() => move({ set: i, at: 'end' })}>
|
||||
@@ -592,7 +642,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className={`rk-rack${shake === 'rack' ? ' anim-shake' : ''}`} role="group" aria-label="내 받침대">
|
||||
<div className={`rk-rack${shake === 'rack' ? ' anim-shake' : ''}`} role="group" aria-label="내 받침대" data-fx="rk-rack">
|
||||
{rack.length === 0 && <span className="rk-rack-empty">{my.rack.length ? '모두 바닥에 놓았어요.' : '타일이 없어요.'}</span>}
|
||||
{rack.map((id) => {
|
||||
const k = fly ? fly.ids.indexOf(id) : -1;
|
||||
@@ -616,11 +666,7 @@ function RummikubBoard({ view: v, me, players, act, pending, deadline }: BoardPr
|
||||
<p className="sr-only" aria-live="polite">
|
||||
{announce}
|
||||
</p>
|
||||
{banner && (
|
||||
<div key={banner.seq} className={`rk-banner anim-banner${banner.big ? ' big' : ''}`} aria-hidden>
|
||||
{banner.text}
|
||||
</div>
|
||||
)}
|
||||
{banner}
|
||||
{confirm === 'draw' && (
|
||||
<ConfirmSheet
|
||||
title="놓은 타일을 되돌리고 한 장 가져올까요?"
|
||||
@@ -654,6 +700,7 @@ function Players({ v, me, players, deadline, shake }: { v: RummikubView; me: str
|
||||
<div
|
||||
key={s.id}
|
||||
role="listitem"
|
||||
data-fx-seat={s.id}
|
||||
className={`rk-player${turn ? ' turn' : ''}${s.left || !s.inRound ? ' gone' : ''}${shake === `p:${s.id}` ? ' anim-shake' : turn && v.phase === 'playing' ? ' anim-glow' : ''}`}
|
||||
aria-label={`${u.nickname}${s.id === me ? '(나)' : ''}, 타일 ${s.tiles}장, ${s.melded ? '첫 등록 함' : '첫 등록 전'}${turn ? ', 지금 차례' : ''}${s.left ? ', 나감' : s.away ? ', 자리 비움' : ''}`}
|
||||
>
|
||||
|
||||
@@ -238,6 +238,7 @@ interface BadukResult {
|
||||
- 사석 확인 단계: 판 위에 사석은 반투명 + ×, 집은 작은 사각 표시, 하단에 "흑 39 : 백 36.5" 미리보기, 큰 "동의" / "이의(대국 재개)" 버튼. 상대가 표시를 바꾸면 바뀐 그룹을 강조.
|
||||
- 규칙 보기: 따내기, 자충수, 패, 집 세는 법 그림 설명. 초보 모드에서 9줄 추천.
|
||||
- 관전자: 계가 미리보기 보기 가능, 버튼 없음.
|
||||
- 움직임 더하기(2026-10-13): 패스하면 "패스" 배너, 둘 다 패스해 계가로 넘어가면 "계가" 배너와 휙 소리. 계가가 시작될 때(사석 확인·결과) 집 표시가 왼쪽 위부터 차례로 톡톡 나타나고, 사석 표시를 바꿔 새로 생긴 집 표시도 톡 튀어나온다. 대국이 끝나면 "흑 승리!" / "백 승리!" / "무승부" 배너(아래에 "흑 2집 반 승" 같은 결과)와 오른쪽 결과 칸의 "흑 ○ : 백 ○"가 1초 동안 0부터 올라간다(화면을 보고 있을 때만, 화면 읽기에는 최종 점수).
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [ ] 1점 따내기, 여러 연결 동시 따내기, 가장자리·귀에서 따내기.
|
||||
|
||||
@@ -147,6 +147,7 @@ interface ClueState {
|
||||
- 반증: 반증자에게만 보여 줄 카드 버튼이 뜬다. 추리한 사람에게는 받은 카드가 크게 보인다.
|
||||
- 추리 노트: 21장 목록, 내 카드·공개 카드·나에게 보여 준 카드는 자동 ✗(누가 보여 줬는지 함께), 나머지는 눌러서 ✗ → ? → ✓. `localStorage` 키 `bg:clue:note:<방 코드>:<게임 번호>` — 기기에만 저장.
|
||||
- 키보드: 모든 방·칩·카드·노트가 버튼. 스크린리더: 방마다 "식당, 5칸, 들어갈 수 있어요, 말: …, 흉기: …", 추리·반증 결과를 aria-live로 읽음. 다크 모드는 공통 색 변수.
|
||||
- 움직임 더하기(2026-10-13): 말과 흉기는 움직일 때(내 이동, 남의 이동, 추리로 방에 끌려올 때) 원래 자리에서 새 자리로 살짝 튀어 오르며 미끄러져 간다(지도 기준이라 스크롤해도 맞음). 추리하면 고른 세 장(용의자·흉기·장소)이 추리한 사람의 말에서 가운데 "사건 봉투"로 날아간다. 카드를 보여 주면 나에게 보여 준 카드는 뒤집히며 나타나고(`anim-flip`), 다른 사람 화면에는 뒤집힌 카드 한 장이 보여 준 사람의 말에서 추리한 사람의 말로 날아간다. 날아가는 카드는 클릭을 막지 않고, 동작 줄이기 설정이면 움직이지 않는다.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 인원별 손패/공개 장수, 봉투가 손패·공개 카드와 겹치지 않음, 스칼렛 선, 흉기 6곳 (`clue.test.ts`)
|
||||
|
||||
@@ -128,6 +128,7 @@ interface LiarState {
|
||||
- PC 세 칸: 사람들(말하는 순서 번호, 말하는 중·투표함·라이어·나감 표시, 투표 때 초록 테두리로 고르기) / 설명 기록(바퀴별) + 토론 채팅 / 할 일(확인·설명 입력·토론 끝내기·투표 안내·정답 입력 또는 단어 목록). 좁은 화면은 할 일 → 사람들 → 설명·채팅 순으로 쌓인다(320px까지).
|
||||
- 게임 중 방 채팅·빠른 반응은 닫힌다(`ownChat`). 끝나면 최종 공개 표(역할·점수).
|
||||
- 30초 요약 카드 3장, [?] 도움말은 보는 사람에 맞게(라이어/시민/관전, 바보 모드 라이어는 시민과 똑같은 글).
|
||||
- 움직임 더하기(2026-10-13): 투표 결과는 적은 표부터 한 줄씩(0.35초 간격) 나오며 줄마다 작은 칩 소리. 다 나오면 지목된 사람에게 스포트라이트(그 칸만 밝고 나머지가 어두워짐, 칸이 화면 밖이면 칸만 빛남)가 떨어지고 칸이 빛나며 흔들린 뒤 배너: 라이어를 잡으면 "잡았다!", 아니면 "헛다리!". 동점이면 "동점!" / "또 동점!". 라이어의 정답은 "정답!"(빨강) / "땡!"(초록), 끝에 "라이어 승리!" / "시민 승리!" 배너. 하나가 끝나야 다음이 나오고(1.5초 간격), 클릭을 막지 않으며 동작 줄이기 설정이면 움직이지 않는다.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [x] 제시어 은행: 주제 10개, 단어 15개 이상, 설명 4개 이상, 설명에 단어 없음, 고운 말 필터 (`liar.test.ts`)
|
||||
|
||||
@@ -230,6 +230,7 @@ interface MafiaResult {
|
||||
- 투표 결과 애니메이션: 득표 막대. 처형/사망 발표는 큰 카드 팝업.
|
||||
- 어린이용: 직업 설명 그림 카드, "규칙 보기"에 낮/밤 흐름 그림.
|
||||
- PC: 왼쪽 플레이어 목록, 가운데 채팅, 오른쪽 행동 패널.
|
||||
- 움직임 더하기(2026-10-13): 밤이 되면 화면 전체가 잠깐 남색으로 어두워지며 달이 떠오르고, 아침이 되면 밝은 빛과 해가 떠오른다(1.7초, 클릭을 막지 않음). 득표 막대는 적은 표부터 한 줄씩(0.35초 간격) 자라고 표 수가 톡 튀어나온다. 탈락한 사람의 칸은 한 번 뒤집히며 흐려지고 배너("○○님 탈락", 아래에 어떻게·직업)가 뜬다. 의사·군인이 살리거나 찬반에서 살아남으면 초록 배너("살았다!" / "버텼다!" / "살아남았다!" / "정치인!"), 조용한 밤은 "조용한 밤". 이긴 쪽은 "시민 팀 승리!"(파랑) / "마피아 팀 승리!"(빨강) 배너. 아침 발표는 해가 뜬 뒤(0.9초) 차례로 1.5초씩 보여 준다. 모두 누구의 행동이든 화면 변화에 반응하고, 동작 줄이기 설정이면 움직이지 않는다.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [ ] 4~12인 자동 배분이 표와 일치, 추가 직업 선택 시 시민 수만큼만 대체, 부족하면 대기실 거부.
|
||||
|
||||
@@ -296,6 +296,7 @@ interface OmokResult {
|
||||
- 규칙 보기: 선택된 규칙 모드의 요약 + 예시 그림(5.3의 예 A~D).
|
||||
- PC: 판 좌측, 기보·채팅 우측.
|
||||
- 관전자: 판 위에 "관전 중" 배지, 기보 되돌려 보기(관전자 로컬에서만).
|
||||
- 움직임 더하기(2026-10-13): 금수 자리를 누르거나(키보드 Enter 포함) 두려 하면 그 자리에 빨간 ✕ 표시가 튀어나오고 "금수" 글자가 떠오르며 판이 살짝 흔들린다. 다섯 줄이 완성되면 "오목!" 배너(아래에 "흑 승리"), 기권·시간 등으로 끝나면 "흑 승리" / "백 승리" / "무승부" 배너.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
- [ ] 가로/세로/↘/↗ 4방향 각각 5목 완성 시 승리, 판 가장자리에 닿는 5목도 승리.
|
||||
|
||||
@@ -625,6 +625,7 @@ interface PokerResult /* extends GameResult */ {
|
||||
- 첫 핸드에서 말풍선 튜토리얼(끌 수 있음). 내 차례에 진동/소리(설정에서 끄기), 남은 시간 원형 게이지, 5초 남으면 빨간색.
|
||||
- 접근성: 무늬는 색 + 모양 + 글자(♠ 검정, ◆ 파랑, ♥ 빨강, ♣ 초록 4색 덱 옵션)로 구분, 큰 글씨 모드.
|
||||
- 카드 그림(2026-10-13): 숫자 카드·뒷면·큰 모서리 글자(숫자+무늬)는 `PlayingCard`가 직접 그리고, J·Q·K 12장과 조커 2장은 Dmitry Fomin의 실제 카드 그림(Wikimedia Commons "SVG English pattern playing cards", "Atlas deck joker", CC0 1.0)을 쓴다. 그림카드는 진짜 카드처럼 테두리 안에 그림을 넣고 왼쪽 위만 비워 큰 모서리 글자가 잘 보이게 했다. 원본 SVG에서 그림 부분만(조커는 광대만) 잘라 높이 282px WebP 14장(합계 약 250KB)으로 줄였고, 그 카드가 화면에 나올 때만 따로 받는다. 출처는 `apps/web/src/components/cards/court/ATTRIBUTION.txt`, 규칙 보기 맨 아래 작은 글씨(`PLAYING_CARD_CREDIT`).
|
||||
- 움직임 더하기(2026-10-13): 쇼다운 때 남의 숨긴 카드는 뒷면이 돌아가 사라진 뒤 앞면이 돌아 나오는 진짜 뒤집기로 한 자리씩(0.22초 간격) 보인다. 인디언 포커에서 내 이마 카드가 공개될 때도 같다.
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
|
||||
|
||||
@@ -292,14 +292,15 @@ interface GameResult {
|
||||
### 9.1 소리·움직임
|
||||
소리는 모두 화면 안에서 합성한다(플라스틱 타일 "딱" 소리 = 짧은 잡음 + 높은 음). 상대·컴퓨터의 행동은 화면 정보가 바뀔 때 울리고, 처음 들어왔을 때·다시 접속했을 때는 울리지 않는다. 내 타일 옮기기처럼 서버에 보이지 않는 조작만 누르는 순간 울린다.
|
||||
- 타일 고르기: 가벼운 "틱". 바닥·받침대에 놓기: "딱". 되돌리기·처음으로: 휙.
|
||||
- 확정(누구든): 놓은 장수만큼 "딱딱딱"(최대 5번). 내 확정이면 성공음이 더해진다. 다른 사람이 새로 놓은 타일은 톡 튀어나오고(anim-pop), 바뀐 묶음은 노랗게 반짝인다.
|
||||
- 첫 등록: 성공음 + 배너("첫 등록 성공!" / "○○님 첫 등록!").
|
||||
- 타일 옮기기(내 화면): 고른 타일이 원래 자리(받침대·다른 묶음)에서 놓은 자리로 미끄러져 간다(`flyFrom`).
|
||||
- 확정(누구든): 놓은 장수만큼 "딱딱딱"(최대 5번). 내 확정이면 성공음이 더해진다. 다른 사람이 바닥에 새로 놓은 타일(보이는 초안 포함)은 그 사람 칸에서 날아오고, 바뀐 묶음은 노랗게 반짝인다.
|
||||
- 첫 등록: 성공음 + 배너("첫 등록!", 아래에 누가 했는지).
|
||||
- 틀린 확정(서버가 받아 주지 않을 때): 실패음 + 바닥이 흔들린다(anim-shake).
|
||||
- 한 장 가져오기(누구든): 미끄러지는 소리 뒤에 "딱". 내가 가져온 타일은 받침대 위쪽에서 날아와 꽂힌다(anim-deal).
|
||||
- 벌칙(3장 등): 실패음 + 장수만큼 가져오는 소리. 내 벌칙이면 받침대가 흔들리고 배너, 다른 사람이면 그 사람 칸이 흔들린다.
|
||||
- 한 장 가져오기(누구든): 미끄러지는 소리 뒤에 "딱". 내가 가져온 타일은 "남은 타일"에서 받침대로 날아오고, 다른 사람이 가져가면 뒤집힌 타일이 그 사람 칸으로 날아간다(`flyGhost`).
|
||||
- 벌칙(3장 등): 실패음 + 장수만큼 가져오는 소리와 날아가는 타일. 내 벌칙이면 받침대가 흔들리고 배너("벌칙! 3장"), 다른 사람이면 그 사람 칸이 흔들린다.
|
||||
- 넘기기: 휙. 다른 사람이 자기 차례에 타일을 옮기는 중이면 아주 작은 "딱".
|
||||
- 새 판: 섞는 소리 + 나눠 주는 소리, 받침대 14장이 차례로 날아온다.
|
||||
- 다 냈다: 큰 배너. 다음 판이 남아 있으면 팡파르(게임 전체가 끝날 때의 승리·패배음은 방 화면이 낸다).
|
||||
- 다 냈다: 큰 배너 "루미큐브!"(누가 다 냈는지)와 그 사람 칸이 통 튄다. 다음 판이 남아 있으면 팡파르. 더 낼 사람이 없어 끝나면 "판 끝" 배너. 게임이 끝나면 이어서 승리 배너("승리!" / "○○님 승리"). 게임 전체의 승리·패배음은 방 화면이 낸다. 배너는 공통 `useBanner`.
|
||||
- 내 차례: 기존 차례 알림음. 지금 차례인 사람 칸은 은은하게 빛난다(anim-glow). 남은 타일 수·사람별 타일 수가 바뀌면 숫자가 통 튄다(anim-bump).
|
||||
|
||||
## 10. 테스트 체크리스트
|
||||
|
||||
Reference in New Issue
Block a user