Merge branch 'wip/game-gemblo' into codex/owner/grp_discord_joke-app

# Conflicts:
#	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:
EJClaw
2026-10-15 19:41:49 +09:00
27 changed files with 3961 additions and 25 deletions

View File

@@ -13,6 +13,7 @@
"./magical-athlete/racers": "./src/magical-athlete/racers.ts",
"./seotda/money": "./src/seotda/money.ts",
"./six-nimmt/rules": "./src/six-nimmt/rules.ts",
"./gemblo/board": "./src/gemblo/board.ts",
"./*": "./src/*/index.ts"
},
"dependencies": {

View File

@@ -39,6 +39,7 @@ import { liarBot } from '../liar/bot';
import { magicalAthleteBot } from '../magical-athlete/bot';
import { blackjackBot } from '../blackjack/bot';
import { sixNimmtBot } from '../six-nimmt/bot';
import { gembloBot } from '../gemblo/bot';
export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types';
export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona';
@@ -75,6 +76,7 @@ export const BOT_STRATEGIES: Record<string, BotStrategy> = {
'magical-athlete': magicalAthleteBot,
blackjack: blackjackBot,
'six-nimmt': sixNimmtBot,
gemblo: gembloBot,
};
/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */

View File

@@ -33,8 +33,8 @@ describe('luck', () => {
});
test('luck is for games with cards, tiles, dice or hidden roles — not for board games', () => {
for (const id of ['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'connect-four', 'mafia', 'dobble']) expect(luckApplies(id)).toBe(false);
for (const id of Object.keys(BOT_STRATEGIES).filter((g) => !['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'connect-four'].includes(g))) {
for (const id of ['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'connect-four', 'mafia', 'dobble', 'gemblo']) expect(luckApplies(id)).toBe(false);
for (const id of Object.keys(BOT_STRATEGIES).filter((g) => !['omok', 'chess', 'janggi', 'othello', 'baduk', 'quoridor', 'connect-four', 'gemblo'].includes(g))) {
expect(luckApplies(id)).toBe(true);
}
});

View File

@@ -10,7 +10,7 @@ import { BOT_STRATEGIES, decideBotAction } from './index';
import type { BotLevel } from './persona';
/** Games where everything is in view from the start: a shuffle only decides who goes first, so luck stays out. */
const NO_LUCK = new Set(['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'connect-four']);
const NO_LUCK = new Set(['omok', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'connect-four', 'gemblo']);
export const luckApplies = (gameId: string): boolean => gameId in BOT_STRATEGIES && !NO_LUCK.has(gameId);

View File

@@ -0,0 +1,482 @@
/**
* 젬블로 판·블록 (docs/games/gemblo.md §3, §5). Pure geometry and placement checks shared by the rules (`index.ts`),
* the computer (`bot.ts`) and the browser (preview, tap-to-cycle). Nothing here keeps game state: every function
* takes a `BoardInput` (the state or the view have the same fields).
*
* Axial coordinates (q, r), flat-top hexes. Screen centre of (q, r) with hex radius s: x = 1.5·s·q, y = √3·s·(r + q/2).
*/
export type PieceId = 'p1' | 'p2' | 'i3' | 'a3' | 'c3' | 'i4' | 'o4' | 's4' | 'u4' | 'y4' | 'i5' | 'v5' | 'l5' | 'j5' | 'f5' | 'w5' | 'n5' | 't5';
export type ColorId = 'red' | 'yellow' | 'green' | 'blue' | 'purple' | 'orange';
export type BlockColor = ColorId | 'gold';
export type Layout = 'full' | 'four' | 'three' | 'duo';
export interface Hex {
q: number;
r: number;
}
export const COLORS: readonly ColorId[] = ['red', 'yellow', 'green', 'blue', 'purple', 'orange'];
export const COLOR_KO: Record<BlockColor, string> = { red: '빨강', yellow: '노랑', green: '초록', blue: '파랑', purple: '보라', orange: '주황', gold: '금색' };
export interface PieceDef {
id: PieceId;
nameKo: string;
cells: readonly (readonly [number, number])[];
}
/** 3.1: 5칸 8 + 4칸 5 + 3칸 3 + 2칸 1 + 1칸 1 = 18개, 72칸. Big blocks first (tray order). */
export const PIECES: readonly PieceDef[] = [
{ id: 'i5', nameKo: '일자 5', cells: [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4]] },
{ id: 'v5', nameKo: '좁은 V 5', cells: [[0, 0], [0, 1], [0, 2], [1, 0], [2, 0]] },
{ id: 'l5', nameKo: '넓은 V 5', cells: [[0, 0], [0, 1], [0, 2], [1, 2], [2, 2]] },
{ id: 'j5', nameKo: '번개 5', cells: [[0, 0], [0, 1], [0, 2], [1, 2], [1, 3]] },
{ id: 'f5', nameKo: '갈고리 5', cells: [[0, 0], [0, 1], [1, 1], [1, 2], [2, 0]] },
{ id: 'w5', nameKo: '계단 5', cells: [[0, 0], [0, 1], [1, 1], [1, 2], [2, 2]] },
{ id: 'n5', nameKo: 'N자 5', cells: [[0, 0], [0, 1], [1, 1], [2, 1], [2, 2]] },
{ id: 't5', nameKo: '긴 Y 5', cells: [[0, 1], [1, 1], [1, 2], [1, 3], [2, 0]] },
{ id: 'i4', nameKo: '일자 4', cells: [[0, 0], [0, 1], [0, 2], [0, 3]] },
{ id: 'o4', nameKo: '마름모 4', cells: [[0, 0], [0, 1], [1, 0], [1, 1]] },
{ id: 's4', nameKo: 'S자 4', cells: [[0, 0], [0, 1], [1, 1], [1, 2]] },
{ id: 'u4', nameKo: '아치 4', cells: [[0, 0], [0, 1], [1, 1], [2, 0]] },
{ id: 'y4', nameKo: '바람개비 4', cells: [[0, 1], [1, 1], [1, 2], [2, 0]] },
{ id: 'i3', nameKo: '일자 3', cells: [[0, 0], [0, 1], [0, 2]] },
{ id: 'a3', nameKo: '삼각 3', cells: [[0, 0], [0, 1], [1, 0]] },
{ id: 'c3', nameKo: '꺾인 3', cells: [[0, 0], [0, 1], [1, 1]] },
{ id: 'p2', nameKo: '두 칸', cells: [[0, 0], [0, 1]] },
{ id: 'p1', nameKo: '한 칸', cells: [[0, 0]] },
];
export const PIECE_IDS: readonly PieceId[] = PIECES.map((p) => p.id);
export const PIECE_BY_ID: Record<PieceId, PieceDef> = Object.fromEntries(PIECES.map((p) => [p.id, p])) as Record<PieceId, PieceDef>;
export const PIECE_SIZE: Record<PieceId, number> = Object.fromEntries(PIECES.map((p) => [p.id, p.cells.length])) as Record<PieceId, number>;
const PIECE_INDEX: Record<PieceId, number> = Object.fromEntries(PIECES.map((p, i) => [p.id, i])) as Record<PieceId, number>;
export const cellsOf = (ids: readonly PieceId[]): number => ids.reduce((n, id) => n + PIECE_SIZE[id], 0);
// ---------------------------------------------------------------- transforms (3.2)
/** Rotate 60° clockwise on screen. */
export const rot = (q: number, r: number): [number, number] => [-r, q + r];
/** Mirror left ↔ right. */
export const mirror = (q: number, r: number): [number, number] => [-q, q + r];
/** Orientation o (0~11): k = o % 6 rotations after an optional mirror (o >= 6). */
export function transform(o: number, q: number, r: number): [number, number] {
let p: [number, number] = o >= 6 ? mirror(q, r) : [q, r];
for (let k = 0; k < o % 6; k++) p = rot(p[0], p[1]);
return p;
}
/** Cell offsets of a piece in orientation o, relative to where its first base cell lands. */
export function pieceOffsets(id: PieceId, o: number): [number, number][] {
const cs = PIECE_BY_ID[id].cells;
const [q0, r0] = transform(o, cs[0]![0], cs[0]![1]);
return cs.map(([q, r]) => {
const [a, b] = transform(o, q, r);
return [a - q0, b - r0];
});
}
function shapeKey(offs: [number, number][]): string {
const mq = Math.min(...offs.map((c) => c[0]));
const mr = Math.min(...offs.map((c) => c[1]));
return offs
.map(([q, r]) => `${q - mq},${r - mr}`)
.sort()
.join(';');
}
export interface Orientation {
o: number;
offs: [number, number][];
}
/** Distinct orientations per piece (0~5 first, then the mirrored ones that differ): `ORIENTS[id].slice(0, NO_FLIP_COUNT[id])` without flipping. */
export const ORIENTS: Record<PieceId, Orientation[]> = {} as Record<PieceId, Orientation[]>;
export const NO_FLIP_COUNT: Record<PieceId, number> = {} as Record<PieceId, number>;
for (const p of PIECES) {
const seen = new Set<string>();
const list: Orientation[] = [];
for (let o = 0; o < 12; o++) {
const offs = pieceOffsets(p.id, o);
const k = shapeKey(offs);
if (seen.has(k)) continue;
seen.add(k);
list.push({ o, offs });
if (o < 6) NO_FLIP_COUNT[p.id] = list.length;
}
ORIENTS[p.id] = list;
}
export const orientCount = (id: PieceId, allowFlip: boolean): number => (allowFlip ? ORIENTS[id].length : NO_FLIP_COUNT[id]);
// ---------------------------------------------------------------- board cells (3.3)
const OFF = 30;
const W = 2 * OFF + 1;
const hexMax = (q: number, r: number) => Math.max(Math.abs(2 * q + r), Math.abs(q + 2 * r), Math.abs(q - r));
const inFull = (q: number, r: number) => hexMax(q, r) <= 21;
/** All 463 cells of the full (6-player) board, sorted by r then q. Cell numbers are indices into this list. */
export const CELLS: readonly Hex[] = (() => {
const out: Hex[] = [];
for (let r = -OFF; r <= OFF; r++) for (let q = -OFF; q <= OFF; q++) if (inFull(q, r)) out.push({ q, r });
return out;
})();
export const CELL_COUNT = CELLS.length;
const GRID = new Int16Array(W * W).fill(-1);
CELLS.forEach((c, i) => (GRID[(c.q + OFF) * W + (c.r + OFF)] = i));
/** Cell number of (q, r), or -1 off the board. */
export function cellAt(q: number, r: number): number {
if (q < -OFF || q > OFF || r < -OFF || r > OFF) return -1;
return GRID[(q + OFF) * W + (r + OFF)]!;
}
/** Edge neighbours: up, upper right, lower right, down, lower left, upper left. */
export const NEIGHBOR_DIRS: readonly (readonly [number, number])[] = [[0, -1], [1, -1], [1, 0], [0, 1], [-1, 1], [-1, 0]];
/** 5.4: diagonal position B − A and the two cells m1, m2 (A + …) whose shared edge is the link line. */
export const DIAG_DIRS: readonly { d: readonly [number, number]; m1: readonly [number, number]; m2: readonly [number, number] }[] = [
{ d: [2, -1], m1: [1, 0], m2: [1, -1] },
{ d: [1, -2], m1: [1, -1], m2: [0, -1] },
{ d: [-1, -1], m1: [0, -1], m2: [-1, 0] },
{ d: [-2, 1], m1: [-1, 0], m2: [-1, 1] },
{ d: [-1, 2], m1: [-1, 1], m2: [0, 1] },
{ d: [1, 1], m1: [0, 1], m2: [1, 0] },
];
/** NEIGH[i * 6 + k]: neighbour cell or -1. */
export const NEIGH = new Int16Array(CELL_COUNT * 6);
/** DIAG[(i * 6 + k) * 3 + 0..2]: B, m1, m2 (each -1 off the board). */
export const DIAG = new Int16Array(CELL_COUNT * 18);
CELLS.forEach((c, i) => {
NEIGHBOR_DIRS.forEach(([dq, dr], k) => (NEIGH[i * 6 + k] = cellAt(c.q + dq, c.r + dr)));
DIAG_DIRS.forEach(({ d, m1, m2 }, k) => {
DIAG[(i * 6 + k) * 3] = cellAt(c.q + d[0], c.r + d[1]);
DIAG[(i * 6 + k) * 3 + 1] = cellAt(c.q + m1[0], c.r + m1[1]);
DIAG[(i * 6 + k) * 3 + 2] = cellAt(c.q + m2[0], c.r + m2[1]);
});
});
const regionMask = (f: (q: number, r: number) => boolean) => Uint8Array.from(CELLS, (c) => (f(c.q, c.r) ? 1 : 0));
/** Cells used by each layout (3.3). */
export const IN_LAYOUT: Record<Layout, Uint8Array> = {
full: regionMask(() => true),
three: regionMask((q, r) => hexMax(q, r) <= 15),
four: regionMask((q, r) => Math.abs(q) <= 9 && Math.abs(q + 2 * r) <= 15),
duo: regionMask((q, r) => hexMax(q, r) <= 12),
};
/** 5인 장애물(4장 3.): 맨 바깥 칸(판 밖과 변을 맞댄 84칸)과 그 안쪽 두 번째 줄(72칸). */
export const OUTER = Uint8Array.from(CELLS, (_, i) => {
for (let k = 0; k < 6; k++) if (NEIGH[i * 6 + k]! < 0) return 1;
return 0;
});
export const SECOND = Uint8Array.from(CELLS, (_, i) => {
if (OUTER[i]) return 0;
for (let k = 0; k < 6; k++) {
const n = NEIGH[i * 6 + k]!;
if (n >= 0 && OUTER[n]) return 1;
}
return 0;
});
export const hexDistance = (a: Hex, b: Hex): number => (Math.abs(a.q - b.q) + Math.abs(a.r - b.r) + Math.abs(a.q + a.r - b.q - b.r)) / 2;
/** Screen position (hex radius 1). */
export const toXY = (q: number, r: number): [number, number] => [1.5 * q, Math.sqrt(3) * (r + q / 2)];
// ---------------------------------------------------------------- starts (4장)
const H = (q: number, r: number): Hex => ({ q, r });
export const STARTS = {
six: [H(-7, -7), H(7, -14), H(14, -7), H(7, 7), H(-7, 14), H(-14, 7)],
five: [H(-10, -1), H(4, -12), H(14, -7), H(4, 8), H(-10, 11)],
four: [H(-9, -3), H(9, -12), H(9, 3), H(-9, 12)],
three: [H(-5, -5), H(10, -5), H(-5, 10)],
duo: [H(-4, 2), H(4, -2)],
} as const;
/** 5인 구역: 이웃한 두 시작점 사이(시작점 각도로 나눔). Screen angles of the starts, ascending (clockwise on screen). */
const FIVE_ANGLES = STARTS.five.map((s) => Math.atan2(toXY(s.q, s.r)[1], toXY(s.q, s.r)[0])).sort((a, b) => a - b);
/** Sector 0~4 of a screen point (the arc from start k to start k + 1, clockwise). */
export function sectorOf(x: number, y: number): number {
const a = Math.atan2(y, x);
for (let k = 0; k < 4; k++) if (a >= FIVE_ANGLES[k]! && a < FIVE_ANGLES[k + 1]!) return k;
return 4;
}
// ---------------------------------------------------------------- placement checks (5.2~5.4)
export type BridgeRule = 'official' | 'free';
/** What the checks need to know about the board (the game state and the view both have these fields). */
export interface BoardInput {
layout: Layout;
/** CELL_COUNT entries: -1 empty, otherwise the placement's `seq`. */
board: readonly number[];
placements: readonly { color: BlockColor; cells: readonly number[] }[];
bridgeRule: BridgeRule;
}
/** The colour being placed. */
export interface ColorInput {
color: ColorId;
start: Hex;
/** Blocks this colour still has. */
left: readonly PieceId[];
/** Blocks it has already placed (0 = the first block must cover the start). */
placed: number;
}
export function ownCells(b: BoardInput, color: ColorId): number[] {
const out: number[] = [];
for (const p of b.placements) if (p.color === color) out.push(...p.cells);
return out;
}
/** usable[i] = 1 when a block of `color` may cover cell i: in this layout, empty, not next to the same colour. */
export function usableMask(b: BoardInput, color: ColorId, own = ownCells(b, color)): Uint8Array {
const inL = IN_LAYOUT[b.layout];
const m = new Uint8Array(CELL_COUNT);
for (let i = 0; i < CELL_COUNT; i++) m[i] = inL[i]! && b.board[i]! < 0 ? 1 : 0;
for (const c of own) for (let k = 0; k < 6; k++) {
const n = NEIGH[c * 6 + k]!;
if (n >= 0) m[n] = 0;
}
return m;
}
/** 5.4: the link line between m1 and m2 is closed only when one block covers both (official rule). */
export function bridgeOpen(b: BoardInput, m1: number, m2: number): boolean {
if (b.bridgeRule === 'free' || m1 < 0 || m2 < 0) return true;
const inL = IN_LAYOUT[b.layout];
if (!inL[m1] || !inL[m2]) return true;
const s = b.board[m1]!;
return s < 0 || s !== b.board[m2];
}
/** 이음점: cells where a block of this colour could put one cell right now (the start for the first block). */
export function linkPoints(b: BoardInput, c: ColorInput, own = ownCells(b, c.color), usable = usableMask(b, c.color, own)): number[] {
if (c.placed === 0) {
const s = cellAt(c.start.q, c.start.r);
return s >= 0 && usable[s] ? [s] : [];
}
const out: number[] = [];
const seen = new Uint8Array(CELL_COUNT);
for (const a of own) {
for (let k = 0; k < 6; k++) {
const j = (a * 6 + k) * 3;
const bb = DIAG[j]!;
if (bb < 0 || seen[bb] || !usable[bb]) continue;
if (!bridgeOpen(b, DIAG[j + 1]!, DIAG[j + 2]!)) continue;
seen[bb] = 1;
out.push(bb);
}
}
return out;
}
/** Cells of a piece placed with its first base cell at (q, r), or null when a cell falls off the board. */
export function placementCells(id: PieceId, o: number, q: number, r: number): number[] | null {
const out: number[] = [];
for (const [dq, dr] of pieceOffsets(id, o)) {
const i = cellAt(q + dq, r + dr);
if (i < 0) return null;
out.push(i);
}
return out;
}
/** Why a block of colour `c` can't go there (5.2~5.4), or null when it can. Same code on the server and in the browser. */
export function placementRefusal(b: BoardInput, c: ColorInput, id: PieceId, o: number, q: number, r: number, allowFlip: boolean): string | null {
if (!c.left.includes(id)) return '이미 쓴 블록이에요.';
if (!Number.isInteger(o) || o < 0 || o > 11) return '블록 방향이 잘못됐어요.';
if (o >= 6 && !allowFlip) return '이 방에서는 블록을 뒤집을 수 없어요.';
const cells = placementCells(id, o, q, r);
if (!cells) return '판 밖이에요.';
return cellsRefusal(b, c, cells);
}
export function cellsRefusal(b: BoardInput, c: ColorInput, cells: readonly number[]): string | null {
const inL = IN_LAYOUT[b.layout];
if (cells.some((i) => !inL[i])) return '이번 판에서 쓰지 않는 칸이에요.';
if (cells.some((i) => b.board[i]! >= 0)) return '다른 블록과 겹쳐요.';
const own = ownCells(b, c.color);
const near = new Uint8Array(CELL_COUNT);
for (const a of own) for (let k = 0; k < 6; k++) {
const n = NEIGH[a * 6 + k]!;
if (n >= 0) near[n] = 1;
}
if (cells.some((i) => near[i])) return '같은 색 블록과 닿으면 안 돼요.';
if (c.placed === 0) {
const s = cellAt(c.start.q, c.start.r);
return cells.includes(s) ? null : '첫 블록은 시작점을 덮어야 해요.';
}
const mine = new Uint8Array(CELL_COUNT);
for (const a of own) mine[a] = 1;
let diagonal = false;
for (const bb of cells) {
for (let k = 0; k < 6; k++) {
// A = B − d: walk the diagonals from B backwards (the table is symmetric: B's diagonal k+3 is the reverse of k).
const j = (bb * 6 + k) * 3;
const a = DIAG[j]!;
if (a < 0 || !mine[a]) continue;
diagonal = true;
if (bridgeOpen(b, DIAG[j + 1]!, DIAG[j + 2]!)) return null;
}
}
return diagonal ? '이 선은 다른 블록에 막혀 있어요.' : '내 블록에서 선으로 이어지는 곳이 아니에요.';
}
export interface Placement {
pieceId: PieceId;
orient: number;
/** Where the first base cell lands (the action's q, r). */
q: number;
r: number;
cells: number[];
}
// One stamp per (piece, orientation, anchor) so the same placement found from two link points is listed once.
const STAMP = new Int32Array(PIECES.length * 12 * CELL_COUNT);
let stampNo = 0;
/**
* Legal placements for colour `c`: every link point × block × orientation × "which cell sits on the point".
* `limit` stops early (1 = "is there any?"); `points` / `pieces` narrow the search (tap-to-cycle, one block).
*/
export function legalPlacements(
b: BoardInput,
c: ColorInput,
allowFlip: boolean,
opts: { limit?: number; points?: readonly number[]; pieces?: readonly PieceId[] } = {},
): Placement[] {
const own = ownCells(b, c.color);
const usable = usableMask(b, c.color, own);
const lp = linkPoints(b, c, own, usable);
const points = opts.points ? opts.points.filter((p) => lp.includes(p)) : lp;
const pieces = opts.pieces ? c.left.filter((id) => opts.pieces!.includes(id)) : c.left;
const limit = opts.limit ?? Infinity;
const out: Placement[] = [];
if (++stampNo > 2_000_000_000) {
STAMP.fill(0);
stampNo = 1;
}
for (const id of pieces) {
const pi = PIECE_INDEX[id];
const orients = ORIENTS[id];
const n = orientCount(id, allowFlip);
for (let oi = 0; oi < n; oi++) {
const { o, offs } = orients[oi]!;
for (const p of points) {
const P = CELLS[p]!;
for (const [jq, jr] of offs) {
const aq = P.q - jq;
const ar = P.r - jr;
const anchor = cellAt(aq, ar);
if (anchor < 0 || !usable[anchor]) continue;
const key = (pi * 12 + o) * CELL_COUNT + anchor;
if (STAMP[key] === stampNo) continue;
const cells: number[] = [];
let okAll = true;
for (const [dq, dr] of offs) {
const i = cellAt(aq + dq, ar + dr);
if (i < 0 || !usable[i]) {
okAll = false;
break;
}
cells.push(i);
}
STAMP[key] = stampNo;
if (!okAll) continue;
out.push({ pieceId: id, orient: o, q: aq, r: ar, cells });
if (out.length >= limit) return out;
}
}
}
}
return out;
}
export const hasAnyPlacement = (b: BoardInput, c: ColorInput, allowFlip: boolean): boolean => legalPlacements(b, c, allowFlip, { limit: 1 }).length > 0;
/** Blocks with at least one legal placement right now. */
export function placeablePieces(b: BoardInput, c: ColorInput, allowFlip: boolean): PieceId[] {
return c.left.filter((id) => legalPlacements(b, c, allowFlip, { limit: 1, pieces: [id] }).length > 0);
}
// ---------------------------------------------------------------- 5인 장애물 (4장 3.)
/** Why an obstacle can't go on these cells, or null. `sectorCount`: obstacles already in each of the 5 sectors. */
export function obstacleRefusal(b: BoardInput, cells: readonly number[], sectorCount: readonly number[]): string | null {
if (cells.some((i) => b.board[i]! >= 0)) return '다른 블록과 겹쳐요.';
if (cells.some((i) => OUTER[i])) return '맨 바깥 줄에는 놓을 수 없어요.';
const second = cells.filter((i) => SECOND[i]);
if (!second.length) return '바깥에서 두 번째 줄 칸을 하나 이상 덮어야 해요.';
const centroid = (xs: readonly number[]) => {
let x = 0;
let y = 0;
for (const i of xs) {
const [a, bb] = toXY(CELLS[i]!.q, CELLS[i]!.r);
x += a;
y += bb;
}
return [x / xs.length, y / xs.length] as const;
};
const [bx, by] = centroid(cells);
const [sx, sy] = centroid(second);
if (Math.hypot(bx, by) >= Math.hypot(sx, sy) - 1e-9) return '판 가운데 쪽으로 뻗어야 해요.';
if ((sectorCount[obstacleSector(cells)] ?? 0) >= 3) return '이 구역(두 시작점 사이)에는 장애물이 벌써 3개 있어요.';
return null;
}
/** The sector of an obstacle: the angle of the second-row cells it covers. */
export function obstacleSector(cells: readonly number[]): number {
let x = 0;
let y = 0;
let n = 0;
for (const i of cells) {
if (!SECOND[i]) continue;
const [a, b] = toXY(CELLS[i]!.q, CELLS[i]!.r);
x += a;
y += b;
n++;
}
return n ? sectorOf(x / n, y / n) : sectorOf(0, 0);
}
/** Every legal obstacle placement of these blocks (all orientations, flips included: obstacles belong to nobody). */
export function obstaclePlacements(b: BoardInput, pieces: readonly PieceId[], sectorCount: readonly number[], onlySector?: number, limit = Infinity): Placement[] {
const out: Placement[] = [];
const seconds: number[] = [];
for (let i = 0; i < CELL_COUNT; i++) if (SECOND[i] && b.board[i]! < 0) seconds.push(i);
if (++stampNo > 2_000_000_000) {
STAMP.fill(0);
stampNo = 1;
}
for (const id of new Set(pieces)) {
const pi = PIECE_INDEX[id];
for (const { o, offs } of ORIENTS[id]) {
for (const p of seconds) {
const P = CELLS[p]!;
for (const [jq, jr] of offs) {
const aq = P.q - jq;
const ar = P.r - jr;
const anchor = cellAt(aq, ar);
if (anchor < 0) continue;
const key = (pi * 12 + o) * CELL_COUNT + anchor;
if (STAMP[key] === stampNo) continue;
STAMP[key] = stampNo;
const cells: number[] = [];
for (const [dq, dr] of offs) {
const i = cellAt(aq + dq, ar + dr);
if (i < 0 || OUTER[i] || b.board[i]! >= 0) break;
cells.push(i);
}
if (cells.length !== offs.length || obstacleRefusal(b, cells, sectorCount)) continue;
if (onlySector !== undefined && obstacleSector(cells) !== onlySector) continue;
out.push({ pieceId: id, orient: o, q: aq, r: ar, cells });
if (out.length >= limit) return out;
}
}
}
}
return out;
}

View File

@@ -0,0 +1,63 @@
/** 젬블로 computer (docs/games/gemblo.md §8.7). */
import { describe, expect, test } from 'bun:test';
import { SeededRng, seedN } from '@bg/engine';
import { decideBotAction } from '../bots/index';
import { botPlayout } from '../bots/playout';
import { PIECE_SIZE, cellAt, gemblo, type GembloAction, type GembloState } from './index';
const make = (n: number, opts: object = {}) =>
gemblo.setup({ players: ['bot:1:a', 'bot:2:b', 'bot:3:c', 'bot:4:d', 'bot:5:e', 'bot:6:f'].slice(0, n), options: gemblo.optionsSchema.parse({ seatOrder: 'joinOrder', ...opts }), rng: SeededRng.fromSeed(seedN(1)), now: 0 });
const decide = (s: GembloState, level?: number, random = () => 0.5) => decideBotAction(gemblo, s, s.colors[s.turn]!.owner, { now: 1000, random, level }) as GembloAction;
describe('gemblo bot', () => {
test('starts with a five-cell block on its start', () => {
const s = make(4);
const a = decide(s) as Extract<GembloAction, { type: 'place' }>;
expect(a.type).toBe('place');
expect(PIECE_SIZE[a.pieceId]).toBe(5);
const after = gemblo.apply(s, s.colors[0]!.owner, a, { rng: SeededRng.fromSeed(seedN(2)), now: 1000 }).state;
expect(after.board[cellAt(-9, -3)]).toBe(0);
});
test('every move is legal and quick, at the weakest and strongest levels, in every mode', () => {
for (const [n, opts] of [[2, {}], [3, {}], [4, { teams: 'pairs' }], [5, { fivePlayerObstacles: 'draft' }], [6, {}], [2, { twoPlayerMode: 'duo' }]] as [number, object][]) {
for (const level of [1, 60]) {
const r = botPlayout(gemblo, { players: Array.from({ length: n }, (_, i) => `bot:${i}:x`), options: gemblo.optionsSchema.parse(opts), seed: seedN(40 + n), isBot: () => true, level });
expect(r.finished).toBe(true);
expect(r.botTimeouts).toBe(0);
expect(r.maxBotMs).toBeLessThan(250);
}
}
});
test('plays much better than random moves (fewer cells left)', () => {
// 2 players, 2 colours each: the bot (A) against a player who picks any legal placement.
let botLeft = 0;
let randLeft = 0;
for (let g = 0; g < 6; g++) {
const rng = SeededRng.fromSeed(seedN(70 + g));
const pickRng = SeededRng.fromSeed(seedN(170 + g));
const players = g % 2 ? ['bot:1:a', 'r'] : ['r', 'bot:1:a'];
let s = gemblo.setup({ players, options: gemblo.optionsSchema.parse({ seatOrder: 'joinOrder' }), rng, now: 0 });
for (let k = 0; k < 200 && s.phase !== 'finished'; k++) {
const p = s.colors[s.turn]!.owner;
const legal = gemblo.legalActions!(s, p);
const a = p === 'r' ? legal[pickRng.int(legal.length)]! : (decideBotAction(gemblo, s, p, { now: k, random: () => pickRng.next(), level: 50 }) as GembloAction);
s = gemblo.apply(s, p, a, { rng, now: k }).state;
}
expect(s.phase).toBe('finished');
botLeft += s.result!.scores['bot:1:a']!;
randLeft += s.result!.scores.r!;
}
expect(botLeft).toBeLessThan(randLeft * 0.6);
});
test('accepts undo requests', () => {
let s = make(2, { twoPlayerMode: 'duo', undo: '1' });
const a = s.colors[0]!.owner;
s = gemblo.apply(s, a, { type: 'place', pieceId: 'p1', orient: 0, q: -4, r: 2 }, { rng: SeededRng.fromSeed(seedN(3)), now: 1 }).state;
s = gemblo.apply(s, a, { type: 'requestUndo' }, { rng: SeededRng.fromSeed(seedN(3)), now: 2 }).state;
const b = s.colors[1]!.owner;
expect(decideBotAction(gemblo, s, b, { now: 3, random: () => 0.5 })).toEqual({ type: 'respondUndo', accept: true });
});
});

View File

@@ -0,0 +1,74 @@
/**
* 젬블로 computer (docs/games/gemblo.md §8.7): big blocks first, keep my link points open, close the others' link
* points, head for the centre early on. Only the view and the legal placements are used.
*/
import type { BotStrategy } from '../bots/types';
import { answerRequests, humanBest, pick, playable, typeOf } from '../bots/policy';
import { CELLS, PIECE_SIZE, hexDistance, linkPoints, placementCells, type BoardInput, type PieceId } from './board';
import type { GembloView } from './types';
type Place = { type: 'place'; pieceId: PieceId; orient: number; q: number; r: number };
const CENTER = { q: 0, r: 0 };
/** Placements looked at closely (link point changes) after the quick size + centre sort. */
export const BOT_SHORTLIST = 80;
export const gembloBot: BotStrategy<GembloView> = ({ me, view, legal, random, level }) => {
const req = answerRequests(legal);
if (req) return req;
const places = legal.filter((a) => typeOf(a) === 'place') as Place[];
if (!places.length) {
// 5인 장애물 고르기: 큰 블록부터(놓기 쉬운 자리가 많음). 놓기: 아무 자리나.
const picks = legal.filter((a) => typeOf(a) === 'pickObstacle') as { pieceId: PieceId }[];
if (picks.length) {
const top = Math.max(...picks.map((p) => PIECE_SIZE[p.pieceId]));
return pick(picks.filter((p) => PIECE_SIZE[p.pieceId] === top), random);
}
return pick(playable(legal), random);
}
const ci = view.turn;
const c = view.colors[ci]!;
const mineTeam = new Set<string>([me, ...(view.teams?.find((t) => t.includes(me)) ?? [])]);
const rivals = view.colors.filter((x) => !x.done && !mineTeam.has(x.owner));
const board = [...view.board];
const placements: { color: BoardInput['placements'][number]['color']; cells: readonly number[] }[] = [...view.placements];
const b: BoardInput = { layout: view.layout, board, placements, bridgeRule: view.bridgeRule };
const myBefore = linkPoints(b, c);
const myPoints = new Set(myBefore);
const rivalBefore = rivals.map((x) => linkPoints(b, x).length);
let near = Infinity;
for (const p of view.placements) if (p.color === c.color) for (const i of p.cells) near = Math.min(near, hexDistance(CELLS[i]!, CENTER));
if (near === Infinity) near = hexDistance(c.start, CENTER);
const early = c.placed < 4;
const cand = places.map((a) => {
const cells = placementCells(a.pieceId, a.orient, a.q, a.r)!;
const d = Math.min(...cells.map((i) => hexDistance(CELLS[i]!, CENTER)));
const gain = early ? Math.max(0, near - d) : 0;
return { a, cells, gain, quick: 10 * PIECE_SIZE[a.pieceId] + 2 * gain + random() * 0.5 };
});
cand.sort((x, y) => y.quick - x.quick);
const short = cand.slice(0, BOT_SHORTLIST);
// Lower levels look less at blocking (doc: "막기를 덜 본다").
const blockWeight = level === undefined ? 4 : 4 * Math.min(1, 0.3 + level / 50);
const seq = placements.length;
const scores = new Map<Place, number>();
for (const x of short) {
for (const i of x.cells) board[i] = seq;
placements.push({ color: c.color, cells: x.cells });
const myAfter = linkPoints(b, { ...c, placed: c.placed + 1 }).length;
let blocked = 0;
rivals.forEach((r, k) => (blocked += rivalBefore[k]! - linkPoints(b, r).length));
placements.pop();
for (const i of x.cells) board[i] = -1;
const covered = x.cells.filter((i) => myPoints.has(i)).length;
scores.set(x.a, 10 * PIECE_SIZE[x.a.pieceId] + 3 * (myAfter - myBefore.length) + blockWeight * blocked + 2 * x.gain - (covered >= 2 ? 8 : 0));
}
return humanBest(
short.map((x) => x.a),
(a) => scores.get(a)!,
random,
level,
{ small: 10, critical: Infinity },
);
};

View File

@@ -0,0 +1,603 @@
/** 젬블로 rules (docs/games/gemblo.md §10). */
import { describe, expect, test } from 'bun:test';
import { SeededRng, playoutSeeds, randomPlayout, seedN } from '@bg/engine';
import {
CELLS,
IN_LAYOUT,
NEIGH,
NO_FLIP_COUNT,
OBSTACLE_POOL,
ORIENTS,
OUTER,
PIECES,
PIECE_IDS,
SECOND,
STARTS,
cellAt,
gemblo,
hexDistance,
legalPlacements,
linkPoints,
mirror,
obstacleSector,
placementCells,
placementRefusal,
rot,
type BoardInput,
type BlockColor,
type GembloAction,
type GembloOptions,
type GembloState,
type GembloView,
type PieceId,
} from './index';
const rng = (n = 1) => SeededRng.fromSeed(seedN(n));
const IDS = ['A', 'B', 'C', 'D', 'E', 'F'];
function make(n: number, opts: Partial<GembloOptions> = {}, seed = 1): GembloState {
const options = gemblo.optionsSchema.parse({ seatOrder: 'joinOrder', ...opts });
return gemblo.setup({ players: IDS.slice(0, n), options, rng: rng(seed), now: 0 });
}
/** Puts a block straight onto the board (no rule checks). Player colours count it as placed. */
function put(s: GembloState, color: BlockColor, cells: [number, number][], pieceId: PieceId = 'i5'): number {
const seq = s.placements.length;
const idx = cells.map(([q, r]) => cellAt(q, r));
for (const i of idx) s.board[i] = seq;
s.placements.push({ seq, color, pieceId, orient: 0, cells: idx, auto: false, kind: color === 'gold' ? 'neutral' : 'play' });
const c = s.colors.find((x) => x.color === color);
if (c) c.placed++;
return seq;
}
function act(s: GembloState, actor: string, a: GembloAction, now = 1000, seed = 9): GembloState {
const v = gemblo.validate(s, actor, a);
if (!v.ok) throw new Error(v.reason);
return gemblo.apply(s, actor, a, { rng: rng(seed), now }).state;
}
const turnOwner = (s: GembloState) => s.colors[s.turn]!.owner;
const board = (s: GembloState): BoardInput => ({ layout: s.layout, board: s.board, placements: s.placements, bridgeRule: s.options.bridgeRule });
const why = (s: GembloState, pieceId: PieceId, orient: number, q: number, r: number) => {
const v = gemblo.validate(s, turnOwner(s), { type: 'place', pieceId, orient, q, r });
return v.ok ? 'ok' : v.reason;
};
const count = (layout: keyof typeof IN_LAYOUT) => IN_LAYOUT[layout].reduce((n, x) => n + x, 0);
describe('판·블록 (3장)', () => {
test('판·구역 칸 수: 전체 463, 3인 241, 4인 295, 듀오 157', () => {
expect(CELLS).toHaveLength(463);
expect([count('full'), count('three'), count('four'), count('duo')]).toEqual([463, 241, 295, 157]);
expect(OUTER.reduce((n, x) => n + x, 0)).toBe(84);
expect(SECOND.reduce((n, x) => n + x, 0)).toBe(72);
});
test('시작 칸은 모두 그 구역 안이고 구역의 맨 바깥 칸', () => {
const edge = (layout: keyof typeof IN_LAYOUT, q: number, r: number) => {
const i = cellAt(q, r);
expect(IN_LAYOUT[layout][i]).toBe(1);
let outside = false;
for (let k = 0; k < 6; k++) {
const n = NEIGH[i * 6 + k]!;
if (n < 0 || !IN_LAYOUT[layout][n]) outside = true;
}
expect(outside).toBe(true);
};
for (const h of STARTS.six) edge('full', h.q, h.r);
for (const h of STARTS.five) edge('full', h.q, h.r);
for (const h of STARTS.four) edge('four', h.q, h.r);
for (const h of STARTS.three) edge('three', h.q, h.r);
for (const h of STARTS.duo) expect(IN_LAYOUT.duo[cellAt(h.q, h.r)]).toBe(1);
});
test('블록 18개 72칸, 방향 수 표와 같음(74 / 92), R⁶·M² = 제자리', () => {
expect(PIECES).toHaveLength(18);
expect(PIECES.reduce((n, p) => n + p.cells.length, 0)).toBe(72);
const sizes = PIECES.map((p) => p.cells.length);
expect([5, 4, 3, 2, 1].map((k) => sizes.filter((x) => x === k).length)).toEqual([8, 5, 3, 1, 1]);
const table: Record<PieceId, [number, number]> = {
p1: [1, 1], p2: [3, 3], i3: [3, 3], a3: [2, 2], c3: [6, 6], i4: [3, 3], o4: [3, 3], s4: [3, 6], u4: [6, 6], y4: [2, 2],
i5: [3, 3], v5: [6, 6], l5: [6, 6], j5: [6, 12], f5: [6, 12], w5: [6, 6], n5: [3, 6], t5: [6, 6],
};
for (const id of PIECE_IDS) expect([NO_FLIP_COUNT[id], ORIENTS[id].length], id).toEqual(table[id]);
expect(PIECE_IDS.reduce((n, id) => n + NO_FLIP_COUNT[id], 0)).toBe(74);
expect(PIECE_IDS.reduce((n, id) => n + ORIENTS[id].length, 0)).toBe(92);
for (const [q, r] of [[1, 2], [-3, 1], [0, 5]] as [number, number][]) {
let p: [number, number] = [q, r];
for (let k = 0; k < 6; k++) p = rot(...p);
expect(p.map((x) => x + 0)).toEqual([q, r]);
expect(mirror(...mirror(q, r)).map((x) => x + 0)).toEqual([q, r]);
}
});
});
describe('준비 (4장)', () => {
const owners = (s: GembloState) => s.colors.map((c) => `${c.color}:${c.owner}`).join(' ');
test('인원·모드별 색 배분과 차례 순서', () => {
expect(owners(make(6))).toBe('red:A yellow:B green:C blue:D purple:E orange:F');
expect(make(6).layout).toBe('full');
expect(owners(make(4))).toBe('red:A yellow:B green:C blue:D');
expect(make(4).layout).toBe('four');
expect(make(4).colors.map((c) => `${c.start.q},${c.start.r}`)).toEqual(['-9,-3', '9,-12', '9,3', '-9,12']);
expect(owners(make(3))).toBe('red:A yellow:B green:C');
expect(make(3).layout).toBe('three');
expect(owners(make(3, { threePlayerMode: 'twoColors' }))).toBe('red:A yellow:B green:C blue:A purple:B orange:C');
expect(owners(make(2))).toBe('red:A yellow:B green:A blue:B');
expect(make(2).layout).toBe('four');
expect(owners(make(2, { twoPlayerMode: 'threeColors' }))).toBe('red:A yellow:B green:A blue:B purple:A orange:B');
expect(make(2, { twoPlayerMode: 'threeColors' }).layout).toBe('full');
const duo = make(2, { twoPlayerMode: 'duo' });
expect([owners(duo), duo.layout]).toEqual(['red:A yellow:B', 'duo']);
expect(owners(make(5, { fivePlayerObstacles: 'none' }))).toBe('red:A yellow:B green:C blue:D purple:E');
});
test('팀전: 자리로 정해지고(4명 대각선, 6명 마주 보기 / 한 칸 건너), 인원이 안 맞으면 거부', () => {
expect(make(4, { teams: 'pairs' }).teams).toEqual([['A', 'C'], ['B', 'D']]);
expect(make(6, { teams: 'pairs' }).teams).toEqual([['A', 'D'], ['B', 'E'], ['C', 'F']]);
expect(make(6, { teams: 'triples' }).teams).toEqual([['A', 'C', 'E'], ['B', 'D', 'F']]);
const o = (teams: GembloOptions['teams']) => gemblo.optionsSchema.parse({ teams });
expect(gemblo.playerCountError!(o('pairs'), 3)).toBe('팀전(2명씩)은 4명 또는 6명일 때만 돼요.');
expect(gemblo.playerCountError!(o('triples'), 4)).toBe('팀전(3명씩)은 6명일 때만 돼요.');
expect(gemblo.playerCountError!(o('pairs'), 4)).toBeNull();
expect(() => make(5, { teams: 'pairs' })).toThrow('팀전');
});
test('random 자리는 RNG로, 같은 시드면 같은 결과', () => {
const seats = (n: number) => gemblo.setup({ players: IDS, options: gemblo.defaultOptions, rng: rng(n), now: 0 }).players.join('');
expect(seats(3)).toBe(seats(3));
expect(new Set([1, 2, 3, 4, 5, 6, 7, 8].map(seats)).size).toBeGreaterThan(1);
});
});
describe('놓기 (5장)', () => {
test('첫 블록: 시작점을 덮어야 하고, 합법 수 56 / 45 / 44 / 56', () => {
const six = make(6);
six.turn = 2; // (14,-7)
expect(gemblo.legalActions!(six, 'C')).toHaveLength(56);
const sixNoFlip = make(6, { allowFlip: false });
sixNoFlip.turn = 2;
expect(gemblo.legalActions!(sixNoFlip, 'C')).toHaveLength(45);
expect(gemblo.legalActions!(make(4), 'A')).toHaveLength(44);
expect(gemblo.legalActions!(make(3), 'A')).toHaveLength(56);
const s = make(6);
expect(why(s, 'p1', 0, -7, -7)).toBe('ok');
expect(why(s, 'p1', 0, -6, -7)).toBe('첫 블록은 시작점을 덮어야 해요.');
expect(why(s, 'p2', 0, -7, -8)).toBe('판 밖이에요.');
});
test('같은 색과 변을 맞대면 거부, 다른 색과는 허용', () => {
const s = make(6);
put(s, 'red', [[0, 0]]);
put(s, 'yellow', [[2, 0]]);
expect(why(s, 'p1', 0, 0, 1)).toBe('같은 색 블록과 닿으면 안 돼요.');
// (1,1) is diagonal (B − A = (1,1)) and touches the yellow block at (2,0): fine.
expect(why(s, 'p1', 0, 1, 1)).toBe('ok');
expect(why(s, 'p1', 0, 2, 0)).toBe('다른 블록과 겹쳐요.');
});
test('이음선 6방향 모두 허용, 대각 위치가 아니면 거부', () => {
const s = make(6);
put(s, 'red', [[0, 0]]);
for (const [q, r] of [[2, -1], [1, -2], [-1, -1], [-2, 1], [-1, 2], [1, 1]]) expect(why(s, 'p1', 0, q!, r!), `${q},${r}`).toBe('ok');
expect(why(s, 'p1', 0, 2, 0)).toBe('내 블록에서 선으로 이어지는 곳이 아니에요.');
expect(linkPoints(board(s), s.colors[0]!).map((i) => `${CELLS[i]!.q},${CELLS[i]!.r}`).sort()).toEqual(['-1,-1', '-1,2', '-2,1', '1,-2', '1,1', '2,-1']);
});
test('막힘: 한 블록이 사이 두 칸을 덮으면 거부, 두 블록이 맞댄 틈·한 칸만 덮임은 허용, free는 모두 허용', () => {
// A = (0,0), B = (2,-1): 사이 칸 m1 = (1,0), m2 = (1,-1).
const base = (opts: Partial<GembloOptions> = {}) => {
const s = make(6, opts);
put(s, 'red', [[0, 0]]);
return s;
};
let s = base();
put(s, 'yellow', [[1, -1], [1, 0]], 'p2');
expect(why(s, 'p1', 0, 2, -1)).toBe('이 선은 다른 블록에 막혀 있어요.');
s = base({ bridgeRule: 'free' });
put(s, 'yellow', [[1, -1], [1, 0]], 'p2');
expect(why(s, 'p1', 0, 2, -1)).toBe('ok');
s = base();
put(s, 'yellow', [[1, 0]]);
put(s, 'green', [[1, -1]]);
expect(why(s, 'p1', 0, 2, -1)).toBe('ok');
s = base();
put(s, 'yellow', [[1, 0]]);
expect(why(s, 'p1', 0, 2, -1)).toBe('ok');
s = base();
put(s, 'gold', [[1, 0]]);
put(s, 'gold', [[1, -1]]);
expect(why(s, 'p1', 0, 2, -1)).toBe('ok');
s = base();
put(s, 'gold', [[1, -1], [1, 0]], 'p2');
expect(why(s, 'p1', 0, 2, -1)).toBe('이 선은 다른 블록에 막혀 있어요.');
});
test('구역 밖 칸은 못 놓고, 사이 칸이 구역 밖이면 열린 것으로 봄', () => {
const s = make(4);
expect(why(s, 'p2', 0, -10, 0)).toBe('이번 판에서 쓰지 않는 칸이에요.');
// A = (1,7) (q + 2r = 15, the edge), B = (-1,8): m2 = (0,8) lies outside the 4-player area.
const t = make(4);
put(t, 'red', [[1, 7]]);
put(t, 'gold', [[0, 7], [0, 8]], 'p2');
expect(IN_LAYOUT.four[cellAt(0, 8)]).toBe(0);
expect(why(t, 'p1', 0, -1, 8)).toBe('ok');
});
test('뒤집기 금지: 방향 6~11 거부, 거울상 블록 방향 수 절반', () => {
const flipped = gemblo.legalActions!(make(6), 'A').find((a) => a.type === 'place' && a.pieceId === 'j5' && a.orient >= 6) as Extract<GembloAction, { type: 'place' }>;
expect(flipped).toBeDefined();
const s = make(6, { allowFlip: false });
expect(why(s, 'j5', flipped.orient, flipped.q, flipped.r)).toBe('이 방에서는 블록을 뒤집을 수 없어요.');
expect(why(make(6), 'j5', flipped.orient, flipped.q, flipped.r)).toBe('ok');
for (const id of ['s4', 'j5', 'f5', 'n5'] as PieceId[]) expect(NO_FLIP_COUNT[id] * 2).toBe(ORIENTS[id].length);
});
});
describe('차례와 끝 (5.5)', () => {
test('놓을 곳 없는 색은 자동으로 끝남, 이후 차례에서 빠지고, 2색 가진 사람의 다른 색은 계속', () => {
let s = make(2); // red A, yellow B, green A, blue B
put(s, 'gold', [[9, -12]]); // yellow's start is covered
s.colors[1]!.placed = 0;
s = act(s, 'A', { type: 'place', pieceId: 'i5', orient: 0, q: -9, r: -3 });
expect(s.colors[1]!.done).toBe(true);
expect(s.colors[1]!.doneReason).toBe('blocked');
expect(s.history.some((m) => m.kind === 'out' && m.color === 'yellow' && m.leftCells === 72)).toBe(true);
expect(s.turn).toBe(2);
s = act(s, 'A', { type: 'place', pieceId: 'i5', orient: 3, q: 9, r: 3 });
expect(s.turn).toBe(3);
expect(turnOwner(s)).toBe('B');
s = act(s, 'B', { type: 'place', pieceId: 'i5', orient: 3, q: -9, r: 12 });
expect(s.turn).toBe(0); // yellow is skipped from now on
});
test('모든 색이 끝나면 종료: 남은 칸 합, 블로커스 점수(+20 / +15)', () => {
const end = (scoring: GembloOptions['scoring'], last: PieceId) => {
let s = make(2, { twoPlayerMode: 'duo', scoring });
s.colors[0]!.left = [last];
s.colors[1]!.done = true;
s.colors[1]!.doneReason = 'blocked';
s.colors[1]!.left = ['i5', 'v5'];
const [q, r] = last === 'p1' ? [-4, 2] : [-4, 2];
s = act(s, 'A', { type: 'place', pieceId: last, orient: 0, q, r });
return s;
};
let s = end('remaining', 'p1');
expect(s.phase).toBe('finished');
expect(s.result!.ranking).toEqual([['A'], ['B']]);
expect(s.result!.scores).toEqual({ A: 0, B: 10 });
expect(s.result!.scoreText).toEqual({ A: '모두 놓음', B: '남은 10칸' });
expect(s.result!.summary).toBe('빨강 승리 — 모두 놓음');
s = end('blokusBonus', 'p1');
expect(s.result!.scores).toEqual({ A: 20, B: -10 });
expect(s.result!.scoreText).toEqual({ A: '+20점', B: '−10점' });
s = end('blokusBonus', 'p2');
expect(s.result!.scores.A).toBe(15);
});
test('동점은 공동 순위, 팀전은 팀원 합으로 같은 순위', () => {
let s = make(3);
s.colors[1]!.done = true;
s.colors[1]!.left = ['i3'];
s.colors[2]!.done = true;
s.colors[2]!.left = ['a3'];
s.colors[0]!.left = ['p1', 'p2', 'c3'];
s = act(s, 'A', { type: 'place', pieceId: 'p1', orient: 0, q: -5, r: -5 });
// red can still place: keep going until red is blocked or done
expect(s.phase).toBe('playing');
s.colors[0]!.done = true;
s.colors[0]!.left = ['p2', 'p1'];
s.colors[1]!.done = false;
s.colors[1]!.left = ['p1'];
s.turn = 1;
s = act(s, 'B', { type: 'place', pieceId: 'p1', orient: 0, q: 10, r: -5 });
expect(s.phase).toBe('finished');
// A 3칸, B 0칸, C 3칸 → B 1등, A·C 공동 2등.
expect(s.result!.ranking).toEqual([['B'], ['A', 'C']]);
let t = make(4, { teams: 'pairs' }); // A·C vs B·D
t.colors[0]!.left = ['p1'];
for (const [k, left] of [[1, ['i5']], [2, ['i3']], [3, []]] as [number, PieceId[]][]) {
t.colors[k]!.done = true;
t.colors[k]!.left = left;
}
t = act(t, 'A', { type: 'place', pieceId: 'p1', orient: 0, q: -9, r: -3 });
expect(t.result!.teams).toEqual([{ members: ['A', 'C'], total: 3 }, { members: ['B', 'D'], total: 5 }]);
expect(t.result!.ranking).toEqual([['A', 'C'], ['B', 'D']]);
expect(t.result!.summary).toBe('빨강·초록 팀 승리 — 남은 합계 3칸');
});
});
describe('5명 장애물 (4장 3.)', () => {
test('auto: 장애물 15개, 맨 바깥 칸 없음, 두 번째 줄 1칸 이상, 구역마다 3개, 겹침 없음', () => {
const n = playoutSeeds(1000);
for (let i = 1; i <= n; i++) {
const s = gemblo.setup({ players: IDS.slice(0, 5), options: gemblo.defaultOptions, rng: rng(i), now: 0 });
const obs = s.placements.filter((p) => p.kind === 'obstacle');
expect(obs).toHaveLength(15);
expect(obs.map((p) => p.pieceId).sort()).toEqual([...OBSTACLE_POOL].sort());
const sectors = [0, 0, 0, 0, 0];
const covered = new Set<number>();
for (const p of obs) {
expect(p.cells.some((c) => OUTER[c])).toBe(false);
expect(p.cells.some((c) => SECOND[c])).toBe(true);
for (const c of p.cells) {
expect(covered.has(c)).toBe(false);
covered.add(c);
}
sectors[obstacleSector(p.cells)]!++;
}
expect(sectors).toEqual([3, 3, 3, 3, 3]);
expect(s.phase).toBe('playing');
}
});
test('draft: 고르기 3바퀴 → 놓기 순서, 조건 위반 거부, 마지막에 놓은 사람이 시작', () => {
let s = make(5, { fivePlayerObstacles: 'draft' });
expect(s.phase).toBe('obstacleDraft');
const pickers: string[] = [];
while (s.phase === 'obstacleDraft') {
const who = s.players[s.obstacle!.seat]!;
pickers.push(who);
expect(gemblo.validate(s, who === 'A' ? 'B' : 'A', { type: 'pickObstacle', pieceId: s.obstacle!.pool[0]! }).ok).toBe(false);
s = act(s, who, { type: 'pickObstacle', pieceId: s.obstacle!.pool[0]! });
}
expect(pickers.join('')).toBe('ABCDEABCDEABCDE');
expect(Object.values(s.obstacle!.hands).map((h) => h.length)).toEqual([3, 3, 3, 3, 3]);
expect(s.phase).toBe('obstaclePlace');
expect(s.players[s.obstacle!.seat]).toBe('A');
const hand = s.obstacle!.hands.A!;
// 맨 바깥 칸에 걸치면 거부.
const v = gemblo.validate(s, 'A', { type: 'placeObstacle', pieceId: hand[0]!, orient: 0, q: -7, r: -7 });
expect(v.ok).toBe(false);
const placers: string[] = [];
while (s.phase === 'obstaclePlace') {
const who = s.players[s.obstacle!.seat]!;
placers.push(who);
const legal = gemblo.legalActions!(s, who);
expect(legal.length).toBeGreaterThan(0);
s = act(s, who, legal[0]!);
}
expect(s.phase).toBe('playing');
const last = s.obstacle!.lastPlacer!;
expect(placers.at(-1)).toBe(last);
expect(turnOwner(s)).toBe(last);
expect(s.placements.filter((p) => p.kind === 'obstacle').length + s.history.filter((m) => m.kind === 'obstacle' && m.seq === null).length).toBe(15);
});
test('none: 장애물 없이 판 전체', () => {
const s = make(5, { fivePlayerObstacles: 'none' });
expect(s.placements).toHaveLength(0);
expect(s.phase).toBe('playing');
});
});
test('금색 방해 블록: 개수, 가운데 거리 7 이내, 시작점과 거리 6 이상, 서로 안 닿음', () => {
for (const [n, opts] of [[6, {}], [2, { twoPlayerMode: 'duo' }], [3, {}], [4, {}]] as [number, Partial<GembloOptions>][]) {
for (let seed = 1; seed <= 5; seed++) {
const s = make(n, { ...opts, neutralBlocks: 6 }, seed);
const gold = s.placements.filter((p) => p.kind === 'neutral');
expect(gold).toHaveLength(6);
for (const p of gold) {
for (const c of p.cells) {
expect(IN_LAYOUT[s.layout][c]).toBe(1);
expect(hexDistance(CELLS[c]!, { q: 0, r: 0 })).toBeLessThanOrEqual(7);
// 듀오는 시작점이 가운데에서 4칸이라 자리가 모자라면 거리를 줄여 놓는다(서비스 규칙).
for (const col of s.colors) expect(hexDistance(CELLS[c]!, col.start)).toBeGreaterThanOrEqual(s.layout === 'duo' ? 3 : 6);
for (let k = 0; k < 6; k++) {
const nb = NEIGH[c * 6 + k]!;
if (nb >= 0 && s.board[nb]! >= 0) expect(s.board[nb]).toBe(p.seq);
}
}
}
}
}
});
describe('시간 초과 (8.5)', () => {
test('autoPlace: 가장 큰 블록을 합법하게, 같은 시드 같은 결과, 연속 한도를 넘으면 그 사람 색 모두 끝남', () => {
let s = make(2, { twoPlayerMode: 'duo' });
const a = gemblo.apply(s, 'A', { type: 'timeout' }, { rng: rng(4), now: 61_000 }).state;
const b = gemblo.apply(s, 'A', { type: 'timeout' }, { rng: rng(4), now: 61_000 }).state;
expect(a).toEqual(b);
const p = a.placements[0]!;
expect(p.auto).toBe(true);
expect(p.cells).toHaveLength(5);
expect(p.cells).toContain(cellAt(-4, 2));
expect(a.streak.A).toBe(1);
s = a;
s = act(s, 'B', { type: 'timeout' }, 2000);
s = act(s, 'A', { type: 'timeout' }, 3000); // streak 2 (limit)
expect(s.streak.A).toBe(2);
s = act(s, 'B', { type: 'place', ...(gemblo.legalActions!(s, 'B')[0] as object) } as GembloAction, 4000);
expect(s.streak.B).toBe(0);
s = act(s, 'A', { type: 'timeout' }, 5000); // third in a row → out
expect(s.phase).toBe('finished');
expect(s.result!.reason).toBe('timeout');
expect(s.result!.ranking).toEqual([['B'], ['A']]);
expect(s.colors[0]!.doneReason).toBe('timeLoss');
});
test('pass는 이번 차례만 넘기고 색은 남음, retire는 바로 끝남', () => {
let s = make(3, { timeoutPolicy: 'pass' });
s = act(s, 'A', { type: 'timeout' });
expect(s.colors[0]!.done).toBe(false);
expect(s.history.at(-1)).toEqual({ kind: 'pass', color: 'red' });
expect(turnOwner(s)).toBe('B');
let t = make(3, { timeoutPolicy: 'retire' });
t = act(t, 'A', { type: 'timeout' });
expect(t.colors[0]!.doneReason).toBe('timeLoss');
expect(t.out).toEqual([{ playerId: 'A', reason: 'timeLoss', at: 1000 }]);
expect(t.phase).toBe('playing');
});
test('fischer: 시간을 다 쓰면 시간패, 남으면 추가 시간', () => {
const tc = { kind: 'fischer' as const, perMoveSec: 60 as const, baseSec: 300 as const, incSec: 5 };
let s = make(2, { twoPlayerMode: 'duo', timeControl: tc });
expect(gemblo.deadline!(s)).toBe(300_000);
const ok = act(s, 'A', { type: 'place', pieceId: 'p1', orient: 0, q: -4, r: 2 }, 10_000);
expect(ok.clock.remainingMs.A).toBe(295_000);
s = act(s, 'A', { type: 'place', pieceId: 'p1', orient: 0, q: -4, r: 2 }, 301_000);
expect(s.phase).toBe('finished');
expect(s.result!.reason).toBe('timeout');
expect(s.placements).toHaveLength(0);
});
test('onTimeout은 모든 단계에서 합법(장애물 고르기·놓기 포함)', () => {
let s = make(5, { fivePlayerObstacles: 'draft' });
for (let k = 0; k < 40 && s.phase !== 'finished'; k++) {
const who = gemblo.timeoutPlayers!(s)[0]!;
const a = gemblo.onTimeout(s, who);
expect(gemblo.validate(s, who, a).ok).toBe(true);
s = gemblo.apply(s, who, a, { rng: rng(k), now: 1000 * k }).state;
if (s.phase === 'playing') break;
}
expect(s.phase).toBe('playing');
expect(s.placements.filter((p) => p.kind === 'obstacle').length).toBeGreaterThan(10);
});
});
describe('무르기·기권', () => {
test('전원 수락 시 배치와 그 뒤 자동 colorOut을 함께 되돌림', () => {
let s = make(3, { undo: '1' });
put(s, 'gold', [[10, -5]]); // yellow can't start
s.colors[1]!.placed = 0;
s = act(s, 'A', { type: 'place', pieceId: 'i5', orient: 0, q: -5, r: -5 });
expect(s.colors[1]!.done).toBe(true);
expect(turnOwner(s)).toBe('C');
s = act(s, 'A', { type: 'requestUndo' });
expect(gemblo.activePlayers(s).sort()).toEqual(['B', 'C']);
s = act(s, 'B', { type: 'respondUndo', accept: true });
expect(s.placements).toHaveLength(2); // C has not answered yet
s = act(s, 'C', { type: 'respondUndo', accept: true });
expect(s.placements).toHaveLength(1);
expect(s.colors[0]!.left).toEqual([...PIECE_IDS]);
expect(s.colors[0]!.placed).toBe(0);
expect(s.colors[1]!.done).toBe(false);
expect(s.history.filter((m) => m.kind !== 'obstacle')).toEqual([]);
expect(turnOwner(s)).toBe('A');
expect(s.board[cellAt(-5, -5)]).toBe(-1);
expect(gemblo.validate(s, 'A', { type: 'requestUndo' }).ok).toBe(false); // used up / nothing to undo
});
test('다음 색이 놓은 뒤에는 요청 불가, 무르기 끔이면 불가', () => {
let s = make(2, { twoPlayerMode: 'duo', undo: '3' });
s = act(s, 'A', { type: 'place', pieceId: 'p1', orient: 0, q: -4, r: 2 });
expect(gemblo.validate(s, 'A', { type: 'requestUndo' }).ok).toBe(true);
expect(gemblo.validate(s, 'B', { type: 'requestUndo' }).ok).toBe(false);
s = act(s, 'B', { type: 'place', pieceId: 'p1', orient: 0, q: 4, r: -2 });
expect(gemblo.validate(s, 'A', { type: 'requestUndo' })).toEqual({ ok: false, reason: '방금 내가 놓은 블록만, 다음 색이 놓기 전에 무를 수 있어요.' });
const off = act(make(2, { twoPlayerMode: 'duo' }), 'A', { type: 'place', pieceId: 'p1', orient: 0, q: -4, r: 2 });
expect(gemblo.validate(off, 'A', { type: 'requestUndo' })).toEqual({ ok: false, reason: '이 방은 무르기를 쓰지 않아요.' });
});
test('기권: 색 끝남, 순위 맨 아래, 2명이면 상대 승', () => {
let s = make(3);
s = act(s, 'B', { type: 'resign' });
expect(s.colors[1]!.doneReason).toBe('resign');
expect(s.phase).toBe('playing');
s = act(s, 'A', { type: 'place', pieceId: 'i5', orient: 0, q: -5, r: -5 });
expect(turnOwner(s)).toBe('C');
s = act(s, 'C', { type: 'resign' });
expect(s.phase).toBe('finished');
expect(s.result!.ranking).toEqual([['A'], ['C'], ['B']]);
expect(s.result!.reason).toBe('resign');
const t = act(make(2), 'B', { type: 'resign' });
expect(t.result!.ranking).toEqual([['A'], ['B']]);
expect(t.result!.summary).toBe('노랑·파랑 기권으로 빨강·초록 승리');
expect(gemblo.onLeave!(make(2), 'A')).toEqual({ type: 'resign' });
});
});
describe('정보·화면 계산', () => {
test('차례 아닌 사람·관전자 view에 legal 없음', () => {
const s = make(3);
expect(gemblo.view(s, 'A').legal).toEqual({ bridgePoints: [cellAt(-5, -5)], placeable: [...PIECE_IDS] });
expect(gemblo.view(s, 'B').legal).toBeNull();
expect(gemblo.view(s, null).legal).toBeNull();
expect(gemblo.secretsOf!(s, 'A')).toEqual([]);
});
test('클라이언트 판정(placementRefusal on view)과 validate가 무작위 배치 1만 개에서 같음', () => {
let s = make(4, { neutralBlocks: 3 });
const r = rng(77);
for (let k = 0; k < 24; k++) {
const legal = gemblo.legalActions!(s, turnOwner(s));
s = act(s, turnOwner(s), legal[r.int(legal.length)]!);
}
const v: GembloView = gemblo.view(s, turnOwner(s));
const c = v.colors[v.turn]!;
const pts = v.legal!.bridgePoints;
let same = 0;
let oks = 0;
for (let k = 0; k < 10_000; k++) {
const id = PIECE_IDS[r.int(18)]!;
const o = r.int(12);
const base = k % 2 ? CELLS[pts[r.int(pts.length)]!]! : CELLS[r.int(CELLS.length)]!;
const q = base.q + r.int(5) - 2;
const rr = base.r + r.int(5) - 2;
const client = placementRefusal(v, c, id, o, q, rr, v.allowFlip);
const server = gemblo.validate(s, turnOwner(s), { type: 'place', pieceId: id, orient: o, q, r: rr });
if ((client === null) === server.ok && (server.ok || server.reason === client)) same++;
if (server.ok) oks++;
}
expect(same).toBe(10_000);
expect(oks).toBeGreaterThan(50);
});
test('legalPlacements는 같은 칸 집합을 한 번만, 모두 validate 통과', () => {
let s = make(6);
const r = rng(5);
for (let k = 0; k < 30 && s.phase === 'playing'; k++) {
const legal = legalPlacements(board(s), s.colors[s.turn]!, true);
const keys = legal.map((p) => [...p.cells].sort((a, b) => a - b).join(','));
expect(new Set(keys).size).toBe(keys.length);
for (const p of legal) expect(placementCells(p.pieceId, p.orient, p.q, p.r)).toEqual(p.cells);
const pick = legal[r.int(legal.length)]!;
s = act(s, turnOwner(s), { type: 'place', pieceId: pick.pieceId, orient: pick.orient, q: pick.q, r: pick.r });
}
});
});
describe('무작위 대국 (09 §7)', () => {
const MODES: [number, Partial<GembloOptions>][] = [
[2, {}],
[2, { twoPlayerMode: 'threeColors' }],
[2, { twoPlayerMode: 'duo', bridgeRule: 'free' }],
[3, {}],
[3, { threePlayerMode: 'twoColors', allowFlip: false }],
[4, { teams: 'pairs', scoring: 'blokusBonus' }],
[5, {}],
[5, { fivePlayerObstacles: 'draft' }],
[5, { fivePlayerObstacles: 'none', neutralBlocks: 6 }],
[6, { teams: 'triples' }],
[6, { undo: '3', timeoutPolicy: 'pass' }],
];
test('2~6명 모든 모드가 끝까지(JSON 왕복·결정성·apply 5ms·legalActions 10ms)', () => {
const games = Math.max(MODES.length, playoutSeeds(400));
let worstLegal = 0;
for (let i = 0; i < games; i++) {
const [n, extra] = MODES[i % MODES.length]!;
const options = gemblo.optionsSchema.parse(extra);
const players = IDS.slice(0, n);
const colorsCount = gemblo.setup({ players, options, rng: rng(1), now: 0 }).colors.length;
const inv = (st: unknown) => {
const s = st as GembloState;
const t0 = performance.now();
if (s.phase !== 'finished') gemblo.legalActions!(s, gemblo.activePlayers(s)[0]!);
worstLegal = Math.max(worstLegal, performance.now() - t0);
// Board and placements agree.
const cells = s.board.filter((x) => x >= 0).length;
expect(cells).toBe(s.placements.reduce((m, p) => m + p.cells.length, 0));
for (const c of s.colors) expect(c.left.length + c.placed).toBe(18);
};
const rep = randomPlayout(gemblo, { players, options, seed: seedN(500 + i), invariant: inv, maxSteps: colorsCount * 18 + colorsCount + 40 });
expect(rep.finished).toBe(true);
if (i % 4 === 0) {
const again = randomPlayout(gemblo, { players, options, seed: seedN(500 + i), maxSteps: 2000 });
expect(JSON.stringify(again.finalState)).toBe(JSON.stringify(rep.finalState));
}
expect(gemblo.result(rep.finalState as GembloState)).not.toBeNull();
}
expect(worstLegal).toBeLessThan(10);
}, 120_000);
});

View File

@@ -0,0 +1,794 @@
/** 젬블로 (docs/games/gemblo.md). 육각형 보석 블록 땅따먹기: 같은 색과 닿지 않게, 선으로 한 칸 떨어진 곳에 잇기. */
import { z } from 'zod';
import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine';
import {
CELLS,
CELL_COUNT,
COLORS,
COLOR_KO,
IN_LAYOUT,
NEIGH,
ORIENTS,
PIECE_IDS,
PIECE_SIZE,
STARTS,
cellAt,
cellsOf,
hasAnyPlacement,
hexDistance,
legalPlacements,
linkPoints,
obstaclePlacements,
obstacleRefusal,
obstacleSector,
placeablePieces,
placementCells,
placementRefusal,
type BoardInput,
type ColorId,
type Hex,
type Layout,
type PieceId,
type Placement,
} from './board';
import { gembloOptionsSchema, type GembloOptions } from './options';
import { gembloActionSchema, type DoneReason, type GembloAction, type GembloColor, type GembloMove, type GembloResult, type GembloState, type GembloView } from './types';
export * from './board';
export * from './types';
export { gembloOptionsSchema, type GembloOptions } from './options';
/** 5인 장애물: 남는 색에서 p1·p2·a3을 뺀 15개. */
export const OBSTACLE_POOL: readonly PieceId[] = PIECE_IDS.filter((id) => id !== 'p1' && id !== 'p2' && id !== 'a3');
const NEUTRAL_PIECES: readonly PieceId[] = ['p1', 'p2', 'i3', 'a3', 'c3'];
/** 장애물 고르기·놓기 한 번의 제한 시간(고정). */
export const OBSTACLE_TURN_MS = 60_000;
// ---------------------------------------------------------------- setup helpers
export interface GembloMode {
layout: Layout;
starts: readonly Hex[];
/** Seat index owning each colour, in turn order. */
owners: number[];
}
/** 4장 표: 인원·옵션별 판, 시작점, 색 배분. */
export function modeFor(n: number, o: GembloOptions): GembloMode {
switch (n) {
case 2:
if (o.twoPlayerMode === 'duo') return { layout: 'duo', starts: STARTS.duo, owners: [0, 1] };
if (o.twoPlayerMode === 'threeColors') return { layout: 'full', starts: STARTS.six, owners: [0, 1, 0, 1, 0, 1] };
return { layout: 'four', starts: STARTS.four, owners: [0, 1, 0, 1] };
case 3:
return o.threePlayerMode === 'twoColors' ? { layout: 'full', starts: STARTS.six, owners: [0, 1, 2, 0, 1, 2] } : { layout: 'three', starts: STARTS.three, owners: [0, 1, 2] };
case 4:
return { layout: 'four', starts: STARTS.four, owners: [0, 1, 2, 3] };
case 5:
return { layout: 'full', starts: STARTS.five, owners: [0, 1, 2, 3, 4] };
case 6:
return { layout: 'full', starts: STARTS.six, owners: [0, 1, 2, 3, 4, 5] };
}
throw new Error(`gemblo: ${n} players`);
}
export function playerCountError(o: GembloOptions, n: number): string | null {
if (n < 2 || n > 6) return '2~6명이 필요해요.';
if (o.teams === 'pairs' && n !== 4 && n !== 6) return '팀전(2명씩)은 4명 또는 6명일 때만 돼요.';
if (o.teams === 'triples' && n !== 6) return '팀전(3명씩)은 6명일 때만 돼요.';
return null;
}
/** 팀은 자리로 정한다: 4명 대각선 모서리, 6명 pairs 마주 보는 꼭짓점, triples 한 칸 건너. */
function teamsFor(o: GembloOptions, seats: PlayerId[]): PlayerId[][] | null {
if (o.teams === 'off') return null;
if (seats.length === 4) return [[seats[0]!, seats[2]!], [seats[1]!, seats[3]!]];
if (o.teams === 'pairs') return [0, 1, 2].map((k) => [seats[k]!, seats[k + 3]!]);
return [[seats[0]!, seats[2]!, seats[4]!], [seats[1]!, seats[3]!, seats[5]!]];
}
const boardOf = (s: GembloState): BoardInput => ({ layout: s.layout, board: s.board, placements: s.placements, bridgeRule: s.options.bridgeRule });
const flipOf = (s: GembloState) => s.options.allowFlip;
function addBlock(s: GembloState, p: Placement, color: GembloState['placements'][number]['color'], kind: 'play' | 'obstacle' | 'neutral', auto: boolean): number {
const seq = s.placements.length;
for (const c of p.cells) {
if (s.board[c] !== -1) throw new Error('gemblo: cell already covered');
s.board[c] = seq;
}
s.placements.push({ seq, color, pieceId: p.pieceId, orient: p.orient, cells: [...p.cells], auto, kind });
return seq;
}
/** 4장 4.: 가운데(거리 7 이내)에 서로 안 닿는 금색 블록, 시작점에서 거리 6 이상. */
function placeNeutral(s: GembloState, count: number, rng: Rng): void {
const starts = s.colors.map((c) => c.start);
const inL = IN_LAYOUT[s.layout];
const center = { q: 0, r: 0 };
let gap = 6;
const fits = (i: number) => {
if (!inL[i] || s.board[i] !== -1) return false;
const h = CELLS[i]!;
if (hexDistance(h, center) > 7 || starts.some((st) => hexDistance(h, st) < gap)) return false;
for (let k = 0; k < 6; k++) {
const n = NEIGH[i * 6 + k]!;
if (n >= 0 && s.board[n] !== -1) return false;
}
return true;
};
for (let k = 0; k < count; k++) {
const id = NEUTRAL_PIECES[rng.int(NEUTRAL_PIECES.length)]!;
// 서비스 규칙: 자리가 모자라면(듀오 판처럼 시작점이 가운데에 가까울 때) 시작점과의 거리를 한 칸씩 줄여 본다.
for (gap = 6; gap >= 3; gap--) {
const cands: Placement[] = [];
for (let i = 0; i < CELL_COUNT; i++) {
if (!fits(i)) continue;
for (const { o } of ORIENTS[id]) {
const cells = placementCells(id, o, CELLS[i]!.q, CELLS[i]!.r);
if (cells && cells.every(fits)) cands.push({ pieceId: id, orient: o, q: CELLS[i]!.q, r: CELLS[i]!.r, cells });
}
}
if (cands.length) {
addBlock(s, cands[rng.int(cands.length)]!, 'gold', 'neutral', true);
break;
}
}
}
}
/** 5명 auto: 15개를 섞어 구역마다 3개씩, 조건을 지키는 자리 중 무작위(모든 후보를 세어 고르므로 실패가 없다). */
function placeObstaclesAuto(s: GembloState, rng: Rng): void {
const ob = s.obstacle!;
const order = rng.shuffle([...OBSTACLE_POOL]);
order.forEach((id, k) => {
const sector = k % 5;
const cands = obstaclePlacements(boardOf(s), [id], ob.sectorCount, sector);
if (!cands.length) {
s.history.push({ kind: 'obstacle', by: null, pieceId: id, seq: null });
return;
}
const p = cands[rng.int(cands.length)]!;
const seq = addBlock(s, p, 'gold', 'obstacle', true);
ob.sectorCount[sector]!++;
s.history.push({ kind: 'obstacle', by: null, pieceId: id, seq });
});
}
// ---------------------------------------------------------------- turn flow
const isOut = (s: GembloState, p: PlayerId) => s.out.some((x) => x.playerId === p);
const undoLimit = (o: GembloOptions) => (o.undo === 'off' ? 0 : Number(o.undo));
const respondersOf = (s: GembloState, by: PlayerId) => s.players.filter((p) => p !== by && !isOut(s, p));
export function turnPlayer(s: GembloState): PlayerId | null {
if (s.phase === 'playing') return s.colors[s.turn]!.owner;
if (s.phase === 'obstacleDraft' || s.phase === 'obstaclePlace') return s.players[s.obstacle!.seat]!;
return null;
}
function markDone(s: GembloState, i: number, reason: DoneReason, events: GameEvent[]): void {
const c = s.colors[i]!;
if (c.done) return;
c.done = true;
c.doneReason = reason;
const leftCells = cellsOf(c.left);
s.history.push({ kind: 'out', color: c.color, leftCells, reason });
events.push({ type: 'colorOut', color: c.color, leftCells, reason });
}
/** Next colour after `from` that can still place; colours with nowhere to go are out for good (5.5). Returns those. */
function advance(s: GembloState, from: number, now: number, events: GameEvent[]): number[] {
const n = s.colors.length;
const outs: number[] = [];
const b = boardOf(s);
for (let step = 1; step <= n; step++) {
const i = (from + step) % n;
const c = s.colors[i]!;
if (c.done) continue;
if (hasAnyPlacement(b, c, flipOf(s))) {
s.turn = i;
s.turnStartedAt = now;
return outs;
}
markDone(s, i, 'blocked', events);
outs.push(i);
}
finish(s, 'normal', events);
return outs;
}
function placeColor(s: GembloState, i: number, p: Placement, auto: boolean, now: number, events: GameEvent[]): void {
const c = s.colors[i]!;
const leftIndex = c.left.indexOf(p.pieceId);
if (leftIndex < 0) throw new Error('gemblo: piece already used');
const seq = addBlock(s, p, c.color, 'play', auto);
const historyLength = s.history.length;
c.left.splice(leftIndex, 1);
c.placed++;
c.lastPiece = p.pieceId;
s.history.push({ kind: 'place', color: c.color, pieceId: p.pieceId, seq, auto });
s.undo.pending = null;
events.push({ type: 'placed', color: c.color, pieceId: p.pieceId, cells: p.cells, auto });
const allPlaced = c.left.length === 0;
if (allPlaced) markDone(s, i, 'allPlaced', events);
const outs = advance(s, i, now, events);
s.undo.last = !auto && s.phase === 'playing' ? { by: c.owner, color: i, seq, leftIndex, outs, historyLength, allPlaced } : null;
}
/** 무르기 수락: 그 배치 하나와 그 뒤 자동 colorOut을 되돌린다. */
function rewind(s: GembloState, now: number): void {
const last = s.undo.last!;
const p = s.placements.pop()!;
if (p.seq !== last.seq) throw new Error('gemblo: undo record mismatch');
for (const cell of p.cells) s.board[cell] = -1;
const c = s.colors[last.color]!;
c.left.splice(last.leftIndex, 0, p.pieceId);
c.placed--;
const prev = [...s.placements].reverse().find((x) => x.color === c.color);
c.lastPiece = prev ? prev.pieceId : null;
if (last.allPlaced) {
c.done = false;
c.doneReason = null;
}
for (const k of last.outs) {
s.colors[k]!.done = false;
s.colors[k]!.doneReason = null;
}
s.history.length = last.historyLength;
if (s.options.timeControl.kind === 'fischer') {
const thinker = s.colors[s.turn]!.owner;
s.clock.remainingMs[thinker] = Math.max(0, s.clock.remainingMs[thinker]! - (now - s.turnStartedAt));
}
s.turn = last.color;
s.turnStartedAt = now;
s.undo.usedBy[last.by] = (s.undo.usedBy[last.by] ?? 0) + 1;
s.undo.last = null;
s.undo.pending = null;
}
function chargeClock(s: GembloState, p: PlayerId, now: number): boolean {
if (s.options.timeControl.kind !== 'fischer') return true;
const left = s.clock.remainingMs[p]! - (now - s.turnStartedAt);
if (left <= 0) {
s.clock.remainingMs[p] = 0;
return false;
}
s.clock.remainingMs[p] = left + s.options.timeControl.incSec * 1000;
return true;
}
/** Remaining people (or teams) still in the game. */
function aliveSides(s: GembloState): number {
const alive = s.players.filter((p) => !isOut(s, p));
if (!s.teams) return alive.length;
return s.teams.filter((t) => t.some((p) => alive.includes(p))).length;
}
/** 기권·시간패: 그 사람의 색은 바로 끝남. 남은 사람(팀)이 하나 이하면 종료. */
function retire(s: GembloState, p: PlayerId, reason: 'resign' | 'timeLoss', now: number, events: GameEvent[]): void {
if (isOut(s, p)) return;
s.out.push({ playerId: p, reason, at: now });
events.push({ type: 'playerOut', player: p, reason });
s.undo.pending = null;
s.undo.last = null;
s.colors.forEach((c, i) => {
if (c.owner === p && !c.done) markDone(s, i, reason, events);
});
if (aliveSides(s) <= 1) {
finish(s, reason, events);
return;
}
if (s.phase === 'playing') {
if (s.colors[s.turn]!.done) advance(s, s.turn, now, events);
return;
}
const ob = s.obstacle!;
const hand = ob.hands[p] ?? [];
if (s.phase === 'obstacleDraft') {
ob.pool.push(...hand);
ob.hands[p] = [];
if (s.players[ob.seat] === p) nextPicker(s, now, events);
} else {
// The leaver's picks are not placed (their hand is dropped); everybody else still places theirs.
ob.hands[p] = [];
for (const id of hand) s.history.push({ kind: 'obstacle', by: p, pieceId: id, seq: null });
if (s.players[ob.seat] === p) nextPlacer(s, ob.seat, now, events);
}
}
// ---------------------------------------------------------------- 5인 draft
function nextAliveSeat(s: GembloState, from: number): number {
const n = s.players.length;
for (let k = 1; k <= n; k++) {
const i = (from + k) % n;
if (!isOut(s, s.players[i]!)) return i;
}
return from;
}
function nextPicker(s: GembloState, now: number, events: GameEvent[]): void {
const ob = s.obstacle!;
s.turnStartedAt = now;
if (ob.pool.length === 0) {
s.phase = 'obstaclePlace';
// 놓기는 첫 자리부터 차례로.
nextPlacer(s, s.players.length - 1, now, events);
return;
}
ob.seat = nextAliveSeat(s, ob.seat);
}
/** Next seat after `from` with a block in hand that fits somewhere; hands that can't be placed are dropped. */
function nextPlacer(s: GembloState, from: number, now: number, events: GameEvent[]): void {
const ob = s.obstacle!;
const n = s.players.length;
s.turnStartedAt = now;
for (let round = 0; round < 2 * n + 1; round++) {
for (let k = 1; k <= n; k++) {
const i = (from + k) % n;
const p = s.players[i]!;
const hand = ob.hands[p] ?? [];
if (!hand.length || isOut(s, p)) continue;
if (obstaclePlacements(boardOf(s), hand, ob.sectorCount, undefined, 1).length) {
ob.seat = i;
return;
}
for (const id of hand) s.history.push({ kind: 'obstacle', by: p, pieceId: id, seq: null });
events.push({ type: 'obstacleDropped', player: p, pieces: hand });
ob.hands[p] = [];
}
}
startPlaying(s, now, events);
}
function startPlaying(s: GembloState, now: number, events: GameEvent[]): void {
const ob = s.obstacle;
s.phase = 'playing';
let first = 0;
if (ob?.lastPlacer) {
const k = s.colors.findIndex((c) => c.owner === ob.lastPlacer);
if (k >= 0) first = k;
}
s.turnStartedAt = now;
const c = s.colors[first]!;
if (!c.done && hasAnyPlacement(boardOf(s), c, flipOf(s))) s.turn = first;
else advance(s, first, now, events);
}
// ---------------------------------------------------------------- automatic moves
/** autoPlace: 가장 큰 블록 → 놓은 뒤 이음점이 가장 많은 배치(같으면 RNG). */
export function autoPlacement(s: GembloState, i: number, rng: Rng | null): Placement | null {
const c = s.colors[i]!;
const b = boardOf(s);
const all = legalPlacements(b, c, flipOf(s));
if (!all.length) return null;
const top = Math.max(...all.map((p) => PIECE_SIZE[p.pieceId]));
const big = all.filter((p) => PIECE_SIZE[p.pieceId] === top);
let best = -1;
let pool: Placement[] = [];
const board = [...s.board];
const seq = s.placements.length;
for (const p of big) {
for (const cell of p.cells) board[cell] = seq;
const tmp: BoardInput = { ...b, board, placements: [...s.placements, { color: c.color, cells: p.cells }] };
const n = linkPoints(tmp, { ...c, placed: c.placed + 1 }).length;
for (const cell of p.cells) board[cell] = -1;
if (n > best) {
best = n;
pool = [p];
} else if (n === best) pool.push(p);
}
return rng ? pool[rng.int(pool.length)]! : pool[0]!;
}
function randomObstacle(s: GembloState, p: PlayerId, rng: Rng): Placement | null {
const ob = s.obstacle!;
const cands = obstaclePlacements(boardOf(s), ob.hands[p] ?? [], ob.sectorCount);
return cands.length ? cands[rng.int(cands.length)]! : null;
}
function doPlaceObstacle(s: GembloState, p: PlayerId, pl: Placement, now: number, events: GameEvent[]): void {
const ob = s.obstacle!;
const hand = ob.hands[p]!;
hand.splice(hand.indexOf(pl.pieceId), 1);
const sector = obstacleSector(pl.cells);
const seq = addBlock(s, pl, 'gold', 'obstacle', false);
ob.sectorCount[sector]!++;
ob.lastPlacer = p;
s.history.push({ kind: 'obstacle', by: p, pieceId: pl.pieceId, seq });
events.push({ type: 'obstaclePlaced', player: p, pieceId: pl.pieceId, cells: pl.cells });
nextPlacer(s, ob.seat, now, events);
}
// ---------------------------------------------------------------- result (6장)
export function colorScore(o: GembloOptions, c: GembloColor): number {
const left = cellsOf(c.left);
if (o.scoring === 'remaining') return left;
const bonus = c.left.length === 0 ? (c.lastPiece === 'p1' ? 20 : 15) : 0;
return bonus - left;
}
const scoreLabel = (o: GembloOptions, n: number) =>
o.scoring === 'remaining' ? (n === 0 ? '모두 놓음' : `남은 ${n}칸`) : `${n > 0 ? '+' : n < 0 ? '−' : ''}${Math.abs(n)}점`;
function finish(s: GembloState, why: 'normal' | 'resign' | 'timeLoss', events: GameEvent[]): void {
if (s.phase === 'finished') return;
s.phase = 'finished';
s.undo.pending = null;
s.undo.last = null;
const o = s.options;
const better = (a: number, b: number) => (o.scoring === 'remaining' ? a - b : b - a);
const scores: Record<PlayerId, number> = {};
for (const p of s.players) scores[p] = 0;
for (const c of s.colors) scores[c.owner]! += colorScore(o, c);
const outAt = (p: PlayerId) => s.out.findIndex((x) => x.playerId === p);
const ranking: PlayerId[][] = [];
const colorsOf = (ps: PlayerId[]) => s.colors.filter((c) => ps.includes(c.owner)).map((c) => COLOR_KO[c.color]).join('·');
let teamsOut: GembloResult['teams'];
if (s.teams) {
teamsOut = s.teams.map((members) => ({ members, total: members.reduce((n, p) => n + scores[p]!, 0) }));
const alive = teamsOut.filter((t) => t.members.some((p) => outAt(p) < 0));
const dead = teamsOut.filter((t) => !alive.includes(t)).sort((a, b) => Math.max(...b.members.map(outAt)) - Math.max(...a.members.map(outAt)));
const totals = [...new Set(alive.map((t) => t.total))].sort(better);
for (const v of totals) ranking.push(alive.filter((t) => t.total === v).flatMap((t) => t.members));
for (const t of dead) ranking.push([...t.members]);
} else {
const alive = s.players.filter((p) => outAt(p) < 0);
const totals = [...new Set(alive.map((p) => scores[p]!))].sort(better);
for (const v of totals) ranking.push(alive.filter((p) => scores[p] === v));
for (const p of s.players.filter((x) => outAt(x) >= 0).sort((a, b) => outAt(b) - outAt(a))) ranking.push([p]);
}
const winners = ranking[0] ?? [];
const top = s.teams ? (teamsOut!.find((t) => t.members.includes(winners[0]!))?.total ?? 0) : (scores[winners[0]!] ?? 0);
const amount = o.scoring === 'remaining' ? (top === 0 ? '모두 놓음' : `남은 ${s.teams ? '합계 ' : ''}${top}칸`) : `${s.teams ? '합계 ' : ''}${scoreLabel(o, top)}`;
let summary: string;
if (why !== 'normal') {
const last = s.out[s.out.length - 1]!;
summary = `${colorsOf([last.playerId])} ${why === 'resign' ? '기권' : '시간패'}으로 ${colorsOf(winners)}${s.teams ? ' 팀' : ''} 승리`;
} else if (s.teams) {
const tied = teamsOut!.filter((t) => t.total === top && t.members.some((p) => outAt(p) < 0));
summary = tied.length > 1 ? `${tied.map((t) => colorsOf(t.members)).join(', ')} 팀 공동 1등 — ${amount}` : `${colorsOf(winners)} 팀 승리 — ${amount}`;
} else {
summary = winners.length > 1 ? `${winners.map((p) => colorsOf([p])).join(', ')} 공동 1등 — ${amount}` : `${colorsOf(winners)} 승리 — ${amount}`;
}
s.result = {
ranking,
scores,
scoreText: Object.fromEntries(s.players.map((p) => [p, scoreLabel(o, scores[p]!)])),
perColor: s.colors.map((c) => ({
color: c.color,
owner: c.owner,
leftCells: cellsOf(c.left),
leftPieces: [...c.left],
allPlaced: c.left.length === 0,
bonus: c.left.length === 0 ? (c.lastPiece === 'p1' ? 20 : 15) : 0,
})),
...(teamsOut ? { teams: teamsOut } : {}),
summary,
reason: why === 'timeLoss' ? 'timeout' : why,
};
events.push({ type: 'gameEnded', ranking, reason: s.result.reason });
}
// ---------------------------------------------------------------- definition
export function setupGemblo(players: PlayerId[], options: GembloOptions, rng: Rng, now: number): GembloState {
const err = playerCountError(options, players.length);
if (err) throw new Error(`gemblo: ${err}`);
const seats = options.seatOrder === 'random' ? rng.shuffle(players) : [...players];
const mode = modeFor(seats.length, options);
const s: GembloState = {
options,
layout: mode.layout,
players: seats,
board: Array.from({ length: CELL_COUNT }, () => -1),
placements: [],
colors: mode.owners.map((seat, k) => ({
color: COLORS[k]!,
owner: seats[seat]!,
start: { ...mode.starts[k]! },
left: [...PIECE_IDS],
placed: 0,
done: false,
doneReason: null,
lastPiece: null,
})),
turn: 0,
phase: 'playing',
obstacle: null,
teams: teamsFor(options, seats),
turnStartedAt: now,
clock: { remainingMs: Object.fromEntries(seats.map((p) => [p, options.timeControl.baseSec * 1000])) },
streak: Object.fromEntries(seats.map((p) => [p, 0])),
history: [],
undo: { usedBy: Object.fromEntries(seats.map((p) => [p, 0])), pending: null, last: null },
out: [],
result: null,
};
if (options.neutralBlocks > 0) placeNeutral(s, options.neutralBlocks, rng);
if (seats.length === 5 && options.fivePlayerObstacles !== 'none') {
s.obstacle = { pool: [...OBSTACLE_POOL], hands: Object.fromEntries(seats.map((p) => [p, []])), sectorCount: [0, 0, 0, 0, 0], seat: 0, lastPlacer: null };
if (options.fivePlayerObstacles === 'auto') {
placeObstaclesAuto(s, rng);
s.obstacle.pool = [];
s.turn = rng.int(5);
} else s.phase = 'obstacleDraft';
}
return s;
}
export const gemblo: GameDefinition<GembloState, GembloAction, GembloView, GembloOptions> = {
id: 'gemblo',
nameKo: '젬블로',
minPlayers: 2,
maxPlayers: 6,
stateVersion: 1,
defaultOptions: gembloOptionsSchema.parse({}),
optionsSchema: gembloOptionsSchema as unknown as z.ZodType<GembloOptions>,
actionSchema: gembloActionSchema as z.ZodType<GembloAction>,
playerCountError,
setup({ players, options, rng, now }) {
return setupGemblo(players, options, rng, now);
},
validate(s, actor, a) {
if (!s.players.includes(actor)) return fail('이 게임의 플레이어가 아니에요.');
if (s.phase === 'finished') return fail('게임이 이미 끝났어요.');
if (isOut(s, actor)) return fail('이미 게임에서 빠졌어요.');
const mine = turnPlayer(s) === actor;
switch (a.type) {
case 'place': {
if (s.phase !== 'playing') return fail('아직 장애물을 놓는 중이에요.');
if (!mine) return fail('지금은 내 차례가 아니에요.');
const why = placementRefusal(boardOf(s), s.colors[s.turn]!, a.pieceId, a.orient, a.q, a.r, flipOf(s));
return why ? fail(why) : ok;
}
case 'pickObstacle':
if (s.phase !== 'obstacleDraft') return fail('지금은 장애물을 고르는 때가 아니에요.');
if (!mine) return fail('지금은 내가 고를 차례가 아니에요.');
return s.obstacle!.pool.includes(a.pieceId) ? ok : fail('이미 누가 고른 블록이에요.');
case 'placeObstacle': {
if (s.phase !== 'obstaclePlace') return fail('지금은 장애물을 놓는 때가 아니에요.');
if (!mine) return fail('지금은 내가 놓을 차례가 아니에요.');
if (!(s.obstacle!.hands[actor] ?? []).includes(a.pieceId)) return fail('내가 고른 블록이 아니에요.');
const cells = placementCells(a.pieceId, a.orient, a.q, a.r);
if (!cells) return fail('판 밖이에요.');
const why = obstacleRefusal(boardOf(s), cells, s.obstacle!.sectorCount);
return why ? fail(why) : ok;
}
case 'timeout':
return mine ? ok : fail('지금은 내 차례가 아니에요.');
case 'requestUndo': {
if (s.options.undo === 'off') return fail('이 방은 무르기를 쓰지 않아요.');
if (s.phase !== 'playing') return fail('지금은 무를 수 없어요.');
if (s.undo.pending) return fail('이미 대기 중인 요청이 있어요.');
if ((s.undo.usedBy[actor] ?? 0) >= undoLimit(s.options)) return fail('무르기 횟수를 다 썼어요.');
if (!s.undo.last || s.undo.last.by !== actor) return fail('방금 내가 놓은 블록만, 다음 색이 놓기 전에 무를 수 있어요.');
return ok;
}
case 'respondUndo': {
const p = s.undo.pending;
if (!p || p.by === actor || p.accepted.includes(actor)) return fail('응답할 무르기 요청이 없어요.');
return ok;
}
case 'cancelUndo':
return s.undo.pending?.by === actor ? ok : fail('취소할 요청이 없어요.');
case 'resign':
return ok;
}
return fail('알 수 없는 행동이에요.');
},
apply(prev, actor, a, { rng, now }) {
const s = structuredClone(prev);
const events: GameEvent[] = [];
switch (a.type) {
case 'place': {
if (!chargeClock(s, actor, now)) {
retire(s, actor, 'timeLoss', now, events);
break;
}
const c = s.colors[s.turn]!;
if (placementRefusal(boardOf(s), c, a.pieceId, a.orient, a.q, a.r, flipOf(s))) throw new Error('gemblo: illegal placement');
s.streak[actor] = 0;
placeColor(s, s.turn, { pieceId: a.pieceId, orient: a.orient, q: a.q, r: a.r, cells: placementCells(a.pieceId, a.orient, a.q, a.r)! }, false, now, events);
break;
}
case 'pickObstacle': {
const ob = s.obstacle!;
ob.pool.splice(ob.pool.indexOf(a.pieceId), 1);
ob.hands[actor]!.push(a.pieceId);
events.push({ type: 'obstaclePicked', player: actor, pieceId: a.pieceId });
nextPicker(s, now, events);
break;
}
case 'placeObstacle':
doPlaceObstacle(s, actor, { pieceId: a.pieceId, orient: a.orient, q: a.q, r: a.r, cells: placementCells(a.pieceId, a.orient, a.q, a.r)! }, now, events);
break;
case 'timeout': {
if (s.phase === 'obstacleDraft') {
const ob = s.obstacle!;
const id = ob.pool[rng.int(ob.pool.length)]!;
ob.pool.splice(ob.pool.indexOf(id), 1);
ob.hands[actor]!.push(id);
events.push({ type: 'obstaclePicked', player: actor, pieceId: id, auto: true });
nextPicker(s, now, events);
break;
}
if (s.phase === 'obstaclePlace') {
const pl = randomObstacle(s, actor, rng);
if (pl) doPlaceObstacle(s, actor, pl, now, events);
else nextPlacer(s, s.obstacle!.seat, now, events);
break;
}
const tc = s.options.timeControl.kind;
const streak = s.streak[actor] ?? 0;
if (tc === 'fischer' || s.options.timeoutPolicy === 'retire' || streak >= s.options.autoMoveLimit) {
if (tc === 'fischer') s.clock.remainingMs[actor] = 0;
retire(s, actor, 'timeLoss', now, events);
break;
}
s.streak[actor] = streak + 1;
if (s.options.timeoutPolicy === 'pass') {
const c = s.colors[s.turn]!;
s.history.push({ kind: 'pass', color: c.color });
s.undo.pending = null;
s.undo.last = null;
events.push({ type: 'passed', color: c.color });
advance(s, s.turn, now, events);
break;
}
const pl = autoPlacement(s, s.turn, rng);
if (!pl) throw new Error('gemblo: turn colour has no placement');
placeColor(s, s.turn, pl, true, now, events);
break;
}
case 'requestUndo':
s.undo.pending = { by: actor, accepted: [] };
events.push({ type: 'undoRequested', player: actor });
break;
case 'respondUndo': {
const p = s.undo.pending!;
if (!a.accept) {
s.undo.pending = null;
events.push({ type: 'undoDeclined', player: p.by, by: actor });
break;
}
p.accepted.push(actor);
if (respondersOf(s, p.by).every((x) => p.accepted.includes(x))) {
rewind(s, now);
events.push({ type: 'undoAccepted', player: p.by });
} else events.push({ type: 'undoAcceptedBy', player: p.by, by: actor });
break;
}
case 'cancelUndo':
s.undo.pending = null;
events.push({ type: 'undoCancelled', player: actor });
break;
case 'resign':
retire(s, actor, 'resign', now, events);
break;
}
return { state: s, events };
},
view(s, viewer) {
const tp = turnPlayer(s);
const mineTurn = s.phase === 'playing' && viewer !== null && tp === viewer;
const b = boardOf(s);
const c = s.colors[s.turn]!;
const limit = undoLimit(s.options);
const pending = s.undo.pending;
let lastSeq: number | null = null;
for (let k = s.placements.length - 1; k >= 0; k--) {
if (s.placements[k]!.kind === 'play' || s.placements[k]!.kind === 'obstacle') {
lastSeq = s.placements[k]!.seq;
break;
}
}
return {
layout: s.layout,
bridgeRule: s.options.bridgeRule,
allowFlip: s.options.allowFlip,
showHints: s.options.showHints,
scoring: s.options.scoring,
timeControl: s.options.timeControl,
timeoutPolicy: s.options.timeoutPolicy,
board: s.board,
placements: s.placements,
colors: s.colors.map((x) => ({ ...x, leftCells: cellsOf(x.left) })),
players: s.players.map((p) => ({
id: p,
colors: s.colors.flatMap((x, i) => (x.owner === p ? [i] : [])),
out: s.out.find((x) => x.playerId === p)?.reason ?? null,
streak: s.streak[p] ?? 0,
remainingMs: s.clock.remainingMs[p] ?? 0,
team: s.teams ? s.teams.findIndex((t) => t.includes(p)) : null,
})),
teams: s.teams,
turn: s.turn,
turnPlayer: tp,
phase: s.phase,
myColors: viewer === null ? [] : s.colors.flatMap((x, i) => (x.owner === viewer ? [i] : [])),
turnStartedAt: s.turnStartedAt,
history: s.history,
lastSeq,
legal: mineTurn ? { bridgePoints: linkPoints(b, c), placeable: placeablePieces(b, c, flipOf(s)) } : null,
obstacle: s.obstacle && (s.phase === 'obstacleDraft' || s.phase === 'obstaclePlace') ? { ...s.obstacle, remaining: s.obstacle.pool.length + Object.values(s.obstacle.hands).reduce((n, h) => n + h.length, 0) } : null,
undo: {
allowed: s.options.undo !== 'off',
remaining: Object.fromEntries(s.players.map((p) => [p, Math.max(0, limit - (s.undo.usedBy[p] ?? 0))])),
pending,
responders: pending ? respondersOf(s, pending.by) : [],
canRequest: viewer !== null && s.phase === 'playing' && !pending && s.undo.last?.by === viewer && (s.undo.usedBy[viewer] ?? 0) < limit,
},
result: s.result,
};
},
activePlayers(s) {
const tp = turnPlayer(s);
if (!tp) return [];
const out = [tp];
const p = s.undo.pending;
if (p) for (const x of respondersOf(s, p.by)) if (!p.accepted.includes(x) && !out.includes(x)) out.push(x);
return out;
},
deadline(s) {
if (s.phase === 'finished') return null;
if (s.phase !== 'playing') return s.turnStartedAt + OBSTACLE_TURN_MS;
const tc = s.options.timeControl;
if (tc.kind === 'perMove') return s.turnStartedAt + tc.perMoveSec * 1000;
if (tc.kind === 'fischer') return s.turnStartedAt + (s.clock.remainingMs[s.colors[s.turn]!.owner] ?? 0);
return null;
},
timeoutPlayers(s) {
const tp = turnPlayer(s);
return tp ? [tp] : [];
},
onTimeout() {
return { type: 'timeout' };
},
onLeave(s, player) {
if (s.phase === 'finished' || !s.players.includes(player) || isOut(s, player)) return null;
return { type: 'resign' };
},
result(s): GameResult | null {
const r = s.result;
if (!r) return null;
return { ranking: r.ranking, scores: r.scores, scoreText: r.scoreText, summary: r.summary, reason: r.reason };
},
/** 테스트·컴퓨터용: 지금 차례 색의 모든 합법 배치(같은 칸 집합은 하나), 장애물 고르기·놓기, 무르기 응답. */
legalActions(s, p) {
if (s.phase === 'finished' || !s.players.includes(p) || isOut(s, p)) return [];
const out: GembloAction[] = [];
const u = s.undo.pending;
if (u && u.by !== p && !u.accepted.includes(p)) out.push({ type: 'respondUndo', accept: true }, { type: 'respondUndo', accept: false });
if (turnPlayer(s) !== p) return out;
if (s.phase === 'obstacleDraft') {
for (const id of new Set(s.obstacle!.pool)) out.push({ type: 'pickObstacle', pieceId: id });
return out;
}
if (s.phase === 'obstaclePlace') {
for (const pl of obstaclePlacements(boardOf(s), s.obstacle!.hands[p] ?? [], s.obstacle!.sectorCount)) out.push({ type: 'placeObstacle', pieceId: pl.pieceId, orient: pl.orient, q: pl.q, r: pl.r });
return out;
}
for (const pl of legalPlacements(boardOf(s), s.colors[s.turn]!, flipOf(s))) out.push({ type: 'place', pieceId: pl.pieceId, orient: pl.orient, q: pl.q, r: pl.r });
return out;
},
/** 완전 정보 게임: 숨길 정보가 없다(RNG는 상태 밖). */
secretsOf() {
return [];
},
};

View File

@@ -0,0 +1,65 @@
/** 젬블로 room options (docs/games/gemblo.md §2). */
import { z } from 'zod';
const lit = <T extends string | number>(...vals: T[]) =>
z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral<T>, z.ZodLiteral<T>, ...z.ZodLiteral<T>[]]);
export const gembloOptionsSchema = z.object({
seatOrder: z.enum(['random', 'joinOrder']).default('random').meta({ title: '자리(시작점)와 순서', labels: { random: '무작위', joinOrder: '들어온 순서' } }),
twoPlayerMode: z
.enum(['twoColors', 'threeColors', 'duo'])
.default('twoColors')
.meta({ title: '2명일 때 방식', labels: { twoColors: '2색씩, 4인 구역(원작)', threeColors: '3색씩, 판 전체(원작)', duo: '1색씩, 작은 판(듀오)' } }),
threePlayerMode: z
.enum(['oneColor', 'twoColors'])
.default('oneColor')
.meta({ title: '3명일 때 방식', labels: { oneColor: '1색씩, 3인 구역(원작)', twoColors: '2색씩, 판 전체' } }),
fivePlayerObstacles: z
.enum(['auto', 'draft', 'none'])
.default('auto')
.meta({ title: '5명일 때 장애물(남는 색 블록 15개)', labels: { auto: '자동으로 놓기', draft: '3개씩 골라 직접 놓기(원작)', none: '장애물 없음' } }),
bridgeRule: z
.enum(['official', 'free'])
.default('official')
.meta({ title: '이음선 막힘', labels: { official: '블록 하나가 사이 두 칸을 덮으면 막힘(원작)', free: '안 막힘(처음 하는 사람용)' } }),
allowFlip: z.boolean().default(true).meta({ title: '블록 뒤집기', labels: { true: '허용', false: '안 됨(돌리기만)' } }),
scoring: z
.enum(['remaining', 'blokusBonus'])
.default('remaining')
.meta({ title: '점수 방식', labels: { remaining: '남은 칸이 적을수록 좋음(원작)', blokusBonus: '남은 칸 −1점, 다 놓으면 +15, 마지막이 한 칸이면 +20' } }),
teams: z
.enum(['off', 'pairs', 'triples'])
.default('off')
.meta({ title: '팀전', labels: { off: '개인전', pairs: '마주 보는 2명씩(4·6명)', triples: '한 칸 건너 3명씩(6명)' } }),
neutralBlocks: lit(0, 3, 6)
.default(0)
.meta({ title: '가운데 금색 방해 블록', labels: { 0: '없음', 3: '3개', 6: '6개' } }),
showHints: z.boolean().default(true).meta({ title: '이을 수 있는 자리(이음점) 표시', labels: { true: '보여 주기', false: '안 보여 주기' } }),
timeControl: z
.object({
kind: z
.enum(['none', 'perMove', 'fischer'])
.default('perMove')
.meta({ title: '시간 방식', labels: { none: '제한 없음', perMove: '한 번(한 색 차례)당 제한', fischer: '전체 시간 + 한 번마다 추가' } }),
perMoveSec: lit(30, 60, 90, 120)
.default(60)
.meta({ title: '한 번당 제한', labels: { 30: '30초', 60: '60초', 90: '90초', 120: '120초' } }),
baseSec: lit(300, 600)
.default(600)
.meta({ title: '전체 시간', labels: { 300: '5분', 600: '10분' } }),
incSec: z.number().int().min(0).max(30).default(5).meta({ title: '한 번마다 추가(초)' }),
})
.default({ kind: 'perMove', perMoveSec: 60, baseSec: 600, incSec: 5 })
.meta({ title: '시간 제한' }),
timeoutPolicy: z
.enum(['autoPlace', 'pass', 'retire'])
.default('autoPlace')
.meta({ title: '한 번 시간이 다 되면', labels: { autoPlace: '놓을 수 있는 큰 블록 자동 배치', pass: '이번 차례만 넘김', retire: '그 사람의 색은 더 안 놓음' } }),
autoMoveLimit: z.number().int().min(0).max(5).default(2).meta({ title: '연속 자동 처리 허용 횟수(넘으면 그 사람의 색 모두 끝남)' }),
undo: z
.enum(['off', '1', '3'])
.default('off')
.meta({ title: '무르기(1인당, 다른 모든 사람 동의)', labels: { off: '안 씀', 1: '1번', 3: '3번' } }),
});
export type GembloOptions = z.infer<typeof gembloOptionsSchema>;

View File

@@ -0,0 +1,149 @@
/** 젬블로 state, actions and view (docs/games/gemblo.md §8). */
import { z } from 'zod';
import type { PlayerId } from '@bg/engine';
import { PIECE_IDS, type BlockColor, type BridgeRule, type ColorId, type Hex, type Layout, type PieceId } from './board';
import type { GembloOptions } from './options';
const pieceId = z.enum(PIECE_IDS as [PieceId, ...PieceId[]]);
const coord = z.number().int().min(-40).max(40);
export const gembloActionSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('place'), pieceId, orient: z.number().int().min(0).max(11), q: coord, r: coord }),
z.object({ type: z.literal('pickObstacle'), pieceId }),
z.object({ type: z.literal('placeObstacle'), pieceId, orient: z.number().int().min(0).max(11), q: coord, r: coord }),
z.object({ type: z.literal('requestUndo') }),
z.object({ type: z.literal('respondUndo'), accept: z.boolean() }),
z.object({ type: z.literal('cancelUndo') }),
z.object({ type: z.literal('resign') }),
]);
/** Client actions + the system-only timeout (not in the schema). */
export type GembloAction = z.infer<typeof gembloActionSchema> | { type: 'timeout' };
export type DoneReason = 'blocked' | 'allPlaced' | 'resign' | 'timeLoss';
export interface GembloColor {
color: ColorId;
owner: PlayerId;
start: Hex;
/** Blocks not used yet (tray order). */
left: PieceId[];
placed: number;
done: boolean;
doneReason: DoneReason | null;
/** blokusBonus: the last block placed. */
lastPiece: PieceId | null;
}
/** One block on the board (5-player obstacles and gold neutral blocks included). */
export interface GembloPlacement {
seq: number;
color: BlockColor;
pieceId: PieceId;
orient: number;
cells: number[];
auto: boolean;
kind: 'play' | 'obstacle' | 'neutral';
}
export type GembloMove =
| { kind: 'place'; color: ColorId; pieceId: PieceId; seq: number; auto: boolean }
| { kind: 'pass'; color: ColorId }
| { kind: 'out'; color: ColorId; leftCells: number; reason: DoneReason }
| { kind: 'obstacle'; by: PlayerId | null; pieceId: PieceId; seq: number | null };
export interface GembloObstacle {
/** draft: blocks nobody picked yet. */
pool: PieceId[];
hands: Record<PlayerId, PieceId[]>;
/** Obstacles placed in each of the 5 sectors (between neighbouring starts). */
sectorCount: number[];
/** Seat (index into `players`) whose pick / placement it is. */
seat: number;
lastPlacer: PlayerId | null;
}
export interface GembloOut {
playerId: PlayerId;
reason: 'resign' | 'timeLoss';
at: number;
}
export interface GembloResult {
ranking: PlayerId[][];
scores: Record<PlayerId, number>;
scoreText: Record<PlayerId, string>;
perColor: { color: ColorId; owner: PlayerId; leftCells: number; leftPieces: PieceId[]; allPlaced: boolean; bonus: number }[];
teams?: { members: PlayerId[]; total: number }[];
summary: string;
reason: 'normal' | 'resign' | 'timeout';
}
export interface GembloState {
options: GembloOptions;
layout: Layout;
/** Seat order (clockwise); a seat owns one or more colours. */
players: PlayerId[];
board: number[];
placements: GembloPlacement[];
/** Turn order. */
colors: GembloColor[];
turn: number;
phase: 'obstacleDraft' | 'obstaclePlace' | 'playing' | 'finished';
obstacle: GembloObstacle | null;
teams: PlayerId[][] | null;
turnStartedAt: number;
clock: { remainingMs: Record<PlayerId, number> };
/** Consecutive automatic turns (timeouts) per person. */
streak: Record<PlayerId, number>;
history: GembloMove[];
undo: {
usedBy: Record<PlayerId, number>;
pending: { by: PlayerId; accepted: PlayerId[] } | null;
/** The last manual placement, while nobody has played since: what an accepted undo takes back. */
last: { by: PlayerId; color: number; seq: number; leftIndex: number; outs: number[]; historyLength: number; allPlaced: boolean } | null;
};
out: GembloOut[];
result: GembloResult | null;
}
export interface GembloColorView extends GembloColor {
leftCells: number;
}
export interface GembloPlayerView {
id: PlayerId;
colors: number[];
out: 'resign' | 'timeLoss' | null;
streak: number;
remainingMs: number;
team: number | null;
}
export interface GembloView {
layout: Layout;
bridgeRule: BridgeRule;
allowFlip: boolean;
showHints: boolean;
scoring: GembloOptions['scoring'];
timeControl: GembloOptions['timeControl'];
timeoutPolicy: GembloOptions['timeoutPolicy'];
board: number[];
placements: GembloPlacement[];
colors: GembloColorView[];
players: GembloPlayerView[];
teams: PlayerId[][] | null;
turn: number;
/** Who acts now (colour owner, or the obstacle picker / placer). */
turnPlayer: PlayerId | null;
phase: GembloState['phase'];
/** Colour indices of the viewer. */
myColors: number[];
turnStartedAt: number;
history: GembloMove[];
/** seq of the last placement (thin outline until the next one). */
lastSeq: number | null;
/** Only for the person whose colour it is. */
legal: { bridgePoints: number[]; placeable: PieceId[] } | null;
obstacle: (GembloObstacle & { remaining: number }) | null;
undo: { allowed: boolean; remaining: Record<PlayerId, number>; pending: { by: PlayerId; accepted: PlayerId[] } | null; responders: PlayerId[]; canRequest: boolean };
result: GembloResult | null;
}

View File

@@ -34,6 +34,7 @@ import { liar } from './liar';
import { magicalAthlete } from './magical-athlete';
import { blackjack } from './blackjack';
import { sixNimmt } from './six-nimmt';
import { gemblo } from './gemblo';
export const GAMES: Record<string, AnyGameDefinition> = {
[omok.id]: omok,
@@ -71,4 +72,5 @@ export const GAMES: Record<string, AnyGameDefinition> = {
[magicalAthlete.id]: magicalAthlete,
[blackjack.id]: blackjack,
[sixNimmt.id]: sixNimmt,
[gemblo.id]: gemblo,
};

View File

@@ -60,6 +60,7 @@ export const BOT_GAMES: readonly string[] = [
'magical-athlete',
'blackjack',
'six-nimmt',
'gemblo',
];
/** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */

View File

@@ -46,6 +46,7 @@ export const CATALOG: CatalogEntry[] = [
{ id: 'liar', nameKo: '라이어 게임', minPlayers: 3, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '모두 같은 제시어를 받았는데 한 명만 몰라요! 한 문장씩 설명하며 라이어를 찾아요 · 채팅 추리', available: true },
{ id: 'blackjack', nameKo: '블랙잭', minPlayers: 1, maxPlayers: 7, minutes: '10~20', level: '쉬움', blurb: '딜러를 상대로 21에 가깝게! 공식 규칙 + 5카드 찰리·7트리플 하우스 룰 · 놀이용 칩 · 혼자서도 OK', available: true },
{ id: 'six-nimmt', nameKo: '젝스님트', minPlayers: 2, maxPlayers: 10, minutes: '20~45', level: '쉬움', blurb: '숫자 카드를 동시에 내고 작은 수부터 줄에 붙여요. 여섯 번째 카드면 소머리 벌점! · 10명까지', available: true },
{ id: 'gemblo', nameKo: '젬블로', minPlayers: 2, maxPlayers: 6, minutes: '20~30', level: '쉬움', blurb: '육각 보석 블록을 꼭짓점 선으로 이어 놓는 땅따먹기! 같은 색끼리는 닿으면 안 돼요 · 2~6명', available: true },
];
export const catalogById = (id: string): CatalogEntry | undefined => CATALOG.find((g) => g.id === id);