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

@@ -0,0 +1,113 @@
/** 젬블로 through a real Room: practice against computers from the person's own screen, and the turn clock (docs/games/gemblo.md §8.5, §10). */
import { afterEach, describe, expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import type { GembloAction, GembloState, GembloView } from '@bg/games/gemblo';
import { legalPlacements, obstaclePlacements } from '@bg/games/gemblo/board';
import { botProfile, isBotId, type ServerMessage } from '@bg/shared';
import { openDb } from '../db';
import { RoomManager } from './manager';
import { Room, type Conn } from './room';
import { RoomStore } from './store';
const rooms: Room[] = [];
afterEach(() => {
for (const r of rooms.splice(0)) r.clearTimer();
});
function harness() {
const db = openDb(':memory:');
const store = new RoomStore(db);
let now = 1_000_000;
const clock = { now: () => now, advance: (ms: number) => (now += ms) };
const users = { publicUser: (id: string) => botProfile(id) ?? { id, nickname: id, avatar: null, kind: 'guest' as const } };
const manager = new RoomManager({ store, games: GAMES, users, now: clock.now, botDelay: () => 0 });
const conn = (userId: string) => {
const msgs: ServerMessage[] = [];
const c: Conn & { msgs: ServerMessage[] } = { userId, msgs, send: (m) => msgs.push(m), close: () => {} };
return c;
};
return { db, clock, manager, conn };
}
type StateMsg = Extract<ServerMessage, { t: 'state' }>;
const lastView = (c: { msgs: ServerMessage[] }) => (c.msgs.filter((m): m is StateMsg => m.t === 'state').at(-1)?.view ?? null) as GembloView | null;
/** What the person does, read only from their own screen: tap the first link point, take the first way it offers. */
function personMove(v: GembloView, me: string): GembloAction | null {
if (v.turnPlayer !== me || v.phase === 'finished') return null;
if (v.phase === 'obstacleDraft') return { type: 'pickObstacle', pieceId: v.obstacle!.pool[0]! };
if (v.phase === 'obstaclePlace') {
const p = obstaclePlacements(v, v.obstacle!.hands[me]!, v.obstacle!.sectorCount, undefined, 1)[0]!;
return { type: 'placeObstacle', pieceId: p.pieceId, orient: p.orient, q: p.q, r: p.r };
}
if (!v.legal) return null;
const c = v.colors[v.turn]!;
// A link point may be one no block left can cover (only the 1-cell block would fit): try the next point.
for (const point of v.legal.bridgePoints) {
const p = legalPlacements(v, c, v.allowFlip, { points: [point] })[0];
if (p) return { type: 'place', pieceId: p.pieceId, orient: p.orient, q: p.q, r: p.r };
}
throw new Error('my turn without a placement');
}
function drive(h: ReturnType<typeof harness>, room: Room, a: ReturnType<ReturnType<typeof harness>['conn']>, play: boolean) {
let cs = 0;
let mine = 0;
for (let i = 0; i < 20_000 && !room.game!.finished; i++) {
h.clock.advance(500);
if (room.bots.dueAt !== null && room.bots.dueAt <= h.clock.now()) room.bots.fire();
const d = room.effectiveDeadline();
if (d !== null && d <= h.clock.now()) room.onTimer();
const v = lastView(a);
const m = play && v ? personMove(v, 'A') : null;
if (m) {
room.act('A', ++cs, m);
mine++;
}
}
return mine;
}
describe('젬블로 room flow', () => {
test('컴퓨터 1명과 연습: 사람은 자기 화면(이음점 → 놓는 방법)만 보고 끝까지', () => {
const h = harness();
const room = h.manager.createPractice('A', 'gemblo') as Room;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
expect(room.start('A')).toBeNull();
const mine = drive(h, room, a, true);
expect(room.game!.finished).toBe(true);
expect(a.msgs.filter((m) => m.t === 'reject')).toEqual([]);
const s = room.game!.state as GembloState;
expect(s.colors).toHaveLength(4); // 2명 = 2색씩
expect(s.placements.filter((p) => p.auto)).toEqual([]);
expect(mine).toBeGreaterThan(10);
const v = lastView(a)!;
expect(v.result!.ranking.flat().sort()).toEqual(['A', ...s.players.filter(isBotId)].sort());
const row = h.db.query<{ result_json: string }, []>('SELECT result_json FROM games').get()!;
expect(JSON.parse(row.result_json).practice).toBe(true);
});
test('5명(장애물 직접 고르기) + 시간 초과만 하는 사람: 자동 배치 두 번 뒤 그 사람 색은 끝나고 게임은 끝까지', () => {
const h = harness();
const r = h.manager.create('A', 'gemblo', 'private');
if (typeof r === 'string') throw new Error(r);
const room = r;
rooms.push(room);
const a = h.conn('A');
room.join(a, 'player');
for (let i = 0; i < 4; i++) expect(room.addBot('A')).toBeNull();
expect(room.configure('A', { options: { ...GAMES.gemblo!.defaultOptions, fivePlayerObstacles: 'draft' } })).toBeNull();
expect(room.start('A')).toBeNull();
expect((room.game!.state as GembloState).phase).toBe('obstacleDraft');
drive(h, room, a, false);
expect(room.game!.finished).toBe(true);
const s = room.game!.state as GembloState;
expect(s.placements.filter((p) => p.kind === 'obstacle').length).toBeGreaterThanOrEqual(13);
const auto = s.placements.filter((p) => p.auto && p.kind === 'play' && s.colors.find((c) => c.color === p.color)?.owner === 'A');
expect(auto).toHaveLength(2);
expect(s.out).toEqual([expect.objectContaining({ playerId: 'A', reason: 'timeLoss' })]);
expect(lastView(a)!.result!.ranking.at(-1)).toEqual(['A']);
});
});

View File

@@ -0,0 +1,133 @@
/** 젬블로 그림 도우미: 납작한 육각형 칸, 보석 색과 무늬(색약 배려), 작은 블록 그림. */
import type { BlockColor, PieceId } from '@bg/games/gemblo';
import { pieceOffsets } from '@bg/games/gemblo/board';
export const SQ3 = Math.sqrt(3);
/** Screen centre of (q, r) with hex radius 1. */
export const hx = (q: number, r: number): [number, number] => [1.5 * q, SQ3 * (r + q / 2)];
const CORNERS = Array.from({ length: 6 }, (_, k) => [Math.cos((Math.PI / 3) * k), Math.sin((Math.PI / 3) * k)] as const);
/** Polygon points of a flat-top hex. */
export function hexPoints(cx: number, cy: number, s = 1): string {
return CORNERS.map(([a, b]) => `${(cx + a * s).toFixed(3)},${(cy + b * s).toFixed(3)}`).join(' ');
}
export const GEM: Record<BlockColor, { fill: string; edge: string; light: string }> = {
red: { fill: '#e11d48', edge: '#9f1239', light: '#fda4af' },
yellow: { fill: '#eab308', edge: '#a16207', light: '#fef08a' },
green: { fill: '#16a34a', edge: '#166534', light: '#86efac' },
blue: { fill: '#2563eb', edge: '#1e3a8a', light: '#93c5fd' },
purple: { fill: '#9333ea', edge: '#581c87', light: '#d8b4fe' },
orange: { fill: '#ea580c', edge: '#9a3412', light: '#fdba74' },
gold: { fill: '#a8842c', edge: '#6b5313', light: '#f3dc8f' },
};
/** A different mark per colour so colours can be told apart without seeing colour. */
export function Glyph({ color, cx, cy, s = 0.3 }: { color: BlockColor; cx: number; cy: number; s?: number }) {
const f = 'rgba(255,255,255,0.78)';
switch (color) {
case 'red':
return <circle cx={cx} cy={cy} r={s * 0.8} fill={f} />;
case 'yellow':
return <polygon points={`${cx},${cy - s} ${cx + s * 0.95},${cy + s * 0.7} ${cx - s * 0.95},${cy + s * 0.7}`} fill="rgba(80,50,0,0.55)" />;
case 'green':
return <rect x={cx - s * 0.7} y={cy - s * 0.7} width={s * 1.4} height={s * 1.4} fill={f} />;
case 'blue':
return <polygon points={`${cx},${cy - s} ${cx + s},${cy} ${cx},${cy + s} ${cx - s},${cy}`} fill={f} />;
case 'purple': {
const pts = Array.from({ length: 10 }, (_, k) => {
const a = -Math.PI / 2 + (Math.PI / 5) * k;
const rr = k % 2 ? s * 0.45 : s * 1.05;
return `${(cx + Math.cos(a) * rr).toFixed(3)},${(cy + Math.sin(a) * rr).toFixed(3)}`;
}).join(' ');
return <polygon points={pts} fill={f} />;
}
case 'orange':
return <path d={`M${cx - s} ${cy}H${cx + s}M${cx} ${cy - s}V${cy + s}`} stroke={f} strokeWidth={s * 0.5} strokeLinecap="round" />;
case 'gold':
return <path d={`M${cx - s * 0.8} ${cy + s * 0.8}L${cx + s * 0.8} ${cy - s * 0.8}`} stroke="rgba(60,40,0,0.5)" strokeWidth={s * 0.35} strokeLinecap="round" />;
}
}
/** One gem cell (board and pictures share it). */
export function GemCell({ color, cx, cy, s = 0.94, ghost, bad }: { color: BlockColor; cx: number; cy: number; s?: number; ghost?: boolean; bad?: boolean }) {
const g = GEM[color];
if (bad) return <polygon points={hexPoints(cx, cy, s)} fill="rgba(220,38,38,0.55)" stroke="#7f1d1d" strokeWidth={0.1} strokeDasharray="0.25 0.15" />;
return (
<g opacity={ghost ? 0.6 : 1}>
<polygon points={hexPoints(cx, cy, s)} fill={g.fill} stroke={g.edge} strokeWidth={0.1} />
<polygon points={hexPoints(cx - 0.12, cy - 0.14, s * 0.42)} fill={g.light} opacity={0.55} />
<Glyph color={color} cx={cx} cy={cy + 0.05} />
</g>
);
}
/** Cells of a piece in orientation o, as (q, r) offsets moved so the picture starts at (0, 0). */
export function pieceShape(id: PieceId, o: number): [number, number][] {
return pieceOffsets(id, o);
}
/** Small picture of a block (tray, rules, results). `size` = pixel height of the box. */
export function PieceIcon({ id, orient = 0, color, size = 44, dim, title }: { id: PieceId; orient?: number; color: BlockColor; size?: number; dim?: boolean; title?: string }) {
const cells = pieceShape(id, orient).map(([q, r]) => hx(q, r));
const xs = cells.map((c) => c[0]);
const ys = cells.map((c) => c[1]);
const minX = Math.min(...xs) - 1.05;
const maxX = Math.max(...xs) + 1.05;
const minY = Math.min(...ys) - 0.95;
const maxY = Math.max(...ys) + 0.95;
// Square box so every block in the tray has the same footprint (at least 4.6 units: a 5-cell line fits).
const side = Math.max(maxX - minX, maxY - minY, 4.6);
const cx = (minX + maxX) / 2;
const cy = (minY + maxY) / 2;
return (
<svg viewBox={`${cx - side / 2} ${cy - side / 2} ${side} ${side}`} width={size} height={size} aria-hidden={title ? undefined : true} role={title ? 'img' : undefined} aria-label={title} style={{ opacity: dim ? 0.35 : 1, display: 'block' }}>
{cells.map(([x, y], i) => (
<GemCell key={i} color={color} cx={x} cy={y} />
))}
</svg>
);
}
/** Mini board picture for the rules / 30초 요약: hexes in a small patch with coloured cells. */
export interface MiniCell {
q: number;
r: number;
color?: BlockColor;
mark?: 'start' | 'link' | 'bad' | 'ghost';
}
export function MiniHex({ radius = 3, cells, lines = [], crosses = [], width = 170 }: { radius?: number; cells: MiniCell[]; lines?: [number, number, number, number][]; crosses?: [number, number][]; width?: number }) {
const all: [number, number][] = [];
for (let q = -radius; q <= radius; q++) for (let r = -radius; r <= radius; r++) if (Math.abs(q + r) <= radius) all.push([q, r]);
const w = 3 * radius + 2.2;
const h = SQ3 * (2 * radius + 1) + 0.4;
const byKey = new Map(cells.map((c) => [`${c.q},${c.r}`, c]));
return (
<svg viewBox={`${-w / 2} ${-h / 2} ${w} ${h}`} width={width} height={(width * h) / w} aria-hidden style={{ display: 'block', margin: '0 auto' }}>
<rect x={-w / 2} y={-h / 2} width={w} height={h} rx={0.8} fill="var(--wood)" />
{all.map(([q, r]) => {
const [x, y] = hx(q, r);
const c = byKey.get(`${q},${r}`);
if (c?.color && c.mark !== 'ghost' && c.mark !== 'bad') return <GemCell key={`${q},${r}`} color={c.color} cx={x} cy={y} />;
return (
<g key={`${q},${r}`}>
<polygon points={hexPoints(x, y, 0.94)} fill="rgba(255,255,255,0.5)" />
{c?.mark === 'ghost' && c.color && <GemCell color={c.color} cx={x} cy={y} ghost />}
{c?.mark === 'bad' && <GemCell color="red" cx={x} cy={y} bad />}
{c?.mark === 'start' && <polygon points={hexPoints(x, y, 0.7)} fill="none" stroke={GEM[c.color ?? 'red'].fill} strokeWidth={0.18} />}
{c?.mark === 'link' && <circle cx={x} cy={y} r={0.26} fill={GEM[c.color ?? 'red'].fill} stroke="#fff" strokeWidth={0.08} />}
</g>
);
})}
{lines.map(([q1, r1, q2, r2], i) => {
const [x1, y1] = hx(q1, r1);
const [x2, y2] = hx(q2, r2);
return <line key={`l${i}`} x1={x1 + (x2 - x1) * 0.3} y1={y1 + (y2 - y1) * 0.3} x2={x1 + (x2 - x1) * 0.7} y2={y1 + (y2 - y1) * 0.7} stroke="#111827" strokeWidth={0.16} strokeLinecap="round" />;
})}
{crosses.map(([q, r], i) => {
const [x, y] = hx(q, r);
return <path key={`x${i}`} d={`M${x - 0.35} ${y - 0.35}L${x + 0.35} ${y + 0.35}M${x + 0.35} ${y - 0.35}L${x - 0.35} ${y + 0.35}`} stroke="#dc2626" strokeWidth={0.2} strokeLinecap="round" />;
})}
</svg>
);
}

View File

@@ -0,0 +1,27 @@
import { expect, test } from 'bun:test';
import { GAMES } from '@bg/games';
import { applyAction, setupGame, usersOf } from '../help-kit.test-util';
import { helpNow } from './help';
const users = usersOf(['A', 'B', 'C', 'D', 'E']);
const view = (s: unknown, who: string | null) => GAMES.gemblo!.view(s, who) as any;
test('젬블로: 내 차례(첫 블록) / 남의 차례 / 관전', () => {
const { state } = setupGame('gemblo', 2, { seatOrder: 'joinOrder' }); // A: 빨강·초록, B: 노랑·파랑
const mine = helpNow(view(state, 'A'), 'A', users);
expect(mine).toContain('내 차례예요. 빨강 블록을 하나 놓아요(남은 72칸)');
expect(mine).toContain('시작점을 덮어야');
expect(mine).toContain('이음점');
expect(helpNow(view(state, 'B'), 'B', users)).toContain('호랑이님(빨강) 차례예요. 기다려 주세요');
expect(helpNow(view(state, null), null, users)).toContain('구경하고 있어요');
});
test('젬블로: 두 번째 블록부터는 이음점 안내, 무르기 요청, 5명 장애물 고르기', () => {
let { state } = setupGame('gemblo', 2, { seatOrder: 'joinOrder', undo: '1' });
state = applyAction('gemblo', state, 'A', { type: 'place', pieceId: 'i5', orient: 0, q: -9, r: -3 });
state = applyAction('gemblo', state, 'A', { type: 'requestUndo' });
expect(helpNow(view(state, 'B'), 'B', users)).toContain('무르기를 부탁했어요');
const five = setupGame('gemblo', 5, { seatOrder: 'joinOrder', fivePlayerObstacles: 'draft' }).state;
expect(helpNow(view(five, 'A'), 'A', users)).toContain('장애물로 놓을 블록을 하나 골라요');
expect(helpNow(view(five, 'B'), 'B', users)).toContain('호랑이님이 장애물 블록을 고르고 있어요');
});

View File

@@ -0,0 +1,57 @@
/** 젬블로 [?] "지금 할 수 있는 것" (docs/07 §5). Pure: only reads the client view. */
import type { GembloView } from '@bg/games/gemblo';
import { COLOR_KO } from '@bg/games/gemblo/board';
import type { PublicUser } from '@bg/shared/lite';
export function helpNow(v: GembloView, me: string | null, players: Record<string, PublicUser>): string {
const nick = (id: string | null) => (id ? `${players[id]?.nickname ?? '다른 사람'}님` : '다른 사람');
const mine = v.players.find((p) => p.id === me) ?? null;
const myColors = mine ? mine.colors.map((i) => v.colors[i]!) : [];
const myText = myColors.length ? `내 색은 ${myColors.map((c) => `${COLOR_KO[c.color]}(남은 ${c.leftCells}칸${c.done ? ', 끝' : ''})`).join(', ')}이에요.` : '';
const goal = '같은 색끼리는 변이 닿으면 안 되고, 내 블록 꼭짓점에서 선을 따라 한 칸 떨어진 곳(이음점)에 이어 놓아요. 끝날 때 남은 칸이 적을수록 이겨요.';
if (v.phase === 'finished') {
const r = v.result;
if (!r) return '게임이 끝났어요.';
const place = mine ? r.ranking.findIndex((g) => g.includes(mine.id)) : -1;
const tail = place === 0 ? ' 내가 1등이에요!' : place > 0 ? ` 나는 ${place + 1}등이에요.` : '';
return `게임이 끝났어요. ${r.summary}.${tail} 판 아래에 색마다 남은 블록이 보여요.`;
}
if (!mine) {
const turn = v.phase === 'playing' ? `${nick(v.turnPlayer)}(${COLOR_KO[v.colors[v.turn]!.color]}) 차례예요.` : `${nick(v.turnPlayer)}이 장애물을 ${v.phase === 'obstacleDraft' ? '고르는' : '놓는'} 중이에요.`;
return `구경하고 있어요. ${turn}\n${goal}`;
}
if (mine.out) return `게임에서 빠졌어요(${mine.out === 'resign' ? '기권' : '시간패'}). 남은 사람들이 끝낼 때까지 지켜볼 수 있어요.\n${myText}`;
const u = v.undo.pending;
if (u && u.by !== mine.id && !u.accepted.includes(mine.id)) {
return `${nick(u.by)}이 무르기를 부탁했어요. [수락]하면 방금 놓은 블록 하나가 되돌려지고, [거절]하면 그대로 계속해요.`;
}
if (v.phase === 'obstacleDraft') {
if (v.turnPlayer === mine.id) return '5명 게임 준비예요. 남는 색 블록 15개를 장애물로 써요. 아래 목록에서 장애물로 놓을 블록을 하나 골라요(한 사람이 3개씩).';
return `5명 게임 준비 중이에요. ${nick(v.turnPlayer)}이 장애물 블록을 고르고 있어요. 다 고르면 차례로 하나씩 판에 놓아요.`;
}
if (v.phase === 'obstaclePlace') {
if (v.turnPlayer === mine.id)
return '내가 고른 장애물을 판에 놓을 차례예요. 맨 바깥 줄에는 못 놓고, 바깥에서 두 번째 줄 칸을 하나 이상 덮으면서 판 가운데 쪽으로 뻗어야 해요. 두 시작점 사이마다 장애물은 3개까지예요.';
return `${nick(v.turnPlayer)}이 장애물을 놓고 있어요. 장애물을 마지막에 놓은 사람부터 게임을 시작해요.`;
}
const c = v.colors[v.turn]!;
if (v.turnPlayer !== mine.id) {
const wait = u && (u.by === mine.id || u.accepted.includes(mine.id)) ? '\n무르기 요청에 다른 사람이 답하기를 기다리는 중이에요.' : '';
return `${nick(v.turnPlayer)}(${COLOR_KO[c.color]}) 차례예요. 기다려 주세요.\n${myText}${wait}`;
}
const lines = [`내 차례예요. ${COLOR_KO[c.color]} 블록을 하나 놓아요(남은 ${c.leftCells}칸).`];
if (c.placed === 0) lines.push('첫 블록은 판에 테두리로 표시된 내 시작점을 덮어야 해요.');
else lines.push(goal);
lines.push('아래에서 블록을 고르고 판의 칸을 눌러 미리 본 뒤 [놓기]를 눌러요. ⟲ ⟳로 돌리고' + (v.allowFlip ? ' ↔로 뒤집어요.' : '요(이 방은 뒤집기 금지).'));
if (v.showHints && v.legal) lines.push(`판의 내 색 점 ${v.legal.bridgePoints.length}개가 이음점이에요. 점을 누르면 그 점을 덮는 방법이 바로 나오고, 다시 누르면 다음 방법이에요.`);
if (v.legal) {
const locked = c.left.length - v.legal.placeable.length;
if (locked > 0) lines.push(`🔒 표시 블록 ${locked}개는 지금 놓을 곳이 없어요.`);
}
return lines.join('\n');
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,24 @@
/** 젬블로 30초 규칙 요약 (docs/07 §5). Small hex patches drawn inline. */
import type { QuickCard } from '../types';
import { MiniHex } from './draw';
export const quickStart: QuickCard[] = [
{
pic: <MiniHex cells={[{ q: 0, r: 0, color: 'red' }, { q: 0, r: 1, color: 'red' }, { q: 2, r: -1, mark: 'link', color: 'red' }, { q: 1, r: 2, mark: 'link', color: 'red' }, { q: -1, r: -1, mark: 'link', color: 'red' }]} lines={[[0, 0, 2, -1], [0, 1, 1, 2], [0, 0, -1, -1]]} />,
alt: '빨간 블록의 꼭짓점에서 선을 따라 한 칸 떨어진 곳에 빨간 점이 찍혀 있어요',
title: '선으로 한 칸 떨어져 이어요',
text: '첫 블록은 내 시작점을 덮고, 그다음부터는 내 블록 꼭짓점에서 선을 따라 한 칸 떨어진 곳(내 색 점)에 이어 놓아요.',
},
{
pic: <MiniHex cells={[{ q: 0, r: 0, color: 'red' }, { q: 0, r: 1, mark: 'bad' }, { q: 1, r: 0, color: 'blue' }, { q: 1, r: 1, color: 'blue' }]} />,
alt: '빨간 블록 바로 옆 칸은 빨갛게 막혀 있고, 파란 블록은 빨간 블록 옆에 붙어 있어요',
title: '같은 색끼리는 닿으면 안 돼요',
text: '같은 색 블록끼리는 변이 닿으면 안 돼요. 다른 색과는 붙어도 괜찮아요. 서로 다른 두 블록 사이의 틈은 지나갈 수 있어요.',
},
{
pic: <MiniHex radius={2} cells={[{ q: -1, r: 0, color: 'green' }, { q: -1, r: 1, color: 'green' }, { q: 0, r: 0, color: 'yellow' }, { q: 1, r: -1, color: 'red' }, { q: 1, r: 0, color: 'red' }, { q: 0, r: 1, color: 'blue' }, { q: 0, r: -1, color: 'purple' }]} />,
alt: '여러 색 보석 블록이 판을 채우고 있어요',
title: '남은 칸이 적으면 승리',
text: '놓을 곳이 없으면 그 색은 끝나요. 모두 끝나면 못 놓은 블록의 칸 수가 가장 적은 사람이 이겨요. 큰 블록부터 쓰세요!',
},
];

View File

@@ -0,0 +1,24 @@
/** 젬블로 소리: 보석 블록 "딸깍". Short and soft; the site volume is applied by feedback.ts. */
import { noise, tone } from '../../lib/feedback';
export const gmSound = {
/** A block set down: a glassy click with a little shimmer. */
place: () => {
noise(28, 0.12, 0, 'bandpass', 3400, 2.2);
tone(1760, 70, 'triangle', 0.07, 4);
tone(2640, 90, 'sine', 0.035, 24);
},
/** A spot where the block can't go (small and low). */
refuse: () => tone(190, 120, 'triangle', 0.08, 0, { slideTo: 140 }),
/** A colour has nowhere left to go: a short falling pair. */
out: () => {
tone(523, 110, 'triangle', 0.06);
tone(392, 160, 'triangle', 0.06, 110);
},
/** All 18 blocks of a colour placed: a quick sparkle. */
allPlaced: () => [1319, 1568, 1976, 2637].forEach((f, i) => tone(f, 110, 'sine', 0.05, 60 + i * 55)),
/** Rotating / flipping the block in hand. */
turn: () => tone(1100, 30, 'triangle', 0.05),
/** Moves taken back (무르기). */
undo: () => tone(700, 160, 'sine', 0.06, 0, { slideTo: 420 }),
};

View File

@@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti
const IDS = Object.keys(GAME_UI);
test('모든 게임에 도움말이 있어요', () => {
expect(IDS).toHaveLength(35);
expect(IDS).toHaveLength(36);
for (const id of IDS) {
const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8');
expect(src, id).toMatch(/\bquickStart,/);

View File

@@ -37,6 +37,7 @@ export const GAME_UI: Record<string, () => Promise<{ default: GameUI }>> = {
'magical-athlete': () => import('./magical-athlete'),
blackjack: () => import('./blackjack'),
'six-nimmt': () => import('./six-nimmt'),
gemblo: () => import('./gemblo'),
};
const cache = new Map<string, GameUI>();

View File

@@ -34,6 +34,7 @@ export const GAME_ICON: Record<string, string> = {
'magical-athlete': '🏃',
blackjack: '🂡',
'six-nimmt': '🐮',
gemblo: '💠',
};
/** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */
@@ -41,7 +42,7 @@ export const UPCOMING: string[] = [];
/** Tabs on the game picker (docs/07 §3.3). Games not listed here only show under 전체. */
export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue'] },
{ key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue', 'gemblo'] },
{ key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code', 'six-nimmt'] },
{ key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple'] },
];

View File

@@ -48,6 +48,7 @@
| `magical-athlete` | 야단법석 달리기 | 2~6 | 2026-10 새 게임 |
| `blackjack` | 블랙잭 | 1~7 | 2026-10 새 게임 |
| `six-nimmt` | 젝스님트 | 2~10 | 2026-10 새 게임 |
| `gemblo` | 젬블로 | 2~6 | 2026-10 새 게임 |
인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선).

View File

@@ -1,6 +1,6 @@
# 젬블로 (`gemblo`)
> 마일스톤: 미정(사용자 확인 후 시작) · 인원: 최소 2 ~ 최대 6명 · 예상 시간: 약 20~30분 · 난이도: 쉬움~보통
> 마일스톤: 2026-10 새 게임 · 인원: 최소 2 ~ 최대 6명 · 예상 시간: 약 20~30분 · 난이도: 쉬움~보통
## 1. 개요
- 육각형 칸 1~5개로 된 보석 블록 18개를 육각형 판에 하나씩 올려놓는 땅따먹기 게임. 같은 색 블록끼리는 절대 닿으면 안 되고, 이미 놓은 내 블록의 꼭짓점에서 "선을 따라 한 칸 떨어진 곳"에만 이어 놓을 수 있다. 남의 블록으로 내 길이 막히기도 하고, 서로 다른 색 블록 두 개가 맞닿은 틈은 뚫고 지나갈 수 있어서 "빈틈 찾기"가 재미의 핵심이다. 더 놓을 수 없으면 끝나고, 못 놓은 블록의 칸 수가 가장 적은 사람이 이긴다.
@@ -29,6 +29,7 @@
| `autoMoveLimit` | 연속 자동 처리 허용 횟수(넘으면 그 사람의 색 모두 `retire`) | 0~5 | 2 |
| `undo` | 무르기(1인당, 다른 모든 사람 동의) | `off` / `1` / `3` | `off` |
- 구현(2026-10-15): 위 표의 옵션을 모두 방 설정으로 넣었다(나중으로 미룬 것 없음). `neutralBlocks`·`perMoveSec`·`baseSec`는 표의 값만 고를 수 있고, `incSec`는 0~30초(기본 5초).
- 모든 항목에 `.meta({ title, labels })`를 붙인다(09 §2). 인원과 맞지 않는 옵션(예: 4명인데 `twoPlayerMode`)은 무시한다. `teams=triples`는 6명, `pairs`는 4·6명일 때만 받고 아니면 setup에서 "팀전은 4명 또는 6명일 때만 돼요"로 거부.
- 연결 끊김 유예는 방 설정(`graceSec`)을 따른다.
@@ -289,25 +290,25 @@ interface GembloResult {
- 규칙 보기: ① 시작점 덮기 ② "선으로 한 칸 떨어져 잇기"(원작 화살표 그림) ③ 한 블록이 사이를 막으면 못 감 / 두 블록 틈은 지나감 ④ 끝과 점수. 각 1장씩 그림.
## 10. 테스트 체크리스트
- [ ] 판·구역 칸 수: 전체 463, 3인 241, 4인 295, 듀오 157. 6꼭짓점·4인 모서리·3인 꼭짓점·5인 시작 칸이 모두 해당 구역 안이고 맨 바깥 칸.
- [ ] 블록 18개 칸 수 합 72, 서로 다른 방향 수 표(3.1)와 같음(합 74 / 92). `R`을 6번 하면 제자리, `M`을 2번 하면 제자리.
- [ ] 인원·모드별 색 배분과 차례 순서(4장 표), 팀전 자리 맞춤, 팀전 인원 불일치 거부.
- [ ] 첫 블록: 시작점 안 덮으면 거부, 덮으면 허용. 첫 블록 합법 수 개수(8.2: 56 / 45 / 44 / 56).
- [ ] 같은 색 변 맞댐 거부, 다른 색과 맞댐 허용.
- [ ] 이음선 6방향 각각 허용. 대각 위치가 아닌 곳(예: `B − A = (2,0)` 직선 두 칸)은 거부("선으로 이어지는 곳이 아니에요").
- [ ] 막힘: 사이 두 칸을 다른 색 블록 하나가 덮으면 거부, 다른 색 블록 두 개가 한 칸씩이면 허용, 한 칸만 덮였으면 허용, 금색 장애물 두 개가 맞댄 틈은 허용, 같은 장애물 하나면 거부. `free`에서는 모두 허용.
- [ ] 구역 밖 칸(4인·3인)은 놓을 수 없고, 사이 칸이 구역 밖이면 열린 것으로 봄.
- [ ] 놓을 곳 없는 색 자동 `colorOut`, 이후 차례에서 빠짐, 모든 색 끝나면 종료. 2색 가진 사람의 한 색만 끝난 경우 다른 색은 계속.
- [ ] 점수: 남은 칸 합, 공동 순위, `blokusBonus`(다 놓음 +15, 마지막 `p1` +20), 팀 합계.
- [ ] 5명 `auto`: 장애물 15개, 맨 바깥 칸 없음, 두 번째 줄 1칸 이상, 구역마다 3개, 겹침 없음. 시드 1,000개에서 배치 실패 없음.
- [ ] 5명 `draft`: 고르기 3바퀴·놓기 순서, 조건 위반 거부, 마지막에 놓은 사람이 시작.
- [ ] `neutralBlocks`: 개수, 시작점과 거리, 서로 안 닿음.
- [ ] `allowFlip=false`: `orient` 6~11 거부, 거울상 블록 방향 수 절반.
- [ ] 시간 초과: `autoPlace`가 가장 큰 블록을 합법하게 놓음, 같은 시드 같은 결과, 연속 한도 넘으면 그 사람 색 모두 끝남. `pass`는 색 유지. `fischer` 시간패.
- [ ] 무르기: 전원 수락 시 배치·자동 `colorOut` 함께 복원, 다음 색이 놓은 뒤에는 요청 불가.
- [ ] 기권: 색 끝남 처리, 순위 맨 아래, 2명이면 상대 승.
- [ ] 정보: 차례 아닌 사람·관전자 view에 `legal` 없음, 모든 view에 `rng` 없음. `checkPlacement`(클라이언트)와 `validate` 결과가 무작위 배치 1만 개에서 같음.
- [ ] 성능: 무작위 대국에서 `legalActions` 최악 10ms 이내, `apply` 5ms 이내. 2~6명 모든 모드 무작위 대국이 끝까지 감(상한: 색 수 × 18 + 색 수 차례).
- [x] 판·구역 칸 수: 전체 463, 3인 241, 4인 295, 듀오 157. 6꼭짓점·4인 모서리·3인 꼭짓점·5인 시작 칸이 모두 해당 구역 안이고 맨 바깥 칸.
- [x] 블록 18개 칸 수 합 72, 서로 다른 방향 수 표(3.1)와 같음(합 74 / 92). `R`을 6번 하면 제자리, `M`을 2번 하면 제자리.
- [x] 인원·모드별 색 배분과 차례 순서(4장 표), 팀전 자리 맞춤, 팀전 인원 불일치 거부.
- [x] 첫 블록: 시작점 안 덮으면 거부, 덮으면 허용. 첫 블록 합법 수 개수(8.2: 56 / 45 / 44 / 56).
- [x] 같은 색 변 맞댐 거부, 다른 색과 맞댐 허용.
- [x] 이음선 6방향 각각 허용. 대각 위치가 아닌 곳(예: `B − A = (2,0)` 직선 두 칸)은 거부("선으로 이어지는 곳이 아니에요").
- [x] 막힘: 사이 두 칸을 다른 색 블록 하나가 덮으면 거부, 다른 색 블록 두 개가 한 칸씩이면 허용, 한 칸만 덮였으면 허용, 금색 장애물 두 개가 맞댄 틈은 허용, 같은 장애물 하나면 거부. `free`에서는 모두 허용.
- [x] 구역 밖 칸(4인·3인)은 놓을 수 없고, 사이 칸이 구역 밖이면 열린 것으로 봄.
- [x] 놓을 곳 없는 색 자동 `colorOut`, 이후 차례에서 빠짐, 모든 색 끝나면 종료. 2색 가진 사람의 한 색만 끝난 경우 다른 색은 계속.
- [x] 점수: 남은 칸 합, 공동 순위, `blokusBonus`(다 놓음 +15, 마지막 `p1` +20), 팀 합계.
- [x] 5명 `auto`: 장애물 15개, 맨 바깥 칸 없음, 두 번째 줄 1칸 이상, 구역마다 3개, 겹침 없음. 시드 1,000개에서 배치 실패 없음.
- [x] 5명 `draft`: 고르기 3바퀴·놓기 순서, 조건 위반 거부, 마지막에 놓은 사람이 시작.
- [x] `neutralBlocks`: 개수, 시작점과 거리, 서로 안 닿음.
- [x] `allowFlip=false`: `orient` 6~11 거부, 거울상 블록 방향 수 절반.
- [x] 시간 초과: `autoPlace`가 가장 큰 블록을 합법하게 놓음, 같은 시드 같은 결과, 연속 한도 넘으면 그 사람 색 모두 끝남. `pass`는 색 유지. `fischer` 시간패.
- [x] 무르기: 전원 수락 시 배치·자동 `colorOut` 함께 복원, 다음 색이 놓은 뒤에는 요청 불가.
- [x] 기권: 색 끝남 처리, 순위 맨 아래, 2명이면 상대 승.
- [x] 정보: 차례 아닌 사람·관전자 view에 `legal` 없음, 모든 view에 `rng` 없음. `checkPlacement`(클라이언트)와 `validate` 결과가 무작위 배치 1만 개에서 같음.
- [x] 성능: 무작위 대국에서 `legalActions` 최악 10ms 이내, `apply` 5ms 이내. 2~6명 모든 모드 무작위 대국이 끝까지 감(상한: 색 수 × 18 + 색 수 차례).
## 11. 참고 자료
- 코리아보드게임즈 「젬블로」 상품 페이지: https://www.koreaboardgames.com/product/detail?prdCd=PD2024002311KZKT (1~6명, 6세+, 20분, 게임 방법: 시작점 덮기, "선을 따라 한 칸 떨어진 곳", "서로 다른 색 블록 사이는 뚫고 지나감", 남은 칸 적은 사람 승리, 젬블로·디럭스·젬블로Q 비교)
@@ -331,3 +332,16 @@ interface GembloResult {
- 동점 처리: 원작에 규칙이 있다고만 알려져 있어 공동 순위로 둠.
- 블록 모양 18개: Gough 그림 기준, 디럭스판 사진과 개수·종류가 맞음(사진이 비스듬해 5칸 블록 일부는 그림으로만 확정).
- 금전·베팅 요소 없음.
## 13. 구현하면서 정한 것 (2026-10-15)
- 코드: 규칙 `packages/games/src/gemblo/`(board.ts 판·블록·판정, index.ts 규칙, bot.ts 컴퓨터), 화면 `apps/web/src/games/gemblo/`. 브라우저 미리보기는 `@bg/games/gemblo/board`의 `placementRefusal`(서버 `validate`와 같은 코드)로 바로 판정한다.
- 팀은 자리로 정한다: 4명은 1·3번 자리 대 2·4번 자리(대각선 모서리), 6명 `pairs`는 1·4 / 2·5 / 3·6번, `triples`는 1·3·5 대 2·4·6번. `seatOrder=random`이면 팀도 무작위, `joinOrder`면 방의 자리 순서대로(방장이 자리를 바꿔 팀을 맞춘다).
- 팀전 순위: 남은 사람이 있는 팀끼리 합계로, 모두 빠진 팀은 그 아래(늦게 빠진 팀이 위). "남은 사람이 1명 이하"로 끝나는 조건은 팀전에서 "남은 팀이 1개 이하".
- 5명 `auto` 장애물: 200번 무작위 시도 대신, 그 구역에 놓을 수 있는 자리를 모두 세어 RNG로 하나 고른다(실패 없음, 시드 1,000개 테스트). 장애물과 금색 블록은 모두 `gold`로 저장하고 `kind`(obstacle / neutral)로 구분한다.
- 5명 `draft`: 고르기는 자리 순서 0→4로 3바퀴, 놓기는 0번 자리부터 한 개씩. 손에 든 블록이 더 놓일 곳이 없으면 그 블록들은 빠진다(기록에 "빠짐"). 고르는 중에 기권하면 고른 블록은 다시 더미로, 놓는 중에 기권하면 그 사람 블록은 빠진다. 장애물 차례는 시간 방식과 상관없이 60초.
- 금색 블록: 시작점과 거리 6 이상인 자리가 없으면(듀오 판은 시작점이 가운데에서 4칸) 5 → 4 → 3으로 줄여 놓는다.
- 연속 자동 처리 횟수는 색이 아니라 사람 단위(`streak`)로 센다. `pass`도 자동 처리로 센다. 시간 제한 없음(`none`)에서도 연결 끊김 유예가 끝나면 `timeoutPolicy`대로 처리한다.
- 무르기: 다른 사람이 답하지 않아도 다음 색이 놓으면 요청은 사라진다(별도 30초 거절 타이머 없음). 요청한 사람은 [요청 취소]로 거둘 수 있다(`cancelUndo`). 자동 배치는 무를 수 없다.
- view의 `legal.bridgePoints`는 칸 번호(`CELLS` 인덱스) 목록이다.
- 화면: 블록 트레이와 버튼은 PC에서도 판 아래에 둔다(오른쪽 패널은 사람·시계·기록·채팅). PC는 18개 격자(쓴 블록 흐리게, 놓을 곳 없으면 🔒), 휴대폰은 남은 블록만 한 줄로 밀어 본다. 휴대폰은 칸을 누르면 미리보기, 같은 칸을 한 번 더 누르거나 [놓기]로 놓는다. 이음점을 누르면 그 점을 덮는 합법 배치를 큰 블록부터 차례로 보여 준다(같은 점을 다시 누르면 다음). [🔍 확대]/[🔍 전체] 단추는 판 위 줄에 둔다(판 안에 두면 칸을 가린다). 키보드: 방향키 이동, R(Shift+R) 돌리기, F 뒤집기, [ ] 블록 바꾸기, N 이음점의 놓는 방법 차례로, Enter 놓기, Esc 취소.
- 컴퓨터: 판이 공개 정보뿐이라 운(04 §5.1)은 쓰지 않는다(`NO_LUCK`).

View File

@@ -3345,6 +3345,134 @@ const PLANS: Record<string, Plan> = {
await host.screenshot({ path: join(SHOTS, 'six-nimmt-pro-result-pc.png') });
if (st.drafts !== 20 || st.selects < 19) throw new Error(`too few real steps: ${JSON.stringify(st)}`);
console.log(` six-nimmt-pro: ${st.drafts} draft picks, ${st.selects} card picks, ${st.rows} row choices, ${st.spots} spot choices`);
gemblo: {
// PC 방장 + 휴대폰 친구(2명 → 2색씩, 4인 구역). PC 첫 수는 키보드(N으로 이음점의 놓는 방법 → Enter), 그다음은 마우스로
// 이음점 누르기 → [놓기]. 휴대폰은 블록 고르기 → 칸 누르기(안 되는 자리는 빨간 미리보기·이유, [놓기] 꺼짐) → 이음점을 두 번
// 눌러 다음 방법으로 바꾸기 → [놓기]. 16수 뒤 320px 화면·어두운 화면 확인, 휴대폰 쪽이 기권해 결과까지.
lobby: async (host) => {
await host.getByRole('group', { name: '시간' }).getByRole('button', { name: '시간 제한 없음' }).click();
await host.getByText(/^시간 제한 없음/).first().waitFor();
},
drive: async (pages) => {
const [host, guest] = pages as [Page, Page];
const svg = (p: Page) => p.locator('svg.gm-board');
await svg(host).waitFor();
await svg(guest).waitFor();
const placed = async (p: Page) => Number(await svg(p).getAttribute('data-placements'));
const mine = async (p: Page) => (await svg(p).getAttribute('data-my-turn')) === '1';
const center = async (p: Page, sel: string) => {
const b = await p.locator(sel).first().boundingBox();
if (!b) throw new Error(`no box for ${sel}`);
return { x: b.x + b.width / 2, y: b.y + b.height / 2 };
};
const tapAt = async (p: Page, sel: string) => {
const { x, y } = await center(p, sel);
if (tag(p) === 'phone') await p.touchscreen.tap(x, y);
else await p.mouse.click(x, y);
};
const st = { keyboard: false, mouse: 0, phone: 0, refused: false, cycled: false };
let turns = 0;
for (let t = 0; t < 400 && turns < 16; t++) {
const p = (await mine(host)) ? host : (await mine(guest)) ? guest : null;
if (!p) {
await host.waitForTimeout(150);
continue;
}
const before = await placed(p);
if (p === host && !st.keyboard) {
await keys(host, ['n']);
await host.waitForFunction(() => document.querySelector('svg.gm-board')?.getAttribute('data-preview') === 'ok', null, { timeout: 5000 });
await host.screenshot({ path: join(SHOTS, 'gemblo-preview-pc.png') });
await host.keyboard.press('Enter');
st.keyboard = true;
} else if (p === host) {
if (st.mouse === 1) {
// A spot that doesn't work: red preview with the reason while hovering.
await host.locator('.gm-tray [data-piece]:not([disabled]):not([data-locked])').first().click();
// Over my own block: "다른 블록과 겹쳐요".
const { x, y } = await center(host, `[data-block][data-color="${await host.locator('[data-chip].turn, .gm-chip.turn').first().getAttribute('data-chip')}"] polygon`);
await host.mouse.move(x, y);
await host.waitForFunction(() => document.querySelector('svg.gm-board')?.getAttribute('data-preview') === 'bad', null, { timeout: 5000 });
await host.screenshot({ path: join(SHOTS, 'gemblo-refused-pc.png') });
await host.keyboard.press('Escape');
await svg(host).focus();
await host.keyboard.press('Escape');
await host.mouse.move(5, 5);
}
await tapAt(host, '[data-link]');
await host.waitForFunction(() => document.querySelector('svg.gm-board')?.getAttribute('data-preview') === 'ok', null, { timeout: 5000 });
await host.getByRole('button', { name: /^놓기 · / }).click();
st.mouse++;
} else {
if (!st.refused) {
// Pick a block, tap a cell next to my own colour (or anywhere that doesn't work): red preview, [놓기] off.
await guest.locator('.gm-tray [data-piece]:not([disabled])').first().tap();
const cells = await guest.locator('polygon[data-free]').evaluateAll((els) => els.map((e) => e.getAttribute('data-cell')!));
for (const c of cells.slice(0, 40)) {
const box = await guest.locator(`[data-cell="${c}"]`).boundingBox();
if (!box || box.y < 0) continue;
await guest.touchscreen.tap(box.x + box.width / 2, box.y + box.height / 2);
if ((await svg(guest).getAttribute('data-preview')) === 'bad') break;
}
if ((await svg(guest).getAttribute('data-preview')) !== 'bad') throw new Error('no refused preview on the phone');
if (await guest.getByRole('button', { name: /^놓기/ }).isEnabled()) throw new Error('[놓기] enabled for a refused spot');
await guest.waitForTimeout(300);
await guest.screenshot({ path: join(SHOTS, 'gemblo-refused-phone.png') });
await guest.getByRole('button', { name: '취소' }).tap();
st.refused = true;
}
await tapAt(guest, '[data-link]');
await guest.waitForFunction(() => document.querySelector('svg.gm-board')?.getAttribute('data-preview') === 'ok', null, { timeout: 5000 });
const first = await svg(guest).locator('[data-preview-cells]').getAttribute('data-preview-cells');
await tapAt(guest, '[data-link]');
await guest.waitForTimeout(150);
const second = await svg(guest).locator('[data-preview-cells]').getAttribute('data-preview-cells');
if (first !== second) st.cycled = true;
if (st.phone === 0) await guest.screenshot({ path: join(SHOTS, 'gemblo-cycle-phone.png') });
await guest.getByRole('button', { name: /^놓기 · / }).tap();
st.phone++;
}
await p.waitForFunction((n) => Number(document.querySelector('svg.gm-board')?.getAttribute('data-placements')) > n, before, { timeout: 5000 });
turns++;
await host.waitForTimeout(120);
}
if (turns < 16) throw new Error(`only ${turns} turns (${JSON.stringify(st)})`);
if (!st.cycled) throw new Error('tapping the same link point twice never changed the placement');
await host.waitForTimeout(400);
await host.screenshot({ path: join(SHOTS, 'gemblo-mid-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'gemblo-mid-phone.png') });
await guest.screenshot({ path: join(SHOTS, 'gemblo-mid-phone-full.png'), fullPage: true });
await guest.setViewportSize({ width: 320, height: 640 });
await guest.waitForTimeout(400);
await guest.screenshot({ path: join(SHOTS, 'gemblo-mid-phone-320.png'), fullPage: true });
const wide = await guest.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 1);
if (wide) throw new Error('board screen overflows at 320px');
await host.emulateMedia({ colorScheme: 'dark' });
await guest.emulateMedia({ colorScheme: 'dark' });
await host.waitForTimeout(300);
await host.screenshot({ path: join(SHOTS, 'gemblo-mid-pc-dark.png') });
await guest.screenshot({ path: join(SHOTS, 'gemblo-mid-phone-320-dark.png') });
await host.emulateMedia({ colorScheme: 'light' });
await guest.emulateMedia({ colorScheme: 'light' });
await guest.setViewportSize({ width: 390, height: 844 });
// Zoom in and back (phone).
await guest.getByRole('button', { name: '내 블록 근처 확대' }).tap();
if (Number(await svg(guest).getAttribute('data-zoom')) <= 1) throw new Error('zoom did not change');
await guest.screenshot({ path: join(SHOTS, 'gemblo-zoom-phone.png') });
await guest.getByRole('button', { name: '판 전체 보기' }).tap();
await guest.getByRole('button', { name: '🏳 기권' }).tap();
await guest.getByRole('button', { name: '기권하기' }).tap();
await host.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 10_000 });
await guest.getByRole('dialog', { name: '게임 결과' }).waitFor({ timeout: 10_000 });
await host.waitForTimeout(600);
await host.screenshot({ path: join(SHOTS, 'gemblo-result-pc.png') });
await guest.screenshot({ path: join(SHOTS, 'gemblo-result-phone.png') });
const summary = await host.getByRole('dialog', { name: '게임 결과' }).innerText();
if (!/기권으로 .+ 승리/.test(summary)) throw new Error(`unexpected result: ${summary.slice(0, 120)}`);
await host.keyboard.press('Escape');
await host.locator('section[aria-label="남은 블록"]').waitFor();
await host.screenshot({ path: join(SHOTS, 'gemblo-final-pc.png'), fullPage: true });
console.log(` gemblo: ${turns} placements ${JSON.stringify(st)}, ${summary.split('\n').find((l) => l.includes('승리'))}`);
},
},
};

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);