윷놀이: 증강 윷놀이 옵션 추가 (원작 증강 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:
@@ -10,7 +10,7 @@
|
||||
|---|---|
|
||||
| 2인 수 싸움 | 오목, 커넥트 포(사목), 오셀로, 체스(체스960 포함), 장기, 바둑, 쿼리도(2·4명) |
|
||||
| 카드·화투 | 원카드, 우노, 도둑잡기, 섯다, 포커, 블랙잭, 고스톱, 달무티, 티츄, 젝스님트, 구십구, 바퀴벌레 포커, 뱅! |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 |
|
||||
| 타일·주사위·판 | 루미큐브, 다빈치 코드, 마작, 요트 다이스, 윷놀이(지역 룰 선택, 증강 윷놀이), 라스베가스, 부루마불, 스플렌더, 야단법석 달리기, 클루, 젬블로, 버건디의 성 |
|
||||
| 순발력·대화·파티 | 할리갈리, 도블, 그림 맞히기, 사과 게임, 마피아, 라이어 게임, 핫스트릭, 사건 파일(협력 추리) |
|
||||
|
||||
칩·포인트·지폐, 섯다의 "원"은 모두 놀이용이다(실제 돈과 무관, 충전·환전 없음).
|
||||
|
||||
172
apps/web/src/games/yut/aug-options.tsx
Normal file
172
apps/web/src/games/yut/aug-options.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
746
apps/web/src/games/yut/aug-ui.tsx
Normal file
746
apps/web/src/games/yut/aug-ui.tsx
Normal 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;
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
@@ -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(' · ');
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|---|---|---|---|---|
|
||||
| `janggi` | 장기 | 2 | 한국 전통 2인 전략 | M2 |
|
||||
| `othello` | 오셀로 | 2 | 규칙 쉬움, 어린이·어르신 | M2 |
|
||||
| `yut` | 윷놀이 | 개인 2~4, 팀전 2팀 최대 8 | 명절 국민 게임 | M4 |
|
||||
| `yut` | 윷놀이 (옵션: [증강 윷놀이](yut-augmented.md)) | 개인 2~4, 팀전 2팀 최대 8 | 명절 국민 게임 | M4 |
|
||||
| `one-card` | 원카드 (+ 색깔 카드 모드) | 2~9 (색깔 카드 2~10) | 판매 2위(우노/원카드) | M4 |
|
||||
| `gostop` | 고스톱 / 맞고 | 2~5 (맞고 2, 고스톱 3, 광팔기 4~5) | 한국 대표 화투 게임 | M5 |
|
||||
| `rummikub` | 루미큐브 | 2~4 | 판매 3위, 카페 2위 | M4 |
|
||||
|
||||
174
docs/games/yut-augmented.md
Normal file
174
docs/games/yut-augmented.md
Normal file
@@ -0,0 +1,174 @@
|
||||
# 증강 윷놀이 (`yut` 옵션 `augmented`)
|
||||
|
||||
> 윷놀이의 옵션. 방 설정 [게임 종류]에서 **증강 윷놀이**를 고르면 [증강 윷놀이] 탭이 생긴다. 개인전 2~4명만.
|
||||
> 원작: Steam 「증강 윷놀이」(어수룩 게임즈, 2026-09). 규칙 출처: 나무위키 "증강 윷놀이"(2026-10-16 판), Steam 상점 스크린샷·트레일러.
|
||||
> 원작의 증강 71개를 모두 넣고, 이 사이트 증강 10개를 더했다(모두 81개). 엔진: `packages/games/src/yut/aug.ts`. 목록: `augments.ts`. 알까기 물리: `physics.ts`. 컴퓨터: `aug-bot.ts`. 화면: `apps/web/src/games/yut/aug-ui.tsx`, `aug-options.tsx`.
|
||||
|
||||
## 1. 진행
|
||||
- 기본은 이 방의 윷놀이 규칙(지역 룰 포함)을 그대로 따른다. 증강이 규칙을 바꾸면 증강이 우선한다.
|
||||
- **라운드**: 살아 있는 모두가 한 차례씩 하면 1라운드. 첫 차례인 사람부터 센다. 메아리의 형상의 두 번째 차례는 라운드를 넘기지 않는다.
|
||||
- **증강 선택**: 정해진 라운드(`augRounds`: 1·6·12 기본, 1·4·8, 1·3·5·7·9)가 시작될 때, 그 라운드 첫 차례 직전에 살아 있는 모두가 **동시에** 고른다.
|
||||
- 후보는 사람마다 따로, `augOffers`(기본 3)개. **후보와 고른 것은 자기에게만** 보인다(view에 남의 후보 없음). 이미 가진 증강은 안 나온다. 같은 라운드에 다른 사람과 겹칠 수는 있다.
|
||||
- 첫 선택은 범용 + 시작 전용, 마지막은 범용 + 마무리 전용, 그 사이는 범용 + 중간 전용. `augOff`에 든 증강은 나오지 않는다.
|
||||
- 혼돈 모드(`augChaos`): 한 번에 두 번 고른다(두 번째는 새 후보).
|
||||
- 모두 고르면 공개되고, 차례 순서대로 효과가 난다. 명탐정이 먼저 적용된다.
|
||||
- 이의있음!: 고르면 새 후보(이의있음 제외)로 바로 다시 고른다. 가진 증강으로 남지 않는다.
|
||||
- 고를 것이 없으면(후보 0개) 그 사람은 건너뛴다. 시간 제한은 max(30초, 행동 시간×2), 넘기면 첫 후보(이의있음 제외, 대상은 첫 항목).
|
||||
- **질문(prompt)**: 효과에 선택이 필요한 증강(거머리·접기·돌림판·착각·계획·승부·손버릇은 주인, 나 누구게?는 다른 모두, 내려는 모두)은 공개 직후 차례로 묻는다. 시간 초과는 첫 선택지.
|
||||
- **순위**: 말을 모두 내거나 특수 승리 조건을 이루면 그 즉시 비어 있는 가장 높은 순위(공동 순위는 같은 숫자, 다음은 +1)를 받고 빠진다. 탈락하면 판 위 말이 빠지고 꼴찌 쪽(늦게 탈락할수록 위). `ranking=first`면 첫 승자가 나오면 끝(동메달은 '승자'가 아님), `all`이면 한 명 남을 때까지. 끝날 때 남은 사람은 난 말 수·남은 거리로 순위를 매긴다.
|
||||
- 거머리·네크로맨서로 이어진 사람은 상대가 이기면 같은 순위를 받는다(거머리는 탈락도 같이).
|
||||
|
||||
## 2. 공통 규칙
|
||||
- **특수 말**(도깨비·선봉장·포·폰·김첨지·중전마마·마라토너)은 업히지 않고 늘 따로 선다(같은 칸이면 나란히). 광신도는 광신도끼리만 업힌다.
|
||||
- **함께 서기**: 보호막·평화 협정·거북이 등껍질·프랜드 실드로 잡히지 않은 말은 그 칸에 남아 다른 편 말과 함께 선다. 다음에 그 칸에 멈추는 말은 거기 있는 다른 편 말을 모두 잡으려 한다.
|
||||
- **잡기 판정 순서**(`killPieces`): 평화 협정(잡는 쪽·잡히는 쪽 중 하나라도) → 거북이 등껍질(한 칸 3개 이상) → 보호막(한 번 막고 사라짐) → 프랜드 실드(1개만). 증강으로 잡는 것도 같다. 잡을 때 오르는 것: 무신정변·소 뒷걸음질(빽도)·살인(체력)·나만 친구 없어·어부지리(차례가 아닌 사람)·복수의 칼날.
|
||||
- 잡으면 한 번 더 던지기는 보통 이동·특수 말 이동만. 증강 효과로 잡은 것(트럭·합체·바둑 등)은 한 번 더 던지지 않는다(바둑은 잡은 수만큼 던진다).
|
||||
- **차례 소모**(8톤 트럭·3단 합체·알까기): 그 차례 첫 던지기 전에만 쓰고, 쓰면 차례가 끝난다.
|
||||
- 1회 증강은 쓰면 칸에 "사용함" 도장(✔). 명탐정에 걸린 증강은 줄이 그어진다. 언제부터 착각한 거지?에 걸리면 🐱(효과·버튼·승리 조건 모두 꺼짐).
|
||||
- 취~소 뒤에는 모든 승리 조건 증강이 꺼진다(중전마마·김첨지 등의 말은 남고 승리만 없음).
|
||||
|
||||
## 3. 해석이 필요했던 부분
|
||||
원작 설명이 짧아 다음처럼 정했다(규칙 화면의 '세부'에도 나온다).
|
||||
- 8톤 트럭: "막히기 전까지 도만큼 직선" → 한 칸씩 직진하다 꺾이는 곳(모서리·참먹이)에서 멈추고, 지나는 칸의 다른 편 말을 잡는다.
|
||||
- 과유불급: 가락 6개는 앞뒤 반반 확률(실제 윷 확률이면 6개가 모두 배일 확률이 4.7%라 너무 자주 탈락). 배 4~5개 윷, 6개 탈락, 7개 이상(짐덩이로 7개)은 탈락 없음.
|
||||
- 말이오? 파티: 해골 1(잡힘)·마녀 모자 5(뒤로 2칸)·선물 4(앞으로 2칸, 누구나). 스크린샷의 함정 배치(모자 5·해골 1·선물 4)를 따랐다. 딱 멈출 때만, 연쇄는 없음.
|
||||
- 천상천하 유아독존: 시작하자마자 첫 말을 올리면 바로 이기는 문제를 막기 위해 "내가 잡아서" 판에 내 말뭉치 하나만 남을 때로 했다.
|
||||
- 안개·영역 전개·김첨지·승부다의 "차례"는 그 사람의 차례 수. 안개는 내 차례가 두 번 다시 시작될 때 걷힌다.
|
||||
- 히히 똥!: 똥은 계속 남고, 주인이 아닌 말이 지나가다 밟으면 그 칸에 멈춘다.
|
||||
- 나 누구게?: 주인 말고 모두에게 판 색·사람 카드·기록이 가려진다. 맞히는 사람은 자기 색을 고른다.
|
||||
- 내려: 자기에게는 투표할 수 없고, 동점이면 모두 건너뛴다.
|
||||
- 중전마마: 목숨 1, 다른 말이 날 때마다 +1, 잡히면 목숨 −1 후 대기로. 12번 던지면 승리. 중전마마 말고 다 나면 그것도 완주.
|
||||
- 동메달도 잘한 거야: 3명 이상 남았고 3위가 비어 있을 때만 후보에 나온다.
|
||||
- 알까기: 고른 말뭉치에서 말 1개만 날아간다. 판 밖(가장자리 0.5~99.5)으로 나간 말은 잡히고, 멈춘 말은 다른 편이 없는 가장 가까운 칸(참먹이 제외)에 선다. 마우스·손가락으로 새총처럼 끌거나, 방향(0~359°)·힘(1~100) 막대로 정한다.
|
||||
|
||||
## 4. 증강 목록
|
||||
|
||||
### 범용 (42개)
|
||||
| id | 이름 | 종류 | 효과 | 세부 |
|
||||
|---|---|---|---|---|
|
||||
| `truck` | 8톤 트럭 | 사용·1회·차례 소모 | 말이 2개 이상 업힌 내 말뭉치 하나가 꺾이는 곳까지 앞으로 쭉 달려요. 지나가는 길의 다른 편 말은 모두 잡아요. | 차례를 다 써요(던지기 전에만). 모서리·방에 서 있었다면 지름길로 출발하고, 모서리·참먹이에 닿으면 멈춰요. |
|
||||
| `combo` | 3단 합체 필살기!!! | 사용·1회·차례 소모 | 말이 3개 이상 업힌 내 말뭉치를 골라요. 그 말뭉치를 뺀 판 위의 모든 말뭉치를 잡아요(내 다른 말도요). | 차례를 다 써요(던지기 전에만). |
|
||||
| `chosen` | 간택 | 규칙 | 이제 모든 사람은 증강 후보에 고양이가 나오면 꼭 고양이를 골라야 해요. | |
|
||||
| `fold` | 게임 접어라 | 즉시 | 윷판을 반으로 접어요. 접는 방향을 고르면, 접히는 쪽 말이 반대쪽 같은 자리로 옮겨져요. | 옮겨진 말이 다른 편 말 위에 떨어지면 그 말을 잡아요. 내 말끼리는 업혀요. |
|
||||
| `cat` | 고양이 | 규칙 | 아무 능력이 없어요. 왜 있냐고요? 귀엽잖아요. | |
|
||||
| `excess` | 과유불급 | 규칙 | 윷가락 6개로 던져요. 배가 0개면 모, 4~5개면 윷, 6개가 모두 배면 탈락해요. | 배가 1~3개면 도·개·걸이에요. 이 증강의 윷가락은 앞뒤가 반반으로 나와요. |
|
||||
| `doggy` | 개돼지 | 규칙 | 던지면 도와 개만 나오지만, 둘 중 하나를 골라서 낼 수 있어요. | |
|
||||
| `leech` | 거머리 | 즉시 | 다른 사람 한 명에게 내 말 1개를 줘요. 그 사람이 이기면 나도 같은 순위로 이기고, 탈락하면 나도 탈락해요. | 대기 중인 말을 먼저 줘요. 나도 따로 이길 수 있어요. |
|
||||
| `whoami` | 나 누구게? | 즉시 | 잠깐 모든 말의 색이 가려져요. 다른 사람은 자기 색을 맞혀야 하고, 틀리면 차례를 한 번 건너뛰어요. | |
|
||||
| `notme` | 나만 아니면 돼~ | 즉시 | 다른 사람 중 무작위로 한 명의 판 위 말을 모두 잡아요. | |
|
||||
| `getoff` | 내려 | 즉시 | 모두 투표해요. 표를 가장 많이 받은 사람은 차례를 한 번 건너뛰어요. 나는 2표를 행사해요. | 자기 자신에게는 투표할 수 없어요. 동점이면 동점인 사람이 모두 건너뛰어요. |
|
||||
| `doberman` | 도베르만 | 사용·1회 | 이번 게임에서 낸 개 수만큼 개 코인을 받아요. 그 뒤로는 던질 때마다 개 코인 2개를 써서 모가 나와요. | 개 코인이 2개보다 적으면 평소처럼 던져요. |
|
||||
| `roulette` | 돌려돌려 돌림판 | 즉시 | 판을 돌려 모든 말이 돌아간 자리로 옮겨져요. 결과가 마음에 안 들면 한 번 더 돌릴 수 있어요. | |
|
||||
| `sniper` | 명사수 | 사용 | 던지기 한 번을 써서 칸 하나를 조준해요. 다음 내 차례가 시작될 때 그 칸의 말을 모두 잡아요. | 한 차례에 한 번, 조준은 한 곳만 할 수 있어요. 내 말도 잡혀요. |
|
||||
| `detective` | 명탐정 | 즉시 | 증강 하나를 지목해요. 이번 증강 선택에서 다른 사람이 그 증강을 고르면 무효가 돼요. | |
|
||||
| `moordo` | 모 아니면 도 | 규칙 | 던지면 모 아니면 도만 나와요. 모가 나올 확률은 40%예요. | |
|
||||
| `baduk` | 바둑 | 사용·1회 | 한 줄 위에 있는 내 말뭉치 둘 사이의 다른 편 말을 모두 잡고, 잡은 말 수만큼 더 던져요. | |
|
||||
| `delivery` | 배달 | 즉시 | 증강 하나를 주문해요. 다음 증강 선택 때 그 증강이 내 후보에 꼭 나와요. | |
|
||||
| `dokkaebi` | 변환: 도깨비 | 사용·1회 | 내 일반 말 하나를 도깨비로 바꿔요. 도깨비는 내 차례마다 한 번, 던지지 않고 앞이나 뒤로 1칸 갈 수 있어요. | |
|
||||
| `vanguard` | 변환: 선봉장 | 사용·1회 | 내 일반 말 하나를 선봉장으로 바꿔요. 선봉장이 판 위에 있는 동안 내 말은 앞으로 갈 때마다 1칸 더 가요. | |
|
||||
| `cannon` | 변환: 포 | 사용·1회 | 내 판 위 일반 말 하나를 포로 바꿔요. 포는 내 차례마다 한 번, 말이 있는 칸 하나를 넘어 한 줄로 원하는 만큼 갈 수 있어요. | 넘은 뒤 처음 만나는 말이 다른 편이면 잡을 수 있어요. 참먹이에는 내려앉지 못해요. |
|
||||
| `pawn` | 변환: 폰 | 사용·1회 | 내 일반 말 하나를 폰으로 바꿔요. 폰은 직접 움직일 수 없지만 내가 던질 때마다 1칸씩 앞으로 가요. | |
|
||||
| `four` | 사목 | 승리 조건 | 내 말이 한 줄로 이어진 네 칸을 차지하거나, 내 말 4개가 한 말뭉치가 되면 이겨요. | |
|
||||
| `ox` | 소 뒷걸음질 | 승리 조건 | 빽도로 말을 두 번 잡으면 이겨요. | |
|
||||
| `sleight` | 손은 눈보다 빠르다 | 사용·1회 | 이번 던지기의 결과를 원하는 대로 골라서 내요. | |
|
||||
| `timetravel` | 시간 여행 | 사용·1회 | 내 말뭉치 하나를 지나온 칸 중 원하는 곳으로 되돌려요. | |
|
||||
| `score` | 악보가 완성되었다! | 승리 조건 | 이번 게임에서 빽도·도·개·걸·윷·모를 모두 한 번 이상 내면 이겨요. | 증강을 얻기 전에 낸 것도 세요. |
|
||||
| `fog` | 안개 | 사용·1회 | 내 차례 두 번이 돌아올 때까지 판에 안개가 껴요. 다른 사람은 자기 말 근처만 볼 수 있어요. | |
|
||||
| `alkkagi` | 알까기 | 사용·1회·차례 소모 | 내 말 하나를 손가락으로 튕겨요. 부딪힌 말이 판 밖으로 나가면 잡혀요. | 차례를 다 써요(던지기 전에만). 업힌 말뭉치를 고르면 말 1개만 날아가요. 멈춘 말은 가장 가까운 칸에 서요. |
|
||||
| `catlover` | 애묘인 | 승리 조건 | 누구든 고양이를 고른 사람이 있으면 이겨요. | 이미 고른 사람이 있어도 돼요. |
|
||||
| `fisherman` | 어부지리 | 규칙 | 내 차례가 아닐 때 다른 사람 말이 2개 잡힐 때마다 개를 하나 받아요. 받은 개는 다음 내 차례에 써요. | |
|
||||
| `illusion` | 언제부터 착각한 거지? | 즉시 | 다른 사람의 증강 하나를 3라운드 동안 고양이로 바꿔요. | 이미 다 쓴 증강은 고를 수 없어요. |
|
||||
| `throwyut` | 윷을 잘 던져봐 | 사용·1회 | 윷을 던져 한 사람을 맞혀요. 맞은 사람은 차례를 두 번 건너뛰어요. | |
|
||||
| `dual` | 이도류 | 규칙 | 윷가락을 2개씩 두 번 던져서 결과를 두 개 받아요. 모(둘 다 등)는 도로 바뀌어요. | 도·개·빽도만 나와서 한 번 더 던지는 일은 없어요. |
|
||||
| `objection` | 이의있음! | 즉시 | 이번 증강 선택을 없던 걸로 하고 새 후보 중에서 다시 골라요. | |
|
||||
| `jajinmori` | 자진모리 장단 | 규칙 | 걸이 두 번 나올 때마다 개를 하나 더 받아요. | |
|
||||
| `moonwalk` | 천마군림보 - 달걸음 | 규칙 | 내 말은 모두 반대 방향(시계 방향)으로 돌아요. | 참먹이에서 날윷 쪽으로 출발하고, 찌모·뒷모·방에 멈추면 지름길로 꺾어요. |
|
||||
| `shield` | 천상의 보호막 | 사용·1회 | 내 말뭉치 하나에 보호막을 씌워요. 보호막은 잡힐 때 한 번 막아 줘요. | 막아 낸 말은 그 자리에 그대로 남아요. |
|
||||
| `bigred` | 크고 빨간 버튼 | 즉시 | 두 대각선 지름길(방 포함, 모서리 제외)에 있는 모든 말을 잡아요. 내 말도요. | |
|
||||
| `friendshield` | 프랜드 실드 | 규칙 | 내 말뭉치가 잡힐 때 말 1개만 잡히고 나머지는 남아요. | |
|
||||
| `sacrifice` | 희생 | 사용·1회 | 판 위의 내 말 하나를 스스로 잡혀요. 판 위의 다른 내 말에 모두 보호막을 씌워요. | |
|
||||
| `poop` | 히히 똥! | 즉시 | 무작위 칸에 똥을 싸요. 다른 사람 말은 지나가다 똥을 밟으면 그 자리에 멈춰요. | |
|
||||
|
||||
### 시작 전용 (9개)
|
||||
| id | 이름 | 종류 | 효과 | 세부 |
|
||||
|---|---|---|---|---|
|
||||
| `equiv` | 등가교환 | 즉시 | 내 말 1개와 윷가락 1개를 빼고 시작해요. | 윷가락 3개로는 윷이 나오지 않아요(배 3개는 걸). |
|
||||
| `party` | 말이오? 파티 | 즉시 | 판에 함정 6개와 선물 4개를 깔아요. 딱 멈춘 말은 잡히거나 옮겨져요. 내가 깐 함정에는 걸리지 않아요. | 해골: 잡힘 · 마녀 모자: 뒤로 2칸 · 선물: 앞으로 2칸(누구나). |
|
||||
| `speedrun` | 스겜 | 즉시 | 모든 사람의 말이 2개가 되고, 내 말은 도와 개 자리에서 시작해요. | |
|
||||
| `kim` | 시작 변환: 김첨지 | 즉시·승리 조건 | 내 말 하나가 김첨지가 돼요. 김첨지가 내 차례 6번 안에 나면 이겨요. | 6번이 지나면 보통 말처럼 움직여요. |
|
||||
| `queen` | 시작 변환: 중전마마 | 즉시·승리 조건 | 내 말 하나가 중전마마가 되어 뒷모(왼쪽 위)에 서요. 내가 12번 던질 때까지 지키면 이기고, 목숨이 다 떨어지면 탈락해요. | 중전마마는 날 수 없어요. 목숨은 1개로 시작하고, 다른 말이 날 때마다 1개 늘어요. 잡히면 목숨을 잃고 대기로 돌아가요. |
|
||||
| `bear` | 웅녀 | 즉시·승리 조건 | 무작위 칸 3곳에 마늘이 놓여요. 내 말이 마늘 칸에 멈춰 3개를 모두 모으면 이겨요. | |
|
||||
| `piggyback` | 이리 오너라 업고 놀자 | 즉시 | 내 말을 모두 업은 채 도 자리에서 시작해요. | |
|
||||
| `burden` | 짐덩이와 복덩이 | 즉시 | 내 말 1개와 윷가락 1개를 더하고 시작해요. | 윷가락 5개로 던져요. 배가 4~5개면 윷이에요. |
|
||||
| `alone` | 천상천하 유아독존 | 승리 조건 | 내가 잡아서 판 위에 내 말뭉치 1개만 남으면 이겨요. | |
|
||||
|
||||
### 중간 전용 (7개)
|
||||
| id | 이름 | 종류 | 효과 | 세부 |
|
||||
|---|---|---|---|---|
|
||||
| `triple7` | 777 | 승리 조건 | 한 차례 안에 같은 결과가 세 번 나오면 이겨요. | |
|
||||
| `nofriends` | 나만 친구 없어 | 승리 조건 | 이 증강을 고른 뒤 다른 모든 사람이 내 말을 한 번씩 잡으면 이겨요. | |
|
||||
| `summon` | 마신 소환 | 즉시·승리 조건 | 내 일반 말이 모두 광신도가 돼요. 내 차례가 시작될 때 판 위 광신도마다 의식 코인을 1개 받고, 12개를 모으면 이겨요. | |
|
||||
| `coup` | 무신정변 | 승리 조건 | 이 증강을 고른 뒤 다른 편 말을 4개 잡으면 이겨요. | |
|
||||
| `treason` | 역모 | 규칙 | 나보다 난 말이 많은 사람의 말을 잡으면 한 번 더 던져요. | |
|
||||
| `wait` | 잠깐! | 즉시 | 다른 사람 말 중 가장 앞선 말뭉치 하나가 2라운드 동안 못 움직여요. | |
|
||||
| `peace` | 평화 협정 | 규칙 | 나는 다른 사람 말을 잡을 수 없고, 다른 사람도 내 말을 잡을 수 없어요. 증강으로 잡는 것도요. | 같은 칸에 멈추면 함께 서 있어요. |
|
||||
|
||||
### 마무리 전용 (13개)
|
||||
| id | 이름 | 종류 | 효과 | 세부 |
|
||||
|---|---|---|---|---|
|
||||
| `plan` | 계획대로 | 즉시·승리 조건 | 모든 사람의 최종 순위를 예언해요. 다 맞히면 순위를 없애고 나 혼자 이겨요. | |
|
||||
| `murder` | 나에게 윷놀이는 "살인"이다 | 즉시 | 모든 사람에게 체력 3이 생겨요. 내가 말을 잡을 때마다 잡힌 말 수만큼 그 사람 체력이 줄고, 0이 되면 탈락해요. | |
|
||||
| `necro` | 네크로맨서 | 사용·1회 | 탈락한 사람 한 명을 되살려요. 그 사람이 이기면 나도 같은 순위로 이겨요. | 기권하거나 나간 사람은 되살릴 수 없어요. |
|
||||
| `poison` | 독이 든 성배 | 사용 | 내 차례에 마시면 던지기 3번을 더 받아요. 마신 차례에 모가 나오면 탈락해요. | 한 차례에 한 번 마실 수 있어요. |
|
||||
| `bronze` | 동메달도 잘한 거야 | 즉시·승리 조건 | 바로 3위로 게임을 마쳐요. | 3명 이상 남아 있을 때만 후보에 나와요. |
|
||||
| `lastdance` | 라스트 댄스 | 사용·1회 | 이번 차례 동안 내 말이 모두 두 배로 움직여요. 차례가 끝나면 탈락해요. | 이번 차례에 이기면 탈락하지 않아요. |
|
||||
| `echo` | 메아리의 형상 | 즉시 | 내 차례부터 모든 사람이 차례를 두 번씩 해요. | |
|
||||
| `marathon` | 변환: 마라토너 | 사용·1회·승리 조건 | 대기 중인 내 일반 말 하나를 마라토너로 바꿔요. 마라토너가 나면 이겨요. | |
|
||||
| `duel` | 승부다! | 즉시 | 한 사람을 골라요. 그 사람이 자기 차례 3번 안에 말을 하나도 못 내면 탈락하고, 내면 내가 탈락해요. | |
|
||||
| `comeback` | 역전 찬스 | 즉시 | 무작위 증강 3개를 받아요. | |
|
||||
| `domain` | 영역 전개 | 사용·1회·승리 조건 | 판 위 내 말뭉치 하나를 못 움직이게 묶어요. 내 차례가 두 번 돌아올 때까지 살아남으면 이기고, 잡히면 탈락해요. | |
|
||||
| `cancel` | 취~소 | 즉시 | 모든 특수 승리를 취소해요. 승리 조건 증강은 모두 효과가 없어지고, 특수 승리로 끝낸 사람은 게임으로 돌아와요. | |
|
||||
| `cannibal` | 카니발리즘 | 규칙 | 내 말끼리 업을 수 없는 대신 내 말을 잡을 수 있어요. 내 말을 잡으면 한 번 더 던져요. | |
|
||||
|
||||
### 이 사이트 추가 (10개)
|
||||
| id | 이름 | 종류 | 효과 | 세부 |
|
||||
|---|---|---|---|---|
|
||||
| `teleport` | 순간이동 | 사용·1회 | 내 말뭉치 하나를 다른 내 말뭉치 자리로 옮겨 업어요. | |
|
||||
| `shortcut` | 지름길 달인 | 규칙 | 내 말은 모서리와 방을 지나가기만 해도 지름길로 꺾어요. | |
|
||||
| `turtle` | 거북이 등껍질 | 규칙 | 말이 3개 이상 업힌 내 말뭉치는 잡히지 않아요. | |
|
||||
| `revenge` | 복수의 칼날 | 규칙 | 내 말이 잡힐 때마다 다음 내 차례에 한 번 더 던져요. | 모아 둘 수 있는 건 2번까지예요. |
|
||||
| `thief` | 손버릇 | 즉시 | 다른 사람의 아직 쓰지 않은 증강 하나를 빼앗아 와요. | |
|
||||
| `mine` | 지뢰 매설 | 사용·1회 | 내 말이 있는 칸에 지뢰를 몰래 묻어요. 다른 사람 말이 그 칸에 멈추면 잡혀요. | 지뢰는 나에게만 보이고, 한 번 터지면 사라져요. |
|
||||
| `tiger` | 호랑이 기운 | 규칙 | 걸이 나와도 윷·모처럼 한 번 더 던져요. | |
|
||||
| `twins` | 쌍둥이 | 사용·1회 | 대기 중인 내 말 하나를 판 위 내 말뭉치에 바로 업혀요. | |
|
||||
| `swap` | 자리 바꾸기 | 사용·1회 | 내 말뭉치 하나와 다른 사람 말뭉치 하나의 자리를 맞바꿔요. | |
|
||||
| `storm` | 회오리 | 즉시·중간 전용 | 판 위의 모든 말뭉치가 회오리에 휩쓸려 무작위 칸으로 흩어져요. | 참먹이에는 떨어지지 않고, 말뭉치끼리 겹치지 않아요. |
|
||||
|
||||
## 5. 옵션
|
||||
| 키 | 설명 | 기본 |
|
||||
|---|---|---|
|
||||
| `augmented` | 증강 윷놀이 | `false` |
|
||||
| `augChaos` | 혼돈 모드(한 번에 2개) | `false` |
|
||||
| `augRounds` | 고르는 라운드 `standard`(1·6·12) / `quick`(1·4·8) / `many`(1·3·5·7·9) | `standard` |
|
||||
| `augOffers` | 후보 수 2·3·4 | 3 |
|
||||
| `augOff` | 나오지 않게 뺀 증강 id 목록 | `[]` |
|
||||
|
||||
관리자 화면에서 기본값·잠금을 정할 수 있다(`augOff`는 체크 목록).
|
||||
|
||||
## 6. 액션
|
||||
`THROW {pick?: 'do'|'gae'}`(개돼지), `MOVE {piece?}`(대기 특수 말은 `from:'home', piece`), `AUG_PICK {aug, target?}`(명탐정·배달 대상), `AUG_ANSWER {choice}`(계획대로는 순서 배열), `AUG_USE {uid, piece?, node?, node2?, target?, result?, angle?, power?}`, `SPECIAL {piece, to}`(도깨비·포).
|
||||
|
||||
## 7. 화면
|
||||
- 오른쪽 위 라운드 막대: "N라운드 · 다음 증강 선택 M라운드", 메아리·안개·취소 표시.
|
||||
- 증강 선택 창(시트): 원작처럼 후보 카드 + "이 후보와 고른 것은 나에게만 보여요" + [👁 판 보기]로 잠깐 닫고 [증강 후보 보기]로 다시 연다. 간택이면 고양이 말고는 못 누름.
|
||||
- 사람 카드: 가진 증강 칩(사용함 ✔, 무효 줄, 🐱), 진행(투척 n/12, 의식 n/12, 마늘 n/3 …), 체력·건너뛰기·윷가락 수·거머리 연결.
|
||||
- 판: 함정 💀🎩, 선물 🎁, 똥 💩, 마늘 🧄, 조준 🎯, 지뢰 💣(주인만), 특수 말 배지(👹🚩包♟🧔👑🕯🏃), 보호막 금색 점선, 묶임 ❄, 안개(내 말 근처만 뚫린 회색 막), 알까기 조준 화살표와 튕김 재생.
|
||||
- [✨ 내 증강 쓰기]: 지금 쓸 수 있는 증강 버튼 → 대상 목록(칸 대상은 판에서 눌러도 됨) → 바로 사용. 특수 말 이동 버튼.
|
||||
- 특수 승리·탈락 팝업(원작처럼 "특수 승리 조건 달성 / 증강 이름 / 사람 / N위 확보"), 그 밖의 효과는 판 위 알림.
|
||||
- 결과 화면 점수 칸에 순위 사유(전원 완주, 증강 이름, 탈락 사유).
|
||||
|
||||
## 8. 컴퓨터
|
||||
`aug-bot.ts`: 증강마다 가치표로 고르고(동메달은 뒤처질 때, 취~소는 남이 승리 조건을 가졌을 때 높게), 질문은 선두를 견제(거머리·투표는 선두, 승부는 꼴찌), 능력은 잡을 말이 있을 때(트럭·바둑·합체·명사수), 알까기는 가까운 적을 겨냥, 변환은 바로. 나머지는 보통 윷놀이 컴퓨터.
|
||||
|
||||
## 9. 테스트
|
||||
`packages/games/src/yut/aug.test.ts`: 선택(비공개 후보, 제외, 명탐정, 이의있음, 간택, 혼돈, 6라운드 재선택, 시간 초과), 던지기 증강, 이동·잡기 증강, 능력·즉시 효과, 특수 승리·탈락, 무작위 대국(검증: view 오류 없음, 탈락·순위 편 말이 판에 없음, 움직일 차례가 살아 있는 편), 컴퓨터 대국. 브라우저: `bun e2e/games.e2e.ts yut-aug`.
|
||||
@@ -7,6 +7,8 @@
|
||||
- 인원 근거: 전통 윷놀이는 2명이 겨루거나, 여러 명이 두 편으로 나뉘어(인원 제한 없음) 한다. 개인전은 화면·말 색 구분이 가능한 4명까지, 팀전은 2팀 × 최대 4명(총 8명)으로 제한한다. `minPlayers = 2`, `maxPlayers = 8`이며 개인전 5명 이상은 옵션 검증에서 막는다.
|
||||
|
||||
## 2. 모드와 옵션
|
||||
> 증강 윷놀이(`augmented`, `augChaos`, `augRounds`, `augOffers`, `augOff`)는 [yut-augmented.md](yut-augmented.md)에 따로 정리했다.
|
||||
|
||||
| 옵션 키 | 설명 | 선택지 | 기본값 |
|
||||
|---|---|---|---|
|
||||
| `mode` | 개인전 / 팀전 | `individual`(2~4명), `team`(4·6·8명, 2팀) | `individual` |
|
||||
|
||||
156
e2e/games.e2e.ts
156
e2e/games.e2e.ts
@@ -1598,6 +1598,162 @@ const PLANS: Record<string, Plan> = {
|
||||
console.log(` yut: finished after ${actions} UI actions (지역 룰 choices used: ${[...yutChoiceSeen].join(', ') || 'none'})`);
|
||||
},
|
||||
},
|
||||
'yut-aug': {
|
||||
// 증강 윷놀이: 방장이 게임 종류를 증강으로 바꾸고 [증강 윷놀이] 탭에서 설정을 확인한 뒤, PC 방장 + 휴대폰 친구 둘이
|
||||
// 증강 선택 창·질문 창·증강 쓰기·말 움직이기를 실제 화면 조작으로 해 나간다(끝까지 또는 200번 조작).
|
||||
game: 'yut',
|
||||
players: 3,
|
||||
lobby: async (host) => {
|
||||
await host.getByRole('button', { name: '증강 윷놀이', exact: true }).first().click();
|
||||
await host.getByRole('tab', { name: '증강 윷놀이' }).click();
|
||||
await host.getByText(/켜진 증강/).first().waitFor();
|
||||
await host.screenshot({ path: join(SHOTS, 'yut-aug-options-pc.png'), fullPage: true });
|
||||
await host.getByRole('tab', { name: '기본 설정' }).click();
|
||||
await host.getByRole('button', { name: '3개', exact: true }).click();
|
||||
// 증강을 자주 고르도록 1·3·5·7·9라운드, 후보 4개
|
||||
await host.getByRole('tab', { name: '증강 윷놀이' }).click();
|
||||
await host.getByRole('button', { name: '1·3·5·7·9라운드' }).click();
|
||||
await host.getByRole('button', { name: '4개', exact: true }).click();
|
||||
await host.getByRole('tab', { name: '기본 설정' }).click();
|
||||
await host.getByText(/증강 윷놀이 · 개인전 · 말 3개/).first().waitFor();
|
||||
const guest = host.context().browser()!.contexts().at(-1)!.pages()[0]!;
|
||||
await guest.getByRole('button', { name: '설정 보기' }).click();
|
||||
const sheet = guest.getByRole('dialog', { name: '게임 설정' });
|
||||
await sheet.getByRole('tab', { name: '증강 윷놀이' }).click();
|
||||
await sheet.getByText(/켜진 증강/).first().waitFor();
|
||||
await guest.screenshot({ path: join(SHOTS, 'yut-aug-options-phone.png') });
|
||||
await guest.setViewportSize({ width: 320, height: 640 });
|
||||
await guest.emulateMedia({ colorScheme: 'dark' });
|
||||
await guest.screenshot({ path: join(SHOTS, 'yut-aug-options-phone-320-dark.png') });
|
||||
const wide = await guest.evaluate(() => {
|
||||
const sh = document.querySelector('.sheet');
|
||||
return document.documentElement.scrollWidth > window.innerWidth + 1 || (!!sh && sh.scrollWidth > sh.clientWidth + 1);
|
||||
});
|
||||
if (wide) throw new Error('증강 options overflow at 320px');
|
||||
await guest.emulateMedia({ colorScheme: 'light' });
|
||||
await guest.setViewportSize({ width: 390, height: 844 });
|
||||
await sheet.getByRole('button', { name: '닫기', exact: true }).click();
|
||||
},
|
||||
drive: async (pages) => {
|
||||
const [host, guest] = pages as [Page, Page];
|
||||
const tag = (p: Page) => (p.viewportSize()!.width < 600 ? 'phone' : 'pc');
|
||||
const seen = new Set<string>();
|
||||
const shotOnce = async (p: Page, name: string) => {
|
||||
const k = `${name}-${tag(p)}`;
|
||||
if (seen.has(k)) return;
|
||||
seen.add(k);
|
||||
await p.waitForTimeout(250);
|
||||
await p.screenshot({ path: join(SHOTS, `yut-aug-${k}.png`), fullPage: tag(p) === 'phone' });
|
||||
};
|
||||
const stats = { picks: 0, prompts: 0, uses: 0, moves: 0, popups: 0 };
|
||||
/** One augment UI step on `p`, or false. */
|
||||
const augStep = async (p: Page): Promise<boolean> => {
|
||||
const dialog = p.getByRole('dialog');
|
||||
if (await dialog.count()) {
|
||||
// special victory / out popup
|
||||
const ok = dialog.getByRole('button', { name: /^(\d+위 확보|확인)$/ });
|
||||
if (await ok.count()) {
|
||||
await shotOnce(p, 'popup');
|
||||
await ok.first().click();
|
||||
stats.popups++;
|
||||
return true;
|
||||
}
|
||||
const cards = dialog.locator('.aug-card:not([disabled])');
|
||||
if (await cards.count()) {
|
||||
await shotOnce(p, 'select');
|
||||
await cards.nth(stats.picks % (await cards.count())).click();
|
||||
const sel = dialog.locator('select');
|
||||
if (await sel.count()) await sel.selectOption({ index: 1 });
|
||||
await dialog.getByRole('button', { name: /고르기$/ }).click();
|
||||
stats.picks++;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const open = p.getByRole('button', { name: '증강 후보 보기' });
|
||||
if ((await open.count()) && !(await dialog.count())) {
|
||||
await open.click();
|
||||
return true;
|
||||
}
|
||||
const plan = p.getByRole('button', { name: '이 순서로 예언하기' });
|
||||
if (await plan.count()) {
|
||||
for (const b of await p.locator('.aug-plan button').all()) await b.click();
|
||||
await plan.click();
|
||||
stats.prompts++;
|
||||
return true;
|
||||
}
|
||||
const prompt = p.locator('.card .aug-target-list button:not([disabled])');
|
||||
if ((await prompt.count()) && !(await p.locator('.aug-uses').count())) {
|
||||
await shotOnce(p, 'prompt');
|
||||
await prompt.first().click();
|
||||
stats.prompts++;
|
||||
return true;
|
||||
}
|
||||
// use an augment now and then (not the whole-turn ones every time)
|
||||
const useBtn = p.locator('.aug-uses .aug-use-row button:not([disabled])');
|
||||
if ((await useBtn.count()) && stats.moves % 2 === 0) {
|
||||
await useBtn.first().click();
|
||||
const aim = p.getByRole('button', { name: /튕기기/ });
|
||||
const target = p.locator('.aug-uses .aug-target-list button.btn-primary:not([disabled])');
|
||||
if (await target.count()) {
|
||||
await shotOnce(p, 'use');
|
||||
await target.first().click();
|
||||
if (await aim.count()) {
|
||||
await shotOnce(p, 'aim');
|
||||
await aim.click();
|
||||
}
|
||||
stats.uses++;
|
||||
stats.moves++;
|
||||
return true;
|
||||
}
|
||||
if (await aim.count()) {
|
||||
await aim.click();
|
||||
stats.uses++;
|
||||
stats.moves++;
|
||||
return true;
|
||||
}
|
||||
const cancel = p.locator('.aug-uses').getByRole('button', { name: '취소' });
|
||||
if (await cancel.count()) await cancel.click();
|
||||
}
|
||||
const pig = p.getByRole('button', { name: /개 내기/ });
|
||||
if ((await pig.count()) && (await pig.isEnabled())) {
|
||||
await pig.click();
|
||||
stats.moves++;
|
||||
return true;
|
||||
}
|
||||
if (await yutStep(p)) {
|
||||
stats.moves++;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const until = Date.now() + 360_000;
|
||||
const over = () => host.getByText(/이겼어요|아쉽게 졌어요/).count();
|
||||
let steps = 0;
|
||||
while (Date.now() < until && !(await over()) && steps < 320) {
|
||||
let acted = false;
|
||||
for (const p of pages) {
|
||||
if (await augStep(p).catch(() => false)) {
|
||||
acted = true;
|
||||
steps++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const objs = await host.locator('[aria-label="판 위의 증강 물건"] > g').count();
|
||||
if (objs && !seen.has('objs')) {
|
||||
seen.add('objs');
|
||||
await host.locator('.yut-board').screenshot({ path: join(SHOTS, 'yut-aug-objs-board.png') });
|
||||
}
|
||||
if (steps === 30 || steps === 120 || steps === 200) {
|
||||
await host.screenshot({ path: join(SHOTS, `yut-aug-mid${steps}-pc.png`) });
|
||||
await guest.screenshot({ path: join(SHOTS, `yut-aug-mid${steps}-phone.png`), fullPage: true });
|
||||
}
|
||||
if (!acted) await host.waitForTimeout(150);
|
||||
}
|
||||
await host.screenshot({ path: join(SHOTS, 'yut-aug-end-pc.png') });
|
||||
console.log(` yut-aug: ${steps} UI steps ${JSON.stringify(stats)} finished=${(await over()) > 0}`);
|
||||
if (stats.picks < 3) throw new Error('augment selection did not work');
|
||||
},
|
||||
},
|
||||
'one-card': {
|
||||
// 3 players, default 원카드: whoever has the turn plays a highlighted card (tap to lift, tap again to play,
|
||||
// pick a suit for 7) or draws; the 원카드 button is pressed whenever it lights up. 60 turns or until the game ends.
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
"./tichu/combo": "./src/tichu/combo.ts",
|
||||
"./case-file/types": "./src/case-file/types.ts",
|
||||
"./castles-of-burgundy/data": "./src/castles-of-burgundy/data.ts",
|
||||
"./yut/board": "./src/yut/board.ts",
|
||||
"./yut/augments": "./src/yut/augments.ts",
|
||||
"./*": "./src/*/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
179
packages/games/src/yut/aug-bot.ts
Normal file
179
packages/games/src/yut/aug-bot.ts
Normal file
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* 증강 윷놀이 computer decisions: which augment to pick, how to answer prompts, and when to use an ability.
|
||||
* Returns null to fall back to the plain 윷놀이 bot (throwing and moving).
|
||||
*/
|
||||
import { AUGS, type AugId } from './augments';
|
||||
import { NODE_POS, remainingDistance, type NodeId } from './board';
|
||||
import type { YutAction, YutView } from './index';
|
||||
|
||||
/** Rough worth of each augment for a computer (higher = pick first). */
|
||||
const VALUE: Partial<Record<AugId, number>> = {
|
||||
comeback: 9, notme: 8, combo: 7, sleight: 7, tiger: 7, vanguard: 7, thief: 6, bigred: 6, truck: 6, baduk: 6, doberman: 6, shield: 6,
|
||||
friendshield: 6, dokkaebi: 6, marathon: 6, speedrun: 6, piggyback: 6, summon: 6, coup: 6, murder: 6, throwyut: 6, peace: 5,
|
||||
catlover: 5, turtle: 5, revenge: 5, fisherman: 5, kim: 5, party: 5, burden: 5, equiv: 5, triple7: 5, wait: 5, duel: 5, doggy: 5,
|
||||
score: 5, twins: 5, swap: 5, shortcut: 5, cannon: 5, poison: 4, jajinmori: 4, pawn: 4, queen: 4, bear: 4, treason: 4, echo: 4,
|
||||
domain: 4, getoff: 4, moordo: 4, leech: 4, illusion: 4, alkkagi: 4, four: 4, mine: 4, teleport: 4, cannibal: 3, alone: 3,
|
||||
nofriends: 3, plan: 3, necro: 3, cancel: 3, whoami: 3, roulette: 3, fold: 3, excess: 3, dual: 3, fog: 3, sniper: 3, ox: 3,
|
||||
detective: 3, delivery: 3, storm: 3, sacrifice: 3, moonwalk: 3, lastdance: 1, chosen: 2, objection: 2, timetravel: 2, cat: 1,
|
||||
};
|
||||
|
||||
type A = YutAction;
|
||||
|
||||
export function augBotAction(view: YutView, legal: A[], random: () => number): A | null {
|
||||
const aug = view.aug!;
|
||||
const me = view.mySide;
|
||||
const has = (t: string) => legal.filter((a) => a.type === t);
|
||||
// ---- picking an augment
|
||||
const picks = has('AUG_PICK') as Extract<A, { type: 'AUG_PICK' }>[];
|
||||
if (picks.length) {
|
||||
const progress = me === null ? 0 : standing(view, me);
|
||||
const worth = (id: AugId) => {
|
||||
let v = VALUE[id] ?? 3;
|
||||
if (id === 'bronze') v = progress >= 0.6 ? 2 : 8; // a sure 3rd place is good when behind
|
||||
if (id === 'cancel') v = (aug.sides.some((x) => x.id !== me && x.augs.some((o) => ['four', 'ox', 'score', 'catlover', 'coup', 'summon', 'queen', 'kim', 'bear', 'domain', 'marathon'].includes(o.id))) ? 7 : 2);
|
||||
return v + random() * 1.5;
|
||||
};
|
||||
const best = picks.reduce((x, y) => (worth(y.aug) > worth(x.aug) ? y : x));
|
||||
if (best.aug === 'detective' || best.aug === 'delivery') {
|
||||
const same = picks.filter((p) => p.aug === best.aug);
|
||||
return same.reduce((x, y) => ((VALUE[y.target!] ?? 3) > (VALUE[x.target!] ?? 3) ? y : x));
|
||||
}
|
||||
return best;
|
||||
}
|
||||
// ---- answering a prompt
|
||||
const answers = has('AUG_ANSWER') as Extract<A, { type: 'AUG_ANSWER' }>[];
|
||||
if (answers.length) {
|
||||
const pr = aug.prompt;
|
||||
if (!pr) return answers[0]!;
|
||||
const leader = [...view.sides].filter((x) => x.id !== me && !x.out && x.finishedRank === null).sort((p, q) => q.done - p.done || p.remaining - q.remaining)[0]?.id;
|
||||
const trailer = [...view.sides].filter((x) => x.id !== me && !x.out && x.finishedRank === null).sort((p, q) => p.done - q.done || q.remaining - p.remaining)[0]?.id;
|
||||
const byChoice = (v: number | undefined) => answers.find((a) => a.choice === v) ?? answers[Math.floor(random() * answers.length)]!;
|
||||
switch (pr.kind) {
|
||||
case 'leech':
|
||||
return byChoice(leader);
|
||||
case 'vote':
|
||||
return byChoice(leader);
|
||||
case 'duel':
|
||||
return byChoice(trailer);
|
||||
case 'roulette':
|
||||
return answers[random() < 0.5 ? 0 : answers.length - 1]!;
|
||||
case 'plan': {
|
||||
const order = [...view.sides].sort((p, q) => (p.finishedRank ?? 99) - (q.finishedRank ?? 99) || +p.out - +q.out || q.done - p.done || p.remaining - q.remaining).map((x) => x.id);
|
||||
return { type: 'AUG_ANSWER', choice: order } as A;
|
||||
}
|
||||
case 'illusion':
|
||||
case 'thief': {
|
||||
const opts = pr.choices ?? [];
|
||||
const val = (label: string) => {
|
||||
const name = label.split(' · ')[1] ?? '';
|
||||
const id = (Object.keys(VALUE) as AugId[]).find((k) => AUG_NAME[k] === name);
|
||||
return id ? (VALUE[id] ?? 3) : 3;
|
||||
};
|
||||
const top = opts.reduce((x, y) => (val(y.label) > val(x.label) ? y : x), opts[0]!);
|
||||
return byChoice(top?.value);
|
||||
}
|
||||
default:
|
||||
return answers[Math.floor(random() * answers.length)]!;
|
||||
}
|
||||
}
|
||||
// ---- my turn: abilities before throwing / moving
|
||||
const uses = has('AUG_USE') as Extract<A, { type: 'AUG_USE' }>[];
|
||||
const opt = (a: Extract<A, { type: 'AUG_USE' }>) => aug.uses.find((u) => u.uid === a.uid && u.action.piece === a.piece && u.action.node === a.node && u.action.node2 === a.node2 && u.action.target === a.target && u.action.result === a.result);
|
||||
const idOf = (a: Extract<A, { type: 'AUG_USE' }>) => aug.sides.find((x) => x.id === me)?.augs.find((o) => o.uid === a.uid)?.id;
|
||||
let bestUse: { a: A; v: number } | null = null;
|
||||
const consider = (a: A, v: number) => {
|
||||
if (v > 0 && (!bestUse || v > bestUse.v)) bestUse = { a, v };
|
||||
};
|
||||
const leaderSide = [...view.sides].filter((x) => x.id !== me && !x.out && x.finishedRank === null).sort((p, q) => q.done - p.done || p.remaining - q.remaining)[0]?.id;
|
||||
for (const u of uses) {
|
||||
const id = idOf(u);
|
||||
const o = opt(u);
|
||||
if (!id) continue;
|
||||
switch (id) {
|
||||
case 'combo':
|
||||
consider(u, (o?.kills ?? 0) >= 3 ? 10 + (o?.kills ?? 0) : 0);
|
||||
break;
|
||||
case 'truck':
|
||||
case 'baduk':
|
||||
consider(u, (o?.kills ?? 0) > 0 ? 8 + (o?.kills ?? 0) : 0);
|
||||
break;
|
||||
case 'sniper':
|
||||
consider(u, (o?.kills ?? 0) >= 2 ? 3 + (o?.kills ?? 0) : 0);
|
||||
break;
|
||||
case 'alkkagi': {
|
||||
if (u.angle === undefined) break;
|
||||
// aim at the nearest enemy stack from this stack
|
||||
if (o?.at === undefined || o.at === 'home') break;
|
||||
const [mx, my] = NODE_POS[o.at]!;
|
||||
const enemy = view.stacks.filter((st) => st.side !== me && st.side >= 0).map((st) => ({ st, d: Math.hypot(NODE_POS[st.node]![0] - mx, NODE_POS[st.node]![1] - my) })).sort((p, q) => p.d - q.d)[0];
|
||||
if (!enemy || enemy.d > 35) break;
|
||||
const [ex, ey] = NODE_POS[enemy.st.node]!;
|
||||
const angle = Math.round(((Math.atan2(ey - my, ex - mx) * 180) / Math.PI + 360) % 360) % 360;
|
||||
consider({ ...u, angle, power: 80 } as A, 7);
|
||||
break;
|
||||
}
|
||||
case 'doberman': {
|
||||
const n = Number(/(\d+)/.exec(o?.label ?? '')?.[1] ?? 0);
|
||||
consider(u, n >= 4 ? 6 : 0);
|
||||
break;
|
||||
}
|
||||
case 'sleight':
|
||||
consider(u, u.result === 'mo' ? 6 : u.result === 'yut' ? 5 : 0);
|
||||
break;
|
||||
case 'vanguard':
|
||||
case 'cannon':
|
||||
consider(u, (o?.label ?? '').startsWith('대기') ? 0 : 6);
|
||||
break;
|
||||
case 'dokkaebi':
|
||||
case 'pawn':
|
||||
case 'marathon':
|
||||
case 'fog':
|
||||
case 'mine':
|
||||
case 'twins':
|
||||
case 'shield':
|
||||
consider(u, 5);
|
||||
break;
|
||||
case 'throwyut':
|
||||
consider(u, u.target === leaderSide ? 6 : 1);
|
||||
break;
|
||||
case 'necro':
|
||||
consider(u, 4);
|
||||
break;
|
||||
case 'poison':
|
||||
consider(u, random() < 0.25 ? 4 : 0);
|
||||
break;
|
||||
case 'domain':
|
||||
consider(u, random() < 0.2 ? 3 : 0);
|
||||
break;
|
||||
case 'swap': {
|
||||
if (o?.at === undefined || o.at === 'home' || u.node === undefined) break;
|
||||
const gain = remainingDistance(o.at, view.options.finishRule) - remainingDistance(u.node as NodeId, view.options.finishRule);
|
||||
consider(u, gain >= 5 ? 5 : 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// special pieces: a free step forward (or a catch) is always worth it
|
||||
for (const sp of has('SPECIAL') as Extract<A, { type: 'SPECIAL' }>[]) {
|
||||
const m = aug.specials.find((x) => x.piece === sp.piece && x.to === sp.to);
|
||||
if (!m) continue;
|
||||
const fwd = m.to === 'goal' || m.from === 'home' || remainingDistance(m.to as NodeId, view.options.finishRule) < remainingDistance(m.from as NodeId, view.options.finishRule);
|
||||
consider(sp, m.captures ? 9 : m.to === 'goal' ? 8 : fwd ? 4 + random() : 0);
|
||||
}
|
||||
if (bestUse) return (bestUse as { a: A }).a;
|
||||
// 개돼지: pick the result
|
||||
const throws = has('THROW') as Extract<A, { type: 'THROW' }>[];
|
||||
if (throws.length > 1) return throws.find((t) => t.pick === 'gae') ?? throws[0]!;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 0 (last) .. 1 (first): how well I'm doing by finished pieces and distance. */
|
||||
function standing(view: YutView, me: number): number {
|
||||
const live = view.sides.filter((x) => !x.out && x.finishedRank === null);
|
||||
if (live.length <= 1) return 1;
|
||||
const sorted = [...live].sort((p, q) => q.done - p.done || p.remaining - q.remaining);
|
||||
const i = sorted.findIndex((x) => x.id === me);
|
||||
return i < 0 ? 0 : 1 - i / (sorted.length - 1);
|
||||
}
|
||||
|
||||
const AUG_NAME = Object.fromEntries(Object.values(AUGS).map((a) => [a.id, a.name])) as Record<AugId, string>;
|
||||
693
packages/games/src/yut/aug.test.ts
Normal file
693
packages/games/src/yut/aug.test.ts
Normal file
@@ -0,0 +1,693 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { SeededRng, playoutSeeds, randomPlayout, seedN, type Rng } from '@bg/engine';
|
||||
import { botPlayout } from '../bots/playout';
|
||||
import { decideBotAction } from '../bots/index';
|
||||
import { augGiveForTest } from './aug';
|
||||
import { AUG_IDS, AUGS, type AugId } from './augments';
|
||||
import { yut, type NodeId, type Throw, type YutAction, type YutOptions, type YutState } from './index';
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
class Script implements Rng {
|
||||
private vals: number[];
|
||||
constructor(vals: number[]) {
|
||||
this.vals = [...vals];
|
||||
}
|
||||
next(): number {
|
||||
const v = this.vals.shift();
|
||||
if (v === undefined) throw new Error('script exhausted');
|
||||
return v;
|
||||
}
|
||||
int(n: number): number {
|
||||
return Math.floor(this.next() * n);
|
||||
}
|
||||
shuffle<T>(a: readonly T[]): T[] {
|
||||
return [...a];
|
||||
}
|
||||
}
|
||||
const F = 0; // 배
|
||||
const R = 0.99; // 등
|
||||
const STICKS: Record<Throw, number[]> = { do: [R, F, R, R], backdo: [F, R, R, R], gae: [F, F, R, R], geol: [F, F, F, R], yut: [F, F, F, F], mo: [R, R, R, R] };
|
||||
const script = (...ts: Throw[]) => new Script(ts.flatMap((t) => STICKS[t]));
|
||||
const PLAYERS = ['A', 'B', 'C', 'D'];
|
||||
|
||||
/** 증강 game with the selection skipped: side 0 to throw, nobody has an augment yet. */
|
||||
function make(n = 2, opts: Partial<YutOptions> = {}): YutState {
|
||||
const options = yut.optionsSchema.parse({ augmented: true, ...opts });
|
||||
const s = yut.setup({ players: PLAYERS.slice(0, n), options, rng: SeededRng.fromSeed(seedN(3)), now: 0 });
|
||||
const a = s.aug!;
|
||||
a.select = null;
|
||||
a.selNo = 1;
|
||||
a.pendingBegin = false;
|
||||
a.firstSide = 0;
|
||||
Object.assign(s, { turnSide: 0, current: 'A', phase: 'throw', throwsOwed: 1, pending: [] });
|
||||
return s;
|
||||
}
|
||||
const give = (s: YutState, side: number, id: AugId, rng: Rng = SeededRng.fromSeed(seedN(9)), target?: AugId) => augGiveForTest(s, side, id, rng, target);
|
||||
function put(s: YutState, side: number, piece: number, node: NodeId, trail: NodeId[] = [node]): void {
|
||||
Object.assign(s.sides[side]!.pieces[piece]!, { status: 'board', node, trail, lapped: node === 0 });
|
||||
}
|
||||
function act(s: YutState, actor: string, a: YutAction, rng: Rng = SeededRng.fromSeed(seedN(5))): YutState {
|
||||
const v = yut.validate(s, actor, a);
|
||||
if (!v.ok) throw new Error(`${actor} ${JSON.stringify(a)}: ${v.reason}`);
|
||||
return yut.apply(s, actor, a, { rng, now: 1000 }).state;
|
||||
}
|
||||
const moving = (s: YutState, pending: Throw[]) => Object.assign(s, { phase: 'move', throwsOwed: 0, pending });
|
||||
const nodesOf = (s: YutState, side: number) => s.sides[side]!.pieces.map((p) => (p.status === 'board' ? p.node : p.status));
|
||||
const uidOf = (s: YutState, side: number, id: AugId) => s.aug!.sides[side]!.augs.find((o) => o.id === id)!.uid;
|
||||
|
||||
// ---------------------------------------------------------------- options & selection
|
||||
|
||||
describe('증강 윷놀이: options and selection', () => {
|
||||
test('개인전 only; plain games have no aug state', () => {
|
||||
expect(yut.playerCountError!(yut.optionsSchema.parse({ augmented: true, mode: 'team' }), 4)).toContain('개인전');
|
||||
const plain = yut.setup({ players: ['A', 'B'], options: yut.defaultOptions, rng: SeededRng.fromSeed(seedN(1)), now: 0 });
|
||||
expect(plain.aug).toBeUndefined();
|
||||
expect(yut.view(plain, 'A').aug).toBeUndefined();
|
||||
});
|
||||
|
||||
test('the game opens with everyone picking from private offers at once', () => {
|
||||
const s = yut.setup({ players: ['A', 'B', 'C'], options: yut.optionsSchema.parse({ augmented: true }), rng: SeededRng.fromSeed(seedN(2)), now: 0 });
|
||||
expect(s.phase).toBe('aug');
|
||||
expect(yut.activePlayers(s).sort()).toEqual(['A', 'B', 'C']);
|
||||
const va = yut.view(s, 'A').aug!;
|
||||
const vb = yut.view(s, 'B').aug!;
|
||||
expect(va.select!.offers).toHaveLength(3);
|
||||
// first selection: 범용 + 시작 전용 only
|
||||
for (const id of va.select!.offers) expect(['any', 'start']).toContain(AUGS[id].tier);
|
||||
// nobody sees someone else's offers
|
||||
expect(JSON.stringify(yut.view(s, null).aug!.select!.offers)).toBe('[]');
|
||||
expect(vb.select!.offers).toEqual(s.aug!.select!.offers['1']!);
|
||||
let t = s;
|
||||
for (const p of ['A', 'B', 'C']) {
|
||||
const offers = t.aug!.select!.offers[String(['A', 'B', 'C'].indexOf(p))]!;
|
||||
const id = offers.find((x) => x !== 'objection' && x !== 'detective' && x !== 'delivery') ?? offers[0]!;
|
||||
const legal = yut.legalActions!(t, p).find((a) => a.type === 'AUG_PICK' && a.aug === id)!;
|
||||
t = act(t, p, legal);
|
||||
}
|
||||
expect(['throw', 'prompt', 'finished']).toContain(t.phase);
|
||||
expect(t.aug!.sides.every((x) => x.augs.length === 1)).toBe(true);
|
||||
});
|
||||
|
||||
test('augOff: excluded augments are never offered', () => {
|
||||
const off = AUG_IDS.filter((id) => id !== 'cat' && id !== 'tiger' && id !== 'shield' && id !== 'kim');
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const s = yut.setup({ players: ['A', 'B'], options: yut.optionsSchema.parse({ augmented: true, augOff: off }), rng: SeededRng.fromSeed(seedN(40 + i)), now: 0 });
|
||||
for (const k of ['0', '1']) for (const id of s.aug!.select!.offers[k]!) expect(['cat', 'tiger', 'shield', 'kim']).toContain(id);
|
||||
}
|
||||
});
|
||||
|
||||
test('명탐정 voids the same augment picked by someone else in that selection', () => {
|
||||
const s = yut.setup({ players: ['A', 'B'], options: yut.optionsSchema.parse({ augmented: true }), rng: SeededRng.fromSeed(seedN(2)), now: 0 });
|
||||
s.aug!.select!.offers = { '0': ['detective', 'cat', 'fog'], '1': ['tiger', 'cat', 'fog'] };
|
||||
let t = act(s, 'A', { type: 'AUG_PICK', aug: 'detective', target: 'tiger' });
|
||||
expect(yut.validate(t, 'B', { type: 'AUG_PICK', aug: 'detective' }).ok).toBe(false);
|
||||
t = act(t, 'B', { type: 'AUG_PICK', aug: 'tiger' });
|
||||
expect(t.aug!.sides[1]!.augs[0]).toMatchObject({ id: 'tiger', voided: true });
|
||||
expect(yut.view(t, 'A').aug!.sides[1]!.augs[0]!.voided).toBe(true);
|
||||
});
|
||||
|
||||
test('이의있음! rerolls the offers and is not kept', () => {
|
||||
const s = yut.setup({ players: ['A', 'B'], options: yut.optionsSchema.parse({ augmented: true }), rng: SeededRng.fromSeed(seedN(2)), now: 0 });
|
||||
s.aug!.select!.offers['0'] = ['objection', 'cat', 'fog'];
|
||||
const t = act(s, 'A', { type: 'AUG_PICK', aug: 'objection' });
|
||||
const offers = t.aug!.select!.offers['0']!;
|
||||
expect(offers).toHaveLength(3);
|
||||
expect(offers).not.toContain('objection');
|
||||
expect(offers).not.toContain('cat');
|
||||
expect(t.aug!.select!.left['0']).toBe(1);
|
||||
});
|
||||
|
||||
test('간택: a 고양이 among the offers must be taken', () => {
|
||||
const s = make(2);
|
||||
give(s, 1, 'chosen');
|
||||
s.aug!.select = { no: 2, tier: 'mid', offers: { '0': ['cat', 'fog', 'tiger'], '1': ['fog', 'tiger', 'coup'] }, left: { '0': 1, '1': 1 }, picks: [] };
|
||||
s.phase = 'aug';
|
||||
expect(yut.validate(s, 'A', { type: 'AUG_PICK', aug: 'fog' }).ok).toBe(false);
|
||||
expect(yut.validate(s, 'A', { type: 'AUG_PICK', aug: 'cat' }).ok).toBe(true);
|
||||
expect(yut.view(s, 'A').aug!.select!.forced).toBe('cat');
|
||||
});
|
||||
|
||||
test('혼돈 모드: two picks per selection', () => {
|
||||
const s = yut.setup({ players: ['A', 'B'], options: yut.optionsSchema.parse({ augmented: true, augChaos: true }), rng: SeededRng.fromSeed(seedN(2)), now: 0 });
|
||||
expect(s.aug!.select!.left).toEqual({ '0': 2, '1': 2 });
|
||||
});
|
||||
|
||||
test('a new selection opens when round 6 starts, with 중간 전용 augments', () => {
|
||||
const s = make(2);
|
||||
s.aug!.round = 5;
|
||||
s.turnSide = 1;
|
||||
s.current = 'B';
|
||||
// B ends the round: throw 도, move in → next turn is A in round 6
|
||||
let t = act(s, 'B', { type: 'THROW' }, script('do'));
|
||||
t = act(t, 'B', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(t.aug!.round).toBe(6);
|
||||
expect(t.phase).toBe('aug');
|
||||
expect(t.aug!.select!.tier).toBe('mid');
|
||||
for (const id of t.aug!.select!.offers['0']!) expect(['any', 'mid']).toContain(AUGS[id].tier);
|
||||
});
|
||||
|
||||
test('timeouts pick for whoever is late', () => {
|
||||
const s = yut.setup({ players: ['A', 'B'], options: yut.optionsSchema.parse({ augmented: true }), rng: SeededRng.fromSeed(seedN(2)), now: 0 });
|
||||
expect(s.deadlineAt).toBe(60_000);
|
||||
let t = yut.apply(s, 'A', { type: 'TIMEOUT' }, { rng: SeededRng.fromSeed(seedN(1)), now: 1 }).state;
|
||||
expect(t.aug!.select!.left['0']).toBe(0);
|
||||
expect(t.aug!.select!.left['1']).toBe(1);
|
||||
t = yut.apply(t, 'B', { type: 'TIMEOUT' }, { rng: SeededRng.fromSeed(seedN(1)), now: 2 }).state;
|
||||
expect(t.phase).not.toBe('aug');
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- throwing
|
||||
|
||||
describe('증강 윷놀이: throws', () => {
|
||||
test('개돼지 picks 도 or 개', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'doggy');
|
||||
expect(yut.view(s, 'A').aug!.pickThrow).toBe(true);
|
||||
const t = act(s, 'A', { type: 'THROW', pick: 'do' });
|
||||
expect(t.lastThrow!.result).toBe('do');
|
||||
});
|
||||
|
||||
test('이도류 throws two pairs: two results, 모 becomes 도', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'dual');
|
||||
const t = act(s, 'A', { type: 'THROW' }, new Script([R, R, F, F]));
|
||||
expect(t.lastThrow!.results).toEqual(['do', 'gae']);
|
||||
expect(t.phase).toBe('move');
|
||||
});
|
||||
|
||||
test('과유불급: six sticks, all 배 → out', () => {
|
||||
const s = make(3);
|
||||
give(s, 0, 'excess');
|
||||
expect(s.aug!.sides[0]!.sticks).toBe(6);
|
||||
const t = act(s, 'A', { type: 'THROW' }, new Script([F, F, F, F, F, F]));
|
||||
expect(t.sides[0]!.out).toBe(true);
|
||||
expect(t.current).toBe('B');
|
||||
const u = act(make(2), 'A', { type: 'THROW' }, new Script([F, F, F, F]));
|
||||
expect(u.lastThrow!.result).toBe('yut');
|
||||
});
|
||||
|
||||
test('손은 눈보다 빠르다 throws the chosen result', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'sleight');
|
||||
const t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'sleight'), result: 'mo' });
|
||||
expect(t.pending).toEqual(['mo']);
|
||||
expect(t.phase).toBe('throw'); // 모: one more throw
|
||||
expect(yut.view(t, 'A').aug!.uses.some((u) => u.id === 'sleight')).toBe(false);
|
||||
});
|
||||
|
||||
test('자진모리 장단: every second 걸 adds a 개', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'jajinmori');
|
||||
s.aug!.sides[0]!.augs[0]!.n = 1;
|
||||
const t = act(s, 'A', { type: 'THROW' }, script('geol'));
|
||||
expect(t.pending).toEqual(['geol', 'gae']);
|
||||
});
|
||||
|
||||
test('도베르만: 개 coins become 모', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'doberman');
|
||||
s.aug!.sides[0]!.thrown.gae = 5;
|
||||
let t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'doberman') });
|
||||
expect(t.aug!.sides[0]!.dogCoins).toBe(5);
|
||||
t = act(t, 'A', { type: 'THROW' }, new Script([]));
|
||||
expect(t.lastThrow!.result).toBe('mo');
|
||||
expect(t.aug!.sides[0]!.dogCoins).toBe(3);
|
||||
});
|
||||
|
||||
test('독이 든 성배: three more throws, a 모 that turn is out', () => {
|
||||
const s = make(3);
|
||||
give(s, 0, 'poison');
|
||||
let t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'poison') });
|
||||
expect(t.throwsOwed).toBe(4);
|
||||
t = act(t, 'A', { type: 'THROW' }, script('mo'));
|
||||
expect(t.sides[0]!.out).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- moving & catching
|
||||
|
||||
describe('증강 윷놀이: moves and catches', () => {
|
||||
test('천마군림보 - 달걸음: pieces walk the other way round', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'moonwalk');
|
||||
moving(s, ['gae']);
|
||||
const t = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 0)[0]).toBe(18);
|
||||
});
|
||||
|
||||
test('변환: 선봉장 adds a step to every forward move while it is on the board', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'vanguard');
|
||||
put(s, 0, 0, 3);
|
||||
let t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'vanguard'), piece: 0 });
|
||||
moving(t, ['do']);
|
||||
t = act(t, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 0)[1]).toBe(2);
|
||||
});
|
||||
|
||||
test('평화 협정: no catching either way, the pieces stand together', () => {
|
||||
const s = make();
|
||||
give(s, 1, 'peace');
|
||||
put(s, 1, 0, 3);
|
||||
moving(s, ['geol']);
|
||||
const t = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 1)[0]).toBe(3);
|
||||
expect(nodesOf(t, 0)[0]).toBe(3);
|
||||
expect(yut.view(t, 'A').stacks.filter((st) => st.node === 3)).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('천상의 보호막 saves a stack once', () => {
|
||||
const s = make();
|
||||
give(s, 1, 'shield');
|
||||
put(s, 1, 0, 3);
|
||||
s.sides[1]!.pieces[0]!.shield = true;
|
||||
moving(s, ['geol', 'geol']);
|
||||
let t = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 1)[0]).toBe(3);
|
||||
expect(t.phase).toBe('move'); // nothing caught → no bonus throw
|
||||
t = act(t, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 1)[0]).toBe('home');
|
||||
});
|
||||
|
||||
test('프랜드 실드: a caught stack loses only one piece', () => {
|
||||
const s = make();
|
||||
give(s, 1, 'friendshield');
|
||||
put(s, 1, 0, 3);
|
||||
put(s, 1, 1, 3);
|
||||
put(s, 1, 2, 3);
|
||||
moving(s, ['geol']);
|
||||
const t = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 1).filter((n) => n === 3)).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('카니발리즘: landing on my own piece catches it and throws again', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'cannibal');
|
||||
put(s, 0, 0, 3);
|
||||
moving(s, ['geol']);
|
||||
const t = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 0).filter((n) => n === 3)).toHaveLength(1);
|
||||
expect(t.phase).toBe('throw');
|
||||
});
|
||||
|
||||
test('히히 똥!: other pieces stop on the poop', () => {
|
||||
const s = make();
|
||||
s.aug!.objs.push({ kind: 'poop', node: 2, owner: 1 });
|
||||
moving(s, ['yut']);
|
||||
const t = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 0)[0]).toBe(2);
|
||||
});
|
||||
|
||||
test('말이오? 파티: 해골 catches, 선물 moves on, the owner is immune to its traps', () => {
|
||||
const s = make();
|
||||
s.aug!.objs.push({ kind: 'skull', node: 3, owner: 1 }, { kind: 'gift', node: 2, owner: 1 });
|
||||
moving(s, ['geol', 'gae']);
|
||||
let t = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 0)[0]).toBe('home');
|
||||
t = act(t, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(nodesOf(t, 0)[0]).toBe(4);
|
||||
});
|
||||
|
||||
test('변환: 도깨비 steps once a turn without throwing', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'dokkaebi');
|
||||
put(s, 0, 0, 3, [1, 2, 3]);
|
||||
let t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'dokkaebi'), piece: 0 });
|
||||
const sp = yut.view(t, 'A').aug!.specials;
|
||||
expect(sp.map((m) => m.to).sort()).toEqual([2, 4]);
|
||||
t = act(t, 'A', { type: 'SPECIAL', piece: 0, to: 4 });
|
||||
expect(nodesOf(t, 0)[0]).toBe(4);
|
||||
expect(yut.view(t, 'A').aug!.specials).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('변환: 포 jumps over one piece along a line', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'cannon');
|
||||
put(s, 0, 0, 1);
|
||||
put(s, 1, 0, 2);
|
||||
put(s, 1, 1, 4);
|
||||
const t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'cannon'), piece: 0 });
|
||||
const tos = yut.view(t, 'A').aug!.specials.map((m) => m.to);
|
||||
expect(tos).toContain(3);
|
||||
expect(tos).toContain(4); // catch beyond the screen
|
||||
expect(tos).not.toContain(5);
|
||||
const u = act(t, 'A', { type: 'SPECIAL', piece: 0, to: 4 });
|
||||
expect(nodesOf(u, 1)[1]).toBe('home');
|
||||
});
|
||||
|
||||
test('변환: 폰 walks one step on every throw', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'pawn');
|
||||
let t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'pawn'), piece: 0 });
|
||||
t = act(t, 'A', { type: 'THROW' }, script('gae'));
|
||||
expect(nodesOf(t, 0)[0]).toBe(1);
|
||||
expect(yut.view(t, 'A').legalMoves!.every((m) => m.from === 'home')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- abilities & instants
|
||||
|
||||
describe('증강 윷놀이: abilities and instant effects', () => {
|
||||
test('8톤 트럭 runs straight to the corner, catching on the way, and ends the turn', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'truck');
|
||||
put(s, 0, 0, 1);
|
||||
put(s, 0, 1, 1);
|
||||
put(s, 1, 0, 3);
|
||||
const t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'truck'), piece: 0 });
|
||||
expect(nodesOf(t, 0).slice(0, 2)).toEqual([5, 5]);
|
||||
expect(nodesOf(t, 1)[0]).toBe('home');
|
||||
expect(t.current).toBe('B');
|
||||
});
|
||||
|
||||
test('3단 합체 필살기!!! catches every other stack', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'combo');
|
||||
for (const i of [0, 1, 2]) put(s, 0, i, 7);
|
||||
put(s, 0, 3, 2);
|
||||
put(s, 1, 0, 12);
|
||||
const t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'combo'), piece: 0 });
|
||||
expect(nodesOf(t, 0)).toEqual([7, 7, 7, 'home']);
|
||||
expect(nodesOf(t, 1)[0]).toBe('home');
|
||||
});
|
||||
|
||||
test('바둑 catches between two stacks and throws that many times more', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'baduk');
|
||||
put(s, 0, 0, 1);
|
||||
put(s, 0, 1, 4);
|
||||
put(s, 1, 0, 2);
|
||||
put(s, 1, 1, 3);
|
||||
moving(s, ['do']);
|
||||
const t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'baduk'), node: 1, node2: 4 });
|
||||
expect(nodesOf(t, 1).slice(0, 2)).toEqual(['home', 'home']);
|
||||
expect(t.phase).toBe('throw');
|
||||
expect(t.throwsOwed).toBe(2);
|
||||
});
|
||||
|
||||
test('명사수 uses a throw and shoots the node when my next turn starts', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'sniper');
|
||||
put(s, 1, 0, 9);
|
||||
let t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'sniper'), node: 9 });
|
||||
expect(t.current).toBe('B'); // that was the only throw
|
||||
expect(yut.view(t, 'B').aug!.objs).toContainEqual({ kind: 'mark', node: 9, owner: 0 });
|
||||
t = act(t, 'B', { type: 'THROW' }, script('do'));
|
||||
t = act(t, 'B', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(t.current).toBe('A');
|
||||
expect(nodesOf(t, 1)[0]).toBe('home');
|
||||
expect(t.aug!.objs).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('알까기 knocks a piece off the board', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'alkkagi');
|
||||
put(s, 0, 0, 2);
|
||||
put(s, 1, 0, 1);
|
||||
// straight down from 개 (2) onto 도 (1), hard: 도 flies off the bottom-right edge
|
||||
const t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'alkkagi'), piece: 0, angle: 90, power: 100 });
|
||||
expect(nodesOf(t, 1)[0]).toBe('home');
|
||||
expect(t.aug!.fx.some((f) => f.kind === 'flick' && f.bodies!.length >= 2)).toBe(true);
|
||||
expect(t.current).toBe('B');
|
||||
});
|
||||
|
||||
test('나만 아니면 돼~ wipes the board pieces of another player', () => {
|
||||
const s = make(3);
|
||||
put(s, 1, 0, 4);
|
||||
put(s, 2, 0, 6);
|
||||
give(s, 0, 'notme', new Script([0.1]));
|
||||
expect(nodesOf(s, 1)[0]).toBe('home');
|
||||
expect(nodesOf(s, 2)[0]).toBe(6);
|
||||
});
|
||||
|
||||
test('크고 빨간 버튼 clears both diagonals (own pieces too), not the corners', () => {
|
||||
const s = make();
|
||||
put(s, 0, 0, 22);
|
||||
put(s, 1, 0, 26);
|
||||
put(s, 1, 1, 5);
|
||||
give(s, 0, 'bigred');
|
||||
expect(nodesOf(s, 0)[0]).toBe('home');
|
||||
expect(nodesOf(s, 1).slice(0, 2)).toEqual(['home', 5]);
|
||||
});
|
||||
|
||||
test('거머리 gives a piece and shares the winner’s rank', () => {
|
||||
const s = make(3, { ranking: 'all' });
|
||||
give(s, 0, 'leech');
|
||||
expect(s.phase).toBe('prompt');
|
||||
let t = act(s, 'A', { type: 'AUG_ANSWER', choice: 2 });
|
||||
expect(t.sides[0]!.pieces).toHaveLength(3);
|
||||
expect(t.sides[2]!.pieces).toHaveLength(5);
|
||||
expect(t.phase).toBe('throw');
|
||||
// C brings everything home but one piece, then finishes it
|
||||
for (const p of t.sides[2]!.pieces) Object.assign(p, { status: 'done', node: null, trail: [] });
|
||||
put(t, 2, 0, 19);
|
||||
Object.assign(t, { turnSide: 2, current: 'C' });
|
||||
moving(t, ['gae']);
|
||||
t = act(t, 'C', { type: 'MOVE', throwIndex: 0, from: 19 });
|
||||
expect(t.sides[2]!.finishedRank).toBe(1);
|
||||
expect(t.sides[0]!.finishedRank).toBe(1);
|
||||
});
|
||||
|
||||
test('나 누구게? hides colours until everyone guessed; a wrong guess skips a turn', () => {
|
||||
const s = make(3);
|
||||
put(s, 1, 0, 4);
|
||||
give(s, 0, 'whoami');
|
||||
expect(s.phase).toBe('prompt');
|
||||
const vb = yut.view(s, 'B');
|
||||
expect(vb.aug!.hidden).toBe(true);
|
||||
expect(vb.mySide).toBe(null);
|
||||
expect(vb.stacks.every((st) => st.side === -1)).toBe(true);
|
||||
expect(JSON.stringify(vb.sides.map((x) => x.members))).toBe('[[],[],[]]');
|
||||
let t = act(s, 'B', { type: 'AUG_ANSWER', choice: 1 });
|
||||
t = act(t, 'C', { type: 'AUG_ANSWER', choice: 0 });
|
||||
expect(t.aug!.hidden).toBe(false);
|
||||
expect(t.aug!.sides[1]!.skip).toBe(0);
|
||||
expect(t.aug!.sides[2]!.skip).toBe(1);
|
||||
});
|
||||
|
||||
test('내려: the owner votes twice; the most votes skips a turn', () => {
|
||||
const s = make(3);
|
||||
give(s, 0, 'getoff');
|
||||
let t = act(s, 'A', { type: 'AUG_ANSWER', choice: 2 });
|
||||
t = act(t, 'B', { type: 'AUG_ANSWER', choice: 0 });
|
||||
t = act(t, 'C', { type: 'AUG_ANSWER', choice: 0 });
|
||||
expect(t.aug!.sides[0]!.skip).toBe(1);
|
||||
expect(t.aug!.sides[2]!.skip).toBe(1);
|
||||
});
|
||||
|
||||
test('게임 접어라: the folded half lands on the other half and catches there', () => {
|
||||
const s = make();
|
||||
put(s, 0, 0, 11); // left side
|
||||
put(s, 1, 0, 4); // right side, mirror of 11
|
||||
give(s, 0, 'fold');
|
||||
const t = act(s, 'A', { type: 'AUG_ANSWER', choice: 0 });
|
||||
expect(nodesOf(t, 0)[0]).toBe(4);
|
||||
expect(nodesOf(t, 1)[0]).toBe('home');
|
||||
});
|
||||
|
||||
test('돌려돌려 돌림판 turns every piece; one re-spin', () => {
|
||||
const s = make();
|
||||
put(s, 0, 0, 1);
|
||||
give(s, 0, 'roulette', new Script([0.1]));
|
||||
expect(s.aug!.prompts[0]!.spin).toBe(1);
|
||||
let t = act(s, 'A', { type: 'AUG_ANSWER', choice: 1 }, new Script([0.9]));
|
||||
expect(t.aug!.prompts[0]!.spin).toBe(3);
|
||||
expect(yut.view(t, 'A').aug!.prompt!.canRespin).toBe(false);
|
||||
t = act(t, 'A', { type: 'AUG_ANSWER', choice: 0 });
|
||||
expect(nodesOf(t, 0)[0]).toBe(6); // three quarter turns clockwise: 도 → 날도 → 찌도 → 뒷도
|
||||
});
|
||||
|
||||
test('잠깐! freezes the furthest enemy stack for two rounds', () => {
|
||||
const s = make();
|
||||
put(s, 1, 0, 3);
|
||||
put(s, 1, 1, 17);
|
||||
give(s, 0, 'wait');
|
||||
expect(s.sides[1]!.pieces[1]!.frozenUntil).toBe(3);
|
||||
expect(yut.view(s, 'B').stacks.find((st) => st.node === 17)!.frozen).toBe(true);
|
||||
});
|
||||
|
||||
test('안개 hides enemy stacks far from my pieces', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'fog');
|
||||
put(s, 0, 0, 3);
|
||||
put(s, 1, 0, 4);
|
||||
put(s, 1, 1, 12);
|
||||
const t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'fog') });
|
||||
const own = yut.view(t, 'A').stacks.map((st) => st.node);
|
||||
expect(own).toEqual(expect.arrayContaining([3, 4, 12]));
|
||||
// B sees only near its own pieces (4 and 12): 3 is next to 4, so visible
|
||||
put(t, 0, 1, 20);
|
||||
const vb = yut.view(t, 'B');
|
||||
expect(vb.aug!.fogged).toBe(true);
|
||||
expect(vb.stacks.some((st) => st.node === 20)).toBe(false);
|
||||
expect(vb.stacks.some((st) => st.node === 3)).toBe(true);
|
||||
});
|
||||
|
||||
test('지뢰 is only visible to its owner', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'mine');
|
||||
put(s, 0, 0, 6);
|
||||
const t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'mine'), node: 6 });
|
||||
expect(yut.view(t, 'A').aug!.objs.some((o) => o.kind === 'mine')).toBe(true);
|
||||
expect(yut.view(t, 'B').aug!.objs.some((o) => o.kind === 'mine')).toBe(false);
|
||||
expect(yut.view(t, null).aug!.objs.some((o) => o.kind === 'mine')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- winning & going out
|
||||
|
||||
describe('증강 윷놀이: special wins and ranks', () => {
|
||||
test('중전마마 wins after 12 throws', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'queen');
|
||||
expect(nodesOf(s, 0)).toContain(10);
|
||||
s.aug!.sides[0]!.augs[0]!.n = 11;
|
||||
const t = act(s, 'A', { type: 'THROW' }, script('gae'));
|
||||
expect(t.sides[0]!.finishedRank).toBe(1);
|
||||
expect(t.phase).toBe('finished');
|
||||
expect(t.final!.ranking[0]!.reason).toBe('시작 변환: 중전마마');
|
||||
expect(yut.result(t)!.scoreText!.A).toContain('중전마마');
|
||||
});
|
||||
|
||||
test('김첨지 home within six turns wins', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'kim');
|
||||
const kim = s.sides[0]!.pieces.find((p) => p.kind === 'kim')!;
|
||||
put(s, 0, kim.id, 19);
|
||||
moving(s, ['gae']);
|
||||
const t = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 19, piece: kim.id });
|
||||
expect(t.final!.ranking[0]!.reason).toBe('김첨지 완주');
|
||||
});
|
||||
|
||||
test('동메달도 잘한 거야: 3rd place at once', () => {
|
||||
const s = make(4, { ranking: 'all' });
|
||||
give(s, 1, 'bronze');
|
||||
expect(s.sides[1]!.finishedRank).toBe(3);
|
||||
expect(s.phase).not.toBe('finished');
|
||||
});
|
||||
|
||||
test('라스트 댄스 doubles moves and goes out at the end of the turn', () => {
|
||||
const s = make(3);
|
||||
give(s, 0, 'lastdance');
|
||||
let t = act(s, 'A', { type: 'AUG_USE', uid: uidOf(s, 0, 'lastdance') });
|
||||
t = act(t, 'A', { type: 'THROW' }, script('gae'));
|
||||
t = act(t, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(t.sides[0]!.out).toBe(true);
|
||||
expect(t.current).toBe('B');
|
||||
});
|
||||
|
||||
test('메아리의 형상: everyone plays two turns in a row', () => {
|
||||
const s = make();
|
||||
give(s, 0, 'echo');
|
||||
let t = act(s, 'A', { type: 'THROW' }, script('do'));
|
||||
t = act(t, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(t.current).toBe('B');
|
||||
s.aug!.echo!.on = true;
|
||||
let u = act(s, 'A', { type: 'THROW' }, script('do'));
|
||||
u = act(u, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(u.current).toBe('A');
|
||||
u = act(u, 'A', { type: 'THROW' }, script('do'));
|
||||
u = act(u, 'A', { type: 'MOVE', throwIndex: 0, from: 1 });
|
||||
expect(u.current).toBe('B');
|
||||
});
|
||||
|
||||
test('나에게 윷놀이는 "살인"이다: catches cost health, 0 is out', () => {
|
||||
const s = make(3);
|
||||
give(s, 0, 'murder');
|
||||
s.aug!.sides[1]!.hp = 1;
|
||||
put(s, 1, 0, 3);
|
||||
moving(s, ['geol']);
|
||||
const t = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(t.sides[1]!.out).toBe(true);
|
||||
});
|
||||
|
||||
test('취~소 brings special winners back into the game', () => {
|
||||
const s = make(3, { ranking: 'all' });
|
||||
give(s, 1, 'catlover');
|
||||
give(s, 2, 'cat');
|
||||
// catlover won at once
|
||||
expect(s.sides[1]!.finishedRank).toBe(null); // checked after the selection / next action
|
||||
let t = act(s, 'A', { type: 'THROW' }, script('do'));
|
||||
expect(t.sides[1]!.finishedRank).toBe(1);
|
||||
give(t, 0, 'cancel');
|
||||
expect(t.sides[1]!.finishedRank).toBe(null);
|
||||
expect(t.aug!.winsOff).toBe(true);
|
||||
});
|
||||
|
||||
test('계획대로: a correct prediction wins alone', () => {
|
||||
const s = make(2);
|
||||
give(s, 1, 'plan');
|
||||
let t = act(s, 'B', { type: 'AUG_ANSWER', choice: [0, 1] });
|
||||
for (const p of t.sides[0]!.pieces) Object.assign(p, { status: 'done', node: null, trail: [] });
|
||||
put(t, 0, 0, 19);
|
||||
moving(t, ['gae']);
|
||||
t = act(t, 'A', { type: 'MOVE', throwIndex: 0, from: 19 });
|
||||
expect(t.phase).toBe('finished');
|
||||
expect(t.final!.winners).toEqual(['B']);
|
||||
expect(t.final!.summary).toContain('계획대로');
|
||||
});
|
||||
|
||||
test('승부다!: the challenged side must bring a piece home within 3 turns', () => {
|
||||
const s = make(3);
|
||||
give(s, 0, 'duel');
|
||||
let t = act(s, 'A', { type: 'AUG_ANSWER', choice: 1 });
|
||||
t.aug!.sides[0]!.augs[0]!.n = 1;
|
||||
Object.assign(t, { turnSide: 1, current: 'B' });
|
||||
t = act(t, 'B', { type: 'THROW' }, script('do'));
|
||||
t = act(t, 'B', { type: 'MOVE', throwIndex: 0, from: 'home' });
|
||||
expect(t.sides[1]!.out).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------- whole games
|
||||
|
||||
describe('증강 윷놀이: whole games', () => {
|
||||
test.each(Array.from({ length: playoutSeeds(60) }, (_, i) => i))('random playout %i', (i) => {
|
||||
const n = 2 + (i % 3);
|
||||
const players = PLAYERS.slice(0, n);
|
||||
const options = yut.optionsSchema.parse({
|
||||
augmented: true,
|
||||
augRounds: (['standard', 'quick', 'many'] as const)[i % 3],
|
||||
augChaos: i % 4 === 0,
|
||||
augOffers: 4,
|
||||
nakPercent: i % 5 === 0 ? 5 : 0,
|
||||
stacking: i % 6 === 0 ? 'choose' : 'always',
|
||||
ranking: i % 2 ? 'all' : 'first',
|
||||
});
|
||||
const r = randomPlayout(yut, {
|
||||
players,
|
||||
options,
|
||||
seed: seedN(1000 + i),
|
||||
maxSteps: 6000,
|
||||
maxApplyMs: 50,
|
||||
invariant: (st) => {
|
||||
const s = st as YutState;
|
||||
for (const p of [...players, null]) yut.view(s, p);
|
||||
for (const x of s.sides) {
|
||||
expect(x.out && x.finishedRank !== null).toBe(false);
|
||||
if (x.out || x.finishedRank !== null) expect(x.pieces.some((p) => p.status === 'board')).toBe(false);
|
||||
}
|
||||
if (s.phase === 'throw' || s.phase === 'move') expect(s.sides[s.turnSide]!.out || s.sides[s.turnSide]!.finishedRank !== null).toBe(false);
|
||||
},
|
||||
});
|
||||
expect(r.finished).toBe(true);
|
||||
});
|
||||
|
||||
test('computers finish 증강 games without getting stuck', () => {
|
||||
for (let g = 0; g < playoutSeeds(30); g++) {
|
||||
const n = 2 + (g % 3);
|
||||
const players = ['bot1', 'bot2', 'bot3', 'H'].slice(0, n);
|
||||
const r = botPlayout(yut, { players, options: yut.optionsSchema.parse({ augmented: true, augChaos: g % 3 === 0 }), seed: seedN(g + 7), isBot: (p) => p.startsWith('bot') });
|
||||
expect(r.finished).toBe(true);
|
||||
expect(r.botTimeouts).toBe(0);
|
||||
}
|
||||
});
|
||||
|
||||
test('a computer picks an augment and answers prompts', () => {
|
||||
const s = yut.setup({ players: ['bot', 'H'], options: yut.optionsSchema.parse({ augmented: true }), rng: SeededRng.fromSeed(seedN(2)), now: 0 });
|
||||
const a = decideBotAction(yut, s, 'bot', { now: 1, random: () => 0.3 });
|
||||
expect(a).toMatchObject({ type: 'AUG_PICK' });
|
||||
});
|
||||
});
|
||||
3085
packages/games/src/yut/aug.ts
Normal file
3085
packages/games/src/yut/aug.ts
Normal file
File diff suppressed because it is too large
Load Diff
156
packages/games/src/yut/augments.ts
Normal file
156
packages/games/src/yut/augments.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
/**
|
||||
* 증강 윷놀이 증강 목록 (docs/games/yut-augmented.md). Pure data shared by the rules, the options screen and the board.
|
||||
* Augments are based on the Steam game 「증강 윷놀이」(어수룩 게임즈, 2026); `custom` ones are this site's own.
|
||||
*/
|
||||
|
||||
/** When an augment can be offered: any selection, or only the first / middle / last one. */
|
||||
export type AugTier = 'any' | 'start' | 'mid' | 'final';
|
||||
/** How it works: passive rule, effect right when picked, a button to use, or a win condition. */
|
||||
export type AugKind = 'passive' | 'instant' | 'active' | 'win';
|
||||
|
||||
export interface AugInfo {
|
||||
id: AugId;
|
||||
name: string;
|
||||
tier: AugTier;
|
||||
kind: AugKind;
|
||||
/** Usable once (the slot gets a "사용함" stamp after). */
|
||||
once?: boolean;
|
||||
/** Using it ends the turn, so it can only be used before the first throw of a turn. */
|
||||
wholeTurn?: boolean;
|
||||
/** Has a special win (or 3rd place) condition; [취~소] turns these off. */
|
||||
win?: boolean;
|
||||
/** This site's own augment (not in the original game). */
|
||||
custom?: boolean;
|
||||
/** One or two plain sentences (해요체). */
|
||||
text: string;
|
||||
/** Extra rule details for the rules sheet. */
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export const AUG_IDS = [
|
||||
// 범용
|
||||
'truck', 'combo', 'chosen', 'fold', 'cat', 'excess', 'doggy', 'leech', 'whoami', 'notme', 'getoff', 'doberman',
|
||||
'roulette', 'sniper', 'detective', 'moordo', 'baduk', 'delivery', 'dokkaebi', 'vanguard', 'cannon', 'pawn', 'four',
|
||||
'ox', 'sleight', 'timetravel', 'score', 'fog', 'alkkagi', 'catlover', 'fisherman', 'illusion', 'throwyut', 'dual',
|
||||
'objection', 'jajinmori', 'moonwalk', 'shield', 'bigred', 'friendshield', 'sacrifice', 'poop',
|
||||
// 시작 전용
|
||||
'equiv', 'party', 'speedrun', 'kim', 'queen', 'bear', 'piggyback', 'burden', 'alone',
|
||||
// 중간 전용
|
||||
'triple7', 'nofriends', 'summon', 'coup', 'treason', 'wait', 'peace',
|
||||
// 마무리 전용
|
||||
'plan', 'murder', 'necro', 'poison', 'bronze', 'lastdance', 'echo', 'marathon', 'duel', 'comeback', 'domain', 'cancel',
|
||||
'cannibal',
|
||||
// 이 사이트 추가
|
||||
'teleport', 'shortcut', 'turtle', 'revenge', 'thief', 'mine', 'tiger', 'twins', 'swap', 'storm',
|
||||
] as const;
|
||||
export type AugId = (typeof AUG_IDS)[number];
|
||||
|
||||
const L: Omit<AugInfo, 'id'>[] = [
|
||||
// ---------------------------------------------------------------- 범용
|
||||
{ name: '8톤 트럭', tier: 'any', kind: 'active', once: true, wholeTurn: true, text: '말이 2개 이상 업힌 내 말뭉치 하나가 꺾이는 곳까지 앞으로 쭉 달려요. 지나가는 길의 다른 편 말은 모두 잡아요.', note: '차례를 다 써요(던지기 전에만). 모서리·방에 서 있었다면 지름길로 출발하고, 모서리·참먹이에 닿으면 멈춰요.' },
|
||||
{ name: '3단 합체 필살기!!!', tier: 'any', kind: 'active', once: true, wholeTurn: true, text: '말이 3개 이상 업힌 내 말뭉치를 골라요. 그 말뭉치를 뺀 판 위의 모든 말뭉치를 잡아요(내 다른 말도요).', note: '차례를 다 써요(던지기 전에만).' },
|
||||
{ name: '간택', tier: 'any', kind: 'passive', text: '이제 모든 사람은 증강 후보에 고양이가 나오면 꼭 고양이를 골라야 해요.' },
|
||||
{ name: '게임 접어라', tier: 'any', kind: 'instant', text: '윷판을 반으로 접어요. 접는 방향을 고르면, 접히는 쪽 말이 반대쪽 같은 자리로 옮겨져요.', note: '옮겨진 말이 다른 편 말 위에 떨어지면 그 말을 잡아요. 내 말끼리는 업혀요.' },
|
||||
{ name: '고양이', tier: 'any', kind: 'passive', text: '아무 능력이 없어요. 왜 있냐고요? 귀엽잖아요.' },
|
||||
{ name: '과유불급', tier: 'any', kind: 'passive', text: '윷가락 6개로 던져요. 배가 0개면 모, 4~5개면 윷, 6개가 모두 배면 탈락해요.', note: '배가 1~3개면 도·개·걸이에요. 이 증강의 윷가락은 앞뒤가 반반으로 나와요.' },
|
||||
{ name: '개돼지', tier: 'any', kind: 'passive', text: '던지면 도와 개만 나오지만, 둘 중 하나를 골라서 낼 수 있어요.' },
|
||||
{ name: '거머리', tier: 'any', kind: 'instant', text: '다른 사람 한 명에게 내 말 1개를 줘요. 그 사람이 이기면 나도 같은 순위로 이기고, 탈락하면 나도 탈락해요.', note: '대기 중인 말을 먼저 줘요. 나도 따로 이길 수 있어요.' },
|
||||
{ name: '나 누구게?', tier: 'any', kind: 'instant', text: '잠깐 모든 말의 색이 가려져요. 다른 사람은 자기 색을 맞혀야 하고, 틀리면 차례를 한 번 건너뛰어요.' },
|
||||
{ name: '나만 아니면 돼~', tier: 'any', kind: 'instant', text: '다른 사람 중 무작위로 한 명의 판 위 말을 모두 잡아요.' },
|
||||
{ name: '내려', tier: 'any', kind: 'instant', text: '모두 투표해요. 표를 가장 많이 받은 사람은 차례를 한 번 건너뛰어요. 나는 2표를 행사해요.', note: '자기 자신에게는 투표할 수 없어요. 동점이면 동점인 사람이 모두 건너뛰어요.' },
|
||||
{ name: '도베르만', tier: 'any', kind: 'active', once: true, text: '이번 게임에서 낸 개 수만큼 개 코인을 받아요. 그 뒤로는 던질 때마다 개 코인 2개를 써서 모가 나와요.', note: '개 코인이 2개보다 적으면 평소처럼 던져요.' },
|
||||
{ name: '돌려돌려 돌림판', tier: 'any', kind: 'instant', text: '판을 돌려 모든 말이 돌아간 자리로 옮겨져요. 결과가 마음에 안 들면 한 번 더 돌릴 수 있어요.' },
|
||||
{ name: '명사수', tier: 'any', kind: 'active', text: '던지기 한 번을 써서 칸 하나를 조준해요. 다음 내 차례가 시작될 때 그 칸의 말을 모두 잡아요.', note: '한 차례에 한 번, 조준은 한 곳만 할 수 있어요. 내 말도 잡혀요.' },
|
||||
{ name: '명탐정', tier: 'any', kind: 'instant', text: '증강 하나를 지목해요. 이번 증강 선택에서 다른 사람이 그 증강을 고르면 무효가 돼요.' },
|
||||
{ name: '모 아니면 도', tier: 'any', kind: 'passive', text: '던지면 모 아니면 도만 나와요. 모가 나올 확률은 40%예요.' },
|
||||
{ name: '바둑', tier: 'any', kind: 'active', once: true, text: '한 줄 위에 있는 내 말뭉치 둘 사이의 다른 편 말을 모두 잡고, 잡은 말 수만큼 더 던져요.' },
|
||||
{ name: '배달', tier: 'any', kind: 'instant', text: '증강 하나를 주문해요. 다음 증강 선택 때 그 증강이 내 후보에 꼭 나와요.' },
|
||||
{ name: '변환: 도깨비', tier: 'any', kind: 'active', once: true, text: '내 일반 말 하나를 도깨비로 바꿔요. 도깨비는 내 차례마다 한 번, 던지지 않고 앞이나 뒤로 1칸 갈 수 있어요.' },
|
||||
{ name: '변환: 선봉장', tier: 'any', kind: 'active', once: true, text: '내 일반 말 하나를 선봉장으로 바꿔요. 선봉장이 판 위에 있는 동안 내 말은 앞으로 갈 때마다 1칸 더 가요.' },
|
||||
{ name: '변환: 포', tier: 'any', kind: 'active', once: true, text: '내 판 위 일반 말 하나를 포로 바꿔요. 포는 내 차례마다 한 번, 말이 있는 칸 하나를 넘어 한 줄로 원하는 만큼 갈 수 있어요.', note: '넘은 뒤 처음 만나는 말이 다른 편이면 잡을 수 있어요. 참먹이에는 내려앉지 못해요.' },
|
||||
{ name: '변환: 폰', tier: 'any', kind: 'active', once: true, text: '내 일반 말 하나를 폰으로 바꿔요. 폰은 직접 움직일 수 없지만 내가 던질 때마다 1칸씩 앞으로 가요.' },
|
||||
{ name: '사목', tier: 'any', kind: 'win', win: true, text: '내 말이 한 줄로 이어진 네 칸을 차지하거나, 내 말 4개가 한 말뭉치가 되면 이겨요.' },
|
||||
{ name: '소 뒷걸음질', tier: 'any', kind: 'win', win: true, text: '빽도로 말을 두 번 잡으면 이겨요.' },
|
||||
{ name: '손은 눈보다 빠르다', tier: 'any', kind: 'active', once: true, text: '이번 던지기의 결과를 원하는 대로 골라서 내요.' },
|
||||
{ name: '시간 여행', tier: 'any', kind: 'active', once: true, text: '내 말뭉치 하나를 지나온 칸 중 원하는 곳으로 되돌려요.' },
|
||||
{ name: '악보가 완성되었다!', tier: 'any', kind: 'win', win: true, text: '이번 게임에서 빽도·도·개·걸·윷·모를 모두 한 번 이상 내면 이겨요.', note: '증강을 얻기 전에 낸 것도 세요.' },
|
||||
{ name: '안개', tier: 'any', kind: 'active', once: true, text: '내 차례 두 번이 돌아올 때까지 판에 안개가 껴요. 다른 사람은 자기 말 근처만 볼 수 있어요.' },
|
||||
{ name: '알까기', tier: 'any', kind: 'active', once: true, wholeTurn: true, text: '내 말 하나를 손가락으로 튕겨요. 부딪힌 말이 판 밖으로 나가면 잡혀요.', note: '차례를 다 써요(던지기 전에만). 업힌 말뭉치를 고르면 말 1개만 날아가요. 멈춘 말은 가장 가까운 칸에 서요.' },
|
||||
{ name: '애묘인', tier: 'any', kind: 'win', win: true, text: '누구든 고양이를 고른 사람이 있으면 이겨요.', note: '이미 고른 사람이 있어도 돼요.' },
|
||||
{ name: '어부지리', tier: 'any', kind: 'passive', text: '내 차례가 아닐 때 다른 사람 말이 2개 잡힐 때마다 개를 하나 받아요. 받은 개는 다음 내 차례에 써요.' },
|
||||
{ name: '언제부터 착각한 거지?', tier: 'any', kind: 'instant', text: '다른 사람의 증강 하나를 3라운드 동안 고양이로 바꿔요.', note: '이미 다 쓴 증강은 고를 수 없어요.' },
|
||||
{ name: '윷을 잘 던져봐', tier: 'any', kind: 'active', once: true, text: '윷을 던져 한 사람을 맞혀요. 맞은 사람은 차례를 두 번 건너뛰어요.' },
|
||||
{ name: '이도류', tier: 'any', kind: 'passive', text: '윷가락을 2개씩 두 번 던져서 결과를 두 개 받아요. 모(둘 다 등)는 도로 바뀌어요.', note: '도·개·빽도만 나와서 한 번 더 던지는 일은 없어요.' },
|
||||
{ name: '이의있음!', tier: 'any', kind: 'instant', text: '이번 증강 선택을 없던 걸로 하고 새 후보 중에서 다시 골라요.' },
|
||||
{ name: '자진모리 장단', tier: 'any', kind: 'passive', text: '걸이 두 번 나올 때마다 개를 하나 더 받아요.' },
|
||||
{ name: '천마군림보 - 달걸음', tier: 'any', kind: 'passive', text: '내 말은 모두 반대 방향(시계 방향)으로 돌아요.', note: '참먹이에서 날윷 쪽으로 출발하고, 찌모·뒷모·방에 멈추면 지름길로 꺾어요.' },
|
||||
{ name: '천상의 보호막', tier: 'any', kind: 'active', once: true, text: '내 말뭉치 하나에 보호막을 씌워요. 보호막은 잡힐 때 한 번 막아 줘요.', note: '막아 낸 말은 그 자리에 그대로 남아요.' },
|
||||
{ name: '크고 빨간 버튼', tier: 'any', kind: 'instant', text: '두 대각선 지름길(방 포함, 모서리 제외)에 있는 모든 말을 잡아요. 내 말도요.' },
|
||||
{ name: '프랜드 실드', tier: 'any', kind: 'passive', text: '내 말뭉치가 잡힐 때 말 1개만 잡히고 나머지는 남아요.' },
|
||||
{ name: '희생', tier: 'any', kind: 'active', once: true, text: '판 위의 내 말 하나를 스스로 잡혀요. 판 위의 다른 내 말에 모두 보호막을 씌워요.' },
|
||||
{ name: '히히 똥!', tier: 'any', kind: 'instant', text: '무작위 칸에 똥을 싸요. 다른 사람 말은 지나가다 똥을 밟으면 그 자리에 멈춰요.' },
|
||||
// ---------------------------------------------------------------- 시작 전용
|
||||
{ name: '등가교환', tier: 'start', kind: 'instant', text: '내 말 1개와 윷가락 1개를 빼고 시작해요.', note: '윷가락 3개로는 윷이 나오지 않아요(배 3개는 걸).' },
|
||||
{ name: '말이오? 파티', tier: 'start', kind: 'instant', text: '판에 함정 6개와 선물 4개를 깔아요. 딱 멈춘 말은 잡히거나 옮겨져요. 내가 깐 함정에는 걸리지 않아요.', note: '해골: 잡힘 · 마녀 모자: 뒤로 2칸 · 선물: 앞으로 2칸(누구나).' },
|
||||
{ name: '스겜', tier: 'start', kind: 'instant', text: '모든 사람의 말이 2개가 되고, 내 말은 도와 개 자리에서 시작해요.' },
|
||||
{ name: '시작 변환: 김첨지', tier: 'start', kind: 'instant', win: true, text: '내 말 하나가 김첨지가 돼요. 김첨지가 내 차례 6번 안에 나면 이겨요.', note: '6번이 지나면 보통 말처럼 움직여요.' },
|
||||
{ name: '시작 변환: 중전마마', tier: 'start', kind: 'instant', win: true, text: '내 말 하나가 중전마마가 되어 뒷모(왼쪽 위)에 서요. 내가 12번 던질 때까지 지키면 이기고, 목숨이 다 떨어지면 탈락해요.', note: '중전마마는 날 수 없어요. 목숨은 1개로 시작하고, 다른 말이 날 때마다 1개 늘어요. 잡히면 목숨을 잃고 대기로 돌아가요.' },
|
||||
{ name: '웅녀', tier: 'start', kind: 'instant', win: true, text: '무작위 칸 3곳에 마늘이 놓여요. 내 말이 마늘 칸에 멈춰 3개를 모두 모으면 이겨요.' },
|
||||
{ name: '이리 오너라 업고 놀자', tier: 'start', kind: 'instant', text: '내 말을 모두 업은 채 도 자리에서 시작해요.' },
|
||||
{ name: '짐덩이와 복덩이', tier: 'start', kind: 'instant', text: '내 말 1개와 윷가락 1개를 더하고 시작해요.', note: '윷가락 5개로 던져요. 배가 4~5개면 윷이에요.' },
|
||||
{ name: '천상천하 유아독존', tier: 'start', kind: 'win', win: true, text: '내가 잡아서 판 위에 내 말뭉치 1개만 남으면 이겨요.' },
|
||||
// ---------------------------------------------------------------- 중간 전용
|
||||
{ name: '777', tier: 'mid', kind: 'win', win: true, text: '한 차례 안에 같은 결과가 세 번 나오면 이겨요.' },
|
||||
{ name: '나만 친구 없어', tier: 'mid', kind: 'win', win: true, text: '이 증강을 고른 뒤 다른 모든 사람이 내 말을 한 번씩 잡으면 이겨요.' },
|
||||
{ name: '마신 소환', tier: 'mid', kind: 'instant', win: true, text: '내 일반 말이 모두 광신도가 돼요. 내 차례가 시작될 때 판 위 광신도마다 의식 코인을 1개 받고, 12개를 모으면 이겨요.' },
|
||||
{ name: '무신정변', tier: 'mid', kind: 'win', win: true, text: '이 증강을 고른 뒤 다른 편 말을 4개 잡으면 이겨요.' },
|
||||
{ name: '역모', tier: 'mid', kind: 'passive', text: '나보다 난 말이 많은 사람의 말을 잡으면 한 번 더 던져요.' },
|
||||
{ name: '잠깐!', tier: 'mid', kind: 'instant', text: '다른 사람 말 중 가장 앞선 말뭉치 하나가 2라운드 동안 못 움직여요.' },
|
||||
{ name: '평화 협정', tier: 'mid', kind: 'passive', text: '나는 다른 사람 말을 잡을 수 없고, 다른 사람도 내 말을 잡을 수 없어요. 증강으로 잡는 것도요.', note: '같은 칸에 멈추면 함께 서 있어요.' },
|
||||
// ---------------------------------------------------------------- 마무리 전용
|
||||
{ name: '계획대로', tier: 'final', kind: 'instant', win: true, text: '모든 사람의 최종 순위를 예언해요. 다 맞히면 순위를 없애고 나 혼자 이겨요.' },
|
||||
{ name: '나에게 윷놀이는 "살인"이다', tier: 'final', kind: 'instant', text: '모든 사람에게 체력 3이 생겨요. 내가 말을 잡을 때마다 잡힌 말 수만큼 그 사람 체력이 줄고, 0이 되면 탈락해요.' },
|
||||
{ name: '네크로맨서', tier: 'final', kind: 'active', once: true, text: '탈락한 사람 한 명을 되살려요. 그 사람이 이기면 나도 같은 순위로 이겨요.', note: '기권하거나 나간 사람은 되살릴 수 없어요.' },
|
||||
{ name: '독이 든 성배', tier: 'final', kind: 'active', text: '내 차례에 마시면 던지기 3번을 더 받아요. 마신 차례에 모가 나오면 탈락해요.', note: '한 차례에 한 번 마실 수 있어요.' },
|
||||
{ name: '동메달도 잘한 거야', tier: 'final', kind: 'instant', win: true, text: '바로 3위로 게임을 마쳐요.', note: '3명 이상 남아 있을 때만 후보에 나와요.' },
|
||||
{ name: '라스트 댄스', tier: 'final', kind: 'active', once: true, text: '이번 차례 동안 내 말이 모두 두 배로 움직여요. 차례가 끝나면 탈락해요.', note: '이번 차례에 이기면 탈락하지 않아요.' },
|
||||
{ name: '메아리의 형상', tier: 'final', kind: 'instant', text: '내 차례부터 모든 사람이 차례를 두 번씩 해요.' },
|
||||
{ name: '변환: 마라토너', tier: 'final', kind: 'active', once: true, win: true, text: '대기 중인 내 일반 말 하나를 마라토너로 바꿔요. 마라토너가 나면 이겨요.' },
|
||||
{ name: '승부다!', tier: 'final', kind: 'instant', text: '한 사람을 골라요. 그 사람이 자기 차례 3번 안에 말을 하나도 못 내면 탈락하고, 내면 내가 탈락해요.' },
|
||||
{ name: '역전 찬스', tier: 'final', kind: 'instant', text: '무작위 증강 3개를 받아요.' },
|
||||
{ name: '영역 전개', tier: 'final', kind: 'active', once: true, win: true, text: '판 위 내 말뭉치 하나를 못 움직이게 묶어요. 내 차례가 두 번 돌아올 때까지 살아남으면 이기고, 잡히면 탈락해요.' },
|
||||
{ name: '취~소', tier: 'final', kind: 'instant', text: '모든 특수 승리를 취소해요. 승리 조건 증강은 모두 효과가 없어지고, 특수 승리로 끝낸 사람은 게임으로 돌아와요.' },
|
||||
{ name: '카니발리즘', tier: 'final', kind: 'passive', text: '내 말끼리 업을 수 없는 대신 내 말을 잡을 수 있어요. 내 말을 잡으면 한 번 더 던져요.' },
|
||||
// ---------------------------------------------------------------- 이 사이트 추가
|
||||
{ name: '순간이동', tier: 'any', kind: 'active', once: true, custom: true, text: '내 말뭉치 하나를 다른 내 말뭉치 자리로 옮겨 업어요.' },
|
||||
{ name: '지름길 달인', tier: 'any', kind: 'passive', custom: true, text: '내 말은 모서리와 방을 지나가기만 해도 지름길로 꺾어요.' },
|
||||
{ name: '거북이 등껍질', tier: 'any', kind: 'passive', custom: true, text: '말이 3개 이상 업힌 내 말뭉치는 잡히지 않아요.' },
|
||||
{ name: '복수의 칼날', tier: 'any', kind: 'passive', custom: true, text: '내 말이 잡힐 때마다 다음 내 차례에 한 번 더 던져요.', note: '모아 둘 수 있는 건 2번까지예요.' },
|
||||
{ name: '손버릇', tier: 'any', kind: 'instant', custom: true, text: '다른 사람의 아직 쓰지 않은 증강 하나를 빼앗아 와요.' },
|
||||
{ name: '지뢰 매설', tier: 'any', kind: 'active', once: true, custom: true, text: '내 말이 있는 칸에 지뢰를 몰래 묻어요. 다른 사람 말이 그 칸에 멈추면 잡혀요.', note: '지뢰는 나에게만 보이고, 한 번 터지면 사라져요.' },
|
||||
{ name: '호랑이 기운', tier: 'any', kind: 'passive', custom: true, text: '걸이 나와도 윷·모처럼 한 번 더 던져요.' },
|
||||
{ name: '쌍둥이', tier: 'any', kind: 'active', once: true, custom: true, text: '대기 중인 내 말 하나를 판 위 내 말뭉치에 바로 업혀요.' },
|
||||
{ name: '자리 바꾸기', tier: 'any', kind: 'active', once: true, custom: true, text: '내 말뭉치 하나와 다른 사람 말뭉치 하나의 자리를 맞바꿔요.' },
|
||||
{ name: '회오리', tier: 'mid', kind: 'instant', custom: true, text: '판 위의 모든 말뭉치가 회오리에 휩쓸려 무작위 칸으로 흩어져요.', note: '참먹이에는 떨어지지 않고, 말뭉치끼리 겹치지 않아요.' },
|
||||
];
|
||||
|
||||
export const AUGS: Record<AugId, AugInfo> = Object.fromEntries(AUG_IDS.map((id, i) => [id, { id, ...L[i]! }])) as Record<AugId, AugInfo>;
|
||||
|
||||
if (L.length !== AUG_IDS.length) throw new Error(`augments: ${L.length} entries for ${AUG_IDS.length} ids`);
|
||||
|
||||
export const TIER_KO: Record<AugTier, string> = { any: '범용', start: '시작 전용', mid: '중간 전용', final: '마무리 전용' };
|
||||
export const KIND_KO: Record<AugKind, string> = { passive: '규칙', instant: '즉시', active: '사용', win: '승리 조건' };
|
||||
|
||||
/** 증강 선택 라운드 presets (옵션 `augRounds`). */
|
||||
export const AUG_ROUNDS = { standard: [1, 6, 12], quick: [1, 4, 8], many: [1, 3, 5, 7, 9] } as const;
|
||||
export type AugRoundsKey = keyof typeof AUG_ROUNDS;
|
||||
|
||||
/** Tier of the `i`-th selection out of `n`: the first is 시작, the last 마무리, the rest 중간. */
|
||||
export function selectionTier(i: number, n: number): Exclude<AugTier, 'any'> {
|
||||
if (i === 0) return 'start';
|
||||
if (i === n - 1) return 'final';
|
||||
return 'mid';
|
||||
}
|
||||
|
||||
/** Side colours of 개인전 (mirrors SOLO_NAMES in index.ts) — used in augment texts. */
|
||||
export const COLOR_NAMES = ['빨강', '파랑', '초록', '노랑'] as const;
|
||||
@@ -158,3 +158,78 @@ export function throwProbabilities(p: number, backdo = true): Record<Throw, numb
|
||||
mo: q ** 4,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- geometry (증강 윷놀이)
|
||||
|
||||
/**
|
||||
* Node centres on a 0..100 board (same layout as the screen): 참먹이 bottom-right, 모 top-right, 뒷모 top-left,
|
||||
* 찌모 bottom-left. Used by augments that fold, turn or flick the board.
|
||||
*/
|
||||
export const NODE_POS: readonly (readonly [number, number])[] = (() => {
|
||||
const LO = 8;
|
||||
const HI = 92;
|
||||
const GAP = (HI - LO) / 5;
|
||||
const p: [number, number][] = [];
|
||||
p[0] = [HI, HI];
|
||||
for (let i = 1; i <= 4; i++) p[i] = [HI, HI - GAP * i];
|
||||
p[5] = [HI, LO];
|
||||
for (let i = 6; i <= 9; i++) p[i] = [HI - GAP * (i - 5), LO];
|
||||
p[10] = [LO, LO];
|
||||
for (let i = 11; i <= 14; i++) p[i] = [LO, LO + GAP * (i - 10)];
|
||||
p[15] = [LO, HI];
|
||||
for (let i = 16; i <= 19; i++) p[i] = [LO + GAP * (i - 15), HI];
|
||||
const lerp = (a: [number, number], b: [number, number], t: number): [number, number] => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
|
||||
[20, 21, 22, 23, 24].forEach((n, k) => (p[n] = lerp(p[5]!, p[15]!, (k + 1) / 6)));
|
||||
[25, 26].forEach((n, k) => (p[n] = lerp(p[10]!, p[0]!, (k + 1) / 6)));
|
||||
[27, 28].forEach((n, k) => (p[n] = lerp(p[10]!, p[0]!, (k + 4) / 6)));
|
||||
return p;
|
||||
})();
|
||||
|
||||
/** The six straight lines of the board, end to end (4 sides, 2 diagonals through 방). */
|
||||
export const STRAIGHT_LINES: readonly (readonly NodeId[])[] = [
|
||||
[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],
|
||||
];
|
||||
|
||||
/** Nodes joined by a board line (graph neighbours, both directions). */
|
||||
export const NEIGHBOURS: readonly (readonly NodeId[])[] = (() => {
|
||||
const nb: Set<NodeId>[] = Array.from({ length: NODE_COUNT }, () => new Set<NodeId>());
|
||||
for (const line of STRAIGHT_LINES)
|
||||
for (let i = 0; i + 1 < line.length; i++) {
|
||||
nb[line[i]!]!.add(line[i + 1]!);
|
||||
nb[line[i + 1]!]!.add(line[i]!);
|
||||
}
|
||||
return nb.map((x) => [...x].sort((a, b) => a - b));
|
||||
})();
|
||||
|
||||
/** Node whose centre is `pt` (exact layout match); throws if none. */
|
||||
function nodeAt(pt: readonly [number, number]): NodeId {
|
||||
const i = NODE_POS.findIndex((q) => Math.abs(q[0] - pt[0]) < 1e-6 && Math.abs(q[1] - pt[1]) < 1e-6);
|
||||
if (i < 0) throw new Error(`no node at ${pt}`);
|
||||
return i;
|
||||
}
|
||||
|
||||
const mapNodes = (f: (p: readonly [number, number]) => [number, number]): NodeId[] => NODE_POS.map((p) => nodeAt(f(p)));
|
||||
|
||||
/** Mirror over the 참먹이–뒷모 diagonal: walking the mirrored board forward = walking this one backwards (달걸음). */
|
||||
export const MIRROR_DIAG: readonly NodeId[] = mapNodes(([x, y]) => [y, x]);
|
||||
/** Left ↔ right, top ↔ bottom mirrors and a quarter turn clockwise (as seen on screen). */
|
||||
export const MIRROR_LR: readonly NodeId[] = mapNodes(([x, y]) => [100 - x, y]);
|
||||
export const MIRROR_TB: readonly NodeId[] = mapNodes(([x, y]) => [x, 100 - y]);
|
||||
export const ROTATE_CW: readonly NodeId[] = mapNodes(([x, y]) => [100 - y, x]);
|
||||
|
||||
/** Nodes on the two diagonals, corners excluded (크고 빨간 버튼). */
|
||||
export const DIAGONAL_NODES: readonly NodeId[] = [20, 21, 22, 23, 24, 25, 26, 27, 28];
|
||||
|
||||
/** Result of `k` sticks of which `flats` show 배 (0 = 모, ≥ 4 = 윷); the marked stick alone gives 빽도. */
|
||||
export function throwOfCount(flats: number, markedOnly: boolean, backdo: boolean): Throw {
|
||||
if (flats === 0) return 'mo';
|
||||
if (flats === 1) return backdo && markedOnly ? 'backdo' : 'do';
|
||||
if (flats === 2) return 'gae';
|
||||
if (flats === 3) return 'geol';
|
||||
return 'yut';
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { BotStrategy } from '../bots/types';
|
||||
import { answerRequests, best, pick, playable } from '../bots/policy';
|
||||
import { FLAT_P, GOAL, THROW_STEPS, advance, defaultPrev, remainingDistance, throwProbabilities, type NodeId, type Throw } from './board';
|
||||
import type { YutAction, YutLegalMove, YutView } from './index';
|
||||
import { augBotAction } from './aug-bot';
|
||||
|
||||
const STEP = 3; // points per step of progress per piece
|
||||
const THROWS: Throw[] = ['backdo', 'do', 'gae', 'geol', 'yut', 'mo'];
|
||||
@@ -14,6 +15,10 @@ const THROWS: Throw[] = ['backdo', 'do', 'gae', 'geol', 'yut', 'mo'];
|
||||
export const yutBot: BotStrategy<YutView, YutAction> = ({ view, legal, random }) => {
|
||||
const req = answerRequests(legal);
|
||||
if (req) return req;
|
||||
if (view.aug) {
|
||||
const a = augBotAction(view, legal, random);
|
||||
if (a) return a;
|
||||
}
|
||||
const moves = legal.filter((a) => a.type === 'MOVE') as Extract<YutAction, { type: 'MOVE' }>[];
|
||||
if (!moves.length || !view.legalMoves) return pick(playable(legal), random);
|
||||
|
||||
|
||||
@@ -14,8 +14,24 @@ import {
|
||||
type Sticks,
|
||||
type Throw,
|
||||
} from './board';
|
||||
import { AUGS, AUG_IDS } from './augments';
|
||||
import {
|
||||
augActivePlayers,
|
||||
augApply,
|
||||
augAutoAction,
|
||||
augLegalActions,
|
||||
augMoves,
|
||||
augSetup,
|
||||
augValidate,
|
||||
augView,
|
||||
type AugState,
|
||||
type PieceKind,
|
||||
type YutAugView,
|
||||
} from './aug';
|
||||
|
||||
export * from './board';
|
||||
export type { AugFx, AugObj, AugOwnedView, AugSideView, AugSpecialMove, AugUseOption, PieceKind, YutAugView } from './aug';
|
||||
export { PIECE_KO } from './aug';
|
||||
|
||||
// ---------------------------------------------------------------- options
|
||||
|
||||
@@ -78,23 +94,58 @@ export const yutOptionsSchema = z.object({
|
||||
.union([z.literal(15), z.literal(30), z.literal(60), z.literal(null)])
|
||||
.default(30)
|
||||
.meta({ title: '행동 제한 시간', labels: { 15: '15초', 30: '30초', 60: '60초', null: '무제한' } }),
|
||||
// ---- 증강 윷놀이 (docs/games/yut-augmented.md). 개인전 only.
|
||||
augmented: z.boolean().default(false).meta({ title: '증강 윷놀이' }),
|
||||
augChaos: z.boolean().default(false).meta({ title: '증강: 혼돈 모드(한 번에 2개씩 고름)' }),
|
||||
augRounds: z
|
||||
.enum(['standard', 'quick', 'many'])
|
||||
.default('standard')
|
||||
.meta({ title: '증강: 고르는 라운드', labels: { standard: '1·6·12라운드', quick: '1·4·8라운드', many: '1·3·5·7·9라운드' } }),
|
||||
augOffers: z
|
||||
.union([z.literal(2), z.literal(3), z.literal(4)])
|
||||
.default(3)
|
||||
.meta({ title: '증강: 후보 수', labels: { 2: '2개', 3: '3개', 4: '4개' } }),
|
||||
augOff: z.array(z.enum(AUG_IDS).meta({ labels: Object.fromEntries(AUG_IDS.map((id) => [id, AUGS[id].name])) })).max(AUG_IDS.length).default([]).meta({ title: '증강: 나오지 않게 뺀 증강' }),
|
||||
});
|
||||
export type YutOptions = z.infer<typeof yutOptionsSchema>;
|
||||
|
||||
const THROW_IDS = ['do', 'gae', 'geol', 'yut', 'mo', 'backdo'] as const;
|
||||
const NODE_NO = z.number().int().min(0).max(28);
|
||||
const PIECE_NO = z.number().int().min(0).max(39);
|
||||
|
||||
export const yutActionSchema = z.discriminatedUnion('type', [
|
||||
z.object({ type: z.literal('THROW') }),
|
||||
/** `pick`: 개돼지 (증강) chooses 도 or 개. */
|
||||
z.object({ type: z.literal('THROW'), pick: z.enum(['do', 'gae']).optional() }),
|
||||
z.object({
|
||||
type: z.literal('MOVE'),
|
||||
throwIndex: z.number().int().min(0).max(999),
|
||||
from: z.union([z.literal('home'), z.number().int().min(0).max(28)]),
|
||||
/** Which stack on `from` (any piece id in it) when one node holds several own stacks (`stacking = choose`). */
|
||||
piece: z.number().int().min(0).max(4).optional(),
|
||||
from: z.union([z.literal('home'), NODE_NO]),
|
||||
/**
|
||||
* Which stack on `from` (any piece id in it) when one node holds several own stacks (`stacking = choose`, 증강 special
|
||||
* pieces), or which waiting piece (증강 special pieces).
|
||||
*/
|
||||
piece: PIECE_NO.optional(),
|
||||
/** Take the other road at the starting fork (`forkRule = choose`). */
|
||||
alt: z.boolean().optional(),
|
||||
/** false = do not stack on own pieces there (`stacking = choose`). */
|
||||
stack: z.boolean().optional(),
|
||||
}),
|
||||
z.object({ type: z.literal('CONCEDE') }),
|
||||
// ---- 증강
|
||||
z.object({ type: z.literal('AUG_PICK'), aug: z.enum(AUG_IDS), target: z.enum(AUG_IDS).optional() }),
|
||||
z.object({ type: z.literal('AUG_ANSWER'), choice: z.union([z.number().int().min(0).max(99999), z.array(z.number().int().min(0).max(7)).max(8)]) }),
|
||||
z.object({
|
||||
type: z.literal('AUG_USE'),
|
||||
uid: z.number().int().min(0).max(99999),
|
||||
piece: PIECE_NO.optional(),
|
||||
node: NODE_NO.optional(),
|
||||
node2: NODE_NO.optional(),
|
||||
target: z.number().int().min(0).max(7).optional(),
|
||||
result: z.enum(THROW_IDS).optional(),
|
||||
angle: z.number().int().min(0).max(359).optional(),
|
||||
power: z.number().int().min(1).max(100).optional(),
|
||||
}),
|
||||
z.object({ type: z.literal('SPECIAL'), piece: PIECE_NO, to: z.union([z.literal('goal'), NODE_NO]) }),
|
||||
]);
|
||||
/** Client actions plus the system-only timer action (not in the schema). */
|
||||
export type YutAction = z.infer<typeof yutActionSchema> | { type: 'TIMEOUT' };
|
||||
@@ -118,6 +169,12 @@ export interface Piece {
|
||||
* that stack. Absent = the node's ordinary stack. Pieces on one node with the same key move together.
|
||||
*/
|
||||
group?: number;
|
||||
/** 증강: special piece kind (absent = ordinary piece). */
|
||||
kind?: PieceKind;
|
||||
/** 증강: survives one catch. */
|
||||
shield?: boolean;
|
||||
/** 증강: can't move before this round (잠깐!, 영역 전개). */
|
||||
frozenUntil?: number;
|
||||
}
|
||||
|
||||
export interface SideState {
|
||||
@@ -162,6 +219,8 @@ export interface YutRankEntry {
|
||||
side: SideId;
|
||||
finishedPieces: number;
|
||||
remainingDistance: number;
|
||||
/** 증강: why this rank (전원 완주, an augment, 탈락 …). */
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface YutResult {
|
||||
@@ -179,12 +238,14 @@ export interface YutState {
|
||||
sides: SideState[];
|
||||
turnSide: SideId;
|
||||
current: PlayerId;
|
||||
phase: 'throw' | 'move' | 'finished';
|
||||
/** 증강 adds `aug` (everyone picks an augment) and `prompt` (someone answers an augment's question). */
|
||||
phase: 'throw' | 'move' | 'finished' | 'aug' | 'prompt';
|
||||
/** Throws still owed this turn (윷/모/잡기 bonus). 1 when the throw phase starts. */
|
||||
throwsOwed: number;
|
||||
/** Results collected this turn, in throw order. */
|
||||
pending: Throw[];
|
||||
lastThrow: { no: number; player: PlayerId; sticks: Sticks | null; result: Throw | 'nak' } | null;
|
||||
/** `sticks` has 4 entries in plain games (증강 may use 2~7); `results`: 이도류 gives two; `note`: which augment decided it. */
|
||||
lastThrow: { no: number; player: PlayerId; sticks: Sticks | boolean[] | null; result: Throw | 'nak'; results?: Throw[]; note?: string } | null;
|
||||
lastMove: YutMoveInfo | null;
|
||||
throwNo: number;
|
||||
moveNo: number;
|
||||
@@ -197,6 +258,8 @@ export interface YutState {
|
||||
nextRank: number;
|
||||
outCount: number;
|
||||
final: YutResult | null;
|
||||
/** 증강 윷놀이 only. */
|
||||
aug?: AugState;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- views
|
||||
@@ -231,6 +294,8 @@ export interface YutSideView {
|
||||
onBoard: number;
|
||||
done: number;
|
||||
remaining: number;
|
||||
/** 증강: pieces of this side (augments change it). */
|
||||
total?: number;
|
||||
}
|
||||
|
||||
export interface YutStackView {
|
||||
@@ -239,6 +304,10 @@ export interface YutStackView {
|
||||
count: number;
|
||||
/** Lowest piece id of the stack, only when one node holds several stacks of this side apart (`stacking = choose`). */
|
||||
piece?: number;
|
||||
/** 증강 */
|
||||
kind?: PieceKind;
|
||||
shield?: boolean;
|
||||
frozen?: boolean;
|
||||
}
|
||||
|
||||
export interface YutView {
|
||||
@@ -265,6 +334,8 @@ export interface YutView {
|
||||
log: GameEvent[];
|
||||
stats: YutStats;
|
||||
result: YutResult | null;
|
||||
/** 증강 윷놀이 only. */
|
||||
aug?: YutAugView;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
@@ -284,7 +355,8 @@ export function playerRange(o: Pick<YutOptions, 'mode'>): { min: number; max: nu
|
||||
}
|
||||
|
||||
/** Player-count check that `playersFor` cannot express (팀전은 짝수만). */
|
||||
export function playerCountError(o: Pick<YutOptions, 'mode'>, n: number): string | null {
|
||||
export function playerCountError(o: Pick<YutOptions, 'mode'> & { augmented?: boolean }, n: number): string | null {
|
||||
if (o.mode === 'team' && o.augmented) return '증강 윷놀이는 개인전(2~4명)으로만 할 수 있어요.';
|
||||
if (o.mode === 'team') return n === 4 || n === 6 || n === 8 ? null : '팀전은 4명, 6명, 8명(짝수)으로만 할 수 있어요.';
|
||||
return n >= 2 && n <= 4 ? null : '개인전은 2~4명이 할 수 있어요.';
|
||||
}
|
||||
@@ -788,6 +860,11 @@ function refreshDeadline(s: YutState, now: number): void {
|
||||
s.deadlineAt = null;
|
||||
return;
|
||||
}
|
||||
if (s.phase === 'aug') {
|
||||
// everyone picks at once: a longer, shared clock (reading three cards takes a while)
|
||||
s.deadlineAt = now + Math.max(30, s.options.turnSeconds * 2) * 1000;
|
||||
return;
|
||||
}
|
||||
const away = (s.timeouts[s.current] ?? 0) >= AWAY_AFTER;
|
||||
s.deadlineAt = now + (away ? AWAY_MS : s.options.turnSeconds * 1000);
|
||||
}
|
||||
@@ -854,7 +931,11 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
outCount: 0,
|
||||
final: null,
|
||||
};
|
||||
startTurn(s, rng.int(nSides), []);
|
||||
if (options.augmented) {
|
||||
s.turnSide = rng.int(nSides);
|
||||
s.current = s.sides[s.turnSide]!.members[0]!;
|
||||
augSetup(s, rng, []);
|
||||
} else startTurn(s, rng.int(nSides), []);
|
||||
refreshDeadline(s, now);
|
||||
return s;
|
||||
},
|
||||
@@ -869,6 +950,9 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
if (side.finishedRank !== null) return fail('이미 말을 모두 냈어요.');
|
||||
return ok;
|
||||
}
|
||||
if (s.aug) return augValidate(s, actor, a);
|
||||
if (a.type === 'AUG_PICK' || a.type === 'AUG_ANSWER' || a.type === 'AUG_USE' || a.type === 'SPECIAL') return fail('증강 윷놀이에서만 쓸 수 있어요.');
|
||||
if (a.type === 'THROW' && a.pick) return fail('이 방은 결과를 고를 수 없어요.');
|
||||
if (actor !== s.current) return fail('지금은 다른 사람 차례예요.');
|
||||
switch (a.type) {
|
||||
case 'TIMEOUT':
|
||||
@@ -881,6 +965,7 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
const t = s.pending[a.throwIndex];
|
||||
if (!t) return fail('그 윷 결과는 없어요.');
|
||||
const o = s.options;
|
||||
if (a.from === 'home' && a.piece !== undefined) return fail('그 말은 움직일 수 없어요.');
|
||||
if (o.useOrder === 'thrown' && a.throwIndex !== 0) return fail('이 방은 던진 순서대로 써요. 맨 앞의 결과부터 써 주세요.');
|
||||
if (a.from === 'home') {
|
||||
if (!side.pieces.some((p) => p.status === 'home')) return fail('기다리는 말이 없어요.');
|
||||
@@ -910,12 +995,17 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
const s = structuredClone(prev);
|
||||
const events: GameEvent[] = [];
|
||||
s.turnSeq += 1;
|
||||
const act: Exclude<YutAction, { type: 'TIMEOUT' }> = a.type === 'TIMEOUT' ? autoAction(s) : a;
|
||||
const act: Exclude<YutAction, { type: 'TIMEOUT' }> = a.type === 'TIMEOUT' ? (s.aug ? augAutoAction(s, actor) : autoAction(s)) : a;
|
||||
if (a.type === 'TIMEOUT') {
|
||||
s.timeouts[actor] = (s.timeouts[actor] ?? 0) + 1;
|
||||
pushLog(s, events, { type: 'timeout', player: actor });
|
||||
if (s.timeouts[actor] === AWAY_AFTER) pushLog(s, events, { type: 'away', player: actor });
|
||||
} else if (a.type !== 'CONCEDE') s.timeouts[actor] = 0;
|
||||
if (s.aug) {
|
||||
augApply(s, actor, act, rng, events);
|
||||
refreshDeadline(s, now);
|
||||
return { state: s, events };
|
||||
}
|
||||
switch (act.type) {
|
||||
case 'THROW':
|
||||
doThrow(s, rng, events);
|
||||
@@ -926,6 +1016,8 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
case 'CONCEDE':
|
||||
doConcede(s, actor, events);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`yut: ${act.type} needs 증강 윷놀이`);
|
||||
}
|
||||
refreshDeadline(s, now);
|
||||
return { state: s, events };
|
||||
@@ -944,9 +1036,10 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
}
|
||||
stacks.sort((a, b) => a.node - b.node || (a.piece ?? -1) - (b.piece ?? -1));
|
||||
const mine = s.phase === 'move' && viewer !== null && viewer === s.current;
|
||||
const plans = mine ? legalPlans(s) : [];
|
||||
const plans = mine && !s.aug ? legalPlans(s) : [];
|
||||
const auto = mine && plans.length ? chooseAuto(s, plans) : null;
|
||||
return {
|
||||
const am = s.aug ? augMoves(s, viewer) : null;
|
||||
const base: YutView = {
|
||||
options: o,
|
||||
team: o.mode === 'team',
|
||||
me: mySide === null ? null : viewer,
|
||||
@@ -974,15 +1067,17 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
turnSeq: s.turnSeq,
|
||||
deadlineAt: s.deadlineAt,
|
||||
away: s.players.filter((p) => (s.timeouts[p] ?? 0) >= AWAY_AFTER),
|
||||
legalMoves: mine ? plans.map(toLegal) : null,
|
||||
suggested: auto ? (({ type: _t, ...rest }) => rest)(planAction(auto)) : null,
|
||||
legalMoves: am ? am.legal : mine ? plans.map(toLegal) : null,
|
||||
suggested: am ? am.suggested : auto ? (({ type: _t, ...rest }) => rest)(planAction(auto)) : null,
|
||||
log: s.log,
|
||||
stats: s.stats,
|
||||
result: s.final,
|
||||
};
|
||||
return s.aug ? augView(s, viewer, base) : base;
|
||||
},
|
||||
|
||||
activePlayers(s) {
|
||||
if (s.aug) return augActivePlayers(s);
|
||||
return s.phase === 'finished' ? [] : [s.current];
|
||||
},
|
||||
|
||||
@@ -991,6 +1086,7 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
},
|
||||
|
||||
timeoutPlayers(s) {
|
||||
if (s.aug) return augActivePlayers(s);
|
||||
return s.phase === 'finished' ? [] : [s.current];
|
||||
},
|
||||
|
||||
@@ -1016,7 +1112,9 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
return {
|
||||
ranking: [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ps]) => ps),
|
||||
scores,
|
||||
scoreText: Object.fromEntries(Object.entries(scores).map(([p, n]) => [p, `난 말 ${n}개`])),
|
||||
scoreText: Object.fromEntries(
|
||||
f.ranking.flatMap((r) => r.players.map((p) => [p, r.reason && s.aug ? `난 말 ${r.finishedPieces}개 · ${r.reason}` : `난 말 ${r.finishedPieces}개`])),
|
||||
),
|
||||
summary: f.summary,
|
||||
reason: f.reason,
|
||||
};
|
||||
@@ -1024,6 +1122,7 @@ export const yut: GameDefinition<YutState, YutAction, YutView, YutOptions> = {
|
||||
|
||||
/** Test helper: THROW in the throw phase, every distinct legal MOVE in the move phase (CONCEDE is left out). */
|
||||
legalActions(s, p) {
|
||||
if (s.aug) return augLegalActions(s, p);
|
||||
if (s.phase === 'finished' || p !== s.current) return [];
|
||||
if (s.phase === 'throw') return [{ type: 'THROW' }];
|
||||
return legalPlans(s).map(planAction);
|
||||
|
||||
122
packages/games/src/yut/physics.ts
Normal file
122
packages/games/src/yut/physics.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* 알까기 (증강): a small deterministic disc simulation on the 0..100 board. Runs on the server only; the screen just
|
||||
* replays the sampled frames. Same inputs give the same result (fixed step, no randomness).
|
||||
*/
|
||||
export interface Disc {
|
||||
x: number;
|
||||
y: number;
|
||||
/** Pieces in the disc (heavier stacks are pushed less). */
|
||||
mass: number;
|
||||
}
|
||||
|
||||
export interface FlickResult {
|
||||
/** Final centre of every disc. */
|
||||
end: [number, number][];
|
||||
/** Discs whose centre left the board. */
|
||||
out: boolean[];
|
||||
/** Discs that moved at all. */
|
||||
moved: boolean[];
|
||||
/** Sampled centres of the discs that moved (index → points, ~30 per second), for the animation. */
|
||||
frames: Record<number, [number, number][]>;
|
||||
}
|
||||
|
||||
export const DISC_R = 3.8;
|
||||
const DT = 1 / 60;
|
||||
const MAX_STEPS = 600;
|
||||
const FRICTION = 55; // units / s²
|
||||
const MAX_SPEED = 170; // units / s at power 100
|
||||
const RESTITUTION = 0.9;
|
||||
/** A centre outside this square has fallen off the board. */
|
||||
export const EDGE_LO = 0.5;
|
||||
export const EDGE_HI = 99.5;
|
||||
const SAMPLE_EVERY = 2;
|
||||
|
||||
/**
|
||||
* Flicks disc `hit` towards `angleDeg` (screen degrees: 0 = right, 90 = down) with `power` 1..100.
|
||||
* `ghost`: a disc that starts under the flicked one (the rest of its stack) and does not collide with it until they
|
||||
* have separated once.
|
||||
*/
|
||||
export function flick(discs: Disc[], hit: number, angleDeg: number, power: number, ghost: number | null = null): FlickResult {
|
||||
const n = discs.length;
|
||||
const x = discs.map((d) => d.x);
|
||||
const y = discs.map((d) => d.y);
|
||||
const vx = new Array<number>(n).fill(0);
|
||||
const vy = new Array<number>(n).fill(0);
|
||||
const out = new Array<boolean>(n).fill(false);
|
||||
const moved = new Array<boolean>(n).fill(false);
|
||||
const a = (angleDeg * Math.PI) / 180;
|
||||
const sp = (Math.max(1, Math.min(100, power)) / 100) * MAX_SPEED;
|
||||
vx[hit] = Math.cos(a) * sp;
|
||||
vy[hit] = Math.sin(a) * sp;
|
||||
moved[hit] = true;
|
||||
let ghostOn = ghost !== null;
|
||||
const frames: Record<number, [number, number][]> = {};
|
||||
const r1 = (v: number) => Math.round(v * 10) / 10;
|
||||
const sample = () => {
|
||||
for (let i = 0; i < n; i++) if (moved[i] && !out[i]) (frames[i] ??= [[r1(discs[i]!.x), r1(discs[i]!.y)]]).push([r1(x[i]!), r1(y[i]!)]);
|
||||
};
|
||||
for (let step = 0; step < MAX_STEPS; step++) {
|
||||
// move + friction
|
||||
let anyMoving = false;
|
||||
for (let i = 0; i < n; i++) {
|
||||
if (out[i]) continue;
|
||||
const v = Math.hypot(vx[i]!, vy[i]!);
|
||||
if (v === 0) continue;
|
||||
const nv = Math.max(0, v - FRICTION * DT);
|
||||
const k = nv / v;
|
||||
vx[i] = vx[i]! * k;
|
||||
vy[i] = vy[i]! * k;
|
||||
x[i] = x[i]! + vx[i]! * DT;
|
||||
y[i] = y[i]! + vy[i]! * DT;
|
||||
if (nv < 0.4) {
|
||||
vx[i] = 0;
|
||||
vy[i] = 0;
|
||||
} else anyMoving = true;
|
||||
if (x[i]! < EDGE_LO || x[i]! > EDGE_HI || y[i]! < EDGE_LO || y[i]! > EDGE_HI) {
|
||||
out[i] = true;
|
||||
vx[i] = 0;
|
||||
vy[i] = 0;
|
||||
}
|
||||
}
|
||||
// collisions (equal radius, masses by piece count)
|
||||
for (let i = 0; i < n; i++) {
|
||||
if (out[i]) continue;
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (out[j]) continue;
|
||||
const dx = x[j]! - x[i]!;
|
||||
const dy = y[j]! - y[i]!;
|
||||
const d = Math.hypot(dx, dy);
|
||||
const isGhost = ghostOn && ((i === hit && j === ghost) || (j === hit && i === ghost));
|
||||
if (isGhost) {
|
||||
if (d >= DISC_R * 2) ghostOn = false;
|
||||
continue;
|
||||
}
|
||||
if (d >= DISC_R * 2 || d === 0) continue;
|
||||
const nx = dx / d;
|
||||
const ny = dy / d;
|
||||
const rel = (vx[i]! - vx[j]!) * nx + (vy[i]! - vy[j]!) * ny;
|
||||
// push apart
|
||||
const overlap = DISC_R * 2 - d;
|
||||
const mi = discs[i]!.mass;
|
||||
const mj = discs[j]!.mass;
|
||||
x[i] = x[i]! - nx * overlap * (mj / (mi + mj));
|
||||
y[i] = y[i]! - ny * overlap * (mj / (mi + mj));
|
||||
x[j] = x[j]! + nx * overlap * (mi / (mi + mj));
|
||||
y[j] = y[j]! + ny * overlap * (mi / (mi + mj));
|
||||
if (rel <= 0) continue;
|
||||
const imp = ((1 + RESTITUTION) * rel) / (1 / mi + 1 / mj);
|
||||
vx[i] = vx[i]! - (imp / mi) * nx;
|
||||
vy[i] = vy[i]! - (imp / mi) * ny;
|
||||
vx[j] = vx[j]! + (imp / mj) * nx;
|
||||
vy[j] = vy[j]! + (imp / mj) * ny;
|
||||
moved[i] = true;
|
||||
moved[j] = true;
|
||||
anyMoving = true;
|
||||
}
|
||||
}
|
||||
if (step % SAMPLE_EVERY === 0) sample();
|
||||
if (!anyMoving) break;
|
||||
}
|
||||
sample();
|
||||
return { end: x.map((xi, i) => [xi, y[i]!]), out, moved, frames };
|
||||
}
|
||||
Reference in New Issue
Block a user