Merge branch 'wip/game-castles-of-burgundy' into codex/owner/grp_discord_joke-app
# Conflicts: # apps/web/src/games/help.test.ts # apps/web/src/games/registry.ts # apps/web/src/lib/catalog-ui.ts # docs/games/README.md # e2e/games.e2e.ts # packages/games/package.json # packages/games/src/bots/index.ts # packages/games/src/index.ts # packages/shared/src/bots.ts # packages/shared/src/catalog.ts
This commit is contained in:
91
apps/server/src/rooms/castles-of-burgundy.room.test.ts
Normal file
91
apps/server/src/rooms/castles-of-burgundy.room.test.ts
Normal file
@@ -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<ServerMessage, { t: 'state' }>;
|
||||
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);
|
||||
});
|
||||
59
apps/web/src/games/castles-of-burgundy/help.ts
Normal file
59
apps/web/src/games/castles-of-burgundy/help.ts
Normal file
@@ -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, PublicUser>): 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<string, string> = {
|
||||
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');
|
||||
}
|
||||
158
apps/web/src/games/castles-of-burgundy/hex.tsx
Normal file
158
apps/web/src/games/castles-of-burgundy/hex.tsx
Normal file
@@ -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<Color | 'inn' | 'any', string> = {
|
||||
castle: '#2f6b3a',
|
||||
mine: '#7c828c',
|
||||
monastery: '#e2b93b',
|
||||
building: '#d6b383',
|
||||
livestock: '#8cc152',
|
||||
ship: '#3f86d1',
|
||||
inn: '#b45309',
|
||||
any: '#4b5563',
|
||||
};
|
||||
export const SPACE: Record<Color, string> = {
|
||||
castle: '#9cc7a3',
|
||||
mine: '#c9ccd1',
|
||||
monastery: '#f4e2a6',
|
||||
building: '#efdfc6',
|
||||
livestock: '#cfe8b4',
|
||||
ship: '#b7d3f1',
|
||||
};
|
||||
export const INK: Record<Color | 'inn' | 'any', string> = {
|
||||
castle: '#ffffff',
|
||||
mine: '#ffffff',
|
||||
monastery: '#3b2a00',
|
||||
building: '#3b2a00',
|
||||
livestock: '#1f3a0a',
|
||||
ship: '#ffffff',
|
||||
inn: '#ffffff',
|
||||
any: '#ffffff',
|
||||
};
|
||||
export const GOODS_FILL: Record<Die, string> = { 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 (
|
||||
<g opacity={dim ? 0.45 : 1}>
|
||||
<polygon points={hexPoints(cx, cy, r)} fill={FILL[c]} stroke="rgba(0,0,0,.45)" strokeWidth={Math.max(1, r * 0.06)} />
|
||||
<polygon points={hexPoints(cx, cy, r * 0.8)} fill="none" stroke="rgba(255,255,255,.35)" strokeWidth={Math.max(0.6, r * 0.04)} />
|
||||
<text x={cx} y={text ? cy - r * 0.08 : cy + r * 0.12} textAnchor="middle" fontSize={r * (text ? 0.62 : 0.8)} dominantBaseline="middle">
|
||||
{icon}
|
||||
</text>
|
||||
{text && (
|
||||
<text x={cx} y={cy + r * 0.52} textAnchor="middle" fontSize={r * (text.length > 2 ? 0.34 : 0.42)} fontWeight={800} fill={INK[c]} dominantBaseline="middle">
|
||||
{text}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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<number, [number, number][]> = {
|
||||
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 (
|
||||
<g>
|
||||
{(at[n] ?? []).map(([dx, dy], i) => (
|
||||
<circle key={i} cx={cx + dx} cy={cy + dy} r={s * 0.09} fill={color} />
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
export function DieFace({ n, size = 40, white, used, label }: { n: number; size?: number; white?: boolean; used?: boolean; label?: string }) {
|
||||
return (
|
||||
<svg width={size} height={size} viewBox="0 0 40 40" role="img" aria-label={label ?? `주사위 ${n}`} style={{ display: 'block', opacity: used ? 0.35 : 1 }}>
|
||||
<rect x={2} y={2} width={36} height={36} rx={8} fill={white ? '#ffffff' : '#fde68a'} stroke="#1c1e21" strokeWidth={2} />
|
||||
<Pips n={n} cx={20} cy={20} s={36} />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
1350
apps/web/src/games/castles-of-burgundy/index.tsx
Normal file
1350
apps/web/src/games/castles-of-burgundy/index.tsx
Normal file
File diff suppressed because it is too large
Load Diff
75
apps/web/src/games/castles-of-burgundy/quick.tsx
Normal file
75
apps/web/src/games/castles-of-burgundy/quick.tsx
Normal file
@@ -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: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<foreignObject x={10} y={36} width={44} height={44}>
|
||||
<DieFace n={4} size={44} />
|
||||
</foreignObject>
|
||||
<text x={70} y={64} fontSize={22} fontWeight={900}>
|
||||
=
|
||||
</text>
|
||||
<rect x={92} y={30} width={62} height={56} rx={8} fill="#efece4" stroke="#9ca3af" />
|
||||
<text x={123} y={48} textAnchor="middle" fontSize={12} fontWeight={800}>
|
||||
4번 보급소
|
||||
</text>
|
||||
<TileHex id="S-01" cx={123} cy={70} r={14} />
|
||||
<text x={170} y={64} fontSize={22} fontWeight={900}>
|
||||
=
|
||||
</text>
|
||||
<polygon points={hexPoints(215, 58, 24)} fill={SPACE.ship} stroke="#334155" strokeWidth={2} />
|
||||
<text x={215} y={64} textAnchor="middle" fontSize={20} fontWeight={900}>
|
||||
4
|
||||
</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '주사위 4는 4번 보급소와 공국의 숫자 4 칸을 뜻해요',
|
||||
title: '주사위 눈 = 번호',
|
||||
text: '라운드마다 주사위 2개를 하나씩 써요. 눈과 같은 번호 보급소에서 타일을 가져오고, 같은 숫자 칸에 놓아요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<polygon points={hexPoints(70, 60, 26)} fill={FILL.castle} stroke="#1f2937" strokeWidth={2} />
|
||||
<text x={70} y={66} textAnchor="middle" fontSize={20}>
|
||||
🏰
|
||||
</text>
|
||||
<TileHex id="B-market-1" cx={115} cy={34} r={25} />
|
||||
<polygon points={hexPoints(115, 86, 25)} fill={SPACE.ship} stroke="#2563eb" strokeWidth={3} strokeDasharray="4 3" />
|
||||
<text x={115} y={92} textAnchor="middle" fontSize={18} fontWeight={900}>
|
||||
5
|
||||
</text>
|
||||
<text x={150} y={64} fontSize={13} fontWeight={800} fill="#15803d">
|
||||
같은 색·숫자,
|
||||
</text>
|
||||
<text x={150} y={82} fontSize={13} fontWeight={800} fill="#15803d">
|
||||
맞닿게 놓기
|
||||
</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '성 옆에 시장 타일이 있고, 맞닿은 파란 5번 칸이 빛나요',
|
||||
title: '공국에 맞닿게 놓기',
|
||||
text: '보관 칸 타일을 같은 색·같은 숫자 빈칸에, 이미 놓인 타일과 맞닿게 놓아요. 색마다 효과가 달라요.',
|
||||
},
|
||||
{
|
||||
pic: (
|
||||
<svg viewBox="0 0 250 120" width={250} height={120} aria-hidden>
|
||||
<TileHex id="M-01" cx={40} cy={50} r={24} />
|
||||
<TileHex id="M-02" cx={82} cy={50} r={24} />
|
||||
<TileHex id="M-03" cx={61} cy={86} r={24} />
|
||||
<text x={115} y={58} fontSize={18} fontWeight={900} fill="#15803d">
|
||||
구역 완성!
|
||||
</text>
|
||||
<text x={115} y={84} fontSize={14} fontWeight={800}>
|
||||
3칸 6점 + A 페이즈 10점
|
||||
</text>
|
||||
</svg>
|
||||
),
|
||||
alt: '광산 3칸 구역을 다 채워 점수를 얻어요',
|
||||
title: '구역을 채워 점수',
|
||||
text: '같은 색 구역을 다 채우면 크기 점수와 페이즈 점수(이를수록 큼)를 받아요. 한 색을 전부 채우면 보너스!',
|
||||
},
|
||||
];
|
||||
@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
|
||||
const IDS = Object.keys(GAME_UI);
|
||||
|
||||
test('모든 게임에 도움말이 있어요', () => {
|
||||
expect(IDS).toHaveLength(39);
|
||||
expect(IDS).toHaveLength(40);
|
||||
for (const id of IDS) {
|
||||
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
|
||||
expect(src, id).toMatch(/\bquickStart,/);
|
||||
|
||||
@@ -41,6 +41,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
|
||||
'hot-streak': () => import('./hot-streak'),
|
||||
tichu: () => import('./tichu'),
|
||||
'case-file': () => import('./case-file'),
|
||||
'castles-of-burgundy': () => import('./castles-of-burgundy'),
|
||||
};
|
||||
|
||||
const cache = new Map<string, GameUI>();
|
||||
|
||||
@@ -38,6 +38,7 @@ export const GAME_ICON: Record<string, string> = {
|
||||
'hot-streak': '🏁',
|
||||
tichu: '🐉',
|
||||
'case-file': '🔍',
|
||||
'castles-of-burgundy': '🏰',
|
||||
};
|
||||
|
||||
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
|
||||
@@ -45,7 +46,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', 'gemblo'] },
|
||||
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue', 'gemblo', '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', 'six-nimmt', 'tichu'] },
|
||||
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple', 'hot-streak', 'case-file'] },
|
||||
];
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
| `hot-streak` | 핫스트릭 | 2~10 | 2026-10 새 게임 |
|
||||
| `tichu` | 티츄 | 4 (변형 3·6) | 2026-10 새 게임 |
|
||||
| `case-file` | 사건 파일 | 1~5 | 2026-10 새 게임 |
|
||||
| `castles-of-burgundy` | 버건디의 성 | 1~4 | 2026-10 새 게임 |
|
||||
|
||||
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
140
e2e/games.e2e.ts
140
e2e/games.e2e.ts
@@ -1298,6 +1298,83 @@ async function tichuStep(p: Page, isHost: boolean, st: Record<string, number>):
|
||||
return press(play, 'play');
|
||||
}
|
||||
if (await on(pass)) return press(pass, 'pass');
|
||||
/** 버건디의 성: one UI step for whoever must decide on page `p` (null = nothing to do here). */
|
||||
async function cobStep(p: Page, st: Record<string, number>): Promise<string | null> {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -3770,6 +3847,69 @@ const PLANS: Record<string, Plan> = {
|
||||
if ((st.play ?? 0) < 10 || !st.exchange || !st.grand || !st.tapped || !st.keys) throw new Error(`too few real steps: ${JSON.stringify(st)}`);
|
||||
await host.screenshot({ path: join(SHOTS, 'tichu-round2-pc.png') });
|
||||
console.log(` tichu: ${JSON.stringify(Object.fromEntries(Object.entries(st).filter(([k]) => !k.includes('shot'))))}`);
|
||||
'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<string, number> = {};
|
||||
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)}`);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"./hot-streak/cards": "./src/hot-streak/cards.ts",
|
||||
"./tichu/combo": "./src/tichu/combo.ts",
|
||||
"./case-file/types": "./src/case-file/types.ts",
|
||||
"./castles-of-burgundy/data": "./src/castles-of-burgundy/data.ts",
|
||||
"./*": "./src/*/index.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -42,6 +42,7 @@ import { sixNimmtBot } from '../six-nimmt/bot';
|
||||
import { gembloBot } from '../gemblo/bot';
|
||||
import { hotStreakBot } from '../hot-streak/bot';
|
||||
import { tichuBot } from '../tichu/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';
|
||||
@@ -81,6 +82,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
|
||||
gemblo: gembloBot,
|
||||
'hot-streak': hotStreakBot,
|
||||
tichu: tichuBot,
|
||||
'castles-of-burgundy': cobBot,
|
||||
};
|
||||
|
||||
/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */
|
||||
|
||||
40
packages/games/src/castles-of-burgundy/bot.test.ts
Normal file
40
packages/games/src/castles-of-burgundy/bot.test.ts
Normal file
@@ -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);
|
||||
});
|
||||
167
packages/games/src/castles-of-burgundy/bot.ts
Normal file
167
packages/games/src/castles-of-burgundy/bot.ts
Normal file
@@ -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: <T>(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<string, number> = { 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<PlayerId, Plan>();
|
||||
|
||||
export const cobBot: BotStrategy<CobView, CobAction> = ({ 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;
|
||||
};
|
||||
@@ -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<CobOptions> = {}, 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<number, string> }): 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<CobOptions>[] = [
|
||||
{},
|
||||
{ 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;
|
||||
341
packages/games/src/castles-of-burgundy/data.ts
Normal file
341
packages/games/src/castles-of-burgundy/data.ts
Normal file
@@ -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<BuildingKind, 'crane'>[] = ['warehouse', 'carpenter', 'church', 'market', 'boarding', 'bank', 'townhall', 'watchtower'];
|
||||
export type Animal = 'chicken' | 'sheep' | 'pig' | 'cow' | 'goose';
|
||||
export const ANIMALS: readonly Exclude<Animal, 'goose'>[] = ['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<BuildingKind, 'crane'>;
|
||||
/** Only in the `extraTiles` module. */
|
||||
extra?: boolean;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Korean names (screen)
|
||||
|
||||
export const COLOR_KO: Record<Color, string> = { castle: '성', mine: '광산', monastery: '수도원', building: '건물', livestock: '가축', ship: '배' };
|
||||
export const COLOR_ICON: Record<Color, string> = { castle: '🏰', mine: '⛏', monastery: '📜', building: '🏠', livestock: '🐄', ship: '⛵' };
|
||||
export const BUILDING_KO: Record<BuildingKind, string> = {
|
||||
warehouse: '창고',
|
||||
carpenter: '목공소',
|
||||
church: '교회',
|
||||
market: '시장',
|
||||
boarding: '하숙집',
|
||||
bank: '은행',
|
||||
townhall: '시청',
|
||||
watchtower: '망루',
|
||||
crane: '기중기',
|
||||
};
|
||||
export const BUILDING_EFFECT_KO: Record<BuildingKind, string> = {
|
||||
warehouse: '상품 한 종류를 주사위 없이 팔아요',
|
||||
carpenter: '보급소에서 건물 타일 1장을 가져와요',
|
||||
church: '보급소에서 광산·수도원·성 1장을 가져와요',
|
||||
market: '보급소에서 배·가축 1장을 가져와요',
|
||||
boarding: '일꾼 4개',
|
||||
bank: '은화 2개',
|
||||
townhall: '보관 칸의 타일 1장을 눈과 상관없이 놓아요',
|
||||
watchtower: '4점',
|
||||
crane: '아무 건물 효과 하나를 써요',
|
||||
};
|
||||
export const ANIMAL_KO: Record<Animal, string> = { chicken: '닭', sheep: '양', pig: '돼지', cow: '소', goose: '거위' };
|
||||
export const ANIMAL_ICON: Record<Animal, string> = { chicken: '🐔', sheep: '🐑', pig: '🐖', cow: '🐄', goose: '🪿' };
|
||||
/** Own names for the six goods (doc §3.3: any names). */
|
||||
export const GOODS_KO: Record<Die, string> = { 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-<building>` ids so only the displayed numbers depend on this.
|
||||
*/
|
||||
export const CRAFT_NUMBER: Record<Exclude<BuildingKind, 'crane'>, 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<number, number>> = {
|
||||
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<number, number> = { 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<string, TileDef> = 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<Color, number>;
|
||||
}
|
||||
|
||||
const LETTER: Record<string, Color> = { 목: '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<Color, number>;
|
||||
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<string, DuchyDef> = { '1': DUCHY_1 };
|
||||
1482
packages/games/src/castles-of-burgundy/engine.ts
Normal file
1482
packages/games/src/castles-of-burgundy/engine.ts
Normal file
File diff suppressed because it is too large
Load Diff
212
packages/games/src/castles-of-burgundy/index.ts
Normal file
212
packages/games/src/castles-of-burgundy/index.ts
Normal file
@@ -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<PileKey, number>;
|
||||
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<PlayerId, number> = {};
|
||||
const scoreText: Record<PlayerId, string> = {};
|
||||
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<CobState, CobAction, CobView, CobOptions>;
|
||||
|
||||
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,
|
||||
};
|
||||
172
packages/games/src/castles-of-burgundy/moves.ts
Normal file
172
packages/games/src/castles-of-burgundy/moves.ts
Normal file
@@ -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<string>();
|
||||
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<T>(xs: T[]): T[][] {
|
||||
return xs.reduce<T[][]>((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 };
|
||||
35
packages/games/src/castles-of-burgundy/options.ts
Normal file
35
packages/games/src/castles-of-burgundy/options.ts
Normal file
@@ -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 = <T extends number | null>(...vals: T[]) =>
|
||||
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
|
||||
|
||||
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<typeof cobOptionsSchema>;
|
||||
243
packages/games/src/castles-of-burgundy/types.ts
Normal file
243
packages/games/src/castles-of-burgundy/types.ts
Normal file
@@ -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<typeof dieActSchema>;
|
||||
|
||||
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<typeof cobActionSchema>;
|
||||
/** 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<string, string>;
|
||||
/** 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<string, number>;
|
||||
/** 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<PileKey, string[]>;
|
||||
bonusLeft: Record<Color, ('large' | 'small')[]>;
|
||||
players: Record<PlayerId, CobPlayer>;
|
||||
pending: Pending[];
|
||||
/** Castle choice order (`castleStart='choose'` / solo). */
|
||||
castleQueue: PlayerId[];
|
||||
/** Each player's start castle tile. */
|
||||
startTiles: Record<PlayerId, string>;
|
||||
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<CobPlayer, 'sold'> {
|
||||
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<PileKey, number>;
|
||||
bonusLeft: CobState['bonusLeft'];
|
||||
players: Record<PlayerId, CobPlayerView>;
|
||||
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;
|
||||
}
|
||||
@@ -38,6 +38,7 @@ import { gemblo } from './gemblo';
|
||||
import { hotStreak } from './hot-streak';
|
||||
import { tichu } from './tichu';
|
||||
import { caseFile } from './case-file';
|
||||
import { castlesOfBurgundy } from './castles-of-burgundy';
|
||||
|
||||
export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[omok.id]: omok,
|
||||
@@ -79,4 +80,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
|
||||
[hotStreak.id]: hotStreak,
|
||||
[tichu.id]: tichu,
|
||||
[caseFile.id]: caseFile,
|
||||
[castlesOfBurgundy.id]: castlesOfBurgundy,
|
||||
};
|
||||
|
||||
@@ -63,6 +63,7 @@ export const BOT_GAMES: readonly string[] = [
|
||||
'gemblo',
|
||||
'hot-streak',
|
||||
'tichu',
|
||||
'castles-of-burgundy',
|
||||
];
|
||||
|
||||
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */
|
||||
|
||||
@@ -50,6 +50,7 @@ export const CATALOG: CatalogEntry[] = [
|
||||
{ id: 'hot-streak', nameKo: '핫스트릭', minPlayers: 2, maxPlayers: 10, minutes: '15~25', level: '쉬움', blurb: '마스코트 넷의 엉망진창 달리기에 티켓으로 걸어요! 비밀 카드 한 장 몰래 넣고 소리 지르며 구경 · 놀이용 돈', available: true },
|
||||
{ id: 'tichu', nameKo: '티츄', minPlayers: 3, maxPlayers: 6, minutes: '30~60', level: '보통', blurb: '마주 앉은 짝꿍과 한 팀! 더 센 조합으로 손패를 먼저 털고 점수 카드 모으기 · 폭탄·티츄 선언 · 3인·6인 변형', available: true },
|
||||
{ id: 'case-file', nameKo: '사건 파일', minPlayers: 1, maxPlayers: 5, minutes: '30~60', level: '보통', blurb: '탐정 사무소 팀이 되어 정해진 시간 안에 단서를 골라 읽고, 마지막에 수사 보고서로 범인을 맞혀요 · 함께 추리 · 혼자서도 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);
|
||||
|
||||
Reference in New Issue
Block a user