diff --git a/apps/web/src/games/yut/help.test.ts b/apps/web/src/games/yut/help.test.ts index 9179f5c..e56d3e1 100644 --- a/apps/web/src/games/yut/help.test.ts +++ b/apps/web/src/games/yut/help.test.ts @@ -60,3 +60,56 @@ test('윷: 게임 끝', () => { const s = applyAction('yut', state, other, { type: 'CONCEDE' }); expect(helpNow(view(s, me), me, users)).toContain('게임이 끝났어요'); }); + +// ---------------------------------------------------------------- 지역 룰 + +import { changedTags, houseRules, optionsSummary } from './house-rules'; + +const BK = { backdo: [F, R, R, R] } as const; +function freshWith(opts: Record) { + const f = fresh(); + f.state.options = GAMES.yut!.optionsSchema.parse(opts); + return f; +} + +test('윷 지역 룰: 기본 방의 요약은 그대로이고, 바꾼 규칙만 요약에 붙어요', () => { + const d = GAMES.yut!.defaultOptions as any; + expect(optionsSummary(d)).toBe('개인전 · 말 4개 · 빽도 있음 · 참먹이 지나야 남 · 30초'); + expect(changedTags(d)).toEqual([]); + expect(houseRules(d).every((r) => !r.changed)).toBe(true); + const o = GAMES.yut!.optionsSchema.parse({ stacking: 'choose', forkRule: 'choose', useOrder: 'thrown', backdoNoPiece: 'rethrow', nakPercent: 5, nakRule: 'lose' }) as any; + expect(optionsSummary(o)).toBe('개인전 · 말 4개 · 빽도 있음 · 참먹이 지나야 남 · 낙 5% · 말 없을 때 빽도는 다시 던짐 · 업기 고르기 · 갈림길 고르기 · 던진 순서대로 쓰기 · 낙이면 차례 끝 · 30초'); + // Rules that cannot matter are not listed: no 빽도 → no 빽도 rules, no 낙 → no 낙 handling, 팀전 → no ranking. + const keys = houseRules(GAMES.yut!.optionsSchema.parse({ backdo: false, mode: 'team' }) as any).map((r) => r.key); + expect(keys).not.toContain('backdoNoPiece'); + expect(keys).not.toContain('nakRule'); + expect(keys).not.toContain('ranking'); + // Old rooms saved before the newer keys existed read as the defaults. + const { backdoNoPiece: _a, nakRule: _b, useOrder: _c, stacking: _d, forkRule: _e, ...old } = d; + expect(optionsSummary(old)).toBe(optionsSummary(d)); + for (const r of houseRules(o)) expect(r.text).toMatch(/요(\([^)]*\))?\.$/); +}); + +test('윷 지역 룰: 빽도 다시 던지기 / 던진 순서대로 / 갈 길·업기 고르기 / 날윷 새 말 안내', () => { + const a = freshWith({ backdoNoPiece: 'rethrow' }); + const rethrow = applyAction('yut', a.state, a.me, { type: 'THROW' }, { next: (() => { const q = [...BK.backdo]; return () => q.shift()!; })() } as any); + expect(helpNow(view(rethrow, a.me), a.me, users)).toContain('빽도는 없던 걸로 하고 다시 던져요'); + + const b = freshWith({ useOrder: 'thrown' }); + let t = applyAction('yut', b.state, b.me, { type: 'THROW' }, sticks('yut')); + t = applyAction('yut', t, b.me, { type: 'THROW' }, sticks('geol')); + expect(helpNow(view(t, b.me), b.me, users)).toContain('이 방은 던진 순서대로 써요. 지금은 맨 앞의 윷부터 써요.'); + + const c = freshWith({ forkRule: 'choose', stacking: 'choose' }); + const mine = c.state.sides[0].pieces; + Object.assign(mine[0], { status: 'board', node: 5, trail: [1, 2, 3, 4, 5], lapped: false }); + Object.assign(mine[1], { status: 'board', node: 1, trail: [1], lapped: false }); + const u = applyAction('yut', c.state, c.me, { type: 'THROW' }, sticks('do')); + const text = helpNow(view(u, c.me), c.me, users); + expect(text).toContain('[갈 길 고르기]'); + expect(text).toContain('[따로 두기]'); + + const e = freshWith({ backdoNoPiece: 'enter' }); + const w = applyAction('yut', e.state, e.me, { type: 'THROW' }, { next: (() => { const q = [...BK.backdo]; return () => q.shift()!; })() } as any); + expect(helpNow(view(w, e.me), e.me, users)).toContain('빽도로 새 말을 참먹이 한 칸 뒤(날윷)에 올릴 수 있어요'); +}); diff --git a/apps/web/src/games/yut/help.ts b/apps/web/src/games/yut/help.ts index 5902203..bcfb649 100644 --- a/apps/web/src/games/yut/help.ts +++ b/apps/web/src/games/yut/help.ts @@ -6,11 +6,12 @@ const THROW_KO: Record = { do: '도', gae: '개', geol: '걸', yu const pendingText = (v: YutView) => v.pending.map((t) => THROW_KO[t]).join(', '); -/** Why the current player throws (again): fresh turn, 윷·모, or a capture bonus. */ -function throwReason(v: YutView): 'fresh' | 'yutmo' | 'capture' { +/** Why the current player throws (again): fresh turn, 윷·모, a capture bonus, or a 빽도 thrown again (지역 룰). */ +function throwReason(v: YutView): 'fresh' | 'yutmo' | 'capture' | 'backdo' { for (let i = v.log.length - 1; i >= 0; i--) { const e = v.log[i]!; if (e.type === 'bonusThrow') return 'capture'; + if (e.type === 'backdoRethrow') return 'backdo'; if (e.type === 'thrown') return e.result === 'yut' || e.result === 'mo' ? 'yutmo' : 'fresh'; if (e.type === 'turnChanged' || e.type === 'nak' || e.type === 'moved') return 'fresh'; } @@ -25,6 +26,7 @@ export function helpNow(v: YutView, me: string | null, players: Record 1) lines.push(`이 방은 던진 순서대로 써요. 지금은 맨 앞의 ${THROW_KO[v.pending[0]!]}부터 써요.`); if (moves.length === 1) { lines.push('지금 움직일 수 있는 방법이 하나뿐이에요. 초록색 [자동 이동] 버튼을 누르면 바로 움직여요.'); } else { @@ -57,7 +61,10 @@ export function helpNow(v: YutView, me: string | null, players: Record 0 && moves.some((m) => m.from === 'home')) lines.push(`새 말은 [대기 ${mySide.home}개] 버튼을 눌러 판에 올려요.`); } const usable = new Set(moves.map((m) => m.throw)); - if (v.pending.some((t) => !usable.has(t))) lines.push('지금 쓸 곳이 없는 결과는 눌리지 않아요. 다른 결과를 먼저 써 보세요.'); + if (!ordered && v.pending.some((t) => !usable.has(t))) lines.push('지금 쓸 곳이 없는 결과는 눌리지 않아요. 다른 결과를 먼저 써 보세요.'); + if (moves.some((m) => m.alt)) lines.push('모서리나 방에 멈췄던 말은 [갈 길 고르기]에서 지름길과 다른 길 중에 고를 수 있어요.'); + if (moves.some((m) => m.stack === false)) lines.push('내 말이 있는 자리에 멈출 때 [따로 두기]를 고르면 업지 않고 옆에 둬요.'); + if (moves.some((m) => m.throw === 'backdo' && m.from === 'home')) lines.push('판에 내 말이 없어서 빽도로 새 말을 참먹이 한 칸 뒤(날윷)에 올릴 수 있어요.'); const tips: string[] = []; if (moves.some((m) => m.captures > 0)) { const bonus = moves.some((m) => m.captures > 0 && (m.throw !== 'backdo' || v.options.backdoCaptureBonus)); diff --git a/apps/web/src/games/yut/house-rules.ts b/apps/web/src/games/yut/house-rules.ts new file mode 100644 index 0000000..89121c3 --- /dev/null +++ b/apps/web/src/games/yut/house-rules.ts @@ -0,0 +1,109 @@ +/** 윷놀이 지역 룰 설명 (docs/games/yut.md §7): one plain sentence per rule for the options screen, the rules sheet and the room summary. */ +import type { YutOptions } from '@bg/games/yut'; + +export interface HouseRule { + key: keyof YutOptions; + /** Short heading. */ + title: string; + /** What this room does, in one or two sentences (존댓말). */ + text: string; + /** Short tag for the one-line room summary (only shown when `changed`). */ + tag: string; + /** Differs from the most common rule (the default). */ + changed: boolean; +} + +/** + * Every 지역 룰 that applies with these options, in screen order. Rules that cannot matter (빽도 rules without 빽도, + * 낙 handling without 낙, ranking in 팀전) are left out. Old rooms may lack the newer keys: missing = default. + */ +export function houseRules(o: YutOptions): HouseRule[] { + const out: HouseRule[] = []; + const add = (key: keyof YutOptions, title: string, changed: boolean, tag: string, text: string) => out.push({ key, title, changed, tag, text }); + const reach = o.finishRule === 'reach'; + + add('backdo', '빽도', !o.backdo, '빽도 없음', o.backdo ? "'빽' 표시 가락 하나만 배가 위면 빽도예요. 말이 왔던 길로 한 칸 돌아가요." : '빽도 없이 해요. 표시 가락 하나만 배가 위여도 그냥 도예요.'); + if (o.backdo) { + const np = o.backdoNoPiece ?? 'discard'; + add( + 'backdoNoPiece', + '판에 내 말이 없을 때 빽도', + np !== 'discard', + np === 'rethrow' ? '말 없을 때 빽도는 다시 던짐' : '말 없을 때 빽도는 날윷으로', + np === 'rethrow' + ? '판에 내 말이 없을 때 나온 빽도는 없던 걸로 하고 다시 던져요.' + : np === 'enter' + ? `판에 내 말이 없을 때 빽도가 나오면 새 말이 참먹이 한 칸 뒤(날윷)에 올라가요. ${reach ? '다음에 앞으로 가면 바로 나요.' : '다음에 도면 참먹이에 서고, 개 이상이면 바로 나요.'}` + : '판에 내 말이 없으면 빽도는 쓸 곳이 없어서 버려요.', + ); + add( + 'backdoFromDo', + '도 자리에서 빽도', + o.backdoFromDo === 'finish', + '도 자리 빽도는 바로 남', + o.backdoFromDo === 'finish' ? '도 자리에 있는 말이 빽도를 받으면 그 자리에서 바로 나요.' : '도 자리에 있는 말이 빽도를 받으면 참먹이로 가고, 다음에 앞으로 가면 바로 나요.', + ); + add('backdoCaptureBonus', '빽도로 잡았을 때', !o.backdoCaptureBonus, '빽도로 잡으면 더 안 던짐', o.backdoCaptureBonus ? '빽도로 잡아도 한 번 더 던져요.' : '빽도로 잡을 때는 한 번 더 던지지 않아요.'); + } + const choose = o.stacking === 'choose'; + add( + 'stacking', + '업기', + choose, + '업기 고르기', + choose + ? '내 말이 있는 자리에 멈추면 업을지, 업지 않고 따로 둘지 골라요. 따로 둬도 상대가 그 자리에 오면 모두 잡혀요.' + : '내 말이 있는 자리에 멈추면 무조건 업어서 함께 움직여요.', + ); + const fork = o.forkRule === 'choose'; + add( + 'forkRule', + '갈림길(모서리·방)', + fork, + '갈림길 고르기', + fork + ? '모서리(모·뒷모)나 방에 멈췄다가 출발할 때 지름길로 갈지 다른 길로 갈지 골라요. 지나가기만 할 때는 그대로 직진해요.' + : '모서리(모·뒷모)나 방에 멈췄다가 출발하면 늘 안쪽 지름길로 가요. 방에서는 참먹이 쪽으로 가요.', + ); + const ordered = o.useOrder === 'thrown'; + add( + 'useOrder', + '결과 쓰는 순서', + ordered, + '던진 순서대로 쓰기', + ordered ? '모아 둔 결과는 던진 순서대로 써요. 맨 앞 결과를 쓸 곳이 없으면 그 결과만 버려요.' : '모아 둔 결과는 원하는 순서로 써요.', + ); + add('finishRule', '날(완주)', reach, '참먹이 도착하면 남', reach ? '한 바퀴 돈 말이 참먹이에 도착하면 바로 나요.' : '한 바퀴 돈 말이 참먹이를 지나가야 나요. 참먹이에 딱 멈추면 아직 판 위라서 잡힐 수 있어요.'); + add('nakPercent', '낙', o.nakPercent > 0, `낙 ${o.nakPercent}%`, o.nakPercent > 0 ? `윷가락이 ${o.nakPercent}% 확률로 판 밖으로 떨어져요(낙).` : '낙 없이 해요.'); + if (o.nakPercent > 0) { + const lose = o.nakRule === 'lose'; + add('nakRule', '낙이 나오면', lose, '낙이면 차례 끝', lose ? '낙이 나오면 차례가 바로 끝나요. 이번 차례에 모아 둔 결과도 모두 버려요.' : '낙이 나오면 그 던지기만 무효예요. 그 전에 모아 둔 결과는 남아요.'); + } + add('stickModel', '윷가락 확률', o.stickModel === 'fair', '앞뒤 반반 윷', o.stickModel === 'fair' ? '가락마다 앞뒤가 반반이라 윷·모가 조금 더 자주 나와요.' : '실제 윷처럼 개·걸이 잘 나오고 모는 드물게 나와요.'); + if (o.mode !== 'team') { + const all = o.ranking === 'all'; + add('ranking', '3~4명일 때 순위', all, '꼴찌까지 계속', all ? '3~4명일 때 1등이 나와도 꼴찌가 정해질 때까지 계속해요.' : '3~4명일 때 1등이 나오면 바로 끝나요. 나머지는 난 말 수와 남은 거리로 순위를 매겨요.'); + } + return out; +} + +/** Tags of the rules that differ from the default (for the one-line summary), without the ones the summary already shows. */ +export function changedTags(o: YutOptions): string[] { + const shown = new Set(['backdo', 'finishRule', 'nakPercent']); + return houseRules(o) + .filter((r) => r.changed && !shown.has(r.key)) + .map((r) => r.tag); +} + +/** One-line room summary (lobby): the basics, then every other 지역 룰 that differs from the default. */ +export function optionsSummary(o: YutOptions): string { + return [ + o.mode === 'team' ? '팀전' : '개인전', + `말 ${o.pieces}개`, + o.backdo ? '빽도 있음' : '빽도 없음', + o.finishRule === 'pass' ? '참먹이 지나야 남' : '참먹이 도착하면 남', + ...(o.nakPercent ? [`낙 ${o.nakPercent}%`] : []), + ...changedTags(o), + o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`, + ].join(' · '); +} diff --git a/apps/web/src/games/yut/index.tsx b/apps/web/src/games/yut/index.tsx index 634178b..19c9499 100644 --- a/apps/web/src/games/yut/index.tsx +++ b/apps/web/src/games/yut/index.tsx @@ -7,9 +7,23 @@ import { TurnTimer } from '../../components/TurnTimer'; import { haptic, sounds } from '../../lib/feedback'; import type { BoardProps, GameUI, OptionsProps } from '../types'; import { helpNow } from './help'; +import { houseRules, optionsSummary } from './house-rules'; import { quickStart } from './quick'; type From = number | 'home'; +/** A source the player can pick: a stack (`"7"`, or `"7#2"` when stacks stand apart on 7) or the waiting pieces (`"home"`). */ +type Src = string; +const srcOf = (from: From, piece?: number): Src => (piece === undefined ? String(from) : `${from}#${piece}`); +const toAction = (m: YutLegalMove) => ({ + type: 'MOVE' as const, + throwIndex: m.throwIndex, + from: m.from, + ...(m.piece !== undefined ? { piece: m.piece } : {}), + ...(m.alt ? { alt: true } : {}), + ...(m.stack === false ? { stack: false } : {}), +}); +/** Road names at a fork: the ordinary road first. */ +const roadNames = (from: From): [string, string] => (from === 22 ? ['참먹이 쪽', '찌모 쪽'] : ['지름길', '바깥 길']); type GameEvent = YutView['log'][number]; // The rules module is imported for types only (no zod in this chunk); these small tables mirror packages/games/src/yut/board.ts. @@ -234,7 +248,10 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps (myTurn && v.phase === 'move' ? (v.legalMoves ?? []) : []), [myTurn, v.phase, v.legalMoves]); const [selIdx, setSelIdx] = useState(null); - const [selFrom, setSelFrom] = useState(null); + const [selFrom, setSelFrom] = useState(null); + const [selAlt, setSelAlt] = useState(false); + const [selApart, setSelApart] = useState(false); + const ordered = v.options.useOrder === 'thrown'; const [announce, setAnnounce] = useState(''); const [anim, setAnim] = useState(null); const [flash, setFlash] = useState<{ text: string; at: [number, number]; key: number } | null>(null); @@ -245,15 +262,25 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps { - setSelFrom(null); - if (myTurn && v.phase === 'move' && kinds.length === 1) setSelIdx(v.pending.indexOf(kinds[0]!)); + pickSource(null); + if (myTurn && v.phase === 'move' && (kinds.length === 1 || ordered)) setSelIdx(0); else setSelIdx(null); }, [v.turnSeq]); // eslint-disable-line react-hooks/exhaustive-deps const selThrow = selIdx !== null ? (v.pending[selIdx] ?? null) : null; const forThrow = selThrow ? moves.filter((m) => m.throw === selThrow) : []; - const movable = new Set(forThrow.map((m) => m.from)); - const chosen: YutLegalMove | null = selFrom !== null ? (forThrow.find((m) => m.from === selFrom) ?? null) : null; + const movable = new Set(forThrow.map((m) => srcOf(m.from, m.piece))); + // 지역 룰 variants of the picked source: the other road at a fork, standing apart instead of stacking. + const variants = selFrom !== null ? forThrow.filter((m) => srcOf(m.from, m.piece) === selFrom) : []; + const onRoad = variants.filter((m) => !!m.alt === selAlt); + const chosen: YutLegalMove | null = onRoad.find((m) => (m.stack === false) === selApart) ?? onRoad[0] ?? variants[0] ?? null; + const roadChoice = variants.some((m) => m.alt) ? variants : null; + const apartChoice = onRoad.some((m) => m.stack === false) ? onRoad : null; + function pickSource(src: Src | null) { + setSelFrom(src); + setSelAlt(false); + setSelApart(false); + } // Throw / move feedback: sounds, screen-reader text, hop animation along the path. useEffect(() => { @@ -273,8 +300,10 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps a + c.count, 0); const end = m.to === 'goal' ? HOME_PT : POS[m.to]!; const parts = [`${nick(players, m.player)}님이 ${THROW_KO[m.throw]}로 ${nodeName(m.from)}에서 ${nodeName(m.to)}${m.to === 'goal' ? '' : ' 자리로'} 움직였어요${m.count > 1 ? `(${m.count}개 함께)` : ''}.`]; + if (m.alt) parts.push('갈림길에서 다른 길로 갔어요.'); if (caught) parts.push(`말 ${caught}개를 잡았어요!`); if (m.stacked) parts.push('업었어요.'); + if (m.apart) parts.push('업지 않고 따로 뒀어요.'); if (m.to === 'goal') parts.push(`말 ${m.count}개가 났어요.`); setAnnounce(parts.join(' ')); const text = caught ? '잡았다!' : m.to === 'goal' ? '났다!' : m.stacked ? '업었다!' : null; @@ -311,26 +340,28 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps { - act({ type: 'MOVE', throwIndex: m.throwIndex, from: m.from }); - setSelFrom(null); + act(toAction(m)); + pickSource(null); }; /** First tap shows where it lands, second tap (or the destination / 이동하기) confirms. */ - const tapSource = (from: From) => { + const tapSource = (src: Src) => { if (!myTurn || pending) return; if (!selThrow) { setAnnounce('먼저 아래에서 쓸 윷 결과를 골라 주세요.'); return; } - if (!movable.has(from)) { - setAnnounce(selThrow === 'backdo' && from === 'home' ? '빽도로는 새 말을 올릴 수 없어요.' : '그 말은 지금 움직일 수 없어요.'); + if (!movable.has(src)) { + setAnnounce(selThrow === 'backdo' && src === 'home' ? '지금은 빽도로 새 말을 올릴 수 없어요.' : '그 말은 지금 움직일 수 없어요.'); return; } - if (selFrom === from && chosen) doMove(chosen); + if (selFrom === src && chosen) doMove(chosen); else { - setSelFrom(from); - const m = forThrow.find((x) => x.from === from)!; - setAnnounce(`${nodeName(m.to)}${m.to === 'goal' ? '' : ' 자리'}로 가요. ${badge(m) ?? ''} 한 번 더 누르면 움직여요.`); + pickSource(src); + const all = forThrow.filter((x) => srcOf(x.from, x.piece) === src); + const m = all[0]!; + const extra = [all.some((x) => x.alt) ? '갈 길을 고를 수 있어요.' : '', all.some((x) => x.stack === false) ? '업을지 따로 둘지 고를 수 있어요.' : ''].join(' ').trim(); + setAnnounce(`${nodeName(m.to)}${m.to === 'goal' ? '' : ' 자리'}로 가요. ${badge(m) ?? ''} ${extra} 한 번 더 누르면 움직여요.`.replace(/\s+/g, ' ')); } }; @@ -376,15 +407,22 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps {stacks.map((st) => { - const [x, y] = POS[st.node]!; + // 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); + 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; + const y = POS[st.node]![1]; + const src = srcOf(st.node, st.piece); const mine = v.mySide === st.side; - const can = myTurn && mine && movable.has(st.node); - const sel = mine && selFrom === st.node; + const can = myTurn && mine && movable.has(src); + const sel = mine && selFrom === src; const sideName = v.sides[st.side]!.name; + const r = twins.length > 1 ? 3.3 : BIG.has(st.node) ? 4.6 : 4; return ( - - {(can || sel) && } - + + {(can || sel) && 1 ? r + 1.4 : R_BIG + 0.6} fill="none" stroke={sel ? 'var(--primary)' : 'var(--focus)'} strokeWidth={1.3} className={sel ? undefined : 'yut-can'} />} + {mine && myTurn && v.phase === 'move' && ( tapSource(st.node)} - onKeyDown={keyAct(() => tapSource(st.node))} + aria-label={`${sideName} 말 ${st.count}개 (${NODE_NAMES[st.node]} 자리${twins.length > 1 ? `, 따로 선 무더기 ${k + 1}` : ''}) ${sel ? '— 한 번 더 누르면 움직여요' : '움직이기'}`} + onClick={() => tapSource(src)} + onKeyDown={keyAct(() => tapSource(src))} > - - + 1 ? r + 1.6 : R_BIG + 1} fill="transparent" /> + 1 ? r + 2 : R_BIG + 1.6} fill="none" stroke="var(--focus)" strokeWidth={1} /> )} @@ -452,7 +490,7 @@ function YutBoard({ view: v, me, players, act, pending, deadline }: BoardProps {v.pending.map((t, i) => { - const usable = moves.some((m) => m.throw === t); + const usable = moves.some((m) => m.throw === t) && (!ordered || i === 0); return ( + ); + })} + + + )} + {chosen && apartChoice && ( +
+ {nodeName(chosen.to)} 자리의 내 말 +
+ + +
+
+ )} {chosen ? (
-
) : (

{selThrow ? '반짝이는 말을 누르면 갈 자리가 보여요. 한 번 더 누르면 움직여요.' : '쓸 결과를 먼저 골라 주세요.'} + {ordered && v.pending.length > 1 ? ' 이 방은 던진 순서대로 써요.' : ''}

)} {lone && !chosen && ( @@ -538,6 +606,7 @@ function badge(m: YutLegalMove): string | null { if (m.captures) return '잡기!'; if (m.finishes) return '날!'; if (m.stacks) return '업기'; + if (m.stack === false) return '따로'; return null; } @@ -594,9 +663,11 @@ function logLine(e: GameEvent, v: YutView, players: Record): case 'thrown': return `${who}: ${THROW_KO[e.result as Throw]}`; case 'nak': - return `${who}: 낙! (무효)`; + return e.endsTurn ? `${who}: 낙! 차례가 끝났어요` : `${who}: 낙! (무효)`; + case 'backdoRethrow': + return `${who}: 판에 말이 없어서 빽도는 다시 던져요`; case 'moved': - return `${who}: ${THROW_KO[e.throw as Throw]}로 ${nodeName(e.from as From)} → ${nodeName(e.to as number | 'goal')}${(e.count as number) > 1 ? ` (${e.count}개)` : ''}`; + return `${who}: ${THROW_KO[e.throw as Throw]}로 ${nodeName(e.from as From)} → ${nodeName(e.to as number | 'goal')}${(e.count as number) > 1 ? ` (${e.count}개)` : ''}${e.alt ? ' · 다른 길' : ''}${e.apart ? ' · 따로 둠' : ''}`; case 'captured': return `${sn(e.side)}이 ${sn(e.victimSide)} 말 ${e.count}개를 잡았어요`; case 'stacked': @@ -692,21 +763,44 @@ function Seg({ value, options, onChange }: { value: T ); } -function Field({ label, children }: { label: string; children: React.ReactNode }) { +function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) { return (
{label} {children} + {hint && {hint}}
); } +/** One 지역 룰 group (빽도 / 말 움직이기 / 던지기) inside the 지역 룰 box. */ +function RuleGroup({ title, children }: { title: string; children: React.ReactNode }) { + return ( +
+ {title} + {children} +
+ ); +} + +const OPT_CSS = ` +.yut-rules-box { display: flex; flex-direction: column; gap: 14px; padding: 12px; border: 2px solid var(--border); border-radius: 16px; background: var(--surface-2, var(--surface)); min-width: 0; } +.yut-rule-group { display: flex; flex-direction: column; gap: 14px; margin: 0; padding: 10px 10px 12px; border: 1px dashed var(--border); border-radius: 12px; min-width: 0; } +.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); } +`; + function Options({ value: o, onChange }: OptionsProps) { const [more, setMore] = useState(false); const set = (patch: Partial) => onChange({ ...o, ...patch }); 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 (
+ set({ mode })} /> {o.mode === 'team' && 자리 순서대로 청팀·홍팀이 번갈아 앉아요(1·3·5·7번째 청팀). 자리를 바꿔 팀을 맞춰 주세요.} @@ -721,55 +815,105 @@ function Options({ value: o, onChange }: OptionsProps) { onChange={(k) => set({ turnSeconds: k === 'none' ? null : (Number(k) as 15 | 30 | 60) })} /> - + {!more && changed > 0 && ( + + 적용 중: {rules.filter((r) => r.changed).map((r) => r.tag).join(', ')} + + )} {more && ( - <> - - set({ backdo: k === 'on' })} /> - - {o.backdo && ( - <> - - set({ backdoFromDo })} /> +
+ 집이나 동네마다 다른 규칙이에요. 그대로 두면 가장 흔한 규칙으로 해요. 고른 규칙은 게임 중 [규칙 보기]에도 나와요. + + + set({ backdo: k === 'on' })} /> + + {o.backdo && ( + <> + + set({ backdoNoPiece })} + /> + + + set({ backdoFromDo })} /> + + + set({ backdoCaptureBonus: k === 'on' })} /> + + + )} + + + + set({ stacking })} /> + + + set({ forkRule })} /> + + + set({ useOrder })} /> + + + set({ finishRule })} /> + + + + + set({ stickModel })} /> + + + set({ nakPercent })} /> + + {o.nakPercent > 0 && ( + + set({ nakRule })} /> - - set({ backdoCaptureBonus: k === 'on' })} /> - - - )} - - set({ finishRule })} /> - - - set({ stickModel })} /> - - - set({ nakPercent })} /> - + )} + {o.mode === 'individual' && ( - + set({ ranking })} /> )} - + {changed > 0 && ( + + )} +
)}
); } -function optionsSummary(o: YutOptions): string { - return [ - o.mode === 'team' ? '팀전' : '개인전', - `말 ${o.pieces}개`, - o.backdo ? '빽도 있음' : '빽도 없음', - o.finishRule === 'pass' ? '참먹이 지나야 남' : '참먹이 도착하면 남', - ...(o.nakPercent ? [`낙 ${o.nakPercent}%`] : []), - o.turnSeconds === null ? '시간 무제한' : `${o.turnSeconds}초`, - ].join(' · '); -} - // ---------------------------------------------------------------- rules function MiniBoard() { @@ -830,14 +974,17 @@ function Rules({ options }: { options?: YutOptions }) {

밝은 면이 배(평평한 면), 어두운 면이 등이에요. 배가 위인 가락 수로 결과가 정해져요. '빽' 표시가 있는 가락 하나만 배가 위면 빽도예요.

- 윷·모가 나오면 한 번 더 던져요. 모아 둔 결과는 원하는 순서로, 원하는 말에 하나씩 써요. 결과 칩을 누르고 → 반짝이는 말을 누르면 갈 자리가 보이고 → 한 번 더 누르면 움직여요. + 윷·모가 나오면 한 번 더 던져요. 모아 둔 결과는 {o?.useOrder === 'thrown' ? '던진 순서대로' : '원하는 순서로'}, 원하는 말에 하나씩 써요. 결과 칩을 누르고 → 반짝이는 말을 누르면 갈 자리가 보이고 → 한 번 더 누르면 움직여요.

- 지름길: 모서리(모·뒷모)나 가운데 방에 멈췄다가 다음에 출발하면 안쪽 대각선으로 꺾어요. 지나가기만 하면 그대로 직진해요. 방에서 출발하면 언제나 참먹이 쪽으로 가요. + 지름길: 모서리(모·뒷모)나 가운데 방에 멈췄다가 다음에 출발하면 안쪽 대각선으로 꺾어요. 지나가기만 하면 그대로 직진해요.{' '} + {o?.forkRule === 'choose' + ? '이 방은 갈 길을 고르는 규칙이라, 멈췄던 말을 움직일 때 지름길과 다른 길 중에서 골라요(방에서는 참먹이 쪽과 찌모 쪽).' + : '방에서 출발하면 언제나 참먹이 쪽으로 가요.'}

- 업기: 내 말이 있는 자리에 멈추면 함께 업혀서 같이 움직여요. 잡기: 상대 말이 있는 자리에 멈추면 그 말들을 처음으로 돌려보내고 한 번 더 던져요 + 업기: 내 말이 있는 자리에 멈추면 {o?.stacking === 'choose' ? '업어서 같이 움직일지, 따로 둘지 골라요(따로 둬도 잡힐 때는 함께 잡혀요)' : '함께 업혀서 같이 움직여요'}. 잡기: 상대 말이 있는 자리에 멈추면 그 말들을 처음으로 돌려보내고 한 번 더 던져요 {o && !o.backdoCaptureBonus ? '(빽도로 잡을 때는 빼고)' : ''}. 지나가기만 해서는 잡지 않아요.

@@ -845,11 +992,43 @@ function Rules({ options }: { options?: YutOptions }) {

{o?.backdo !== false && (

- 빽도: 말이 왔던 길로 한 칸 돌아가요. 판 위에 말이 없으면 빽도는 버려져요.{' '} + 빽도: 말이 왔던 길로 한 칸 돌아가요.{' '} + {o?.backdoNoPiece === 'rethrow' + ? '판 위에 내 말이 없을 때 나온 빽도는 없던 걸로 하고 다시 던져요.' + : o?.backdoNoPiece === 'enter' + ? '판 위에 내 말이 없을 때 빽도가 나오면 새 말이 참먹이 한 칸 뒤(날윷)에 올라가요.' + : '판 위에 말이 없으면 빽도는 버려져요.'}{' '} {o?.backdoFromDo === 'finish' ? '도 자리에 있는 말이 빽도를 받으면 바로 나요.' : '도 자리에 있는 말이 빽도를 받으면 참먹이로 가고, 다음 전진에서 바로 나요.'}

)} - {!!o?.nakPercent &&

낙: {o.nakPercent}% 확률로 윷가락이 판 밖으로 떨어져 그 던지기는 무효가 돼요(그 전에 모아 둔 결과는 남아요).

} + {!!o?.nakPercent && ( +

+ 낙: {o.nakPercent}% 확률로 윷가락이 판 밖으로 떨어져요.{' '} + {o.nakRule === 'lose' ? '낙이 나오면 차례가 바로 끝나고, 이번 차례에 모아 둔 결과도 모두 버려요.' : '그 던지기는 무효가 되고, 그 전에 모아 둔 결과는 남아요.'} +

+ )} + {o ? ( +
+ 이 방의 지역 룰 +
    + {houseRules(o).map((r) => ( +
  • + {r.title} + {r.changed && ( + + 기본과 달라요 + + )} + : {r.text} +
  • + ))} +
+
+ ) : ( +

+ 지역 룰: 방장이 방 설정의 [지역 룰]에서 빽도 처리, 업기, 갈림길, 결과 쓰는 순서, 낙 같은 동네마다 다른 규칙을 고를 수 있어요. +

+ )}

시간 안에 하지 않으면 자동으로 던지거나, 잡기 → 내기 → 업기 → 뒤처진 말 순서로 골라 움직여요. 세 번 연속 시간을 넘기면 '자리 비움'이 되고 제한 시간이 5초로 줄어요.

); diff --git a/docs/games/yut.md b/docs/games/yut.md index 6cf2cdf..321e9d4 100644 --- a/docs/games/yut.md +++ b/docs/games/yut.md @@ -18,6 +18,11 @@ | `nakPercent` | 낙(윷가락이 판 밖으로 떨어짐) 확률. 0이면 낙 없음 | 0, 3, 5, 10 | 0 | | `backdoCaptureBonus` | 빽도로 잡아도 한 번 더 던지기를 주는지 | `true`, `false` | `true` | | `ranking` | 3~4명 개인전에서 1등이 나온 뒤 | `first`(1등 나오면 종료, 나머지는 진행도로 순위), `all`(꼴찌가 정해질 때까지 계속) | `first` | +| `backdoNoPiece` | 지역 룰: 판에 내 말이 없을 때 빽도가 나오면 (7장) | `discard`(쓸 곳이 없어 버림), `rethrow`(없던 걸로 하고 다시 던짐), `enter`(새 말이 참먹이 한 칸 뒤 날윷(19)에 올라감) | `discard` | +| `nakRule` | 지역 룰: 낙이 나오면 (`nakPercent > 0`일 때만) | `keep`(그 던지기만 무효, 모아 둔 결과 유지), `lose`(차례 끝, 이번 차례에 모아 둔 결과도 모두 버림) | `keep` | +| `useOrder` | 지역 룰: 모아 둔 결과를 쓰는 순서 | `free`(원하는 순서로), `thrown`(던진 순서대로) | `free` | +| `stacking` | 지역 룰: 내 말이 있는 자리에 멈추면 | `always`(무조건 업음), `choose`(업을지 따로 둘지 고름) | `always` | +| `forkRule` | 지역 룰: 모서리(모·뒷모)·방에 멈췄다가 출발할 때 | `shortcut`(늘 지름길, 방에서는 참먹이 쪽), `choose`(지름길과 다른 길 중 고름) | `shortcut` | | `turnSeconds` | 행동(던지기·말 고르기) 1회당 제한 시간 | 15, 30, 60, `null`(무제한, 끊김 처리만) | 30 | 옵션 검증(zod `superRefine`): @@ -91,7 +96,7 @@ | 0 (참먹이, 한 바퀴 돈 말) | GOAL | GOAL(`pass`) | - 핵심: 모서리(모·뒷모)와 방은 그 자리에 "멈춰 있다가" 다음 이동을 시작할 때만 꺾는다. 지나가는 중이면 직진한다. -- 방에 멈췄다가 출발하면 항상 참먹이 방향(27)으로 간다(가장 빠른 길). +- 방에 멈췄다가 출발하면 항상 참먹이 방향(27)으로 간다(가장 빠른 길). 지역 룰 `forkRule = choose`면 모·뒷모·방에서 다른 길도 고를 수 있다(7.1). - 대기 상태의 말이 처음 들어올 때는 0을 지나는 것이 아니라 1부터 센다(도 = 1, 모 = 5). ### 5.3 차례 진행 @@ -100,7 +105,7 @@ - 도·개·걸·빽도가 나오면(또는 낙) 던지기를 멈추고 이동 단계로 간다. 2. 이동 단계: `pending`에서 결과 하나와 움직일 말(대기 말 또는 판 위의 말 무더기) 하나를 골라 `MOVE`. 순서는 자유. 모든 결과를 다 쓸 때까지 반복한다. - 대기 말은 전진 결과(도~모)로만 판에 올릴 수 있다. 빽도로는 못 올린다. - - 어떤 결과도 둘 곳이 없으면(예: 판 위에 말이 없는데 남은 결과가 빽도뿐) 그 결과들은 자동으로 버려진다. 일부 결과만 둘 곳이 없으면, 다른 결과를 먼저 쓰게 하고 매 이동 후 다시 판정한다(예: 빽도 + 개 → 개로 말을 올린 뒤 빽도를 그 말에 쓸 수 있음). + - 어떤 결과도 둘 곳이 없으면(예: 판 위에 말이 없는데 남은 결과가 빽도뿐) 그 결과들은 자동으로 버려진다(지역 룰 `backdoNoPiece`, `useOrder`로 바뀜, 7.1). 일부 결과만 둘 곳이 없으면, 다른 결과를 먼저 쓰게 하고 매 이동 후 다시 판정한다(예: 빽도 + 개 → 개로 말을 올린 뒤 빽도를 그 말에 쓸 수 있음). 3. 잡기 보너스: 이동이 상대 말을 잡으면 즉시 던지기 단계로 돌아가 1번 더 던진다. 남은 `pending` 결과는 그대로 유지되고 새 결과가 추가된다. 한 번 이동으로 업힌 상대 말 여러 개를 잡아도 보너스는 1번. 한 차례에 잡기를 여러 번 하면 그때마다 1번씩. 4. `pending`이 비고 추가 던지기도 없으면 차례 종료, 다음 편(팀전은 다음 팀의 다음 사람)으로. @@ -113,7 +118,7 @@ - 도 자리(1)에서 빽도(이 말의 기록이 [1]뿐): `backdoFromDo = chammeogi`면 참먹이(0)로 가고 "한 바퀴 돈 말"로 취급한다(다음 전진에서 바로 날 수 있음). `finish`면 즉시 남. - 참먹이(0)에서 빽도: 기록상 직전 자리(19 또는 28)로. 기록이 없으면 19로. - 빽도로 대기 말을 움직일 수는 없다. -- 업기: 자기 편 말이 있는 자리에 멈추면 무조건 업는다(합쳐서 하나의 무더기). 이후 그 무더기는 함께 움직이고, 함께 잡히고, 함께 난다. 업힌 무더기를 일부만 떼어 움직일 수 없다. 팀전에서는 팀 말끼리 업힌다. +- 업기: 자기 편 말이 있는 자리에 멈추면 무조건 업는다(합쳐서 하나의 무더기). 지역 룰 `stacking = choose`면 따로 둘 수도 있다(7.1). 이후 그 무더기는 함께 움직이고, 함께 잡히고, 함께 난다. 업힌 무더기를 일부만 떼어 움직일 수 없다. 팀전에서는 팀 말끼리 업힌다. - 잡기: 상대 편 말(무더기)이 있는 자리에 "멈추면" 그 말들을 모두 대기로 돌려보낸다(기록 초기화). 지나가는 것은 잡지 않는다. 참먹이(0)에 서 있는 말도 잡힌다. 대기·남은 말은 잡을 수 없다. - 한 자리에 서로 다른 편 말이 함께 있을 수 없다(멈추면 반드시 잡으므로). @@ -132,9 +137,32 @@ - 점수(옵션 없이 고정): 결과 화면에는 "난 말 수"와 순위만 표시한다. ## 7. 지역 룰 / 하우스 룰 (옵션으로 켜고 끄기) -- 빽도 사용 여부(`backdo`), 도 자리 빽도 처리(`backdoFromDo`), 날 판정(`finishRule`), 낙(`nakPercent`), 빽도 잡기 보너스(`backdoCaptureBonus`), 순위 방식(`ranking`): 2장 표 참조. +방 설정의 [지역 룰(우리 동네 규칙)] 묶음에서 고른다. 모든 기본값은 위 5장 규칙(가장 흔한 규칙) 그대로라서 기존 방·기록·리플레이는 바뀌지 않는다. 예전에 저장된 옵션에 새 키가 없으면 기본값으로 읽는다(엔진·화면 모두 "기본이 아닌 값인지"만 비교). 고른 규칙은 로비 요약 한 줄(기본과 다른 것만 덧붙임), 게임 중 [규칙 보기]의 "이 방의 지역 룰" 목록, [?] 도움말에 쉬운 말로 나온다. + +- 기존 옵션: 빽도 사용 여부(`backdo`), 도 자리 빽도 처리(`backdoFromDo`), 날 판정(`finishRule`), 낙(`nakPercent`), 빽도 잡기 보너스(`backdoCaptureBonus`), 순위 방식(`ranking`), 윷가락 확률(`stickModel`): 2장 표 참조. - 말 수 2~5개(`pieces`): 전통적으로 3~5개, 흔히 4개. -- 지원하지 않는 변형(문서화만): 자리마다 벌칙이 있는 "함정 윷판", 방에 멈추면 어느 방향이든 고를 수 있는 규칙(우리는 항상 참먹이 쪽), 업기를 거부하는 규칙, 빽도를 다음 차례까지 저장하는 규칙. 필요하면 후속 옵션으로 추가한다. + +### 7.1 추가한 지역 룰 (2026-10-13) +나무위키 "윷놀이"의 지역 차이 설명과 놀이 안내 글에서 "놀기 전에 미리 정하라"고 하는 대표적인 다툼거리를 골랐다. + +| 키 | 실제로 갈리는 지점 | 우리 엔진 동작 | +|---|---|---| +| `backdoNoPiece` | 판에 말이 없는데 빽도가 나오면 낙처럼 버리는 집, 다시 던지는 집, "출발점보다 한 칸 뒤로 가서 다음에 2칸 이상 가면 출발점을 지난 것으로 치는" 집 | `discard`: 지금처럼 쓸 곳이 없으면 버림(5.3-2). `rethrow`: 던진 순간 판에 내 말이 없고 모아 둔 결과에 전진 결과(말을 올릴 수 있는 것)도 없으면 그 빽도는 `pending`에 넣지 않고 한 번 더 던진다(`thrown` 다음 `backdoRethrow` 이벤트, 통계에는 빽도로 셈). `[윷, 빽도]`처럼 윷으로 말을 올린 뒤 쓸 수 있으면 그대로 둔다. `enter`: 판에 내 말이 하나도 없을 때만 대기 말에 빽도를 쓸 수 있고, 그 말은 참먹이 한 칸 뒤 날윷(19)에 선다(기록 `[19]`). 다음에 도면 참먹이(0)에 서고(한 바퀴 돈 말), 개 이상이면 참먹이를 지나 난다(`reach`면 도도 남). 19에 상대 말이 있으면 잡는다. 판에 내 말이 있으면 빽도는 판 위 말에만. | +| `nakRule` | 윷·모 다음 낙이 나면 앞의 윷·모를 인정하는 지역과 그냥 차례를 넘기는 지역 | `keep`: 지금처럼 그 던지기만 무효. `lose`: 낙이 나오면 이번 차례에 아직 안 쓴 결과를 모두 버리고(`discarded` 이벤트) 차례가 끝난다. 잡기 보너스 던지기에서 낙이 나와도 같다. `nak` 이벤트에 `endsTurn: true`. | +| `useOrder` | 윷→모→걸이 나오면 순서를 바꿔 모→걸→윷으로 써도 되는지 | `free`: 지금처럼 자유. `thrown`: `pending[0]`만 쓸 수 있다(다른 인덱스는 "이 방은 던진 순서대로 써요…"로 거부). 맨 앞 결과를 쓸 곳이 없으면 그 결과만 버리고 다음 결과로 넘어간다. 잡기 보너스로 새로 던진 결과는 뒤에 붙는다. | +| `stacking` | 내 말 위에 멈추면 무조건 업는지, 업지 않고 옆에 둘 수 있는지(업기 거부) | `always`: 지금처럼 무조건 업음. `choose`: 같은 편 말이 있는 자리에 멈추는 수마다 "따로 두기" 수(`MOVE.stack = false`)가 하나 더 생긴다. 따로 선 무더기는 `Piece.group`(그 무더기에서 가장 작은 말 번호)으로 구분하고, 각자 움직이며(`MOVE.piece`로 어느 무더기인지 지정), 빽도 기록도 따로다. 상대가 그 자리에 멈추면 그 자리의 내 말을 모두 잡는다(한 자리에 한 편만 있는 불변식 유지). 그 자리에 다시 업으며 멈추면 그 자리의 무더기가 모두 하나로 합쳐진다. | +| `forkRule` | 모서리·방에서 무조건 꺾는지, "갈림길 중 자기가 선택"하는지(나무위키: 무조건 꺾는 규칙이 지배적이나 고르게 하는 문헌도 있음) | `shortcut`: 지금처럼 멈췄다 출발하면 지름길(방에서는 참먹이 쪽). `choose`: 모(5)·뒷모(10)·방(22)에 멈춰 있던 말이 전진할 때 다른 길(`MOVE.alt = true`)도 고를 수 있다. 모 → 뒷도(6) 쪽 바깥 길, 뒷모 → 찌도(11) 쪽 바깥 길, 방 → 속윷(23)(찌모 쪽). 지나가는 중의 갈림길과 빽도는 그대로. | + +- 시간 초과 자동 행동(8.5)과 컴퓨터는 같은 우선순위에서 동점이면 보통 수(지름길, 업기)를 먼저 고른다. 컴퓨터는 남은 거리 표로 다른 길의 손해를 계산하므로, 잡을 수 있을 때만 다른 길로 간다. 따로 서 있는 내 말도 함께 잡힐 위험으로 계산하고, 업기 보너스 점수는 업을 때만 준다. + +### 7.2 일부러 넣지 않은 변형 +- 자리마다 벌칙·업기·강제 이동이 있는 "함정 윷판": 판 그림과 자리 규칙을 통째로 바꿔야 하는 다른 게임에 가깝다. +- 빽도 저장(판에 말이 없을 때 나온 빽도를 다음 차례로 넘겨 다음 결과에서 1칸 빼기): 차례를 넘어 남는 상태와 "어느 결과에서 빼는지" 세부가 집마다 달라 다툼만 늘어난다. 같은 상황을 `backdoNoPiece`의 세 가지로 대신한다. +- 뒷개·뒷걸·자유걸(표시 가락 조합으로 뒤로 2~3칸), 북한식 뒷도 2배: 가락 표시와 확률표가 바뀌는 드문 변형. +- 잡기 보너스 제한(그 차례에 윷·모가 나왔으면 잡아도 더 안 던짐, 잡고 받은 던지기에서는 윷·모가 나와도 더 안 던짐): 문헌에 "경우에 따라서는" 정도로만 나오는 드문 규칙. 윷·모 한 번 더 던지기와 잡으면 한 번 더 던지기는 거의 모든 지역이 같아서 끄는 옵션도 두지 않는다(빽도 잡기 보너스만 `backdoCaptureBonus`로 이미 있음). +- 낙 판정 기준(선에 걸치면 낙인지 등): 화면 속 윷은 판정 자체가 확률(`nakPercent`) 하나라 고를 것이 없다. +- 정확히 참먹이에 도착해야만 나는 규칙: 남는 칸 수를 버릴 수 없어 말이 오래 멈추는 드문 규칙이다(`finishRule`의 `pass`/`reach`로 충분). +- 대기 말 두 개를 업고 출발하기, 업는 말 수 제한: 드물고 근거가 약하다. ## 8. 엔진 설계 @@ -175,7 +203,7 @@ interface YutState { | type | payload | 누가 / 언제 | 검증 조건 | |---|---|---|---| | `THROW` | 없음 | 현재 차례 사람, `phase='throw'` | `throwsOwed > 0`. 위반 시 "지금은 윷을 던질 차례가 아니에요." | -| `MOVE` | `{ throwIndex: number; from: NodeId \| 'home' }` | 현재 차례 사람, `phase='move'` | `pending[throwIndex]` 존재. `from='home'`이면 자기 편 대기 말이 있고 결과가 빽도가 아님. `from`이 노드면 자기 편 말이 그 노드에 있음. 빽도는 판 위 말에만. 위반 시 "그 말은 움직일 수 없어요." 등 | +| `MOVE` | `{ throwIndex: number; from: NodeId \| 'home'; piece?: number; alt?: boolean; stack?: boolean }` (`piece`·`alt`·`stack`은 지역 룰 `stacking`·`forkRule = choose`에서만, 7.1) | 현재 차례 사람, `phase='move'` | `pending[throwIndex]` 존재. `from='home'`이면 자기 편 대기 말이 있고 결과가 빽도가 아님. `from`이 노드면 자기 편 말이 그 노드에 있음. 빽도는 판 위 말에만. 위반 시 "그 말은 움직일 수 없어요." 등 | | `CONCEDE` | 없음 | 아무 참가자, 언제나 | 개인전: 그 편 탈락(남은 편이 1이면 종료). 팀전: 팀원 전원이 기권해야 팀 패배(또는 방장 설정) | - 팀전에서는 현재 차례인 팀원만 행동할 수 있다(같은 팀 다른 사람은 채팅·추천만). @@ -211,6 +239,7 @@ interface YutResult { ## 9. UI/UX - 모바일 세로: 위쪽 2/3에 정사각형 윷판(자리 원 지름 48px 이상, 모서리·방은 더 크게), 아래에 "모아 둔 결과" 칩(도·개·걸·윷·모·빽도, 각 64px 이상)과 큰 "윷 던지기" 버튼, 맨 아래 대기 말·난 말 표시. PC: 윷판 왼쪽, 정보 패널 오른쪽. - 조작: 결과 칩을 먼저 누르고 → 움직일 수 있는 말이 반짝이고 → 말을 누르면 도착 자리가 표시되고 → 다시 누르면 확정(오조작 방지 2단계). 결과가 1개이고 움직일 말이 1가지면 "자동 이동" 버튼 강조. +- 지역 룰 선택(7.1): 고른 말에 다른 길이나 따로 두기가 있으면 [이동하기] 위에 "갈 길 고르기"(지름길/바깥 길, 방에서는 참먹이 쪽/찌모 쪽, 도착 자리와 잡기 표시)와 "업기(함께 움직임)/따로 두기" 버튼이 나오고, 점선 미리보기가 고른 대로 바뀐다. 말을 한 번 더 누르면 고른 대로 움직인다. 따로 선 무더기는 한 자리에 나란히 작게 그린다. 던진 순서대로(`useOrder = thrown`)면 맨 앞 결과 칩만 눌린다. - 합법 수 하이라이트: 도착 자리에 점선 경로 미리보기. 잡을 수 있으면 빨간 테두리 "잡기!", 업기면 "업기", 나면 "날!" 배지. - 애니메이션: 윷가락 4개가 공중에서 돌다 떨어지는 0.8초 애니메이션(서버 결과를 받은 뒤 재생, 결과 조작 불가). 말은 칸마다 통통 튀며 이동. 잡힌 말은 대기 자리로 날아감. - 초보자 도움말: "규칙 보기"에 그림으로 도~모, 지름길(모서리·방에 멈추면 꺾임), 업기, 잡기 설명. 힌트 옵션을 켜면 추천 수(8.5 우선순위)를 연하게 표시. @@ -237,6 +266,7 @@ interface YutResult { - [ ] 정보 유출: View JSON에 `rng`, 시드, 다음 결과가 없음(직렬화 스냅샷 테스트). - [ ] 결정성: 같은 시드 + 같은 액션 열 → 같은 최종 State(리플레이 테스트). - [ ] 옵션 검증: 개인전 5명, 팀전 5명 거부. +- [x] 지역 룰(7.1): 기본값은 예전 동작 그대로. `backdoNoPiece` 버림/다시 던지기/날윷, `nakRule` 차례 끝, `useOrder` 던진 순서(맨 앞 결과만, 못 쓰면 그것만 버림), `stacking` 따로 두기(따로 움직임, 함께 잡힘, 다시 업으면 합쳐짐), `forkRule` 다른 길(모·뒷모 바깥 길, 방 → 속윷, 빽도는 기록대로), 각 옵션 검증 문구. 무작위 대국 테스트에 지역 룰 조합 5개 추가. ## 11. 참고 자료 - 나무위키 "윷놀이": https://namu.wiki/w/윷놀이 (가락 확률 모델, 빽도·낙·업기·잡기·지름길·참먹이 규칙과 지역 차이) diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index 01ff283..924e5ac 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -129,6 +129,7 @@ async function rummikubTurns(pages: Page[], turns: number) { * 윷놀이: one UI step for whoever can act on `p` — press the throw button, or pick a result chip → * a glowing piece (or the waiting-piece tray) → "이동하기" (the two-step move confirmation). */ +const yutChoiceSeen = new Set(); async function yutStep(p: Page): Promise { const throwBtn = p.getByRole('button', { name: /윷 던지기|한 번 더 던지기/ }); if ((await throwBtn.count()) && (await throwBtn.isEnabled().catch(() => false))) { @@ -145,8 +146,24 @@ async function yutStep(p: Page): Promise { await h!.focus(); await p.keyboard.press('Enter'); await p.getByRole('button', { name: /^이동하기/ }).waitFor({ timeout: 1500 }); + // 지역 룰 choices (갈 길 고르기 / 따로 두기): the first time each shows up, take the other option and save a picture. + let apart = false; + for (const [group, tag] of [['갈 길 고르기', 'road'], ['업을지 따로 둘지 고르기', 'apart']] as const) { + const g = p.getByRole('group', { name: group }); + if (yutChoiceSeen.has(tag) || !(await g.count())) continue; + yutChoiceSeen.add(tag); + apart ||= tag === 'apart'; + await g.getByRole('button').nth(1).click(); + await p.waitForTimeout(150); + await p.screenshot({ path: join(SHOTS, `yut-choice-${tag}-${p.viewportSize()!.width < 600 ? 'phone' : 'pc'}.png`), fullPage: p.viewportSize()!.width < 600 }); + } await h!.focus(); await p.keyboard.press('Enter'); + if (apart) { + // Two stacks of the same side standing apart on one node are drawn side by side. + await p.waitForTimeout(1200); + await p.locator('.yut-board').screenshot({ path: join(SHOTS, 'yut-apart-board.png') }); + } return true; } catch { return false; @@ -1142,10 +1159,37 @@ const PLANS: Record = { }, }, yut: { - // 말 2개로 줄여서 PC 방장 + 휴대폰 친구가 실제 화면 조작으로 끝까지 둔다(중간 화면도 저장). + // 말 2개로 줄이고 지역 룰(업기 고르기·갈림길 고르기)을 켠 뒤, PC 방장 + 휴대폰 친구가 실제 화면 조작으로 끝까지 둔다. + // 옵션 화면(PC 방장 / 휴대폰 친구 보기 전용 320px·다크)과 중간 화면도 저장. lobby: async (host) => { await host.getByRole('button', { name: '2개', exact: true }).click(); await host.getByText(/말 2개/).first().waitFor(); + await host.getByRole('button', { name: /지역 룰/ }).click(); + await host.getByRole('button', { name: '업을지 고르기' }).click(); + await host.getByRole('button', { name: '갈 길 고르기' }).click(); + await host.getByText(/업기 고르기 · 갈림길 고르기/).first().waitFor(); + await host.locator('#yut-house-rules').scrollIntoViewIfNeeded(); + await host.screenshot({ path: join(SHOTS, 'yut-options-pc.png') }); + // The phone friend only sees the options (read-only), but can open the 지역 룰 box. + const guest = host.context().browser()!.contexts()[1]!.pages()[0]!; + await guest.getByText(/업기 고르기 · 갈림길 고르기/).first().waitFor(); + await guest.getByRole('button', { name: '설정 보기' }).click(); + const sheet = guest.getByRole('dialog', { name: '게임 설정' }); + await sheet.getByRole('button', { name: /지역 룰/ }).click(); + if (await sheet.getByRole('button', { name: '업을지 고르기' }).isEnabled()) throw new Error('guest can change options'); + await guest.screenshot({ path: join(SHOTS, 'yut-options-phone.png') }); + await guest.setViewportSize({ width: 320, height: 640 }); + await guest.emulateMedia({ colorScheme: 'dark' }); + await sheet.getByText('말 움직이기').scrollIntoViewIfNeeded(); + await guest.screenshot({ path: join(SHOTS, 'yut-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]; @@ -1175,7 +1219,7 @@ const PLANS: Record = { } if (!(await over())) throw new Error(`game did not finish (${actions} UI actions)`); await guest.getByText(/이겼어요|아쉽게 졌어요/).waitFor(); - console.log(` yut: finished after ${actions} UI actions`); + console.log(` yut: finished after ${actions} UI actions (지역 룰 choices used: ${[...yutChoiceSeen].join(', ') || 'none'})`); }, }, 'one-card': { diff --git a/packages/games/src/yut/board.ts b/packages/games/src/yut/board.ts index 225cd67..f3c6073 100644 --- a/packages/games/src/yut/board.ts +++ b/packages/games/src/yut/board.ts @@ -23,14 +23,21 @@ export const THROW_KO: Record = { do: '도', gae: '개', geol: ' /** Display order of the result chips. */ export const THROW_ORDER: Throw[] = ['backdo', 'do', 'gae', 'geol', 'yut', 'mo']; +/** Nodes where a piece that stopped there has two roads ahead: 모, 뒷모, 방. */ +export const FORKS: readonly NodeId[] = [5, 10, 22]; +export const isFork = (n: NodeId | 'home'): boolean => n === 5 || n === 10 || n === 22; + /** * One step forward (§5.2 table). `starting` = this step leaves the node the piece stood on, * `prev` = the node passed just before `node` within the same move (only matters at 방). + * `alt` (지역 룰 `forkRule = choose`): when starting on a fork, take the other road — 모/뒷모 keep to the outer ring, + * 방 goes on toward 찌모 (23). * Returns GOAL when the piece leaves 참먹이 after a lap. */ -export function step(node: NodeId | 'home', starting: boolean, prev: NodeId | null): NodeId | typeof GOAL { +export function step(node: NodeId | 'home', starting: boolean, prev: NodeId | null, alt = false): NodeId | typeof GOAL { if (node === 'home') return 1; if (node === 0) return GOAL; + if (starting && alt && isFork(node)) return node === 22 ? 23 : node + 1; if (starting) { if (node === 5) return 20; if (node === 10) return 25; @@ -61,14 +68,15 @@ export interface Advance { /** * Moves `n` (≥ 1) steps forward from `from`. Reaching GOAL drops the remaining steps. + * `alt`: take the other road at the starting fork (see `step`). * With `reach`, arriving at 참먹이 after a lap (always the case when entering 0 by moving forward) finishes at once. */ -export function advance(from: NodeId | 'home', n: number, finishRule: 'pass' | 'reach'): Advance { +export function advance(from: NodeId | 'home', n: number, finishRule: 'pass' | 'reach', alt = false): Advance { let cur: NodeId | 'home' = from; let prev: NodeId | null = null; const path: NodeId[] = []; for (let i = 0; i < n; i++) { - const nxt = step(cur, i === 0, prev); + const nxt = step(cur, i === 0, prev, alt && i === 0); if (nxt === GOAL) return { path, to: GOAL }; path.push(nxt); prev = cur === 'home' ? null : cur; diff --git a/packages/games/src/yut/bot.test.ts b/packages/games/src/yut/bot.test.ts index 34b9f0e..9284ec8 100644 --- a/packages/games/src/yut/bot.test.ts +++ b/packages/games/src/yut/bot.test.ts @@ -51,6 +51,37 @@ describe('yut bot', () => { expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 0, from: 7 }); }); + test('지역 룰 forkRule = choose: takes the other road from 모 when it catches an enemy there', () => { + const s = moving(['gae'], { forkRule: 'choose' }); + put(s, 0, 0, 5, [1, 2, 3, 4, 5]); + put(s, 1, 0, 7, [6, 7]); + expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 0, from: 5, alt: true }); + // Nothing to catch: the shortcut is better. + const t = moving(['gae'], { forkRule: 'choose' }); + put(t, 0, 0, 5, [1, 2, 3, 4, 5]); + expect(decide(t)).toEqual({ type: 'MOVE', throwIndex: 0, from: 5 }); + }); + + test('지역 룰 stacking = choose: stacks when it may, and moves stacks standing apart one by one', () => { + const s = moving(['geol'], { stacking: 'choose' }); + put(s, 0, 0, 3, [1, 2, 3]); + put(s, 1, 0, 15, [15]); + expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 0, from: 'home' }); + const a = moving(['gae'], { stacking: 'choose' }); + put(a, 0, 0, 3, [1, 2, 3]); + put(a, 0, 1, 3, [2, 3]); + a.sides[0]!.pieces[1]!.group = 1; + put(a, 1, 0, 5, [1, 2, 3, 4, 5]); + const d = decide(a) as { type: string; from: unknown; piece?: number }; + // Either stack on 3 catches the enemy on 5; the action names which one. + expect([d.type, d.from, typeof d.piece]).toEqual(['MOVE', 3, 'number']); + }); + + test('지역 룰 backdoNoPiece = enter: puts a new piece on 날윷 with 빽도 instead of crawling in with 개', () => { + const s = moving(['gae', 'backdo'], { backdoNoPiece: 'enter' }); + expect(decide(s)).toEqual({ type: 'MOVE', throwIndex: 1, from: 'home' }); + }); + test('beats a random player clearly in 1-on-1', () => { let wins = 0; const games = 20; @@ -75,6 +106,9 @@ describe('yut bot', () => { [{ mode: 'team' as const, pieces: 2 as const }, 6], [{ finishRule: 'reach' as const, backdoFromDo: 'finish' as const, nakPercent: 10 as const, stickModel: 'fair' as const }, 3], [{ ranking: 'all' as const, backdo: false }, 4], + [{ stacking: 'choose' as const, forkRule: 'choose' as const, backdoNoPiece: 'enter' as const }, 2], + [{ useOrder: 'thrown' as const, backdoNoPiece: 'rethrow' as const, nakPercent: 10 as const, nakRule: 'lose' as const }, 3], + [{ mode: 'team' as const, stacking: 'choose' as const, forkRule: 'choose' as const, useOrder: 'thrown' as const }, 4], ] as const) { test(`option mode ${JSON.stringify(opts)} with ${n} players finishes`, () => { const options = yut.optionsSchema.parse(opts); diff --git a/packages/games/src/yut/bot.ts b/packages/games/src/yut/bot.ts index 92a1d3f..23a97b0 100644 --- a/packages/games/src/yut/bot.ts +++ b/packages/games/src/yut/bot.ts @@ -25,6 +25,8 @@ export const yutBot: BotStrategy = ({ view, legal, random }) const live = new Set(view.sides.filter((x) => x.id !== me && !x.out && x.finishedRank === null).map((x) => x.id)); const enemyStacks = view.stacks.filter((st) => live.has(st.side)); const enemyHome = view.sides.some((x) => live.has(x.id) && x.home > 0); + // 지역 룰 backdoNoPiece = enter: an enemy with nothing on the board may put a piece on 날윷(19) with 빽도. + const enemyBackdoEnter = o.backdo && o.backdoNoPiece === 'enter' && view.sides.some((x) => live.has(x.id) && x.home > 0 && x.onBoard === 0); /** Chance that some enemy can land on `node` with its next throw (bonus throws ignored). */ const risk = (node: NodeId): number => { @@ -32,12 +34,14 @@ export const yutBot: BotStrategy = ({ view, legal, random }) for (const t of THROWS) { const hits = (t !== 'backdo' && enemyHome && advance('home', THROW_STEPS[t], o.finishRule).to === node) || + (t === 'backdo' && enemyBackdoEnter && node === 19) || enemyStacks.some((st) => (t === 'backdo' ? defaultPrev(st.node) === node : advance(st.node, THROW_STEPS[t], o.finishRule).to === node)); if (hits) p += odds[t]; } return Math.min(1, p); }; - const mineAt = (node: NodeId) => view.stacks.find((st) => st.side === me && st.node === node)?.count ?? 0; + /** Own pieces on `node` (several stacks may share it apart under `stacking = choose`). */ + const mineAt = (node: NodeId) => view.stacks.filter((st) => st.side === me && st.node === node).reduce((a, st) => a + st.count, 0); /** What losing `n` own pieces standing on `node` would cost. */ const exposure = (node: NodeId, n: number) => STEP * n * (home - dist(node)) + 10; @@ -47,15 +51,18 @@ export const yutBot: BotStrategy = ({ view, legal, random }) if (m.finishes) return v + 15 * m.count; const to = m.to as NodeId; if (m.captures) v += 30 + m.captures * (STEP * (home - dist(to)) + 10); - const group = m.count + (m.stacks ? mineAt(to) : 0); + // Standing apart still shares the node, so a catch there takes everything; only stacking earns the small bonus. + const group = m.count + (m.stacks || m.stack === false ? mineAt(to) : 0); if (m.stacks) v += 6; // After a capture we throw again first, so the danger matters less. v -= (m.captures ? 0.5 : 1) * risk(to) * exposure(to, group); return v; }; - const byKey = new Map(view.legalMoves.map((m) => [`${m.throwIndex}:${m.from}`, m])); + const key = (x: { throwIndex: number; from: NodeId | 'home'; piece?: number; alt?: boolean; stack?: boolean }) => + `${x.throwIndex}:${x.from}:${x.piece ?? ''}:${x.alt ? 1 : 0}:${x.stack === false ? 0 : 1}`; + const byKey = new Map(view.legalMoves.map((m) => [key(m), m])); return best(moves, (a) => { - const m = byKey.get(`${a.throwIndex}:${a.from}`); + const m = byKey.get(key(a)); return m ? score(m) : -1e9; }, random); }; diff --git a/packages/games/src/yut/index.ts b/packages/games/src/yut/index.ts index c3e3d23..5676df5 100644 --- a/packages/games/src/yut/index.ts +++ b/packages/games/src/yut/index.ts @@ -7,6 +7,7 @@ import { THROW_STEPS, advance, defaultPrev, + isFork, remainingDistance, rollSticks, type NodeId, @@ -49,6 +50,30 @@ export const yutOptionsSchema = z.object({ .enum(['first', 'all']) .default('first') .meta({ title: '3~4명 개인전에서 1등이 나오면', labels: { first: '바로 끝(나머지는 진행도로 순위)', all: '꼴찌가 정해질 때까지 계속' } }), + // ---- 지역 룰 (docs/games/yut.md §7). Defaults keep the original rules. + backdoNoPiece: z + .enum(['discard', 'rethrow', 'enter']) + .default('discard') + .meta({ + title: '판에 내 말이 없을 때 빽도가 나오면', + labels: { discard: '쓸 곳이 없어 버림', rethrow: '다시 던짐', enter: '새 말이 참먹이 뒤(날윷)로 감' }, + }), + nakRule: z + .enum(['keep', 'lose']) + .default('keep') + .meta({ title: '낙이 나오면', labels: { keep: '그 던지기만 무효(모아 둔 결과는 남음)', lose: '차례가 끝남(모아 둔 결과도 버림)' } }), + useOrder: z + .enum(['free', 'thrown']) + .default('free') + .meta({ title: '모아 둔 결과를 쓰는 순서', labels: { free: '원하는 순서로', thrown: '던진 순서대로' } }), + stacking: z + .enum(['always', 'choose']) + .default('always') + .meta({ title: '내 말이 있는 자리에 멈추면', labels: { always: '무조건 업음', choose: '업을지 따로 둘지 고름' } }), + forkRule: z + .enum(['shortcut', 'choose']) + .default('shortcut') + .meta({ title: '모서리·방에 멈췄다가 출발할 때', labels: { shortcut: '늘 지름길(방에서는 참먹이 쪽)', choose: '갈 길을 고름' } }), turnSeconds: z .union([z.literal(15), z.literal(30), z.literal(60), z.literal(null)]) .default(30) @@ -62,6 +87,12 @@ export const yutActionSchema = z.discriminatedUnion('type', [ 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(), + /** 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') }), ]); @@ -82,6 +113,11 @@ export interface Piece { lapped: boolean; /** Nodes visited since entering the board, current node last (for 빽도). Shared by a stack. */ trail: NodeId[]; + /** + * Stack key when own pieces share a node without being stacked (`stacking = choose`): the lowest piece id of + * that stack. Absent = the node's ordinary stack. Pieces on one node with the same key move together. + */ + group?: number; } export interface SideState { @@ -108,6 +144,10 @@ export interface YutMoveInfo { count: number; captured: { side: SideId; count: number }[]; stacked: boolean; + /** Took the other road at the fork (`forkRule = choose`). */ + alt?: boolean; + /** Stopped on own pieces without stacking (`stacking = choose`). */ + apart?: boolean; } export interface YutStats { @@ -174,6 +214,10 @@ export interface YutLegalMove { captures: number; stacks: boolean; finishes: boolean; + /** Action fields that pick this variant (see the MOVE schema); absent for the ordinary move. */ + piece?: number; + alt?: boolean; + stack?: false; } export interface YutSideView { @@ -193,6 +237,8 @@ export interface YutStackView { node: NodeId; side: SideId; count: number; + /** Lowest piece id of the stack, only when one node holds several stacks of this side apart (`stacking = choose`). */ + piece?: number; } export interface YutView { @@ -215,7 +261,7 @@ export interface YutView { /** Only for the player to move (null otherwise). */ legalMoves: YutLegalMove[] | null; /** The move a timeout would play (§8.5), for the player to move. */ - suggested: { throwIndex: number; from: NodeId | 'home' } | null; + suggested: Omit | null; log: GameEvent[]; stats: YutStats; result: YutResult | null; @@ -272,6 +318,36 @@ function pushLog(s: YutState, events: GameEvent[], e: GameEvent): void { if (s.log.length > LOG_MAX) s.log.splice(0, s.log.length - LOG_MAX); } +/** Pieces of one stack share node and key; `group` is only set while own stacks share a node apart (`stacking = choose`). */ +const groupKey = (p: Piece) => p.group ?? -1; + +function clearPiece(p: Piece, status: 'home' | 'done'): void { + Object.assign(p, { status, node: null, lapped: false, trail: [] }); + delete p.group; +} + +/** Own stacks on the board, by node then lowest piece id; `ids` ascending. */ +function stacksOf(x: SideState): { node: NodeId; ids: number[] }[] { + const byKey = new Map(); + for (const p of [...x.pieces].sort((a, b) => a.id - b.id)) { + if (p.status !== 'board') continue; + const k = `${p.node}:${groupKey(p)}`; + const g = byKey.get(k); + if (g) g.ids.push(p.id); + else byKey.set(k, { node: p.node!, ids: [p.id] }); + } + return [...byKey.values()].sort((a, b) => a.node - b.node || a.ids[0]! - b.ids[0]!); +} + +/** A 빽도 that could never be used this turn: no own piece on the board and no forward result to bring one on. */ +function backdoUseless(s: YutState): boolean { + const side = s.sides[s.turnSide]!; + return !side.pieces.some((p) => p.status === 'board') && !s.pending.some((t) => t !== 'backdo'); +} + +/** Variant fields of a MOVE (see the action schema). */ +type MoveSel = Pick; + interface Plan { throwIndex: number; throw: Throw; @@ -282,29 +358,46 @@ interface Plan { trailAfter: NodeId[]; victims: { side: SideId; ids: number[] }[]; stackWith: number[]; + /** Action selector for the stack on `from` (only when that node holds several own stacks). */ + piece?: number; + alt: boolean; + /** Stops on own pieces but stays apart. */ + apart: boolean; } /** Where `from` would go with `pending[throwIndex]`; null if that is not a legal move. */ -function planMove(s: YutState, sideId: SideId, throwIndex: number, from: NodeId | 'home'): Plan | null { +function planMove(s: YutState, sideId: SideId, throwIndex: number, from: NodeId | 'home', sel: MoveSel = {}): Plan | null { const t = s.pending[throwIndex]; const side = s.sides[sideId]; if (!t || !side) return null; const o = s.options; + const alt = sel.alt === true; + if (alt && (o.forkRule !== 'choose' || from === 'home' || !isFork(from) || t === 'backdo')) return null; let movers: Piece[]; let to: NodeId | typeof GOAL; let path: NodeId[]; let trailAfter: NodeId[]; if (from === 'home') { - if (t === 'backdo') return null; const p = side.pieces.find((x) => x.status === 'home'); if (!p) return null; movers = [p]; - const adv = advance('home', THROW_STEPS[t], o.finishRule); - ({ to, path } = adv); - trailAfter = to === GOAL ? [] : [...path]; + if (t === 'backdo') { + // 지역 룰: with no own piece on the board, a 빽도 puts a new piece one step behind 참먹이 (날윷). + if (o.backdoNoPiece !== 'enter' || side.pieces.some((x) => x.status === 'board')) return null; + to = 19; + path = [19]; + trailAfter = [19]; + } else { + const adv = advance('home', THROW_STEPS[t], o.finishRule); + ({ to, path } = adv); + trailAfter = to === GOAL ? [] : [...path]; + } } else { - movers = side.pieces.filter((x) => x.status === 'board' && x.node === from); - if (movers.length === 0) return null; + const here = side.pieces.filter((x) => x.status === 'board' && x.node === from); + if (here.length === 0) return null; + const lead = sel.piece === undefined ? here.reduce((a, b) => (b.id < a.id ? b : a)) : here.find((x) => x.id === sel.piece); + if (!lead) return null; + movers = here.filter((x) => groupKey(x) === groupKey(lead)); const trail = movers[0]!.trail; if (t === 'backdo') { if (trail.length >= 2) { @@ -319,7 +412,7 @@ function planMove(s: YutState, sideId: SideId, throwIndex: number, from: NodeId } path = to === GOAL ? [] : [to]; } else { - const adv = advance(from, THROW_STEPS[t], o.finishRule); + const adv = advance(from, THROW_STEPS[t], o.finishRule, alt); ({ to, path } = adv); trailAfter = to === GOAL ? [] : [...trail, ...path]; } @@ -334,28 +427,70 @@ function planMove(s: YutState, sideId: SideId, throwIndex: number, from: NodeId else victims.push({ side: x.id, ids: here }); } } - return { throwIndex, throw: t, from, to, path, movers: movers.map((p) => p.id), trailAfter, victims, stackWith }; + const apart = sel.stack === false; + if (apart && (o.stacking !== 'choose' || stackWith.length === 0)) return null; + return { + throwIndex, + throw: t, + from, + to, + path, + movers: movers.map((p) => p.id), + trailAfter, + victims, + stackWith: apart ? [] : stackWith, + ...(sel.piece !== undefined ? { piece: sel.piece } : {}), + alt, + apart, + }; } -/** Legal moves of the side to move. Equal results are listed once (first index). Order: index, node, 'home' last. */ +/** + * Legal moves of the side to move. Equal results are listed once (first index; with `useOrder = thrown` only the + * first result). Order: index, stack (node, then lowest id), 'home' last; per source the ordinary move first, then + * "apart", the other road, other road + apart. + */ function legalPlans(s: YutState): Plan[] { if (s.phase !== 'move') return []; + const o = s.options; const side = s.sides[s.turnSide]!; - const sources: (NodeId | 'home')[] = [...new Set(side.pieces.filter((p) => p.status === 'board').map((p) => p.node!))].sort((a, b) => a - b); - if (side.pieces.some((p) => p.status === 'home')) sources.push('home'); + const stacks = stacksOf(side); + const sources: { from: NodeId | 'home'; piece?: number }[] = stacks.map((g) => + stacks.filter((h) => h.node === g.node).length > 1 ? { from: g.node, piece: g.ids[0]! } : { from: g.node }, + ); + if (side.pieces.some((p) => p.status === 'home')) sources.push({ from: 'home' }); const out: Plan[] = []; const seen = new Set(); - s.pending.forEach((t, i) => { + const indices = o.useOrder === 'thrown' ? s.pending.slice(0, 1) : s.pending; + indices.forEach((t, i) => { if (seen.has(t)) return; seen.add(t); - for (const from of sources) { - const p = planMove(s, s.turnSide, i, from); - if (p) out.push(p); + for (const src of sources) { + const roads = o.forkRule === 'choose' && src.from !== 'home' && isFork(src.from) && t !== 'backdo' ? [false, true] : [false]; + for (const alt of roads) { + const sel: MoveSel = { ...(src.piece !== undefined ? { piece: src.piece } : {}), ...(alt ? { alt } : {}) }; + const p = planMove(s, s.turnSide, i, src.from, sel); + if (!p) continue; + out.push(p); + if (o.stacking === 'choose' && p.stackWith.length) out.push(planMove(s, s.turnSide, i, src.from, { ...sel, stack: false })!); + } } }); return out; } +/** The MOVE action that plays `p`. */ +function planAction(p: Plan): YutMoveAction { + return { + type: 'MOVE', + throwIndex: p.throwIndex, + from: p.from, + ...(p.piece !== undefined ? { piece: p.piece } : {}), + ...(p.alt ? { alt: true } : {}), + ...(p.apart ? { stack: false } : {}), + }; +} + const toLegal = (p: Plan): YutLegalMove => ({ throwIndex: p.throwIndex, throw: p.throw, @@ -366,14 +501,23 @@ const toLegal = (p: Plan): YutLegalMove => ({ captures: p.victims.reduce((a, v) => a + v.ids.length, 0), stacks: p.stackWith.length > 0, finishes: p.to === GOAL, + ...(p.piece !== undefined ? { piece: p.piece } : {}), + ...(p.alt ? { alt: true } : {}), + ...(p.apart ? { stack: false as const } : {}), }); /** Deterministic auto move (§8.5): capture > finish > stack > most-behind piece with the biggest result > enter > rest. */ function chooseAuto(s: YutState, plans: Plan[]): Plan { const rule = s.options.finishRule; const side = s.sides[s.turnSide]!; + const flag = (x: boolean) => (x ? 1 : 0); const byTie = (a: Plan, b: Plan) => - a.throwIndex - b.throwIndex || (a.from === 'home' ? 1 : 0) - (b.from === 'home' ? 1 : 0) || (a.from === 'home' ? 0 : a.from) - (b.from === 'home' ? 0 : (b.from as number)); + a.throwIndex - b.throwIndex || + flag(a.from === 'home') - flag(b.from === 'home') || + (a.from === 'home' ? 0 : a.from) - (b.from === 'home' ? 0 : (b.from as number)) || + (a.piece ?? -1) - (b.piece ?? -1) || + flag(a.alt) - flag(b.alt) || + flag(a.apart) - flag(b.apart); const pick = (list: Plan[], cmp: (a: Plan, b: Plan) => number) => [...list].sort((a, b) => cmp(a, b) || byTie(a, b))[0]; const caps = plans.filter((p) => p.victims.length > 0); if (caps.length) return pick(caps, (a, b) => toLegal(b).captures - toLegal(a).captures)!; @@ -394,8 +538,7 @@ export function autoAction(s: YutState): Exclude if (s.phase !== 'move') return { type: 'THROW' }; const plans = legalPlans(s); if (plans.length === 0) return { type: 'THROW' }; // unreachable: stuck results are discarded right away - const p = chooseAuto(s, plans); - return { type: 'MOVE', throwIndex: p.throwIndex, from: p.from }; + return planAction(chooseAuto(s, plans)); } // ---------------------------------------------------------------- transitions @@ -482,9 +625,15 @@ function finishGame(s: YutState, events: GameEvent[]): void { pushLog(s, events, { type: 'gameOver', winners, summary }); } -/** In the move phase: if no pending result can be used, discard them all and end the turn (§5.3-2). */ +/** + * In the move phase: if no pending result can be used, discard them all and end the turn (§5.3-2). + * With `useOrder = thrown` only the first result counts: an unusable first result is dropped and the next one is tried. + */ function settleMovePhase(s: YutState, events: GameEvent[]): void { if (s.phase !== 'move') return; + if (s.options.useOrder === 'thrown') { + while (s.pending.length && legalPlans(s).length === 0) pushLog(s, events, { type: 'discarded', side: s.turnSide, player: s.current, throws: s.pending.splice(0, 1) }); + } if (s.pending.length === 0) { endTurn(s, events); return; @@ -501,8 +650,22 @@ function doThrow(s: YutState, rng: Rng, events: GameEvent[]): void { s.stats.throws[r.result] += 1; s.lastThrow = { no: s.throwNo, player: s.current, sticks: r.sticks, result: r.result }; s.throwsOwed -= 1; + if (r.result === 'nak' && s.options.nakRule === 'lose') { + // 지역 룰: a 낙 ends the turn and every unused result of this turn is lost. + pushLog(s, events, { type: 'nak', side: s.turnSide, player: s.current, endsTurn: true }); + if (s.pending.length) pushLog(s, events, { type: 'discarded', side: s.turnSide, player: s.current, throws: [...s.pending] }); + s.pending = []; + s.throwsOwed = 0; + endTurn(s, events); + return; + } if (r.result === 'nak') { pushLog(s, events, { type: 'nak', side: s.turnSide, player: s.current }); + } else if (r.result === 'backdo' && s.options.backdoNoPiece === 'rethrow' && backdoUseless(s)) { + // 지역 룰: a 빽도 that could not be used is not kept; throw again. + pushLog(s, events, { type: 'thrown', side: s.turnSide, player: s.current, sticks: r.sticks, result: r.result }); + pushLog(s, events, { type: 'backdoRethrow', side: s.turnSide, player: s.current }); + s.throwsOwed += 1; } else { s.pending.push(r.result); if (r.result === 'yut' || r.result === 'mo') s.throwsOwed += 1; @@ -513,20 +676,30 @@ function doThrow(s: YutState, rng: Rng, events: GameEvent[]): void { settleMovePhase(s, events); } -function doMove(s: YutState, throwIndex: number, from: NodeId | 'home', events: GameEvent[]): void { - const plan = planMove(s, s.turnSide, throwIndex, from); - if (!plan) throw new Error(`yut: illegal move ${throwIndex} ${from}`); +function doMove(s: YutState, a: YutMoveAction, events: GameEvent[]): void { + const plan = planMove(s, s.turnSide, a.throwIndex, a.from, a); + if (!plan) throw new Error(`yut: illegal move ${a.throwIndex} ${a.from}`); const side = s.sides[s.turnSide]!; - s.pending.splice(throwIndex, 1); + s.pending.splice(a.throwIndex, 1); const movers = side.pieces.filter((p) => plan.movers.includes(p.id)); + const lead = Math.min(...plan.movers); for (const p of movers) { - if (plan.to === GOAL) Object.assign(p, { status: 'done', node: null, lapped: false, trail: [] }); - else Object.assign(p, { status: 'board', node: plan.to, lapped: plan.to === 0, trail: [...plan.trailAfter] }); + if (plan.to === GOAL) clearPiece(p, 'done'); + else { + Object.assign(p, { status: 'board', node: plan.to, lapped: plan.to === 0, trail: [...plan.trailAfter] }); + // Standing apart next to own pieces keeps a key of its own; otherwise it is the node's ordinary stack. + if (plan.apart) p.group = lead; + else delete p.group; + } + } + for (const p of side.pieces) { + if (!plan.stackWith.includes(p.id)) continue; + Object.assign(p, { lapped: plan.to === 0, trail: [...plan.trailAfter] }); + delete p.group; } - for (const p of side.pieces) if (plan.stackWith.includes(p.id)) Object.assign(p, { lapped: plan.to === 0, trail: [...plan.trailAfter] }); let caught = 0; for (const v of plan.victims) { - for (const p of s.sides[v.side]!.pieces) if (v.ids.includes(p.id)) Object.assign(p, { status: 'home', node: null, lapped: false, trail: [] }); + for (const p of s.sides[v.side]!.pieces) if (v.ids.includes(p.id)) clearPiece(p, 'home'); caught += v.ids.length; } s.moveNo += 1; @@ -541,8 +714,21 @@ function doMove(s: YutState, throwIndex: number, from: NodeId | 'home', events: count: movers.length, captured: plan.victims.map((v) => ({ side: v.side, count: v.ids.length })), stacked: plan.stackWith.length > 0, + ...(plan.alt ? { alt: true } : {}), + ...(plan.apart ? { apart: true } : {}), }; - pushLog(s, events, { type: 'moved', side: side.id, player: s.current, throw: plan.throw, from: plan.from, to: plan.to, path: plan.path, count: movers.length }); + pushLog(s, events, { + type: 'moved', + side: side.id, + player: s.current, + throw: plan.throw, + from: plan.from, + to: plan.to, + path: plan.path, + count: movers.length, + ...(plan.alt ? { alt: true } : {}), + ...(plan.apart ? { apart: true } : {}), + }); if (plan.stackWith.length) pushLog(s, events, { type: 'stacked', side: side.id, node: plan.to, count: movers.length + plan.stackWith.length }); for (const v of plan.victims) pushLog(s, events, { type: 'captured', side: side.id, victimSide: v.side, count: v.ids.length, node: plan.to }); if (caught) s.stats.captures[String(side.id)] = (s.stats.captures[String(side.id)] ?? 0) + 1; @@ -586,7 +772,7 @@ function doConcede(s: YutState, actor: PlayerId, events: GameEvent[]): void { } side.out = true; side.outSeq = ++s.outCount; - for (const p of side.pieces) if (p.status === 'board') Object.assign(p, { status: 'home', node: null, lapped: false, trail: [] }); + for (const p of side.pieces) if (p.status === 'board') clearPiece(p, 'home'); if (gameShouldEnd(s)) { finishGame(s, events); return; @@ -694,13 +880,27 @@ export const yut: GameDefinition = { if (s.phase !== 'move') return fail('지금은 말을 움직일 차례가 아니에요. 먼저 윷을 던져 주세요.'); const t = s.pending[a.throwIndex]; if (!t) return fail('그 윷 결과는 없어요.'); + const o = s.options; + if (o.useOrder === 'thrown' && a.throwIndex !== 0) return fail('이 방은 던진 순서대로 써요. 맨 앞의 결과부터 써 주세요.'); if (a.from === 'home') { - if (t === 'backdo') return fail('빽도로는 새 말을 올릴 수 없어요.'); if (!side.pieces.some((p) => p.status === 'home')) return fail('기다리는 말이 없어요.'); - } else if (!side.pieces.some((p) => p.status === 'board' && p.node === a.from)) { + if (t === 'backdo') { + if (o.backdoNoPiece !== 'enter') return fail('빽도로는 새 말을 올릴 수 없어요.'); + if (side.pieces.some((p) => p.status === 'board')) return fail('판에 내 말이 있으면 빽도는 판 위의 말에 써야 해요.'); + } + } else if (!side.pieces.some((p) => p.status === 'board' && p.node === a.from && (a.piece === undefined || p.id === a.piece))) { return fail('그 말은 움직일 수 없어요.'); } - return planMove(s, sideId, a.throwIndex, a.from) ? ok : fail('그 말은 움직일 수 없어요.'); + if (a.alt) { + if (o.forkRule !== 'choose') return fail('이 방은 갈 길을 고르지 않아요. 모서리·방에 멈췄던 말은 늘 지름길로 가요.'); + if (a.from === 'home' || !isFork(a.from) || t === 'backdo') return fail('모서리나 방에 멈춰 있던 말이 앞으로 갈 때만 길을 고를 수 있어요.'); + } + if (a.stack === false) { + if (o.stacking !== 'choose') return fail('이 방은 내 말이 있는 자리에 멈추면 무조건 업어요.'); + const plain = planMove(s, sideId, a.throwIndex, a.from, { ...a, stack: undefined }); + if (plain && plain.stackWith.length === 0) return fail('그 자리에는 업을 내 말이 없어요.'); + } + return planMove(s, sideId, a.throwIndex, a.from, a) ? ok : fail('그 말은 움직일 수 없어요.'); } } return fail('알 수 없는 행동이에요.'); @@ -721,7 +921,7 @@ export const yut: GameDefinition = { doThrow(s, rng, events); break; case 'MOVE': - doMove(s, act.throwIndex, act.from, events); + doMove(s, act, events); break; case 'CONCEDE': doConcede(s, actor, events); @@ -736,11 +936,13 @@ export const yut: GameDefinition = { const mySide = viewer !== null && s.sideOf[viewer] !== undefined ? s.sideOf[viewer]! : null; const stacks: YutStackView[] = []; for (const x of s.sides) { - const byNode = new Map(); - for (const p of x.pieces) if (p.status === 'board') byNode.set(p.node!, (byNode.get(p.node!) ?? 0) + 1); - for (const [node, count] of byNode) stacks.push({ node, side: x.id, count }); + const own = stacksOf(x); + for (const g of own) { + const apart = own.filter((h) => h.node === g.node).length > 1; + stacks.push({ node: g.node, side: x.id, count: g.ids.length, ...(apart ? { piece: g.ids[0]! } : {}) }); + } } - stacks.sort((a, b) => a.node - b.node); + 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 auto = mine && plans.length ? chooseAuto(s, plans) : null; @@ -773,7 +975,7 @@ export const yut: GameDefinition = { deadlineAt: s.deadlineAt, away: s.players.filter((p) => (s.timeouts[p] ?? 0) >= AWAY_AFTER), legalMoves: mine ? plans.map(toLegal) : null, - suggested: auto ? { throwIndex: auto.throwIndex, from: auto.from } : null, + suggested: auto ? (({ type: _t, ...rest }) => rest)(planAction(auto)) : null, log: s.log, stats: s.stats, result: s.final, @@ -824,7 +1026,7 @@ export const yut: GameDefinition = { legalActions(s, p) { if (s.phase === 'finished' || p !== s.current) return []; if (s.phase === 'throw') return [{ type: 'THROW' }]; - return legalPlans(s).map((x) => ({ type: 'MOVE' as const, throwIndex: x.throwIndex, from: x.from })); + return legalPlans(s).map(planAction); }, }; diff --git a/packages/games/src/yut/yut.test.ts b/packages/games/src/yut/yut.test.ts index 6a39d25..55aed8f 100644 --- a/packages/games/src/yut/yut.test.ts +++ b/packages/games/src/yut/yut.test.ts @@ -357,6 +357,194 @@ describe('던지기와 이동', () => { }); }); +// ---------------------------------------------------------------- 지역 룰 (§7) + +describe('지역 룰', () => { + test('defaults keep the original rules', () => { + expect(yut.defaultOptions).toMatchObject({ backdoNoPiece: 'discard', nakRule: 'keep', useOrder: 'free', stacking: 'always', forkRule: 'shortcut' }); + }); + + test('backdoNoPiece = rethrow: a 빽도 that could not be used is not kept and the player throws again', () => { + let s = make({ backdoNoPiece: 'rethrow' }); + const rng = script(['backdo', 'gae']); + const r = actE(s, 'A', { type: 'THROW' }, rng); + s = r.state; + expect(r.events.map((e) => e.type)).toEqual(['thrown', 'backdoRethrow']); + expect([s.current, s.phase, s.throwsOwed, s.pending, s.lastThrow?.result]).toEqual(['A', 'throw', 1, [], 'backdo']); + expect(s.stats.throws.backdo).toBe(1); + s = throwN(s, rng); + expect([s.phase, s.pending]).toEqual(['move', ['gae']]); + // With a piece on the board (or a forward result to bring one on) the 빽도 is kept as usual. + const b = make({ backdoNoPiece: 'rethrow' }); + put(b, 0, 0, 3, [1, 2, 3]); + expect(act(b, 'A', { type: 'THROW' }, script(['backdo'])).pending).toEqual(['backdo']); + const y = throwN(make({ backdoNoPiece: 'rethrow' }), script(['yut', 'backdo']), 2); + expect([y.phase, y.pending]).toEqual(['move', ['yut', 'backdo']]); + }); + + test('backdoNoPiece = enter: with nothing on the board a 빽도 puts a new piece on 날윷(19); 개 from there finishes', () => { + let s = moving(make({ backdoNoPiece: 'enter' }), ['backdo', 'gae']); + expect(yut.view(s, 'A').legalMoves!.map((m) => [m.throw, m.from, m.to])).toEqual([ + ['backdo', 'home', 19], + ['gae', 'home', 2], + ]); + s = act(s, 'A', mv(0, 'home')); + expect(piece(s, 0, 0)).toMatchObject({ status: 'board', node: 19, trail: [19], lapped: false }); + s = act(s, 'A', mv(0, 19)); + expect(piece(s, 0, 0).status).toBe('done'); + // 도 stops on 참먹이 (pass) — the piece counts as lapped there. + let d = moving(make({ backdoNoPiece: 'enter' }), ['backdo', 'do']); + d = use(use(d, 'backdo', 'home'), 'do', 19); + expect(piece(d, 0, 0)).toMatchObject({ node: 0, lapped: true }); + // Only while no own piece is on the board; an enemy on 19 is caught. + const busy = make({ backdoNoPiece: 'enter' }); + put(busy, 0, 0, 3, [1, 2, 3]); + expect(reject(moving(busy, ['backdo']), 'A', mv(0, 'home'))).toBe('판에 내 말이 있으면 빽도는 판 위의 말에 써야 해요.'); + expect(reject(moving(make(), ['backdo']), 'A', mv(0, 'home'))).toBe('빽도로는 새 말을 올릴 수 없어요.'); + const cap = make({ backdoNoPiece: 'enter' }); + put(cap, 1, 0, 19, [16, 17, 18, 19]); + const c = act(moving(cap, ['backdo']), 'A', mv(0, 'home')); + expect([piece(c, 1, 0).status, c.phase]).toEqual(['home', 'throw']); + }); + + test('nakRule = lose: a 낙 ends the turn and the collected results are lost; keep (default) keeps them', () => { + let s = make({ nakPercent: 10, nakRule: 'lose' }); + const rng = script(['yut', 'nak'], true); + s = throwN(s, rng); + const r = actE(s, 'A', { type: 'THROW' }, rng); + s = r.state; + expect(r.events.find((e) => e.type === 'nak')).toMatchObject({ endsTurn: true }); + expect(r.events.find((e) => e.type === 'discarded')).toMatchObject({ throws: ['yut'] }); + expect([s.current, s.phase, s.pending]).toEqual(['B', 'throw', []]); + // Also on a capture-bonus throw: earlier unused results go too. + let b = make({ nakPercent: 10, nakRule: 'lose' }); + put(b, 0, 0, 2, [1, 2]); + put(b, 1, 0, 4, [1, 2, 3, 4]); + b = use(moving(b, ['gae', 'geol']), 'gae', 2); + b = act(b, 'A', { type: 'THROW' }, script(['nak'], true)); + expect([b.current, b.pending]).toEqual(['B', []]); + expect(piece(b, 0, 0).node).toBe(4); + }); + + test('useOrder = thrown: only the first result can be used; an unusable first result is dropped', () => { + let s = moving(make({ useOrder: 'thrown' }), ['yut', 'mo', 'geol']); + expect(new Set(yut.legalActions!(s, 'A').map((a) => (a as { throwIndex: number }).throwIndex))).toEqual(new Set([0])); + expect(reject(s, 'A', mv(1, 'home'))).toBe('이 방은 던진 순서대로 써요. 맨 앞의 결과부터 써 주세요.'); + s = act(s, 'A', mv(0, 'home')); + expect([piece(s, 0, 0).node, s.pending]).toEqual([4, ['mo', 'geol']]); + // Free order (default) may start with 모. + expect(yut.validate(moving(make(), ['yut', 'mo', 'geol']), 'A', mv(1, 'home')).ok).toBe(true); + // [걸, 빽도, 개] with the only board piece finishing on 걸: the 빽도 has nowhere to go and is dropped, 개 stays. + let d = make({ useOrder: 'thrown' }); + put(d, 0, 0, 18, [16, 17, 18]); + const r = actE(moving(d, ['geol', 'backdo', 'gae']), 'A', mv(0, 18)); + d = r.state; + expect(piece(d, 0, 0).status).toBe('done'); + expect(r.events.find((e) => e.type === 'discarded')).toMatchObject({ throws: ['backdo'] }); + expect([d.phase, d.pending, d.current]).toEqual(['move', ['gae'], 'A']); + }); + + test('stacking = choose: stop next to own pieces apart, move each stack on its own, both get caught together', () => { + let s = make({ stacking: 'choose' }); + put(s, 0, 0, 3, [1, 2, 3]); + s = moving(s, ['geol', 'gae', 'do']); + const lm = yut.view(s, 'A').legalMoves!.filter((m) => m.throw === 'geol' && m.from === 'home'); + expect(lm.map((m) => [m.to, m.stacks, m.stack])).toEqual([ + [3, true, undefined], + [3, false, false], + ]); + s = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 'home', stack: false }); + expect(piece(s, 0, 1)).toMatchObject({ node: 3, group: 1 }); + expect(s.lastMove).toMatchObject({ stacked: false, apart: true }); + expect(yut.view(s, 'A').stacks).toEqual([ + { node: 3, side: 0, count: 1, piece: 0 }, + { node: 3, side: 0, count: 1, piece: 1 }, + ]); + const from3 = yut.legalActions!(s, 'A').filter((a) => a.type === 'MOVE' && a.from === 3); + expect(from3).toContainEqual({ type: 'MOVE', throwIndex: 0, from: 3, piece: 0 }); + expect(from3).toContainEqual({ type: 'MOVE', throwIndex: 0, from: 3, piece: 1 }); + s = act(s, 'A', { type: 'MOVE', throwIndex: 0, from: 3, piece: 1 }); // 개: only piece 1 → 5 + expect([piece(s, 0, 0).node, piece(s, 0, 1).node]).toEqual([3, 5]); + expect(piece(s, 0, 1).group).toBeUndefined(); + // Stacking onto a node that holds two stacks apart merges all of them. + let m = make({ stacking: 'choose' }); + put(m, 0, 0, 4, [1, 2, 3, 4]); + put(m, 0, 1, 4, [2, 3, 4]); + m.sides[0]!.pieces[1]!.group = 1; + put(m, 0, 2, 2, [1, 2]); + m = act(moving(m, ['gae']), 'A', mv(0, 2)); + expect(yut.view(m, 'A').stacks).toEqual([{ node: 4, side: 0, count: 3 }]); + expect(m.sides[0]!.pieces.map((p) => p.group)).toEqual([undefined, undefined, undefined, undefined]); + // An enemy landing there catches every own piece on the node. + let c = make({ stacking: 'choose' }); + put(c, 1, 0, 3, [1, 2, 3]); + put(c, 1, 1, 3, [1, 2, 3]); + c.sides[1]!.pieces[1]!.group = 1; + const cr = actE(moving(c, ['geol']), 'A', mv(0, 'home')); + expect(cr.events.find((e) => e.type === 'captured')).toMatchObject({ count: 2 }); + expect([piece(cr.state, 1, 0).status, piece(cr.state, 1, 1).status, piece(cr.state, 1, 1).group]).toEqual(['home', 'home', undefined]); + }); + + test('stacking: validation (always = no choice; apart needs own pieces there; piece must stand on from)', () => { + const a = make(); + put(a, 0, 0, 3, [1, 2, 3]); + expect(reject(moving(a, ['geol']), 'A', { type: 'MOVE', throwIndex: 0, from: 'home', stack: false })).toBe('이 방은 내 말이 있는 자리에 멈추면 무조건 업어요.'); + expect(yut.view(moving(a, ['geol']), 'A').legalMoves!.every((m) => m.stack === undefined)).toBe(true); + const c = make({ stacking: 'choose' }); + put(c, 0, 0, 3, [1, 2, 3]); + expect(reject(moving(c, ['gae']), 'A', { type: 'MOVE', throwIndex: 0, from: 'home', stack: false })).toBe('그 자리에는 업을 내 말이 없어요.'); + expect(reject(moving(c, ['gae']), 'A', { type: 'MOVE', throwIndex: 0, from: 3, piece: 2 })).toBe('그 말은 움직일 수 없어요.'); + }); + + test('forkRule = choose: a piece that stopped on 모 / 뒷모 / 방 may take the other road', () => { + const at = (node: NodeId, trail: NodeId[], t: Throw) => { + const s = make({ forkRule: 'choose' }); + put(s, 0, 0, node, trail); + return moving(s, [t]); + }; + const roads = (s: YutState) => yut.view(s, 'A').legalMoves!.filter((m) => m.from !== 'home').map((m) => [m.to, m.alt ?? false]); + expect(roads(at(5, [1, 2, 3, 4, 5], 'geol'))).toEqual([[22, false], [8, true]]); + expect(roads(at(10, [6, 7, 8, 9, 10], 'gae'))).toEqual([[26, false], [12, true]]); + expect(roads(at(22, [20, 21, 22], 'do'))).toEqual([[27, false], [23, true]]); + expect(roads(at(3, [1, 2, 3], 'do'))).toEqual([[4, false]]); + expect(roads(at(5, [4, 5], 'backdo'))).toEqual([[4, false]]); + let s = act(at(5, [1, 2, 3, 4, 5], 'geol'), 'A', { type: 'MOVE', throwIndex: 0, from: 5, alt: true }); + expect(piece(s, 0, 0)).toMatchObject({ node: 8, trail: [1, 2, 3, 4, 5, 6, 7, 8] }); + expect(s.lastMove).toMatchObject({ alt: true, path: [6, 7, 8] }); + // 빽도 afterwards walks the recorded road back. + s.turnSide = 0; + s.current = 'A'; + s = act(moving(s, ['backdo']), 'A', mv(0, 8)); + expect(piece(s, 0, 0).node).toBe(7); + // Passing a fork is unchanged: 4 + 걸 → 7. + expect(roads(at(4, [1, 2, 3, 4], 'geol'))).toEqual([[7, false]]); + // The other road can catch. + const cap = at(5, [1, 2, 3, 4, 5], 'gae'); + put(cap, 1, 0, 7, [6, 7]); + const c = act(cap, 'A', { type: 'MOVE', throwIndex: 0, from: 5, alt: true }); + expect([piece(c, 1, 0).status, c.phase]).toEqual(['home', 'throw']); + }); + + test('forkRule: validation', () => { + const s = make(); + put(s, 0, 0, 5, [1, 2, 3, 4, 5]); + expect(reject(moving(s, ['geol']), 'A', { type: 'MOVE', throwIndex: 0, from: 5, alt: true })).toBe('이 방은 갈 길을 고르지 않아요. 모서리·방에 멈췄던 말은 늘 지름길로 가요.'); + const c = make({ forkRule: 'choose' }); + put(c, 0, 0, 5, [4, 5]); + put(c, 0, 1, 3, [1, 2, 3]); + expect(reject(moving(c, ['geol']), 'A', { type: 'MOVE', throwIndex: 0, from: 3, alt: true })).toBe('모서리나 방에 멈춰 있던 말이 앞으로 갈 때만 길을 고를 수 있어요.'); + expect(reject(moving(c, ['backdo']), 'A', { type: 'MOVE', throwIndex: 0, from: 5, alt: true })).toBe('모서리나 방에 멈춰 있던 말이 앞으로 갈 때만 길을 고를 수 있어요.'); + expect(reject(moving(c, ['geol']), 'A', { type: 'MOVE', throwIndex: 0, from: 'home', alt: true })).toBe('모서리나 방에 멈춰 있던 말이 앞으로 갈 때만 길을 고를 수 있어요.'); + }); + + test('timeouts pick the ordinary move first (shortcut, stacking)', () => { + const s = make({ forkRule: 'choose', stacking: 'choose' }); + put(s, 0, 0, 5, [1, 2, 3, 4, 5]); + put(s, 0, 1, 20, [20]); + expect(autoAction(moving(s, ['do']))).toEqual({ type: 'MOVE', throwIndex: 0, from: 5 }); + }); +}); + // ---------------------------------------------------------------- turns, teams, ranking describe('차례·팀전·순위', () => { @@ -618,6 +806,12 @@ const CONFIGS: Config[] = [ { opts: { mode: 'team', pieces: 5, backdo: false, nakPercent: 3 }, n: 8 }, { opts: { pieces: 5, ranking: 'all', finishRule: 'reach', stickModel: 'fair' }, n: 3 }, { opts: { pieces: 2, nakPercent: 5, turnSeconds: null }, n: 2 }, + // 지역 룰 + { opts: { stacking: 'choose', forkRule: 'choose' }, n: 2 }, + { opts: { backdoNoPiece: 'rethrow', useOrder: 'thrown', nakPercent: 10, nakRule: 'lose' }, n: 3 }, + { opts: { backdoNoPiece: 'enter', stacking: 'choose', stickModel: 'fair', finishRule: 'reach' }, n: 4 }, + { opts: { mode: 'team', forkRule: 'choose', useOrder: 'thrown', backdoNoPiece: 'enter', pieces: 5 }, n: 4 }, + { opts: { stacking: 'choose', forkRule: 'choose', backdoNoPiece: 'rethrow', nakPercent: 3, nakRule: 'lose', ranking: 'all', pieces: 5 }, n: 4 }, ]; /** Per-step invariants: piece count, one side per node, trail ends on the node, phase consistency, onTimeout legal. */ @@ -636,12 +830,21 @@ function invariant(st: unknown): void { occupied.set(p.node, x.id); } else if (p.node !== null || p.trail.length) throw new Error('off-board piece keeps a position'); } - const stacked = new Map(); + const stacked = new Map(); for (const p of x.pieces) { - if (p.status !== 'board') continue; + if (p.status !== 'board') { + if (p.group !== undefined) throw new Error('off-board piece keeps a stack key'); + continue; + } + if (p.group !== undefined) { + if (s.options.stacking !== 'choose') throw new Error('stack key without stacking = choose'); + const lead = x.pieces[p.group]; + if (!lead || lead.status !== 'board' || lead.node !== p.node || lead.group !== p.group) throw new Error('stack key without its lead piece'); + } + const k = `${p.node}:${p.group ?? -1}`; const key = JSON.stringify(p.trail); - if (stacked.has(p.node!) && stacked.get(p.node!) !== key) throw new Error('stack with different trails'); - stacked.set(p.node!, key); + if (stacked.has(k) && stacked.get(k) !== key) throw new Error('stack with different trails'); + stacked.set(k, key); } if (x.finishedRank !== null && x.pieces.some((p) => p.status !== 'done')) throw new Error('finished side with pieces left'); }