윷놀이: 증강 윷놀이 옵션 추가 (원작 증강 71개 + 추가 10개, 증강 탭·선택 창·능력·알까기·특수 승리)

- 엔진 aug.ts: 라운드·동시 비공개 증강 선택(1·6·12 등, 혼돈 모드, 후보 수, 제외 목록), 질문(거머리·접기·돌림판·투표·색 맞히기 등),
  특수 말·보호막·함께 서기·함정/선물/똥/마늘/조준/지뢰, 특수 승리·탈락·순위, 컴퓨터(aug-bot.ts), 알까기 물리(physics.ts)
- 화면: 방 설정 [게임 종류] + [증강 윷놀이] 탭(켜기/끄기·찾기), 증강 선택 창, 내 증강 쓰기, 증강 칸, 특수 승리 팝업, 안개, 알까기 조준
- 문서 docs/games/yut-augmented.md, 테스트 aug.test.ts 59개, e2e yut-aug

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-19 22:42:52 +09:00
parent d40ba1e121
commit 28ef4ed947
21 changed files with 5928 additions and 41 deletions

View File

@@ -0,0 +1,172 @@
/** 증강 윷놀이 방 설정 (docs/games/yut-augmented.md): 혼돈 모드, 고르는 라운드, 후보 수, 나오게 할 증강 목록. */
import { useState } from 'react';
import type { YutOptions } from '@bg/games/yut';
import { AUGS, AUG_IDS, AUG_ROUNDS, KIND_KO, TIER_KO, selectionTier, type AugId, type AugRoundsKey, type AugTier } from '@bg/games/yut/augments';
const CATS: { key: string; title: string; ids: AugId[] }[] = [
{ key: 'any', title: '범용', ids: AUG_IDS.filter((id) => AUGS[id].tier === 'any' && !AUGS[id].custom) },
{ key: 'start', title: '시작 전용', ids: AUG_IDS.filter((id) => AUGS[id].tier === 'start' && !AUGS[id].custom) },
{ key: 'mid', title: '중간 전용', ids: AUG_IDS.filter((id) => AUGS[id].tier === 'mid' && !AUGS[id].custom) },
{ key: 'final', title: '마무리 전용', ids: AUG_IDS.filter((id) => AUGS[id].tier === 'final' && !AUGS[id].custom) },
{ key: 'custom', title: '이 사이트 추가', ids: AUG_IDS.filter((id) => AUGS[id].custom) },
];
const WIN_IDS = AUG_IDS.filter((id) => AUGS[id].win);
const CUSTOM_IDS = AUG_IDS.filter((id) => AUGS[id].custom);
const ROUND_LABELS: Record<AugRoundsKey, string> = { standard: '1·6·12라운드', quick: '1·4·8라운드', many: '1·3·5·7·9라운드' };
const AUG_CSS = `
.yut-aug-tools { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.yut-aug-cat { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 10px; border: 1px dashed var(--border); border-radius: 12px; min-width: 0; }
.yut-aug-cat-head { display: flex; flex-wrap: wrap; gap: 6px 8px; align-items: center; }
.yut-aug-cat-head strong { margin-right: auto; }
.yut-aug-row { display: flex; gap: 10px; align-items: flex-start; min-height: 44px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); cursor: pointer; min-width: 0; }
.yut-aug-row.off { opacity: .6; }
.yut-aug-row input { flex: none; width: 22px; height: 22px; margin: 1px 0 0; accent-color: var(--primary); }
.yut-aug-body { display: flex; flex-direction: column; gap: 2px; min-width: 0; overflow-wrap: anywhere; }
.yut-aug-name { display: flex; flex-wrap: wrap; gap: 4px 6px; align-items: center; font-weight: 700; }
.yut-aug-badge { border-radius: 999px; padding: 0 7px; font-size: .75rem; font-weight: 700; background: var(--primary-soft); color: var(--text); white-space: nowrap; }
.yut-aug-badge.win { background: var(--warning-soft, var(--primary-soft)); }
.yut-aug-warn { color: var(--danger); }
`;
function Seg<T extends string | number>({ value, options, onChange }: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
return (
<div className="segmented">
{options.map(([k, l]) => (
<button key={String(k)} type="button" aria-pressed={value === k} onClick={() => onChange(k)}>
{l}
</button>
))}
</div>
);
}
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
return (
<div className="stack" style={{ gap: 6 }}>
<strong>{label}</strong>
{children}
{hint && <span className="small muted">{hint}</span>}
</div>
);
}
export function AugOptions({ value: o, onChange }: { value: YutOptions; onChange: (patch: Partial<YutOptions>) => void }) {
const [query, setQuery] = useState('');
const [open, setOpen] = useState<Record<string, boolean>>({});
const off = new Set<AugId>(o.augOff ?? []);
/** Keep `augOff` in AUG_IDS order so the value is stable. */
const setOff = (next: Set<AugId>) => onChange({ augOff: AUG_IDS.filter((id) => next.has(id)) });
const toggle = (id: AugId) => {
const next = new Set(off);
if (next.has(id)) next.delete(id);
else next.add(id);
setOff(next);
};
const setMany = (ids: readonly AugId[], on: boolean) => {
const next = new Set(off);
for (const id of ids) {
if (on) next.delete(id);
else next.add(id);
}
setOff(next);
};
const roundsKey: AugRoundsKey = o.augRounds ?? 'standard';
const n = AUG_ROUNDS[roundsKey].length;
const tiers = [...new Set(Array.from({ length: n }, (_, i) => selectionTier(i, n)))];
const warnings = tiers.flatMap((t: Exclude<AugTier, 'any'>) => {
const c = AUG_IDS.filter((id) => !off.has(id) && (AUGS[id].tier === 'any' || AUGS[id].tier === t)).length;
return c < 3 ? [`${TIER_KO[t]} 선택 때 나올 수 있는 증강이 ${c}개뿐이에요(범용 + ${TIER_KO[t]}). 후보가 적게 나오거나 아예 안 나올 수 있어요.`] : [];
});
const q = query.trim().toLowerCase();
const match = (id: AugId) => !q || AUGS[id].name.toLowerCase().includes(q) || AUGS[id].text.toLowerCase().includes(q);
const onCount = AUG_IDS.length - off.size;
return (
<div className="stack" style={{ gap: 16 }}>
<style>{AUG_CSS}</style>
<Field label="혼돈 모드" hint="증강을 고를 때마다 두 번씩 골라요.">
<Seg value={o.augChaos ? 'on' : 'off'} options={[['off', '끄기'], ['on', '켜기(한 번에 2개)']]} onChange={(k) => onChange({ augChaos: k === 'on' })} />
</Field>
<Field label="증강을 고르는 라운드" hint="첫 선택은 범용 + 시작 전용, 마지막 선택은 범용 + 마무리 전용, 그 사이는 범용 + 중간 전용 증강 중에서 나와요.">
<Seg value={roundsKey} options={(Object.keys(AUG_ROUNDS) as AugRoundsKey[]).map((k) => [k, ROUND_LABELS[k]])} onChange={(augRounds) => onChange({ augRounds })} />
</Field>
<Field label="후보 수" hint="한 번 고를 때 보여 주는 증강 수예요.">
<Seg value={o.augOffers ?? 3} options={[[2, '2개'], [3, '3개'], [4, '4개']]} onChange={(augOffers) => onChange({ augOffers })} />
</Field>
<div className="stack" style={{ gap: 10 }}>
<strong>
나오게 할 증강 <span className="yut-rules-count">켜진 증강 {onCount}/{AUG_IDS.length}</span>
</strong>
<span className="small muted">끈 증강은 후보에 나오지 않아요.</span>
<input className="input" type="search" placeholder="증강 이름이나 설명으로 찾기" aria-label="증강 찾기" value={query} onChange={(e) => setQuery(e.target.value)} />
<div className="yut-aug-tools">
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setOff(new Set())} disabled={off.size === 0}>
전체 켜기
</button>
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(WIN_IDS, false)}>
승리 조건 증강 끄기
</button>
<button type="button" className="btn btn-secondary btn-sm" onClick={() => setMany(CUSTOM_IDS, false)}>
추가 증강 끄기
</button>
</div>
{warnings.map((w) => (
<span key={w} className="small yut-aug-warn" role="status">
⚠ {w}
</span>
))}
{CATS.map((cat) => {
const shown = cat.ids.filter(match);
if (!shown.length) return null;
const on = cat.ids.filter((id) => !off.has(id)).length;
const showRows = !!q || !!open[cat.key];
return (
<section key={cat.key} className="yut-aug-cat" aria-label={cat.title}>
<div className="yut-aug-cat-head">
<button
type="button"
className="btn btn-ghost btn-sm"
style={{ marginRight: 'auto', fontWeight: 800 }}
aria-expanded={showRows}
onClick={() => setOpen((o) => ({ ...o, [cat.key]: !o[cat.key] }))}
>
{showRows ? '▲' : '▼'} {cat.title} <span className="small muted" style={{ marginLeft: 6 }}>켜짐 {on}/{cat.ids.length}</span>
</button>
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setMany(cat.ids, true)} disabled={on === cat.ids.length}>
모두 켜기
</button>
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setMany(cat.ids, false)} disabled={on === 0}>
모두 끄기
</button>
</div>
{showRows && shown.map((id) => {
const a = AUGS[id];
const enabled = !off.has(id);
return (
<label key={id} className={`yut-aug-row${enabled ? '' : ' off'}`} title={a.note}>
<input type="checkbox" checked={enabled} onChange={() => toggle(id)} />
<span className="yut-aug-body">
<span className="yut-aug-name">
{a.name}
{cat.key === 'custom' && a.tier !== 'any' && <span className="yut-aug-badge">{TIER_KO[a.tier]}</span>}
<span className={`yut-aug-badge${a.kind === 'win' ? ' win' : ''}`}>{KIND_KO[a.kind]}</span>
{a.once && <span className="yut-aug-badge">1회</span>}
{a.win && a.kind !== 'win' && <span className="yut-aug-badge win">승리 조건</span>}
</span>
<span className="small muted">{a.text}</span>
{a.note && <span className="small muted" style={{ fontSize: '.8rem' }}>{a.note}</span>}
</span>
</label>
);
})}
</section>
);
})}
{q && CATS.every((c) => !c.ids.some(match)) && <span className="small muted">'{query.trim()}'에 맞는 증강이 없어요.</span>}
</div>
</div>
);
}

View File

@@ -0,0 +1,746 @@
/**
* 증강 윷놀이 screen parts (docs/games/yut-augmented.md §화면): augment selection, prompts, popups, the "내 증강" panel,
* board objects, fog, special-piece badges and the 알까기 aim / replay. Used by index.tsx only when `view.aug` exists.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
import type { AugFx, AugUseOption, PieceKind, YutAugView, YutView } from '@bg/games/yut';
import { AUGS, KIND_KO, TIER_KO, type AugId } from '@bg/games/yut/augments';
import { NODE_POS } from '@bg/games/yut/board';
import type { PublicUser } from '@bg/shared/lite';
import { Sheet } from '../../components/ui';
import { haptic, sounds } from '../../lib/feedback';
import { fxMs } from '../../lib/motion';
type Act = (a: unknown) => void;
const nick = (players: Record<string, PublicUser>, id: string | undefined) => (id ? (players[id]?.nickname ?? '알 수 없음') : '알 수 없음');
const SOLO = ['빨강', '파랑', '초록', '노랑'];
const COLORS = ['#dc2626', '#2563eb', '#16a34a', '#eab308'];
export const augSideName = (side: number) => SOLO[side] ?? '?';
const playerOf = (v: YutView, side: number) => v.sides[side]?.members[0];
const who = (v: YutView, players: Record<string, PublicUser>, side: number) => {
const p = playerOf(v, side);
return p ? `${nick(players, p)}(${augSideName(side)})` : augSideName(side);
};
export const AUG_CSS = `
.aug-chip { display: inline-flex; align-items: center; gap: 4px; min-height: 30px; padding: 2px 8px; border-radius: 10px; border: 2px solid var(--border);
background: var(--surface-2, var(--surface)); font-size: .8rem; font-weight: 700; line-height: 1.15; position: relative; max-width: 100%; }
.aug-chip.used { opacity: .6; }
.aug-chip.used::after { content: '✔'; position: absolute; right: -6px; top: -8px; width: 18px; height: 18px; border-radius: 50%; background: var(--danger); color: #fff; font-size: .7rem; display: grid; place-items: center; }
.aug-chip.voided { text-decoration: line-through; opacity: .5; }
.aug-chip.cat { border-style: dashed; }
.aug-chip small { font-weight: 600; color: var(--text-sub); }
.aug-chip.win { border-color: #f59e0b; }
.aug-slots { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
.aug-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
.aug-card { text-align: left; border: 3px solid var(--border); border-radius: 14px; background: var(--surface); color: var(--text); padding: 10px 12px; cursor: pointer;
display: flex; flex-direction: column; gap: 6px; min-height: 120px; font: inherit; }
.aug-card[aria-pressed='true'] { border-color: var(--primary); background: var(--primary-soft); }
.aug-card:disabled { cursor: not-allowed; opacity: .55; }
.aug-card h3 { margin: 0; font-size: 1.05rem; }
.aug-card p { margin: 0; font-size: .9rem; }
.aug-tags { display: flex; gap: 4px; flex-wrap: wrap; }
.aug-tag { font-size: .7rem; font-weight: 800; border-radius: 999px; padding: 1px 7px; background: var(--primary-soft); color: var(--text); }
.aug-tag.win { background: #fde68a; color: #78350f; }
.aug-tag.custom { background: #ddd6fe; color: #4c1d95; }
.aug-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; font-weight: 700; }
.aug-bar .muted { font-weight: 600; }
.aug-popup { text-align: center; display: flex; flex-direction: column; gap: 10px; align-items: center; }
.aug-popup .kicker { color: var(--danger); font-weight: 800; }
.aug-popup h2 { margin: 0; font-size: 2rem; }
.aug-toast { position: absolute; left: 50%; bottom: 10px; transform: translateX(-50%); z-index: 5; max-width: 92%; background: rgba(17, 24, 39, .88); color: #fff;
padding: 8px 14px; border-radius: 12px; font-weight: 700; font-size: .92rem; text-align: center; pointer-events: none; animation: aug-toast 3.2s ease both; }
@keyframes aug-toast { 0% { opacity: 0; transform: translate(-50%, 6px); } 8%, 85% { opacity: 1; transform: translate(-50%, 0); } 100% { opacity: 0; } }
.aug-uses { display: flex; flex-direction: column; gap: 8px; }
.aug-use-row { display: flex; flex-wrap: wrap; gap: 6px; }
.aug-target-list { display: flex; flex-wrap: wrap; gap: 6px; max-height: 220px; overflow: auto; }
.aug-target-list .btn { min-height: 44px; }
.aug-plan { display: flex; flex-wrap: wrap; gap: 8px; }
.aug-board-wrap { position: relative; }
.aug-aim { touch-action: none; cursor: crosshair; }
.sheet:has(.aug-cards) { width: min(100%, 780px); }
@media (prefers-reduced-motion: reduce) { .aug-toast { animation: none; } }
`;
// ---------------------------------------------------------------- round bar
export function AugRoundBar({ v }: { v: YutView }) {
const a = v.aug!;
const next = a.rounds[a.selectNo];
return (
<div className="aug-bar small" aria-label="증강 윷놀이 진행">
<span>🌀 {a.round}라운드</span>
<span className="muted">{next !== undefined ? `다음 증강 선택: ${next}라운드` : '증강 선택 끝'}</span>
{a.echo && <span className="aug-tag">메아리: 차례 두 번씩</span>}
{a.fogOwner !== null && <span className="aug-tag">🌫 안개</span>}
{a.winsOff && <span className="aug-tag win">특수 승리 취소됨</span>}
</div>
);
}
// ---------------------------------------------------------------- slots in the side card
export function AugSlots({ v, side }: { v: YutView; side: number }) {
const s = v.aug?.sides.find((x) => x.id === side);
if (!s) return null;
const info: string[] = [];
if (s.sticks !== 4) info.push(`윷가락 ${s.sticks}개`);
if (s.skip) info.push(`건너뛰기 ${s.skip}번`);
if (s.hp !== null) info.push(`체력 ${'❤'.repeat(Math.max(0, s.hp))}${s.hp <= 0 ? '0' : ''}`);
if (s.queenLives !== null) info.push(`👑 목숨 ${s.queenLives}`);
for (const l of s.links) info.push(`${l.by === 'leech' ? '🩸 거머리' : '💀 네크로'} → ${augSideName(l.to)}`);
return (
<>
{info.length > 0 && <div className="small muted" style={{ marginTop: 6 }}>{info.join(' · ')}</div>}
<div className="aug-slots" aria-label="가진 증강">
{s.augs.length === 0 && <span className="small muted">증강 없음</span>}
{s.augs.map((o) => {
const meta = AUGS[o.id];
const cat = o.catUntil !== null;
return (
<span
key={o.uid}
className={`aug-chip${o.used ? ' used' : ''}${o.voided ? ' voided' : ''}${cat ? ' cat' : ''}${meta.win ? ' win' : ''}`}
title={`${meta.name}: ${meta.text}${meta.note ? ` (${meta.note})` : ''}`}
aria-label={`${meta.name}${o.used ? ' (사용함)' : ''}${o.voided ? ' (무효)' : ''}${cat ? ` (${o.catUntil}라운드까지 고양이)` : ''}${o.note ? `, ${o.note}` : ''}`}
>
{cat ? '🐱 ' : ''}
{meta.name}
{o.note && <small>{o.note}</small>}
</span>
);
})}
</div>
</>
);
}
// ---------------------------------------------------------------- selection
function AugCard({ id, picked, onPick, disabled }: { id: AugId; picked: boolean; onPick: () => void; disabled?: boolean }) {
const m = AUGS[id];
return (
<button type="button" className="aug-card" aria-pressed={picked} onClick={onPick} disabled={disabled}>
<h3>{m.name}</h3>
<span className="aug-tags">
<span className="aug-tag">{TIER_KO[m.tier]}</span>
<span className="aug-tag">{KIND_KO[m.kind]}</span>
{m.once && <span className="aug-tag">1회</span>}
{m.win && <span className="aug-tag win">승리 조건</span>}
{m.custom && <span className="aug-tag custom">추가</span>}
</span>
<p>{m.text}</p>
{m.note && <p className="small muted">{m.note}</p>}
</button>
);
}
export function AugSelect({ v, act, pending, players }: { v: YutView; act: Act; pending: boolean; players: Record<string, PublicUser> }) {
const sel = v.aug!.select!;
const [choice, setChoice] = useState<AugId | null>(null);
const [target, setTarget] = useState<AugId | ''>('');
const [open, setOpen] = useState(true);
const mine = sel.offers.length > 0 && sel.picksLeft > 0;
const key = sel.offers.join(',');
useEffect(() => {
setChoice(sel.forced);
setTarget('');
if (mine) setOpen(true);
}, [key]); // eslint-disable-line react-hooks/exhaustive-deps
const tierText = { start: '범용 + 시작 전용', mid: '범용 + 중간 전용', final: '범용 + 마무리 전용' }[sel.tier];
const targets = choice === 'detective' ? sel.detectiveTargets : choice === 'delivery' ? sel.deliveryTargets : [];
const needTarget = choice === 'detective' || (choice === 'delivery' && targets.length > 0);
const waiting = sel.waiting.map((s) => who(v, players, s)).join(', ');
if (!mine) {
return (
<div className="card" style={{ padding: 12 }} role="status">
<strong>{v.aug!.round}라운드 증강 선택 중</strong>
<div className="small muted">{waiting ? `${waiting}님이 고르는 중이에요.` : '곧 끝나요.'}</div>
</div>
);
}
const confirm = () => {
if (!choice || (needTarget && !target)) return;
act({ type: 'AUG_PICK', aug: choice, ...(needTarget ? { target } : {}) });
haptic(30);
};
return (
<>
<div className="card" style={{ padding: 12, display: 'flex', flexDirection: 'column', gap: 8 }}>
<strong>🎁 증강을 골라 주세요{sel.picksLeft > 1 ? ` (혼돈 모드: ${sel.picksLeft}개 남음)` : ''}</strong>
<button type="button" className="btn btn-primary" onClick={() => setOpen(true)}>
증강 후보 보기
</button>
</div>
{open && (
<Sheet onClose={() => setOpen(false)} label={`${v.aug!.round}라운드 증강 선택`}>
<div className="stack" style={{ gap: 4, textAlign: 'center' }}>
<h2 style={{ margin: 0 }}>{v.aug!.round}라운드 증강 선택</h2>
<span className="small muted">
이 후보와 고른 것은 나에게만 보여요. {sel.offers.length}개 중 하나를 고르세요. ({tierText})
</span>
{sel.forced && <span className="small" style={{ color: 'var(--danger)', fontWeight: 700 }}>간택: 고양이가 나와서 고양이를 골라야 해요!</span>}
</div>
<div className="aug-cards" role="group" aria-label="증강 후보">
{sel.offers.map((id) => (
<AugCard key={id} id={id} picked={choice === id} disabled={!!sel.forced && id !== sel.forced} onPick={() => (setChoice(id), setTarget(''))} />
))}
</div>
{needTarget && (
<label className="stack" style={{ gap: 6 }}>
<strong>{choice === 'detective' ? '무효로 만들 증강' : '다음에 받을 증강'}</strong>
<select className="input" value={target} onChange={(e) => setTarget(e.target.value as AugId)}>
<option value="">골라 주세요</option>
{targets.map((t) => (
<option key={t} value={t}>
{AUGS[t].name} ({TIER_KO[AUGS[t].tier]})
</option>
))}
</select>
</label>
)}
<div className="row" style={{ flexWrap: 'nowrap' }}>
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setOpen(false)} aria-label="판 보기(후보 창 잠깐 닫기)">
👁 판 보기
</button>
<button type="button" className="btn btn-primary" style={{ flex: 2 }} disabled={!choice || (needTarget && !target) || pending} onClick={confirm}>
{choice ? `${AUGS[choice].name} 고르기` : '후보를 고른 뒤 확인하세요'}
</button>
</div>
</Sheet>
)}
</>
);
}
// ---------------------------------------------------------------- prompts
const PROMPT_TITLE: Record<NonNullable<YutAugView['prompt']>['kind'], string> = {
leech: '거머리: 누구에게 말을 줄까요?',
fold: '게임 접어라: 어느 쪽으로 접을까요?',
whoami: '나 누구게? 내 색은 무엇일까요?',
vote: '내려: 누가 차례를 건너뛸까요?',
roulette: '돌려돌려 돌림판',
illusion: '언제부터 착각한 거지? 어떤 증강을 고양이로 바꿀까요?',
plan: '계획대로: 최종 순위를 예언해 주세요',
duel: '승부다! 누구와 겨룰까요?',
thief: '손버릇: 어떤 증강을 빼앗을까요?',
};
export function AugPrompt({ v, act, pending, players }: { v: YutView; act: Act; pending: boolean; players: Record<string, PublicUser> }) {
const pr = v.aug!.prompt!;
const [plan, setPlan] = useState<number[]>([]);
const owner = who(v, players, pr.owner);
if (!pr.choices) {
return (
<div className="card" style={{ padding: 12 }} role="status">
<strong>{PROMPT_TITLE[pr.kind].split(':')[0]}</strong>
<div className="small muted">
{pr.kind === 'whoami' || pr.kind === 'vote' ? `${pr.waiting.length}명이 고르는 중이에요.` : `${v.aug!.hidden ? '누군가' : owner}님이 고르는 중이에요.`}
</div>
</div>
);
}
const send = (choice: number | number[]) => act({ type: 'AUG_ANSWER', choice });
if (pr.kind === 'plan') {
const all = pr.choices;
return (
<div className="card stack" style={{ padding: 12, gap: 8 }}>
<strong>{PROMPT_TITLE.plan}</strong>
<span className="small muted">1등부터 차례로 눌러 주세요. 모두 맞히면 나 혼자 이겨요.</span>
<div className="aug-plan">
{all.map((c) => {
const i = plan.indexOf(c.value);
return (
<button key={c.value} type="button" className={`btn ${i >= 0 ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setPlan(i >= 0 ? plan.filter((x) => x !== c.value) : [...plan, c.value])}>
{i >= 0 ? `${i + 1}등 · ` : ''}
{who(v, players, c.value)}
</button>
);
})}
</div>
<button type="button" className="btn btn-primary" disabled={plan.length !== all.length || pending} onClick={() => send(plan)}>
이 순서로 예언하기
</button>
</div>
);
}
return (
<div className="card stack" style={{ padding: 12, gap: 8 }} aria-label={PROMPT_TITLE[pr.kind]}>
<strong>{PROMPT_TITLE[pr.kind]}</strong>
{pr.kind === 'roulette' && (
<span>
돌림판 결과: <strong>{(pr.spin ?? 1) * 90}도</strong> 돌아가요. {pr.canRespin ? '마음에 안 들면 한 번 더 돌릴 수 있어요.' : '이제 그대로 돌아가요.'}
</span>
)}
{pr.kind === 'whoami' && <span className="small muted">말 색이 모두 가려졌어요. 내 말이 어디 있었는지 떠올려 보세요. 틀리면 차례를 한 번 건너뛰어요.</span>}
{pr.kind === 'vote' && <span className="small muted">표를 가장 많이 받은 사람이 차례를 건너뛰어요. {augSideName(pr.owner)}의 표는 2표예요.</span>}
<div className="aug-target-list">
{pr.choices.map((c) => (
<button
key={c.value}
type="button"
className="btn btn-secondary"
disabled={pending}
onClick={() => send(c.value)}
style={pr.kind === 'whoami' || pr.kind === 'vote' || pr.kind === 'leech' || pr.kind === 'duel' ? { borderColor: COLORS[c.value], borderWidth: 3 } : undefined}
>
{pr.kind === 'whoami' ? c.label : pr.kind === 'vote' || pr.kind === 'leech' || pr.kind === 'duel' ? who(v, players, c.value) : c.label}
</button>
))}
</div>
</div>
);
}
// ---------------------------------------------------------------- popups & toasts
/** Shows each new effect once: a dialog for victories / going out, a short toast for the rest. */
export function AugFxLayer({ v, players, me }: { v: YutView; players: Record<string, PublicUser>; me: string | null }) {
const fx = v.aug?.fx ?? [];
const seen = useRef(fx.reduce((m, f) => Math.max(m, f.no), 0));
const [popup, setPopup] = useState<AugFx | null>(null);
const [toast, setToast] = useState<{ key: number; text: string } | null>(null);
useEffect(() => {
const fresh = fx.filter((f) => f.no > seen.current);
if (!fresh.length) return;
seen.current = Math.max(...fresh.map((f) => f.no));
// When the game just ended the result window says it all.
const big = v.phase === 'finished' ? undefined : fresh.find((f) => f.kind === 'win' || f.kind === 'out' || f.kind === 'bronze');
if (big) {
setPopup(big);
const mine = playerOf(v, big.side) === me;
if (big.kind === 'out') (mine ? sounds.lose : sounds.buzz)();
else (mine ? sounds.win : sounds.ding)();
}
const small = fresh.filter((f) => f !== big && f.kind !== 'flick');
if (small.length) setToast({ key: small[small.length - 1]!.no, text: small.map((f) => f.text).join(' · ') });
}, [fx.map((f) => f.no).join(',')]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (!toast) return;
const t = setTimeout(() => setToast(null), fxMs(3200));
return () => clearTimeout(t);
}, [toast]);
return (
<>
{toast && (
<div key={toast.key} className="aug-toast" role="status" aria-live="polite">
{toast.text}
</div>
)}
{popup && (
<Sheet onClose={() => setPopup(null)} label="증강 알림">
<div className="aug-popup">
<span className="kicker">{popup.kind === 'out' ? '탈락' : popup.kind === 'bronze' ? '3위 확정' : popup.aug ? '특수 승리 조건 달성' : '완주'}</span>
<h2>{popup.aug ? AUGS[popup.aug].name : popup.kind === 'out' ? '탈락' : '전원 완주'}</h2>
<strong style={{ color: COLORS[popup.side] }}>{who(v, players, popup.side)}</strong>
<p style={{ margin: 0 }}>{popup.text}</p>
<button type="button" className="btn btn-primary" onClick={() => setPopup(null)} style={{ minWidth: 200 }}>
{popup.rank ? `${popup.rank}위 확보` : '확인'}
</button>
</div>
</Sheet>
)}
</>
);
}
// ---------------------------------------------------------------- my augments panel
export interface AimState {
uid: number;
piece: number;
at: number;
angle: number;
power: number;
}
/** Ability buttons for the player to move; node-target choices can also be tapped on the board (`onTargets`). */
export function AugUses({
v,
act,
pending,
aim,
setAim,
targetUid,
setTargetUid,
}: {
v: YutView;
act: Act;
pending: boolean;
aim: AimState | null;
setAim: (a: AimState | null) => void;
targetUid: number | null;
setTargetUid: (u: number | null) => void;
}) {
const a = v.aug!;
const byUid = useMemo(() => {
const m = new Map<number, AugUseOption[]>();
for (const u of a.uses) m.set(u.uid, [...(m.get(u.uid) ?? []), u]);
return m;
}, [a.uses]);
const specials = a.specials;
if (!byUid.size && !specials.length) return null;
const use = (u: AugUseOption) => {
if (u.id === 'alkkagi') {
if (u.at === undefined || u.at === 'home') return;
setAim({ uid: u.uid, piece: u.action.piece!, at: u.at, angle: 270, power: 60 });
return;
}
act({ type: 'AUG_USE', ...u.action });
setTargetUid(null);
haptic(30);
};
const open = targetUid !== null ? (byUid.get(targetUid) ?? []) : [];
return (
<div className="aug-uses" aria-label="내 증강 쓰기">
<strong className="small">✨ 내 증강 쓰기</strong>
<div className="aug-use-row">
{[...byUid.entries()].map(([uid, opts]) => {
const id = opts[0]!.id;
return (
<button
key={uid}
type="button"
className={`btn btn-sm ${targetUid === uid ? 'btn-primary' : 'btn-secondary'}`}
disabled={pending}
aria-pressed={targetUid === uid}
title={AUGS[id].text}
onClick={() => {
setAim(null);
if (opts.length === 1 && id !== 'alkkagi' && !['sniper', 'mine'].includes(id)) setTargetUid(uid);
else setTargetUid(targetUid === uid ? null : uid);
}}
>
{AUGS[id].name}
</button>
);
})}
</div>
{open.length > 0 && !aim && (
<div className="stack" style={{ gap: 6 }}>
<span className="small muted">
{AUGS[open[0]!.id].text}
{AUGS[open[0]!.id].wholeTurn ? ' (쓰면 이번 차례가 끝나요)' : ''}
{open.some((o) => o.action.node !== undefined && o.action.piece === undefined && o.action.node2 === undefined) ? ' 판에서 칸을 눌러도 돼요.' : ''}
</span>
{open.length > 8 ? (
<ManyTargets opts={open} pending={pending} onUse={use} />
) : (
<div className="aug-target-list">
{open.map((u, i) => (
<button key={i} type="button" className="btn btn-primary btn-sm" disabled={pending} onClick={() => use(u)}>
{open.length === 1 && !u.label ? '사용하기' : u.label}
{u.kills ? ` (잡기 ${u.kills})` : ''}
</button>
))}
</div>
)}
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setTargetUid(null)}>
취소
</button>
</div>
)}
{aim && (
<div className="stack" style={{ gap: 6 }}>
<span className="small">🎯 판에서 말 반대쪽으로 끌었다 놓아 방향과 힘을 정하세요(새총처럼). 아래에서 조절해도 돼요.</span>
<label className="small">
방향 {aim.angle}°
<input type="range" min={0} max={359} value={aim.angle} onChange={(e) => setAim({ ...aim, angle: Number(e.target.value) })} style={{ width: '100%' }} />
</label>
<label className="small">
힘 {aim.power}
<input type="range" min={1} max={100} value={aim.power} onChange={(e) => setAim({ ...aim, power: Number(e.target.value) })} style={{ width: '100%' }} />
</label>
<div className="row" style={{ flexWrap: 'nowrap' }}>
<button
type="button"
className="btn btn-primary"
style={{ flex: 2 }}
disabled={pending}
onClick={() => {
act({ type: 'AUG_USE', uid: aim.uid, piece: aim.piece, angle: aim.angle, power: aim.power });
setAim(null);
setTargetUid(null);
haptic([20, 20, 60]);
}}
>
🫰 튕기기
</button>
<button type="button" className="btn btn-secondary" style={{ flex: 1 }} onClick={() => setAim(null)}>
취소
</button>
</div>
</div>
)}
{specials.length > 0 && (
<div className="stack" style={{ gap: 6 }}>
<strong className="small">특수 말 움직이기 (던지지 않고 한 번)</strong>
<div className="aug-target-list">
{specials.map((m, i) => (
<button key={i} type="button" className="btn btn-secondary btn-sm" disabled={pending} onClick={() => act({ type: 'SPECIAL', piece: m.piece, to: m.to })}>
{KIND_ICON[m.kind]} {m.kind === 'dokkaebi' ? '도깨비' : '포'}: {nodeKo(m.from)} → {nodeKo(m.to)}
{m.captures ? ' (잡기!)' : ''}
</button>
))}
</div>
</div>
)}
</div>
);
}
/** Long target lists (명사수: every node): a select + button. */
function ManyTargets({ opts, pending, onUse }: { opts: AugUseOption[]; pending: boolean; onUse: (u: AugUseOption) => void }) {
const [i, setI] = useState(0);
return (
<div className="row" style={{ flexWrap: 'nowrap' }}>
<select className="input" aria-label="대상 고르기" value={i} onChange={(e) => setI(Number(e.target.value))} style={{ flex: 2, minWidth: 0 }}>
{opts.map((u, k) => (
<option key={k} value={k}>
{u.label}
{u.kills ? ` (잡기 ${u.kills})` : ''}
</option>
))}
</select>
<button type="button" className="btn btn-primary btn-sm" style={{ flex: 1 }} disabled={pending} onClick={() => opts[i] && onUse(opts[i]!)}>
사용하기
</button>
</div>
);
}
const NODE_KO = ['참먹이', '도', '개', '걸', '윷', '모', '뒷도', '뒷개', '뒷걸', '뒷윷', '뒷모', '찌도', '찌개', '찌걸', '찌윷', '찌모', '날도', '날개', '날걸', '날윷', '앞모도', '앞모개', '방', '속윷', '속모', '뒷모도', '뒷모개', '사려', '안찌'];
const nodeKo = (n: number | 'home' | 'goal') => (n === 'home' ? '대기' : n === 'goal' ? '남' : (NODE_KO[n] ?? String(n)));
// ---------------------------------------------------------------- board layers (inside the board <svg>)
export const KIND_ICON: Record<PieceKind, string> = { dokkaebi: '👹', vanguard: '🚩', cannon: '包', pawn: '♟', kim: '🧔', queen: '👑', cultist: '🕯', marathon: '🏃' };
const OBJ_ICON = { skull: '💀', hat: '🎩', gift: '🎁', poop: '💩', garlic: '🧄', mark: '🎯', mine: '💣' } as const;
const OBJ_KO = { skull: '해골 함정', hat: '마녀 모자 함정', gift: '선물', poop: '똥', garlic: '마늘', mark: '명사수 조준', mine: '지뢰' } as const;
export function BoardObjects({ v }: { v: YutView }) {
return (
<g aria-label="판 위의 증강 물건">
{v.aug!.objs.map((o, i) => {
const [x, y] = NODE_POS[o.node]!;
return (
<g key={i} transform={`translate(${x + 3.6} ${y - 3.6})`} aria-label={`${NODE_KO[o.node]}: ${OBJ_KO[o.kind]}`} role="img">
<circle r={2.9} fill="var(--surface)" stroke={o.owner >= 0 ? COLORS[o.owner] : 'var(--wood-line)'} strokeWidth={0.6} opacity={0.95} />
<text textAnchor="middle" dominantBaseline="central" fontSize={3.4}>
{OBJ_ICON[o.kind]}
</text>
</g>
);
})}
</g>
);
}
/** Badge on a token for special pieces, shields and frozen pieces. */
export function TokenBadges({ x, y, r, kind, shield, frozen }: { x: number; y: number; r: number; kind?: PieceKind; shield?: boolean; frozen?: boolean }) {
return (
<g pointerEvents="none">
{shield && <circle cx={x} cy={y} r={r + 1.3} fill="none" stroke="#fbbf24" strokeWidth={0.9} strokeDasharray="1.6 0.8" />}
{kind && (
<text x={x} y={y + 0.2} textAnchor="middle" dominantBaseline="central" fontSize={r * 1.15} fontWeight={900} fill="#fff" stroke="#000" strokeWidth={0.25} paintOrder="stroke">
{KIND_ICON[kind]}
</text>
)}
{frozen && (
<text x={x - r * 0.9} y={y - r * 0.9} textAnchor="middle" dominantBaseline="central" fontSize={r * 0.95}>
❄
</text>
)}
</g>
);
}
/** 안개: everything but the nodes near my pieces is covered. */
export function FogLayer({ v }: { v: YutView }) {
const a = v.aug!;
if (!a.fogged) return null;
const mine = v.stacks.filter((st) => st.side === v.mySide).map((st) => st.node);
const near = new Set<number>(mine);
const NB: Record<number, number[]> = {};
const lines: number[][] = [[0, 1, 2, 3, 4, 5], [5, 6, 7, 8, 9, 10], [10, 11, 12, 13, 14, 15], [15, 16, 17, 18, 19, 0], [5, 20, 21, 22, 23, 24, 15], [10, 25, 26, 22, 27, 28, 0]];
for (const l of lines) for (let i = 0; i + 1 < l.length; i++) ((NB[l[i]!] ??= []).push(l[i + 1]!), (NB[l[i + 1]!] ??= []).push(l[i]!));
for (const n of mine) for (const m of NB[n] ?? []) near.add(m);
return (
<g pointerEvents="none" aria-label="안개: 내 말 근처만 보여요">
<defs>
<mask id="yut-fog-mask">
<rect x={0} y={0} width={100} height={100} fill="#fff" />
{[...near].map((n) => (
<circle key={n} cx={NODE_POS[n]![0]} cy={NODE_POS[n]![1]} r={9} fill="#000" />
))}
</mask>
</defs>
<rect x={0} y={0} width={100} height={100} fill="#94a3b8" opacity={0.82} mask="url(#yut-fog-mask)" />
<text x={50} y={8} textAnchor="middle" fontSize={4} fontWeight={800} fill="#334155">
🌫 안개
</text>
</g>
);
}
/** Replays the last 알까기 (frames from the server). */
export function FlickReplay({ v, draw }: { v: YutView; draw: (side: number, x: number, y: number, count: number, key: string) => React.ReactNode }) {
const f = (v.aug?.fx ?? []).find((x) => x.kind === 'flick' && x.bodies?.length);
const [t, setT] = useState(-1);
const seen = useRef(f?.no ?? 0);
useEffect(() => {
if (!f || f.no === seen.current) return;
seen.current = f.no;
const len = Math.max(...f.bodies!.map((b) => b.pts.length));
let i = 0;
setT(0);
const id = setInterval(() => {
i += 1;
if (i >= len + 8) {
clearInterval(id);
setT(-1);
} else setT(i);
}, fxMs(33));
return () => clearInterval(id);
}, [f?.no]); // eslint-disable-line react-hooks/exhaustive-deps
if (!f || t < 0) return null;
return (
<g pointerEvents="none">
{f.bodies!.map((b, i) => {
const p = b.pts[Math.min(t, b.pts.length - 1)];
if (!p) return null;
const gone = b.out && t >= b.pts.length - 1;
return <g key={i} opacity={gone ? 0 : 1}>{draw(b.side, p[0], p[1], b.count, `fl${i}`)}</g>;
})}
</g>
);
}
/** Slingshot aim: drag away from the piece; the arrow shows where it flies. */
export function FlickAim({ aim, setAim, svg }: { aim: AimState; setAim: (a: AimState) => void; svg: React.RefObject<SVGSVGElement | null> }) {
const [cx, cy] = NODE_POS[aim.at]!;
const dragging = useRef(false);
const toBoard = (e: React.PointerEvent) => {
const el = svg.current;
if (!el) return null;
const pt = el.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
const m = el.getScreenCTM();
if (!m) return null;
const p = pt.matrixTransform(m.inverse());
return [p.x, p.y] as const;
};
const update = (e: React.PointerEvent) => {
const p = toBoard(e);
if (!p) return;
const dx = cx - p[0];
const dy = cy - p[1];
const len = Math.hypot(dx, dy);
if (len < 1) return;
const angle = Math.round(((Math.atan2(dy, dx) * 180) / Math.PI + 360) % 360) % 360;
const power = Math.max(1, Math.min(100, Math.round((len / 30) * 100)));
setAim({ ...aim, angle, power });
};
const rad = (aim.angle * Math.PI) / 180;
const L = 6 + (aim.power / 100) * 26;
const tx = cx + Math.cos(rad) * L;
const ty = cy + Math.sin(rad) * L;
const bx = cx - Math.cos(rad) * (L * 0.5);
const by = cy - Math.sin(rad) * (L * 0.5);
return (
<g>
<rect
className="aug-aim"
x={0}
y={0}
width={100}
height={100}
fill="transparent"
onPointerDown={(e) => {
dragging.current = true;
(e.target as Element).setPointerCapture?.(e.pointerId);
update(e);
}}
onPointerMove={(e) => dragging.current && update(e)}
onPointerUp={() => (dragging.current = false)}
aria-label="알까기 조준: 말 반대쪽으로 끌어서 방향과 힘을 정해요"
/>
<line x1={cx} y1={cy} x2={bx} y2={by} stroke="var(--text-sub)" strokeWidth={0.6} strokeDasharray="1.2 1" pointerEvents="none" />
<line x1={cx} y1={cy} x2={tx} y2={ty} stroke="#f59e0b" strokeWidth={1.6} strokeLinecap="round" pointerEvents="none" />
<polygon
points={`${tx + Math.cos(rad) * 2.6},${ty + Math.sin(rad) * 2.6} ${tx + Math.cos(rad + 2.4) * 2.4},${ty + Math.sin(rad + 2.4) * 2.4} ${tx + Math.cos(rad - 2.4) * 2.4},${ty + Math.sin(rad - 2.4) * 2.4}`}
fill="#f59e0b"
pointerEvents="none"
/>
<circle cx={cx} cy={cy} r={6.6} fill="none" stroke="#f59e0b" strokeWidth={1.2} pointerEvents="none" />
</g>
);
}
/** Node targets of the opened ability (명사수, 지뢰, …): tap a highlighted node to choose it. */
export function NodeTargets({ opts, onPick }: { opts: AugUseOption[]; onPick: (u: AugUseOption) => void }) {
const nodeOpts = opts.filter((o) => o.action.node !== undefined && o.action.piece === undefined && o.action.node2 === undefined);
const pieceOpts = opts.filter((o) => o.at !== undefined && o.at !== 'home' && o.action.node === undefined && o.action.node2 === undefined && o.action.target === undefined);
const pts = [...nodeOpts.map((o) => ({ o, n: o.action.node! })), ...pieceOpts.map((o) => ({ o, n: o.at as number }))];
return (
<g>
{pts.map(({ o, n }, i) => {
const [x, y] = NODE_POS[n]!;
return (
<g key={i} className="yut-hit" role="button" tabIndex={0} aria-label={`${o.label} 고르기`} onClick={() => onPick(o)} onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && (e.preventDefault(), onPick(o))}>
<circle cx={x} cy={y} r={6.2} fill="rgba(245, 158, 11, .18)" stroke="#f59e0b" strokeWidth={1} strokeDasharray="1.6 1" className="yut-can" />
<circle className="yut-focus" cx={x} cy={y} r={7.6} fill="none" stroke="var(--focus)" strokeWidth={1} />
</g>
);
})}
</g>
);
}
// ---------------------------------------------------------------- log & status
/** Log line for 증강 events (null = not an augment event). */
export function augLogLine(e: { type: string; [k: string]: unknown }, v: YutView, players: Record<string, PublicUser>): string | null | undefined {
const sn = (s: unknown) => (typeof s === 'number' && s >= 0 ? augSideName(s) : '누군가');
switch (e.type) {
case 'augSelect':
return `🎁 ${e.round}라운드: 증강을 골라요`;
case 'augPicked':
return `${sn(e.side)}: [${AUGS[e.aug as AugId]?.name ?? ''}]${e.voided ? ' — 명탐정에게 걸려 무효!' : ' 획득'}`;
case 'augEffect':
return String(e.text ?? '');
case 'augCaught':
return `${e.side === null || e.side === undefined ? '' : `${sn(e.side)}이 `}${sn(e.victimSide)} 말 ${e.count}개를 잡았어요${e.aug ? ` (${AUGS[e.aug as AugId]?.name ?? ''})` : ''}`;
case 'augShield':
return `${sn(e.side)}: 보호막이 한 번 막았어요`;
case 'augOut':
return `${sn(e.side)} 탈락! (${e.reason})`;
case 'augSkip':
return `${sn(e.side)}: 차례를 건너뛰어요`;
case 'sideFinished':
return e.aug ? `${sn(e.side)} ${e.rank}위! (${AUGS[e.aug as AugId]?.name ?? ''})` : undefined;
case 'moved':
return e.fog ? `${sn(e.side)}: 안개 속에서 말을 움직였어요` : undefined;
case 'hidden':
return null;
case 'turnChanged':
return null;
}
void v;
void players;
return undefined;
}
export function augStatus(v: YutView, me: string | null, players: Record<string, PublicUser>): string | null {
const a = v.aug;
if (!a) return null;
if (v.phase === 'aug' && a.select) return a.select.offers.length && a.select.picksLeft ? `${a.round}라운드: 증강을 골라 주세요` : `${a.round}라운드: 다른 사람이 증강을 고르는 중이에요`;
if (v.phase === 'prompt' && a.prompt) {
if (a.prompt.choices) return PROMPT_TITLE[a.prompt.kind];
return `${a.hidden ? '누군가' : who(v, players, a.prompt.owner)}의 증강: 고르는 중이에요`;
}
void me;
return null;
}

View File

@@ -21,6 +21,15 @@ function throwReason(v: YutView): 'fresh' | 'yutmo' | 'capture' | 'backdo' {
export function helpNow(v: YutView, me: string | null, players: Record<string, PublicUser>): string {
const goal = '내 말을 모두 먼저 한 바퀴 돌려 판 밖으로 내보내면(날) 이겨요.';
if (v.phase === 'finished') return `게임이 끝났어요. ${v.result?.summary ?? ''}`.trim() + '\n결과 창에서 [한 판 더]를 누르면 다시 할 수 있어요.';
if (v.aug) {
const a = v.aug;
if (v.phase === 'aug' && a.select) {
return a.select.offers.length && a.select.picksLeft
? `${a.round}라운드 증강 선택이에요. [증강 후보 보기]를 눌러 후보 중 하나를 고르고 확인을 누르세요. 후보와 고른 것은 나에게만 보여요.\n증강은 규칙을 바꾸거나(규칙), 바로 효과가 나거나(즉시), 내 차례에 버튼으로 쓰거나(사용), 특별한 방법으로 이기게 해 줘요(승리 조건).`
: `${a.round}라운드 증강 선택이에요. 다른 사람이 고를 때까지 기다려 주세요.`;
}
if (v.phase === 'prompt' && a.prompt) return a.prompt.choices ? '증강 효과 때문에 하나를 골라야 해요. 오른쪽(휴대폰은 아래)의 선택지에서 골라 주세요.' : '다른 사람이 증강 효과를 고르는 중이에요. 기다려 주세요.';
}
const turnSide = v.sides[v.turnSide];
const sideTag = turnSide ? `(${turnSide.name}${v.team ? '' : ' 말'})` : '';
const who = `${players[v.current]?.nickname ?? '다른 사람'}님`;
@@ -47,6 +56,8 @@ export function helpNow(v: YutView, me: string | null, players: Record<string, P
else lines.push(`내 차례예요. [🥢 윷 던지기]를 눌러 윷을 던져요.`);
if (v.pending.length) lines.push(`모아 둔 결과(${pendingText(v)})는 다 던진 뒤에 ${ordered ? '던진 순서대로' : '원하는 순서로'} 써요.`);
else lines.push(`도 1칸, 개 2칸, 걸 3칸, 윷 4칸, 모 5칸 움직여요. 윷·모가 나오면 한 번 더 던져요.`);
if (v.aug?.uses.length) lines.push('[✨ 내 증강 쓰기]에서 지금 쓸 수 있는 증강을 누르면 쓸 곳을 고를 수 있어요.');
if (v.aug?.pickThrow) lines.push('개돼지: [도 내기]나 [개 내기]를 눌러 원하는 결과를 내요.');
lines.push(progress);
return lines.join('\n');
}

View File

@@ -98,6 +98,7 @@ export function changedTags(o: YutOptions): string[] {
/** One-line room summary (lobby): the basics, then every other 지역 룰 that differs from the default. */
export function optionsSummary(o: YutOptions): string {
return [
...(o.augmented ? ['증강 윷놀이'] : []),
o.mode === 'team' ? '팀전' : '개인전',
`말 ${o.pieces}개`,
o.backdo ? '빽도 있음' : '빽도 없음',
@@ -105,5 +106,7 @@ export function optionsSummary(o: YutOptions): string {
...(o.nakPercent ? [`낙 ${o.nakPercent}%`] : []),
...changedTags(o),
o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`,
...(o.augmented && o.augChaos ? ['혼돈 모드'] : []),
...(o.augmented && o.augOff?.length ? [`증강 ${o.augOff.length}개 뺌`] : []),
].join(' · ');
}

View File

@@ -6,6 +6,27 @@ import { Avatar, ConfirmSheet } from '../../components/ui';
import { TurnTimer } from '../../components/TurnTimer';
import { haptic, sounds } from '../../lib/feedback';
import type { BoardProps, GameUI, OptionsProps } from '../types';
import { AugOptions } from './aug-options';
import { AUGS, AUG_IDS, type AugId } from '@bg/games/yut/augments';
import {
AUG_CSS,
AugFxLayer,
AugPrompt,
AugRoundBar,
AugSelect,
AugSlots,
AugUses,
BoardObjects,
FlickAim,
FlickReplay,
FogLayer,
KIND_ICON,
NodeTargets,
TokenBadges,
augLogLine,
augStatus,
type AimState,
} from './aug-ui';
import { helpNow } from './help';
import { houseRules, optionsSummary } from './house-rules';
import { quickStart } from './quick';
@@ -221,11 +242,12 @@ function Sticks({ view: v, players }: { view: YutView; players: Record<string, P
const t = setTimeout(() => setTossing(false), fxMs(820));
return () => clearTimeout(t);
}, [lt?.no]); // eslint-disable-line react-hooks/exhaustive-deps
const sticks = lt?.sticks ?? [false, true, false, true];
const label = !lt ? '' : tossing ? '…' : lt.result === 'nak' ? '낙!' : `${THROW_KO[lt.result]}!`;
const sticks = lt?.sticks ?? (v.aug ? Array.from({ length: v.aug.sides.find((x) => x.id === v.mySide)?.sticks ?? 4 }, (_, i) => i % 2 === 1) : [false, true, false, true]);
const vbW = Math.max(120, 14 + sticks.length * 27);
const label = !lt ? '' : tossing ? '…' : lt.result === 'nak' ? '낙!' : lt.results ? `${lt.results.map((r) => THROW_KO[r]).join('·')}!` : `${THROW_KO[lt.result]}!`;
return (
<div className="yut-sticks-box">
<svg className={`yut-sticks${tossing ? ' yut-toss' : ''}`} viewBox="0 0 120 80" role="img" aria-label={lt ? `${nick(players, lt.player)}님이 던진 윷: ${lt.result === 'nak' ? '낙' : THROW_KO[lt.result]}` : '윷가락 네 개'}>
<svg className={`yut-sticks${tossing ? ' yut-toss' : ''}`} viewBox={`0 0 ${vbW} 80`} style={{ width: (vbW / 120) * 120 }} role="img" aria-label={lt ? `${nick(players, lt.player)}님이 던진 윷: ${lt.result === 'nak' ? '낙' : THROW_KO[lt.result]}` : '윷가락 네 개'}>
{lt?.result === 'nak' ? (
<g key={`nak${lt.no}`} className={tossing ? undefined : 'yut-nak'}>
<g opacity={0.45} transform="rotate(-18 60 40)">
@@ -235,14 +257,18 @@ function Sticks({ view: v, players }: { view: YutView; players: Record<string, P
</g>
</g>
) : (
sticks.map((f, i) => <Stick key={i} x={8 + i * 27} flat={f} marked={i === 0 && v.options.backdo} delay={i * 40} spin={SPINS[i]!} />)
sticks.map((f, i) => <Stick key={i} x={8 + i * 27} flat={f} marked={i === 0 && v.options.backdo} delay={i * 40} spin={SPINS[i % SPINS.length]!} />)
)}
</svg>
<div>
<div key={tossing ? 'toss' : `r${lt?.no ?? 0}`} className={`yut-result${lt && !tossing ? ' anim-pop' : ''}${lt && (lt.result === 'yut' || lt.result === 'mo') ? ' big' : ''}`} aria-hidden>
{label}
</div>
{lt && !tossing && <div className="small muted">{nick(players, lt.player)}님</div>}
{lt && !tossing && (
<div className="small muted">
{nick(players, lt.player)}님{lt.note ? ` · ${lt.note}` : ''}
</div>
)}
</div>
</div>
);
@@ -272,6 +298,15 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
const [anim, setAnim] = useState<Anim | null>(null);
const [flash, setFlash] = useState<{ text: string; at: [number, number]; key: number } | null>(null);
const [landing, setLanding] = useState<{ no: number; at: [number, number]; delayMs: number; goal: boolean; victims: { side: number; count: number }[] } | null>(null);
const aug = v.aug ?? null;
const [aim, setAim] = useState<AimState | null>(null);
const [targetUid, setTargetUid] = useState<number | null>(null);
const svgRef = useRef<SVGSVGElement>(null);
useEffect(() => {
setAim(null);
setTargetUid(null);
}, [v.turnSeq]);
const openUses = aug && targetUid !== null ? aug.uses.filter((u) => u.uid === targetUid) : [];
const lastMoveNo = useRef(v.lastMove?.no ?? 0);
const lastThrowNo = useRef(v.lastThrow?.no ?? 0);
const prevCurrent = useRef(v.current);
@@ -412,8 +447,10 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
return (
<div className="yut-wrap">
<style>{CSS}</style>
<div className="yut-board-box">
<svg className="yut-board" viewBox="0 0 100 100" role="group" aria-label={`윷판. 말은 오른쪽 아래 참먹이에서 출발해 시계 반대 방향으로 돌아요.${chosen ? ` 고른 말은 ${nodeName(chosen.to)}로 가요.` : ''}`} style={{ background: 'var(--wood)' }}>
{aug && <style>{AUG_CSS}</style>}
<div className="yut-board-box aug-board-wrap">
{aug && <AugFxLayer v={v} players={players} me={me} />}
<svg ref={svgRef} className="yut-board" viewBox="0 0 100 100" role="group" aria-label={`윷판. 말은 오른쪽 아래 참먹이에서 출발해 시계 반대 방향으로 돌아요.${chosen ? ` 고른 말은 ${nodeName(chosen.to)}로 가요.` : ''}`} style={{ background: 'var(--wood)' }}>
<rect x={1.5} y={1.5} width={97} height={97} rx={6} fill="none" stroke="var(--wood-line)" strokeWidth={0.6} opacity={0.6} />
{LINES.map(([a, b]) => (
<line key={`${a}-${b}`} x1={POS[a]![0]} y1={POS[a]![1]} x2={POS[b]![0]} y2={POS[b]![1]} stroke="var(--wood-line)" strokeWidth={0.9} strokeLinecap="round" opacity={0.75} />
@@ -434,9 +471,10 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
))}
{/* direction hint at the start */}
<path d={`M ${HI - 4.5} ${HI - 9} L ${HI - 4.5} ${HI - 14} M ${HI - 6.3} ${HI - 12} L ${HI - 4.5} ${HI - 14.2} L ${HI - 2.7} ${HI - 12}`} stroke="var(--wood-line)" strokeWidth={0.7} fill="none" strokeLinecap="round" opacity={0.8} />
{aug && <BoardObjects v={v} />}
{stacks.map((st) => {
// Stacks standing apart on one node (지역 룰 stacking = choose) sit side by side.
const twins = st.piece === undefined ? [] : stacks.filter((o) => o.node === st.node && o.side === st.side);
// Stacks standing apart on one node (지역 룰 stacking = choose; 증강: special pieces, several sides) sit side by side.
const twins = aug ? stacks.filter((o) => o.node === st.node) : st.piece === undefined ? [] : stacks.filter((o) => o.node === st.node && o.side === st.side);
const k = twins.indexOf(st);
const dx = twins.length > 1 ? (k - (twins.length - 1) / 2) * 5.2 : 0;
const x = POS[st.node]![0] + dx;
@@ -445,12 +483,13 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
const mine = v.mySide === st.side;
const can = myTurn && mine && movable.has(src);
const sel = mine && selFrom === src;
const sideName = v.sides[st.side]!.name;
const sideName = v.sides[st.side]?.name ?? '가려진';
const r = twins.length > 1 ? 3.3 : BIG.has(st.node) ? 4.6 : 4;
return (
<g key={`s${src}`}>
<g key={`s${st.side}:${src}`}>
{(can || sel) && <circle cx={x} cy={y} r={twins.length > 1 ? r + 1.4 : R_BIG + 0.6} fill="none" stroke={sel ? 'var(--primary)' : 'var(--focus)'} strokeWidth={1.3} className={sel ? undefined : 'yut-can'} />}
<Token side={st.side} team={v.team} x={x} y={y} r={r} count={st.count} />
{aug && <TokenBadges x={x} y={y} r={r} kind={st.kind} shield={st.shield} frozen={st.frozen} />}
{mine && myTurn && v.phase === 'move' && (
<g
className="yut-hit"
@@ -509,6 +548,22 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
strokeWidth={landing.goal ? 1.6 : 1.1}
/>
)}
{aug && <FogLayer v={v} />}
{aug && <FlickReplay v={v} draw={(side, x, y, count, key) => <Token key={key} side={side} team={v.team} x={x} y={y} r={4} count={count} />} />}
{aug && aim && <FlickAim aim={aim} setAim={setAim} svg={svgRef} />}
{aug && !aim && openUses.length > 0 && (
<NodeTargets
opts={openUses}
onPick={(u) => {
if (u.id === 'alkkagi') {
if (u.at !== undefined && u.at !== 'home') setAim({ uid: u.uid, piece: u.action.piece!, at: u.at, angle: 270, power: 60 });
return;
}
act({ type: 'AUG_USE', ...u.action });
setTargetUid(null);
}}
/>
)}
{anim && (
<g key={`${anim.no}-${anim.i}`} className="yut-hop">
<Token side={anim.side} team={v.team} x={anim.pts[anim.i]![0]} y={anim.pts[anim.i]![1]} r={4.4} count={anim.count} />
@@ -525,6 +580,9 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
</div>
<div className="yut-ctrl">
{aug && <AugRoundBar v={v} />}
{aug && v.phase === 'aug' && aug.select && <AugSelect v={v} act={act} pending={pending} players={players} />}
{aug && v.phase === 'prompt' && aug.prompt && <AugPrompt v={v} act={act} pending={pending} players={players} />}
<div className="row" style={{ justifyContent: 'space-between', flexWrap: 'nowrap' }}>
<Sticks view={v} players={players} />
{v.phase !== 'finished' && <TurnTimer deadline={deadline} totalMs={Math.max(1000, totalMs)} mine={myTurn} size={44} />}
@@ -562,10 +620,23 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
)}
</div>
{myTurn && v.phase === 'throw' && (
{myTurn && v.phase === 'throw' && !aim && (aug?.pickThrow ? (
<div className="row" style={{ flexWrap: 'nowrap' }} aria-label="개돼지: 도나 개를 골라서 내요">
<button className="btn btn-primary yut-throw" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'THROW', pick: 'do' })}>
🐷 도 내기
</button>
<button className="btn btn-primary yut-throw" style={{ flex: 1 }} disabled={pending} onClick={() => act({ type: 'THROW', pick: 'gae' })}>
🐶 개 내기
</button>
</div>
) : (
<button className="btn btn-primary btn-block yut-throw" disabled={pending} onClick={() => act({ type: 'THROW' })}>
{v.pending.length || v.lastThrow?.player === me ? '🥢 한 번 더 던지기' : '🥢 윷 던지기'}
</button>
))}
{aug && myTurn && (v.phase === 'throw' || v.phase === 'move') && (
<AugUses v={v} act={act} pending={pending} aim={aim} setAim={setAim} targetUid={targetUid} setTargetUid={setTargetUid} />
)}
{myTurn && v.phase === 'move' && (
@@ -636,8 +707,27 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps<Y
<TokenIcon side={mySideView.id} team={v.team} />
대기 {mySideView.home}개{myTurn && movable.has('home') ? ' · 새 말 올리기' : ''}
</button>
{aug?.sides
.find((x) => x.id === mySideView.id)
?.homeSpecial.map((h) => {
const src = srcOf('home', h.piece);
const can = myTurn && movable.has(src);
return (
<button
key={h.piece}
type="button"
className={`yut-tray-btn${can ? (selFrom === src ? ' sel' : ' can') : ''}`}
disabled={!can || pending}
aria-pressed={selFrom === src}
onClick={() => tapSource(src)}
aria-label={`대기 중인 특수 말${can ? ' — 올리기' : ''}`}
>
{KIND_ICON[h.kind]} 대기
</button>
);
})}
<span className="small" aria-label={`난 말 ${mySideView.done}개`}>
🏁 난 말 <strong>{mySideView.done}</strong>/{v.options.pieces}
🏁 난 말 <strong>{mySideView.done}</strong>/{mySideView.total ?? v.options.pieces}
</span>
</div>
)}
@@ -662,7 +752,8 @@ function badge(m: YutLegalMove): string | null {
function SideCard({ side, view: v, players, me, deadline }: { side: YutSideView; view: YutView; players: Record<string, PublicUser>; me: string | null; deadline: number | null }) {
const turn = v.phase !== 'finished' && v.turnSide === side.id;
const shape = SHAPE_KO[sideShape(side.id)];
const status = side.finishedRank !== null ? `${side.finishedRank}등` : side.out ? '기권' : null;
const augSide = v.aug?.sides.find((x) => x.id === side.id);
const status = side.finishedRank !== null ? (v.aug ? `${side.finishedRank}위` : `${side.finishedRank}등`) : side.out ? (v.aug ? (augSide?.reason === '기권' ? '기권' : '탈락') : '기권') : null;
return (
<div className={`card yut-side-card${turn ? ' turn' : ''}`} aria-label={`${side.name}(${shape}) 대기 ${side.home}개, 판 위 ${side.onBoard}개, 남 ${side.done}개${status ? `, ${status}` : ''}${turn ? ', 차례' : ''}`}>
<div className="row" style={{ gap: 8, flexWrap: 'nowrap' }}>
@@ -678,19 +769,25 @@ function SideCard({ side, view: v, players, me, deadline }: { side: YutSideView;
)}
<span className="small" style={{ fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }} aria-hidden>
대기 {side.home} · 판 {side.onBoard} · 🏁 {side.done}
{side.total !== undefined ? `/${side.total}` : ''}
</span>
</div>
{augSide?.reason && (side.out || side.finishedRank !== null) && <div className="small muted">{augSide.reason}</div>}
<div className="stack" style={{ gap: 4, marginTop: 6 }}>
{side.members.map((id) => {
const u = userOf(players, id);
const cur = turn && v.current === id;
// 증강 선택·질문 중에는 고르는 사람에게 시계가 간다.
const waitingOn = v.phase === 'aug' ? v.aug?.select?.waiting : v.phase === 'prompt' ? v.aug?.prompt?.waiting : undefined;
const cur = waitingOn ? waitingOn.includes(side.id) : turn && v.current === id;
return (
<div key={id} className="row" style={{ gap: 6, flexWrap: 'nowrap', opacity: side.conceded.includes(id) ? 0.55 : 1 }}>
<Avatar user={u} size={24} />
<span style={{ flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', fontWeight: cur ? 800 : 500 }}>
{u.nickname}
{id === me && <span className="muted small"> (나)</span>}
{cur && <span className="small" style={{ color: 'var(--primary)' }}> · {v.phase === 'throw' ? '던지는 중' : '옮기는 중'}</span>}
{cur && !waitingOn && (v.phase === 'throw' || v.phase === 'move') && <span className="small" style={{ color: 'var(--primary)' }}> · {v.phase === 'throw' ? '던지는 중' : '옮기는 중'}</span>}
{v.phase === 'aug' && v.aug?.select?.waiting.includes(side.id) && <span className="small" style={{ color: 'var(--primary)' }}> · 증강 고르는 중</span>}
{v.phase === 'prompt' && v.aug?.prompt?.waiting.includes(side.id) && <span className="small" style={{ color: 'var(--primary)' }}> · 고르는 중</span>}
</span>
{side.conceded.includes(id) && <span className="yut-badge" style={{ background: 'var(--text-sub)' }}>기권</span>}
{v.away.includes(id) && !side.conceded.includes(id) && <span className="yut-badge" style={{ background: 'var(--warning)' }}>자리 비움</span>}
@@ -699,11 +796,16 @@ function SideCard({ side, view: v, players, me, deadline }: { side: YutSideView;
);
})}
</div>
{v.aug && <AugSlots v={v} side={side.id} />}
</div>
);
}
function logLine(e: GameEvent, v: YutView, players: Record<string, PublicUser>): string | null {
if (v.aug) {
const l = augLogLine(e, v, players);
if (l !== undefined) return l;
}
const who = typeof e.player === 'string' ? nick(players, e.player) : '';
const sn = (s: unknown) => v.sides[s as number]?.name ?? '';
switch (e.type) {
@@ -787,6 +889,9 @@ function YutSide({ view: v, me, players, act, deadline }: BoardProps<YutView>) {
function statusText(v: YutView, me: string | null, players: Record<string, PublicUser>): string {
if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요';
const augText = augStatus(v, me, players);
if (augText) return augText;
if (v.aug?.hidden) return '나 누구게? 모두 자기 색을 맞히는 중이에요';
const cur = nick(players, v.current);
if (v.current === me) {
if (v.phase === 'throw') return v.pending.length || v.lastThrow?.player === me ? '내 차례예요. 한 번 더 던져요' : '내 차례예요. 윷을 던져 주세요';
@@ -836,21 +941,26 @@ const OPT_CSS = `
.yut-rule-group legend { padding: 0 6px; font-weight: 800; color: var(--text-sub); }
.yut-rules-toggle { justify-content: space-between; text-align: left; white-space: normal; height: auto; min-height: var(--tap); }
.yut-rules-count { display: inline-block; margin-left: 6px; border-radius: 999px; padding: 0 8px; font-size: .8rem; font-weight: 800; background: var(--primary-soft); color: var(--text); }
.yut-opt-tabs { border-bottom: 1px solid var(--border); padding-bottom: 10px; }
.yut-opt-tabs button { flex: 1; }
.yut-opt-tabs button[aria-selected='true'] { border-color: var(--primary); background: var(--primary-soft); font-weight: 700; }
`;
function Options({ value: o, onChange }: OptionsProps<YutOptions>) {
const [more, setMore] = useState(false);
const [tab, setTab] = useState<'base' | 'aug'>('base');
const set = (patch: Partial<YutOptions>) => onChange({ ...o, ...patch });
const aug = o.augmented === true;
const onOff = (b: boolean) => (b ? 'on' : 'off');
const rules = houseRules(o);
const hint = (key: keyof YutOptions) => rules.find((r) => r.key === key)?.text;
const changed = rules.filter((r) => r.changed).length;
return (
<div className="stack" style={{ gap: 16 }}>
<style>{OPT_CSS}</style>
const base = (
<>
<Field label="경기 방식">
<Seg value={o.mode} options={[['individual', '개인전(2~4명)'], ['team', '팀전(4·6·8명)']]} onChange={(mode) => set({ mode })} />
{o.mode === 'team' && <span className="small muted">자리 순서대로 청팀·홍팀이 번갈아 앉아요(1·3·5·7번째 청팀). 자리를 바꿔 팀을 맞춰 주세요.</span>}
<Seg value={o.mode} options={aug ? [['individual', '개인전(2~4명)']] : [['individual', '개인전(2~4명)'], ['team', '팀전(4·6·8명)']]} onChange={(mode) => set({ mode })} />
{aug && <span className="small muted">증강 윷놀이는 개인전만 돼요.</span>}
{!aug && o.mode === 'team' && <span className="small muted">자리 순서대로 청팀·홍팀이 번갈아 앉아요(1·3·5·7번째 청팀). 자리를 바꿔 팀을 맞춰 주세요.</span>}
</Field>
<Field label="한 편의 말 수">
<Seg value={o.pieces} options={[[2, '2개'], [3, '3개'], [4, '4개'], [5, '5개']]} onChange={(pieces) => set({ pieces })} />
@@ -957,6 +1067,31 @@ function Options({ value: o, onChange }: OptionsProps<YutOptions>) {
)}
</div>
)}
</>
);
return (
<div className="stack" style={{ gap: 16 }}>
<style>{OPT_CSS}</style>
<Field label="게임 종류">
<Seg value={aug ? 'aug' : 'plain'} options={[['plain', '일반 윷놀이'], ['aug', '증강 윷놀이']]} onChange={(k) => set(k === 'aug' ? { augmented: true, mode: 'individual' } : { augmented: false })} />
</Field>
{aug ? (
<>
<div className="segmented yut-opt-tabs" role="tablist" aria-label="윷놀이 설정">
<button type="button" role="tab" id="yut-tab-base" aria-selected={tab === 'base'} aria-controls="yut-tabpanel" onClick={() => setTab('base')}>
기본 설정
</button>
<button type="button" role="tab" id="yut-tab-aug" aria-selected={tab === 'aug'} aria-controls="yut-tabpanel" onClick={() => setTab('aug')}>
증강 윷놀이
</button>
</div>
<div className="stack" style={{ gap: 16 }} role="tabpanel" id="yut-tabpanel" aria-labelledby={tab === 'base' ? 'yut-tab-base' : 'yut-tab-aug'}>
{tab === 'base' ? base : <AugOptions value={o} onChange={set} />}
</div>
</>
) : (
base
)}
</div>
);
}
@@ -1003,10 +1138,56 @@ function StickRow({ flats, label }: { flats: boolean[]; label: string }) {
);
}
function AugRules({ o }: { o: YutOptions }) {
const off = new Set(o.augOff ?? []);
const rounds = { standard: '1·6·12', quick: '1·4·8', many: '1·3·5·7·9' }[o.augRounds ?? 'standard'];
const groups: [string, (a: (typeof AUGS)[AugId]) => boolean][] = [
['범용', (a) => a.tier === 'any' && !a.custom],
['시작 전용', (a) => a.tier === 'start'],
['중간 전용', (a) => a.tier === 'mid' && !a.custom],
['마무리 전용', (a) => a.tier === 'final'],
['이 사이트 추가', (a) => !!a.custom],
];
return (
<section className="stack" style={{ gap: 8 }} aria-label="증강 윷놀이 규칙">
<h3 style={{ margin: 0 }}>🌀 증강 윷놀이</h3>
<p style={{ margin: 0 }}>
보통 윷놀이에 <strong>증강</strong>(특별한 규칙·능력)이 더해져요. 모두가 한 번씩 차례를 하면 한 라운드예요. <strong>{rounds}라운드</strong>가 시작될 때 모두 동시에 후보 {o.augOffers ?? 3}개 중 하나를 고르고
{o.augChaos ? '(혼돈 모드: 두 번씩)' : ''}, 후보와 고른 것은 자기에게만 보여요. 첫 선택은 범용+시작 전용, 마지막은 범용+마무리 전용, 그 사이는 범용+중간 전용 증강이 나와요.
</p>
<p style={{ margin: 0 }}>
증강을 쓰거나 승리 조건을 이루면 바로 순위가 정해지고, 탈락하면 꼴찌 쪽 순위가 돼요. 개인전(2~4명)으로만 해요. 고른 증강은 모두에게 보이고, 오른쪽 사람 카드에서 확인할 수 있어요.
</p>
{groups.map(([title, f]) => {
const list = AUG_IDS.filter((id) => f(AUGS[id]) && !off.has(id));
if (!list.length) return null;
return (
<details key={title}>
<summary style={{ cursor: 'pointer', fontWeight: 800 }}>
{title} ({list.length})
</summary>
<ul className="stack small" style={{ gap: 4, margin: '6px 0 0', paddingLeft: 18 }}>
{list.map((id) => (
<li key={id}>
<strong>{AUGS[id].name}</strong>
{AUGS[id].once ? ' (1회)' : ''}: {AUGS[id].text}
{AUGS[id].note ? <span className="muted"> {AUGS[id].note}</span> : null}
</li>
))}
</ul>
</details>
);
})}
{off.size > 0 && <p className="small muted" style={{ margin: 0 }}>이 방에서 뺀 증강 {off.size}개는 나오지 않아요.</p>}
</section>
);
}
function Rules({ options }: { options?: YutOptions }) {
const o = options;
return (
<div className="stack">
{o?.augmented && <AugRules o={o} />}
<p>
윷가락 네 개를 던져 나온 만큼 말을 움직여, <strong>내 말을 모두 먼저 판 밖으로 내보내면(날)</strong> 이겨요. 말은 오른쪽 아래 <strong>참먹이</strong>에서 출발해 시계 반대 방향으로 돌아요.
{o?.mode === 'team' ? ' 팀전은 청팀·홍팀이 번갈아 던지고, 팀 안에서는 자리 순서대로 돌아가요.' : ''}
@@ -1085,7 +1266,12 @@ const ui: GameUI<YutView, YutOptions> = {
Board: YutBoard,
Side: YutSide,
statusText,
isMyTurn: (v, me) => v.phase !== 'finished' && !!me && v.current === me,
isMyTurn: (v, me) => {
if (v.phase === 'finished' || !me) return false;
if (v.aug && v.phase === 'aug') return !!v.aug.select && v.aug.select.offers.length > 0 && v.aug.select.picksLeft > 0;
if (v.aug && v.phase === 'prompt') return !!v.aug.prompt?.choices;
return v.current === me;
},
Options,
optionsSummary,
Rules,

View File

@@ -633,7 +633,8 @@ function SettingsForm({ room, ui, inline, readOnly, onDone }: { room: RoomView;
/**
* Locks every control inside (each game's options form has its own buttons, selects and inputs), except
* disclosure toggles (`aria-expanded`, e.g. "▼ 자세한 설정") so hidden rules can still be opened and read.
* disclosure toggles (`aria-expanded`, e.g. "▼ 자세한 설정"), tabs (`role="tab"`) and search boxes (`type="search"`)
* so hidden rules can still be opened and read.
* Re-locks whatever the form renders later (opening "자세한 설정" adds new controls).
*/
function ReadOnlyControls({ children }: { children: ReactNode }) {
@@ -641,7 +642,7 @@ function ReadOnlyControls({ children }: { children: ReactNode }) {
useLayoutEffect(() => {
const root = ref.current!;
const lock = () => {
root.querySelectorAll<HTMLButtonElement | HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>('button:not([aria-expanded]), input, select, textarea').forEach((el) => {
root.querySelectorAll<HTMLButtonElement | HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>('button:not([aria-expanded]):not([role="tab"]), input:not([type="search"]), select, textarea').forEach((el) => {
if (!el.disabled) el.disabled = true;
});
};

View File

@@ -13,6 +13,7 @@ export interface JsonSchema {
const?: string | number | boolean;
anyOf?: JsonSchema[];
properties?: Record<string, JsonSchema>;
items?: JsonSchema;
minimum?: number;
maximum?: number;
default?: unknown;
@@ -70,7 +71,26 @@ function Field({ schema, value, onChange, path, locked, onToggleLock, root }: Pr
let control: ReactNode;
const opts = choices(schema);
if (opts) {
const itemOpts = schema.type === 'array' && schema.items ? choices(schema.items) : null;
if (itemOpts) {
const cur = (Array.isArray(value) ? value : Array.isArray(schema.default) ? schema.default : []) as unknown[];
const labels = schema.items?.labels;
control = (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px 12px', maxHeight: 280, overflowY: 'auto', padding: 8, border: '1px solid var(--border)', borderRadius: 8 }}>
{itemOpts.map((o) => (
<label key={String(o)} className="row small" style={{ gap: 6, cursor: 'pointer', minHeight: 32 }}>
<input
type="checkbox"
checked={cur.includes(o)}
onChange={(e) => onChange(e.target.checked ? itemOpts.filter((x) => x === o || cur.includes(x)) : cur.filter((x) => x !== o))}
style={{ width: 18, height: 18 }}
/>
{labels?.[String(o)] ?? String(o)}
</label>
))}
</div>
);
} else if (opts) {
const cur = value ?? schema.default;
control = (
<select