- 무제한(null): 차례 시계·타임아웃 없음, 자리 비움만 짧은 시계, 연결 끊김은 방 유예 뒤 자동 행동 그대로 - 포커는 리바이 고르는 시간도 무제한 가능, 고스톱은 고·스톱 선택 시간도 무제한 가능, 뱅!은 반응 시간·캐릭터 고르기도 - card-fx: 날아가는 카드·칩(ghost), 제자리 날아오기, 배너, view 변화 감지 훅(처음 렌더·다시 보기는 건너뜀) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1158 lines
54 KiB
TypeScript
1158 lines
54 KiB
TypeScript
/** 달무티 화면 (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<number, string> = {
|
||
1: '왕',
|
||
2: '왕비',
|
||
3: '재상',
|
||
4: '공작',
|
||
5: '백작',
|
||
6: '기사',
|
||
7: '학자',
|
||
8: '상인',
|
||
9: '요리사',
|
||
10: '목동',
|
||
11: '광부',
|
||
12: '농부',
|
||
13: '광대',
|
||
};
|
||
const CARD_HUE: Record<number, string> = {
|
||
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<Title, string> = { 대달무티: '👑', 소달무티: '🎩', 평민: '🙂', 소농노: '🌾', 대농노: '🧺' };
|
||
const TIP_KEY = 'dm-tip-hidden';
|
||
|
||
const nick = (players: Record<string, PublicUser>, id: string) => players[id]?.nickname ?? '알 수 없음';
|
||
const userOf = (players: Record<string, PublicUser>, 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 (
|
||
<span className={`dm-card${n === JESTER ? ' jester' : ''}`} style={style} aria-hidden>
|
||
<span className="band">{n === JESTER ? '★' : n}</span>
|
||
<span className="big">{n === JESTER ? '광대' : n}</span>
|
||
<span className="nm">{CARD_NAME[n]}</span>
|
||
</span>
|
||
);
|
||
}
|
||
|
||
function SetArt({ play, w, top }: { play: Pick<PlayView, 'cards'>; w?: number; top?: boolean }) {
|
||
return (
|
||
<span className={`dm-set${top ? ' top' : ''}`} style={w ? ({ '--w': `${w}px` } as CSSProperties) : undefined}>
|
||
{play.cards.map((n, i) => (
|
||
<CardArt key={i} n={n} w={w} />
|
||
))}
|
||
</span>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- seats
|
||
|
||
function seatLabel(s: SeatView, v: DalmutiView, players: Record<string, PublicUser>, 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<string, PublicUser>; me: string | null; deadline: number | null }) {
|
||
const flip = v.revolution === 'great';
|
||
return (
|
||
<>
|
||
<ol className={`dm-seats${flip ? ' dm-flip' : ''}`} aria-label="신분 순서(턴 순서)" key={`${v.round}-${v.revolution}`}>
|
||
{v.seats.map((s, i) => {
|
||
const u = userOf(players, s.id);
|
||
return (
|
||
<li
|
||
key={s.id}
|
||
className={`dm-seat${s.isTurn && v.phase === 'playing' ? ' turn anim-glow' : ''}${s.id === me ? ' me' : ''}${s.place ? ' out' : ''}`}
|
||
data-fx-seat={s.id}
|
||
style={{ animationDelay: `${i * 40}ms` }}
|
||
aria-label={seatLabel(s, v, players, me)}
|
||
>
|
||
{s.passed && (
|
||
<span className="dm-bubble" aria-hidden>
|
||
패스
|
||
</span>
|
||
)}
|
||
<span className="ttl" aria-hidden>
|
||
{TITLE_ICON[s.title]} {s.title}
|
||
</span>
|
||
<div className="row" style={{ gap: 5, flexWrap: 'nowrap' }} aria-hidden>
|
||
<Avatar user={u} size={22} />
|
||
<span className="nm">{u.nickname}</span>
|
||
{s.isTurn && v.phase === 'playing' && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={s.id === me} size={26} />}
|
||
</div>
|
||
<div className="meta" aria-hidden>
|
||
<span className="dm-count">
|
||
<i />
|
||
{s.cards}
|
||
</span>
|
||
{s.place && <span className="dm-badge" style={{ background: 'var(--success)', color: '#fff' }}>{s.place}등</span>}
|
||
{v.phase === 'revolutionCheck' && (
|
||
<span className="dm-badge" style={{ background: s.confirmed ? 'var(--success-soft)' : 'var(--surface-2)', color: 'var(--text)' }}>
|
||
{s.confirmed ? '확인 ✓' : '확인 중'}
|
||
</span>
|
||
)}
|
||
{s.lockedOut && !s.passed && <span className="dm-badge" style={{ background: 'var(--surface-2)', color: 'var(--text)' }}>빠짐</span>}
|
||
{s.left ? (
|
||
<span className="dm-badge" style={{ background: 'var(--text-sub)', color: 'var(--surface)' }}>나감</span>
|
||
) : (
|
||
s.away && <span className="dm-badge" style={{ background: 'var(--warning-soft)', color: 'var(--text)' }}>자리 비움</span>
|
||
)}
|
||
</div>
|
||
</li>
|
||
);
|
||
})}
|
||
</ol>
|
||
<p className="dm-order" aria-hidden>
|
||
차례: 왼쪽 위부터 신분 순서대로 돌아요 ↻
|
||
</p>
|
||
</>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- table
|
||
|
||
function TableArea({ v, players, me }: { v: DalmutiView; players: Record<string, PublicUser>; 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 (
|
||
<div className="dm-table" data-fx="dm-center" role="region" aria-label="바닥">
|
||
{top ? (
|
||
<>
|
||
<div className="dm-now" aria-live="polite">
|
||
지금 기준: {setText(top)}
|
||
<small>
|
||
{top.by === me ? '내가' : `${nick(players, top.by)}님이`} 냈어요 · 같은 장수로 더 낮은 숫자만 낼 수 있어요
|
||
</small>
|
||
</div>
|
||
<div className="dm-pile">
|
||
{prev.length > 0 && (
|
||
<div className="dm-prev" aria-label={`이전 묶음: ${prev.map((p) => setText(p)).join(', ')}`}>
|
||
{prev.map((p, i) => (
|
||
<SetArt key={i} play={p} w={30} />
|
||
))}
|
||
</div>
|
||
)}
|
||
<span role="img" aria-label={`맨 위 묶음 ${facesText(top.cards)}`}>
|
||
<SetArt key={`${t.pile.length}`} play={top} top />
|
||
</span>
|
||
</div>
|
||
</>
|
||
) : (
|
||
<div className="dm-now" aria-live="polite">
|
||
{leaderName} 새로 시작해요
|
||
<small>{v.current === me ? '아무 숫자나 같은 숫자로 원하는 장수만큼 내요' : `${curName} 차례예요`}</small>
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- hand (playing)
|
||
|
||
interface Group {
|
||
n: number;
|
||
cards: DCard[];
|
||
}
|
||
|
||
function groupsOf(hand: DCard[]): Group[] {
|
||
const map = new Map<number, DCard[]>();
|
||
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<HTMLDivElement>, selector: string) {
|
||
if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') return;
|
||
const btns = Array.from(e.currentTarget.querySelectorAll<HTMLButtonElement>(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<Sel | null>(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 (
|
||
<div className="dm-hand-wrap">
|
||
<div className="row" style={{ justifyContent: 'space-between', gap: 6 }}>
|
||
<strong>
|
||
내 카드 {my.hand.length}장{J > 0 ? ` · 광대 ${J}장` : ''}
|
||
</strong>
|
||
{mine && <span className="small muted">{top ? `${setText(top)}보다 낮은 숫자를 골라요` : '낼 숫자를 골라요'}</span>}
|
||
</div>
|
||
<div className="dm-hand" data-fx="dm-hand" role="group" aria-label="내 카드(숫자별). 좌우 방향키로 고르고 Enter로 선택해요" onKeyDown={(e) => onArrowKeys(e, 'button.dm-group')}>
|
||
{groups.map((g) => {
|
||
const c = choice(g.n);
|
||
const picked = sel?.rank === g.n;
|
||
return (
|
||
<button
|
||
key={g.n}
|
||
type="button"
|
||
className="dm-group"
|
||
data-legal={mine ? !!c : undefined}
|
||
data-n={g.n}
|
||
aria-pressed={picked}
|
||
disabled={pending && mine}
|
||
onClick={() => tap(g)}
|
||
aria-label={`${cardName(g.n)} ${g.cards.length}장${mine ? (c ? (c.needsJester ? ', 광대를 섞어야 낼 수 있음' : ', 낼 수 있음') : ', 지금은 낼 수 없음') : ''}${picked ? ', 골랐음' : ''}`}
|
||
>
|
||
<span className="stack" data-many={g.cards.length > 1}>
|
||
<CardArt n={g.n} />
|
||
{g.cards.length > 1 && (
|
||
<span className="cnt" aria-hidden>
|
||
×{g.cards.length}
|
||
</span>
|
||
)}
|
||
</span>
|
||
<span className="tag" aria-hidden>
|
||
{mine && c?.needsJester ? '광대 필요' : ''}
|
||
</span>
|
||
</button>
|
||
);
|
||
})}
|
||
{my.hand.length === 0 && <span className="muted">손패를 다 냈어요! 다른 사람을 지켜봐요.</span>}
|
||
</div>
|
||
{mine && sel && ch && (
|
||
<div className="dm-pick" aria-live="polite">
|
||
<strong>{sel.rank === JESTER ? '광대' : cardName(sel.rank)}</strong>
|
||
{!top && (
|
||
<span className="stepper" role="group" aria-label="낼 장수">
|
||
<button type="button" aria-label="한 장 덜 내기" disabled={sel.count <= 1} onClick={() => setCount(sel.count - 1)}>
|
||
−
|
||
</button>
|
||
<b>{sel.count}장</b>
|
||
<button type="button" aria-label="한 장 더 내기" disabled={sel.count >= maxCount} onClick={() => setCount(sel.count + 1)}>
|
||
+
|
||
</button>
|
||
</span>
|
||
)}
|
||
{mixAllowed && (
|
||
<button type="button" className="dm-toggle" aria-pressed={sel.mix || jUsed > 0} disabled={mixLocked} onClick={toggleMix}>
|
||
🃏 광대 섞기{mixLocked ? '(필요)' : ''}
|
||
</button>
|
||
)}
|
||
<span className="small">
|
||
{legal ? `${rankText(sel.rank)} × ${sel.count}장${jUsed > 0 && sel.rank !== JESTER ? ` (광대 ${jUsed}장 포함)` : ''}` : '이렇게는 낼 수 없어요'}
|
||
</span>
|
||
</div>
|
||
)}
|
||
{mine && (
|
||
<div className="dm-actions">
|
||
<button type="button" className="btn btn-primary" disabled={!legal || pending} onClick={send}>
|
||
{legal && sel ? `내기 (${rankText(sel.rank)} × ${sel.count}장)` : '내기'}
|
||
</button>
|
||
<button type="button" className="btn btn-secondary" disabled={!my.canPass || pending} onClick={() => act({ type: 'pass' })}>
|
||
패스
|
||
</button>
|
||
</div>
|
||
)}
|
||
{!mine && my.lockedOut && <span className="small muted">이번 트릭은 패스해서 빠졌어요. 다음 트릭을 기다려요.</span>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- revolution check / tax
|
||
|
||
function RoundRecap({ v, players, me }: { v: DalmutiView; players: Record<string, PublicUser>; me: string | null }) {
|
||
const last = v.roundResults[v.roundResults.length - 1];
|
||
if (last) {
|
||
return (
|
||
<div className="stack" style={{ gap: 4 }}>
|
||
<strong>{last.round}라운드 결과 → 새 신분</strong>
|
||
<ol style={{ margin: 0, paddingLeft: 22 }}>
|
||
{last.order.map((p, i) => (
|
||
<li key={p} className="small">
|
||
{nick(players, p)}
|
||
{p === me ? '(나)' : ''} · +{last.points[p]}점 → {TITLE_ICON[v.seats[i]?.title ?? '평민']} {v.seats.find((s) => s.id === p)?.title}
|
||
</li>
|
||
))}
|
||
</ol>
|
||
</div>
|
||
);
|
||
}
|
||
if (!v.firstDraw) return null;
|
||
return (
|
||
<div className="stack" style={{ gap: 4 }}>
|
||
<strong>첫 신분 뽑기 · 낮은 숫자일수록 높은 신분이에요</strong>
|
||
<div className="dm-draws">
|
||
{v.seats.map((s, i) => (
|
||
<span key={s.id} className="dm-draw" style={{ animationDelay: `${i * 120}ms` }} aria-label={`${nick(players, s.id)}: ${v.firstDraw![s.id]!.map((n) => (n === JESTER ? '광대' : n)).join(', 다시 뽑아 ')} → ${s.title}`}>
|
||
<span className="dm-mini" aria-hidden>
|
||
{v.firstDraw![s.id]!.map((n, k) => (
|
||
<CardArt key={k} n={n} />
|
||
))}
|
||
</span>
|
||
<span className="small" aria-hidden>
|
||
<b>{nick(players, s.id)}</b>
|
||
<br />
|
||
{TITLE_ICON[s.title]} {s.title}
|
||
</span>
|
||
</span>
|
||
))}
|
||
</div>
|
||
{Object.values(v.firstDraw).some((d) => d.length > 1) && <span className="small muted">같은 숫자가 나온 사람끼리는 다시 뽑았어요.</span>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function HandPreview({ hand }: { hand: DCard[] }) {
|
||
return (
|
||
<div className="dm-hand" aria-label={`내 카드 ${hand.length}장: ${groupsOf(hand).map((g) => `${cardName(g.n)} ${g.cards.length}장`).join(', ')}`} role="img">
|
||
{groupsOf(hand).map((g) => (
|
||
<span key={g.n} className="dm-group" style={{ cursor: 'default' }} aria-hidden>
|
||
<span className="stack" data-many={g.cards.length > 1}>
|
||
<CardArt n={g.n} />
|
||
{g.cards.length > 1 && <span className="cnt">×{g.cards.length}</span>}
|
||
</span>
|
||
</span>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function RevolutionPanel({ v, players, me, act, pending }: { v: DalmutiView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void; pending: boolean }) {
|
||
const my = v.my;
|
||
const done = v.seats.filter((s) => s.confirmed).length;
|
||
return (
|
||
<div className="dm-panel" data-fx="dm-center">
|
||
<h3>
|
||
{v.round}라운드 준비 · 손패 확인 ({done}/{v.seats.length})
|
||
</h3>
|
||
<RoundRecap v={v} players={players} me={me} />
|
||
{my && (
|
||
<>
|
||
<HandPreview hand={my.hand} />
|
||
{my.canConfirm ? (
|
||
<div className="dm-actions">
|
||
<button type="button" className="btn btn-primary" disabled={pending} onClick={() => act({ type: 'confirmHand' })}>
|
||
손패 확인
|
||
</button>
|
||
{my.canDeclareRevolution && (
|
||
<button type="button" className="btn btn-danger" disabled={pending} onClick={() => act({ type: 'confirmHand', declareRevolution: true })}>
|
||
혁명!
|
||
</button>
|
||
)}
|
||
</div>
|
||
) : (
|
||
<span className="small muted">다른 사람이 확인하기를 기다리는 중이에요…</span>
|
||
)}
|
||
{my.canDeclareRevolution && (
|
||
<span className="small">
|
||
광대 2장이 다 있어요! 혁명을 선언하면 광대 2장을 보여 주고 이번 라운드 세금이 없어요.
|
||
{v.seats[v.seats.length - 1]?.id === me ? ' 대농노가 선언하면 대혁명으로 신분이 완전히 뒤집혀요.' : ''}
|
||
</span>
|
||
)}
|
||
</>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function TaxPanel({ v, players, me, act, pending }: { v: DalmutiView; players: Record<string, PublicUser>; me: string | null; act: (a: unknown) => void; pending: boolean }) {
|
||
const my = v.my;
|
||
const owe = my?.owe ?? null;
|
||
const [picked, setPicked] = useState<string[]>([]);
|
||
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 (
|
||
<div className={`dm-panel${owe ? ' hot' : ''}`} data-fx="dm-center">
|
||
<h3>세금 카드 교환</h3>
|
||
<RoundRecap v={v} players={players} me={me} />
|
||
<ul style={{ margin: 0, paddingLeft: 20 }} aria-label="세금 내역">
|
||
{v.tax.map((t, i) => (
|
||
<li key={i} className="small">
|
||
{titleOf(t.from)} {who(t.from)} → {titleOf(t.to)} {who(t.to)} {t.count}장 {t.kind === 'tax' ? '세금' : '돌려줌'}
|
||
{t.cards && <b> ({facesText(t.cards)})</b>}
|
||
</li>
|
||
))}
|
||
{v.taxPending
|
||
.filter((p) => !p.done)
|
||
.map((p) => (
|
||
<li key={`w-${p.from}`} className="small muted">
|
||
{titleOf(p.from)} {subject(p.from)} {p.count}장을 돌려줄 차례예요
|
||
</li>
|
||
))}
|
||
</ul>
|
||
{owe && my ? (
|
||
<>
|
||
<strong>돌려줄 카드 {owe.count}장을 고르세요 · 받은 카드도 돌려줄 수 있어요</strong>
|
||
<div className="dm-hand" role="group" aria-label={`돌려줄 카드 고르기. ${owe.count}장`} onKeyDown={(e) => onArrowKeys(e, 'button.dm-one')}>
|
||
{my.hand.map((c) => {
|
||
const on = picked.includes(c.id);
|
||
const got = my.receivedIds.includes(c.id);
|
||
return (
|
||
<button
|
||
key={c.id}
|
||
type="button"
|
||
className="dm-one"
|
||
data-received={got}
|
||
aria-pressed={on}
|
||
onClick={() => toggle(c.id)}
|
||
aria-label={`${cardName(c.n)}${got ? ', 방금 받은 카드' : ''}${on ? ', 돌려줄 카드로 골랐음' : ''}`}
|
||
>
|
||
<CardArt n={c.n} w={40} />
|
||
</button>
|
||
);
|
||
})}
|
||
</div>
|
||
<div className="dm-actions">
|
||
<button type="button" className="btn btn-primary" disabled={pending || picked.length !== owe.count} onClick={() => act({ type: 'returnTax', cardIds: picked })}>
|
||
{picked.length === owe.count ? `돌려주기 (${picked.length}장)` : `${owe.count - picked.length}장 더 골라 주세요`}
|
||
</button>
|
||
</div>
|
||
</>
|
||
) : (
|
||
my && <HandPreview hand={my.hand} />
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- log
|
||
|
||
function logText(e: LogEntry, players: Record<string, PublicUser>): 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 (
|
||
<div className="dm-tip">
|
||
<span>💡 숫자가 낮을수록 강해요 · 앞사람과 같은 장수로만 낼 수 있어요</span>
|
||
<button
|
||
type="button"
|
||
aria-label="도움말 닫기"
|
||
onClick={() => {
|
||
setHidden(true);
|
||
try {
|
||
localStorage.setItem(TIP_KEY, '1');
|
||
} catch {}
|
||
}}
|
||
>
|
||
✕
|
||
</button>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function RevolutionBanner({ v, players, me }: { v: DalmutiView; players: Record<string, PublicUser>; me: string | null }) {
|
||
if (v.revolution === 'none' || !v.revolutionBy || v.phase !== 'playing') return null;
|
||
const who = v.revolutionBy === me ? '내가' : `${nick(players, v.revolutionBy)}님이`;
|
||
return (
|
||
<div className="dm-rev" role="status">
|
||
{v.revolution === 'great'
|
||
? `🃏🃏 대혁명! ${who} 광대 2장으로 신분을 완전히 뒤집었어요. 세금은 없어요`
|
||
: `🃏🃏 혁명! ${who} 광대 2장을 보여 줬어요. 이번 라운드는 세금이 없어요`}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function DalmutiBoard({ view: v, me, players, act, pending, deadline }: BoardProps<DalmutiView>) {
|
||
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 (
|
||
<div className="dm">
|
||
<style>{CSS}</style>
|
||
<Tip />
|
||
<Seats v={v} players={players} me={me} deadline={deadline} />
|
||
<RevolutionBanner v={v} players={players} me={me} />
|
||
{v.phase === 'revolutionCheck' && <RevolutionPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||
{v.phase === 'taxReturn' && <TaxPanel v={v} players={players} me={me} act={act} pending={pending} />}
|
||
{v.phase === 'playing' && <TableArea v={v} players={players} me={me} />}
|
||
{v.phase === 'playing' && v.my && <PlayHand v={v} act={act} pending={pending} />}
|
||
{v.phase === 'finished' && v.result && (
|
||
<div className="dm-panel">
|
||
<h3>게임이 끝났어요</h3>
|
||
<span>{v.result.summary}</span>
|
||
</div>
|
||
)}
|
||
<p className="sr-only" aria-live="polite">
|
||
{announce}
|
||
</p>
|
||
{banner}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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<string, PublicUser>, showBanner: ReturnType<typeof useBanner>[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<DalmutiView>) {
|
||
const phaseKo = v.phase === 'revolutionCheck' ? '손패 확인' : v.phase === 'taxReturn' ? '세금 교환' : v.phase === 'playing' ? '진행 중' : '게임 끝';
|
||
const rounds = v.roundResults;
|
||
return (
|
||
<>
|
||
<style>{CSS}</style>
|
||
<div className="card stack" style={{ gap: 6, padding: 12 }}>
|
||
<div className="row" style={{ justifyContent: 'space-between' }}>
|
||
<strong>
|
||
달무티 · {Math.min(v.round, v.options.rounds)}/{v.options.rounds}라운드 · {phaseKo}
|
||
</strong>
|
||
{v.phase !== 'finished' && <TurnTimer deadline={deadline} totalMs={v.deadlineTotalMs} mine={isMyTurn(v, me)} size={36} />}
|
||
</div>
|
||
<span className="small muted">{rulesLine(v.options)}</span>
|
||
<ol style={{ listStyle: 'none', margin: 0, padding: 0, display: 'grid', gap: 4 }}>
|
||
{v.seats.map((s) => (
|
||
<li key={s.id} className="row" style={{ gap: 6, flexWrap: 'nowrap' }} aria-label={seatLabel(s, v, players, me)}>
|
||
<span aria-hidden style={{ width: 22, textAlign: 'center' }}>
|
||
{TITLE_ICON[s.title]}
|
||
</span>
|
||
<Avatar user={userOf(players, s.id)} size={22} />
|
||
<span style={{ flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: s.id === me ? 800 : 600 }} aria-hidden>
|
||
{s.isTurn && v.phase === 'playing' ? '▶ ' : ''}
|
||
{nick(players, s.id)}
|
||
{s.id === me ? ' (나)' : ''} <span className="small muted">{s.title}</span>
|
||
</span>
|
||
<span className="small" aria-hidden>
|
||
{s.total}점
|
||
</span>
|
||
<span className="dm-count" aria-hidden>
|
||
<i />
|
||
{s.cards}
|
||
</span>
|
||
</li>
|
||
))}
|
||
</ol>
|
||
</div>
|
||
{rounds.length > 0 && (
|
||
<div className="card" style={{ padding: 12, overflowX: 'auto', flex: 'none' }}>
|
||
<strong>라운드 순위</strong>
|
||
<table className="dm-rules small" style={{ borderCollapse: 'collapse', width: '100%', marginTop: 6 }}>
|
||
<thead>
|
||
<tr>
|
||
<th scope="col">이름</th>
|
||
{rounds.map((r) => (
|
||
<th key={r.round} scope="col">
|
||
{r.round}R
|
||
</th>
|
||
))}
|
||
<th scope="col">합계</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{(v.result ? v.result.players.map((p) => p.player) : v.seats.map((s) => s.id)).map((p) => (
|
||
<tr key={p}>
|
||
<th scope="row" style={{ fontWeight: p === me ? 800 : 600 }}>
|
||
{nick(players, p)}
|
||
</th>
|
||
{rounds.map((r) => (
|
||
<td key={r.round}>{r.order.indexOf(p) + 1}등</td>
|
||
))}
|
||
<td>
|
||
<b>{v.seats.find((s) => s.id === p)?.total ?? 0}점</b>
|
||
</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
{v.result && <p className="small muted" style={{ margin: '6px 0 0' }}>{v.result.summary}</p>}
|
||
</div>
|
||
)}
|
||
{v.log.length > 0 && (
|
||
<details className="card wide-open" open style={{ padding: 12 }}>
|
||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>기록</summary>
|
||
<ol className="dm-log">
|
||
{[...v.log].reverse().map((e, i) => (
|
||
<li key={`${e.seq}-${e.t}-${i}`} className="small">
|
||
{logText(e, players)}
|
||
</li>
|
||
))}
|
||
</ol>
|
||
</details>
|
||
)}
|
||
<details className="card" style={{ padding: 12 }}>
|
||
<summary style={{ cursor: 'pointer', fontWeight: 700 }}>카드 장수표</summary>
|
||
<CardTable removeHigh={v.options.removeHighCards} />
|
||
</details>
|
||
</>
|
||
);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 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, PublicUser>): 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<T extends string | number | boolean | null>({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) {
|
||
return (
|
||
<div className="segmented" role="group" aria-label={label}>
|
||
{options.map(([k, l]) => (
|
||
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
|
||
{l}
|
||
</button>
|
||
))}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
function Field({ label, children, help }: { label: string; children: ReactNode; help?: string }) {
|
||
return (
|
||
<div className="stack" style={{ gap: 6 }}>
|
||
<strong>{label}</strong>
|
||
{children}
|
||
{help && <span className="small muted">{help}</span>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const onOff: [boolean, string][] = [
|
||
[true, '켜기'],
|
||
[false, '끄기'],
|
||
];
|
||
|
||
function Options({ value: o, onChange }: OptionsProps<DalmutiOptions>) {
|
||
const [more, setMore] = useState(false);
|
||
const set = (patch: Partial<DalmutiOptions>) => onChange({ ...o, ...patch });
|
||
return (
|
||
<div className="stack" style={{ gap: 16 }}>
|
||
<Field label="라운드 수" help="라운드마다 손패를 다 낸 순서대로 다음 라운드 신분이 정해져요.">
|
||
<Seg label="라운드 수" value={o.rounds} options={[[1, '1라운드'], [3, '3라운드'], [5, '5라운드'], [7, '7라운드']]} onChange={(rounds) => set({ rounds })} />
|
||
</Field>
|
||
<Field label="최종 순위 방식">
|
||
<Seg label="최종 순위 방식" value={o.scoring} options={[['rank-points', '순위 점수 합'], ['last-round', '마지막 라운드 순위']]} onChange={(scoring) => set({ scoring })} />
|
||
</Field>
|
||
<Field label="혁명 규칙" help="광대 2장을 가진 사람이 선언하면 세금이 없어요. 대농노가 선언하면 신분이 뒤집혀요.">
|
||
<Seg label="혁명 규칙" value={o.revolution} options={onOff} onChange={(revolution) => set({ revolution })} />
|
||
</Field>
|
||
<Field label="한 턴 제한 시간">
|
||
<Seg label="한 턴 제한 시간" value={o.turnSeconds} options={[[15, '15초'], [20, '20초'], [30, '30초'], [45, '45초'], [null, '무제한']]} onChange={(turnSeconds) => set({ turnSeconds })} />
|
||
</Field>
|
||
<button type="button" className="btn btn-ghost" onClick={() => setMore(!more)} aria-expanded={more}>
|
||
{more ? '▲ 자세한 설정 닫기' : '▼ 자세한 설정'}
|
||
</button>
|
||
{more && (
|
||
<>
|
||
<Field label="첫 라운드 신분 정하기">
|
||
<Seg label="첫 라운드 신분 정하기" value={o.firstRanking} options={[['draw', '카드 한 장씩 뽑기'], ['random', '무작위']]} onChange={(firstRanking) => set({ firstRanking })} />
|
||
</Field>
|
||
<Field label="세금 낼 때 광대도 좋은 카드로 내기">
|
||
<Seg label="세금에 광대 포함" value={o.jesterTaxable} options={onOff} onChange={(jesterTaxable) => set({ jesterTaxable })} />
|
||
</Field>
|
||
<Field label="한 번 패스하면 그 트릭에서 빠지기">
|
||
<Seg label="패스하면 트릭에서 빠지기" value={o.passLocksOut} options={onOff} onChange={(passLocksOut) => set({ passLocksOut })} />
|
||
</Field>
|
||
<Field label="9~12 카드 빼기" help="38장으로 짧게 해요.">
|
||
<Seg label="9~12 카드 빼기" value={o.removeHighCards} options={onOff} onChange={(removeHighCards) => set({ removeHighCards })} />
|
||
</Field>
|
||
</>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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 (
|
||
<table className="dm-rules small" style={{ borderCollapse: 'collapse', width: '100%', marginTop: 8 }}>
|
||
<thead>
|
||
<tr>
|
||
<th scope="col">카드</th>
|
||
<th scope="col">숫자</th>
|
||
<th scope="col">이름</th>
|
||
<th scope="col">장수</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
{rows.map((n) => (
|
||
<tr key={n}>
|
||
<td style={{ width: 36 }}>
|
||
<CardArt n={n} />
|
||
</td>
|
||
<td>{n === JESTER ? '13 / 와일드' : n}</td>
|
||
<td>{CARD_NAME[n]}</td>
|
||
<td>{n === JESTER ? 2 : n}장</td>
|
||
</tr>
|
||
))}
|
||
</tbody>
|
||
</table>
|
||
);
|
||
}
|
||
|
||
function Rules({ options }: { options?: DalmutiOptions }) {
|
||
const o = options;
|
||
const titles: Title[] = ['대달무티', '소달무티', '평민', '소농노', '대농노'];
|
||
return (
|
||
<div className="stack">
|
||
<p>
|
||
<strong>숫자가 낮을수록 강해요.</strong> 손패를 먼저 다 내는 사람이 다음 라운드에서 높은 신분이 돼요. 4~8명이 해요.
|
||
</p>
|
||
<p>
|
||
새로 시작하는 사람은 <strong>같은 숫자 카드</strong>를 원하는 장수만큼 내요. 다음 사람부터는 <strong>같은 장수</strong>로 <strong>더 낮은 숫자</strong>를 내거나 패스해요. 낸 사람
|
||
말고 모두 패스하면 바닥을 치우고 마지막에 낸 사람이 새로 시작해요.
|
||
{o?.passLocksOut ? ' 이 방에서는 한 번 패스하면 그 트릭이 끝날 때까지 빠져요.' : ' 패스해도 차례가 다시 오면 낼 수 있어요.'}
|
||
</p>
|
||
<p>
|
||
<strong>광대</strong>는 혼자 내면 13이에요. 숫자 카드와 함께 내면 그 숫자로 바뀌어요(예: 4 + 광대 = 4 두 장).
|
||
</p>
|
||
<p>
|
||
<strong>신분</strong>: {titles.map((t) => `${TITLE_ICON[t]} ${t}`).join(' → ')} (4명이면 평민이 없어요). 라운드를 시작할 때 대농노는 가장 좋은 카드 2장을 대달무티에게, 소농노는
|
||
1장을 소달무티에게 세금으로 줘요. 받은 사람은 아무 카드나 같은 장수만큼 돌려줘요.
|
||
</p>
|
||
{(o?.revolution ?? true) && (
|
||
<p>
|
||
<strong>혁명</strong>: 손패를 확인할 때 광대 2장을 다 가진 사람은 혁명을 선언할 수 있어요. 그 라운드는 세금이 없어요. 대농노가 선언하면 <strong>대혁명</strong>으로 신분이 완전히
|
||
뒤집혀요.
|
||
</p>
|
||
)}
|
||
<p>
|
||
라운드에서 1등은 (사람 수 − 1)점, 마지막 순위는 0점을 받아요. {o?.scoring === 'last-round' ? '이 방은 마지막 라운드 순위가 최종 순위예요.' : '총점이 높은 사람이 이기고, 같으면 마지막 라운드 순위로 정해요.'}{' '}
|
||
점수는 이 방 안에서만 쓰는 표시용이에요.
|
||
</p>
|
||
<p>
|
||
{o?.turnSeconds === null ? '이 방은 시간 제한이 없어요. 다만 연결이 끊긴 채 오래 돌아오지 않으면' : '시간 안에 고르지 않으면'} 새로 시작할 때는 가장 큰 숫자 카드를 모두 내고, 따라 낼 때는
|
||
패스해요.
|
||
</p>
|
||
<CardTable removeHigh={o?.removeHighCards} />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
const ui: GameUI<DalmutiView, DalmutiOptions> = {
|
||
Board: DalmutiBoard,
|
||
Side: DalmutiSide,
|
||
statusText,
|
||
isMyTurn,
|
||
Options,
|
||
optionsSummary,
|
||
Rules,
|
||
quickStart,
|
||
helpNow,
|
||
};
|
||
|
||
export default ui;
|