diff --git a/apps/server/src/rooms/castles-of-burgundy.room.test.ts b/apps/server/src/rooms/castles-of-burgundy.room.test.ts new file mode 100644 index 0000000..33478aa --- /dev/null +++ b/apps/server/src/rooms/castles-of-burgundy.room.test.ts @@ -0,0 +1,91 @@ +/** 버건디의 성 through a real Room: a practice game against a computer, played from the person's own screen, with turn clocks (docs/games/castles-of-burgundy.md §8.5). */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { GAMES } from '@bg/games'; +import type { CobAction, CobState, CobView } from '@bg/games/castles-of-burgundy'; +import { botProfile, isBotId, type ServerMessage } from '@bg/shared'; +import { openDb } from '../db'; +import { RoomManager } from './manager'; +import type { Room, Conn } from './room'; +import { RoomStore } from './store'; + +const rooms: Room[] = []; +afterEach(() => { + for (const r of rooms.splice(0)) r.clearTimer(); +}); + +function harness() { + const db = openDb(':memory:'); + const store = new RoomStore(db); + let now = 1_000_000; + const clock = { now: () => now, advance: (ms: number) => (now += ms) }; + const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } }; + const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 }); + const conn = (userId: string) => { + const msgs: ServerMessage[] = []; + const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} }; + return c; + }; + return { db, clock, manager, conn }; +} + +type StateMsg = Extract; +const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m): m is StateMsg => m.t === 'state').at(-1)?.view ?? null) as CobView | null; + +/** What the person presses, read only from their own screen: place > take > anything but ending the turn early. */ +function personMove(v: CobView): CobAction | null { + const my = v.my; + if (!my || !my.moves.length) return null; + const rank = (a: CobAction) => + a.type === 'useDie' ? (a.act.kind === 'place' ? 0 : a.act.kind === 'take' ? 1 : 3) : a.type === 'endTurn' ? 9 : a.type === 'buy' ? 8 : 2; + let best = my.moves.map((a, i) => ({ a, i })).sort((x, y) => rank(x.a) - rank(y.a) || (my.costs[x.i] ?? 0) - (my.costs[y.i] ?? 0) || x.i - y.i)[0]!.a; + if (my.needDiscard) { + if ((best.type === 'useDie' || best.type === 'bonus') && best.act.kind === 'take') best = { ...best, act: { ...best.act, discard: 0 } }; + else if ((best.type === 'buy' || best.type === 'depotTake' || best.type === 'soloTrade') && 'tile' in best) best = { ...best, discard: 0 } as CobAction; + } + return best; +} + +describe('버건디의 성 room flow', () => { + test('컴퓨터와 연습: 사람은 자기 화면만 보고 두고, 가끔 시간을 넘겨도 끝까지 가요', () => { + const h = harness(); + const room = h.manager.createPractice('A', 'castles-of-burgundy') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + const bots = room.game!.players.filter(isBotId); + expect(bots.length).toBeGreaterThan(0); + let cs = 0; + let mine = 0; + let lastTurn = -1; + let skipTurn = false; + for (let i = 0; i < 60_000 && !room.game!.finished; i++) { + h.clock.advance(250); + if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire(); + const d = room.effectiveDeadline(); + if (d !== null && d <= h.clock.now()) room.onTimer(); + const v = lastView(a); + if (!v || !v.my) continue; + if (v.turnSeq !== lastTurn) { + lastTurn = v.turnSeq; + skipTurn = v.turnSeq % 7 === 3; // now and then the person lets the clock run out + } + if (skipTurn) continue; + const m = personMove(v); + if (m) { + room.act('A', ++cs, m); + mine++; + } + } + expect(room.game!.finished).toBe(true); + expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]); + const s = room.game!.state as CobState; + expect(s.stage).toBe('finished'); + expect(s.log.some((e) => e.t === 'end')).toBe(true); + expect(mine).toBeGreaterThan(40); + const last = lastView(a)!; + expect(last.final!.map((r) => r.player).sort()).toEqual(['A', ...bots].sort()); + const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!; + expect(JSON.parse(row.result_json).practice).toBe(true); + }, 60_000); +}); diff --git a/apps/web/src/games/castles-of-burgundy/help.ts b/apps/web/src/games/castles-of-burgundy/help.ts new file mode 100644 index 0000000..ba5a95d --- /dev/null +++ b/apps/web/src/games/castles-of-burgundy/help.ts @@ -0,0 +1,59 @@ +/** 버건디의 성 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */ +import type { CobView } from '@bg/games/castles-of-burgundy'; +import type { PublicUser } from '@bg/shared/lite'; + +const PHASE = ['A', 'B', 'C', 'D', 'E']; + +export function helpNow(v: CobView, me: string | null, players: Record): string { + const name = (id: string) => `${players[id]?.nickname ?? '다른 사람'}님`; + const pv = me ? v.players[me] : undefined; + const where = `페이즈 ${PHASE[v.phase] ?? 'E'}, 라운드 ${Math.min(5, v.round + 1)}/5`; + if (v.stage === 'finished') { + if (v.solo) return v.endReason === 'soloWin' ? '성공했어요! 공국 37칸을 모두 채웠어요.' : '게임이 끝났어요. 25라운드 안에 공국을 다 채우지 못했어요.'; + const rows = [...(v.final ?? [])].sort((a, b) => b.total - a.total); + const top = rows[0]; + const mine = me ? rows.find((r) => r.player === me) : undefined; + return [`게임이 끝났어요.${top ? ` 1위는 ${name(top.player)}(${top.total}점)이에요.` : ''}`, mine ? `내 점수는 ${mine.total}점이에요(빈칸 ${mine.emptySpaces}칸).` : '', '같은 점수면 공국 빈칸이 더 많은 사람이 이겨요.'] + .filter(Boolean) + .join('\n'); + } + const waiting = v.waiting[0]; + if (!pv || pv.conceded) { + const head = pv?.conceded ? '기권해서 구경하는 중이에요. ' : ''; + return `${head}${where}. ${waiting ? `${name(waiting)} 차례예요.` : '잠시만 기다려 주세요.'}\n공국을 누르면 크게 볼 수 있어요.`; + } + const status = `내 점수 ${pv.vp}점 · 일꾼 ${pv.workers}개 · 은화 ${pv.silver}개 · 보관 칸 ${pv.storage.length}/3.`; + if (v.stage === 'castle') { + return v.my ? '시작 성을 놓을 성(진초록) 칸을 눌러 주세요. 첫 타일은 그 성 옆에 놓게 돼요.' : `${waiting ? name(waiting) : '다른 사람'}이 시작 성 칸을 고르는 중이에요.`; + } + if (!v.my) { + return [`${where}. ${waiting ? `${name(waiting)} 차례예요.` : ''} 기다리는 동안 다음 차례를 계획해 보세요.`, `내 주사위: ${pv.dice.join('·')} (모든 눈이 모두에게 보여요).`, status].join('\n'); + } + const top = v.pending[v.pending.length - 1]; + if (top) { + const tips: Record = { + bonus: '성 보너스예요. 주사위 하나를 원하는 눈으로 쓴 것처럼 가져오기·놓기·팔기·일꾼 받기 중 하나를 해요(일꾼 필요 없음).', + ship: '배를 놓았어요. 상품을 모두 가져올 보급소를 골라 주세요. 상품 칸은 3종류까지예요. 차례 트랙에서 한 칸 앞으로 가요.', + depotTake: '건물 효과로 번호 보급소에서 정해진 색 타일 1장을 공짜로 가져와요. 빛나는 타일을 누르거나 건너뛰어요.', + warehouse: '창고: 가진 상품 한 종류를 주사위 없이 팔아요.', + townhall: '시청: 보관 칸 타일 1장을 숫자와 상관없이 놓아요(색과 맞닿음은 지켜요).', + crane: '기중기: 아무 건물 효과 하나를 골라요.', + geese: '거위: 같은 목초지의 가축 한 종류를 골라 그 점수를 더 받아요.', + shieldCopy: '방패 6번: 수도원 효과를 함께 쓸 사람을 골라요.', + upkeep: '페이즈 끝 방패 유지비: 남길 방패 1개당 은화 1개예요.', + phasePlace: '방패 효과: 타일 1장을 골라 공국에 바로 놓아요(숫자 조건 없음).', + soloTrade: '상품 5장을 내고 검은 보급소 타일 1장을 뒷면으로 받을 수 있어요. 뒷면 타일은 아무 색 칸에나 놓아요.', + soloBlack: '색을 모두 채운 보상: 검은 보급소 타일 1장을 공국에 바로 놓아요.', + }; + return [tips[top.kind] ?? '위의 안내에 따라 골라 주세요.', status].join('\n'); + } + const left = [pv.used[0] ? null : pv.dice[0], pv.used[1] ? null : pv.dice[1]].filter((x) => x !== null); + const lines = [`내 차례예요(${where}). 남은 주사위: ${left.length ? left.join('·') : '없음'}.`]; + if (left.length) { + lines.push('주사위를 누르면 할 수 있는 일이 빛나요: 같은 번호 보급소에서 가져오기, 같은 색·숫자 칸에 놓기, 같은 번호 상품 팔기, 일꾼 2개 받기.'); + lines.push('일꾼 1개로 눈을 ±1 바꿀 수 있어요(6과 1은 이어져요). 빛나는 칸의 "일꾼 n"이 드는 일꾼 수예요.'); + } else lines.push('주사위를 다 썼어요. 살 것이 있으면 [🛒 구매], 아니면 [차례 끝]을 눌러요.'); + if (!pv.bought && pv.silver >= 2) lines.push('은화 2개로 검은 보급소 타일 1장을 살 수 있어요(차례당 1장).'); + lines.push(status); + return lines.join('\n'); +} diff --git a/apps/web/src/games/castles-of-burgundy/hex.tsx b/apps/web/src/games/castles-of-burgundy/hex.tsx new file mode 100644 index 0000000..67cef6f --- /dev/null +++ b/apps/web/src/games/castles-of-burgundy/hex.tsx @@ -0,0 +1,158 @@ +/** 버건디의 성 drawing helpers: own hex tile art (colour + symbol, no original artwork). */ +import { ANIMAL_ICON, ANIMAL_KO, BUILDING_KO, COLOR_ICON, COLOR_KO, GOODS_KO, MONASTERIES, TILES, type Color, type Die } from '@bg/games/castles-of-burgundy/data'; + +export const FILL: Record = { + castle: '#2f6b3a', + mine: '#7c828c', + monastery: '#e2b93b', + building: '#d6b383', + livestock: '#8cc152', + ship: '#3f86d1', + inn: '#b45309', + any: '#4b5563', +}; +export const SPACE: Record = { + castle: '#9cc7a3', + mine: '#c9ccd1', + monastery: '#f4e2a6', + building: '#efdfc6', + livestock: '#cfe8b4', + ship: '#b7d3f1', +}; +export const INK: Record = { + castle: '#ffffff', + mine: '#ffffff', + monastery: '#3b2a00', + building: '#3b2a00', + livestock: '#1f3a0a', + ship: '#ffffff', + inn: '#ffffff', + any: '#ffffff', +}; +export const GOODS_FILL: Record = { 1: '#7c3aed', 2: '#ca8a04', 3: '#db2777', 4: '#0891b2', 5: '#ea580c', 6: '#65a30d' }; + +const SQ3 = Math.sqrt(3); +export function hexPoints(cx: number, cy: number, r: number): string { + const pts: string[] = []; + for (let k = 0; k < 6; k++) { + const a = (Math.PI / 180) * (60 * k - 90); + pts.push(`${(cx + r * Math.cos(a)).toFixed(2)},${(cy + r * Math.sin(a)).toFixed(2)}`); + } + return pts.join(' '); +} +/** Axial (q, r) → pixel centre for pointy-top hexes of radius `size`. */ +export const axial = (q: number, r: number, size: number): [number, number] => [size * SQ3 * (q + r / 2), size * 1.5 * r]; +export const HEX_W = (size: number) => size * SQ3; + +export function tileColor(id: string, facedown = false): Color | 'inn' | 'any' { + if (facedown) return 'any'; + return TILES[id]?.color ?? 'any'; +} + +/** Short text inside a tile. */ +export function tileShort(id: string, facedown = false): { icon: string; text: string } { + if (facedown) return { icon: '■', text: '뒷면' }; + const t = TILES[id]; + if (!t) return { icon: '?', text: '' }; + if (t.color === 'inn') return { icon: '🛏', text: '여관' }; + if (t.building) return { icon: '🏠', text: BUILDING_KO[t.building] }; + if (t.animal) return { icon: ANIMAL_ICON[t.animal], text: `×${t.count}` }; + if (t.monastery) return { icon: '📜', text: String(t.monastery) }; + return { icon: COLOR_ICON[t.color as Color], text: '' }; +} + +/** Full Korean name of a tile ("시장(건물)", "양 3마리", "수도원 8 힘센 일꾼"). */ +export function tileName(id: string, facedown = false): string { + if (facedown) return '뒷면 타일(아무 색)'; + const t = TILES[id]; + if (!t) return '타일'; + if (t.color === 'inn') return '여관'; + if (t.building) return `${BUILDING_KO[t.building]}(건물)`; + if (t.animal) return `${ANIMAL_KO[t.animal]} ${t.count}마리`; + if (t.monastery) return `수도원 ${t.monastery}번 ${monasteryName(t.monastery, t.craft)}`; + return COLOR_KO[t.color as Color]; +} +export function monasteryName(n: number, craft?: string): string { + if (craft) return `${BUILDING_KO[craft as 'bank']} 장인`; + return MONASTERIES.find((m) => m.n === n)?.name ?? ''; +} +export function monasteryText(n: number, craft?: string): string { + if (craft) return `게임 끝: 내 공국의 ${BUILDING_KO[craft as 'bank']} 1개당 4점`; + return MONASTERIES.find((m) => m.n === n)?.text ?? ''; +} + +export const goodsName = (d: Die) => `${d} ${GOODS_KO[d]}`; + +/** One hex tile at (cx, cy). */ +export function TileHex({ id, cx, cy, r, facedown, dim }: { id: string; cx: number; cy: number; r: number; facedown?: boolean; dim?: boolean }) { + const c = tileColor(id, facedown); + const { icon, text } = tileShort(id, facedown); + return ( + + + + + {icon} + + {text && ( + 2 ? 0.34 : 0.42)} fontWeight={800} fill={INK[c]} dominantBaseline="middle"> + {text} + + )} + + ); +} + +/** A die face with pips (for the dice bar and the duchy spaces). */ +export function Pips({ n, cx, cy, s, color = '#1c1e21' }: { n: number; cx: number; cy: number; s: number; color?: string }) { + const o = s * 0.28; + const at: Record = { + 1: [[0, 0]], + 2: [ + [-o, -o], + [o, o], + ], + 3: [ + [-o, -o], + [0, 0], + [o, o], + ], + 4: [ + [-o, -o], + [o, -o], + [-o, o], + [o, o], + ], + 5: [ + [-o, -o], + [o, -o], + [0, 0], + [-o, o], + [o, o], + ], + 6: [ + [-o, -o], + [o, -o], + [-o, 0], + [o, 0], + [-o, o], + [o, o], + ], + }; + return ( + + {(at[n] ?? []).map(([dx, dy], i) => ( + + ))} + + ); +} + +export function DieFace({ n, size = 40, white, used, label }: { n: number; size?: number; white?: boolean; used?: boolean; label?: string }) { + return ( + + + + + ); +} diff --git a/apps/web/src/games/castles-of-burgundy/index.tsx b/apps/web/src/games/castles-of-burgundy/index.tsx new file mode 100644 index 0000000..535237d --- /dev/null +++ b/apps/web/src/games/castles-of-burgundy/index.tsx @@ -0,0 +1,1350 @@ +/** 버건디의 성 화면 (docs/games/castles-of-burgundy.md §9). Everything is drawn from the view; art is own SVG. */ +import { useEffect, useMemo, useState, type ReactNode } from 'react'; +import type { CobAction, CobOptions, CobPlayerView, CobView, LogEntry, Pending } from '@bg/games/castles-of-burgundy'; +import { + ANIMAL_KO, + BUILDING_EFFECT_KO, + BUILDING_KO, + COLOR_ICON, + COLOR_KO, + COLORS, + DUCHY_1, + PHASE_KO, + REGION_VP, + PHASE_VP, + SHIELDS, + TILES, + type Color, + type Die, +} from '@bg/games/castles-of-burgundy/data'; +import type { PublicUser } from '@bg/shared/lite'; +import { Avatar, ConfirmSheet, Sheet } from '../../components/ui'; +import { TurnTimer } from '../../components/TurnTimer'; +import { haptic, sfx } from '../../lib/feedback'; +import { bump, fxEl, useBanner, useNewEntries } from '../card-fx'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { DieFace, FILL, GOODS_FILL, INK, Pips, SPACE, TileHex, axial, goodsName, hexPoints, monasteryText, tileName } from './hex'; +import { helpNow } from './help'; +import { quickStart } from './quick'; + +type M = { a: CobAction; cost: number }; +type Sel = { kind: 'die'; i: 0 | 1 } | { kind: 'buy' } | { kind: 'pick'; tile: string } | null; + +const nick = (players: Record, id: string) => players[id]?.nickname ?? '알 수 없음'; +const userOf = (players: Record, id: string): PublicUser => players[id] ?? { id, nickname: '알 수 없음', avatar: null, kind: 'guest' }; +const iGa = (w: string) => { + const code = w.charCodeAt(w.length - 1) - 0xac00; + return code >= 0 && code <= 11171 && code % 28 !== 0 ? '이' : '가'; +}; +const topOf = (v: CobView): Pending | undefined => v.pending[v.pending.length - 1]; +const workerBadge = (n: number) => (n > 0 ? `일꾼 ${n}` : ''); + +const CSS = ` +.cob-root { width: 100%; max-width: 1180px; display: flex; flex-direction: column; gap: 8px; align-self: center; } +.game-main:has(.cob-root) { justify-content: flex-start; overflow: auto; } +.cob-wide { display: grid; grid-template-columns: minmax(0, 1.05fr) minmax(0, 1fr); gap: 10px; align-items: start; } +.cob-card { background: var(--surface); border-radius: var(--radius); box-shadow: var(--shadow); padding: 8px; } +.cob-banner { border-radius: var(--radius); padding: 8px 10px; background: var(--warning-soft); border: 2px solid var(--warning); display: flex; flex-direction: column; gap: 6px; } +.cob-banner.mine { background: var(--primary-soft); border-color: var(--primary); } +.cob-banner strong { font-size: 1rem; } +.cob-choices { display: flex; flex-wrap: wrap; gap: 6px; } +.cob-choices .btn { min-height: 44px; } +.cob-depots { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; } +.cob-depot { border: 2px solid var(--border); border-radius: 10px; padding: 4px; display: flex; flex-direction: column; gap: 3px; background: var(--surface-2); min-width: 0; } +.cob-depot.white { border-color: var(--primary); } +.cob-depot-h { display: flex; align-items: center; gap: 4px; font-weight: 800; font-size: .8rem; } +.cob-slots { display: flex; flex-wrap: wrap; gap: 2px; } +.cob-hexbtn { padding: 0; border: 0; background: none; cursor: pointer; position: relative; line-height: 0; border-radius: 8px; } +.cob-hexbtn:disabled { cursor: default; } +.cob-hexbtn:focus-visible { outline: 3px solid var(--focus); outline-offset: 1px; } +.cob-hexbtn.on { animation: cob-pulse 1.1s ease-in-out infinite; } +.cob-hexbtn.on svg { filter: drop-shadow(0 0 3px var(--primary)) drop-shadow(0 0 2px var(--primary)); } +.cob-hexbtn.buy svg { filter: drop-shadow(0 0 3px #ca8a04) drop-shadow(0 0 2px #ca8a04); } +.cob-cost { position: absolute; right: -2px; top: -4px; background: #b45309; color: #fff; font-size: .62rem; font-weight: 800; border-radius: 6px; padding: 1px 3px; line-height: 1.2; pointer-events: none; } +.cob-goods { display: flex; flex-wrap: wrap; gap: 2px; min-height: 18px; } +.cob-good { display: inline-flex; align-items: center; justify-content: center; min-width: 20px; height: 20px; border-radius: 5px; color: #fff; font-weight: 900; font-size: .78rem; padding: 0 4px; border: 2px solid rgba(0,0,0,.25); } +button.cob-good { cursor: pointer; min-height: 32px; min-width: 40px; font-size: .9rem; } +button.cob-good.on { box-shadow: 0 0 0 3px var(--primary); } +.cob-shield { display: inline-flex; align-items: center; gap: 1px; font-size: .7rem; font-weight: 800; padding: 1px 4px; border-radius: 6px; background: #e5e7eb; color: #1f2937; border: 1px solid #9ca3af; } +button.cob-shield { cursor: pointer; min-height: 28px; } +button.cob-shield.on { background: var(--primary); color: #fff; border-color: var(--primary); } +.cob-black { display: flex; flex-wrap: wrap; gap: 3px; align-items: center; } +.cob-row { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.cob-small { font-size: .78rem; color: var(--text-sub); } +.cob-duchy { width: 100%; height: auto; display: block; touch-action: manipulation; } +.cob-duchy .sp { cursor: default; } +.cob-duchy .sp.on { cursor: pointer; } +.cob-duchy .sp.on polygon.base { stroke: var(--primary); stroke-width: 3.5; } +.cob-duchy .sp:focus-visible polygon.base { stroke: var(--focus); stroke-width: 4; } +.cob-duchy .ring { fill: none; stroke: var(--primary); stroke-width: 2.5; stroke-dasharray: 4 3; } +.cob-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.cob-diebtn { padding: 2px; border-radius: 10px; border: 3px solid transparent; background: none; cursor: pointer; min-width: 48px; min-height: 48px; display: flex; align-items: center; justify-content: center; } +.cob-diebtn.sel { border-color: var(--primary); background: var(--primary-soft); } +.cob-diebtn:disabled { cursor: default; } +.cob-res { display: inline-flex; align-items: center; gap: 3px; font-weight: 800; padding: 2px 6px; border-radius: 8px; background: var(--surface-2); } +.cob-storage { display: flex; gap: 4px; } +.cob-slotbox { width: 46px; height: 50px; border: 2px dashed var(--border); border-radius: 8px; display: flex; align-items: center; justify-content: center; } +.cob-tabs { display: none; } +.cob-sticky { display: contents; } +.cob-tile-sheet { display: flex; gap: 8px; flex-wrap: wrap; } +.cob-pl { border-radius: 10px; padding: 6px; border: 2px solid transparent; } +.cob-pl.turn { border-color: var(--primary); } +.cob-pl.gone { opacity: .55; } +.cob-track { display: flex; gap: 4px; flex-wrap: wrap; } +@keyframes cob-pulse { 0%,100% { filter: brightness(1); } 50% { filter: brightness(1.18); } } +@media (prefers-reduced-motion: reduce) { .cob-hexbtn.on { animation: none; } } +@media (max-width: 899px) { + .cob-wide { display: block; } + .cob-wide > .cob-pane { display: none; } + .cob-wide > .cob-pane.show { display: block; } + .cob-tabs { display: grid; grid-template-columns: repeat(3, 1fr); gap: 4px; } + .cob-tabs button { min-height: 44px; } + .cob-sticky { display: block; position: sticky; bottom: 0; z-index: 5; background: var(--surface); border-top: 2px solid var(--border); padding: 6px; margin: 0 -4px; border-radius: 12px 12px 0 0; box-shadow: 0 -4px 12px rgba(0,0,0,.12); } + .cob-depots { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} +`; + +let cssDone = false; +function useCss() { + useEffect(() => { + if (cssDone || typeof document === 'undefined') return; + cssDone = true; + const el = document.createElement('style'); + el.textContent = CSS; + document.head.appendChild(el); + }, []); +} + +// ---------------------------------------------------------------- targets + +interface Targets { + space: Map; + tile: Map; + goods: Map; + shield: Map; +} + +function moveList(v: CobView): M[] { + if (!v.my) return []; + return v.my.moves.map((a, i) => ({ a, cost: v.my!.costs[i] ?? 0 })); +} + +function targetsFor(v: CobView, moves: M[], sel: Sel, slot: number | null): Targets { + const t: Targets = { space: new Map(), tile: new Map(), goods: new Map(), shield: new Map() }; + const addS = (k: number, m: M) => t.space.set(k, [...(t.space.get(k) ?? []), m]); + const addT = (k: string, m: M) => t.tile.set(k, [...(t.tile.get(k) ?? []), m]); + const top = topOf(v); + for (const m of moves) { + const a = m.a; + if (a.type === 'chooseCastle') addS(a.space, m); + else if (a.type === 'townhall' && 'space' in a) { + if (slot === null || a.slot === slot) addS(a.space, m); + } else if ((a.type === 'phasePlace' || a.type === 'soloBlack') && 'tile' in a) { + if (sel?.kind === 'pick' && sel.tile === a.tile) addS(a.space, m); + else addT(a.tile, m); + } else if ((a.type === 'depotTake' || a.type === 'soloTrade') && 'tile' in a) addT(a.tile, m); + else if (a.type === 'warehouse' && 'goods' in a) t.goods.set(a.goods, m); + else if (a.type === 'buy') { + if (sel?.kind === 'buy') addT(a.tile, m); + } else if (a.type === 'takeShield') { + if (!t.shield.has(`${a.depot}:${a.shield}`)) t.shield.set(`${a.depot}:${a.shield}`, m); + } else if (a.type === 'useDie' || a.type === 'bonus') { + const active = a.type === 'bonus' ? top?.kind === 'bonus' : sel?.kind === 'die' && sel.i === a.die; + if (!active) continue; + const act = a.act; + if (act.kind === 'take') addT(act.tile, m); + else if (act.kind === 'place') { + if (slot === null || act.slot === slot) addS(act.space, m); + } else if (act.kind === 'sell') t.goods.set(act.goods, m); + else if (act.kind === 'shield') { + if (!t.shield.has(`${act.depot}:${act.shield}`)) t.shield.set(`${act.depot}:${act.shield}`, m); + } + } + } + return t; +} + +// ---------------------------------------------------------------- duchy + +function Duchy({ + pv, + size = 30, + targets, + onSpace, + label, + fxPrefix, +}: { + pv: CobPlayerView; + size?: number; + targets?: Map; + onSpace?: (space: number) => void; + label: string; + fxPrefix?: string; +}) { + const w = size * Math.sqrt(3) * 7 + 4; + const h = size * 11 + 4; + return ( + + {DUCHY_1.spaces.map((sp) => { + const [x, y] = axial(sp.q, sp.r, size); + const tile = pv.placed[sp.id]; + const ms = targets?.get(sp.id); + const on = !!ms?.length && !!onSpace; + const cost = ms?.length ? Math.min(...ms.map((m) => m.cost)) : 0; + const shield = pv.shields[sp.id]; + const desc = tile ? tileName(tile, pv.facedown.includes(tile)) : `빈칸, ${COLOR_KO[sp.color]} ${sp.die}`; + return ( + onSpace!(sp.id) : undefined} + onKeyDown={on ? (e) => (e.key === 'Enter' || e.key === ' ') && (e.preventDefault(), onSpace!(sp.id)) : undefined} + > + + {tile ? ( + + ) : ( + <> + + {COLOR_ICON[sp.color]} + + + + )} + {sp.id === pv.start && tile && } + {shield !== undefined && ( + + + + 🛡{shield} + + + )} + {on && } + {on && cost > 0 && ( + + + + 일꾼 {cost} + + + )} + + ); + })} + + ); +} + +// ---------------------------------------------------------------- depot board + +function HexButton({ + tile, + slotColor, + ms, + buy, + onPick, + size = 24, + label, +}: { + tile: string | null; + slotColor?: Color; + ms?: M[]; + buy?: boolean; + onPick?: (tile: string) => void; + size?: number; + label: string; +}) { + const on = !!tile && !!ms?.length && !!onPick; + const cost = ms?.length ? Math.min(...ms.map((m) => m.cost)) : 0; + const w = size * 1.8; + const h = size * 2; + return ( + + ); +} + +function Good({ d, n, on, onClick, label }: { d: Die; n?: number; on?: boolean; onClick?: () => void; label?: string }) { + const style = { background: GOODS_FILL[d] }; + const text = n && n > 1 ? `${d}×${n}` : String(d); + if (onClick) + return ( + + ); + return ( + + {text} + + ); +} + +function DepotBoard({ v, t, onTile, onShield, buyMode }: { v: CobView; t: Targets; onTile: (tile: string) => void; onShield: (key: string) => void; buyMode: boolean }) { + const nPhase = PHASE_KO[v.phase] ?? 'E'; + return ( +
+
+ + 페이즈 {nPhase} · 라운드 {Math.min(5, v.round + 1)}/5 + + + 다음 상품 {v.roundGoods.length ? v.roundGoods.map((d, i) => ) : '없음'} + +
+
+ {v.depots.map((d, i) => { + const no = (i + 1) as Die; + return ( +
+
+ + {no}번 + {v.whiteDie === no && 흰 주사위} +
+
+ {d.slots.map((tile, k) => ( + + ))} +
+
+ {d.goods.map((g, k) => ( + + ))} + {d.shields.map((s) => { + const key = `${no}:${s}`; + const m = t.shield.get(key); + return m ? ( + + ) : ( + + 🛡{s} + + ); + })} +
+
+ ); + })} +
+
+ ⬛ 검은 보급소(은화 2로 사기, 차례당 1장) +
+ {v.black.map((tile, k) => ( + + ))} + {v.inns.length > 0 && ( + + + ×{v.inns.length} + + )} +
+
+ {!v.solo && ( +
+ 색 보너스: + {COLORS.map((c) => ( + + {COLOR_ICON[c]} + {v.bonusLeft[c].length === 2 ? '큰·작은' : v.bonusLeft[c].length === 1 ? '작은' : '—'} + + ))} +
+ )} + {v.solo && ( +
+ 🎯 목표 표시기 {v.solo.target}점 · 공국 37칸을 25라운드 안에 모두 채우면 성공(1번 공국으로 하는 혼자 하기) +
+ )} +
+ ); +} + +// ---------------------------------------------------------------- my bar + +function Storage({ pv, slot, setSlot, selectable }: { pv: CobPlayerView; slot: number | null; setSlot?: (i: number | null) => void; selectable: boolean }) { + const boxes = Math.max(3, pv.storage.length); + return ( +
+ {Array.from({ length: boxes }, (_, i) => { + const tile = pv.storage[i]; + if (!tile) return
; + const fd = pv.facedown.includes(tile); + return ( + + ); + })} +
+ ); +} + +// ---------------------------------------------------------------- pending banner + +function moveLabel(m: M, v: CobView, players: Record): string { + const a = m.a; + switch (a.type) { + case 'ship': { + const parts = [`${a.depot}번 보급소`]; + if (a.adjacent) parts.push(`+ ${a.adjacent}번`); + if (a.extra) parts.push(`+ 모든 곳의 ${a.extra}번 상품`); + const goods = [a.depot, a.adjacent].filter(Boolean).flatMap((d) => v.depots[d! - 1]!.goods); + if (a.keep) parts.push(`(새 상품 ${a.keep.join('·')}만 담기)`); + return `${parts.join(' ')} — 상품 ${goods.length ? goods.join(' ') : '없음'}`; + } + case 'warehouse': + return 'skip' in a ? '팔지 않기' : `${goodsName(a.goods as Die)} 팔기`; + case 'crane': + return `${BUILDING_KO[a.building]}: ${BUILDING_EFFECT_KO[a.building]}`; + case 'geese': + return a.animal ? `${ANIMAL_KO[a.animal]} 점수 받기` : '받지 않기'; + case 'shieldCopy': + return `${nick(players, a.player)}님의 수도원 효과`; + case 'upkeep': + return a.keep.length ? `방패 ${a.keep.join('·')} 남기기(은화 ${a.keep.length})` : '방패를 모두 내려놓기'; + default: + return 'skip' in a ? '건너뛰기' : ''; + } +} + +const PENDING_TEXT: Record = { + bonus: '🏰 성 보너스: 원하는 눈의 주사위 하나처럼 행동 1번(일꾼 없이)', + ship: '⛵ 배: 상품을 모두 가져올 보급소를 골라 주세요(차례 트랙 한 칸 앞으로)', + depotTake: '🏠 보급소에서 타일 1장 가져오기', + warehouse: '🏠 창고: 상품 한 종류를 주사위 없이 팔아요', + townhall: '🏠 시청: 보관 칸의 타일 1장을 눈과 상관없이 놓아요', + crane: '🏗 기중기: 쓸 건물 효과를 골라 주세요', + geese: '🪿 거위: 같은 목초지의 가축 한 종류 점수를 더 받아요', + shieldCopy: '🛡 방패 6번: 수도원 효과를 함께 쓸 사람을 골라 주세요', + upkeep: '🛡 페이즈 끝: 방패 유지비(1개당 은화 1)', + phasePlace: '🛡 페이즈 끝: 타일 1장을 공국에 바로 놓아요', + soloTrade: '📦 상품 5장을 내고 검은 보급소 타일 1장을 뒷면으로 받을 수 있어요', + soloBlack: '👑 색 완성 보상: 검은 보급소 타일 1장을 공국에 바로 놓아요', +}; + +function pendingText(p: Pending): string { + if (p.kind === 'bonus' && p.source === 'solo') return '🎯 목표 점수 도달! 원하는 눈으로 행동 1번(일꾼 없이)'; + if (p.kind === 'depotTake') { + const names = p.colors.map((c) => COLOR_KO[c]).join('·'); + return `🏠 ${BUILDING_KO[p.source]}: 번호 보급소에서 ${names} 타일 1장을 골라 주세요`; + } + if (p.kind === 'phasePlace') return p.from === 'black' ? '🛡 방패 15번: 검은 보급소 타일 1장을 공국에 바로 놓아요' : '🛡 방패 14번: 번호 보급소 타일 1장을 공국에 바로 놓아요'; + return PENDING_TEXT[p.kind]; +} + +// ---------------------------------------------------------------- board + +function useNarrow(): boolean { + const q = '(max-width: 899px)'; + const [n, setN] = useState(() => typeof matchMedia === 'function' && matchMedia(q).matches); + useEffect(() => { + if (typeof matchMedia !== 'function') return; + const mq = matchMedia(q); + const on = () => setN(mq.matches); + mq.addEventListener('change', on); + return () => mq.removeEventListener('change', on); + }, []); + return n; +} + +type Ask = + | { kind: 'discard'; m: M } + | { kind: 'slot'; ms: M[] } + | { kind: 'confirm'; m: M; title: string; body: string } + | { kind: 'buy'; ms: M[] } + | { kind: 'player'; id: string } + | null; + +function CobBoard({ view: v, me, players, act, pending: busy, tapConfirm }: BoardProps) { + useCss(); + const narrow = useNarrow(); + const [sel, setSel] = useState(null); + const [slot, setSlot] = useState(null); + const [ask, setAsk] = useState(null); + const [tab, setTab] = useState<'duchy' | 'depots' | 'others'>('duchy'); + const [banner, showBanner] = useBanner(); + const myPv = me ? v.players[me] : undefined; + const moves = useMemo(() => moveList(v), [v]); + const top = topOf(v); + const mineNow = !!v.my; + const myTurn = mineNow && v.stage === 'turn'; + const freeTurn = myTurn && !top; + + // Reset selections whenever the decision changes. + useEffect(() => { + setSel(null); + setSlot(null); + setAsk(null); + }, [v.seq]); + + const t = useMemo(() => targetsFor(v, moves, sel, slot), [v, moves, sel, slot]); + + // Mobile: jump to the tab where the choice is. + useEffect(() => { + if (!narrow || !mineNow) return; + if (t.space.size && !t.tile.size) setTab('duchy'); + else if (t.tile.size && !t.space.size) setTab('depots'); + }, [narrow, mineNow, t.space.size, t.tile.size]); + + // Sounds / banners from the public log. + useNewEntries( + v.log, + (e) => `${e.seq}:${JSON.stringify(e)}`, + (fresh) => { + for (const e of fresh) { + if (e.t === 'round') sfx.dice(); + else if (e.t === 'place') { + sfx.piece(); + if (e.p === me) bump(fxEl(`me-${e.space}`)); + } else if (e.t === 'region' && e.p === me) { + sfx.good(); + showBanner(`+${e.vp}점`, 'green', '구역 완성!'); + } else if (e.t === 'colorBonus') { + sfx.good(); + showBanner(e.p === me ? `👑 ${COLOR_KO[e.color]} 색 ${e.size === 'large' ? '첫' : '둘째'} 완성!` : `${nick(players, e.p)}님 ${COLOR_KO[e.color]} 색 완성`, 'gold', `+${e.vp}점`); + } else if (e.t === 'sell') sfx.coin(); + else if (e.t === 'ship') sfx.whoosh(); + else if (e.t === 'phase' && e.phase > 0) showBanner(`페이즈 ${PHASE_KO[e.phase]}`, 'blue', '보급소를 새로 채웠어요'); + else if (e.t === 'soloTarget') showBanner('🎯 목표 도달!', 'gold', `다음 목표 ${e.target}점`); + } + }, + ); + + const send = (a: CobAction) => { + if (busy) return; + haptic(15); + act(a); + setSel(null); + setSlot(null); + setAsk(null); + }; + const needDiscard = (a: CobAction) => { + if (!v.my?.needDiscard) return false; + if ((a.type === 'useDie' || a.type === 'bonus') && a.act.kind === 'take') return true; + return (a.type === 'buy' || a.type === 'depotTake' || a.type === 'soloTrade') && 'tile' in a; + }; + const run = (m: M) => { + if (needDiscard(m.a)) return setAsk({ kind: 'discard', m }); + if (m.cost > 0 || tapConfirm) { + return setAsk({ kind: 'confirm', m, title: confirmTitle(m, v), body: m.cost > 0 ? `일꾼 ${m.cost}개를 써요.` : '' }); + } + send(m.a); + }; + + const onSpace = (space: number) => { + const ms = t.space.get(space) ?? []; + if (!ms.length) return; + const slots = new Set(ms.map((m) => slotOf(m.a))); + if (slots.size > 1) return setAsk({ kind: 'slot', ms }); + run(ms[0]!); + }; + const onTile = (tile: string) => { + const ms = t.tile.get(tile) ?? []; + if (!ms.length) return; + const a = ms[0]!.a; + if ((a.type === 'phasePlace' || a.type === 'soloBlack') && 'tile' in a) { + setSel({ kind: 'pick', tile }); + if (narrow) setTab('duchy'); + return; + } + if (a.type === 'buy') { + if (ms.length > 1) return setAsk({ kind: 'buy', ms }); + return run(ms[0]!); + } + run(ms.reduce((x, y) => (y.cost < x.cost ? y : x))); + }; + const onShield = (key: string) => { + const m = t.shield.get(key); + if (m) run(m); + }; + + const dieMoves = (i: 0 | 1) => moves.filter((m) => m.a.type === 'useDie' && m.a.die === i); + const workersMove = (i: 0 | 1 | 'bonus') => + moves.find((m) => (i === 'bonus' ? m.a.type === 'bonus' : m.a.type === 'useDie' && m.a.die === i) && 'act' in m.a && m.a.act.kind === 'workers'); + const choiceMoves = moves.filter((m) => ['ship', 'warehouse', 'crane', 'geese', 'shieldCopy', 'upkeep'].includes(m.a.type) || ('skip' in m.a && m.a.type !== 'warehouse')); + const buyMoves = moves.filter((m) => m.a.type === 'buy'); + const endMove = moves.find((m) => m.a.type === 'endTurn'); + const extraMoves = moves.filter((m) => m.a.type === 'buyWorkers' || m.a.type === 'soloBuyVp'); + + const castleChoose = v.stage === 'castle'; + const waitingName = v.waiting[0] ? nick(players, v.waiting[0]) : ''; + const bannerBox = (() => { + if (castleChoose) { + return ( +
+ {mineNow ? '🏰 시작 성을 놓을 성(진초록) 칸을 눌러 주세요' : `${waitingName}님이 시작 성 칸을 고르는 중이에요`} +
+ ); + } + if (!top || v.stage === 'finished') return null; + const who = v.waiting[0]; + if (!mineNow) { + return ( +
+ + {who ? `${nick(players, who)}님: ` : ''} + {pendingText(top)} + +
+ ); + } + const hint = + top.kind === 'bonus' + ? '보급소 타일·공국 칸·상품이 빛나요. 눌러서 고르거나 아래 버튼을 눌러요.' + : top.kind === 'townhall' + ? '보관 칸 타일을 고르고(선택) 빛나는 칸을 눌러요.' + : top.kind === 'depotTake' || top.kind === 'soloTrade' + ? '빛나는 보급소 타일을 눌러요.' + : top.kind === 'phasePlace' || top.kind === 'soloBlack' + ? sel?.kind === 'pick' + ? `${tileName(sel.tile)}: 공국의 빛나는 칸을 눌러요.` + : '먼저 빛나는 타일을 누르고 공국 칸을 골라요.' + : top.kind === 'warehouse' + ? '팔 상품을 눌러요.' + : ''; + return ( +
+ {pendingText(top)} + {hint && {hint}} +
+ {top.kind === 'bonus' && workersMove('bonus') && ( + + )} + {top.kind === 'warehouse' && + moves + .filter((m) => m.a.type === 'warehouse') + .map((m, i) => ( + + ))} + {top.kind !== 'warehouse' && + choiceMoves.map((m, i) => ( + + ))} + {top.kind === 'bonus' && extraMoves.map((m, i) => )} +
+
+ ); + })(); + + const diceBar = myPv && v.stage !== 'finished' && ( +
+ {myPv.dice.map((d, i) => { + const idx = i as 0 | 1; + const usable = freeTurn && !myPv.used[idx] && dieMoves(idx).length > 0; + const selected = sel?.kind === 'die' && sel.i === idx; + return ( + + ); + })} + + 👷 {myPv.workers} + + + 🪙 {myPv.silver} + + + ⭐ {myPv.vp} + + {sel?.kind === 'die' && workersMove(sel.i) && ( + + )} + {buyMoves.length > 0 && (freeTurn || top?.kind === 'bonus') && ( + + )} + {freeTurn && extraMoves.map((m, i) => )} + {endMove && ( + + )} +
+ ); + + const myHint = (() => { + if (!myTurn || top) return null; + if (sel?.kind === 'die') { + const n = dieMoves(sel.i).filter((m) => 'act' in m.a && m.a.act.kind !== 'workers').length; + return n ? '빛나는 곳(보급소 타일·공국 칸·상품)을 눌러요. "일꾼 n" 표시는 눈을 바꾸는 데 드는 일꾼이에요.' : '이 주사위로는 일꾼 받기만 할 수 있어요.'; + } + if (sel?.kind === 'buy') return '살 타일(금색으로 빛나는 것)을 눌러요.'; + if (myPv && (!myPv.used[0] || !myPv.used[1])) return '주사위를 눌러 고르면 할 수 있는 일이 빛나요.'; + return null; + })(); + + const myArea = myPv && ( +
+
+ 내 공국 + + 빈칸 {myPv.emptySpaces} · 차례 트랙 {myPv.track.pos + 1}번 칸{v.my?.projected !== null && v.my?.projected !== undefined ? ` · 지금 끝나면 약 ${v.my.projected}점` : ''} + +
+ +
+ +
+ 상품(최대 {v.solo ? '6' : '3'}종) · 판 상품 {myPv.soldCount}장 +
+ {myPv.goods.length === 0 && 없음} + {myPv.goods.map((g) => { + const m = t.goods.get(g.die); + return m ? ( + run(m)} + label={`${goodsName(g.die)} ${g.count}장 팔기${m.cost ? `, 일꾼 ${m.cost}개` : ''}`} + /> + ) : ( + + ); + })} +
+ {myPv.bonus.length > 0 && 보너스: {myPv.bonus.map((b) => `${COLOR_ICON[b.color]}${b.size === 'large' ? '큰' : '작은'}`).join(' ')}} +
+
+ {v.options.showHints && } +
+ ); + + const others = ( +
+ 다른 사람 + {v.seats + .filter((p) => p !== me) + .map((p) => ( + + ))} + {v.seats.length === 1 && 혼자 하는 중이에요.} +
+ ); + + const depots = ; + + return ( +
+ {banner} + {bannerBox} + {!myPv && ( +
+ +
+ )} + {myPv && ( + <> +
+ {( + [ + ['duchy', '내 공국'], + ['depots', '보급소'], + ['others', '다른 사람'], + ] as const + ).map(([k, l]) => ( + + ))} +
+
+
{depots}
+
{myArea}
+ {narrow &&
{others}
} +
+
+ {myHint &&
{myHint}
} + {diceBar} +
+ + )} + {!myPv && depots} + {ask?.kind === 'discard' && ( + setAsk(null)} label="버릴 타일 고르기"> +

보관 칸이 꽉 찼어요

+

버릴 타일을 하나 골라 주세요(게임에서 빠져요).

+
+ {myPv!.storage.map((tile, i) => ( + + ))} +
+
+ )} + {ask?.kind === 'slot' && ( + setAsk(null)} label="놓을 타일 고르기"> +

어느 타일을 놓을까요?

+
+ {ask.ms.map((m, i) => { + const s = slotOf(m.a); + const tile = s === null ? null : myPv!.storage[s]; + return ( + + ); + })} +
+
+ )} + {ask?.kind === 'buy' && ( + setAsk(null)} label="내는 방법 고르기"> +

무엇으로 낼까요?

+
+ {ask.ms.map((m, i) => ( + + ))} +
+
+ )} + {ask?.kind === 'confirm' && send(ask.m.a)} onClose={() => setAsk(null)} />} + {ask?.kind === 'player' && ( + setAsk(null)} label={`${nick(players, ask.id)}님의 공국`}> +

{nick(players, ask.id)}님의 공국

+ + + + +
+ )} +
+ ); +} + +function ExtraButton({ m, send, busy }: { m: M; send: (a: CobAction) => void; busy: boolean }) { + return ( + + ); +} + +function slotOf(a: CobAction): number | null { + if ((a.type === 'useDie' || a.type === 'bonus') && a.act.kind === 'place') return a.act.slot; + if (a.type === 'townhall' && 'slot' in a) return a.slot; + return null; +} + +function withDiscard(a: CobAction, i: number): CobAction { + if ((a.type === 'useDie' || a.type === 'bonus') && a.act.kind === 'take') return { ...a, act: { ...a.act, discard: i } }; + return { ...a, discard: i } as CobAction; +} + +function confirmTitle(m: M, v: CobView): string { + const a = m.a; + const me = v.me ? v.players[v.me] : undefined; + if ((a.type === 'useDie' || a.type === 'bonus') && a.act.kind === 'place' && me) { + const tile = me.storage[a.act.slot]; + return tile ? `이 칸에 ${tileName(tile, me.facedown.includes(tile))}을(를) 놓을까요?` : '놓을까요?'; + } + if ((a.type === 'useDie' || a.type === 'bonus') && a.act.kind === 'take') return `${tileName(a.act.tile)}을(를) 가져올까요?`; + if ((a.type === 'useDie' || a.type === 'bonus') && a.act.kind === 'sell') return `${goodsName(a.act.goods as Die)}을(를) 모두 팔까요?`; + if (a.type === 'buy') return `${tileName(a.tile)}을(를) 살까요?`; + if (a.type === 'takeShield') return `방패 ${a.shield}번을 가져올까요?`; + return '할까요?'; +} + +function RegionHints({ pv, phase }: { pv: CobPlayerView; phase: number }) { + const near = DUCHY_1.regions + .map((r) => ({ r, left: r.spaces.filter((x) => !pv.placed[x]).length })) + .filter((x) => x.left > 0 && x.left < x.r.spaces.length && x.left <= 2) + .slice(0, 4); + const colors = COLORS.map((c) => ({ c, left: DUCHY_1.spaces.filter((x) => x.color === c && !pv.placed[x.id]).length })).filter((x) => x.left > 0 && x.left <= 2); + if (!near.length && !colors.length) return null; + return ( +
+ {near.map(({ r, left }) => ( +
+ {COLOR_ICON[r.color]} {COLOR_KO[r.color]} {r.spaces.length}칸 구역: {left}칸 남음(완성 {REGION_VP[r.spaces.length]! + PHASE_VP[phase]!}점) +
+ ))} + {colors.map(({ c, left }) => ( +
+ 👑 {COLOR_KO[c]} 색 전부까지 {left}칸 +
+ ))} +
+ ); +} + +function PlayerLine({ pv, name }: { pv: CobPlayerView; name: string }) { + return ( +
+
+ {name} + ⭐{pv.vp} + 👷{pv.workers} + 🪙{pv.silver} + 🎲{pv.dice.join('·')} + 빈칸 {pv.emptySpaces} + {pv.conceded && 기권} + {pv.away && !pv.conceded && 자리 비움} +
+
+ 보관: {pv.storage.length ? pv.storage.map((t) => tileName(t, pv.facedown.includes(t))).join(', ') : '없음'} · 상품: {pv.goods.length ? pv.goods.map((g) => `${g.die}×${g.count}`).join(' ') : '없음'} +
+
+ ); +} + +// ---------------------------------------------------------------- side + +function logText(e: LogEntry, players: Record, me: string | null): string | null { + const who = (p: string) => (p === me ? '나' : `${nick(players, p)}님`); + switch (e.t) { + case 'phase': + return `── 페이즈 ${PHASE_KO[e.phase]} 시작 ──`; + case 'round': + return `라운드 ${e.round + 1}: 흰 주사위 ${e.white}${e.goods ? ` → ${e.depot}번 보급소에 상품 ${e.goods}` : ''}`; + case 'take': + return `${who(e.p)}: ${e.depot === 'black' ? '검은 보급소' : `${e.depot}번 보급소`}에서 ${tileName(e.tile)} 가져옴`; + case 'buy': + return `${who(e.p)}: ${tileName(e.tile)} 삼`; + case 'place': + return `${who(e.p)}: ${tileName(e.tile)} 놓음`; + case 'region': + return `${who(e.p)}: ${e.size}칸 구역 완성 +${e.vp}점`; + case 'colorBonus': + return `${who(e.p)}: ${COLOR_KO[e.color]} 색 ${e.size === 'large' ? '첫' : '둘째'} 완성 +${e.vp}점`; + case 'livestock': + return e.vp ? `${who(e.p)}: 가축 +${e.vp}점` : null; + case 'sell': + return `${who(e.p)}: 상품 ${e.goods} ${e.count}장 팔기 +${e.vp}점, 은화 ${e.silver}`; + case 'workers': + return `${who(e.p)}: 일꾼 ${e.n}개 받기`; + case 'ship': + return `${who(e.p)}: 배로 ${e.depots.join('·')}번 보급소 상품 ${e.goods.length}장`; + case 'shield': + return `${who(e.p)}: 방패 ${e.shield}번`; + case 'shieldLost': + return `${who(e.p)}: 방패 ${e.shield}번 내려놓음`; + case 'income': + return `${who(e.p)}: 광산 은화 ${e.silver}${e.workers ? `, 일꾼 ${e.workers}` : ''}`; + case 'discard': + return `${who(e.p)}: ${tileName(e.tile)} 버림`; + case 'soloRemove': + return `${e.depot}번 보급소의 ${tileName(e.tile)} 빠짐`; + case 'soloTarget': + return `목표 도달! 다음 목표 ${e.target}점`; + case 'auto': + return `${who(e.p)}: 시간이 지나 자동 진행`; + case 'concede': + return `${who(e.p)}: 기권`; + case 'end': + return '게임 끝'; + default: + return null; + } +} + +function CobSide({ view: v, me, players, act, deadline }: BoardProps) { + useCss(); + const [ask, setAsk] = useState(false); + const [look, setLook] = useState(null); + const mine = me ? v.players[me] : undefined; + const log = useMemo( + () => + [...v.log] + .reverse() + .map((e, i) => ({ k: `${e.seq}-${i}`, text: logText(e, players, me) })) + .filter((x) => x.text), + [v.log, players, me], + ); + const order = v.roundOrder.length ? v.roundOrder : v.seats; + const rows = v.final ? [...v.final].sort((a, b) => b.total - a.total) : null; + return ( + <> +
+ {v.stage === 'finished' ? '게임 끝' : `페이즈 ${PHASE_KO[v.phase]} · 라운드 ${Math.min(5, v.round + 1)}/5 · 차례 순서`} + {order.map((p, i) => { + const pv = v.players[p]!; + const turn = v.waiting.includes(p); + return ( +
+
+ + {i + 1} + + +
+
+ {nick(players, p)} + {p === me && (나)} +
+
+ {pv.conceded ? '기권' : pv.away ? '자리 비움' : `👷${pv.workers} 🪙${pv.silver} 🎲${pv.dice.join('·')} · 빈칸 ${pv.emptySpaces}`} +
+
+ + {pv.vp} + + {turn && v.stage !== 'finished' && } +
+ {p !== me && ( + + )} +
+ ); + })} +
+ {rows && ( +
+ 최종 점수 + {rows.map((r) => ( +
+ + {nick(players, r.player)} {r.total}점 + {' '} + = 게임 중 {r.inGame} + 상품 {r.goodsLeft} + 은화 {r.silver} + 일꾼 {r.workers} + {r.monasteries.length ? ` + 수도원 ${r.monasteries.reduce((a, m) => a + m.vp, 0)}` : ''} + {r.shields ? ` + 방패 ${r.shields}` : ''} · 빈칸 {r.emptySpaces} + {r.conceded ? ' · 기권' : ''} +
+ ))} +
+ )} + {log.length > 0 && ( +
+ 기록 +
    + {log.map((e) => ( +
  1. + {e.text} +
  2. + ))} +
+
+ )} +
+ 타일 효과 요약 + +
+
+ 규칙 요약 + +
+ {v.stage !== 'finished' && mine && !mine.conceded && ( + + )} + {ask && ( + act({ type: 'concede' })} + onClose={() => setAsk(false)} + /> + )} + {look && v.players[look] && ( + setLook(null)} label={`${nick(players, look)}님의 공국`}> +

{nick(players, look)}님의 공국

+ + + +
+ )} + + ); +} + +function TileTable() { + const rows: [Color, string][] = [ + ['castle', '놓으면 원하는 눈으로 행동 1번 더'], + ['mine', '페이즈 끝마다 광산 1개당 은화 1'], + ['monastery', '규칙을 바꾸는 특수 능력(번호마다 다름)'], + ['building', '놓을 때 효과 한 번 · 한 마을에 같은 건물 1개'], + ['livestock', '같은 목초지의 같은 동물 수만큼 점수'], + ['ship', '보급소 상품 모두 가져오기 + 차례 트랙 앞으로'], + ]; + return ( +
+ {rows.map(([c, text]) => ( +
+ + {COLOR_ICON[c]} + + + {COLOR_KO[c]}: {text} + +
+ ))} +
+ 건물:{' '} + {(['warehouse', 'carpenter', 'church', 'market', 'boarding', 'bank', 'townhall', 'watchtower'] as const).map((b) => `${BUILDING_KO[b]}(${BUILDING_EFFECT_KO[b]})`).join(', ')} +
+
+ 수도원:{' '} + {Object.values(TILES) + .filter((t) => t.monastery && !t.extra) + .sort((a, b) => a.monastery! - b.monastery!) + .map((t) => `${t.monastery} ${monasteryText(t.monastery!, t.craft)}`) + .join(' / ')} +
+
+ ); +} + +// ---------------------------------------------------------------- status + +function isMyTurn(v: CobView, me: string | null): boolean { + return !!me && !!v.my && v.stage !== 'finished'; +} + +function statusText(v: CobView, me: string | null, players: Record): string { + if (v.stage === 'finished') { + if (v.solo) return v.endReason === 'soloWin' ? '성공! 공국을 모두 채웠어요' : '실패: 공국을 다 채우지 못했어요'; + const top = v.final ? [...v.final].sort((a, b) => b.total - a.total)[0] : null; + return top ? `게임 끝 · 1위 ${nick(players, top.player)}님 ${top.total}점` : '게임이 끝났어요'; + } + if (me && v.players[me]?.conceded) return '기권했어요. 구경하는 중이에요'; + const top = topOf(v); + if (v.stage === 'castle') return isMyTurn(v, me) ? '시작 성을 놓을 칸을 골라 주세요' : `${nick(players, v.waiting[0] ?? '')}님이 시작 성 칸을 고르는 중이에요`; + if (isMyTurn(v, me)) { + if (top) return `내 차례예요 · ${pendingText(top).replace(/^\S+\s/, '')}`; + return '내 차례예요. 주사위를 골라 행동해 주세요'; + } + const who = v.waiting[0]; + if (!who) return '잠시만 기다려 주세요'; + const n = nick(players, who); + return v.stage === 'phaseEnd' ? `페이즈 끝 정리 중 · ${n}님 선택` : `${n}님 차례예요`; +} + +// ---------------------------------------------------------------- options + +function Seg({ value, options, onChange, label }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { + return ( +
+ {options.map(([k, l]) => ( + + ))} +
+ ); +} +function Field({ label, children }: { label: string; children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} +const onOff = (b: boolean) => (b ? 'on' : 'off'); + +function Options({ value: o, onChange }: OptionsProps) { + const set = (patch: Partial) => onChange({ ...o, ...patch }); + return ( +
+ + set({ mode })} /> + + + set({ castleStart })} /> + + + set({ monasteryRules })} /> + + + set({ extraTiles: k === 'on' })} /> + + + set({ inns: k === 'on' })} /> + + + set({ shields: k === 'on' })} /> + + {o.mode === 'solo' && ( + + set({ soloTarget: Number(k) as CobOptions['soloTarget'] })} + /> + + )} + + set({ turnSeconds: k === 'none' ? null : (Number(k) as 60 | 90 | 120 | 180) })} + /> + + + set({ showHints: k === 'on' })} /> + +
+ ); +} + +function optionsSummary(o: CobOptions): string { + const ex = [o.extraTiles && '추가 타일', o.inns && '여관', o.shields && o.mode !== 'solo' && '방패'].filter(Boolean); + return [ + o.mode === 'solo' ? `혼자 하기(목표 ${o.soloTarget}점)` : '개인전', + o.castleStart === 'choose' ? '시작 성 고르기' : null, + o.monasteryRules === '2011' ? '2011년판 수도원' : null, + ex.length ? `확장: ${ex.join('·')}` : null, + o.turnSeconds === null ? '시간 제한 없음' : `한 차례 ${o.turnSeconds}초`, + o.showHints ? null : '도움 표시 끔', + ] + .filter(Boolean) + .join(' · '); +} + +// ---------------------------------------------------------------- rules + +function Rules({ options }: { options?: CobOptions }) { + const solo = options?.mode === 'solo'; + return ( +
+

+ 5페이즈 × 5라운드 동안, 라운드마다 주사위 2개를 굴려 하나씩 써요. 주사위 눈 = 보급소 번호 = 공국 칸 숫자 = 상품 번호예요. +

+
    +
  • + 가져오기: 눈과 같은 번호 보급소의 타일 1장을 보관 칸(3칸)으로. +
  • +
  • + 놓기: 보관 칸 타일을 공국의 같은 색·같은 숫자 빈칸에, 이미 놓인 타일과 맞닿게. +
  • +
  • + 팔기: 눈과 같은 번호 상품을 모두 팔아 은화 1개 + 장당 점수. +
  • +
  • + 일꾼 받기: 눈과 상관없이 일꾼 2개. 일꾼 1개로 눈을 ±1 바꿔요(6과 1은 이어져요). +
  • +
+

+ 차례마다 한 번 은화 2개로 검은 보급소 타일을 살 수 있어요. 같은 색 구역을 다 채우면 구역 크기 점수(1·3·6·10·15·21) + 페이즈 점수(A 10 … E 2), 한 색을 모두 채우면 색 보너스예요. +

+

+ 게임 끝에 남은 상품·은화 1개당 1점, 일꾼 2개당 1점, 점수형 수도원을 더해요. 같은 점수면 공국 빈칸이 더 많은 사람이 이겨요. +

+ {solo &&

혼자 하기: 라운드마다 흰 주사위 보급소에서 타일 1장이 빠지고, 새 구역은 강(배 칸)이나 시작 성 옆에서만 열 수 있어요. 25라운드 안에 37칸을 다 채우면 성공이에요.

} +

시간 안에 하지 않으면 일꾼 없이 놓을 수 있는 타일을 놓고(없으면 일꾼 받기) 차례를 넘겨요. 은화는 쓰지 않아요.

+
+ ); +} + +const ui: GameUI = { + Board: CobBoard, + Side: CobSide, + statusText, + isMyTurn, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/castles-of-burgundy/quick.tsx b/apps/web/src/games/castles-of-burgundy/quick.tsx new file mode 100644 index 0000000..14cdd9a --- /dev/null +++ b/apps/web/src/games/castles-of-burgundy/quick.tsx @@ -0,0 +1,75 @@ +/** 버건디의 성 30초 규칙 요약 (docs/07 §5). */ +import type { QuickCard } from '../types'; +import { DieFace, FILL, SPACE, TileHex, hexPoints } from './hex'; + +export const quickStart: QuickCard[] = [ + { + pic: ( + + + + + + = + + + + 4번 보급소 + + + + = + + + + 4 + + + ), + alt: '주사위 4는 4번 보급소와 공국의 숫자 4 칸을 뜻해요', + title: '주사위 눈 = 번호', + text: '라운드마다 주사위 2개를 하나씩 써요. 눈과 같은 번호 보급소에서 타일을 가져오고, 같은 숫자 칸에 놓아요.', + }, + { + pic: ( + + + + 🏰 + + + + + 5 + + + 같은 색·숫자, + + + 맞닿게 놓기 + + + ), + alt: '성 옆에 시장 타일이 있고, 맞닿은 파란 5번 칸이 빛나요', + title: '공국에 맞닿게 놓기', + text: '보관 칸 타일을 같은 색·같은 숫자 빈칸에, 이미 놓인 타일과 맞닿게 놓아요. 색마다 효과가 달라요.', + }, + { + pic: ( + + + + + + 구역 완성! + + + 3칸 6점 + A 페이즈 10점 + + + ), + alt: '광산 3칸 구역을 다 채워 점수를 얻어요', + title: '구역을 채워 점수', + text: '같은 색 구역을 다 채우면 크기 점수와 페이즈 점수(이를수록 큼)를 받아요. 한 색을 전부 채우면 보너스!', + }, +]; diff --git a/apps/web/src/games/help.test.ts b/apps/web/src/games/help.test.ts index 29e2479..2f275af 100644 --- a/apps/web/src/games/help.test.ts +++ b/apps/web/src/games/help.test.ts @@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti const IDS = Object.keys(GAME_UI); test('모든 게임에 도움말이 있어요', () => { - expect(IDS).toHaveLength(34); + expect(IDS).toHaveLength(35); for (const id of IDS) { const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8'); expect(src, id).toMatch(/\bquickStart,/); diff --git a/apps/web/src/games/registry.ts b/apps/web/src/games/registry.ts index 36dbfa7..8a78c4a 100644 --- a/apps/web/src/games/registry.ts +++ b/apps/web/src/games/registry.ts @@ -36,6 +36,7 @@ export const GAME_UI: Record Promise<{ default: GameUI }>> = { liar: () => import('./liar'), 'magical-athlete': () => import('./magical-athlete'), blackjack: () => import('./blackjack'), + 'castles-of-burgundy': () => import('./castles-of-burgundy'), }; const cache = new Map(); diff --git a/apps/web/src/lib/catalog-ui.ts b/apps/web/src/lib/catalog-ui.ts index 13dc3e4..2e5ad1a 100644 --- a/apps/web/src/lib/catalog-ui.ts +++ b/apps/web/src/lib/catalog-ui.ts @@ -33,6 +33,7 @@ export const GAME_ICON: Record = { liar: '🤥', 'magical-athlete': '🏃', blackjack: '🂡', + 'castles-of-burgundy': '🏰', }; /** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */ @@ -40,7 +41,7 @@ export const UPCOMING: string[] = []; /** Tabs on the game picker (docs/07 §3.3). Games not listed here only show under 전체. */ export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [ - { key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue'] }, + { key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue', 'castles-of-burgundy'] }, { key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] }, { key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple'] }, ]; diff --git a/docs/games/README.md b/docs/games/README.md index 9862aaf..3ecb20b 100644 --- a/docs/games/README.md +++ b/docs/games/README.md @@ -47,6 +47,7 @@ | `liar` | 라이어 게임 | 3~10 | 2026-10 새 게임 | | `magical-athlete` | 야단법석 달리기 | 2~6 | 2026-10 새 게임 | | `blackjack` | 블랙잭 | 1~7 | 2026-10 새 게임 | +| `castles-of-burgundy` | 버건디의 성 | 1~4 | 2026-10 새 게임 | 인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선). diff --git a/docs/games/castles-of-burgundy.md b/docs/games/castles-of-burgundy.md index 7be5f60..e48a78e 100644 --- a/docs/games/castles-of-burgundy.md +++ b/docs/games/castles-of-burgundy.md @@ -13,23 +13,24 @@ | 옵션 키 | 설명 | 선택지 | 기본값 | |---|---|---|---| -| `mode` | 게임 방식 | `standard`(2~4명 개인전, 원작), `team`(4명 2:2 팀전, 2019 확장 9, **데이터 필요: 팀 공국 12a/12b**), `solo`(1명, 2019 확장 10) | `standard` | -| `duchy` | 공국(개인 판) 고르는 법 | `beginner`(모두 1번 공국, 원작 첫 게임 권장), `same-random`(모두 같은 무작위 공국, BGA), `random-each`(각자 무작위, BGA), `choose-of-two`(무작위 2개 중 골라 쓰기, 원작 숙련자 규칙·BGA "클래식") — `beginner` 말고는 **데이터 필요: 공국 2~10번** | `beginner` | +| `mode` | 게임 방식 | `standard`(2~4명 개인전, 원작), `team`(4명 2:2 팀전, 2019 확장 9, **나중에 — 데이터 필요: 팀 공국 12a/12b**), `solo`(1명, 2019 확장 10, 1번 공국 하우스 룰) | `standard` | +| `duchy` | 공국(개인 판) 고르는 법 | `beginner`(모두 1번 공국, 원작 첫 게임 권장), `same-random`(모두 같은 무작위 공국, BGA), `random-each`(각자 무작위, BGA), `choose-of-two`(무작위 2개 중 골라 쓰기, 원작 숙련자 규칙·BGA "클래식") — `beginner` 말고는 **데이터 필요: 공국 2~10번**. **나중에**: 지금은 옵션 없이 모두 1번 공국(`beginner`) | `beginner` | | `castleStart` | 시작 성 놓는 곳 | `center`(가운데 6번 칸, 원작 기본), `choose`(공국의 진초록 칸 중 아무 데나, 차례 순서대로 골라 공개, 원작 숙련자 규칙) | `center` | | `monasteryRules` | 수도원(노란 타일) 수치 | `2019`(6번 = 7곳 모두에서 은화 2 또는 일꾼 2로 구매, 15번 = 종류당 2점, 26번 = 보너스 1장당 3점), `2011`(6번 = 7곳 모두에서 은화 2로 구매, 15번 = 3점, 26번 = 2점) | `2019` | | `extraTiles` | 추가 육각 타일 4장(2019 확장 2): 수도원 27 다리, 28 일꾼, 검은 건물 기중기, 검은 가축 거위 | `true`, `false` | `false` | | `inns` | 여관(2019 확장 6): 페이즈마다 여관 1장이 검은 보급소 옆에 쌓이고, 사서 놓으면 구역 크기 +1 | `true`, `false` | `false` | | `shields` | 방패(2019 신규 확장): 같은 눈 두 개(더블)가 나오면 두 행동 대신 방패를 가져와 성 위에 올림. 페이즈마다 방패 1개당 은화 1 유지비 | `true`, `false` | `false` | -| `whiteCastles` | 흰 성(2019 확장 5): 놓으면 흰 주사위 눈으로 행동 1번 더(**데이터 필요: 타일 9장 구성**) | `true`, `false` | `false` | -| `tradeRoutes` | 무역로(2019 확장 8): 판 상품을 무역로 칸에 차례로 놓아 색이 맞으면 보너스(**데이터 필요: 무역로 12장 내용**) | `true`, `false` | `false` | -| `borderPosts` | 국경 초소 공국(2019 확장 4, 공국 11a~11f)(**데이터 필요**) | `true`, `false` | `false` | +| `whiteCastles` | 흰 성(2019 확장 5): 놓으면 흰 주사위 눈으로 행동 1번 더(**나중에 — 데이터 필요: 타일 9장 구성**) | `true`, `false` | `false` | +| `tradeRoutes` | 무역로(2019 확장 8): 판 상품을 무역로 칸에 차례로 놓아 색이 맞으면 보너스(**나중에 — 데이터 필요: 무역로 12장 내용**) | `true`, `false` | `false` | +| `borderPosts` | 국경 초소 공국(2019 확장 4, 공국 11a~11f)(**나중에 — 데이터 필요**) | `true`, `false` | `false` | | `soloTarget` | 솔로 목표 점수 표시기 시작 칸(낮을수록 쉬움) | 45, 48, 50, 52, 55 | 50 | | `turnSeconds` | 한 차례(주사위 2개 + 구매) 제한 시간 | 60, 90, 120, 180, `null` | 120 | | `showHints` | 일꾼 몇 개로 어디에 놓을 수 있는지, 다 채우기 직전 구역, 보너스 경쟁 상황 표시 | `true`, `false` | `true` | - `playersFor`: `standard` 2~4, `team` 정확히 4, `solo` 정확히 1. - 확장 옵션은 서로 함께 켤 수 있다(원작도 자유 조합). `solo`에서는 `shields`·`tradeRoutes`를 끈다(원작 솔로 규칙에 조합 설명 없음). -- 1차 구현 범위 제안: `standard` + `beginner` + `castleStart` + `monasteryRules` + `extraTiles` + `inns` + `shields` + `solo`(1번 공국으로 대신하는 하우스 규칙, 7장). 나머지는 데이터를 구한 뒤. +- 1차 구현(2026-10): `mode`(standard·solo), `castleStart`, `monasteryRules`, `extraTiles`, `inns`, `shields`, `soloTarget`, `turnSeconds`, `showHints`. 나중에: `team`, `duchy`(2~10번), `whiteCastles`, `tradeRoutes`, `borderPosts` — 모두 지도·타일 데이터가 없어서(12장). +- 1차 구현 범위 제안(원래): `standard` + `beginner` + `castleStart` + `monasteryRules` + `extraTiles` + `inns` + `shields` + `solo`(1번 공국으로 대신하는 하우스 규칙, 7장). 나머지는 데이터를 구한 뒤. ## 3. 구성물 2019년판 기본 게임(규칙서 구성물 목록 그대로). @@ -481,3 +482,19 @@ interface CobResult extends GameResult { 5. 1번 공국의 눈 일부(사진 해상도 낮음 — 두 구현체와 일치하므로 큰 위험은 낮음). 6. 규칙 해석: 목공소·교회·시장으로 받을 때 보관 칸이 꽉 찼으면 버리고 받기(가져오기 규칙을 똑같이 적용), 수도원 5번의 "이웃 보급소"가 고리(6–1 이웃)인지, 솔로 "강으로만 넓히기" 해석. - 돈·포인트를 걸지 않는다. 은화는 게임 안의 자원일 뿐이다. + +## 13. 구현 결정 (1차 구현, 2026-10) +- 코드: `packages/games/src/castles-of-burgundy/`(data·options·types·engine·moves·index·bot), 화면 `apps/web/src/games/castles-of-burgundy/`. +- **확인 안 된 데이터는 `data.ts` 한 곳**에 "UNCONFIRMED" 주석으로 모았다: 가축 분포(`LIVESTOCK_TABLE`, 종류마다 2·2·3·3·4 + 검정 3·4), 검은 뒷면 수도원(`BLACK_MONASTERIES` 2·3·4·13·24·25), 장인 번호(`CRAFT_NUMBER`, 17 망루·22 은행만 확인), 2·3인 보급소 칸(`DEPOT_SLOTS`). +- 행동 이름은 소문자(`useDie`·`bonus`·`buy`·`ship`·`depotTake`·`warehouse`·`townhall`·`crane`·`geese`·`takeShield`·`shieldCopy`·`upkeep`·`phasePlace`·`soloTrade`·`soloBlack`·`soloBuyVp`·`buyWorkers`·`endTurn`·`concede`, 시스템 `timeout`·`leave`). 주사위 행동은 눈을 따로 보내지 않는다: 가져오기 = 보급소 번호, 놓기 = 칸 숫자, 팔기 = 상품 번호가 곧 원하는 눈이고 일꾼 수는 엔진이 계산. +- 합법성은 `actionError` 하나가 판단하고, 합법 수 목록(`legalMoves`)은 후보를 만들어 그것으로 거른다. 화면용 목록(`view.my.moves`)은 버릴 칸 변형을 뺀 꼴(`needDiscard`면 화면이 물음). +- 효과 처리 순서: 구역 완성 → 색 보너스 → 타일 효과. 선택이 필요한 효과는 `pending` 스택에 쌓고, 고를 것이 없어진 대기(빈 보급소의 시장 등)는 자동으로 건너뛴다. 검은 보급소 구매·일꾼 사기는 성 보너스 대기 중에도 된다(2019 "행동 도중 구매"). +- 두 주사위를 다 쓰고 살 것도 없으면 차례가 저절로 끝난다. 살 수 있으면 [차례 끝]을 눌러야 한다. +- 같은 눈 두 주사위는 컴퓨터·테스트용 목록에서 한쪽만 나온다(같은 수). +- 목공소·교회·시장으로 받을 때 보관 칸이 꽉 차면 1장 버리고 받는다(가져오기와 같게). 수도원 5번 이웃은 고리(6–1 이웃). +- 방패 해석: 3번 유지비는 은화 먼저, 모자라면 일꾼 1개 = 은화 1. 6번은 가져올 때 사람을 고르고, 그 사람의 수도원(27번 제외) 효과·게임 끝 점수를 내 공국 기준으로 받는다. 11번은 성 보너스 대신 아무 보급소의 방패. 14·15번(페이즈 끝 바로 놓기)은 숫자 조건 없이 색·맞닿음만 지키고, 점수(구역·색·가축·망루)와 은행·하숙집은 받지만 선택이 필요한 효과(성·배·창고·목공소·교회·시장·시청·기중기·거위)는 일어나지 않는다. 16번은 차례마다 한 번, 일꾼이 드는 주사위 하나를 공짜로 맞춘다. +- 여관: 페이즈마다 1장(`INN-1`~`INN-5`), 검은 보급소 구매와 같은 1회 구매로 맨 위 1장. 숫자·맞닿음 조건은 그대로, 구역당 1장, 타일 수 불변식에서는 따로 센다. +- 혼자 하기: 시작 성은 언제나 고르기(성 칸 4곳 중). 새 구역(아직 타일이 없는 구역)의 첫 타일은 배 칸 타일이나 시작 성과 맞닿아야 한다. 상품 판매는 2인 점수(장당 2점). 상품 5장 바꾸기는 적게 쌓인 상품부터 낸다. 점수를 얻은 뒤 다음 주사위를 쓰기 전까지 은화 1로 1점씩 살 수 있다. 수도원 점수형은 놓는 순간 그때 값으로. 방패는 꺼진다. 결과는 성공/실패(빈칸 수). +- 차례 트랙은 칸 수 제한 없이 앞으로만 간다. 동점 비교의 "차례 트랙 뒤"는 마지막 라운드 차례 순서가 늦은 사람. +- 시간 초과: 대기 중인 선택을 정해진 값으로 처리하고, 남은 주사위는 일꾼 없이 놓을 수 있으면 놓고(구역 완성 우선) 아니면 일꾼 받기, 구매는 안 한다. 3번 연속이면 자리 비움으로 10초. +- 컴퓨터: 뷰를 상태로 되돌려(더미는 빈 채로) 자기 차례 안을 미리 둔다. 1~20단계는 한 수 + 잡음, 21~40은 상위 3개 첫 수 × 두 번째 주사위(일꾼 1개까지), 41~60은 상위 6개 × 일꾼 2개까지. 정한 묶음은 차례 끝까지 기억해 다시 계산하지 않는다. 한 수 평균 2~18ms. diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index b7ceb39..043ce31 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -1191,6 +1191,86 @@ async function magicalStep(p: Page, phone: boolean, st: { picks: number; selects return false; } +/** 버건디의 성: one UI step for whoever must decide on page `p` (null = nothing to do here). */ +async function cobStep(p: Page, st: Record): Promise { + const status = (await p.locator('.turn-status').innerText().catch(() => '')).trim(); + if (!/^내 차례|시작 성을 놓을/.test(status)) return null; + const vis = (sel: string) => p.locator(`${sel}:visible`); + const confirm = async () => { + for (let i = 0; i < 2; i++) { + const sheet = p.getByRole('dialog'); + if (!(await sheet.count())) return; + const discard = sheet.getByRole('button', { name: /버리기$/ }).first(); + if (await discard.count()) { + await discard.click(); + st.discard = (st.discard ?? 0) + 1; + continue; + } + const yes = sheet.getByRole('button', { name: /^(네|놓기)$/ }).first(); + if (await yes.count()) await yes.click(); + const pick = sheet.locator('.cob-tile-sheet button').first(); + if (await pick.count()) await pick.click(); + await p.waitForTimeout(80); + } + }; + const space = vis('.cob-duchy .sp.on').first(); + // Castle choice / pendings with space targets (town hall) / die targets: prefer placing. + if (/시작 성/.test(status) && (await space.count())) { + await space.click(); + await confirm(); + return 'castle'; + } + const banner = vis('.cob-banner.mine'); + if (await banner.count()) { + if (await space.count()) { + await space.click(); + await confirm(); + return 'pendingPlace'; + } + const tile = vis('.cob-hexbtn.on:not(:disabled)').first(); + if ((await tile.count()) && !/성 보너스|목표/.test(await banner.innerText())) { + await tile.click(); + await confirm(); + return 'pendingTile'; + } + const choice = banner.locator('.cob-choices button').first(); + if (await choice.count()) { + await choice.click(); + await confirm(); + return 'pending'; + } + } + const dice = vis('.cob-diebtn:not(:disabled)'); + if (await dice.count()) { + await dice.first().click(); + await p.waitForTimeout(120); + const target = vis('.cob-duchy .sp.on').first(); + if (await target.count()) { + await target.click(); + await confirm(); + return 'place'; + } + const take = vis('.cob-hexbtn.on:not(:disabled)').first(); + if (await take.count()) { + await take.click(); + await confirm(); + return 'take'; + } + const workers = vis('.cob-bar button').filter({ hasText: '일꾼 2개 받기' }).first(); + if (await workers.count()) { + await workers.click(); + return 'workers'; + } + } + const end = vis('.cob-bar button').filter({ hasText: '차례 끝' }).first(); + if (await end.count()) { + await end.click(); + await confirm(); + return 'end'; + } + return null; +} + const PLANS: Record = { blackjack: { // PC host + phone guest. Each hand: bet the minimum, stand (decline insurance), then press 다음 판, until the @@ -3190,6 +3270,71 @@ const PLANS: Record = { console.log(` magical-athlete: ${st.picks} picks, ${st.selects} race picks, ${st.acts} turn choices (${st.second} second options), powers + wild track seen`); }, }, + 'castles-of-burgundy': { + // PC host + phone guest. Real turns through the UI (pick a die → highlighted space / depot tile / workers, + // pendings from the banner, discard and confirm sheets) for both players, screenshots on PC and phone (light + + // dark, phone depot tab), then the guest concedes and both see the result. The rules are covered by the engine tests. + drive: async (pages) => { + const [host, guest] = pages as [Page, Page]; + const st: Record = {}; + let steps = 0; + const until = Date.now() + 300_000; + while (Date.now() < until && steps < 70) { + let acted: string | null = null; + for (const p of pages) { + const before = (await p.locator('.turn-status').innerText().catch(() => '')).trim(); + acted = await cobStep(p, st); + if (acted) { + st[acted] = (st[acted] ?? 0) + 1; + steps++; + await p + .waitForFunction((b) => (document.querySelector('.turn-status')?.textContent ?? '').trim() !== b || !!document.querySelector('[role="dialog"]'), before, { timeout: 3000 }) + .catch(() => {}); + break; + } + } + if (steps === 30 && acted) { + await host.waitForTimeout(500); + await host.screenshot({ path: join(SHOTS, 'castles-of-burgundy-mid-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'castles-of-burgundy-mid-phone.png'), fullPage: true }); + const tab = guest.getByRole('tab', { name: '보급소' }); + if (await tab.count()) { + await tab.click(); + await guest.screenshot({ path: join(SHOTS, 'castles-of-burgundy-depots-phone.png'), fullPage: true }); + await guest.getByRole('tab', { name: '내 공국' }).click(); + } + // Narrowest phone (320px): no sideways overflow. + const vp = guest.viewportSize(); + await guest.setViewportSize({ width: 320, height: 640 }); + await guest.waitForTimeout(300); + await guest.screenshot({ path: join(SHOTS, 'castles-of-burgundy-mid-phone-320.png'), fullPage: true }); + const overflow = await guest.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + if (overflow > 1) throw new Error(`320px phone overflows sideways by ${overflow}px`); + if (vp) await guest.setViewportSize(vp); + await host.emulateMedia({ colorScheme: 'dark' }); + await guest.emulateMedia({ colorScheme: 'dark' }); + await host.waitForTimeout(300); + await host.screenshot({ path: join(SHOTS, 'castles-of-burgundy-mid-pc-dark.png') }); + await guest.screenshot({ path: join(SHOTS, 'castles-of-burgundy-mid-phone-dark.png'), fullPage: true }); + await host.emulateMedia({ colorScheme: 'light' }); + await guest.emulateMedia({ colorScheme: 'light' }); + } + if (!acted) await host.waitForTimeout(150); + } + if ((st.place ?? 0) + (st.take ?? 0) < 6 || !st.end) throw new Error(`too few real actions: ${JSON.stringify(st)}`); + // The guest concedes → 2-player game ends. + const concede = guest.getByRole('button', { name: /기권$/ }).first(); + await concede.scrollIntoViewIfNeeded(); + await concede.click(); + await guest.getByRole('dialog').getByRole('button', { name: '기권하기' }).click(); + await host.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 10_000 }); + await guest.getByRole('dialog', { name: '게임 결과' }).waitFor(); + await host.waitForTimeout(500); + await host.screenshot({ path: join(SHOTS, 'castles-of-burgundy-result-pc.png') }); + await guest.screenshot({ path: join(SHOTS, 'castles-of-burgundy-result-phone.png') }); + console.log(` castles-of-burgundy: ${steps} UI steps ${JSON.stringify(st)}`); + }, + }, }; const games = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(PLANS); diff --git a/packages/games/package.json b/packages/games/package.json index 62f16f9..fb954ef 100644 --- a/packages/games/package.json +++ b/packages/games/package.json @@ -12,6 +12,7 @@ "./liar/topics": "./src/liar/topics.ts", "./magical-athlete/racers": "./src/magical-athlete/racers.ts", "./seotda/money": "./src/seotda/money.ts", + "./castles-of-burgundy/data": "./src/castles-of-burgundy/data.ts", "./*": "./src/*/index.ts" }, "dependencies": { diff --git a/packages/games/src/bots/index.ts b/packages/games/src/bots/index.ts index 14d5844..48cdf18 100644 --- a/packages/games/src/bots/index.ts +++ b/packages/games/src/bots/index.ts @@ -38,6 +38,7 @@ import { unoBot } from '../uno/bot'; import { liarBot } from '../liar/bot'; import { magicalAthleteBot } from '../magical-athlete/bot'; import { blackjackBot } from '../blackjack/bot'; +import { cobBot } from '../castles-of-burgundy/bot'; export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types'; export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona'; @@ -73,6 +74,7 @@ export const BOT_STRATEGIES: Record = { uno: unoBot, 'magical-athlete': magicalAthleteBot, blackjack: blackjackBot, + 'castles-of-burgundy': cobBot, }; /** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */ diff --git a/packages/games/src/castles-of-burgundy/bot.test.ts b/packages/games/src/castles-of-burgundy/bot.test.ts new file mode 100644 index 0000000..d083068 --- /dev/null +++ b/packages/games/src/castles-of-burgundy/bot.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, test } from 'bun:test'; +import { SeededRng, seedN } from '@bg/engine'; +import { decideBotAction } from '../bots/index'; +import { castlesOfBurgundy as def, type CobState } from './index'; + +function play(levels: number[], seed: number, opts = {}): number[] { + const players = levels.map((_, i) => `bot:${i}:x`); + const rng = SeededRng.fromSeed(seedN(seed)); + const ch = SeededRng.fromSeed(seedN(seed + 999)); + let s: CobState = def.setup({ players, options: def.optionsSchema.parse(opts), rng, now: 0 }); + let now = 0; + for (let i = 0; i < 5000 && !def.result(s); i++) { + const p = def.activePlayers(s)[0]!; + const a = decideBotAction(def, s, p, { now, random: () => ch.next(), level: levels[players.indexOf(p)] }); + expect(a).not.toBeNull(); + s = def.apply(s, p, a as never, { rng, now: (now += 1000) }).state; + } + expect(def.result(s)).not.toBeNull(); + return s.final!.map((r) => r.total); +} + +describe('castles-of-burgundy bot', () => { + test('1단계 < 60단계 (평균 점수, 같은 판에서)', () => { + let weak = 0; + let strong = 0; + for (let g = 1; g <= 3; g++) { + const [a, b] = play([1, 60], g); + weak += a!; + strong += b!; + } + expect(strong).toBeGreaterThan(weak); + }, 60_000); + test('확장을 모두 켜고 4명이 끝까지', () => { + const r = play([30, 45, 60, 10], 4, { shields: true, inns: true, extraTiles: true }); + expect(r).toHaveLength(4); + }, 60_000); + test('혼자 하기도 끝까지', () => { + play([60], 5, { mode: 'solo' }); + }, 60_000); +}); diff --git a/packages/games/src/castles-of-burgundy/bot.ts b/packages/games/src/castles-of-burgundy/bot.ts new file mode 100644 index 0000000..74b5ec6 --- /dev/null +++ b/packages/games/src/castles-of-burgundy/bot.ts @@ -0,0 +1,167 @@ +/** + * 버건디의 성 computer player (docs/games/castles-of-burgundy.md §8.7). It only sees its view and legal moves: the + * view is turned back into a state without the hidden piles (`stateFromView`), which is enough to look ahead inside + * its own turn (nothing random happens until the turn ends). It scores whole turn bundles — die A → die B (with the + * effects they trigger, resolved greedily) — and keeps the plan for the rest of the turn. + */ +import type { PlayerId, Rng } from '@bg/engine'; +import type { BotStrategy } from '../bots/types'; +import { humanBest } from '../bots/policy'; +import { DUCHY_1, GOODS_VP, PHASE_VP, REGION_VP, tileDef } from './data'; +import { boardN, finalRow, perform, placeSpaces, waitingOn } from './engine'; +import { stateFromView } from './index'; +import { legalMoves } from './moves'; +import type { CobAction, CobState, CobView } from './types'; + +const RNG: Rng = { next: () => 0.5, int: () => 0, shuffle: (a: readonly T[]) => [...a] }; +const key = (a: CobAction) => JSON.stringify(a); + +function sim(s: CobState, me: PlayerId, a: CobAction): CobState { + const c = structuredClone(s); + try { + perform(c, me, a, { rng: RNG, now: 0 }); + } catch { + c.players[me]!.vp -= 1000; + } + return c; +} + +const myFreeTurn = (s: CobState, me: PlayerId, turnSeq: number) => s.stage === 'turn' && s.current === me && s.turnSeq === turnSeq; + +const TILE_WORTH: Record = { castle: 6, ship: 4.5, livestock: 4, building: 4, monastery: 4.5, mine: 3, inn: 3 }; + +/** Rough worth of a state for `me` (points now + what the resources and progress are likely to bring). */ +export function evaluate(s: CobState, me: PlayerId, base: { phase: number; round: number; turnSeq: number }): number { + const pl = s.players[me]!; + const elapsed = base.phase * 5 + base.round; + const rem = Math.max(0, 25 - elapsed) / 25; + const N = boardN(s); + let v = finalRow(s, me).total; + v += Math.min(pl.silver, 6) * 0.5 * rem + Math.min(pl.workers, 8) * 0.35 * rem; + const goods = pl.goods.reduce((a, g) => a + g.count, 0); + v += goods * (GOODS_VP[N]! * 0.6 - 1) * (0.3 + 0.7 * rem) + pl.goods.reduce((a, g) => a + (g.count - 1) * 0.4, 0); + for (const t of pl.storage) { + const fd = pl.facedown.includes(t); + const def = tileDef(t); + const w = fd ? 2.5 : def.color === 'livestock' ? 2 + (def.count ?? 2) : (TILE_WORTH[def.color] ?? 3); + const n = placeSpaces(s, me, t).length; + v += (n ? w * (0.55 + 0.15 * Math.min(3, n)) : 0.6) * (0.25 + 0.75 * rem); + } + const D = DUCHY_1; + const nextPhase = Math.min(4, base.phase + (base.round >= 3 ? 1 : 0)); + for (const r of D.regions) { + const k = r.spaces.filter((x) => pl.placed[x]).length; + if (k > 0 && k < r.spaces.length) v += (k / r.spaces.length) ** 2 * (REGION_VP[r.spaces.length]! + PHASE_VP[nextPhase]!) * 0.45; + } + const mines = D.spaces.filter((x) => x.color === 'mine' && pl.placed[x.id]).length; + v += mines * Math.max(0, 4 - base.phase) * 0.9; + const ongoing = Object.values(pl.placed).filter((t) => { + const d = tileDef(t); + return d.monastery && !d.craft && ![15, 24, 25, 26].includes(d.monastery); + }).length; + v += ongoing * 5 * rem; + const others = s.seats.filter((q) => q !== me && !s.players[q]!.conceded); + if (others.length) { + const avg = others.reduce((a, q) => a + s.players[q]!.track.pos, 0) / others.length; + v += Math.max(-2, Math.min(2, pl.track.pos - avg)) * 1.2 * rem; + } + if (myFreeTurn(s, me, base.turnSeq)) { + v += (pl.used[0] ? 0 : 2.5) + (pl.used[1] ? 0 : 2.5); + const top = s.pending[s.pending.length - 1]; + if (top?.kind === 'bonus') v += 3; + } + if (s.solo) v += Object.keys(pl.placed).length * 5; + if (s.stage === 'finished' && s.endReason === 'soloWin') v += 1000; + return v; +} + +/** Resolve my own pendings greedily (one-step look-ahead each). */ +function resolve(s: CobState, me: PlayerId, base: { phase: number; round: number; turnSeq: number }, plan: CobAction[]): CobState { + for (let i = 0; i < 6; i++) { + if (!myFreeTurn(s, me, base.turnSeq) || !s.pending.length) return s; + const top = s.pending[s.pending.length - 1]!; + if (top.kind === 'bonus') return s; // a bonus action is a real choice: searched like a die + const moves = legalMoves(s, me); + if (!moves.length) return s; + let best = moves[0]!.a; + let bestV = -Infinity; + for (const m of moves) { + const v = evaluate(sim(s, me, m.a), me, base); + if (v > bestV) { + bestV = v; + best = m.a; + } + } + plan.push(best); + s = sim(s, me, best); + } + return s; +} + +/** Cheap pruning: obviously poor die moves (expensive conversions) are skipped at the second level. */ +function trim(moves: { a: CobAction; cost: number }[], maxCost: number): { a: CobAction; cost: number }[] { + return moves.filter((m) => m.cost <= maxCost); +} + +interface Plan { + me: PlayerId; + turnSeq: number; + seq: number; + actions: CobAction[]; +} +const PLANS = new Map(); + +export const cobBot: BotStrategy = ({ me, view, legal, random, level }) => { + const s0 = stateFromView(view); + const legalKeys = new Set(legal.map(key)); + // Follow the plan made earlier this turn while nothing unexpected happened. + const cached = PLANS.get(me); + if (cached && cached.turnSeq === view.turnSeq && cached.seq === view.seq && cached.actions.length) { + const next = cached.actions[0]!; + if (legalKeys.has(key(next))) { + PLANS.set(me, { ...cached, seq: view.seq + 1, actions: cached.actions.slice(1) }); + return next; + } + } + PLANS.delete(me); + const base = { phase: s0.phase, round: s0.round, turnSeq: s0.turnSeq }; + const L = level ?? 60; + if (!waitingOn(s0).includes(me)) return legal[0]!; + // Castle choice / phase-end choices: one-step look-ahead. + const first = legalMoves(s0, me).filter((m) => legalKeys.has(key(m.a))); + const pool = first.length ? first : legal.map((a) => ({ a, cost: 0 })); + const deep = L > 20 && s0.stage === 'turn'; + const K = L > 40 ? 6 : 3; + const maxCost = L > 40 ? 2 : 1; + const scored = pool.map((m) => { + const plan: CobAction[] = [m.a]; + const s1 = resolve(sim(s0, me, m.a), me, base, plan); + const noise = L <= 20 ? random() * (8 - L * 0.3) : 0; + return { a: m.a, s1, plan, v: evaluate(s1, me, base) + noise }; + }); + if (deep) { + scored.sort((x, y) => y.v - x.v); + for (const c of scored.slice(0, K)) { + if (!myFreeTurn(c.s1, me, base.turnSeq)) continue; + const second = trim(legalMoves(c.s1, me), maxCost); + let bestV = c.v; + let bestPlan = c.plan; + for (const m of second) { + if (m.a.type === 'endTurn') continue; + const plan = [...c.plan, m.a]; + const s2 = resolve(sim(c.s1, me, m.a), me, base, plan); + const v = evaluate(s2, me, base); + if (v > bestV) { + bestV = v; + bestPlan = plan; + } + } + c.v = bestV; + c.plan = bestPlan; + } + } + const pickFrom = deep ? scored.slice(0, Math.max(K, 1)) : scored; + const chosen = humanBest(pickFrom, (x) => x.v, random, level, { small: 2, critical: 1e9 }); + if (chosen.plan.length > 1) PLANS.set(me, { me, turnSeq: view.turnSeq, seq: view.seq + 1, actions: chosen.plan.slice(1) }); + return chosen.a; +}; diff --git a/packages/games/src/castles-of-burgundy/castles-of-burgundy.test.ts b/packages/games/src/castles-of-burgundy/castles-of-burgundy.test.ts new file mode 100644 index 0000000..81222c5 --- /dev/null +++ b/packages/games/src/castles-of-burgundy/castles-of-burgundy.test.ts @@ -0,0 +1,616 @@ +import { describe, expect, test } from 'bun:test'; +import { SeededRng, playoutSeeds, randomPlayout, seedN } from '@bg/engine'; +import { DUCHY_1, TILES, depotColors, type Die } from './data'; +import { finalRow, perform, placeError, rawCost, turnOrder } from './engine'; +import { castlesOfBurgundy as def, goodsCount, legalMoves, tileCount, view, type CobAction, type CobOptions, type CobState } from './index'; + +const rng = (n = 1) => SeededRng.fromSeed(seedN(n)); +let clock = 1; + +function make(opts: Partial = {}, players = ['A', 'B']): CobState { + return def.setup({ players, options: def.optionsSchema.parse(opts), rng: rng(), now: 0 }); +} +function act(s: CobState, p: string, a: CobAction): CobState { + const v = def.validate(s, p, a); + if (!v.ok) throw new Error(v.reason); + return def.apply(s, p, a, { rng: rng(clock), now: clock++ * 1000 }).state; +} +const err = (s: CobState, p: string, a: CobAction) => { + const v = def.validate(s, p, a); + return v.ok ? null : v.reason; +}; +/** Space id at axial (q, r). */ +const sp = (q: number, r: number) => DUCHY_1.spaces.find((x) => x.q === q && x.r === r)!.id; +const cur = (s: CobState) => s.current!; +const P = (s: CobState) => s.players[cur(s)]!; +/** Give the current player tiles in storage, dice and resources; clears pending. */ +function rig(s: CobState, o: { storage?: string[]; dice?: [Die, Die]; workers?: number; silver?: number; placed?: Record }): CobState { + s = structuredClone(s); + const pl = P(s); + if (o.storage) pl.storage = o.storage; + if (o.dice) pl.dice = o.dice; + if (o.workers !== undefined) pl.workers = o.workers; + if (o.silver !== undefined) pl.silver = o.silver; + if (o.placed) Object.assign(pl.placed, o.placed); + pl.used = [false, false]; + s.pending = []; + return s; +} + +describe('data', () => { + test('1번 공국: 37칸, 색 개수, 13개 구역, 마을 크기', () => { + expect(DUCHY_1.spaces).toHaveLength(37); + expect(DUCHY_1.colorCount).toEqual({ castle: 4, mine: 3, monastery: 6, building: 12, livestock: 6, ship: 6 }); + expect(DUCHY_1.regions).toHaveLength(13); + const towns = DUCHY_1.regions.filter((r) => r.color === 'building').map((r) => r.spaces.length).sort(); + expect(towns).toEqual([1, 3, 3, 5]); + expect(DUCHY_1.startSpace).toBe(18); + const r11 = DUCHY_1.regions[DUCHY_1.regionOf[sp(0, 1)]!]!; + expect(r11.spaces.map((x) => DUCHY_1.spaces[x]!.die).sort()).toEqual([1, 3, 3, 5, 6]); + const dice = DUCHY_1.spaces.filter((x) => x.id !== 18).map((x) => x.die); + expect([1, 2, 3, 4, 5, 6].map((d) => dice.filter((x) => x === d).length)).toEqual([7, 6, 6, 6, 6, 5]); + }); + test('타일 164장(+확장 4), 색별 뒷면', () => { + const base = Object.values(TILES).filter((t) => !t.extra && t.color !== 'inn'); + expect(base).toHaveLength(164); + expect(base.filter((t) => t.back === 'black')).toHaveLength(40); + expect(base.filter((t) => t.color === 'monastery')).toHaveLength(26); + }); + test('보급소 칸 색: 4명 합계, 3명 6번 보급소 B·D는 광산', () => { + const all = [1, 2, 3, 4, 5, 6].flatMap((d) => depotColors(d, 4, 0)); + expect(all.filter((c) => c === 'building')).toHaveLength(8); + expect(all.filter((c) => c === 'castle')).toHaveLength(2); + expect(depotColors(6, 3, 0)[2]).toBe('castle'); + expect(depotColors(6, 3, 1)[2]).toBe('mine'); + expect(depotColors(6, 3, 3)[2]).toBe('mine'); + }); +}); + +describe('setup', () => { + test.each([2, 3, 4])('%i명: 칸 수, 일꾼 1~4, 은화 1, 상품 3장', (n) => { + const s = make({}, ['A', 'B', 'C', 'D'].slice(0, n)); + expect(s.depots.reduce((a, d) => a + d.slots.length, 0)).toBe(6 * n); + expect(s.black).toHaveLength(2 * n); + const order = turnOrder(s); + order.forEach((p, i) => expect(s.players[p]!.workers).toBe(i + 1)); + for (const p of order) { + expect(s.players[p]!.silver).toBe(1); + expect(s.players[p]!.goods.reduce((a, g) => a + g.count, 0)).toBe(3); + expect(s.players[p]!.placed[18]).toMatch(/^C-/); + } + expect(s.phaseGoods).toHaveLength(4); + expect(s.roundGoods).toHaveLength(4); // one already placed on the white die's depot + expect(goodsCount(s)).toBe(42); + expect(s.depots[s.whiteDie - 1]!.goods).toHaveLength(1); + }); + test('흰 주사위로는 행동하지 않고 상품만 그 보급소로', () => { + const s = make(); + expect(legalMoves(s, cur(s)).some((m) => m.a.type === 'useDie' && (m.a.die as number) > 1)).toBe(false); + }); + test('성 고르기(choose): 차례 순서대로 성 칸에', () => { + let s = make({ castleStart: 'choose' }); + expect(s.stage).toBe('castle'); + const first = s.castleQueue[0]!; + expect(err(s, first, { type: 'chooseCastle', space: 0 })).toBeTruthy(); + s = act(s, first, { type: 'chooseCastle', space: sp(1, -3) }); + s = act(s, s.castleQueue[0]!, { type: 'chooseCastle', space: 18 }); + expect(s.stage).toBe('turn'); + expect(s.players[first]!.placed[sp(1, -3)]).toBeTruthy(); + }); +}); + +describe('workers & dice', () => { + test('일꾼 비용: 2→6 2개, 6→1 1개, 수도원 8번이면 3→6 1개, 9번이면 건물 3→4 공짜', () => { + let s = make(); + const p = cur(s); + expect(rawCost(s, p, 2, 6, 'none')).toBe(2); + expect(rawCost(s, p, 6, 1, 'none')).toBe(1); + s = rig(s, { placed: { [sp(1, -1)]: 'K-08' } }); + expect(rawCost(s, p, 3, 6, 'none')).toBe(2); + expect(rawCost(s, p, 2, 6, 'none')).toBe(1); + s = rig(s, { placed: { [sp(1, -1)]: 'K-09' } }); + expect(rawCost(s, p, 3, 4, 'place-building')).toBe(0); + expect(rawCost(s, p, 3, 5, 'place-building')).toBe(1); + }); + test('일꾼이 모자라면 거부', () => { + let s = make(); + s = rig(s, { storage: ['S-01'], dice: [2, 2], workers: 0 }); + // (1,0) ship 5 touches the castle: 2→5 = 3 workers + expect(err(s, cur(s), { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(1, 0) } })).toMatch(/일꾼/); + s = rig(s, { workers: 3 }); + const s2 = act(s, cur(s), { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(1, 0) } }); + expect(s2.players[cur(s)]!.workers).toBe(0); + }); + test('일꾼 받기 2개, 수도원 14번 4개, 13번 은화 +1', () => { + let s = make(); + const p = cur(s); + s = rig(s, { workers: 0, silver: 0 }); + let s2 = act(s, p, { type: 'useDie', die: 0, act: { kind: 'workers' } }); + expect(s2.players[p]!.workers).toBe(2); + s = rig(s, { placed: { [sp(1, -1)]: 'K-14', [sp(-1, 2)]: 'K-13' } }); + s2 = act(s, p, { type: 'useDie', die: 0, act: { kind: 'workers' } }); + expect(s2.players[p]!.workers).toBe(4); + expect(s2.players[p]!.silver).toBe(1); + }); +}); + +describe('take & place', () => { + test('보관 칸이 꽉 차면 버릴 칸이 필요, 검은 보급소는 주사위로 못 가져옴', () => { + let s = make(); + const p = cur(s); + const tile = s.depots[0]!.slots[0]!; + s = rig(s, { storage: ['S-01', 'S-02', 'S-03'], dice: [1, 1] }); + expect(err(s, p, { type: 'useDie', die: 0, act: { kind: 'take', tile } })).toMatch(/꽉/); + const s2 = act(s, p, { type: 'useDie', die: 0, act: { kind: 'take', tile, discard: 0 } }); + expect(s2.players[p]!.storage).toEqual(['S-02', 'S-03', tile]); + const blk = s.black[0]!; + expect(err(s, p, { type: 'useDie', die: 0, act: { kind: 'take', tile: blk, discard: 0 } })).toBeTruthy(); + }); + test('놓기: 색·눈·맞닿음 각각 거부, 첫 타일은 성 주변만', () => { + const s = make(); + const p = cur(s); + expect(placeError(s, p, 'S-01', sp(0, 1), null)).toMatch(/색/); + expect(placeError(s, p, 'S-01', sp(1, 0), 4)).toMatch(/눈/); + expect(placeError(s, p, 'S-01', sp(2, 0), null)).toMatch(/맞닿/); + expect(placeError(s, p, 'S-01', sp(1, 0), 5)).toBeNull(); + }); + test('같은 마을 같은 건물 금지, 수도원 1번이면 허용, 다른 마을이면 허용', () => { + let s = make(); + const p = cur(s); + s = rig(s, { placed: { [sp(0, 1)]: 'B-market-1' } }); + expect(placeError(s, p, 'B-market-2', sp(1, 1), null)).toMatch(/같은 건물/); + expect(placeError(s, p, 'B-bank-1', sp(1, 1), null)).toBeNull(); + s = rig(s, { placed: { [sp(1, -1)]: 'K-01' } }); + expect(placeError(s, p, 'B-market-2', sp(1, 1), null)).toBeNull(); + }); + test('구역 완성: A 페이즈 3칸 = 6 + 10 = 16점, 시작 성 구역은 0점', () => { + let s = make(); + const p = cur(s); + expect(s.players[p]!.vp).toBe(0); + // R8 ship region (1,0,5) (2,0,4) (3,0,1): fill two, place the third + s = rig(s, { placed: { [sp(1, 0)]: 'S-01', [sp(2, 0)]: 'S-02' }, storage: ['S-03'], dice: [1, 6] }); + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(3, 0) } }); + expect(s.players[p]!.vp).toBe(16); + expect(s.pending.at(-1)?.kind).toBe('ship'); + }); + test('구역 완성: E 페이즈 5칸 = 15 + 2 = 17점', () => { + let s = make(); + const p = cur(s); + s.phase = 4; + s = rig(s, { placed: { [sp(0, 1)]: 'B-bank-1', [sp(1, 1)]: 'B-market-1', [sp(0, 2)]: 'B-church-1', [sp(1, 2)]: 'B-boarding-1' }, storage: ['B-watchtower-1'], dice: [3, 3] }); + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(0, 3) } }); + expect(s.players[p]!.vp).toBe(17 + 4); // + watchtower + }); +}); + +describe('colour bonus', () => { + function fillAllButOne(s: CobState, p: string, color: string): { space: number; s: CobState } { + const spaces = DUCHY_1.spaces.filter((x) => x.color === color && x.id !== 18); + const last = spaces.at(-1)!; + s = structuredClone(s); + let i = 0; + for (const x of spaces.slice(0, -1)) s.players[p]!.placed[x.id] = color === 'mine' ? `M-0${++i}` : `S-1${++i}`; + return { space: last.id, s }; + } + test('2명: 첫 완성 큰 보너스 5점, 둘째 작은 2점', () => { + let s = make(); + const a = cur(s); + const b = s.seats.find((x) => x !== a)!; + let r = fillAllButOne(s, a, 'mine'); + s = r.s; + s.players[b]!.placed = { ...s.players[a]!.placed }; + s = rig(s, { storage: ['M-09'], dice: [DUCHY_1.spaces[r.space]!.die, 1] }); + const before = s.players[a]!.vp; + s = act(s, a, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: r.space } }); + // mine region R10 completes too (3 spaces): 6 + 10, plus large bonus 5 + expect(s.players[a]!.vp - before).toBe(16 + 5); + expect(s.bonusLeft.mine).toEqual(['small']); + }); + test('4명 큰 7점', () => { + let s = make({}, ['A', 'B', 'C', 'D']); + const a = cur(s); + const r = fillAllButOne(s, a, 'mine'); + s = rig(r.s, { storage: ['M-09'], dice: [DUCHY_1.spaces[r.space]!.die, 1] }); + s = act(s, a, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: r.space } }); + expect(s.players[a]!.vp).toBe(16 + 7); + }); +}); + +describe('livestock', () => { + const pasture = { q: [0, -1, 0, -2, -1], r: [-3, -2, -2, -1, -1] }; // R1 (5 spaces) + test('양 4 있는 목초지에 양 3 → 7점, 수도원 7번이면 9점, 다른 목초지는 안 셈', () => { + let s = make(); + const p = cur(s); + // Need adjacency: put a tile path from the castle: (0,-1) building, then (-1,-1) pasture. + s = rig(s, { placed: { [sp(0, -1)]: 'B-bank-1', [sp(-1, -1)]: 'L-sheep-4-5', [sp(2, 1)]: 'L-sheep-4-7' }, storage: ['L-sheep-3-3'], dice: [5, 5] }); + let s2 = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(-2, -1) } }); + expect(s2.players[p]!.vp).toBe(7); + s = rig(s, { placed: { [sp(1, -1)]: 'K-07' } }); + s2 = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(-2, -1) } }); + expect(s2.players[p]!.vp).toBe(9); + void pasture; + }); + test('다른 종류는 그 타일만', () => { + let s = make(); + const p = cur(s); + s = rig(s, { placed: { [sp(0, -1)]: 'B-bank-1', [sp(-1, -1)]: 'L-sheep-4-5' }, storage: ['L-pig-2-1'], dice: [5, 5] }); + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(-2, -1) } }); + expect(s.players[p]!.vp).toBe(2); + }); +}); + +describe('ship', () => { + test('상품 3종 보유 중 새 종류는 남고, 넘치면 고르기, 차례 트랙 전진', () => { + let s = make(); + const p = cur(s); + s = rig(s, { storage: ['S-01'], dice: [5, 5] }); + s.players[p]!.goods = [ + { die: 1, count: 1 }, + { die: 2, count: 1 }, + { die: 3, count: 1 }, + ]; + for (const d of s.depots) d.goods = []; + s.depots[3]!.goods = [1, 4, 4]; + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(1, 0) } }); + expect(s.pending.at(-1)?.kind).toBe('ship'); + s = act(s, p, { type: 'ship', depot: 4 }); + expect(s.players[p]!.goods.find((g) => g.die === 1)!.count).toBe(2); + expect(s.depots[3]!.goods).toEqual([4, 4]); + expect(s.players[p]!.track.pos).toBe(1); + expect(turnOrder(s)[0]).toBe(p); + }); + test('넘칠 때 담을 종류 고르기', () => { + let s = make(); + const p = cur(s); + s = rig(s, { storage: ['S-01'], dice: [5, 5] }); + s.players[p]!.goods = [ + { die: 1, count: 1 }, + { die: 2, count: 1 }, + ]; + for (const d of s.depots) d.goods = []; + s.depots[1]!.goods = [5, 6]; + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(1, 0) } }); + expect(err(s, p, { type: 'ship', depot: 2 })).toMatch(/골라/); + s = act(s, p, { type: 'ship', depot: 2, keep: [6] }); + expect(s.players[p]!.goods.map((g) => g.die).sort()).toEqual([1, 2, 6]); + }); + test('수도원 5번: 이웃 보급소(6과 1 이웃)', () => { + let s = make(); + const p = cur(s); + s = rig(s, { storage: ['S-01'], dice: [5, 5], placed: { [sp(1, -1)]: 'K-05' } }); + s.players[p]!.goods = []; + for (const d of s.depots) d.goods = []; + s.depots[5]!.goods = [3]; + s.depots[0]!.goods = [4]; + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(1, 0) } }); + expect(err(s, p, { type: 'ship', depot: 6, adjacent: 3 })).toBeTruthy(); + s = act(s, p, { type: 'ship', depot: 6, adjacent: 1 }); + expect(s.players[p]!.goods.map((g) => g.die).sort()).toEqual([3, 4]); + }); +}); + +describe('castle & buildings', () => { + test('성: 보너스 행동으로 또 성 → 연쇄', () => { + let s = make(); + const p = cur(s); + // R2 castle region: (1,-2,6) touches the start castle via (1,-1)? no — use (1,-2) after (0,-1) + s = rig(s, { placed: { [sp(0, -1)]: 'B-bank-1' }, storage: ['C-05', 'C-06'], dice: [6, 6] }); + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(1, -2) } }); + expect(s.pending.at(-1)).toEqual({ kind: 'bonus', source: 'castle' }); + s = act(s, p, { type: 'bonus', act: { kind: 'place', slot: 0, space: sp(1, -3) } }); + expect(s.pending.at(-1)).toEqual({ kind: 'bonus', source: 'castle' }); + s = act(s, p, { type: 'bonus', act: { kind: 'workers' } }); + expect(s.players[p]!.placed[sp(1, -3)]).toBe('C-06'); + }); + test('시장: 배·가축만, 시청: 눈 조건 없이 놓고 효과 발동, 창고: 주사위 없이 판매', () => { + let s = make(); + const p = cur(s); + s = rig(s, { storage: ['B-market-1', 'B-townhall-1', 'S-01'], dice: [3, 1] }); + const ship = s.depots.flatMap((d) => d.slots).find((t) => t && TILES[t]!.color === 'ship')!; + const bld = s.depots.flatMap((d) => d.slots).find((t) => t && TILES[t]!.color === 'building')!; + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(0, 1) } }); + expect(s.pending.at(-1)?.kind).toBe('depotTake'); + expect(err(s, p, { type: 'depotTake', tile: bld })).toBeTruthy(); + s = act(s, p, { type: 'depotTake', tile: ship }); + expect(s.players[p]!.storage).toContain(ship); + // town hall on (1,1) [die 1], then place the ship at (1,0) [die 5] without a die + s = act(s, p, { type: 'useDie', die: 1, act: { kind: 'place', slot: 0, space: sp(1, 1) } }); + expect(s.pending.at(-1)?.kind).toBe('townhall'); + s = act(s, p, { type: 'townhall', slot: s.players[p]!.storage.indexOf('S-01'), space: sp(1, 0) }); + expect(s.pending.at(-1)?.kind).toBe('ship'); + }); + test('창고·은행·하숙집·망루', () => { + let s = make({}, ['A', 'B', 'C']); + const p = cur(s); + s = rig(s, { storage: ['B-warehouse-1', 'B-bank-1'], dice: [3, 1], silver: 0, workers: 0 }); + s.players[p]!.goods = [{ die: 4, count: 4 }]; + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(0, 1) } }); + s = act(s, p, { type: 'warehouse', goods: 4 }); + expect(s.players[p]!.vp).toBe(12); // 3 players: 4 × 3 + expect(s.players[p]!.silver).toBe(1); + s = act(s, p, { type: 'useDie', die: 1, act: { kind: 'place', slot: 0, space: sp(1, 1) } }); + expect(s.players[p]!.silver).toBe(3); + }); +}); + +describe('selling & buying', () => { + test('3명 4장 = 은화 1 + 12점, 수도원 3·4번', () => { + let s = make({}, ['A', 'B', 'C']); + const p = cur(s); + s = rig(s, { dice: [4, 4], silver: 0, workers: 0, placed: { [sp(1, -1)]: 'K-03', [sp(-1, 2)]: 'K-04' } }); + s.players[p]!.goods = [{ die: 4, count: 4 }]; + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'sell', goods: 4 } }); + expect(s.players[p]!.vp).toBe(12); + expect(s.players[p]!.silver).toBe(2); + expect(s.players[p]!.workers).toBe(1); + expect(s.players[p]!.goods).toEqual([]); + }); + test('구매: 차례당 1번 은화 2, 2019 수도원 6번이면 번호 보급소·일꾼 지불, 2011은 일꾼 거부', () => { + let s = make(); + const p = cur(s); + s = rig(s, { silver: 4, workers: 4 }); + const blk = s.black[0]!; + const dep = s.depots[0]!.slots[0]!; + expect(err(s, p, { type: 'buy', tile: dep, pay: 'silver' })).toBeTruthy(); + expect(err(s, p, { type: 'buy', tile: blk, pay: 'workers' })).toBeTruthy(); + const s2 = act(s, p, { type: 'buy', tile: blk, pay: 'silver' }); + expect(s2.players[p]!.silver).toBe(2); + expect(err(s2, p, { type: 'buy', tile: s2.black[1]!, pay: 'silver' })).toMatch(/이미/); + const m6 = rig(s, { placed: { [sp(1, -1)]: 'K-06' } }); + expect(err(m6, p, { type: 'buy', tile: dep, pay: 'workers' })).toBeNull(); + let o = make({ monasteryRules: '2011' }); + o = rig(o, { silver: 4, workers: 4, placed: { [sp(1, -1)]: 'K-06' } }); + expect(err(o, cur(o), { type: 'buy', tile: o.depots[0]!.slots[0]!, pay: 'workers' })).toBeTruthy(); + expect(err(o, cur(o), { type: 'buy', tile: o.depots[0]!.slots[0]!, pay: 'silver' })).toBeNull(); + }); +}); + +describe('phase end & game end', () => { + test('페이즈 끝: 광산 1개당 은화 1, 수도원 2번이면 일꾼도', () => { + let s = make(); + for (const p of s.seats) { + s.players[p]!.placed[sp(-1, 1)] = p === 'A' ? 'M-01' : 'M-02'; + if (p === 'A') s.players[p]!.placed[sp(1, -1)] = 'K-02'; + } + const silver = { A: s.players.A!.silver, B: s.players.B!.silver }; + const workers = { A: s.players.A!.workers, B: s.players.B!.workers }; + // play 10 turns of "take workers" + end + for (let i = 0; i < 10; i++) { + const p = cur(s); + s = act(s, p, { type: 'endTurn' }); + } + expect(s.phase).toBe(1); + expect(s.players.A!.silver).toBe(silver.A + 1); + expect(s.players.B!.silver).toBe(silver.B + 1); + expect(s.players.A!.workers).toBe(workers.A + 1); + expect(s.players.B!.workers).toBe(workers.B); + }); + test('페이즈 시작: 남은 육각 타일은 빠지고 상품은 남음', () => { + let s = make(); + const goodsBefore = s.depots.reduce((a, d) => a + d.goods.length, 0); + for (let i = 0; i < 10; i++) s = act(s, cur(s), { type: 'endTurn' }); + expect(s.depots.reduce((a, d) => a + d.goods.length, 0)).toBe(goodsBefore + 4 + 1); + expect(s.out.tiles).toBe(16); + }); + test('게임 끝 점수: 상품·은화·일꾼 2개당 1점·수도원 15/25/26(2019·2011)', () => { + const s = make(); + const p = cur(s); + const pl = s.players[p]!; + Object.assign(pl, { vp: 50, silver: 3, workers: 5, goods: [{ die: 1, count: 2 }], sold: [2, 1, 0, 0, 0, 0], bonus: [{ color: 'mine', size: 'large' }] }); + pl.placed[sp(1, -1)] = 'K-15'; + pl.placed[sp(-1, 2)] = 'K-25'; + pl.placed[sp(2, -2)] = 'K-26'; + pl.placed[sp(3, -3)] = 'K-B-bank'; + pl.placed[sp(0, 1)] = 'B-bank-1'; + const r = finalRow(s, p); + expect(r.total).toBe(50 + 2 + 3 + 2 + 4 + 3 + 3 + 4); + const o = { ...s, options: { ...s.options, monasteryRules: '2011' as const } }; + expect(finalRow(o, p).total).toBe(50 + 2 + 3 + 2 + 6 + 3 + 2 + 4); + }); + test('동점: 빈칸 많은 사람이 위', () => { + let s = make(); + s.stage = 'finished'; + s.final = [ + { player: 'A', inGame: 0, goodsLeft: 0, silver: 0, workers: 0, monasteries: [], shields: 0, total: 182, emptySpaces: 3, conceded: false }, + { player: 'B', inGame: 0, goodsLeft: 0, silver: 0, workers: 0, monasteries: [], shields: 0, total: 182, emptySpaces: 5, conceded: false }, + ]; + expect(def.result(s)!.ranking).toEqual([['B'], ['A']]); + s = structuredClone(s); + s.final![1]!.emptySpaces = 3; + const back = s.roundOrder.at(-1)!; + expect(def.result(s)!.ranking[0]).toEqual([back]); + }); +}); + +describe('expansions', () => { + test('여관: 구역 크기 +1 (4칸 구역 아니어도: 3칸 + 여관 = 10점), 구역당 1장', () => { + let s = make({ inns: true }); + const p = cur(s); + expect(s.inns).toEqual(['INN-1']); + s = rig(s, { placed: { [sp(1, 0)]: 'INN-1', [sp(2, 0)]: 'S-02' }, storage: ['S-03', 'INN-2'], dice: [1, 6] }); + expect(placeError(s, p, 'INN-2', sp(1, -1), null)).toBeNull(); + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(3, 0) } }); + expect(s.players[p]!.vp).toBe(10 + 10); + }); + test('방패: 더블일 때만, 유지비 못 내면 제거, 17번 한 칸 큰 점수', () => { + let s = make({ shields: true }); + const p = cur(s); + const depot = s.depots.findIndex((d) => d.shields.length) + 1; + const shield = s.depots[depot - 1]!.shields[0]!; + s = rig(s, { dice: [depot as Die, ((depot % 6) + 1) as Die], workers: 0 }); + expect(err(s, p, { type: 'takeShield', depot, shield, space: 18 })).toMatch(/일꾼/); + s = rig(s, { dice: [depot as Die, depot as Die] }); + s = act(s, p, { type: 'takeShield', depot, shield, space: 18 }); + expect(s.players[p]!.shields[18]).toBe(shield); + expect(s.players[p]!.used).toEqual([true, true]); + let t = make({ shields: true }); + const q = cur(t); + t = rig(t, { placed: { [sp(1, 0)]: 'S-01', [sp(2, 0)]: 'S-02' }, storage: ['S-03'], dice: [1, 6] }); + t.players[q]!.shields = { 18: 17 }; + t = act(t, q, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(3, 0) } }); + expect(t.players[q]!.vp).toBe(10 + 10); + }); + test('방패 유지비: 페이즈 끝에 못 내면 빠짐', () => { + let s = make({ shields: true }); + const p = cur(s); + s.players[p]!.shields = { 18: 9 }; + s.players[p]!.silver = 0; + for (let i = 0; i < 10; i++) s = act(s, cur(s) ?? p, { type: 'endTurn' }); + expect(s.stage).toBe('phaseEnd'); + expect(err(s, p, { type: 'upkeep', keep: [9] })).toBeTruthy(); + s = act(s, p, { type: 'upkeep', keep: [] }); + expect(s.players[p]!.shields).toEqual({}); + expect(s.phase).toBe(1); + }); + test('거위: 2점 + 고른 가축 점수, 뒤에 같은 목초지 가축마다 2점 더', () => { + let s = make({ extraTiles: true }); + const p = cur(s); + s = rig(s, { placed: { [sp(0, -1)]: 'B-bank-1', [sp(-1, -1)]: 'L-sheep-2-1', [sp(0, -2)]: 'L-sheep-3-3' }, storage: ['L-goose-2-1', 'L-pig-4-5'], dice: [5, 2] }); + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(-2, -1) } }); + expect(s.players[p]!.vp).toBe(2); + s = act(s, p, { type: 'geese', animal: 'sheep' }); + expect(s.players[p]!.vp).toBe(2 + 5); + s = act(s, p, { type: 'useDie', die: 1, act: { kind: 'place', slot: 0, space: sp(-1, -2) } }); + expect(s.players[p]!.vp).toBe(7 + 4 + 2); + }); + test('기중기: 아무 건물 효과', () => { + let s = make({ extraTiles: true }); + const p = cur(s); + s = rig(s, { storage: ['B-crane-1'], dice: [3, 3], silver: 0 }); + s = act(s, p, { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(0, 1) } }); + expect(s.pending.at(-1)?.kind).toBe('crane'); + s = act(s, p, { type: 'crane', building: 'bank' }); + expect(s.players[p]!.silver).toBe(2); + }); +}); + +describe('solo', () => { + test('라운드마다 흰 주사위 보급소 타일 1장 제거, 목표 도달 시 0점·목표 −5·보너스 행동', () => { + let s = make({ mode: 'solo' }, ['A']); + expect(s.stage).toBe('castle'); + s = act(s, 'A', { type: 'chooseCastle', space: 18 }); + expect(s.out.tiles).toBe(1); + expect(s.depots.reduce((a, d) => a + d.slots.filter((t) => t).length, 0)).toBe(11); + s = rig(s, { dice: [4, 4] }); + s.players.A!.goods = [{ die: 4, count: 30 }]; + s = act(s, 'A', { type: 'useDie', die: 0, act: { kind: 'sell', goods: 4 } }); + expect(s.players.A!.vp).toBe(0); + expect(s.solo!.target).toBe(45); + expect(s.pending.at(-1)).toEqual({ kind: 'bonus', source: 'solo' }); + }); + test('혼자 하기: 새 구역은 강이나 시작 성 옆에서만', () => { + let s = make({ mode: 'solo' }, ['A']); + s = act(s, 'A', { type: 'chooseCastle', space: 18 }); + s = rig(s, { placed: { [sp(0, 1)]: 'B-bank-1' } }); + // (-1,1) mine touches (0,1) building and the castle → allowed (castle). (0,2) building same region → fine. + expect(placeError(s, 'A', 'M-01', sp(-1, 1), null)).toBeNull(); + // (1,2) is in R11 (already opened) → fine; (2,1) livestock touches only (1,1)/(1,0)… new region, not from river + s = rig(s, { placed: { [sp(1, 1)]: 'B-bank-2' } }); + expect(placeError(s, 'A', 'L-cow-2-1', sp(2, 1), null)).toMatch(/강/); + s = rig(s, { placed: { [sp(1, 0)]: 'S-01', [sp(2, 0)]: 'S-02' } }); + expect(placeError(s, 'A', 'L-cow-2-1', sp(2, 1), null)).toBeNull(); + }); + test('37칸 모두 채우면 성공', () => { + let s = make({ mode: 'solo' }, ['A']); + s = act(s, 'A', { type: 'chooseCastle', space: 18 }); + const pl = s.players.A!; + let i = 0; + for (const x of DUCHY_1.spaces) if (x.id !== 18 && x.id !== sp(1, 0)) pl.placed[x.id] = `S-0${(i++ % 9) + 1}`; + s = rig(s, { storage: ['S-20'], dice: [5, 5] }); + s = act(s, 'A', { type: 'useDie', die: 0, act: { kind: 'place', slot: 0, space: sp(1, 0) } }); + expect(s.stage).toBe('finished'); + expect(def.result(s)!.scoreText!.A).toBe('성공'); + }); +}); + +describe('timeout & leave', () => { + test('모든 대기 상태에서 TIMEOUT이 합법적으로 차례를 끝냄', () => { + for (const opts of [{}, { shields: true, inns: true, extraTiles: true }, { mode: 'solo' as const }, { castleStart: 'choose' as const }]) { + const players = opts.mode === 'solo' ? ['A'] : ['A', 'B', 'C']; + let s = make(opts, players); + for (let i = 0; i < 400 && !def.result(s); i++) { + const who = def.activePlayers(s)[0]!; + const silver = s.players[who]!.silver; + const turn = s.turnSeq; + expect(def.validate(s, who, def.onTimeout(s, who)).ok).toBe(true); + s = def.apply(s, who, def.onTimeout(s, who), { rng: rng(i), now: i * 1000 }).state; + if (s.stage === 'turn' && s.turnSeq === turn) throw new Error('turn did not end'); + expect(s.players[who]!.silver).toBeGreaterThanOrEqual(silver - (s.options.shields ? 4 : 0)); + } + expect(def.result(s)).not.toBeNull(); + } + }); + test('기권: 남은 사람 1명이면 끝', () => { + let s = make(); + s = act(s, 'A', { type: 'concede' }); + expect(def.result(s)!.ranking).toEqual([['B'], ['A']]); + expect(def.result(s)!.reason).toBe('resign'); + }); + test('정보 유출 없음: 더미 타일·남의 판 상품 종류', () => { + const s = make({}, ['A', 'B', 'C']); + s.players.B!.sold = [3, 0, 0, 0, 0, 0]; + const v = view(s, 'A'); + expect(v.players.B!.sold).toBeNull(); + expect(v.players.B!.soldCount).toBe(3); + const json = JSON.stringify(v); + for (const t of def.secretsOf!(s, 'B')) expect(json.includes(JSON.stringify(t))).toBe(false); + expect(JSON.stringify(v)).not.toContain('phaseGoods'); + }); +}); + +describe('random playouts (invariants, JSON, determinism)', () => { + const OPTS: Partial[] = [ + {}, + { shields: true, inns: true, extraTiles: true }, + { castleStart: 'choose', monasteryRules: '2011', shields: true }, + { mode: 'solo', inns: true, extraTiles: true }, + ]; + const seeds = playoutSeeds(40); + for (const opts of OPTS) { + test(`옵션 ${JSON.stringify(opts)}`, () => { + for (let i = 1; i <= seeds; i++) { + const players = opts.mode === 'solo' ? ['A'] : ['A', 'B', 'C', 'D'].slice(0, 2 + (i % 3)); + let tiles: number | null = null; + const run = () => + randomPlayout(def, { + players, + options: def.optionsSchema.parse(opts), + seed: seedN(i), + maxSteps: 6000, + maxApplyMs: 30, + invariant: (st) => { + const s = st as CobState; + const n = tileCount(s); + if (tiles === null) tiles = n; + if (n !== tiles) throw new Error(`tiles ${n} ≠ ${tiles}`); + if (goodsCount(s) !== 42) throw new Error(`goods ${goodsCount(s)}`); + for (const p of s.seats) if (s.players[p]!.silver < 0 || s.players[p]!.workers < 0) throw new Error('negative'); + }, + }); + const a = run(); + expect(a.finished).toBe(true); + tiles = null; + const b = run(); + expect(JSON.stringify(b.finalState)).toBe(JSON.stringify(a.finalState)); + } + }, 60_000); + } + + test('끝까지 깊게 두기(차례 끝은 마지막에만): 연쇄·효과가 모두 처리됨', () => { + for (let seed = 1; seed <= Math.max(2, seeds); seed++) { + const ch = rng(seed + 50); + let s = make({ shields: true, inns: true, extraTiles: true }, ['A', 'B', 'C', 'D']); + for (let i = 0; i < 4000 && !def.result(s); i++) { + const who = def.activePlayers(s)[0]!; + const legal = def.legalActions!(s, who); + const play = legal.filter((a) => a.type !== 'endTurn'); + const pool = play.length ? play : legal; + const a = pool[ch.int(pool.length)]!; + s = act(s, who, a); + } + expect(def.result(s)).not.toBeNull(); + } + }, 60_000); +}); + +void perform; diff --git a/packages/games/src/castles-of-burgundy/data.ts b/packages/games/src/castles-of-burgundy/data.ts new file mode 100644 index 0000000..778987f --- /dev/null +++ b/packages/games/src/castles-of-burgundy/data.ts @@ -0,0 +1,341 @@ +/** + * 버건디의 성 component data (docs/games/castles-of-burgundy.md §3, §5.8, §5.11). Pure constants, no rules. + * The web imports this module directly (`@bg/games/castles-of-burgundy/data`) to draw the duchy and tiles. + * + * ⚠ UNCONFIRMED DATA (doc §12): every value marked "UNCONFIRMED" below is the doc's chosen default until the real + * components are checked. They are kept in this one file so a correction is a one-line change here. + */ + +export type Color = 'castle' | 'mine' | 'monastery' | 'building' | 'livestock' | 'ship'; +export const COLORS: readonly Color[] = ['castle', 'mine', 'monastery', 'building', 'livestock', 'ship']; +export type Die = 1 | 2 | 3 | 4 | 5 | 6; +export const DICE: readonly Die[] = [1, 2, 3, 4, 5, 6]; +export type BuildingKind = 'warehouse' | 'carpenter' | 'church' | 'market' | 'boarding' | 'bank' | 'townhall' | 'watchtower' | 'crane'; +/** The eight base buildings (the crane of `extraTiles` is not one of them). */ +export const BUILDINGS: readonly Exclude[] = ['warehouse', 'carpenter', 'church', 'market', 'boarding', 'bank', 'townhall', 'watchtower']; +export type Animal = 'chicken' | 'sheep' | 'pig' | 'cow' | 'goose'; +export const ANIMALS: readonly Exclude[] = ['chicken', 'sheep', 'pig', 'cow']; +export type PileKey = Color | 'black'; +export const PILE_KEYS: readonly PileKey[] = ['castle', 'mine', 'monastery', 'building', 'livestock', 'ship', 'black']; + +export interface TileDef { + id: string; + color: Color | 'inn'; + back: 'colored' | 'black'; + building?: BuildingKind; + animal?: Animal; + count?: number; + /** Monastery number 1~28 (16~23 = craftsmen, see `craft`). */ + monastery?: number; + /** Craftsman monastery: the building kind it counts at the end. */ + craft?: Exclude; + /** Only in the `extraTiles` module. */ + extra?: boolean; +} + +// ---------------------------------------------------------------- Korean names (screen) + +export const COLOR_KO: Record = { castle: '성', mine: '광산', monastery: '수도원', building: '건물', livestock: '가축', ship: '배' }; +export const COLOR_ICON: Record = { castle: '🏰', mine: '⛏', monastery: '📜', building: '🏠', livestock: '🐄', ship: '⛵' }; +export const BUILDING_KO: Record = { + warehouse: '창고', + carpenter: '목공소', + church: '교회', + market: '시장', + boarding: '하숙집', + bank: '은행', + townhall: '시청', + watchtower: '망루', + crane: '기중기', +}; +export const BUILDING_EFFECT_KO: Record = { + warehouse: '상품 한 종류를 주사위 없이 팔아요', + carpenter: '보급소에서 건물 타일 1장을 가져와요', + church: '보급소에서 광산·수도원·성 1장을 가져와요', + market: '보급소에서 배·가축 1장을 가져와요', + boarding: '일꾼 4개', + bank: '은화 2개', + townhall: '보관 칸의 타일 1장을 눈과 상관없이 놓아요', + watchtower: '4점', + crane: '아무 건물 효과 하나를 써요', +}; +export const ANIMAL_KO: Record = { chicken: '닭', sheep: '양', pig: '돼지', cow: '소', goose: '거위' }; +export const ANIMAL_ICON: Record = { chicken: '🐔', sheep: '🐑', pig: '🐖', cow: '🐄', goose: '🪿' }; +/** Own names for the six goods (doc §3.3: any names). */ +export const GOODS_KO: Record = { 1: '포도주', 2: '곡물', 3: '비단', 4: '도자기', 5: '장신구', 6: '꿀' }; +export const PHASE_KO = ['A', 'B', 'C', 'D', 'E'] as const; + +// ---------------------------------------------------------------- monasteries (§5.8) + +export interface MonasteryDef { + n: number; + name: string; + text: string; + kind: 'ongoing' | 'phase' | 'end'; +} + +export const MONASTERIES: readonly MonasteryDef[] = [ + { n: 1, name: '자유 건축', text: '한 마을에 같은 종류 건물을 여러 개 놓을 수 있어요', kind: 'ongoing' }, + { n: 2, name: '광부', text: '페이즈 끝에 광산 1개당 일꾼 1개도 받아요', kind: 'phase' }, + { n: 3, name: '상인', text: '상품을 팔 때 은화 1 대신 2개', kind: 'ongoing' }, + { n: 4, name: '장사 일꾼', text: '상품을 팔 때 일꾼 1개 더', kind: 'ongoing' }, + { n: 5, name: '큰 배', text: '배를 놓을 때 이웃 보급소의 상품도 모두 가져와요', kind: 'ongoing' }, + { n: 6, name: '넓은 장터', text: '번호 보급소에서도 살 수 있어요(2019: 일꾼 2로도 낼 수 있어요)', kind: 'ongoing' }, + { n: 7, name: '목동', text: '가축 점수가 날 때 타일 1장마다 1점 더', kind: 'ongoing' }, + { n: 8, name: '힘센 일꾼', text: '일꾼 1개로 눈을 ±2까지 바꿔요', kind: 'ongoing' }, + { n: 9, name: '건축가', text: '건물을 놓을 때 눈 ±1 공짜', kind: 'ongoing' }, + { n: 10, name: '뱃사공·목자', text: '배·가축을 놓을 때 눈 ±1 공짜', kind: 'ongoing' }, + { n: 11, name: '성주', text: '성·광산·수도원을 놓을 때 눈 ±1 공짜', kind: 'ongoing' }, + { n: 12, name: '수집가', text: '보급소에서 타일을 가져올 때 눈 ±1 공짜', kind: 'ongoing' }, + { n: 13, name: '품삯', text: '"일꾼 받기" 때 은화 1개 더', kind: 'ongoing' }, + { n: 14, name: '일꾼 마을', text: '"일꾼 받기" 때 일꾼 2 대신 4개', kind: 'ongoing' }, + { n: 15, name: '다양한 상품', text: '게임 끝: 판 상품 종류 1개당 2점(2011: 3점)', kind: 'end' }, + { n: 24, name: '가축 종류', text: '게임 끝: 내 공국의 가축 종류 1개당 4점', kind: 'end' }, + { n: 25, name: '무역량', text: '게임 끝: 판 상품 1장당 1점', kind: 'end' }, + { n: 26, name: '명예', text: '게임 끝: 색 보너스 타일 1장당 3점(2011: 2점)', kind: 'end' }, + { n: 27, name: '다리', text: '차례 트랙에서 같은 칸이면 늘 내 말이 맨 위', kind: 'ongoing' }, + { n: 28, name: '일꾼 사기', text: '내 차례에 은화 1로 일꾼 2개를 살 수 있어요', kind: 'ongoing' }, +]; + +/** + * UNCONFIRMED (doc §5.8 / §12-2): which craftsman number points at which building. Only 17 = 망루 and 22 = 은행 are + * confirmed by the rulebook example; the engine uses `K-B-` ids so only the displayed numbers depend on this. + */ +export const CRAFT_NUMBER: Record, number> = { + warehouse: 16, + watchtower: 17, + carpenter: 18, + church: 19, + market: 20, + boarding: 21, + bank: 22, + townhall: 23, +}; + +/** UNCONFIRMED (doc §3.3 / §12-2): the six black-backed monasteries. */ +export const BLACK_MONASTERIES: readonly number[] = [2, 3, 4, 13, 24, 25]; + +/** + * UNCONFIRMED (doc §3.3 / §12-1): the 7 tiles of each animal — animals per tile and back colour + * (2마리 2장, 3마리 3장, 4마리 2장; colored 5 + black 2). + */ +export const LIVESTOCK_TABLE: readonly { count: 2 | 3 | 4; back: 'colored' | 'black' }[] = [ + { count: 2, back: 'colored' }, + { count: 2, back: 'colored' }, + { count: 3, back: 'colored' }, + { count: 3, back: 'colored' }, + { count: 4, back: 'colored' }, + { count: 3, back: 'black' }, + { count: 4, back: 'black' }, +]; + +// ---------------------------------------------------------------- shields (§5.11.3) + +export interface ShieldDef { + n: number; + vp: number; + text: string; +} +export const SHIELDS: readonly ShieldDef[] = [ + { n: 1, vp: 12, text: '모든 목초지를 하나로 쳐요' }, + { n: 2, vp: 12, text: '남이 "일꾼 받기"를 할 때마다 나도 일꾼 1개' }, + { n: 3, vp: 12, text: '방패 유지비를 일꾼으로도 내요' }, + { n: 4, vp: 12, text: '보관 칸 제한이 없어요' }, + { n: 5, vp: 12, text: '배를 놓을 때 상품 한 종류를 골라 모든 보급소에서 더 가져와요' }, + { n: 6, vp: 12, text: '한 사람을 골라 그 사람 공국의 수도원 효과를 나도 받아요(27번 제외)' }, + { n: 7, vp: 8, text: '새로 받는 색 보너스 점수 2배' }, + { n: 8, vp: 8, text: '광산 은화 2배' }, + { n: 9, vp: 8, text: '상품 1장 팔 때마다 은화 1개 더' }, + { n: 10, vp: 8, text: '게임 끝 점수형 수도원 점수 2배' }, + { n: 11, vp: 8, text: '성을 놓을 때 보너스 행동 대신 방패를 가져올 수 있어요' }, + { n: 12, vp: 8, text: '상품 판매 점수 2배' }, + { n: 13, vp: 4, text: '게임 끝 방패 점수 2배' }, + { n: 14, vp: 4, text: '페이즈 끝에 번호 보급소 타일 1장을 공국에 바로 놓아요' }, + { n: 15, vp: 4, text: '페이즈 끝에 검은 보급소 타일 1장을 공국에 바로 놓아요' }, + { n: 16, vp: 4, text: '차례마다 주사위 1개를 원하는 눈으로 바꿔요' }, + { n: 17, vp: 4, text: '구역을 완성하면 한 칸 큰 구역 점수' }, + { n: 18, vp: 4, text: '맞닿지 않은 칸에도 놓을 수 있어요' }, +]; +export const shieldDef = (n: number): ShieldDef => SHIELDS[n - 1]!; + +// ---------------------------------------------------------------- scoring tables (§5.6, §5.9) + +/** Region size → points (index = size; 9 = 4-space region... with inns up to 9+). */ +export const REGION_VP: readonly number[] = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66]; +export const PHASE_VP: readonly number[] = [10, 8, 6, 4, 2]; +export const BONUS_VP: Record<'large' | 'small', Record> = { + large: { 1: 0, 2: 5, 3: 6, 4: 7 }, + small: { 1: 0, 2: 2, 3: 3, 4: 4 }, +}; +/** Points per good sold by player count (solo uses the 2-player value). */ +export const GOODS_VP: Record = { 1: 2, 2: 2, 3: 3, 4: 4 }; + +// ---------------------------------------------------------------- tiles + +function pad(n: number): string { + return String(n).padStart(2, '0'); +} + +function baseTiles(): TileDef[] { + const out: TileDef[] = []; + for (const kind of BUILDINGS) for (let i = 1; i <= 7; i++) out.push({ id: `B-${kind}-${i}`, color: 'building', back: i <= 5 ? 'colored' : 'black', building: kind }); + for (const animal of ANIMALS) + LIVESTOCK_TABLE.forEach((t, i) => out.push({ id: `L-${animal}-${t.count}-${i + 1}`, color: 'livestock', back: t.back, animal, count: t.count })); + for (const m of MONASTERIES) { + if (m.n >= 27) continue; + out.push({ id: `K-${pad(m.n)}`, color: 'monastery', back: BLACK_MONASTERIES.includes(m.n) ? 'black' : 'colored', monastery: m.n }); + } + for (const kind of BUILDINGS) out.push({ id: `K-B-${kind}`, color: 'monastery', back: 'colored', monastery: CRAFT_NUMBER[kind], craft: kind }); + for (let i = 1; i <= 16; i++) out.push({ id: `C-${pad(i)}`, color: 'castle', back: i <= 14 ? 'colored' : 'black' }); + for (let i = 1; i <= 12; i++) out.push({ id: `M-${pad(i)}`, color: 'mine', back: i <= 10 ? 'colored' : 'black' }); + for (let i = 1; i <= 26; i++) out.push({ id: `S-${pad(i)}`, color: 'ship', back: i <= 20 ? 'colored' : 'black' }); + return out; +} + +/** The four extra hex tiles (2019 확장 2). */ +export const EXTRA_TILES: readonly TileDef[] = [ + { id: 'K-27', color: 'monastery', back: 'colored', monastery: 27, extra: true }, + { id: 'K-28', color: 'monastery', back: 'colored', monastery: 28, extra: true }, + { id: 'B-crane-1', color: 'building', back: 'black', building: 'crane', extra: true }, + { id: 'L-goose-2-1', color: 'livestock', back: 'black', animal: 'goose', count: 2, extra: true }, +]; +/** Inns (2019 확장 6): one per phase. */ +export const INN_TILES: readonly TileDef[] = [1, 2, 3, 4, 5].map((i) => ({ id: `INN-${i}`, color: 'inn' as const, back: 'colored' as const })); + +export const BASE_TILES: readonly TileDef[] = baseTiles(); +export const TILES: Record = Object.fromEntries([...BASE_TILES, ...EXTRA_TILES, ...INN_TILES].map((t) => [t.id, t])); +export const tileDef = (id: string): TileDef => { + const t = TILES[id]; + if (!t) throw new Error(`unknown tile ${id}`); + return t; +}; + +/** Hex tiles in play (excluding inns, which sit in their own stack). */ +export function tilesInPlay(extraTiles: boolean): TileDef[] { + return extraTiles ? [...BASE_TILES, ...EXTRA_TILES] : [...BASE_TILES]; +} + +// ---------------------------------------------------------------- depots (§3.1.1) + +/** + * Hex spaces of each numbered depot, in the order they open: 2 players use the first two, 3 players add the third, + * 4 players the fourth. UNCONFIRMED (doc §12-3) for the 2/3-player split; the 4-player totals match the tile counts. + * Depot 6's third space is the half-green/half-grey one: castle in phases A·C·E, mine in B·D with 3 players. + */ +export const DEPOT_SLOTS: readonly (readonly Color[])[] = [ + ['ship', 'building', 'monastery', 'livestock'], + ['castle', 'monastery', 'building', 'building'], + ['livestock', 'building', 'ship', 'monastery'], + ['ship', 'building', 'livestock', 'mine'], + ['mine', 'monastery', 'building', 'building'], + ['livestock', 'building', 'castle', 'ship'], +]; + +/** Space colours of numbered depot `depot` (1~6) for `players` (solo = 2) in `phase` (0 = A). */ +export function depotColors(depot: number, players: number, phase: number): Color[] { + const n = Math.min(4, Math.max(2, players)); + const cols = DEPOT_SLOTS[depot - 1]!.slice(0, n); + if (n === 3 && depot === 6 && (phase === 1 || phase === 3)) cols[2] = 'mine'; + return [...cols]; +} +export const blackSlots = (players: number): number => 2 * Math.min(4, Math.max(2, players)); + +/** Shields on each numbered depot at setup (§5.11.3). */ +export function shieldsPerDepot(depot: number, players: number): number { + const n = Math.min(4, Math.max(2, players)); + if (n === 2) return 1; + if (n === 4) return 2; + return depot % 2 === 1 ? 1 : 2; +} + +/** Depots are a ring 1–2–3–4–5–6–1 (monastery 5). */ +export const depotNeighbors = (d: number): [number, number] => [d === 1 ? 6 : d - 1, d === 6 ? 1 : d + 1]; + +// ---------------------------------------------------------------- duchy #1 (§3.2.1) + +export interface Space { + id: number; + q: number; + r: number; + color: Color; + die: Die; +} + +export interface DuchyDef { + id: string; + spaces: Space[]; + startSpace: number; + castleSpaces: number[]; + neighbors: number[][]; + /** Region index per space. */ + regionOf: number[]; + regions: { color: Color; spaces: number[] }[]; + colorCount: Record; +} + +const LETTER: Record = { 목: 'livestock', 성: 'castle', 수: 'monastery', 건: 'building', 배: 'ship', 광: 'mine' }; +/** Rows r = −3..3, each from q = max(−3, −3−r) to min(3, 3−r). Space 18 = (0, 0) is the start castle. */ +const DUCHY1_ROWS = [ + '목6 성5 성4 수3', + '목2 목1 성6 수5 건4', + '목5 목4 건3 수1 건2 건3', + '배6 배1 배2 성6 배5 배4 배1', + '건2 건5 광4 건3 건1 목2', + '건6 광1 수2 건5 건6', + '광3 수4 수1 건3', +]; + +function buildDuchy(id: string, rows: string[], start: [number, number]): DuchyDef { + const spaces: Space[] = []; + rows.forEach((row, i) => { + const r = i - 3; + const q0 = Math.max(-3, -3 - r); + row.split(' ').forEach((cell, j) => { + spaces.push({ id: spaces.length, q: q0 + j, r, color: LETTER[cell[0]!]!, die: Number(cell.slice(1)) as Die }); + }); + }); + const at = new Map(spaces.map((s) => [`${s.q},${s.r}`, s.id])); + const DIRS = [ + [1, 0], + [-1, 0], + [0, 1], + [0, -1], + [1, -1], + [-1, 1], + ]; + const neighbors = spaces.map((s) => DIRS.map(([dq, dr]) => at.get(`${s.q + dq!},${s.r + dr!}`)).filter((x): x is number => x !== undefined)); + const regionOf = spaces.map(() => -1); + const regions: DuchyDef['regions'] = []; + for (const s of spaces) { + if (regionOf[s.id]! >= 0) continue; + const idx = regions.length; + const list: number[] = []; + const stack = [s.id]; + regionOf[s.id] = idx; + while (stack.length) { + const c = stack.pop()!; + list.push(c); + for (const n of neighbors[c]!) { + if (regionOf[n]! < 0 && spaces[n]!.color === s.color) { + regionOf[n] = idx; + stack.push(n); + } + } + } + regions.push({ color: s.color, spaces: list.sort((a, b) => a - b) }); + } + const colorCount = Object.fromEntries(COLORS.map((c) => [c, spaces.filter((s) => s.color === c).length])) as Record; + return { + id, + spaces, + startSpace: at.get(`${start[0]},${start[1]}`)!, + castleSpaces: spaces.filter((s) => s.color === 'castle').map((s) => s.id), + neighbors, + regionOf, + regions, + colorCount, + }; +} + +export const DUCHY_1: DuchyDef = buildDuchy('1', DUCHY1_ROWS, [0, 0]); +export const DUCHIES: Record = { '1': DUCHY_1 }; diff --git a/packages/games/src/castles-of-burgundy/engine.ts b/packages/games/src/castles-of-burgundy/engine.ts new file mode 100644 index 0000000..878ec11 --- /dev/null +++ b/packages/games/src/castles-of-burgundy/engine.ts @@ -0,0 +1,1482 @@ +/** + * 버건디의 성 rules core (docs/games/castles-of-burgundy.md §4~§6, §8). Pure functions over a mutable state clone: + * `index.ts` clones once per `apply`, the computer player clones its own copy to look ahead within its turn. + */ +import type { PlayerId, Rng } from '@bg/engine'; +import { + ANIMALS, + BONUS_VP, + BUILDINGS, + COLORS, + DUCHY_1, + GOODS_VP, + PHASE_VP, + REGION_VP, + blackSlots, + depotColors, + depotNeighbors, + shieldDef, + shieldsPerDepot, + tileDef, + tilesInPlay, + type BuildingKind, + type Color, + type Die, + type DuchyDef, + type PileKey, + type TileDef, +} from './data'; +import type { CobOptions } from './options'; +import type { CobAction, CobPlayer, CobState, DieAct, FinalRow, LogEntry, Pending } from './types'; + +export const LOG_MAX = 80; +export const PENDING_MIN_MS = 20_000; +export const AWAY_AFTER = 3; +export const AWAY_MS = 10_000; +export const CASTLE_MS = 30_000; + +export interface Ctx { + rng: Rng; + now: number; +} + +/** Every player plays on duchy #1 in this phase (doc §2 `duchy` = beginner). */ +export const duchyOf = (_s: CobState, _p: PlayerId): DuchyDef => DUCHY_1; +export const isSolo = (s: CobState): boolean => s.options.mode === 'solo'; +export const shieldsOn = (s: CobState): boolean => s.options.shields && !isSolo(s); +/** Board size used for depots / scoring (solo = the 2-player board). */ +export const boardN = (s: CobState): number => (isSolo(s) ? 2 : s.seats.length); + +type LogInput = LogEntry extends infer T ? (T extends LogEntry ? Omit : never) : never; +export function log(s: CobState, e: LogInput): void { + s.log.push({ seq: s.seq, ...e } as LogEntry); + if (s.log.length > LOG_MAX) s.log.splice(0, s.log.length - LOG_MAX); +} + +const dist = (a: number, b: number): number => { + const d = Math.abs(a - b); + return Math.min(d, 6 - d); +}; + +// ---------------------------------------------------------------- monasteries & shields + +/** Monastery tiles whose effects apply to `p`: own placed ones + (shield 6) the chosen player's, except 27. */ +export function monasteryTiles(s: CobState, p: PlayerId): string[] { + const pl = s.players[p]!; + const own = Object.values(pl.placed).filter((t) => !pl.facedown.includes(t) && TILE_COLOR(t) === 'monastery'); + if (!pl.copyFrom || !s.players[pl.copyFrom] || !hasShield(s, p, 6)) return own; + const other = s.players[pl.copyFrom]!; + const theirs = Object.values(other.placed).filter((t) => !other.facedown.includes(t) && TILE_COLOR(t) === 'monastery' && tileDef(t).monastery !== 27); + return [...own, ...theirs]; +} +const TILE_COLOR = (t: string): TileDef['color'] => tileDef(t).color; + +export function has(s: CobState, p: PlayerId, n: number): boolean { + return monasteryTiles(s, p).some((t) => tileDef(t).monastery === n); +} +export function hasShield(s: CobState, p: PlayerId, n: number): boolean { + if (!shieldsOn(s)) return false; + return Object.values(s.players[p]!.shields).includes(n); +} +export const storageCap = (s: CobState, p: PlayerId): number => (hasShield(s, p, 4) ? 99 : 3); +export const storageFull = (s: CobState, p: PlayerId): boolean => s.players[p]!.storage.length >= storageCap(s, p); +export const goodsCap = (s: CobState): number => (isSolo(s) ? 6 : 3); + +// ---------------------------------------------------------------- tiles + +export type Where = { at: 'depot'; depot: number; slot: number } | { at: 'black'; slot: number } | { at: 'inn' }; + +export function findTile(s: CobState, tile: string): Where | null { + for (let d = 0; d < 6; d++) { + const slot = s.depots[d]!.slots.indexOf(tile); + if (slot >= 0) return { at: 'depot', depot: d + 1, slot }; + } + const b = s.black.indexOf(tile); + if (b >= 0) return { at: 'black', slot: b }; + if (s.inns.length && s.inns[s.inns.length - 1] === tile) return { at: 'inn' }; + return null; +} + +function removeAt(s: CobState, w: Where): void { + if (w.at === 'depot') s.depots[w.depot - 1]!.slots[w.slot] = null; + else if (w.at === 'black') s.black[w.slot] = null; + else s.inns.pop(); +} + +/** Colour a tile counts as for `p`: face-down solo tiles and inns go on any colour. */ +export function colorFor(pl: CobPlayer, tile: string): Color | 'any' { + if (pl.facedown.includes(tile)) return 'any'; + const c = tileDef(tile).color; + return c === 'inn' ? 'any' : c; +} +const isInn = (t: string | undefined): boolean => !!t && t.startsWith('INN-'); + +/** Which free ±1 monastery applies to an action (doc §5.5). */ +type CostKind = 'take' | 'place-building' | 'place-shiplive' | 'place-cmm' | 'none'; +function costKindOfTile(pl: CobPlayer, tile: string): CostKind { + const c = colorFor(pl, tile); + if (c === 'building') return 'place-building'; + if (c === 'ship' || c === 'livestock') return 'place-shiplive'; + if (c === 'castle' || c === 'mine' || c === 'monastery') return 'place-cmm'; + return 'none'; +} +const FREE_MONASTERY: Record = { take: 12, 'place-building': 9, 'place-shiplive': 10, 'place-cmm': 11, none: 0 }; + +/** Workers to turn `face` into `value` (circular, 6↔1), after the free ±1 and monastery 8 (±2 per worker). */ +export function rawCost(s: CobState, p: PlayerId, face: Die, value: number, kind: CostKind): number { + let d = dist(face, value); + const free = FREE_MONASTERY[kind]; + if (free && d > 0 && has(s, p, free)) d -= 1; + if (d === 0) return 0; + return has(s, p, 8) ? Math.ceil(d / 2) : d; +} + +/** Cost with shield 16 (once per turn: any value for free). */ +export function dieCost(s: CobState, p: PlayerId, face: Die, value: number, kind: CostKind): { cost: number; use16: boolean } { + const c = rawCost(s, p, face, value, kind); + if (c > 0 && hasShield(s, p, 16) && !s.players[p]!.free16) return { cost: 0, use16: true }; + return { cost: c, use16: false }; +} + +// ---------------------------------------------------------------- placement + +export function regionSpaces(D: DuchyDef, space: number): number[] { + return D.regions[D.regionOf[space]!]!.spaces; +} + +/** Why `tile` can't go on `space` (null = it can). `die` null = no die condition (town hall, solo bonus, phase-end). */ +export function placeError(s: CobState, p: PlayerId, tile: string, space: number, die: number | null): string | null { + const pl = s.players[p]!; + const D = duchyOf(s, p); + const sp = D.spaces[space]; + if (!sp) return '없는 칸이에요.'; + if (pl.placed[space]) return '이미 타일이 있는 칸이에요.'; + const c = colorFor(pl, tile); + if (c !== 'any' && c !== sp.color) return '타일 색과 칸 색이 달라요.'; + if (die !== null && die !== sp.die) return '주사위 눈과 칸 숫자가 달라요.'; + const touching = D.neighbors[space]!.some((n) => pl.placed[n]); + if (!touching && !hasShield(s, p, 18)) return '이미 놓인 타일과 맞닿은 칸에만 놓을 수 있어요.'; + const region = regionSpaces(D, space); + if (isSolo(s) && !region.some((x) => pl.placed[x])) { + // Solo: a new region opens only from the river (a ship space) or the start castle (doc §5.11.5, decision §13). + const fromRiver = D.neighbors[space]!.some((n) => pl.placed[n] && (D.spaces[n]!.color === 'ship' || n === pl.start)); + if (!fromRiver) return '혼자 하기에서는 새 구역을 강(배 칸)이나 시작 성 옆에서만 열 수 있어요.'; + } + if (isInn(tile) && region.some((x) => isInn(pl.placed[x]))) return '한 구역에는 여관을 1장만 놓을 수 있어요.'; + const def = tileDef(tile); + if (c === 'building' && def.building && !has(s, p, 1)) { + if (region.some((x) => pl.placed[x] && !pl.facedown.includes(pl.placed[x]!) && tileDef(pl.placed[x]!).building === def.building)) return '이 마을에는 이미 같은 건물이 있어요.'; + } + return null; +} + +/** Spaces where `tile` may go now (ignoring the die). */ +export function placeSpaces(s: CobState, p: PlayerId, tile: string): number[] { + const out: number[] = []; + const D = duchyOf(s, p); + for (const sp of D.spaces) if (!placeError(s, p, tile, sp.id, null)) out.push(sp.id); + return out; +} + +// ---------------------------------------------------------------- scoring helpers + +export function gainVp(s: CobState, p: PlayerId, n: number): void { + if (n <= 0) return; + const pl = s.players[p]!; + pl.vp += n; + if (s.solo) { + s.solo.canBuy = true; + if (pl.vp >= s.solo.target) { + pl.vp = 0; + s.solo.target = Math.max(5, s.solo.target - 5); + log(s, { t: 'soloTarget', target: s.solo.target }); + s.pending.push({ kind: 'bonus', source: 'solo' }); + } + } +} + +function pastureSpaces(s: CobState, p: PlayerId, space: number): number[] { + const D = duchyOf(s, p); + if (hasShield(s, p, 1)) return D.spaces.filter((x) => x.color === 'livestock').map((x) => x.id); + return regionSpaces(D, space); +} +function pastureTiles(s: CobState, p: PlayerId, space: number): TileDef[] { + const pl = s.players[p]!; + return pastureSpaces(s, p, space) + .map((x) => pl.placed[x]) + .filter((t): t is string => !!t && !pl.facedown.includes(t) && !isInn(t)) + .map(tileDef) + .filter((d) => d.animal); +} +/** Points of the tiles of `animal` in a pasture (doc §5.7, monastery 7: +1 per tile). */ +function animalPoints(s: CobState, p: PlayerId, tiles: TileDef[], animal: string): number { + const same = tiles.filter((t) => t.animal === animal); + return same.reduce((a, t) => a + (t.count ?? 0), 0) + (has(s, p, 7) ? same.length : 0); +} + +/** Monastery end score (doc §6; solo scores it when placed). */ +export function monasteryVp(s: CobState, p: PlayerId, tile: string, craneUsed: { v: boolean }): number { + const pl = s.players[p]!; + const d = tileDef(tile); + const old = s.options.monasteryRules === '2011'; + const placedDefs = Object.values(pl.placed) + .filter((t) => !pl.facedown.includes(t) && !isInn(t)) + .map(tileDef); + if (d.craft) { + let n = placedDefs.filter((x) => x.building === d.craft).length; + if (!craneUsed.v && placedDefs.some((x) => x.building === 'crane')) { + craneUsed.v = true; + n += 1; + } + return n * 4; + } + switch (d.monastery) { + case 15: + return pl.sold.filter((x) => x > 0).length * (old ? 3 : 2); + case 24: + return new Set(placedDefs.filter((x) => x.animal).map((x) => x.animal)).size * 4; + case 25: + return pl.sold.reduce((a, b) => a + b, 0); + case 26: + return pl.bonus.length * (old ? 2 : 3); + default: + return 0; + } +} +const END_MONASTERY = (t: string): boolean => { + const d = tileDef(t); + return !!d.craft || d.monastery === 15 || d.monastery === 24 || d.monastery === 25 || d.monastery === 26; +}; + +// ---------------------------------------------------------------- effects + +/** Place a tile: region / colour scoring, then the tile's effect (doc §8.2 order). `full` = with chosen effects. */ +export function placeTile(s: CobState, p: PlayerId, tile: string, space: number, full: boolean): void { + const pl = s.players[p]!; + const D = duchyOf(s, p); + pl.placed[space] = tile; + log(s, { t: 'place', p, tile, space }); + const later: Pending[] = []; + const region = regionSpaces(D, space); + if (region.every((x) => pl.placed[x])) { + const inn = region.some((x) => isInn(pl.placed[x])); + const size = Math.min(REGION_VP.length - 1, region.length + (inn ? 1 : 0) + (hasShield(s, p, 17) ? 1 : 0)); + const vp = REGION_VP[size]! + PHASE_VP[s.phase]!; + gainVp(s, p, vp); + log(s, { t: 'region', p, space, size, vp }); + } + const color = D.spaces[space]!.color; + if (D.spaces.every((x) => x.color !== color || pl.placed[x.id])) colorComplete(s, p, color, later); + if (isSolo(s) && D.spaces.every((x) => pl.placed[x.id])) { + finish(s, 'soloWin'); + return; + } + if (!pl.facedown.includes(tile) && !isInn(tile)) tileEffect(s, p, tile, space, full, later); + for (let i = later.length - 1; i >= 0; i--) s.pending.push(later[i]!); +} + +function colorComplete(s: CobState, p: PlayerId, color: Color, later: Pending[]): void { + const pl = s.players[p]!; + if (isSolo(s)) { + if (s.black.some((t) => t)) later.push({ kind: 'soloBlack' }); + return; + } + const size = s.bonusLeft[color].shift(); + if (!size) return; + const vp = BONUS_VP[size][boardN(s)]! * (hasShield(s, p, 7) ? 2 : 1); + pl.bonus.push({ color, size }); + gainVp(s, p, vp); + log(s, { t: 'colorBonus', p, color, size, vp }); +} + +function tileEffect(s: CobState, p: PlayerId, tile: string, space: number, full: boolean, later: Pending[]): void { + const pl = s.players[p]!; + const d = tileDef(tile); + switch (d.color) { + case 'castle': + if (full) later.push({ kind: 'bonus', source: 'castle' }); + return; + case 'mine': + return; + case 'monastery': + if (isSolo(s) && END_MONASTERY(tile)) gainVp(s, p, monasteryVp(s, p, tile, { v: false })); + return; + case 'ship': + if (full) later.push({ kind: 'ship' }); + return; + case 'livestock': { + const tiles = pastureTiles(s, p, space); + let vp: number; + if (d.animal === 'goose') { + vp = (d.count ?? 2) + (has(s, p, 7) ? 1 : 0); + if (full && tiles.some((t) => t.animal !== 'goose')) later.push({ kind: 'geese', region: space }); + } else { + vp = animalPoints(s, p, tiles, d.animal!); + const geese = tiles.filter((t) => t.animal === 'goose'); + vp += geese.reduce((a, g) => a + (g.count ?? 2) + (has(s, p, 7) ? 1 : 0), 0); + } + gainVp(s, p, vp); + log(s, { t: 'livestock', p, vp }); + return; + } + case 'building': + log(s, { t: 'building', p, building: d.building! }); + if (d.building === 'crane') { + if (full) later.push({ kind: 'crane' }); + return; + } + buildingEffect(s, p, d.building!, full, later); + return; + default: + void pl; + } +} + +export const DEPOT_TAKE: Partial> = { + carpenter: ['building'], + church: ['mine', 'monastery', 'castle'], + market: ['ship', 'livestock'], +}; + +function buildingEffect(s: CobState, p: PlayerId, kind: BuildingKind, full: boolean, later: Pending[]): void { + const pl = s.players[p]!; + switch (kind) { + case 'warehouse': + if (full && pl.goods.length) later.push({ kind: 'warehouse' }); + return; + case 'carpenter': + case 'church': + case 'market': + if (full) later.push({ kind: 'depotTake', colors: DEPOT_TAKE[kind]!, source: kind }); + return; + case 'boarding': + pl.workers += 4; + return; + case 'bank': + pl.silver += 2; + return; + case 'townhall': + if (full && pl.storage.length) later.push({ kind: 'townhall' }); + return; + case 'watchtower': + gainVp(s, p, 4); + return; + default: + return; + } +} + +export function sellGoods(s: CobState, p: PlayerId, kind: Die): void { + const pl = s.players[p]!; + const i = pl.goods.findIndex((g) => g.die === kind); + if (i < 0) return; + const count = pl.goods[i]!.count; + pl.goods.splice(i, 1); + const silver = (has(s, p, 3) ? 2 : 1) + (hasShield(s, p, 9) ? count : 0); + pl.silver += silver; + if (has(s, p, 4)) pl.workers += 1; + const vp = count * GOODS_VP[boardN(s)]! * (hasShield(s, p, 12) ? 2 : 1); + pl.sold[kind - 1]! += count; + gainVp(s, p, vp); + log(s, { t: 'sell', p, goods: kind, count, vp, silver }); +} + +function takeWorkers(s: CobState, p: PlayerId): void { + const pl = s.players[p]!; + const n = has(s, p, 14) ? 4 : 2; + pl.workers += n; + if (has(s, p, 13)) pl.silver += 1; + log(s, { t: 'workers', p, n }); + for (const q of s.seats) if (q !== p && !s.players[q]!.conceded && hasShield(s, q, 2)) s.players[q]!.workers += 1; +} + +function toStorage(s: CobState, p: PlayerId, tile: string, discard: number | undefined): void { + const pl = s.players[p]!; + if (pl.storage.length >= storageCap(s, p) && discard !== undefined) { + const [gone] = pl.storage.splice(discard, 1); + if (gone) { + if (!isInn(gone)) s.out.tiles++; + log(s, { t: 'discard', p, tile: gone }); + } + } + pl.storage.push(tile); +} + +function addGoods(pl: CobPlayer, kind: Die, n: number): void { + const g = pl.goods.find((x) => x.die === kind); + if (g) g.count += n; + else pl.goods.push({ die: kind, count: n }); +} + +// ---------------------------------------------------------------- ships + +export interface ShipChoice { + depot: number; + adjacent?: number; + extra?: number; + keep?: number[]; +} + +/** New goods kinds a ship choice brings and how many of them fit. */ +export function shipKinds(s: CobState, p: PlayerId, c: { depot: number; adjacent?: number; extra?: number }): { fresh: number[]; free: number } { + const pl = s.players[p]!; + const kinds = new Set(); + for (const d of [c.depot, c.adjacent]) if (d) for (const g of s.depots[d - 1]!.goods) kinds.add(g); + if (c.extra) kinds.add(c.extra); + const held = new Set(pl.goods.map((g) => g.die)); + const fresh = [...kinds].filter((k) => !held.has(k)).sort((a, b) => a - b); + return { fresh, free: Math.max(0, goodsCap(s) - held.size) }; +} + +export function shipError(s: CobState, p: PlayerId, c: ShipChoice): string | null { + if (c.depot < 1 || c.depot > 6) return '없는 보급소예요.'; + if (c.adjacent !== undefined) { + if (!has(s, p, 5)) return '이웃 보급소 상품은 수도원 5번이 있어야 가져와요.'; + if (!depotNeighbors(c.depot).includes(c.adjacent)) return '고른 보급소의 이웃이 아니에요.'; + } + if (c.extra !== undefined) { + if (!hasShield(s, p, 5)) return '방패 5번이 있어야 해요.'; + if (!s.depots.some((d) => d.goods.includes(c.extra as Die))) return '그 상품이 보급소에 없어요.'; + } + const { fresh, free } = shipKinds(s, p, c); + if (fresh.length <= free || free === 0) return c.keep === undefined ? null : '고를 필요가 없어요.'; + if (!c.keep) return '상품 칸이 모자라요. 담을 상품을 골라 주세요.'; + const k = [...c.keep].sort((a, b) => a - b); + if (k.length !== free || new Set(k).size !== k.length || k.some((x) => !fresh.includes(x))) return '담을 상품을 다시 골라 주세요.'; + return null; +} + +function combos(xs: T[], k: number): T[][] { + if (k === 0) return [[]]; + if (xs.length < k) return []; + const [h, ...t] = xs; + return [...combos(t, k - 1).map((c) => [h!, ...c]), ...combos(t, k)]; +} + +export function shipChoices(s: CobState, p: PlayerId): ShipChoice[] { + const out: ShipChoice[] = []; + const adj = has(s, p, 5); + const extras = hasShield(s, p, 5) ? [...new Set(s.depots.flatMap((d) => d.goods))].sort((a, b) => a - b) : []; + for (let d = 1; d <= 6; d++) { + for (const a of adj ? [undefined, ...depotNeighbors(d)] : [undefined]) { + for (const e of [undefined, ...extras]) { + const base = { depot: d, ...(a ? { adjacent: a } : {}), ...(e ? { extra: e } : {}) }; + const { fresh, free } = shipKinds(s, p, base); + if (fresh.length <= free || free === 0) out.push(base); + else for (const keep of combos(fresh, free)) out.push({ ...base, keep }); + } + } + } + return out; +} + +function doShip(s: CobState, p: PlayerId, c: ShipChoice): void { + const pl = s.players[p]!; + const { fresh, free } = shipKinds(s, p, c); + const held = new Set(pl.goods.map((g) => g.die)); + const ok = new Set([...held, ...(fresh.length <= free ? fresh : (c.keep ?? []))]); + const got: Die[] = []; + const grab = (d: number, only?: number) => { + const dep = s.depots[d - 1]!; + dep.goods = dep.goods.filter((g) => { + if ((only === undefined || g === only) && ok.has(g)) { + addGoods(pl, g, 1); + got.push(g); + return false; + } + return true; + }); + }; + grab(c.depot); + if (c.adjacent) grab(c.adjacent); + if (c.extra) for (let d = 1; d <= 6; d++) grab(d, c.extra); + const depots = [c.depot, ...(c.adjacent ? [c.adjacent] : [])]; + log(s, { t: 'ship', p, depots, goods: got }); + // Turn order track: one space forward, on top of the stack there. + const pos = pl.track.pos + 1; + const top = Math.max(0, ...s.seats.filter((q) => q !== p && s.players[q]!.track.pos === pos).map((q) => s.players[q]!.track.height)); + pl.track = { pos, height: top + 1 }; + if (isSolo(s)) { + for (const dep of s.depots) { + s.out.goods += dep.goods.length; + dep.goods = []; + } + if (pl.goods.reduce((a, g) => a + g.count, 0) >= 5 && s.black.some((t) => t)) s.pending.push({ kind: 'soloTrade' }); + } +} + +/** Solo trade: pay 5 goods, smallest stacks first (decision §13). */ +function payFiveGoods(s: CobState, pl: CobPlayer): void { + let left = 5; + const order = [...pl.goods].sort((a, b) => a.count - b.count || a.die - b.die); + for (const g of order) { + const take = Math.min(left, g.count); + g.count -= take; + left -= take; + s.out.goods += take; + if (!left) break; + } + pl.goods = pl.goods.filter((g) => g.count > 0); +} + +// ---------------------------------------------------------------- turn order + +export function turnOrder(s: CobState): PlayerId[] { + const live = s.seats.filter((p) => !s.players[p]!.conceded); + const bridge = (p: PlayerId) => (has(s, p, 27) ? 1 : 0); + return [...live].sort((a, b) => { + const A = s.players[a]!.track; + const B = s.players[b]!.track; + return B.pos - A.pos || bridge(b) - bridge(a) || B.height - A.height; + }); +} + +// ---------------------------------------------------------------- flow + +function setDeadline(s: CobState, now: number, ms: number | null): void { + s.deadlineMs = ms ?? 0; + s.deadlineAt = ms === null ? null : now + ms; +} + +function turnMs(s: CobState, p: PlayerId): number | null { + if (s.options.turnSeconds === null) return null; + if (s.players[p]!.autoStreak >= AWAY_AFTER) return AWAY_MS; + return s.options.turnSeconds * 1000; +} + +export function startPhase(s: CobState, ctx: Ctx): void { + if (s.phase > 0) { + for (const d of s.depots) { + s.out.tiles += d.slots.filter((t) => t).length; + d.slots = []; + } + s.out.tiles += s.black.filter((t) => t).length; + } + const n = boardN(s); + for (let d = 1; d <= 6; d++) { + const dep = s.depots[d - 1]!; + dep.colors = depotColors(d, n, s.phase); + dep.slots = dep.colors.map((c) => s.piles[c].shift() ?? null); + } + s.black = Array.from({ length: blackSlots(n) }, () => s.piles.black.shift() ?? null); + s.roundGoods = s.phaseGoods.shift() ?? []; + if (s.options.inns) s.inns.push(`INN-${s.phase + 1}`); + log(s, { t: 'phase', phase: s.phase }); + s.round = 0; + startRound(s, ctx); +} + +function startRound(s: CobState, ctx: Ctx): void { + for (const p of s.seats) { + const pl = s.players[p]!; + if (pl.conceded) continue; + pl.dice = [(1 + ctx.rng.int(6)) as Die, (1 + ctx.rng.int(6)) as Die]; + pl.used = [false, false]; + } + s.whiteDie = (1 + ctx.rng.int(6)) as Die; + const g = s.roundGoods.shift() ?? null; + if (g !== null) s.depots[s.whiteDie - 1]!.goods.push(g); + log(s, { t: 'round', round: s.round, white: s.whiteDie, goods: g, depot: s.whiteDie }); + if (isSolo(s)) { + // Remove the first tile of the white die's depot (next depot clockwise when empty). + for (let k = 0; k < 6; k++) { + const d = ((s.whiteDie - 1 + k) % 6) + 1; + const dep = s.depots[d - 1]!; + const i = dep.slots.findIndex((t) => t); + if (i >= 0) { + const tile = dep.slots[i]!; + dep.slots[i] = null; + s.out.tiles++; + log(s, { t: 'soloRemove', tile, depot: d }); + break; + } + } + } + s.roundOrder = turnOrder(s); + s.turnIndex = 0; + startTurn(s, ctx); +} + +function startTurn(s: CobState, ctx: Ctx): void { + while (s.turnIndex < s.roundOrder.length && s.players[s.roundOrder[s.turnIndex]!]!.conceded) s.turnIndex++; + if (s.turnIndex >= s.roundOrder.length) return endRound(s, ctx); + const p = s.roundOrder[s.turnIndex]!; + const pl = s.players[p]!; + s.current = p; + pl.bought = false; + pl.free16 = false; + s.pending = []; + if (s.solo) s.solo.canBuy = false; + s.turnSeq++; + setDeadline(s, ctx.now, turnMs(s, p)); +} + +export function endTurn(s: CobState, ctx: Ctx): void { + s.pending = []; + if (s.solo) s.solo.canBuy = false; + s.turnIndex++; + startTurn(s, ctx); +} + +function endRound(s: CobState, ctx: Ctx): void { + s.current = null; + s.round++; + if (s.round >= 5) { + s.stage = 'phaseEnd'; + s.phaseEndStep = 'upkeep'; + s.pending = []; + continuePhaseEnd(s, ctx); + return; + } + startRound(s, ctx); +} + +export function continuePhaseEnd(s: CobState, ctx: Ctx): void { + while (s.stage === 'phaseEnd' && s.pending.length === 0) { + const order = turnOrder(s); + if (s.phaseEndStep === 'upkeep') { + s.phaseEndStep = 'income'; + if (shieldsOn(s)) { + const holders = order.filter((p) => Object.keys(s.players[p]!.shields).length > 0); + for (let i = holders.length - 1; i >= 0; i--) s.pending.push({ kind: 'upkeep', player: holders[i]! }); + } + } else if (s.phaseEndStep === 'income') { + for (const p of order) { + const pl = s.players[p]!; + const D = duchyOf(s, p); + const mines = D.spaces.filter((x) => x.color === 'mine' && pl.placed[x.id] && !pl.facedown.includes(pl.placed[x.id]!)).length; + const silver = mines * (hasShield(s, p, 8) ? 2 : 1); + const workers = has(s, p, 2) ? mines : 0; + pl.silver += silver; + pl.workers += workers; + if (silver || workers) log(s, { t: 'income', p, silver, workers }); + } + s.phaseEndStep = 'place'; + if (shieldsOn(s) && s.phase < 4) { + const list: Pending[] = []; + for (const p of order) { + if (hasShield(s, p, 14)) list.push({ kind: 'phasePlace', player: p, from: 'depot' }); + if (hasShield(s, p, 15)) list.push({ kind: 'phasePlace', player: p, from: 'black' }); + } + for (let i = list.length - 1; i >= 0; i--) s.pending.push(list[i]!); + dropEmptyPending(s); + } + } else { + s.phaseEndStep = null; + if (s.phase >= 4) return finish(s, isSolo(s) ? 'soloLose' : 'normal'); + s.phase++; + s.stage = 'turn'; + startPhase(s, ctx); + return; + } + } + if (s.stage === 'phaseEnd') setDeadline(s, ctx.now, s.options.turnSeconds === null ? null : PENDING_MIN_MS); +} + +export function finish(s: CobState, reason: NonNullable): void { + s.stage = 'finished'; + s.current = null; + s.pending = []; + s.deadlineAt = null; + s.deadlineMs = 0; + s.endReason = reason; + s.final = s.seats.map((p) => finalRow(s, p)); + log(s, { t: 'end' }); +} + +export function finalRow(s: CobState, p: PlayerId): FinalRow { + const pl = s.players[p]!; + const goodsLeft = pl.goods.reduce((a, g) => a + g.count, 0); + const workers = Math.floor(pl.workers / 2); + const monasteries: { id: string; vp: number }[] = []; + if (!isSolo(s)) { + const crane = { v: false }; + const mult = hasShield(s, p, 10) ? 2 : 1; + for (const t of monasteryTiles(s, p)) if (END_MONASTERY(t)) monasteries.push({ id: t, vp: monasteryVp(s, p, t, crane) * mult }); + } + const shieldVp = shieldsOn(s) ? Object.values(pl.shields).reduce((a, n) => a + shieldDef(n).vp, 0) * (hasShield(s, p, 13) ? 2 : 1) : 0; + const total = pl.vp + goodsLeft + pl.silver + workers + monasteries.reduce((a, m) => a + m.vp, 0) + shieldVp; + const emptySpaces = duchyOf(s, p).spaces.length - Object.keys(pl.placed).length; + return { player: p, inGame: pl.vp, goodsLeft, silver: pl.silver, workers, monasteries, shields: shieldVp, total, emptySpaces, conceded: pl.conceded }; +} + +// ---------------------------------------------------------------- pending options + +/** True when the top pending has a real choice (otherwise it is dropped). */ +function pendingUseful(s: CobState, pd: Pending, p: PlayerId): boolean { + const pl = s.players[p]!; + switch (pd.kind) { + case 'depotTake': + return s.depots.some((d) => d.slots.some((t) => t && pd.colors.includes(tileDef(t).color as Color))); + case 'warehouse': + return pl.goods.length > 0; + case 'townhall': + return pl.storage.some((t) => placeSpaces(s, p, t).length > 0); + case 'geese': { + const tiles = pastureTiles(s, p, pd.region); + return tiles.some((t) => t.animal !== 'goose'); + } + case 'soloTrade': + return pl.goods.reduce((a, g) => a + g.count, 0) >= 5 && s.black.some((t) => t); + case 'soloBlack': + return s.black.some((t) => t && placeSpaces(s, p, t).length > 0); + case 'phasePlace': { + const src = pd.from === 'black' ? s.black : s.depots.flatMap((d) => d.slots); + return src.some((t) => t && placeSpaces(s, p, t).length > 0); + } + case 'shieldCopy': + return s.seats.some((q) => q !== p); + default: + return true; + } +} + +/** Who must answer the top pending. */ +export function pendingActor(s: CobState): PlayerId | null { + const top = s.pending[s.pending.length - 1]; + if (!top) return null; + if (top.kind === 'upkeep' || top.kind === 'phasePlace') return top.player; + return s.current; +} + +export function dropEmptyPending(s: CobState): void { + for (;;) { + const top = s.pending[s.pending.length - 1]; + if (!top) return; + const who = pendingActor(s); + if (who && !s.players[who]!.conceded && pendingUseful(s, top, who)) return; + s.pending.pop(); + } +} + +// ---------------------------------------------------------------- validation + +const ANY_BUY_TIME = (s: CobState): boolean => { + const top = s.pending[s.pending.length - 1]; + return !top || top.kind === 'bonus'; +}; + +export function canBuyAnything(s: CobState, p: PlayerId): boolean { + return buyChoices(s, p).length > 0 || buyWorkersOk(s, p) || soloBuyOk(s, p); +} +const buyWorkersOk = (s: CobState, p: PlayerId): boolean => has(s, p, 28) && s.players[p]!.silver >= 1; +const soloBuyOk = (s: CobState, p: PlayerId): boolean => !!s.solo?.canBuy && s.players[p]!.silver >= 1; + +/** Buyable tiles now (ignoring discard), with the ways to pay. */ +export function buyChoices(s: CobState, p: PlayerId): { tile: string; pay: 'silver' | 'workers' }[] { + const pl = s.players[p]!; + if (pl.bought) return []; + const m6 = has(s, p, 6); + const workersOk = m6 && s.options.monasteryRules === '2019' && pl.workers >= 2; + const silverOk = pl.silver >= 2; + if (!silverOk && !workersOk) return []; + const tiles: string[] = s.black.filter((t): t is string => !!t); + if (s.inns.length) tiles.push(s.inns[s.inns.length - 1]!); + if (m6) for (const d of s.depots) for (const t of d.slots) if (t) tiles.push(t); + const out: { tile: string; pay: 'silver' | 'workers' }[] = []; + for (const tile of tiles) { + if (silverOk) out.push({ tile, pay: 'silver' }); + if (workersOk) out.push({ tile, pay: 'workers' }); + } + return out; +} + +function discardError(s: CobState, p: PlayerId, discard: number | undefined): string | null { + const pl = s.players[p]!; + if (storageFull(s, p)) { + if (discard === undefined) return '보관 칸이 꽉 찼어요. 버릴 타일을 골라 주세요.'; + if (!Number.isInteger(discard) || discard < 0 || discard >= pl.storage.length) return '버릴 타일을 다시 골라 주세요.'; + return null; + } + return discard === undefined ? null : '보관 칸에 빈자리가 있어요.'; +} + +/** Checks one die action. `face` null = a castle bonus (any value, free). Returns error or the worker cost. */ +export function dieActCheck(s: CobState, p: PlayerId, act: DieAct, face: Die | null, bonus: Pending | null): { err: string | null; cost: number; use16: boolean } { + const pl = s.players[p]!; + const bad = (err: string) => ({ err, cost: 0, use16: false }); + const price = (value: number, kind: CostKind) => { + if (face === null) return { err: null, cost: 0, use16: false }; + const c = dieCost(s, p, face, value, kind); + if (c.cost > pl.workers) return { err: `일꾼이 ${c.cost}개 필요해요.`, cost: c.cost, use16: c.use16 }; + return { err: null, ...c }; + }; + switch (act.kind) { + case 'take': { + const w = findTile(s, act.tile); + if (!w || w.at !== 'depot') return bad('번호 보급소의 타일만 주사위로 가져올 수 있어요.'); + const de = discardError(s, p, act.discard); + if (de) return bad(de); + return price(w.depot, 'take'); + } + case 'place': { + const tile = pl.storage[act.slot]; + if (!tile) return bad('보관 칸에 그 타일이 없어요.'); + const pe = placeError(s, p, tile, act.space, null); + if (pe) return bad(pe); + return price(duchyOf(s, p).spaces[act.space]!.die, costKindOfTile(pl, tile)); + } + case 'sell': + if (!pl.goods.some((g) => g.die === act.goods)) return bad('그 상품이 없어요.'); + return price(act.goods, 'none'); + case 'workers': + return { err: null, cost: 0, use16: false }; + case 'shield': { + if (face !== null || !bonus || bonus.kind !== 'bonus' || bonus.source !== 'castle' || !hasShield(s, p, 11)) return bad('방패 11번이 있을 때 성 보너스로만 방패를 가져와요.'); + const e = shieldTakeError(s, p, act.depot, act.shield, act.space); + return e ? bad(e) : { err: null, cost: 0, use16: false }; + } + } +} + +export function shieldTakeError(s: CobState, p: PlayerId, depot: number, shield: number, space: number): string | null { + if (!shieldsOn(s)) return '방패를 쓰지 않는 게임이에요.'; + const dep = s.depots[depot - 1]; + if (!dep || !dep.shields.includes(shield)) return '그 보급소에 그 방패가 없어요.'; + const pl = s.players[p]!; + const castles = myCastles(s, p); + if (!castles.includes(space)) return '내 성 타일 위에만 방패를 놓아요.'; + const empty = castles.filter((c) => pl.shields[c] === undefined); + if (empty.length && pl.shields[space] !== undefined) return '방패가 없는 성이 있어요. 거기에 놓아 주세요.'; + return null; +} + +export function myCastles(s: CobState, p: PlayerId): number[] { + const pl = s.players[p]!; + return duchyOf(s, p) + .spaces.filter((x) => x.color === 'castle' && pl.placed[x.id] && !pl.facedown.includes(pl.placed[x.id]!) && !isInn(pl.placed[x.id])) + .map((x) => x.id); +} + +/** Worker cost of taking shield of depot `v` with both dice. */ +export function doubleCost(s: CobState, p: PlayerId, v: number): { cost: number; use16: boolean } { + const pl = s.players[p]!; + const c0 = rawCost(s, p, pl.dice[0], v, 'none'); + const c1 = rawCost(s, p, pl.dice[1], v, 'none'); + if (hasShield(s, p, 16) && !pl.free16 && Math.max(c0, c1) > 0) return { cost: Math.min(c0, c1), use16: true }; + return { cost: c0 + c1, use16: false }; +} + +const top = (s: CobState): Pending | undefined => s.pending[s.pending.length - 1]; + +/** Single source of truth for legality (`validate` and the legal-move generator). */ +export function actionError(s: CobState, p: PlayerId, a: CobAction): string | null { + if (s.stage === 'finished') return '게임이 끝났어요.'; + const pl = s.players[p]; + if (!pl) return '이 게임의 참가자가 아니에요.'; + if (a.type === 'leave') return pl.conceded ? '이미 기권했어요.' : null; + if (a.type === 'concede') return pl.conceded ? '이미 기권했어요.' : null; + if (pl.conceded) return '기권해서 더 할 수 없어요.'; + if (a.type === 'timeout') return waitingOn(s).includes(p) ? null : '지금은 기다리는 차례가 아니에요.'; + + if (s.stage === 'castle') { + if (a.type !== 'chooseCastle') return '먼저 시작 성을 놓아 주세요.'; + if (s.castleQueue[0] !== p) return '다른 사람이 성을 고르는 중이에요.'; + if (!duchyOf(s, p).castleSpaces.includes(a.space)) return '성(진초록) 칸에만 놓을 수 있어요.'; + return null; + } + + const t = top(s); + if (s.stage === 'phaseEnd') { + if (!t || pendingActor(s) !== p) return '지금은 기다리는 차례가 아니에요.'; + if (t.kind === 'upkeep' && a.type === 'upkeep') { + const mine = Object.values(pl.shields); + if (new Set(a.keep).size !== a.keep.length || a.keep.some((n) => !mine.includes(n))) return '내 방패를 골라 주세요.'; + const can = pl.silver + (hasShield(s, p, 3) ? pl.workers : 0); + return a.keep.length <= can ? null : '유지비(방패 1개당 은화 1)가 모자라요.'; + } + if (t.kind === 'phasePlace' && a.type === 'phasePlace') { + if ('skip' in a) return null; + const w = findTile(s, a.tile); + if (!w || (t.from === 'black' ? w.at !== 'black' : w.at !== 'depot')) return t.from === 'black' ? '검은 보급소 타일을 골라 주세요.' : '번호 보급소 타일을 골라 주세요.'; + return placeError(s, p, a.tile, a.space, null); + } + return '페이즈 끝 정리 중이에요.'; + } + + // stage 'turn' + if (s.current !== p) return '내 차례가 아니에요.'; + if (a.type === 'buy') { + if (!ANY_BUY_TIME(s)) return '먼저 지금 효과를 끝내 주세요.'; + if (pl.bought) return '이번 차례에 이미 샀어요.'; + if (!buyChoices(s, p).some((b) => b.tile === a.tile && b.pay === a.pay)) return '그 타일은 지금 살 수 없어요.'; + return discardError(s, p, a.discard); + } + if (a.type === 'buyWorkers') { + if (!ANY_BUY_TIME(s)) return '먼저 지금 효과를 끝내 주세요.'; + return buyWorkersOk(s, p) ? null : '수도원 28번과 은화 1개가 있어야 해요.'; + } + if (a.type === 'soloBuyVp') { + if (!ANY_BUY_TIME(s)) return '먼저 지금 효과를 끝내 주세요.'; + return soloBuyOk(s, p) ? null : '점수를 얻은 직후에 은화 1개로 1점을 살 수 있어요.'; + } + if (t) { + switch (t.kind) { + case 'bonus': + if (a.type !== 'bonus') return '먼저 보너스 행동을 해 주세요.'; + return dieActCheck(s, p, a.act, null, t).err; + case 'ship': + if (a.type !== 'ship') return '먼저 상품을 가져올 보급소를 골라 주세요.'; + return shipError(s, p, a); + case 'depotTake': { + if (a.type !== 'depotTake') return '먼저 보급소 타일을 골라 주세요.'; + if ('skip' in a) return null; + const w = findTile(s, a.tile); + if (!w || w.at !== 'depot') return '번호 보급소의 타일만 가져올 수 있어요.'; + if (!t.colors.includes(tileDef(a.tile).color as Color)) return '그 색 타일은 가져올 수 없어요.'; + return discardError(s, p, a.discard); + } + case 'warehouse': + if (a.type !== 'warehouse') return '먼저 창고로 팔 상품을 골라 주세요.'; + if ('skip' in a) return null; + return pl.goods.some((g) => g.die === a.goods) ? null : '그 상품이 없어요.'; + case 'townhall': { + if (a.type !== 'townhall') return '먼저 시청 효과를 써 주세요.'; + if ('skip' in a) return null; + const tile = pl.storage[a.slot]; + if (!tile) return '보관 칸에 그 타일이 없어요.'; + return placeError(s, p, tile, a.space, null); + } + case 'crane': + if (a.type !== 'crane') return '먼저 기중기로 쓸 건물 효과를 골라 주세요.'; + return BUILDINGS.includes(a.building) ? null : '건물을 골라 주세요.'; + case 'geese': + if (a.type !== 'geese') return '먼저 거위 점수를 받을 가축을 골라 주세요.'; + if (a.animal === null) return null; + return pastureTiles(s, p, t.region).some((x) => x.animal === a.animal) ? null : '그 목초지에 그 가축이 없어요.'; + case 'shieldCopy': + if (a.type !== 'shieldCopy') return '먼저 수도원 효과를 함께 쓸 사람을 골라 주세요.'; + return a.player !== p && s.players[a.player] ? null : '다른 사람을 골라 주세요.'; + case 'soloTrade': { + if (a.type !== 'soloTrade') return '먼저 상품 5장 바꾸기를 정해 주세요.'; + if ('skip' in a) return null; + const w = findTile(s, a.tile); + if (!w || w.at !== 'black') return '검은 보급소 타일을 골라 주세요.'; + if (pl.goods.reduce((x, g) => x + g.count, 0) < 5) return '상품이 5장 있어야 해요.'; + return discardError(s, p, a.discard); + } + case 'soloBlack': { + if (a.type !== 'soloBlack') return '먼저 검은 보급소 타일을 놓아 주세요.'; + if ('skip' in a) return null; + const w = findTile(s, a.tile); + if (!w || w.at !== 'black') return '검은 보급소 타일을 골라 주세요.'; + return placeError(s, p, a.tile, a.space, null); + } + default: + return '지금은 할 수 없어요.'; + } + } + switch (a.type) { + case 'useDie': { + if (pl.used[a.die]) return '이미 쓴 주사위예요.'; + if (a.act.kind === 'shield') return '방패는 두 주사위로 가져와요.'; + return dieActCheck(s, p, a.act, pl.dice[a.die], null).err; + } + case 'takeShield': { + if (pl.used[0] || pl.used[1]) return '두 주사위를 모두 아직 안 썼을 때만 방패를 가져와요.'; + const e = shieldTakeError(s, p, a.depot, a.shield, a.space); + if (e) return e; + return doubleCost(s, p, a.depot).cost <= pl.workers ? null : '일꾼이 모자라요.'; + } + case 'endTurn': + return null; + default: + return '지금은 할 수 없어요.'; + } +} + +export function waitingOn(s: CobState): PlayerId[] { + if (s.stage === 'finished') return []; + if (s.stage === 'castle') return s.castleQueue.slice(0, 1); + if (s.stage === 'phaseEnd') { + const who = pendingActor(s); + return who ? [who] : []; + } + return s.current ? [s.current] : []; +} + +// ---------------------------------------------------------------- perform + +function performDieAct(s: CobState, p: PlayerId, act: DieAct): void { + const pl = s.players[p]!; + switch (act.kind) { + case 'take': { + const w = findTile(s, act.tile)!; + removeAt(s, w); + toStorage(s, p, act.tile, act.discard); + log(s, { t: 'take', p, tile: act.tile, depot: w.at === 'depot' ? w.depot : 'black' }); + return; + } + case 'place': { + const tile = pl.storage.splice(act.slot, 1)[0]!; + placeTile(s, p, tile, act.space, true); + return; + } + case 'sell': + sellGoods(s, p, act.goods as Die); + return; + case 'workers': + takeWorkers(s, p); + return; + case 'shield': + putShield(s, p, act.depot, act.shield, act.space); + return; + } +} + +function putShield(s: CobState, p: PlayerId, depot: number, shield: number, space: number): void { + const pl = s.players[p]!; + const dep = s.depots[depot - 1]!; + dep.shields.splice(dep.shields.indexOf(shield), 1); + const old = pl.shields[space]; + if (old !== undefined) { + log(s, { t: 'shieldLost', p, shield: old }); + if (old === 6) pl.copyFrom = null; + } + pl.shields[space] = shield; + log(s, { t: 'shield', p, shield }); + if (shield === 6) s.pending.push({ kind: 'shieldCopy' }); +} + +/** Apply a validated action to `s` (mutates). */ +export function perform(s: CobState, p: PlayerId, a: CobAction, ctx: Ctx): void { + const pl = s.players[p]!; + if (a.type !== 'timeout' && a.type !== 'leave') pl.autoStreak = 0; + switch (a.type) { + case 'leave': + case 'concede': + return concede(s, p, ctx); + case 'timeout': + return autoPlay(s, p, ctx); + case 'chooseCastle': { + pl.start = a.space; + pl.placed[a.space] = s.startTiles[p]!; + s.castleQueue.shift(); + log(s, { t: 'place', p, tile: s.startTiles[p]!, space: a.space }); + if (s.castleQueue.length === 0) { + s.stage = 'turn'; + startPhase(s, ctx); + } else setDeadline(s, ctx.now, s.options.turnSeconds === null ? null : CASTLE_MS); + return; + } + case 'useDie': { + const face = pl.dice[a.die]; + const c = dieActCheck(s, p, a.act, face, null); + pl.workers -= c.cost; + if (c.use16) pl.free16 = true; + pl.used[a.die] = true; + if (s.solo) s.solo.canBuy = false; + performDieAct(s, p, a.act); + break; + } + case 'bonus': + s.pending.pop(); + if (s.solo) s.solo.canBuy = false; + performDieAct(s, p, a.act); + break; + case 'takeShield': { + const c = doubleCost(s, p, a.depot); + pl.workers -= c.cost; + if (c.use16) pl.free16 = true; + pl.used = [true, true]; + putShield(s, p, a.depot, a.shield, a.space); + break; + } + case 'buy': { + const w = findTile(s, a.tile)!; + if (a.pay === 'silver') pl.silver -= 2; + else pl.workers -= 2; + pl.bought = true; + removeAt(s, w); + toStorage(s, p, a.tile, a.discard); + log(s, { t: 'buy', p, tile: a.tile, from: w.at === 'depot' ? w.depot : w.at }); + break; + } + case 'buyWorkers': + pl.silver -= 1; + pl.workers += 2; + break; + case 'soloBuyVp': + pl.silver -= 1; + gainVp(s, p, 1); + break; + case 'ship': + s.pending.pop(); + doShip(s, p, a); + break; + case 'depotTake': { + s.pending.pop(); + if ('skip' in a) break; + const w = findTile(s, a.tile)!; + removeAt(s, w); + toStorage(s, p, a.tile, a.discard); + log(s, { t: 'take', p, tile: a.tile, depot: w.at === 'depot' ? w.depot : 'black' }); + break; + } + case 'warehouse': + s.pending.pop(); + if (!('skip' in a)) sellGoods(s, p, a.goods as Die); + break; + case 'townhall': { + s.pending.pop(); + if ('skip' in a) break; + const tile = pl.storage.splice(a.slot, 1)[0]!; + placeTile(s, p, tile, a.space, true); + break; + } + case 'crane': { + s.pending.pop(); + log(s, { t: 'building', p, building: a.building }); + const later: Pending[] = []; + buildingEffect(s, p, a.building, true, later); + for (let i = later.length - 1; i >= 0; i--) s.pending.push(later[i]!); + break; + } + case 'geese': { + const t = s.pending.pop() as Extract; + if (a.animal) { + const vp = animalPoints(s, p, pastureTiles(s, p, t.region), a.animal); + gainVp(s, p, vp); + log(s, { t: 'livestock', p, vp }); + } + break; + } + case 'shieldCopy': + s.pending.pop(); + pl.copyFrom = a.player; + break; + case 'upkeep': { + s.pending.pop(); + let cost = a.keep.length; + const fromSilver = Math.min(cost, pl.silver); + pl.silver -= fromSilver; + cost -= fromSilver; + pl.workers -= cost; + for (const [space, n] of Object.entries(pl.shields)) { + if (!a.keep.includes(n)) { + delete pl.shields[space]; + if (n === 6) pl.copyFrom = null; + log(s, { t: 'shieldLost', p, shield: n }); + } + } + break; + } + case 'phasePlace': { + s.pending.pop(); + if ('skip' in a) break; + const w = findTile(s, a.tile)!; + removeAt(s, w); + placeTile(s, p, a.tile, a.space, false); + break; + } + case 'soloTrade': { + s.pending.pop(); + if ('skip' in a) break; + const w = findTile(s, a.tile)!; + removeAt(s, w); + payFiveGoods(s, pl); + pl.facedown.push(a.tile); + toStorage(s, p, a.tile, a.discard); + log(s, { t: 'take', p, tile: a.tile, depot: 'black' }); + break; + } + case 'soloBlack': { + s.pending.pop(); + if ('skip' in a) break; + const w = findTile(s, a.tile)!; + removeAt(s, w); + placeTile(s, p, a.tile, a.space, true); + break; + } + case 'endTurn': + return endTurn(s, ctx); + } + settle(s, ctx); +} + +/** After an action: drop pendings without a choice, keep the clock fair, end a finished turn, run phase end. */ +export function settle(s: CobState, ctx: Ctx): void { + if (s.stage === 'finished') return; + dropEmptyPending(s); + if (s.stage === 'phaseEnd') { + if (s.pending.length === 0) continuePhaseEnd(s, ctx); + else setDeadline(s, ctx.now, s.options.turnSeconds === null ? null : PENDING_MIN_MS); + return; + } + if (s.stage !== 'turn' || !s.current) return; + const p = s.current; + const pl = s.players[p]!; + if (s.pending.length && s.deadlineAt !== null && s.deadlineAt - ctx.now < PENDING_MIN_MS) { + s.deadlineAt = ctx.now + PENDING_MIN_MS; + } + if (!s.pending.length && pl.used[0] && pl.used[1] && !canBuyAnything(s, p)) endTurn(s, ctx); +} + +// ---------------------------------------------------------------- leaving / clock + +function concede(s: CobState, p: PlayerId, ctx: Ctx): void { + const pl = s.players[p]!; + pl.conceded = true; + log(s, { t: 'concede', p }); + if (isSolo(s)) return finish(s, 'soloLose'); + const live = s.seats.filter((q) => !s.players[q]!.conceded); + if (live.length <= 1) return finish(s, 'resign'); + if (s.stage === 'castle') { + s.castleQueue = s.castleQueue.filter((q) => q !== p); + if (!pl.placed[pl.start >= 0 ? pl.start : -1]) { + const sp = duchyOf(s, p).startSpace; + pl.start = sp; + pl.placed[sp] = s.startTiles[p]!; + } + if (s.castleQueue.length === 0) { + s.stage = 'turn'; + startPhase(s, ctx); + } + return; + } + if (s.stage === 'turn' && s.current === p) return endTurn(s, ctx); + if (s.stage === 'phaseEnd') { + s.pending = s.pending.filter((x) => !((x.kind === 'upkeep' || x.kind === 'phasePlace') && x.player === p)); + settle(s, ctx); + } +} + +/** Deterministic auto choice for the top pending (doc §8.5). */ +export function autoPendingAction(s: CobState, p: PlayerId): CobAction { + const t = top(s)!; + const pl = s.players[p]!; + switch (t.kind) { + case 'bonus': + return { type: 'bonus', act: { kind: 'workers' } }; + case 'ship': { + const all = shipChoices(s, p); + let best = all[0]!; + let bestN = -1; + for (const c of all) { + const { fresh, free } = shipKinds(s, p, c); + const ok = new Set([...pl.goods.map((g) => g.die as number), ...(fresh.length <= free ? fresh : (c.keep ?? []))]); + const ds = c.adjacent ? [c.depot, c.adjacent] : [c.depot]; + const n = ds.reduce((acc, d) => acc + s.depots[d - 1]!.goods.filter((g) => ok.has(g)).length, 0); + if (n > bestN) { + bestN = n; + best = c; + } + } + return { type: 'ship', ...best } as CobAction; + } + case 'depotTake': { + if (storageFull(s, p)) return { type: 'depotTake', skip: true }; + for (const d of s.depots) for (const tile of d.slots) if (tile && t.colors.includes(tileDef(tile).color as Color)) return { type: 'depotTake', tile }; + return { type: 'depotTake', skip: true }; + } + case 'warehouse': { + const g = [...pl.goods].sort((a, b) => b.count - a.count || a.die - b.die)[0]; + return g ? { type: 'warehouse', goods: g.die } : { type: 'warehouse', skip: true }; + } + case 'townhall': + return { type: 'townhall', skip: true }; + case 'crane': + return { type: 'crane', building: 'bank' }; + case 'geese': { + const a = pastureTiles(s, p, t.region).find((x) => x.animal !== 'goose'); + return { type: 'geese', animal: (a?.animal as 'cow') ?? null }; + } + case 'shieldCopy': + return { type: 'shieldCopy', player: s.seats.find((q) => q !== p)! }; + case 'upkeep': { + const can = pl.silver + (hasShield(s, p, 3) ? pl.workers : 0); + const keep = Object.values(pl.shields) + .sort((a, b) => a - b) + .slice(0, can); + return { type: 'upkeep', keep }; + } + case 'phasePlace': + return { type: 'phasePlace', skip: true }; + case 'soloTrade': + return { type: 'soloTrade', skip: true }; + case 'soloBlack': + return { type: 'soloBlack', skip: true }; + } +} + +/** Zero-cost placement for die `i` (region completion first), else take workers. */ +function autoDieAction(s: CobState, p: PlayerId, i: 0 | 1): CobAction { + const pl = s.players[p]!; + const D = duchyOf(s, p); + let best: { slot: number; space: number } | null = null; + let bestScore = -1; + pl.storage.forEach((tile, slot) => { + for (const space of placeSpaces(s, p, tile)) { + const sp = D.spaces[space]!; + if (rawCost(s, p, pl.dice[i], sp.die, costKindOfTile(pl, tile)) > 0) continue; + const region = regionSpaces(D, space); + const completes = region.every((x) => x === space || pl.placed[x]); + const score = completes ? 100 + region.length : 1; + if (score > bestScore) { + bestScore = score; + best = { slot, space }; + } + } + }); + if (best) return { type: 'useDie', die: i, act: { kind: 'place', ...(best as { slot: number; space: number }) } }; + return { type: 'useDie', die: i, act: { kind: 'workers' } }; +} + +function autoPlay(s: CobState, p: PlayerId, ctx: Ctx): void { + const pl = s.players[p]!; + pl.autoStreak++; + log(s, { t: 'auto', p }); + if (s.stage === 'castle') { + const sp = duchyOf(s, p).startSpace; + perform(s, p, { type: 'chooseCastle', space: sp }, ctx); + pl.autoStreak = Math.max(pl.autoStreak, 1); + return; + } + const streak = pl.autoStreak; + const run = (a: CobAction) => { + perform(s, p, a, ctx); + pl.autoStreak = streak; + }; + if (s.stage === 'phaseEnd') { + if (pendingActor(s) === p) run(autoPendingAction(s, p)); + return; + } + const seq = s.turnSeq; + for (let guard = 0; guard < 100; guard++) { + if (s.stage !== 'turn' || s.current !== p || s.turnSeq !== seq) return; + if (s.pending.length) { + run(autoPendingAction(s, p)); + continue; + } + const i = !pl.used[0] ? 0 : !pl.used[1] ? 1 : -1; + if (i < 0) break; + run(autoDieAction(s, p, i as 0 | 1)); + } + if (s.stage === 'turn' && s.current === p && s.turnSeq === seq) { + endTurn(s, ctx); + } +} + +// ---------------------------------------------------------------- setup + +export function setupState(players: PlayerId[], options: CobOptions, rng: Rng, now: number): CobState { + const solo = options.mode === 'solo'; + const n = players.length; + if (solo ? n !== 1 : n < 2 || n > 4) throw new Error(solo ? '혼자 하기는 1명이 해요.' : '버건디의 성은 2~4명이 할 수 있어요.'); + const piles = Object.fromEntries((['castle', 'mine', 'monastery', 'building', 'livestock', 'ship', 'black'] as PileKey[]).map((k) => [k, [] as string[]])) as Record; + for (const t of tilesInPlay(options.extraTiles)) piles[t.back === 'black' ? 'black' : (t.color as Color)].push(t.id); + for (const k of Object.keys(piles) as PileKey[]) piles[k] = rng.shuffle(piles[k]); + const startTiles: Record = {}; + for (const p of players) startTiles[p] = piles.castle.shift()!; + const goods: Die[] = rng.shuffle(([1, 2, 3, 4, 5, 6] as Die[]).flatMap((d) => Array.from({ length: 7 }, () => d))); + const phaseGoods: Die[][] = [0, 1, 2, 3, 4].map((i) => goods.slice(i * 5, i * 5 + 5)); + let rest = goods.slice(25); + const first = rng.int(n); + const order = [...players.slice(first), ...players.slice(0, first)]; + const shieldPool = options.shields && !solo ? rng.shuffle(Array.from({ length: 18 }, (_, i) => i + 1)) : []; + const s: CobState = { + options, + seats: [...players], + phase: 0, + round: 0, + stage: 'turn', + roundOrder: [], + turnIndex: 0, + current: null, + whiteDie: 1, + depots: Array.from({ length: 6 }, (_, d) => ({ + slots: [], + colors: [], + goods: [], + shields: shieldPool.length ? shieldPool.splice(0, shieldsPerDepot(d + 1, n)) : [], + })), + black: [], + inns: [], + roundGoods: [], + phaseGoods, + piles, + bonusLeft: Object.fromEntries(COLORS.map((c) => [c, ['large', 'small']])) as CobState['bonusLeft'], + players: {}, + pending: [], + castleQueue: [], + phaseEndStep: null, + solo: solo ? { target: options.soloTarget, canBuy: false } : null, + out: { tiles: 0, goods: 0 }, + startTiles, + turnSeq: 0, + deadlineAt: null, + deadlineMs: 0, + seq: 0, + log: [], + endReason: null, + final: null, + }; + s.out.goods += shieldPool.length ? 0 : 0; + order.forEach((p, i) => { + const pl: CobPlayer = { + placed: {}, + start: -1, + storage: [], + facedown: [], + goods: [], + sold: [0, 0, 0, 0, 0, 0], + silver: 1, + workers: solo ? 2 : i + 1, + vp: 0, + dice: [1, 1], + used: [false, false], + bought: false, + free16: false, + bonus: [], + shields: {}, + copyFrom: null, + track: { pos: 0, height: n - i }, + conceded: false, + autoStreak: 0, + }; + for (const g of rest.slice(0, 3)) addGoods(pl, g, 1); + rest = rest.slice(3); + s.players[p] = pl; + }); + s.out.goods += rest.length; + const ctx: Ctx = { rng, now }; + if (options.castleStart === 'choose' || solo) { + s.stage = 'castle'; + s.castleQueue = order; + setDeadline(s, now, options.turnSeconds === null ? null : CASTLE_MS); + return s; + } + for (const p of players) { + const pl = s.players[p]!; + const sp = duchyOf(s, p).startSpace; + pl.start = sp; + pl.placed[sp] = startTiles[p]!; + } + startPhase(s, ctx); + return s; +} + +/** Test helper: number of hex tiles accounted for (must stay constant). */ +export function tileCount(s: CobState): number { + let n = s.out.tiles; + for (const k of Object.keys(s.piles) as PileKey[]) n += s.piles[k].length; + for (const d of s.depots) n += d.slots.filter((t) => t).length; + n += s.black.filter((t) => t).length; + for (const p of s.seats) { + const pl = s.players[p]!; + n += pl.storage.filter((t) => !isInn(t)).length + Object.values(pl.placed).filter((t) => !isInn(t)).length; + } + if (s.stage === 'castle') n += s.castleQueue.filter((p) => !Object.keys(s.players[p]!.placed).length).length; + return n; +} +export function goodsCount(s: CobState): number { + let n = s.out.goods + s.roundGoods.length + s.phaseGoods.reduce((a, g) => a + g.length, 0); + for (const d of s.depots) n += d.goods.length; + for (const p of s.seats) { + const pl = s.players[p]!; + n += pl.goods.reduce((a, g) => a + g.count, 0) + pl.sold.reduce((a, b) => a + b, 0); + } + return n; +} + +export { ANIMALS }; diff --git a/packages/games/src/castles-of-burgundy/index.ts b/packages/games/src/castles-of-burgundy/index.ts new file mode 100644 index 0000000..e537987 --- /dev/null +++ b/packages/games/src/castles-of-burgundy/index.ts @@ -0,0 +1,212 @@ +/** 버건디의 성 (docs/games/castles-of-burgundy.md). Pure and deterministic; state is JSON. */ +import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine'; +import { PILE_KEYS, type PileKey } from './data'; +import { actionError, finalRow, perform, setupState, waitingOn, type Ctx } from './engine'; +import { legalMoves } from './moves'; +import { cobOptionsSchema, type CobOptions } from './options'; +import { cobActionSchema, type CobAction, type CobPlayerView, type CobState, type CobView, type FinalRow } from './types'; + +export * from './types'; +export { legalMoves } from './moves'; +export { goodsCount, tileCount, finalRow } from './engine'; + +const RECENT = 30; + +function playerView(s: CobState, p: PlayerId, viewer: PlayerId | null): CobPlayerView { + const pl = s.players[p]!; + const { sold, ...rest } = pl; + return { + ...structuredClone(rest), + id: p, + sold: viewer === p ? [...sold] : null, + soldCount: sold.reduce((a, b) => a + b, 0), + emptySpaces: 37 - Object.keys(pl.placed).length, + away: pl.autoStreak >= 3, + }; +} + +export function view(s: CobState, viewer: PlayerId | null): CobView { + const me = viewer && s.players[viewer] ? viewer : null; + const waiting = waitingOn(s); + let my: CobView['my'] = null; + if (me && waiting.includes(me)) { + const moves = legalMoves(s, me, true); + my = { + moves: moves.map((m) => m.a), + costs: moves.map((m) => m.cost), + needDiscard: s.players[me]!.storage.length >= (Object.values(s.players[me]!.shields).includes(4) && s.options.shields ? 99 : 3), + projected: s.options.showHints ? finalRow(s, me).total : null, + }; + } + const pilesLeft = Object.fromEntries(PILE_KEYS.map((k) => [k, s.piles[k].length])) as Record; + return { + options: s.options, + me, + seats: [...s.seats], + phase: s.phase, + round: s.round, + stage: s.stage, + roundOrder: [...s.roundOrder], + turnIndex: s.turnIndex, + current: s.current, + whiteDie: s.whiteDie, + depots: structuredClone(s.depots), + black: [...s.black], + inns: [...s.inns], + roundGoods: [...s.roundGoods], + pilesLeft, + bonusLeft: structuredClone(s.bonusLeft), + players: Object.fromEntries(s.seats.map((p) => [p, playerView(s, p, me)])), + pending: structuredClone(s.pending), + castleQueue: [...s.castleQueue], + phaseEndStep: s.phaseEndStep, + solo: s.solo ? { ...s.solo } : null, + turnSeq: s.turnSeq, + deadlineAt: s.deadlineAt, + deadlineMs: s.deadlineMs, + seq: s.seq, + log: s.log.slice(-RECENT), + endReason: s.endReason, + final: s.final ? structuredClone(s.final) : null, + waiting, + my, + }; +} + +/** Rebuilds a state from a view for look-ahead inside one turn (hidden piles empty, others' sold unknown). */ +export function stateFromView(v: CobView): CobState { + const players: CobState['players'] = {}; + for (const p of v.seats) { + const pv = v.players[p]!; + const { id: _id, sold, soldCount: _c, emptySpaces: _e, away: _a, ...rest } = pv; + players[p] = { ...structuredClone(rest), sold: sold ? [...sold] : [0, 0, 0, 0, 0, 0] }; + } + return { + options: v.options, + seats: [...v.seats], + phase: v.phase, + round: v.round, + stage: v.stage, + roundOrder: [...v.roundOrder], + turnIndex: v.turnIndex, + current: v.current, + whiteDie: v.whiteDie, + depots: structuredClone(v.depots), + black: [...v.black], + inns: [...v.inns], + roundGoods: [...v.roundGoods], + phaseGoods: [], + piles: Object.fromEntries(PILE_KEYS.map((k) => [k, []])) as unknown as CobState['piles'], + bonusLeft: structuredClone(v.bonusLeft), + players, + pending: structuredClone(v.pending), + castleQueue: [...v.castleQueue], + startTiles: {}, + phaseEndStep: v.phaseEndStep, + solo: v.solo ? { ...v.solo } : null, + out: { tiles: 0, goods: 0 }, + turnSeq: v.turnSeq, + deadlineAt: null, + deadlineMs: 0, + seq: v.seq, + log: [], + endReason: v.endReason, + final: null, + }; +} + +function validate(s: CobState, actor: PlayerId, a: CobAction) { + const e = actionError(s, actor, a); + return e ? fail(e) : ok; +} + +export function applyAction(s0: CobState, actor: PlayerId, a: CobAction, ctx: Ctx): { state: CobState; events: GameEvent[] } { + const s = structuredClone(s0); + s.seq++; + const before = s.log.length ? s.log[s.log.length - 1]!.seq : -1; + perform(s, actor, a, ctx); + const events: GameEvent[] = s.log.filter((e) => e.seq > before).map(({ t, ...rest }) => ({ ...rest, type: t })); + return { state: s, events }; +} + +function rank(s: CobState): FinalRow[][] { + const rows = s.final ?? s.seats.map((p) => finalRow(s, p)); + const order = s.roundOrder.length ? s.roundOrder : s.seats; + const back = (p: PlayerId) => order.indexOf(p); + const sorted = [...rows].sort( + (a, b) => Number(a.conceded) - Number(b.conceded) || b.total - a.total || (a.conceded ? 0 : b.emptySpaces - a.emptySpaces || back(b.player) - back(a.player)), + ); + const groups: FinalRow[][] = []; + for (const r of sorted) { + const g = groups[groups.length - 1]; + const prev = g?.[0]; + const tied = prev && prev.conceded === r.conceded && prev.total === r.total && (r.conceded || (prev.emptySpaces === r.emptySpaces && back(prev.player) === back(r.player))); + if (tied) g!.push(r); + else groups.push([r]); + } + return groups; +} + +function result(s: CobState): GameResult | null { + if (s.stage !== 'finished' || !s.final) return null; + const scores: Record = {}; + const scoreText: Record = {}; + for (const r of s.final) { + scores[r.player] = r.total; + scoreText[r.player] = `${r.total}점`; + } + if (s.options.mode === 'solo') { + const r = s.final[0]!; + const won = s.endReason === 'soloWin'; + scoreText[r.player] = won ? '성공' : `실패(빈칸 ${r.emptySpaces})`; + return { + ranking: [[r.player]], + scores, + scoreText, + summary: won ? '공국 37칸을 모두 채워 성공했어요!' : `공국을 다 채우지 못했어요(빈칸 ${r.emptySpaces}칸).`, + reason: s.players[r.player]!.conceded ? 'resign' : 'normal', + }; + } + const groups = rank(s); + const top = groups[0]!; + let summary = top.length > 1 ? `공동 1위 ${top.length}명, ${top[0]!.total}점` : `1위 ${top[0]!.total}점`; + if (groups[1] && top.length === 1 && groups[1][0]!.total === top[0]!.total) summary += ` (같은 점수 — ${groups[1][0]!.emptySpaces !== top[0]!.emptySpaces ? '빈칸이 더 많아서' : '차례 트랙이 더 뒤여서'} 앞섬)`; + else if (groups[1]) summary += ` · 2위 ${groups[1][0]!.total}점`; + if (s.endReason === 'resign') summary = `다른 사람이 모두 기권했어요. ${summary}`; + return { ranking: groups.map((g) => g.map((r) => r.player)), scores, scoreText, summary, reason: s.endReason === 'resign' ? 'resign' : 'normal' }; +} + +/** Secrets: tile ids still in the face-down piles. */ +function secretsOf(s: CobState): string[] { + return PILE_KEYS.flatMap((k) => s.piles[k]); +} + +export function setupCob(ctx: { players: PlayerId[]; options: CobOptions; rng: Rng; now: number }): CobState { + return setupState(ctx.players, ctx.options, ctx.rng, ctx.now); +} + +type Def = GameDefinition; + +export const castlesOfBurgundy: Def = { + id: 'castles-of-burgundy', + nameKo: '버건디의 성', + minPlayers: 1, + maxPlayers: 4, + stateVersion: 1, + defaultOptions: cobOptionsSchema.parse({}), + optionsSchema: cobOptionsSchema, + actionSchema: cobActionSchema as unknown as Def['actionSchema'], + playersFor: (o) => (o.mode === 'solo' ? { min: 1, max: 1 } : { min: 2, max: 4 }), + setup: ({ players, options, rng, now }) => setupCob({ players, options, rng, now }), + validate, + apply: (s, actor, a, ctx) => applyAction(s, actor, a, ctx), + view, + activePlayers: (s) => waitingOn(s), + deadline: (s) => s.deadlineAt, + timeoutPlayers: (s) => waitingOn(s), + onTimeout: () => ({ type: 'timeout' }), + onLeave: (s, p) => (s.stage === 'finished' || !s.players[p] || s.players[p]!.conceded ? null : { type: 'leave' }), + result, + legalActions: (s, p) => legalMoves(s, p).map((m) => m.a), + secretsOf, +}; diff --git a/packages/games/src/castles-of-burgundy/moves.ts b/packages/games/src/castles-of-burgundy/moves.ts new file mode 100644 index 0000000..29e120b --- /dev/null +++ b/packages/games/src/castles-of-burgundy/moves.ts @@ -0,0 +1,172 @@ +/** 버건디의 성 legal-move generator: candidates filtered by `actionError` (one source of truth). */ +import type { PlayerId } from '@bg/engine'; +import { BUILDINGS, tileDef, type Color, type Die } from './data'; +import { + actionError, + buyChoices, + dieActCheck, + duchyOf, + findTile, + has, + myCastles, + pendingActor, + placeSpaces, + shieldsOn, + shipChoices, + storageFull, + waitingOn, +} from './engine'; +import type { CobAction, CobState, DieAct } from './types'; + +export interface Move { + a: CobAction; + /** Workers this move spends. */ + cost: number; +} + +/** Die acts for a die showing `face` (null = castle bonus), with their worker cost. */ +function dieActs(s: CobState, p: PlayerId, face: Die | null, compact: boolean, bonusShield: boolean): { act: DieAct; cost: number }[] { + const pl = s.players[p]!; + const out: { act: DieAct; cost: number }[] = []; + const full = storageFull(s, p); + const discards = !full ? [undefined] : compact ? [undefined] : pl.storage.map((_, i) => i); + const push = (act: DieAct) => { + if (compact && act.kind === 'take' && full) { + // compact form: report without the discard index; the cost doesn't depend on it. + const c = dieActCheck(s, p, { ...act, discard: 0 }, face, bonusShield ? { kind: 'bonus', source: 'castle' } : null); + if (!c.err) out.push({ act, cost: c.cost }); + return; + } + const c = dieActCheck(s, p, act, face, bonusShield ? { kind: 'bonus', source: 'castle' } : null); + if (!c.err) out.push({ act, cost: c.cost }); + }; + for (let d = 0; d < 6; d++) + for (const tile of s.depots[d]!.slots) if (tile) for (const discard of discards) push(discard === undefined ? { kind: 'take', tile } : { kind: 'take', tile, discard }); + const seen = new Set(); + pl.storage.forEach((tile, slot) => { + const key = pl.facedown.includes(tile) ? `fd${slot}` : tile.replace(/-\d+$/, ''); + if (seen.has(key)) return; // identical tiles (e.g. two ships): one slot is enough + seen.add(key); + for (const space of placeSpaces(s, p, tile)) push({ kind: 'place', slot, space }); + }); + for (const g of pl.goods) push({ kind: 'sell', goods: g.die }); + push({ kind: 'workers' }); + if (bonusShield) { + for (let d = 1; d <= 6; d++) for (const shield of s.depots[d - 1]!.shields) for (const space of myCastles(s, p)) push({ kind: 'shield', depot: d, shield, space }); + } + return out; +} + +function buyMoves(s: CobState, p: PlayerId, compact: boolean): Move[] { + const out: Move[] = []; + const full = storageFull(s, p); + const n = s.players[p]!.storage.length; + for (const b of buyChoices(s, p)) { + if (!full || compact) out.push({ a: { type: 'buy', tile: b.tile, pay: b.pay }, cost: b.pay === 'workers' ? 2 : 0 }); + else for (let i = 0; i < n; i++) out.push({ a: { type: 'buy', tile: b.tile, pay: b.pay, discard: i }, cost: b.pay === 'workers' ? 2 : 0 }); + } + return out; +} + +function subsets(xs: T[]): T[][] { + return xs.reduce((acc, x) => [...acc, ...acc.map((a) => [...a, x])], [[]]); +} + +/** Every legal action of `p` now. `compact` leaves out the discard variants (the screen asks separately). */ +export function legalMoves(s: CobState, p: PlayerId, compact = false): Move[] { + if (!waitingOn(s).includes(p) || s.players[p]?.conceded) return []; + const pl = s.players[p]!; + const raw: Move[] = []; + const add = (a: CobAction, cost = 0) => raw.push({ a, cost }); + if (s.stage === 'castle') { + for (const space of duchyOf(s, p).castleSpaces) add({ type: 'chooseCastle', space }); + } else if (s.stage === 'phaseEnd') { + const t = s.pending[s.pending.length - 1]; + if (t?.kind === 'upkeep' && pendingActor(s) === p) for (const keep of subsets(Object.values(pl.shields).sort((a, b) => a - b))) add({ type: 'upkeep', keep }); + if (t?.kind === 'phasePlace' && pendingActor(s) === p) { + add({ type: 'phasePlace', skip: true }); + const src = t.from === 'black' ? s.black : s.depots.flatMap((d) => d.slots); + for (const tile of src) if (tile) for (const space of placeSpaces(s, p, tile)) add({ type: 'phasePlace', tile, space }); + } + } else { + const t = s.pending[s.pending.length - 1]; + const extras = () => { + raw.push(...buyMoves(s, p, compact)); + if (has(s, p, 28)) add({ type: 'buyWorkers' }); + if (s.solo?.canBuy) add({ type: 'soloBuyVp' }); + }; + if (t) { + const full = storageFull(s, p); + const discards = full && !compact ? pl.storage.map((_, i) => i) : [undefined]; + switch (t.kind) { + case 'bonus': + for (const { act } of dieActs(s, p, null, compact, t.source === 'castle' && shieldsOn(s))) add({ type: 'bonus', act }); + extras(); + break; + case 'ship': + for (const c of shipChoices(s, p)) add({ type: 'ship', ...c } as CobAction); + break; + case 'depotTake': + add({ type: 'depotTake', skip: true }); + for (const d of s.depots) + for (const tile of d.slots) + if (tile && t.colors.includes(tileDef(tile).color as Color)) for (const discard of discards) add(discard === undefined ? { type: 'depotTake', tile } : { type: 'depotTake', tile, discard }); + break; + case 'warehouse': + add({ type: 'warehouse', skip: true }); + for (const g of pl.goods) add({ type: 'warehouse', goods: g.die }); + break; + case 'townhall': + add({ type: 'townhall', skip: true }); + pl.storage.forEach((tile, slot) => { + for (const space of placeSpaces(s, p, tile)) add({ type: 'townhall', slot, space }); + }); + break; + case 'crane': + for (const building of BUILDINGS) add({ type: 'crane', building }); + break; + case 'geese': { + add({ type: 'geese', animal: null }); + for (const animal of ['chicken', 'sheep', 'pig', 'cow'] as const) add({ type: 'geese', animal }); + break; + } + case 'shieldCopy': + for (const q of s.seats) if (q !== p) add({ type: 'shieldCopy', player: q }); + break; + case 'soloTrade': + add({ type: 'soloTrade', skip: true }); + for (const tile of s.black) if (tile) for (const discard of discards) add(discard === undefined ? { type: 'soloTrade', tile } : { type: 'soloTrade', tile, discard }); + break; + case 'soloBlack': + add({ type: 'soloBlack', skip: true }); + for (const tile of s.black) if (tile) for (const space of placeSpaces(s, p, tile)) add({ type: 'soloBlack', tile, space }); + break; + default: + break; + } + } else { + const same = !pl.used[0] && !pl.used[1] && pl.dice[0] === pl.dice[1]; + for (const i of [0, 1] as const) { + if (pl.used[i] || (same && i === 1 && !compact)) continue; + for (const { act, cost } of dieActs(s, p, pl.dice[i], compact, false)) add({ type: 'useDie', die: i, act }, cost); + } + if (shieldsOn(s) && !pl.used[0] && !pl.used[1]) { + for (let d = 1; d <= 6; d++) for (const shield of s.depots[d - 1]!.shields) for (const space of myCastles(s, p)) add({ type: 'takeShield', depot: d, shield, space }); + } + extras(); + add({ type: 'endTurn' }); + } + } + if (compact) return raw.filter((m) => !actionError(s, p, withDiscard(s, p, m.a))); + return raw.filter((m) => !actionError(s, p, m.a)); +} + +/** For checking compact moves: add a discard index when storage is full. */ +function withDiscard(s: CobState, p: PlayerId, a: CobAction): CobAction { + if (!storageFull(s, p)) return a; + if (a.type === 'buy' || a.type === 'depotTake' || a.type === 'soloTrade') return 'tile' in a ? { ...a, discard: 0 } : a; + if ((a.type === 'useDie' || a.type === 'bonus') && a.act.kind === 'take') return { ...a, act: { ...a.act, discard: 0 } }; + return a; +} + +export { findTile }; diff --git a/packages/games/src/castles-of-burgundy/options.ts b/packages/games/src/castles-of-burgundy/options.ts new file mode 100644 index 0000000..2b57aaf --- /dev/null +++ b/packages/games/src/castles-of-burgundy/options.ts @@ -0,0 +1,35 @@ +/** + * 버건디의 성 options (docs/games/castles-of-burgundy.md §2). 2019 rules by default; the expansions whose data is + * fully known are room settings. Not yet: team play, duchies 2~10, white castles, trade routes, border posts (data). + */ +import { z } from 'zod'; + +const lit = (...vals: T[]) => + z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral, z.ZodLiteral, ...z.ZodLiteral[]]); + +export const cobOptionsSchema = z.object({ + mode: z + .enum(['standard', 'solo']) + .default('standard') + .meta({ title: '게임 방식', labels: { standard: '개인전(2~4명)', solo: '혼자 하기(1명, 1번 공국)' } }), + castleStart: z + .enum(['center', 'choose']) + .default('center') + .meta({ title: '시작 성 위치', labels: { center: '가운데 6번 칸(기본)', choose: '성 칸 중 골라 놓기(숙련자)' } }), + monasteryRules: z + .enum(['2019', '2011']) + .default('2019') + .meta({ title: '수도원 수치', labels: { '2019': '2019년판(기본)', '2011': '2011년판(옛 판)' } }), + extraTiles: z.boolean().default(false).meta({ title: '추가 타일 4장(다리·일꾼 사기·기중기·거위)', labels: { true: '넣기', false: '빼기' } }), + inns: z.boolean().default(false).meta({ title: '여관(구역 크기 +1)', labels: { true: '넣기', false: '빼기' } }), + shields: z.boolean().default(false).meta({ title: '방패(더블로 가져오기)', labels: { true: '넣기', false: '빼기' } }), + soloTarget: lit(45, 48, 50, 52, 55) + .default(50) + .meta({ title: '혼자 하기 목표 점수(낮을수록 쉬움)', labels: { 45: '45점', 48: '48점', 50: '50점(기본)', 52: '52점', 55: '55점' } }), + turnSeconds: lit(60, 90, 120, 180, null) + .default(120) + .meta({ title: '한 차례 제한 시간', labels: { 60: '60초', 90: '90초', 120: '120초', 180: '180초', null: '무제한' } }), + showHints: z.boolean().default(true).meta({ title: '도움 표시(일꾼 수·남은 칸)', labels: { true: '켜기', false: '끄기' } }), +}); + +export type CobOptions = z.infer; diff --git a/packages/games/src/castles-of-burgundy/types.ts b/packages/games/src/castles-of-burgundy/types.ts new file mode 100644 index 0000000..449e2bd --- /dev/null +++ b/packages/games/src/castles-of-burgundy/types.ts @@ -0,0 +1,243 @@ +/** 버건디의 성 types: actions, state, view (docs/games/castles-of-burgundy.md §8). */ +import { z } from 'zod'; +import type { PlayerId } from '@bg/engine'; +import type { BuildingKind, Color, Die, PileKey } from './data'; +import type { CobOptions } from './options'; + +export { cobOptionsSchema, type CobOptions } from './options'; + +// ---------------------------------------------------------------- actions + +const die = z.number().int().min(1).max(6); +const idx = z.number().int().min(0).max(60); +const space = z.number().int().min(0).max(36); +const tile = z.string().min(1).max(40); + +/** What one die (or a castle's bonus action) does. The die value is implied: depot / space / goods number. */ +export const dieActSchema = z.union([ + z.object({ kind: z.literal('take'), tile, discard: idx.optional() }), + z.object({ kind: z.literal('place'), slot: idx, space }), + z.object({ kind: z.literal('sell'), goods: die }), + z.object({ kind: z.literal('workers') }), + /** Only as a castle bonus with shield 11. */ + z.object({ kind: z.literal('shield'), depot: die, shield: z.number().int().min(1).max(18), space }), +]); +export type DieAct = z.infer; + +export const cobActionSchema = z.union([ + z.object({ type: z.literal('chooseCastle'), space }), + z.object({ type: z.literal('useDie'), die: z.union([z.literal(0), z.literal(1)]), act: dieActSchema }), + z.object({ type: z.literal('bonus'), act: dieActSchema }), + z.object({ type: z.literal('buy'), tile, pay: z.enum(['silver', 'workers']), discard: idx.optional() }), + z.object({ type: z.literal('ship'), depot: die, adjacent: die.optional(), extra: die.optional(), keep: z.array(die).max(6).optional() }), + z.object({ type: z.literal('depotTake'), tile, discard: idx.optional() }).or(z.object({ type: z.literal('depotTake'), skip: z.literal(true) })), + z.object({ type: z.literal('warehouse'), goods: die }).or(z.object({ type: z.literal('warehouse'), skip: z.literal(true) })), + z.object({ type: z.literal('townhall'), slot: idx, space }).or(z.object({ type: z.literal('townhall'), skip: z.literal(true) })), + z.object({ type: z.literal('crane'), building: z.enum(['warehouse', 'carpenter', 'church', 'market', 'boarding', 'bank', 'townhall', 'watchtower']) }), + z.object({ type: z.literal('geese'), animal: z.enum(['chicken', 'sheep', 'pig', 'cow']).nullable() }), + z.object({ type: z.literal('takeShield'), depot: die, shield: z.number().int().min(1).max(18), space }), + z.object({ type: z.literal('shieldCopy'), player: z.string().min(1).max(80) }), + z.object({ type: z.literal('upkeep'), keep: z.array(z.number().int().min(1).max(18)).max(8) }), + z.object({ type: z.literal('phasePlace'), tile, space }).or(z.object({ type: z.literal('phasePlace'), skip: z.literal(true) })), + z.object({ type: z.literal('soloTrade'), tile, discard: idx.optional() }).or(z.object({ type: z.literal('soloTrade'), skip: z.literal(true) })), + z.object({ type: z.literal('soloBlack'), tile, space }).or(z.object({ type: z.literal('soloBlack'), skip: z.literal(true) })), + z.object({ type: z.literal('soloBuyVp') }), + z.object({ type: z.literal('buyWorkers') }), + z.object({ type: z.literal('endTurn') }), + z.object({ type: z.literal('concede') }), +]); + +export type CobClientAction = z.infer; +/** Client actions plus system-only ones (turn clock, leaving the room). */ +export type CobAction = CobClientAction | { type: 'timeout' } | { type: 'leave' }; + +// ---------------------------------------------------------------- state + +export type Pending = + | { kind: 'bonus'; source: 'castle' | 'solo' } + | { kind: 'ship' } + | { kind: 'depotTake'; colors: Color[]; source: 'market' | 'carpenter' | 'church' } + | { kind: 'warehouse' } + | { kind: 'townhall' } + | { kind: 'crane' } + | { kind: 'geese'; region: number } + | { kind: 'shieldCopy' } + | { kind: 'upkeep'; player: PlayerId } + | { kind: 'phasePlace'; player: PlayerId; from: 'depot' | 'black' } + | { kind: 'soloTrade' } + | { kind: 'soloBlack' }; + +export interface Goods { + die: Die; + count: number; +} + +export interface CobPlayer { + /** Space id → tile id. */ + placed: Record; + /** Space of the start castle (−1 until chosen). */ + start: number; + /** Tiles in the storage spaces (3, or unlimited with shield 4). */ + storage: string[]; + /** Solo: tiles taken face down (any colour, no effect). */ + facedown: string[]; + goods: Goods[]; + /** Goods sold per kind (index = die − 1). Others only see the total. */ + sold: number[]; + silver: number; + workers: number; + vp: number; + dice: [Die, Die]; + used: [boolean, boolean]; + bought: boolean; + /** Shield 16 used this turn. */ + free16: boolean; + bonus: { color: Color; size: 'large' | 'small' }[]; + /** Castle space id → shield number. */ + shields: Record; + /** Shield 6: whose monasteries I also use. */ + copyFrom: PlayerId | null; + track: { pos: number; height: number }; + conceded: boolean; + /** Turns played by the clock in a row (자리 비움 after 3). */ + autoStreak: number; +} + +export type LogEntry = + | { seq: number; t: 'phase'; phase: number } + | { seq: number; t: 'round'; round: number; white: Die; goods: Die | null; depot: number } + | { seq: number; t: 'take'; p: PlayerId; tile: string; depot: number | 'black' | 'inn' } + | { seq: number; t: 'buy'; p: PlayerId; tile: string; from: number | 'black' | 'inn' } + | { seq: number; t: 'place'; p: PlayerId; tile: string; space: number } + | { seq: number; t: 'region'; p: PlayerId; space: number; size: number; vp: number } + | { seq: number; t: 'colorBonus'; p: PlayerId; color: Color; size: 'large' | 'small'; vp: number } + | { seq: number; t: 'livestock'; p: PlayerId; vp: number } + | { seq: number; t: 'sell'; p: PlayerId; goods: Die; count: number; vp: number; silver: number } + | { seq: number; t: 'workers'; p: PlayerId; n: number } + | { seq: number; t: 'ship'; p: PlayerId; depots: number[]; goods: Die[] } + | { seq: number; t: 'building'; p: PlayerId; building: BuildingKind } + | { seq: number; t: 'shield'; p: PlayerId; shield: number } + | { seq: number; t: 'shieldLost'; p: PlayerId; shield: number } + | { seq: number; t: 'income'; p: PlayerId; silver: number; workers: number } + | { seq: number; t: 'discard'; p: PlayerId; tile: string } + | { seq: number; t: 'soloRemove'; tile: string; depot: number } + | { seq: number; t: 'soloTarget'; target: number } + | { seq: number; t: 'auto'; p: PlayerId } + | { seq: number; t: 'concede'; p: PlayerId } + | { seq: number; t: 'end' }; + +export interface Depot { + slots: (string | null)[]; + colors: Color[]; + goods: Die[]; + shields: number[]; +} + +export interface FinalRow { + player: PlayerId; + inGame: number; + goodsLeft: number; + silver: number; + workers: number; + monasteries: { id: string; vp: number }[]; + shields: number; + total: number; + emptySpaces: number; + conceded: boolean; +} + +export interface CobState { + options: CobOptions; + seats: PlayerId[]; + phase: number; + round: number; + stage: 'castle' | 'turn' | 'phaseEnd' | 'finished'; + roundOrder: PlayerId[]; + turnIndex: number; + current: PlayerId | null; + whiteDie: Die; + /** Index 0 = depot 1. */ + depots: Depot[]; + black: (string | null)[]; + /** Inn stack, last = top. */ + inns: string[]; + roundGoods: Die[]; + /** Secret: goods stacks of the coming phases. */ + phaseGoods: Die[][]; + /** Secret: face-down hex piles. */ + piles: Record; + bonusLeft: Record; + players: Record; + pending: Pending[]; + /** Castle choice order (`castleStart='choose'` / solo). */ + castleQueue: PlayerId[]; + /** Each player's start castle tile. */ + startTiles: Record; + phaseEndStep: 'upkeep' | 'income' | 'place' | null; + solo: { target: number; canBuy: boolean } | null; + /** Removed from the game (invariants). */ + out: { tiles: number; goods: number }; + turnSeq: number; + deadlineAt: number | null; + deadlineMs: number; + seq: number; + log: LogEntry[]; + endReason: 'normal' | 'resign' | 'soloWin' | 'soloLose' | null; + final: FinalRow[] | null; +} + +// ---------------------------------------------------------------- view + +export interface CobPlayerView extends Omit { + id: PlayerId; + /** Kinds sold: only for myself (others: null). */ + sold: number[] | null; + soldCount: number; + emptySpaces: number; + away: boolean; +} + +export interface CobMyView { + /** Legal moves for my current decision, without the discard variants (`needDiscard`). */ + moves: CobAction[]; + /** Storage is full: a take/buy needs a `discard` index. */ + needDiscard: boolean; + /** Worker cost of each `useDie` move (same order as `moves`, 0 for others). */ + costs: number[]; + /** Estimated final score now (showHints). */ + projected: number | null; +} + +export interface CobView { + options: CobOptions; + me: PlayerId | null; + seats: PlayerId[]; + phase: number; + round: number; + stage: CobState['stage']; + roundOrder: PlayerId[]; + turnIndex: number; + current: PlayerId | null; + whiteDie: Die; + depots: Depot[]; + black: (string | null)[]; + inns: string[]; + roundGoods: Die[]; + pilesLeft: Record; + bonusLeft: CobState['bonusLeft']; + players: Record; + pending: Pending[]; + castleQueue: PlayerId[]; + phaseEndStep: CobState['phaseEndStep']; + solo: CobState['solo']; + turnSeq: number; + deadlineAt: number | null; + deadlineMs: number; + seq: number; + log: LogEntry[]; + endReason: CobState['endReason']; + final: FinalRow[] | null; + /** Whose decision it is now (turn player, or the upkeep / castle chooser). */ + waiting: PlayerId[]; + my: CobMyView | null; +} diff --git a/packages/games/src/index.ts b/packages/games/src/index.ts index e40af82..fbf357a 100644 --- a/packages/games/src/index.ts +++ b/packages/games/src/index.ts @@ -33,6 +33,7 @@ import { uno } from './uno'; import { liar } from './liar'; import { magicalAthlete } from './magical-athlete'; import { blackjack } from './blackjack'; +import { castlesOfBurgundy } from './castles-of-burgundy'; export const GAMES: Record = { [omok.id]: omok, @@ -69,4 +70,5 @@ export const GAMES: Record = { [liar.id]: liar, [magicalAthlete.id]: magicalAthlete, [blackjack.id]: blackjack, + [castlesOfBurgundy.id]: castlesOfBurgundy, }; diff --git a/packages/shared/src/bots.ts b/packages/shared/src/bots.ts index 134d6f7..f89e4b1 100644 --- a/packages/shared/src/bots.ts +++ b/packages/shared/src/bots.ts @@ -59,6 +59,7 @@ export const BOT_GAMES: readonly string[] = [ 'liar', 'magical-athlete', 'blackjack', + 'castles-of-burgundy', ]; /** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */ diff --git a/packages/shared/src/catalog.ts b/packages/shared/src/catalog.ts index b95f2ac..f043915 100644 --- a/packages/shared/src/catalog.ts +++ b/packages/shared/src/catalog.ts @@ -45,6 +45,7 @@ export const CATALOG: CatalogEntry[] = [ { id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true }, { id: 'liar', nameKo: '라이어 게임', minPlayers: 3, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '모두 같은 제시어를 받았는데 한 명만 몰라요! 한 문장씩 설명하며 라이어를 찾아요 · 채팅 추리', available: true }, { id: 'blackjack', nameKo: '블랙잭', minPlayers: 1, maxPlayers: 7, minutes: '10~20', level: '쉬움', blurb: '딜러를 상대로 21에 가깝게! 공식 규칙 + 5카드 찰리·7트리플 하우스 룰 · 놀이용 칩 · 혼자서도 OK', available: true }, + { id: 'castles-of-burgundy', nameKo: '버건디의 성', minPlayers: 1, maxPlayers: 4, minutes: '60~120', level: '어려움', blurb: '주사위 두 개로 육각 타일을 가져와 내 공국을 채워요! 성·배·건물·가축·광산·수도원 · 혼자 하기도 OK', available: true }, ]; export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);