/** 달무티 화면 (docs/games/dalmuti.md §9). */ import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type KeyboardEvent, type ReactNode } from 'react'; import type { Choice, DCard, DalmutiOptions, DalmutiView, LogEntry, PlayView, SeatView, Title } from '@bg/games/dalmuti'; import type { PublicUser } from '@bg/shared/lite'; import { Avatar } from '../../components/ui'; import { TurnTimer } from '../../components/TurnTimer'; import { haptic, noise, sfx, sounds, tone } from '../../lib/feedback'; import { bump, cssEsc, flyFrom, flyGhost, fxEl, reducedMotion, seatEl, useBanner, useNewEntries } from '../card-fx'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; import { quickStart } from './quick'; const JESTER = 13; /** Same names as the rules module (kept here so the screen chunk does not pull in the rules code). */ const CARD_NAME: Record = { 1: '왕', 2: '왕비', 3: '재상', 4: '공작', 5: '백작', 6: '기사', 7: '학자', 8: '상인', 9: '요리사', 10: '목동', 11: '광부', 12: '농부', 13: '광대', }; const CARD_HUE: Record = { 1: '#b7791f', 2: '#7c3aed', 3: '#4338ca', 4: '#1d4ed8', 5: '#0f766e', 6: '#15803d', 7: '#4d7c0f', 8: '#a16207', 9: '#c2410c', 10: '#9a3412', 11: '#475569', 12: '#57534e', }; const TITLE_ICON: Record = { 대달무티: '👑', 소달무티: '🎩', 평민: '🙂', 소농노: '🌾', 대농노: '🧺' }; const TIP_KEY = 'dm-tip-hidden'; const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; const cardName = (n: number) => (n === JESTER ? '광대' : `${n} ${CARD_NAME[n]}`); const rankText = (rank: number) => (rank === JESTER ? '광대(13)' : String(rank)); const setText = (p: { rank: number; count: number }) => `${rankText(p.rank)} × ${p.count}장`; const facesText = (cards: number[]) => cards.map((n) => (n === JESTER ? '광대' : String(n))).join(', '); /** 달무티 sounds on top of the shared palette (synthesized, no files). */ const dmSfx = { /** A set lands on the pile: one slap per card. */ set: (n: number) => { for (let i = 0; i < Math.min(n, 6); i++) noise(60, 0.15, i * 55, 'bandpass', 1500 + i * 120, 0.9); tone(220, 70, 'sine', 0.09, Math.min(n - 1, 5) * 55); }, /** Soft double knock on the table (pass). */ knock: () => { tone(190, 70, 'sine', 0.14); noise(35, 0.06, 0, 'lowpass', 700); tone(165, 70, 'sine', 0.12, 120); noise(35, 0.05, 120, 'lowpass', 700); }, /** 혁명 / 대혁명: drum roll, falling growl, then a big chord (higher and longer for 대혁명). */ revolution: (great: boolean) => { for (let i = 0; i < 7; i++) noise(90, 0.1 + i * 0.012, i * 55, 'lowpass', 320); tone(130, 520, 'sawtooth', 0.06, 0, { slideTo: great ? 55 : 80 }); [392, 494, 587, 784].forEach((f, i) => tone(f, 420, 'square', 0.045, 420 + i * 35)); if (great) [523, 659, 784, 1046].forEach((f, i) => tone(f, 520, 'square', 0.045, 820 + i * 35)); }, /** Tax card slides over (with a little coin ring). */ tax: () => { noise(140, 0.1, 0, 'bandpass', 1200, 0.6); tone(660, 80, 'triangle', 0.07, 120); tone(990, 130, 'triangle', 0.06, 190); }, /** Card given back: slide + a lower note. */ give: () => { noise(140, 0.1, 0, 'bandpass', 1000, 0.6); tone(520, 110, 'triangle', 0.06, 120); }, }; /** Where my last played set was (its button may be gone once the view arrives), so the pile cards fly from there. */ let myPlayRect: DOMRect | null = null; const rememberPlay = (rank: number) => { myPlayRect = document.querySelector(`.dm-group[data-n="${cssEsc(String(rank))}"]`)?.getBoundingClientRect() ?? null; }; /** Brief dim of a seat (pass). */ function dim(el: Element | null): void { if (!el || reducedMotion() || typeof (el as HTMLElement).animate !== 'function') return; (el as HTMLElement).animate([{ opacity: 1 }, { opacity: 0.4, offset: 0.35 }, { opacity: 1 }], { duration: 650, easing: 'ease-out' }); } const CSS = ` .dm { width: 100%; max-width: 1080px; display: flex; flex-direction: column; gap: 10px; align-self: center; } .dm-tip { display: flex; align-items: center; gap: 8px; background: var(--primary-soft); color: var(--text); border-radius: 12px; padding: 6px 6px 6px 12px; font-weight: 700; font-size: .95rem; } .dm-tip span { flex: 1; min-width: 0; } .dm-tip button { min-width: 40px; min-height: 40px; border: 0; border-radius: 10px; background: transparent; color: var(--text); font-size: 1.1rem; cursor: pointer; } .dm-seats { display: flex; flex-wrap: wrap; gap: 6px; margin: 0; padding: 0; list-style: none; justify-content: center; } .dm-seat { position: relative; flex: 0 1 124px; min-width: 104px; background: var(--surface); color: var(--text); border-radius: 12px; padding: 6px 8px; border: 3px solid transparent; box-shadow: var(--shadow); display: flex; flex-direction: column; gap: 2px; font-size: .88rem; animation: dm-in .35s ease both; } .dm-seat.turn { border-color: var(--focus); } .dm-seat.anim-glow { animation: anim-glow 1.4s ease-in-out infinite; } .dm-seat.me { background: var(--primary-soft); } .dm-seat.out { opacity: .7; } .dm-seat .nm { font-weight: 800; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; min-width: 0; } .dm-seat .ttl { font-weight: 800; font-size: .8rem; color: var(--text-sub); white-space: nowrap; } .dm-seat .meta { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; min-height: 22px; } .dm-count { display: inline-flex; align-items: center; gap: 4px; font-weight: 800; font-variant-numeric: tabular-nums; } .dm-count i { display: inline-block; width: 11px; height: 15px; border-radius: 3px; background: #7c2d12; border: 1.5px solid #fdba74; } .dm-badge { display: inline-block; border-radius: 999px; padding: 0 7px; font-weight: 800; font-size: .76rem; line-height: 1.6; white-space: nowrap; } .dm-bubble { position: absolute; top: -10px; right: -4px; background: #fff; color: #1f2937; border: 2px solid #9ca3af; border-radius: 10px; padding: 0 6px; font-weight: 800; font-size: .76rem; animation: dm-pop .25s ease; } .dm-order { font-size: .78rem; color: var(--text-sub); text-align: center; margin: -4px 0 0; } .dm-table { position: relative; border-radius: 22px; background: radial-gradient(ellipse at center, rgba(255,255,255,.12), rgba(255,255,255,0) 65%), var(--felt); border: 8px solid var(--wood); box-shadow: var(--shadow); padding: 14px; min-height: 200px; color: #fff; display: flex; flex-direction: column; gap: 10px; align-items: center; justify-content: center; } .dm-now { font-size: 1.6rem; font-weight: 900; text-shadow: 0 1px 3px rgba(0,0,0,.5); text-align: center; line-height: 1.25; } .dm-now small { display: block; font-size: .95rem; font-weight: 700; opacity: .92; } .dm-pile { display: flex; align-items: flex-end; gap: 14px; justify-content: center; flex-wrap: wrap; } .dm-prev { display: flex; gap: 6px; opacity: .8; } .dm-prev .dm-card .nm { display: none; } .dm-set { display: flex; } .dm-set > .dm-card + .dm-card { margin-left: calc(var(--w) * -0.55); } .dm-card { --w: 60px; position: relative; flex: none; width: var(--w); height: calc(var(--w) * 1.4); border-radius: calc(var(--w) * .13); background: #fffdf7; color: #1f2937; border: 2px solid var(--c, #444); box-shadow: 0 2px 4px rgba(0,0,0,.28); display: flex; flex-direction: column; align-items: center; overflow: hidden; font-family: inherit; } .dm-card .band { width: 100%; background: var(--c, #444); color: #fff; font-weight: 900; font-size: calc(var(--w) * .2); line-height: 1.35; text-align: left; padding-left: 4px; } .dm-card .big { flex: 1; display: flex; align-items: center; justify-content: center; font-weight: 900; font-size: calc(var(--w) * .5); color: var(--c, #444); line-height: 1; font-variant-numeric: tabular-nums; } .dm-card .nm { font-size: calc(var(--w) * .19); font-weight: 800; padding-bottom: 3px; white-space: nowrap; } .dm-card.jester { --c: #be185d; background: linear-gradient(160deg, #fff7ed, #fdf2f8); } .dm-card.jester .band { background: linear-gradient(90deg, #dc2626, #f59e0b, #16a34a, #2563eb, #9333ea); } .dm-card.jester .big { font-size: calc(var(--w) * .42); } .dm-hand-wrap { background: var(--surface); border-radius: 16px; box-shadow: var(--shadow); padding: 10px 12px; display: flex; flex-direction: column; gap: 8px; } .dm-hand { display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end; } .dm-group { position: relative; min-width: 56px; min-height: 56px; padding: 4px 4px 0; border: 3px solid transparent; border-radius: 12px; background: none; cursor: pointer; transition: transform .12s ease, opacity .12s ease; display: flex; flex-direction: column; align-items: center; gap: 2px; color: var(--text); font: inherit; } .dm-group .stack { position: relative; } .dm-group .stack[data-many='true'] .dm-card { box-shadow: 3px -3px 0 -1px #fffdf7, 3px -3px 0 1px var(--c, #444), 0 2px 4px rgba(0,0,0,.28); } .dm-group .cnt { position: absolute; right: -7px; top: -7px; background: #111827; color: #fff; border-radius: 999px; padding: 0 7px; font-weight: 900; font-size: .85rem; line-height: 1.5; } .dm-group .tag { font-size: .72rem; font-weight: 800; color: var(--warning); white-space: nowrap; min-height: 1.1em; } .dm-group[data-legal='false'] { opacity: .42; filter: grayscale(.5); cursor: default; } .dm-group[aria-pressed='true'] { border-color: var(--primary); transform: translateY(-6px); background: var(--primary-soft); } .dm-group:focus-visible, .dm-one:focus-visible { outline: 3px solid var(--focus); outline-offset: 2px; } .dm-one { padding: 2px; border: 3px solid transparent; border-radius: 10px; background: none; cursor: pointer; position: relative; } .dm-one[aria-pressed='true'] { border-color: var(--primary); transform: translateY(-8px); } .dm-one[data-received='true']::after { content: '받음'; position: absolute; left: 50%; top: -9px; transform: translateX(-50%); background: var(--warning); color: #fff; font-size: .7rem; font-weight: 800; border-radius: 999px; padding: 0 6px; animation: dm-pop .4s ease; } .dm-pick { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; background: var(--surface-2); border-radius: 12px; padding: 8px 10px; } .dm-pick .stepper { display: inline-flex; align-items: center; gap: 6px; } .dm-pick .stepper button { width: 48px; height: 48px; border-radius: 12px; border: 2px solid var(--border); background: var(--surface); color: var(--text); font-size: 1.4rem; font-weight: 900; cursor: pointer; } .dm-pick .stepper button:disabled { opacity: .4; cursor: not-allowed; } .dm-pick .stepper b { min-width: 3.2em; text-align: center; font-size: 1.1rem; } .dm-toggle { min-height: 48px; border-radius: 12px; border: 2px solid var(--border); background: var(--surface); color: var(--text); font-weight: 800; padding: 0 12px; cursor: pointer; } .dm-toggle[aria-pressed='true'] { background: #fce7f3; border-color: #be185d; color: #831843; } .dm-toggle:disabled { opacity: .55; cursor: not-allowed; } .dm-actions { display: flex; gap: 8px; } .dm-actions .btn { flex: 1 1 0; min-height: 56px; font-size: 1.1rem; } .dm-panel { background: var(--surface); color: var(--text); border-radius: 16px; box-shadow: var(--shadow); padding: 12px; display: flex; flex-direction: column; gap: 8px; } .dm-panel.hot { border: 3px solid var(--warning); } .dm-panel h3 { margin: 0; font-size: 1.05rem; } .dm-rev { background: linear-gradient(90deg, #7c2d12, #be185d); color: #fff; border-radius: 12px; padding: 8px 12px; font-weight: 800; text-align: center; animation: dm-pop .4s ease; } .dm-draws { display: flex; flex-wrap: wrap; gap: 8px; } .dm-draw { display: flex; align-items: center; gap: 6px; background: var(--surface-2); border-radius: 10px; padding: 4px 8px; animation: dm-in .4s ease both; } .dm-mini { display: flex; flex-wrap: wrap; gap: 3px; } .dm-mini .dm-card { --w: 30px; } .dm-mini .dm-card .nm { display: none; } .dm-log { list-style: none; margin: 8px 0 0; padding: 0; display: grid; gap: 3px; max-height: 220px; overflow: auto; } .dm-rules td, .dm-rules th { padding: 3px 6px; text-align: left; border-bottom: 1px solid var(--border); vertical-align: middle; } .dm-rules .dm-card { --w: 28px; } .dm-rules .dm-card .nm { display: none; } .dm-flip { animation: dm-flip .7s ease both; } @keyframes dm-in { from { transform: translateY(-8px); opacity: 0; } to { transform: none; opacity: 1; } } @keyframes dm-pop { 0% { transform: scale(.6); } 70% { transform: scale(1.12); } 100% { transform: scale(1); } } @keyframes dm-flip { from { transform: rotateY(180deg); } to { transform: none; } } @media (prefers-reduced-motion: reduce) { .dm *, .dm-seat, .dm-rev, .dm-bubble, .dm-draw, .dm-flip { animation: none !important; transition: none !important; } } @media (max-width: 719px) { .dm { gap: 8px; } .dm-seat { flex: 1 1 30%; min-width: 0; padding: 4px 6px; font-size: .82rem; } .dm-table { border-width: 6px; padding: 10px; min-height: 150px; } .dm-now { font-size: 1.3rem; } .dm-card { --w: 44px; } .dm-hand { gap: 4px; } .dm-group { min-width: 48px; padding: 3px 2px 0; } .dm-hand-wrap { padding: 8px; position: relative; } .dm-actions { position: sticky; bottom: 0; background: var(--surface); padding: 6px 0 2px; z-index: 2; } } `; // ---------------------------------------------------------------- cards function CardArt({ n, w }: { n: number; w?: number }) { const style = { ...(w ? { '--w': `${w}px` } : {}), ...(n === JESTER ? {} : { '--c': CARD_HUE[n] }) } as CSSProperties; return ( {n === JESTER ? '★' : n} {n === JESTER ? '광대' : n} {CARD_NAME[n]} ); } function SetArt({ play, w, top }: { play: Pick; w?: number; top?: boolean }) { return ( {play.cards.map((n, i) => ( ))} ); } // ---------------------------------------------------------------- seats function seatLabel(s: SeatView, v: DalmutiView, players: Record, me: string | null): string { const parts = [`${s.rank + 1}번째 신분 ${s.title}`, `${nick(players, s.id)}${s.id === me ? '(나)' : ''}`, `카드 ${s.cards}장`]; if (s.place) parts.push(`${s.place}등으로 다 냄`); if (s.passed) parts.push('패스'); if (s.lockedOut && !s.passed) parts.push('이번 트릭 빠짐'); if (v.phase === 'revolutionCheck') parts.push(s.confirmed ? '확인함' : '확인 전'); if (s.left) parts.push('나감'); else if (s.away) parts.push('자리 비움'); if (s.isTurn && v.phase === 'playing') parts.push('차례'); parts.push(`총점 ${s.total}점`); return parts.join(', '); } function Seats({ v, players, me, deadline }: { v: DalmutiView; players: Record; me: string | null; deadline: number | null }) { const flip = v.revolution === 'great'; return ( <>
    {v.seats.map((s, i) => { const u = userOf(players, s.id); return (
  1. {s.passed && ( 패스 )} {TITLE_ICON[s.title]} {s.title}
    {u.nickname} {s.isTurn && v.phase === 'playing' && }
    {s.cards} {s.place && {s.place}등} {v.phase === 'revolutionCheck' && ( {s.confirmed ? '확인 ✓' : '확인 중'} )} {s.lockedOut && !s.passed && 빠짐} {s.left ? ( 나감 ) : ( s.away && 자리 비움 )}
  2. ); })}

차례: 왼쪽 위부터 신분 순서대로 돌아요 ↻

); } // ---------------------------------------------------------------- table function TableArea({ v, players, me }: { v: DalmutiView; players: Record; me: string | null }) { const t = v.trick; if (!t) return null; const top = t.top; const prev = t.pile.slice(0, -1).slice(-4); const leaderName = t.leader === me ? '내가' : `${nick(players, t.leader)}님이`; const curName = v.current === me ? '내' : `${nick(players, v.current ?? '')}님`; return (
{top ? ( <>
지금 기준: {setText(top)} {top.by === me ? '내가' : `${nick(players, top.by)}님이`} 냈어요 · 같은 장수로 더 낮은 숫자만 낼 수 있어요
{prev.length > 0 && (
setText(p)).join(', ')}`}> {prev.map((p, i) => ( ))}
)}
) : (
{leaderName} 새로 시작해요 {v.current === me ? '아무 숫자나 같은 숫자로 원하는 장수만큼 내요' : `${curName} 차례예요`}
)}
); } // ---------------------------------------------------------------- hand (playing) interface Group { n: number; cards: DCard[]; } function groupsOf(hand: DCard[]): Group[] { const map = new Map(); for (const c of hand) map.set(c.n, [...(map.get(c.n) ?? []), c]); return [...map.entries()].sort((a, b) => a[0] - b[0]).map(([n, cards]) => ({ n, cards })); } /** Card ids for `count` cards of `rank` with at least `minJ` jesters (more if needed); null if impossible. */ function pickIds(hand: DCard[], rank: number, count: number, minJ: number): string[] | null { const js = hand.filter((c) => c.n === JESTER); if (rank === JESTER) return count <= js.length ? js.slice(0, count).map((c) => c.id) : null; const ns = hand.filter((c) => c.n === rank); const j = Math.max(minJ, count - ns.length); if (j > js.length || count - j < 1 || count - j > ns.length) return null; return [...ns.slice(0, count - j), ...js.slice(0, j)].map((c) => c.id); } function onArrowKeys(e: KeyboardEvent, selector: string) { if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return; const btns = Array.from(e.currentTarget.querySelectorAll(selector)); const i = btns.indexOf(document.activeElement as HTMLButtonElement); if (i < 0) return; e.preventDefault(); btns[(i + (e.key === 'ArrowRight' ? 1 : btns.length - 1)) % btns.length]?.focus(); } interface Sel { rank: number; count: number; mix: boolean; } function PlayHand({ v, act, pending }: { v: DalmutiView; act: (a: unknown) => void; pending: boolean }) { const my = v.my!; const [sel, setSel] = useState(null); const turnKey = `${v.turnNo}`; useEffect(() => setSel(null), [turnKey]); const groups = groupsOf(my.hand); const choice = (n: number): Choice | undefined => my.choices.find((c) => c.rank === n); const top = v.trick?.top ?? null; const J = my.jesters; const mine = my.canPlay; const tap = (g: Group) => { const ch = choice(g.n); if (!mine || !ch) return; if (sel?.rank === g.n) { setSel(null); return; } sfx.select(); if (top) setSel({ rank: g.n, count: top.count, mix: ch.needsJester }); else setSel({ rank: g.n, count: ch.have, mix: false }); }; const ch = sel ? choice(sel.rank) : undefined; const have = ch?.have ?? 0; const maxCount = !sel || !ch ? 0 : sel.rank === JESTER ? J : sel.mix ? have + J : have; const ids = sel && ch ? pickIds(my.hand, sel.rank, sel.count, sel.mix && sel.rank !== JESTER ? 1 : 0) : null; const legal = !!ids && !!ch && ch.counts.includes(sel!.count); const jUsed = ids ? ids.filter((id) => id.startsWith('j')).length : 0; const setCount = (count: number) => sel && setSel({ ...sel, count }); const toggleMix = () => { if (!sel || !ch) return; if (top) { setSel({ ...sel, mix: !sel.mix }); return; } if (!sel.mix) setSel({ ...sel, mix: true, count: Math.min(have + J, Math.max(sel.count, have) + 1) }); else setSel({ ...sel, mix: false, count: Math.min(sel.count, have) }); }; const send = () => { if (!ids || !legal) return; rememberPlay(sel!.rank); act({ type: 'play', cardIds: ids }); setSel(null); }; const mixLocked = !!top && !!ch?.needsJester; const mixAllowed = !!sel && sel.rank !== JESTER && J > 0 && !!ch && (!top || ch.needsJester || have >= 2); return (
내 카드 {my.hand.length}장{J > 0 ? ` · 광대 ${J}장` : ''} {mine && {top ? `${setText(top)}보다 낮은 숫자를 골라요` : '낼 숫자를 골라요'}}
onArrowKeys(e, 'button.dm-group')}> {groups.map((g) => { const c = choice(g.n); const picked = sel?.rank === g.n; return ( ); })} {my.hand.length === 0 && 손패를 다 냈어요! 다른 사람을 지켜봐요.}
{mine && sel && ch && (
{sel.rank === JESTER ? '광대' : cardName(sel.rank)} {!top && ( {sel.count}장 )} {mixAllowed && ( )} {legal ? `${rankText(sel.rank)} × ${sel.count}장${jUsed > 0 && sel.rank !== JESTER ? ` (광대 ${jUsed}장 포함)` : ''}` : '이렇게는 낼 수 없어요'}
)} {mine && (
)} {!mine && my.lockedOut && 이번 트릭은 패스해서 빠졌어요. 다음 트릭을 기다려요.}
); } // ---------------------------------------------------------------- revolution check / tax function RoundRecap({ v, players, me }: { v: DalmutiView; players: Record; me: string | null }) { const last = v.roundResults[v.roundResults.length - 1]; if (last) { return (
{last.round}라운드 결과 → 새 신분
    {last.order.map((p, i) => (
  1. {nick(players, p)} {p === me ? '(나)' : ''} · +{last.points[p]}점 → {TITLE_ICON[v.seats[i]?.title ?? '평민']} {v.seats.find((s) => s.id === p)?.title}
  2. ))}
); } if (!v.firstDraw) return null; return (
첫 신분 뽑기 · 낮은 숫자일수록 높은 신분이에요
{v.seats.map((s, i) => ( (n === JESTER ? '광대' : n)).join(', 다시 뽑아 ')} → ${s.title}`}> {v.firstDraw![s.id]!.map((n, k) => ( ))} {nick(players, s.id)}
{TITLE_ICON[s.title]} {s.title}
))}
{Object.values(v.firstDraw).some((d) => d.length > 1) && 같은 숫자가 나온 사람끼리는 다시 뽑았어요.}
); } function HandPreview({ hand }: { hand: DCard[] }) { return (
`${cardName(g.n)} ${g.cards.length}장`).join(', ')}`} role="img"> {groupsOf(hand).map((g) => ( 1}> {g.cards.length > 1 && ×{g.cards.length}} ))}
); } function RevolutionPanel({ v, players, me, act, pending }: { v: DalmutiView; players: Record; me: string | null; act: (a: unknown) => void; pending: boolean }) { const my = v.my; const done = v.seats.filter((s) => s.confirmed).length; return (

{v.round}라운드 준비 · 손패 확인 ({done}/{v.seats.length})

{my && ( <> {my.canConfirm ? (
{my.canDeclareRevolution && ( )}
) : ( 다른 사람이 확인하기를 기다리는 중이에요… )} {my.canDeclareRevolution && ( 광대 2장이 다 있어요! 혁명을 선언하면 광대 2장을 보여 주고 이번 라운드 세금이 없어요. {v.seats[v.seats.length - 1]?.id === me ? ' 대농노가 선언하면 대혁명으로 신분이 완전히 뒤집혀요.' : ''} )} )}
); } function TaxPanel({ v, players, me, act, pending }: { v: DalmutiView; players: Record; me: string | null; act: (a: unknown) => void; pending: boolean }) { const my = v.my; const owe = my?.owe ?? null; const [picked, setPicked] = useState([]); const oweKey = owe ? `${v.round}-${owe.count}` : ''; useEffect(() => setPicked(my?.suggestedReturn ?? []), [oweKey]); // eslint-disable-line react-hooks/exhaustive-deps const titleOf = (id: string) => v.seats.find((s) => s.id === id)?.title ?? ''; const who = (id: string) => (id === me ? '나' : `${nick(players, id)}님`); const subject = (id: string) => (id === me ? '내가' : `${nick(players, id)}님이`); const toggle = (id: string) => { if (!owe) return; sfx.select(); if (picked.includes(id)) setPicked(picked.filter((x) => x !== id)); else setPicked(picked.length >= owe.count ? [...picked.slice(1), id] : [...picked, id]); }; return (

세금 카드 교환

    {v.tax.map((t, i) => (
  • {titleOf(t.from)} {who(t.from)} → {titleOf(t.to)} {who(t.to)} {t.count}장 {t.kind === 'tax' ? '세금' : '돌려줌'} {t.cards && ({facesText(t.cards)})}
  • ))} {v.taxPending .filter((p) => !p.done) .map((p) => (
  • {titleOf(p.from)} {subject(p.from)} {p.count}장을 돌려줄 차례예요
  • ))}
{owe && my ? ( <> 돌려줄 카드 {owe.count}장을 고르세요 · 받은 카드도 돌려줄 수 있어요
onArrowKeys(e, 'button.dm-one')}> {my.hand.map((c) => { const on = picked.includes(c.id); const got = my.receivedIds.includes(c.id); return ( ); })}
) : ( my && )}
); } // ---------------------------------------------------------------- log function logText(e: LogEntry, players: Record): string { const n = (id: string) => `${nick(players, id)}님`; switch (e.t) { case 'play': return `${n(e.p)}: ${setText(e)}${e.cards.includes(JESTER) && e.rank !== JESTER ? ' (광대 포함)' : ''}`; case 'pass': return `${n(e.p)}: 패스`; case 'trick': return `모두 패스해서 ${n(e.p)}이 새로 시작해요`; case 'out': return `${n(e.p)}이 손패를 다 냈어요 (${e.place}등)`; case 'revolution': return e.kind === 'great' ? `${n(e.p)}의 대혁명! 신분이 뒤집혔어요` : `${n(e.p)}의 혁명! 이번 라운드는 세금이 없어요`; case 'tax': return `세금: ${n(e.from)} → ${n(e.to)} ${e.n}장`; case 'return': return `돌려줌: ${n(e.from)} → ${n(e.to)} ${e.n}장`; case 'round': return `${e.round}라운드가 끝났어요`; case 'timeout': return `${n(e.p)}의 시간이 다 되어 자동으로 진행했어요`; case 'left': return `${n(e.p)}이 나갔어요. 남은 차례는 자동으로 진행해요`; } } // ---------------------------------------------------------------- board function Tip() { const [hidden, setHidden] = useState(() => { try { return localStorage.getItem(TIP_KEY) === '1'; } catch { return false; } }); if (hidden) return null; return (
💡 숫자가 낮을수록 강해요 · 앞사람과 같은 장수로만 낼 수 있어요
); } function RevolutionBanner({ v, players, me }: { v: DalmutiView; players: Record; me: string | null }) { if (v.revolution === 'none' || !v.revolutionBy || v.phase !== 'playing') return null; const who = v.revolutionBy === me ? '내가' : `${nick(players, v.revolutionBy)}님이`; return (
{v.revolution === 'great' ? `🃏🃏 대혁명! ${who} 광대 2장으로 신분을 완전히 뒤집었어요. 세금은 없어요` : `🃏🃏 혁명! ${who} 광대 2장을 보여 줬어요. 이번 라운드는 세금이 없어요`}
); } function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardProps) { const [announce, setAnnounce] = useState(''); const mine = isMyTurn(v, me); const prevMine = useRef(false); const lastLog = v.log[v.log.length - 1]; const [banner, showBanner] = useBanner(); useDalmutiFx(v, me, players, showBanner); useEffect(() => { if (mine && !prevMine.current) { haptic(40); sounds.myTurn(); setAnnounce(statusText(v, me, players)); } prevMine.current = mine; }, [mine]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { if (lastLog && !mine) setAnnounce(logText(lastLog, players)); }, [lastLog?.seq, lastLog?.t]); // eslint-disable-line react-hooks/exhaustive-deps return (
{v.phase === 'revolutionCheck' && } {v.phase === 'taxReturn' && } {v.phase === 'playing' && } {v.phase === 'playing' && v.my && } {v.phase === 'finished' && v.result && (

게임이 끝났어요

{v.result.summary}
)}

{announce}

{banner}
); } 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]) { const later = (ms: number, f: () => void) => (ms ? setTimeout(f, 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. const deal = (delay = 0) => { const c = fxEl('dm-center'); later(delay, sfx.shuffle); later(delay + 300, () => sfx.deal(6, 60)); document.querySelectorAll('.dm-hand .dm-group, .dm-hand .dm-one').forEach((el, i) => 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 }); }; useNewEntries(v.log, logKey, (fresh) => { const lastPlay = [...fresh].reverse().find((e) => e.t === 'play'); let t = 0; for (const e of fresh) { const at = t; switch (e.t) { case 'play': { if (e === lastPlay) { const from = e.p === me ? (myPlayRect ?? fxEl('dm-hand')) : seatEl(e.p); document.querySelectorAll('.dm-set.top .dm-card').forEach((el, i) => flyFrom(el, from, { delay: at + i * 60, ms: 340, rotate: -12 })); } if (e.p === me) myPlayRect = null; later(at, () => dmSfx.set(e.count)); t += 150; break; } case 'pass': later(at, dmSfx.knock); dim(seatEl(e.p)); t += 120; break; case 'trick': // Everyone passed: the pile is swept to whoever leads next. flyGhost(fxEl('dm-center'), seatEl(e.p), { count: 3, gap: 60, delay: at, ms: 420 }); later(at, sfx.whoosh); later(at + 380, () => bump(seatEl(e.p))); t += 200; break; case 'out': showBanner(`${e.place}등!`, e.place === 1 ? 'gold' : 'green', e.p === me ? '손패를 다 냈어요' : `${nick(players, e.p)}님`); later(at + 80, e.place === 1 ? sfx.fanfare : sfx.good); bump(seatEl(e.p)); t += 250; break; case 'revolution': { const great = e.kind === 'great'; showBanner(great ? '대혁명!' : '혁명!', great ? 'dark' : 'red', great ? `${who(e.p)} · 신분이 뒤집혀요` : `${who(e.p)} · 세금 없음`); later(at, () => dmSfx.revolution(great)); t += 300; break; } case 'tax': case 'return': flyGhost(seatEl(e.from), seatEl(e.to), { count: e.n, gap: 90, delay: at, ms: 520 }); later(at, e.t === 'tax' ? dmSfx.tax : dmSfx.give); t += 350; break; case 'round': // The next round's cards are dealt (not after the last round). if (v.phase !== 'finished') { deal(at + 500); t += 1300; } break; case 'timeout': later(at, sfx.tick); break; default: break; } } }); const started = useRef(false); useLayoutEffect(() => { if (started.current) return; started.current = true; // Mounted right at the start of the game (nobody has done anything yet): show the deal once. const fresh = v.round === 1 && (v.phase === 'revolutionCheck' ? v.log.length === 0 && !v.seats.some((s) => s.confirmed) : v.phase === 'taxReturn' && !v.options.revolution && v.log.every((e) => e.t === 'tax') && v.taxPending.every((p) => !p.done)); if (fresh) deal(); }, []); // eslint-disable-line react-hooks/exhaustive-deps } // ---------------------------------------------------------------- side function rulesLine(o: DalmutiOptions): string { return [ `${o.rounds}라운드`, o.scoring === 'rank-points' ? '순위 점수 합' : '마지막 라운드 순위', o.revolution ? '혁명 있음' : '혁명 없음', o.jesterTaxable ? '세금에 광대 포함' : '세금에 광대 빼기', o.passLocksOut ? '패스하면 트릭에서 빠짐' : '패스해도 다시 낼 수 있음', o.removeHighCards ? '9~12 빼기' : '', o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`, ] .filter(Boolean) .join(' · '); } function DalmutiSide({ view: v, me, players, deadline }: BoardProps) { const phaseKo = v.phase === 'revolutionCheck' ? '손패 확인' : v.phase === 'taxReturn' ? '세금 교환' : v.phase === 'playing' ? '진행 중' : '게임 끝'; const rounds = v.roundResults; return ( <>
달무티 · {Math.min(v.round, v.options.rounds)}/{v.options.rounds}라운드 · {phaseKo} {v.phase !== 'finished' && }
{rulesLine(v.options)}
    {v.seats.map((s) => (
  1. {TITLE_ICON[s.title]} {s.isTurn && v.phase === 'playing' ? '▶ ' : ''} {nick(players, s.id)} {s.id === me ? ' (나)' : ''} {s.title} {s.total}점 {s.cards}
  2. ))}
{rounds.length > 0 && (
라운드 순위 {rounds.map((r) => ( ))} {(v.result ? v.result.players.map((p) => p.player) : v.seats.map((s) => s.id)).map((p) => ( {rounds.map((r) => ( ))} ))}
이름 {r.round}R 합계
{nick(players, p)} {r.order.indexOf(p) + 1}등 {v.seats.find((s) => s.id === p)?.total ?? 0}점
{v.result &&

{v.result.summary}

}
)} {v.log.length > 0 && (
기록
    {[...v.log].reverse().map((e, i) => (
  1. {logText(e, players)}
  2. ))}
)}
카드 장수표
); } // ---------------------------------------------------------------- status function isMyTurn(v: DalmutiView, me: string | null): boolean { if (!me || !v.my) return false; if (v.phase === 'revolutionCheck') return v.my.canConfirm; if (v.phase === 'taxReturn') return !!v.my.owe; return v.phase === 'playing' && v.current === me; } function statusText(v: DalmutiView, me: string | null, players: Record): string { if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요'; if (v.phase === 'revolutionCheck') { if (v.my?.canDeclareRevolution) return '손패를 확인해 주세요 · 광대 2장으로 혁명할 수 있어요'; if (v.my?.canConfirm) return `${v.round}라운드 손패를 확인해 주세요`; return '다른 사람이 손패를 확인하는 중이에요'; } if (v.phase === 'taxReturn') { if (v.my?.owe) return `내 차례예요 · 돌려줄 카드 ${v.my.owe.count}장을 골라 주세요`; return '세금 카드를 주고받는 중이에요'; } if (me && v.current === me) return v.my?.leading ? '내 차례예요 · 새로 시작해요' : '내 차례예요'; if (!v.current) return '잠시만 기다려 주세요'; return `${nick(players, v.current)}님 차례예요`; } // ---------------------------------------------------------------- options function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { return (
{options.map(([k, l]) => ( ))}
); } function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) { return (
{label} {children} {help && {help}}
); } const onOff: [boolean, string][] = [ [true, '켜기'], [false, '끄기'], ]; function Options({ value: o, onChange }: OptionsProps) { const [more, setMore] = useState(false); const set = (patch: Partial) => onChange({ ...o, ...patch }); return (
set({ rounds })} /> set({ scoring })} /> set({ revolution })} /> set({ turnSeconds })} /> {more && ( <> set({ firstRanking })} /> set({ jesterTaxable })} /> set({ passLocksOut })} /> set({ removeHighCards })} /> )}
); } function optionsSummary(o: DalmutiOptions): string { const parts = [`${o.rounds}라운드`, o.scoring === 'rank-points' ? '순위 점수 합' : '마지막 라운드 순위']; if (!o.revolution) parts.push('혁명 없음'); if (o.jesterTaxable) parts.push('세금에 광대'); if (o.passLocksOut) parts.push('패스하면 빠짐'); if (o.removeHighCards) parts.push('9~12 빼기'); parts.push(o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`); return parts.join(' · '); } // ---------------------------------------------------------------- rules function CardTable({ removeHigh }: { removeHigh?: boolean }) { const rows = Array.from({ length: 13 }, (_, i) => i + 1).filter((n) => !removeHigh || n <= 8 || n === JESTER); return ( {rows.map((n) => ( ))}
카드 숫자 이름 장수
{n === JESTER ? '13 / 와일드' : n} {CARD_NAME[n]} {n === JESTER ? 2 : n}장
); } function Rules({ options }: { options?: DalmutiOptions }) { const o = options; const titles: Title[] = ['대달무티', '소달무티', '평민', '소농노', '대농노']; return (

숫자가 낮을수록 강해요. 손패를 먼저 다 내는 사람이 다음 라운드에서 높은 신분이 돼요. 4~8명이 해요.

새로 시작하는 사람은 같은 숫자 카드를 원하는 장수만큼 내요. 다음 사람부터는 같은 장수로 더 낮은 숫자를 내거나 패스해요. 낸 사람 말고 모두 패스하면 바닥을 치우고 마지막에 낸 사람이 새로 시작해요. {o?.passLocksOut ? ' 이 방에서는 한 번 패스하면 그 트릭이 끝날 때까지 빠져요.' : ' 패스해도 차례가 다시 오면 낼 수 있어요.'}

광대는 혼자 내면 13이에요. 숫자 카드와 함께 내면 그 숫자로 바뀌어요(예: 4 + 광대 = 4 두 장).

신분: {titles.map((t) => `${TITLE_ICON[t]} ${t}`).join(' → ')} (4명이면 평민이 없어요). 라운드를 시작할 때 대농노는 가장 좋은 카드 2장을 대달무티에게, 소농노는 1장을 소달무티에게 세금으로 줘요. 받은 사람은 아무 카드나 같은 장수만큼 돌려줘요.

{(o?.revolution ?? true) && (

혁명: 손패를 확인할 때 광대 2장을 다 가진 사람은 혁명을 선언할 수 있어요. 그 라운드는 세금이 없어요. 대농노가 선언하면 대혁명으로 신분이 완전히 뒤집혀요.

)}

라운드에서 1등은 (사람 수 − 1)점, 마지막 순위는 0점을 받아요. {o?.scoring === 'last-round' ? '이 방은 마지막 라운드 순위가 최종 순위예요.' : '총점이 높은 사람이 이기고, 같으면 마지막 라운드 순위로 정해요.'}{' '} 점수는 이 방 안에서만 쓰는 표시용이에요.

{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는 패스해요.

); } const ui: GameUI = { Board: DalmutiBoard, Side: DalmutiSide, statusText, isMyTurn, Options, optionsSummary, Rules, quickStart, helpNow, }; export default ui;