diff --git a/apps/server/src/rooms/gemblo.room.test.ts b/apps/server/src/rooms/gemblo.room.test.ts new file mode 100644 index 0000000..94cca14 --- /dev/null +++ b/apps/server/src/rooms/gemblo.room.test.ts @@ -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; +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, room: Room, a: ReturnType['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']); + }); +}); diff --git a/apps/web/src/games/gemblo/draw.tsx b/apps/web/src/games/gemblo/draw.tsx new file mode 100644 index 0000000..8d11441 --- /dev/null +++ b/apps/web/src/games/gemblo/draw.tsx @@ -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 = { + 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 ; + case 'yellow': + return ; + case 'green': + return ; + case 'blue': + return ; + 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 ; + } + case 'orange': + return ; + case 'gold': + return ; + } +} + +/** 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 ; + return ( + + + + + + ); +} + +/** 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 ( + + {cells.map(([x, y], i) => ( + + ))} + + ); +} + +/** 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 ( + + + {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 ; + return ( + + + {c?.mark === 'ghost' && c.color && } + {c?.mark === 'bad' && } + {c?.mark === 'start' && } + {c?.mark === 'link' && } + + ); + })} + {lines.map(([q1, r1, q2, r2], i) => { + const [x1, y1] = hx(q1, r1); + const [x2, y2] = hx(q2, r2); + return ; + })} + {crosses.map(([q, r], i) => { + const [x, y] = hx(q, r); + return ; + })} + + ); +} diff --git a/apps/web/src/games/gemblo/help.test.ts b/apps/web/src/games/gemblo/help.test.ts new file mode 100644 index 0000000..cef8c1f --- /dev/null +++ b/apps/web/src/games/gemblo/help.test.ts @@ -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('호랑이님이 장애물 블록을 고르고 있어요'); +}); diff --git a/apps/web/src/games/gemblo/help.ts b/apps/web/src/games/gemblo/help.ts new file mode 100644 index 0000000..7ac2228 --- /dev/null +++ b/apps/web/src/games/gemblo/help.ts @@ -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 { + 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'); +} diff --git a/apps/web/src/games/gemblo/index.tsx b/apps/web/src/games/gemblo/index.tsx new file mode 100644 index 0000000..6fa0751 --- /dev/null +++ b/apps/web/src/games/gemblo/index.tsx @@ -0,0 +1,1176 @@ +/** 젬블로 화면 (docs/games/gemblo.md §9). 판은 납작한 육각형 SVG, 블록 트레이와 버튼은 판 아래. */ +import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import type { BlockColor, ColorId, GembloColorView, GembloMove, GembloOptions, GembloPlayerView, GembloView, PieceId, Placement } from '@bg/games/gemblo'; +import { + CELLS, + COLOR_KO, + DIAG, + IN_LAYOUT, + PIECE_BY_ID, + PIECE_IDS, + PIECE_SIZE, + bridgeOpen, + cellAt, + legalPlacements, + obstacleRefusal, + ownCells, + pieceOffsets, + placementCells, + placementRefusal, +} from '@bg/games/gemblo/board'; +import type { PublicUser } from '@bg/shared/lite'; +import { Avatar, ConfirmSheet, Sheet } from '../../components/ui'; +import { TurnTimer, useServerNow } from '../../components/TurnTimer'; +import { haptic } from '../../lib/feedback'; +import { toast } from '../../store/toast'; +import { BOARD_MOTION_CSS, useMoveDiff } from '../board-motion'; +import type { BoardProps, GameUI, OptionsProps } from '../types'; +import { GEM, GemCell, MiniHex, PieceIcon, SQ3, hexPoints, hx } from './draw'; +import { helpNow } from './help'; +import { quickStart } from './quick'; +import { gmSound } from './sound'; + +// ---------------------------------------------------------------- geometry (screen) + +const CELL_XY = CELLS.map((c) => hx(c.q, c.r)); +const CELL_PTS = CELL_XY.map(([x, y]) => hexPoints(x, y, 0.94)); +type Box = { x: number; y: number; w: number; h: number }; +const BOXES: Record = Object.fromEntries( + (['full', 'four', 'three', 'duo'] as const).map((l) => { + const xs: number[] = []; + const ys: number[] = []; + CELL_XY.forEach(([x, y], i) => { + if (IN_LAYOUT[l][i]) { + xs.push(x); + ys.push(y); + } + }); + const x = Math.min(...xs) - 1.4; + const y = Math.min(...ys) - 1.2; + return [l, { x, y, w: Math.max(...xs) + 1.4 - x, h: Math.max(...ys) + 1.2 - y }]; + }), +) as Record; + +/** Screen point → cell (cube rounding), -1 off the board. */ +function cellFromXY(x: number, y: number): number { + const q = x / 1.5; + const r = y / SQ3 - q / 2; + const s = -q - r; + let rq = Math.round(q); + let rr = Math.round(r); + const rs = Math.round(s); + const dq = Math.abs(rq - q); + const dr = Math.abs(rr - r); + const ds = Math.abs(rs - s); + if (dq > dr && dq > ds) rq = -rr - rs; + else if (dr > ds) rr = -rq - rs; + return cellAt(rq, rr); +} + +/** Keyboard moves on the hex grid: ↑↓ along the column, ←→ keep the screen row. */ +function stepCell(cell: number, key: string): number { + const { q, r } = CELLS[cell]!; + let t = -1; + if (key === 'ArrowUp') t = cellAt(q, r - 1); + else if (key === 'ArrowDown') t = cellAt(q, r + 1); + else if (key === 'ArrowLeft' || key === 'ArrowRight') { + const q2 = key === 'ArrowLeft' ? q - 1 : q + 1; + const row = r + (q - (q & 1)) / 2; + t = cellAt(q2, row - (q2 - (q2 & 1)) / 2); + } + return t >= 0 ? t : cell; +} + +/** Which cell of the block follows the pointer: the one nearest its middle. */ +function grabIndex(id: PieceId, o: number): number { + const offs = pieceOffsets(id, o).map(([q, r]) => hx(q, r)); + const mx = offs.reduce((a, c) => a + c[0], 0) / offs.length; + const my = offs.reduce((a, c) => a + c[1], 0) / offs.length; + let best = 0; + offs.forEach(([x, y], i) => { + if (Math.hypot(x - mx, y - my) < Math.hypot(offs[best]![0] - mx, offs[best]![1] - my)) best = i; + }); + return best; +} + +const rotateO = (o: number, d: 1 | -1) => (o >= 6 ? 6 : 0) + (((o % 6) + d + 6) % 6); +/** Mirror the block as it looks now: M ∘ R^k = R^-k ∘ M. */ +const flipO = (o: number) => (o >= 6 ? 0 : 6) + ((6 - (o % 6)) % 6); + +// ---------------------------------------------------------------- words + +/** 은/는 after a colour name. */ +const eun = (c: BlockColor) => `${COLOR_KO[c]}${c === 'purple' ? '는' : '은'}`; +const nickOf = (players: Record, id: string | null) => (id ? (players[id]?.nickname ?? '알 수 없음') : ''); +const pieceName = (id: PieceId) => PIECE_BY_ID[id].nameKo; + +function moveText(m: GembloMove, players: Record): string { + if (m.kind === 'place') return `${COLOR_KO[m.color]} ${pieceName(m.pieceId)}${m.auto ? '(자동)' : ''}`; + if (m.kind === 'pass') return `${COLOR_KO[m.color]} 쉼(시간 초과)`; + if (m.kind === 'obstacle') return m.seq === null ? `장애물 ${pieceName(m.pieceId)} 빠짐` : `장애물 ${pieceName(m.pieceId)}${m.by ? ` · ${nickOf(players, m.by)}` : ''}`; + const why = m.reason === 'allPlaced' ? '모두 놓음' : m.reason === 'blocked' ? `끝(남은 ${m.leftCells}칸)` : m.reason === 'resign' ? '기권' : '시간패'; + return `${COLOR_KO[m.color]} ${why}`; +} + +const CSS = ` +.gm-board * { pointer-events: none; } +.gm-board { touch-action: none; user-select: none; -webkit-user-select: none; } +.gm-board.fit { touch-action: pan-y; } +.gm-link { animation: gm-pulse 1.6s ease-in-out infinite; } +@keyframes gm-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .45; } } +.gm-spark { transform-box: fill-box; transform-origin: center; animation: gm-spark .7s ease-out .15s both; pointer-events: none; } +@keyframes gm-spark { 0% { opacity: 0; transform: scale(.3) rotate(0deg); } 30% { opacity: 1; } 100% { opacity: 0; transform: scale(1.6) rotate(45deg); } } +.gm-shake { animation: gm-shake 320ms ease both; } +@keyframes gm-shake { 20%, 60% { transform: translateX(-0.25px); } 40%, 80% { transform: translateX(0.25px); } } +.gm-tray { display: flex; gap: 6px; } +.gm-tray.gm-grid { flex-wrap: wrap; justify-content: center; } +.gm-tray.gm-line { flex-wrap: nowrap; overflow-x: auto; overscroll-behavior-x: contain; padding-bottom: 4px; scrollbar-width: thin; } +.gm-piece { position: relative; flex: 0 0 auto; min-width: 48px; min-height: 48px; padding: 2px; border-radius: 10px; border: 2px solid var(--border); background: var(--surface); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; } +.gm-piece[aria-pressed='true'] { border-color: var(--focus); box-shadow: 0 0 0 2px var(--focus); } +.gm-piece:disabled { cursor: default; } +.gm-piece .gm-lock { position: absolute; right: 1px; bottom: 0; font-size: .7rem; } +.gm-piece.used { opacity: .3; } +.gm-ctrl { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; } +.gm-ctrl .btn { min-height: 46px; padding-inline: 6px; white-space: nowrap; font-size: .95rem; } +.gm-ctrl .gm-go { grid-column: span 2; } +.gm-ctrl.wide { grid-template-columns: 1fr 1fr 1fr 0.8fr 2fr; } +.gm-ctrl.wide .gm-go { grid-column: auto; } +.gm-strip { display: flex; align-items: center; gap: 8px; justify-content: center; font-weight: 700; flex-wrap: wrap; text-align: center; } +.gm-dot { width: 14px; height: 14px; border-radius: 50%; display: inline-block; border: 2px solid rgba(255,255,255,.8); box-shadow: 0 0 0 1px rgba(0,0,0,.25); } +.gm-hint { min-height: 1.4em; text-align: center; font-weight: 700; margin: 0; } +.gm-hint.bad { color: var(--danger); } +.gm-top { display: flex; align-items: center; gap: 8px; } +.gm-top .gm-strip { flex: 1; min-width: 0; } +.gm-zoom { flex: 0 0 auto; min-height: 36px; padding: 0 10px; font-size: .85rem; } +.gm-chips { display: flex; gap: 6px; flex-wrap: wrap; } +.gm-chip { display: inline-flex; align-items: center; gap: 4px; padding: 1px 6px; border-radius: 999px; font-size: .8rem; font-weight: 700; background: var(--surface-2); } +.gm-chip.turn { box-shadow: 0 0 0 2px var(--focus); } +.gm-chip.done { opacity: .55; } +.gm-left { display: flex; flex-wrap: wrap; gap: 2px; } +@media (prefers-reduced-motion: reduce) { .gm-link { animation: none; } } +`; + +// ---------------------------------------------------------------- board layers + +interface CellsProps { + layout: GembloView['layout']; + board: number[]; + placements: GembloView['placements']; + starts: { color: ColorId; cell: number }[]; + fresh: number; + lastSeq: number | null; + glow: number; +} + +/** Everything that changes only when a block is placed (463 cells, blocks, starts). */ +const BoardCells = memo(function BoardCells({ layout, board, placements, starts, fresh, lastSeq, glow }: CellsProps) { + const inL = IN_LAYOUT[layout]; + return ( + <> + {CELL_PTS.map((pts, i) => + board[i]! >= 0 ? null : , + )} + {starts.map((s) => ( + + ))} + {placements.map((p) => { + const isNew = p.seq >= fresh; + return ( + + {p.cells.map((c) => ( + + ))} + + ); + })} + {placements + .filter((p) => p.seq >= fresh) + .map((p) => { + const [x, y] = CELL_XY[p.cells[0]!]!; + return ; + })} + {lastSeq !== null && + placements[lastSeq]?.cells.map((c) => )} + + ); +}); + +interface Preview { + pieceId: PieceId; + orient: number; + q: number; + r: number; + /** Cells on the board (off-board ones dropped). */ + cells: number[]; + why: string | null; + links: [number, number][]; + crosses: [number, number][]; +} + +type Pin = { q: number; r: number }; +type Cycle = { point: number; list: Placement[]; k: number }; + +// ---------------------------------------------------------------- board + +function GembloBoard({ view: v, me, players, act, pending }: BoardProps) { + const wrapRef = useRef(null); + const svgRef = useRef(null); + const [width, setWidth] = useState(800); + // Measure the column the board sits in (not the board itself, whose width depends on `narrow`). + useLayoutEffect(() => { + const el = wrapRef.current?.parentElement ?? wrapRef.current; + if (!el) return; + setWidth(el.clientWidth); + const ro = new ResizeObserver(() => setWidth(el.clientWidth)); + ro.observe(el); + return () => ro.disconnect(); + }, []); + const narrow = width < 600; + + const turnColor = v.colors[v.turn]!; + const myTurn = v.phase === 'playing' && v.turnPlayer === me && v.legal !== null; + const myObstacle = v.phase === 'obstaclePlace' && v.turnPlayer === me; + const myPick = v.phase === 'obstacleDraft' && v.turnPlayer === me; + const placing: 'color' | 'obstacle' | null = myTurn ? 'color' : myObstacle ? 'obstacle' : null; + const drawColor: BlockColor = placing === 'obstacle' ? 'gold' : turnColor.color; + const allowFlip = placing === 'obstacle' ? true : v.allowFlip; + const hand: PieceId[] = placing === 'color' ? turnColor.left : placing === 'obstacle' ? (v.obstacle?.hands[me ?? ''] ?? []) : []; + const placeable = new Set(placing === 'color' ? (v.legal?.placeable ?? []) : hand); + const links = useMemo(() => (myTurn ? (v.legal?.bridgePoints ?? []) : []), [myTurn, v.legal]); + const linkSet = useMemo(() => new Set(links), [links]); + + const [sel, setSel] = useState(null); + const [orient, setOrient] = useState(0); + const [pin, setPin] = useState(null); + const [hover, setHover] = useState(null); + const [cursor, setCursor] = useState(() => cellAt(turnColor.start.q, turnColor.start.r)); + const [kbd, setKbd] = useState(false); + const [cycle, setCycle] = useState(null); + const [announce, setAnnounce] = useState(''); + const [shake, setShake] = useState(0); + const [zoom, setZoom] = useState<{ z: number; cx: number; cy: number } | null>(null); + + const box = BOXES[v.layout]; + // 휴대폰에서 판 전체(463칸)는 칸이 너무 작아 기본은 내 블록 근처 2배 확대. 3인·4인 구역과 듀오는 구역에 맞춤. + const defaultZ = narrow && v.layout === 'full' ? 2 : 1; + const focus = useMemo(() => { + const mine = v.myColors.map((i) => v.colors[i]!); + const color = mine.find((c) => c.color === turnColor.color) ?? mine.find((c) => !c.done) ?? mine[0]; + if (!color) return { x: box.x + box.w / 2, y: box.y + box.h / 2 }; + const pts = links.length ? links : ownCells(v, color.color); + if (!pts.length) return { x: hx(color.start.q, color.start.r)[0], y: hx(color.start.q, color.start.r)[1] }; + return { x: pts.reduce((a, c) => a + CELL_XY[c]![0], 0) / pts.length, y: pts.reduce((a, c) => a + CELL_XY[c]![1], 0) / pts.length }; + }, [v, links, turnColor.color, box]); + const z = zoom?.z ?? defaultZ; + const vw = box.w / z; + const vh = box.h / z; + const clampX = (x: number) => Math.min(box.x + box.w - vw / 2, Math.max(box.x + vw / 2, x)); + const clampY = (y: number) => Math.min(box.y + box.h - vh / 2, Math.max(box.y + vh / 2, y)); + const cx = clampX(zoom?.cx ?? focus.x); + const cy = clampY(zoom?.cy ?? focus.y); + + // New turn of mine: forget the old preview, put the cursor on a link point, re-centre the zoomed view. + useEffect(() => { + setPin(null); + setCycle(null); + if (placing === 'color' && links.length) setCursor(links[0]!); + if (placing) setZoom((zz) => (zz && zz.z > 1 ? null : zz)); + if (sel && !hand.includes(sel)) setSel(null); + }, [v.turn, v.phase, v.placements.length]); // eslint-disable-line react-hooks/exhaustive-deps + + // Sounds, toasts, screen-reader lines for what just happened (anyone's move). + const { before, forward } = useMoveDiff({ n: v.placements.length, h: v.history.length }, v.placements.length * 1000 + v.history.length); + const fresh = before && forward ? before.n : Infinity; + const glowKey = v.placements.length; + const prevHist = useRef(v.history.length); + useLayoutEffect(() => { + const prev = prevHist.current; + prevHist.current = v.history.length; + if (v.history.length < prev) { + gmSound.undo(); + setAnnounce('무르기로 블록 하나를 되돌렸어요.'); + return; + } + if (v.history.length === prev) return; + const added = v.history.slice(prev); + if (added.some((m) => m.kind === 'place' || (m.kind === 'obstacle' && m.seq !== null))) gmSound.place(); + for (const m of added) { + if (m.kind !== 'out') continue; + if (m.reason === 'blocked') { + toast(`${eun(m.color)} 더 놓을 곳이 없어요(남은 ${m.leftCells}칸)`); + gmSound.out(); + } else if (m.reason === 'allPlaced') { + toast(`${eun(m.color)} 18개를 모두 놓았어요!`); + gmSound.allPlaced(); + } + } + setAnnounce(added.map((m) => moveText(m, players)).join('. ')); + if (v.phase === 'playing' && v.turnPlayer === me) haptic(40); + }, [v.history.length]); // eslint-disable-line react-hooks/exhaustive-deps + + /** Anchor (first base cell) that puts the grab cell of `sel` on `cell`. */ + const anchorAt = (cell: number, id: PieceId, o: number): Pin => { + const off = pieceOffsets(id, o)[grabIndex(id, o)]!; + return { q: CELLS[cell]!.q - off[0], r: CELLS[cell]!.r - off[1] }; + }; + + const judge = (id: PieceId, o: number, at: Pin): Preview => { + const offs = pieceOffsets(id, o); + const cells = offs.map(([dq, dr]) => cellAt(at.q + dq, at.r + dr)).filter((c) => c >= 0); + let why: string | null; + if (placing === 'obstacle') { + const full = placementCells(id, o, at.q, at.r); + why = !hand.includes(id) ? '내가 고른 블록이 아니에요.' : !full ? '판 밖이에요.' : obstacleRefusal(v, full, v.obstacle!.sectorCount); + } else why = placementRefusal(v, turnColor, id, o, at.q, at.r, v.allowFlip); + const lk: [number, number][] = []; + const cr: [number, number][] = []; + if (placing === 'color' && v.showHints && (why === null || why === '이 선은 다른 블록에 막혀 있어요.')) { + const own = new Set(ownCells(v, turnColor.color)); + for (const b of cells) { + for (let k = 0; k < 6; k++) { + const j = (b * 6 + k) * 3; + const a = DIAG[j]!; + if (a < 0 || !own.has(a)) continue; + if (bridgeOpen(v, DIAG[j + 1]!, DIAG[j + 2]!)) lk.push([a, b]); + else cr.push([DIAG[j + 1]!, DIAG[j + 2]!]); + } + } + } + return { pieceId: id, orient: o, q: at.q, r: at.r, cells, why, links: lk, crosses: why === null ? [] : cr }; + }; + + const at: Pin | null = !placing || !sel ? null : (pin ?? (hover !== null ? anchorAt(hover, sel, orient) : kbd ? anchorAt(cursor, sel, orient) : null)); + const preview = sel && at ? judge(sel, orient, at) : null; + + const refuse = (msg: string) => { + gmSound.refuse(); + haptic([30, 30, 30]); + setShake((n) => n + 1); + setAnnounce(msg); + toast(msg); + }; + + const commit = (p: Preview | null) => { + if (!p || pending) return; + if (p.why) { + refuse(p.why); + return; + } + act({ type: placing === 'obstacle' ? 'placeObstacle' : 'place', pieceId: p.pieceId, orient: p.orient, q: p.q, r: p.r }); + setPin(null); + setCycle(null); + setSel(null); + setHover(null); + }; + + const choose = (id: PieceId) => { + if (!placing || !hand.includes(id)) return; + if (sel === id) { + setSel(null); + setPin(null); + return; + } + gmSound.turn(); + setSel(id); + setCycle(null); + // Keep the spot the player already chose (the grab cell stays put). + if (pin && sel) { + const g = pieceOffsets(sel, orient)[grabIndex(sel, orient)]!; + setPin(anchorAt(cellAt(pin.q + g[0], pin.r + g[1]), id, orient < 6 || allowFlip ? orient : orient - 6)); + } + if (!allowFlip && orient >= 6) setOrient(orient - 6); + setAnnounce(`${pieceName(id)} 블록을 골랐어요. 판에서 놓을 칸을 골라요.${placeable.has(id) ? '' : ' 이 블록은 지금 놓을 곳이 없어요.'}`); + }; + + /** Re-orient around the grab cell. */ + const reorient = (o: number) => { + if (!sel) return; + gmSound.turn(); + if (pin) { + const g = pieceOffsets(sel, orient)[grabIndex(sel, orient)]!; + const cell = cellAt(pin.q + g[0], pin.r + g[1]); + if (cell >= 0) setPin(anchorAt(cell, sel, o)); + } + setOrient(o); + setCycle(null); + }; + const rotate = (d: 1 | -1) => reorient(rotateO(orient, d)); + const flip = () => allowFlip && reorient(flipO(orient)); + + /** 이음점을 누르면 그 점을 덮는 합법 배치를 하나씩 돌아가며 보여 준다. */ + const cycleAt = (point: number) => { + if (placing !== 'color') return; + let list = cycle && cycle.point === point ? cycle.list : []; + let k = cycle && cycle.point === point ? cycle.k + 1 : 0; + if (!list.length) { + const pieces = sel ? [sel] : undefined; + list = legalPlacements(v, turnColor, v.allowFlip, { points: [point], pieces }); + if (!list.length && sel) list = legalPlacements(v, turnColor, v.allowFlip, { points: [point] }); + list.sort((a, b) => PIECE_SIZE[b.pieceId] - PIECE_SIZE[a.pieceId] || PIECE_IDS.indexOf(a.pieceId) - PIECE_IDS.indexOf(b.pieceId)); + k = 0; + } + if (!list.length) { + refuse('이 점을 덮어 놓을 수 있는 블록이 없어요.'); + return; + } + k %= list.length; + const p = list[k]!; + setCycle({ point, list, k }); + setSel(p.pieceId); + setOrient(p.orient); + setPin({ q: p.q, r: p.r }); + setCursor(point); + gmSound.turn(); + setAnnounce(`${pieceName(p.pieceId)}, 놓는 방법 ${k + 1}/${list.length}. 다시 누르면 다음 방법이에요.`); + }; + + // ---------------------------------------------------------------- pointer: tap, hover, drag preview, pan, pinch + const pointers = useRef(new Map()); + const gesture = useRef<{ kind: 'none' | 'drag' | 'pan' | 'pinch'; d0?: number; z0?: number; grab?: number; cx0?: number; cy0?: number }>({ kind: 'none' }); + const toSvg = (clientX: number, clientY: number): [number, number] | null => { + const svg = svgRef.current; + if (!svg) return null; + const pt = svg.createSVGPoint(); + pt.x = clientX; + pt.y = clientY; + const m = svg.getScreenCTM(); + if (!m) return null; + const p = pt.matrixTransform(m.inverse()); + return [p.x, p.y]; + }; + const cellAtClient = (x: number, y: number) => { + const p = toSvg(x, y); + return p ? cellFromXY(p[0], p[1]) : -1; + }; + const unitsPerPx = () => { + const svg = svgRef.current; + return svg ? vw / Math.max(1, svg.clientWidth) : 0.05; + }; + + const tap = (cell: number, mouse: boolean) => { + if (cell < 0) return; + setCursor(cell); + if (!placing) return; + if (placing === 'color' && linkSet.has(cell) && (!mouse || !sel)) { + cycleAt(cell); + return; + } + if (!sel) { + setAnnounce('먼저 아래에서 블록을 골라 주세요.'); + toast(placing === 'color' && v.showHints ? '먼저 블록을 고르거나, 내 색 점(이음점)을 눌러 보세요' : '먼저 아래에서 블록을 골라 주세요'); + return; + } + const target = anchorAt(cell, sel, orient); + if (mouse) { + commit(judge(sel, orient, target)); + return; + } + // Touch: the first tap shows the block there; tapping the same spot again places it (or press [놓기]). + if (pin && pin.q === target.q && pin.r === target.r) { + commit(judge(sel, orient, target)); + return; + } + setPin(target); + setCycle(null); + const j = judge(sel, orient, target); + if (j.why) { + gmSound.refuse(); + setShake((n) => n + 1); + } + }; + + const onPointerDown = (e: React.PointerEvent) => { + (e.currentTarget as Element).setPointerCapture?.(e.pointerId); + pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY, sx: e.clientX, sy: e.clientY, moved: false, type: e.pointerType }); + if (pointers.current.size === 2) { + const [a, b] = [...pointers.current.values()]; + gesture.current = { kind: 'pinch', d0: Math.hypot(a!.x - b!.x, a!.y - b!.y), z0: z, cx0: cx, cy0: cy }; + return; + } + gesture.current = { kind: 'none' }; + if (e.pointerType !== 'mouse' && preview && pin) { + const c = cellAtClient(e.clientX, e.clientY); + const k = preview.cells.indexOf(c); + if (k >= 0) gesture.current = { kind: 'drag', grab: k }; + } + }; + const onPointerMove = (e: React.PointerEvent) => { + const p = pointers.current.get(e.pointerId); + if (!p) { + if (e.pointerType === 'mouse' && placing) { + const c = cellAtClient(e.clientX, e.clientY); + const h = c >= 0 ? c : null; + if (h !== hover) { + setHover(h); + setKbd(false); + } + } + return; + } + const dx = e.clientX - p.x; + const dy = e.clientY - p.y; + p.x = e.clientX; + p.y = e.clientY; + if (Math.hypot(e.clientX - p.sx, e.clientY - p.sy) > 8) p.moved = true; + const g = gesture.current; + if (g.kind === 'pinch' && pointers.current.size === 2) { + const [a, b] = [...pointers.current.values()]; + const d = Math.hypot(a!.x - b!.x, a!.y - b!.y); + const nz = Math.min(3, Math.max(1, (g.z0! * d) / Math.max(1, g.d0!))); + setZoom({ z: nz, cx: g.cx0!, cy: g.cy0! }); + return; + } + if (!p.moved) return; + if (g.kind === 'drag' && sel && preview) { + const c = cellAtClient(e.clientX, e.clientY); + if (c < 0) return; + const off = pieceOffsets(sel, orient)[g.grab!]!; + const next = { q: CELLS[c]!.q - off[0], r: CELLS[c]!.r - off[1] }; + if (!pin || pin.q !== next.q || pin.r !== next.r) setPin(next); + return; + } + if (z > 1 && e.pointerType !== 'mouse') { + gesture.current = { kind: 'pan' }; + const u = unitsPerPx(); + setZoom({ z, cx: clampX(cx - dx * u), cy: clampY(cy - dy * u) }); + } else if (z > 1 && e.pointerType === 'mouse' && (e.buttons & 1)) { + gesture.current = { kind: 'pan' }; + const u = unitsPerPx(); + setZoom({ z, cx: clampX(cx - dx * u), cy: clampY(cy - dy * u) }); + } + }; + const onPointerUp = (e: React.PointerEvent) => { + const p = pointers.current.get(e.pointerId); + pointers.current.delete(e.pointerId); + if (!p) return; + const g = gesture.current; + if (pointers.current.size === 0) gesture.current = { kind: 'none' }; + if (g.kind === 'pinch' || g.kind === 'pan' || p.moved) return; + setKbd(false); + tap(cellAtClient(e.clientX, e.clientY), e.pointerType === 'mouse'); + }; + + // Wheel turns the block in hand (PC). Needs a non-passive listener to keep the page from scrolling. + const wheelRef = useRef<(e: WheelEvent) => void>(() => {}); + wheelRef.current = (e: WheelEvent) => { + if (!sel || !placing) return; + e.preventDefault(); + rotate(e.deltaY > 0 ? 1 : -1); + }; + useEffect(() => { + const svg = svgRef.current; + if (!svg) return; + const fn = (e: WheelEvent) => wheelRef.current(e); + svg.addEventListener('wheel', fn, { passive: false }); + return () => svg.removeEventListener('wheel', fn); + }, []); + + const placeableList = hand.filter((id) => placeable.has(id)); + const onKey = (e: React.KeyboardEvent) => { + setKbd(true); + const k = e.key; + if (k.startsWith('Arrow')) { + e.preventDefault(); + const next = stepCell(cursor, k); + setCursor(next); + setPin(null); + const c = CELLS[next]!; + const who = v.board[next]! >= 0 ? `${COLOR_KO[v.placements[v.board[next]!]!.color]} 블록` : IN_LAYOUT[v.layout][next] ? (linkSet.has(next) ? '이음점' : '빈칸') : '안 쓰는 칸'; + setAnnounce(`${c.q}, ${c.r} ${who}`); + } else if (k === 'r' || k === 'R') { + e.preventDefault(); + rotate(e.shiftKey ? -1 : 1); + } else if (k === 'f' || k === 'F') { + e.preventDefault(); + flip(); + } else if (k === '[' || k === ']') { + e.preventDefault(); + if (!placeableList.length) return; + const i = sel ? placeableList.indexOf(sel) : -1; + const next = placeableList[(i + (k === ']' ? 1 : -1) + placeableList.length) % placeableList.length]!; + choose(next); + } else if (k === 'n' || k === 'N' || k === ' ') { + e.preventDefault(); + if (linkSet.has(cursor)) cycleAt(cursor); + else if (links.length) { + setCursor(links[0]!); + cycleAt(links[0]!); + } + } else if (k === 'Escape') { + setSel(null); + setPin(null); + setCycle(null); + } else if (k === 'Enter') { + e.preventDefault(); + if (preview) commit(preview); + else if (linkSet.has(cursor)) cycleAt(cursor); + else if (placing) setAnnounce('블록을 고르거나 N 키로 놓을 수 있는 방법을 차례로 보세요.'); + } + }; + + const starts = useMemo( + () => v.colors.filter((c) => c.placed === 0 && !c.done).map((c) => ({ color: c.color, cell: cellAt(c.start.q, c.start.r) })), + [v.colors], + ); + const mineAll = v.myColors.map((i) => v.colors[i]!); + const trayColor: GembloColorView | null = placing === 'color' ? turnColor : (mineAll.find((c) => !c.done) ?? null); + const shownTray: PieceId[] = placing ? hand : myPick ? (v.obstacle?.pool ?? []) : (trayColor?.left ?? []); + const trayAll = !narrow && (placing === 'color' || (!placing && !myPick && trayColor)); + const trayIds = trayAll ? [...PIECE_IDS] : shownTray; + const trayOwnerColor: BlockColor = placing === 'obstacle' || myPick ? 'gold' : (trayColor?.color ?? 'gold'); + + const turnNick = nickOf(players, v.turnPlayer); + const strip = + v.phase === 'playing' ? ( + <> + + + {COLOR_KO[turnColor.color]} 차례 · 남은 {turnColor.leftCells}칸{v.turnPlayer === me ? ' · 내 차례' : turnNick ? ` · ${turnNick}님` : ''} + + + ) : v.phase === 'obstacleDraft' ? ( + + 장애물 고르기 · {turnNick}님 차례 · 남은 {v.obstacle?.pool.length ?? 0}개 + + ) : v.phase === 'obstaclePlace' ? ( + + 장애물 놓기 · {turnNick}님 차례 · 남은 {v.obstacle?.remaining ?? 0}개 + + ) : ( + 게임이 끝났어요 + ); + + const hintText = !placing + ? myPick + ? '장애물로 쓸 블록을 하나 골라 주세요.' + : '' + : !sel + ? placing === 'color' + ? v.showHints + ? narrow + ? '블록을 고르거나, 판의 내 색 점을 눌러 보세요.' + : '블록을 고르거나, 판의 내 색 점(이음점)을 눌러 보세요.' + : '아래에서 블록을 골라 주세요.' + : '장애물로 놓을 블록을 골라 주세요.' + : !preview + ? narrow + ? '판의 칸을 눌러 놓을 자리를 골라요.' + : '판 위로 마우스를 옮겨 자리를 골라요. 휠·R 돌리기, F 뒤집기.' + : preview.why + ? preview.why + : `${pieceName(preview.pieceId)} 놓을 수 있어요${cycle ? ` (${cycle.k + 1}/${cycle.list.length})` : ''}`; + + const aspect = box.w / box.h; + return ( +
+ +
+
+ {strip} +
+ +
+
+ { + pointers.current.delete(e.pointerId); + gesture.current = { kind: 'none' }; + }} + onPointerLeave={(e) => e.pointerType === 'mouse' && setHover(null)} + > + + {placing === 'color' && + v.showHints && + links.map((c) => ( + + ))} + {preview && ( + + {preview.cells.map((c) => ( + + ))} + {preview.links.map(([a, b], i) => { + const [x1, y1] = CELL_XY[a]!; + const [x2, y2] = CELL_XY[b]!; + return ; + })} + {preview.crosses.map(([m1, m2], i) => { + const x = (CELL_XY[m1]![0] + CELL_XY[m2]![0]) / 2; + const y = (CELL_XY[m1]![1] + CELL_XY[m2]![1]) / 2; + return ; + })} + + )} + {kbd && placing && } + +
+

+ {announce} +

+ {(placing || myPick) && ( +

+ {hintText} +

+ )} + {trayIds.length > 0 && v.phase !== 'finished' && (placing || myPick || trayColor) && ( +
+ {trayIds.map((id) => { + const used = placing === 'color' ? !hand.includes(id) : !placing && !myPick && trayColor ? !trayColor.left.includes(id) : false; + const locked = placing === 'color' && !used && !placeable.has(id); + const can = myPick ? !pending : !!placing && !used; + return ( + + ); + })} +
+ )} + {placing && ( +
+ + + + + +
+ )} + {v.phase === 'finished' && } +
+ ); +} + +/** 끝나면 남은 블록을 색별로 판 옆에 펼쳐 보여 준다. */ +function LeftPieces({ view: v, players }: { view: GembloView; players: Record }) { + return ( +
+ 남은 블록 + {v.colors.map((c) => ( +
+ + + {COLOR_KO[c.color]} · {nickOf(players, c.owner)} + + {c.left.length === 0 ? ( + 모두 놓음 ✨ + ) : ( + + {c.left.map((id) => ( + + ))} + + )} +
+ ))} +
+ ); +} + +// ---------------------------------------------------------------- side panel + +function ColorChip({ v, i }: { v: GembloView; i: number }) { + const c = v.colors[i]!; + const turn = v.phase === 'playing' && v.turn === i; + const state = c.done ? (c.doneReason === 'allPlaced' ? '✓' : c.doneReason === 'blocked' ? '끝' : c.doneReason === 'resign' ? '기권' : '시간패') : `${c.leftCells}칸`; + return ( + + + {COLOR_KO[c.color]} {state} + + ); +} + +function PlayerRow({ v, p, players, deadline, me }: { v: GembloView; p: GembloPlayerView; players: Record; deadline: number | null; me: string | null }) { + const u = players[p.id] ?? { id: p.id, nickname: '알 수 없음', avatar: null, kind: 'guest' as const }; + const active = v.phase !== 'finished' && v.turnPlayer === p.id; + const now = useServerNow(500); + const tc = v.timeControl; + let clock: React.ReactNode = null; + if (!p.out && v.phase === 'playing' && tc.kind === 'fischer') { + const ms = Math.max(0, p.remainingMs - (active ? now - v.turnStartedAt : 0)); + const s = Math.ceil(ms / 1000); + clock = ( + + {Math.floor(s / 60)}:{String(s % 60).padStart(2, '0')} + + ); + } else if (active && (tc.kind === 'perMove' || v.phase !== 'playing')) { + clock = ; + } + const left = p.colors.reduce((n, i) => n + v.colors[i]!.leftCells, 0); + const teamColors = p.team !== null && v.teams ? ` · ${p.team + 1}팀` : ''; + return ( +
+
+ +
+
+ {u.nickname} + {p.id === me && (나)} +
+
+ {p.out === 'resign' ? '기권' : p.out === 'timeLoss' ? '시간패' : `남은 ${left}칸`} + {teamColors} + {p.streak > 0 && !p.out ? ` · 자리 비움 ${p.streak}번` : ''} +
+
+ {clock} +
+
+ {p.colors.map((i) => ( + + ))} +
+
+ ); +} + +function GembloSide({ view: v, me, players, act, pending, deadline }: BoardProps) { + const [confirm, setConfirm] = useState(false); + const mine = v.players.find((p) => p.id === me) ?? null; + const live = v.phase !== 'finished' && !!mine && !mine.out; + const u = v.undo.pending; + const incoming = live && u && u.by !== me && !u.accepted.includes(me!) ? u : null; + const waiting = live && u && (u.by === me || u.accepted.includes(me!)); + const order = mine ? [...v.players.filter((p) => p.id !== me), mine] : v.players; + return ( + <> + {order.map((p) => ( + + ))} + {live && ( +
+ {v.undo.allowed && ( + + )} + +
+ )} + {waiting && ( +
+ 다른 사람의 답을 기다리는 중… + {u!.by === me && ( + + )} +
+ )} + + {incoming && ( + {}} label="무르기 요청"> +

{nickOf(players, incoming.by)}님이 무르기를 부탁했어요

+

수락하면 방금 놓은 블록 하나가 되돌려져요.{v.undo.responders.length > 1 ? ' 다른 사람도 모두 수락해야 해요.' : ''}

+
+ + +
+
+ )} + {confirm && ( + act({ type: 'resign' })} + onClose={() => setConfirm(false)} + /> + )} + + ); +} + +function MoveList({ view: v, players }: { view: GembloView; players: Record }) { + const ref = useRef(null); + useEffect(() => { + ref.current?.scrollTo({ top: ref.current.scrollHeight }); + }, [v.history.length]); + if (!v.history.length) return null; + const color = (m: GembloMove): BlockColor => (m.kind === 'obstacle' ? 'gold' : m.color); + return ( +
+ 기록 ({v.history.filter((m) => m.kind === 'place').length}수) +
    + {v.history.map((m, i) => ( +
  1. + + ●{' '} + + {moveText(m, players)} +
  2. + ))} +
+
+ ); +} + +function statusText(v: GembloView, me: string | null, players: Record): string { + if (v.phase === 'finished') return v.result?.summary ?? '게임이 끝났어요'; + const nick = nickOf(players, v.turnPlayer); + const mine = v.turnPlayer === me; + const p = v.undo.pending; + if (p && me && p.by !== me && !p.accepted.includes(me) && v.players.some((x) => x.id === me && !x.out)) return '무르기 요청이 왔어요'; + if (v.phase === 'obstacleDraft') return mine ? '내 차례예요. 장애물로 쓸 블록을 하나 골라요' : `${nick}님이 장애물을 고르는 중이에요`; + if (v.phase === 'obstaclePlace') return mine ? '내 차례예요. 장애물을 판에 놓아요' : `${nick}님이 장애물을 놓는 중이에요`; + const c = v.colors[v.turn]!; + if (mine) return `내 차례예요. ${COLOR_KO[c.color]} 블록을 놓아요`; + return `${nick}님(${COLOR_KO[c.color]}) 차례예요`; +} + +// ---------------------------------------------------------------- options + +function Seg({ value, options, onChange, label: aria }: { value: T; options: [T, string][]; onChange: (v: T) => void; label: string }) { + return ( +
+ {options.map(([k, l]) => ( + + ))} +
+ ); +} + +function Field({ label: title, children }: { label: string; children: React.ReactNode }) { + return ( +
+ {title} + {children} +
+ ); +} + +const TIME_PRESETS: [string, string, Partial][] = [ + ['pm30', '한 번 30초', { kind: 'perMove', perMoveSec: 30 }], + ['pm60', '한 번 60초', { kind: 'perMove', perMoveSec: 60 }], + ['pm90', '한 번 90초', { kind: 'perMove', perMoveSec: 90 }], + ['pm120', '한 번 120초', { kind: 'perMove', perMoveSec: 120 }], + ['f5', '5분 + 5초', { kind: 'fischer', baseSec: 300, incSec: 5 }], + ['f10', '10분 + 5초', { kind: 'fischer', baseSec: 600, incSec: 5 }], + ['none', '시간 제한 없음', { kind: 'none' }], +]; +const timeKey = (tc: GembloOptions['timeControl']) => (tc.kind === 'none' ? 'none' : tc.kind === 'perMove' ? `pm${tc.perMoveSec}` : `f${Math.round(tc.baseSec / 60)}`); +function timeLabel(tc: GembloOptions['timeControl']): string { + if (tc.kind === 'none') return '시간 제한 없음'; + if (tc.kind === 'perMove') return `한 번 ${tc.perMoveSec}초`; + return `${Math.round(tc.baseSec / 60)}분 + ${tc.incSec}초`; +} + +function Options({ value: o, onChange }: OptionsProps) { + const [more, setMore] = useState(false); + const set = (patch: Partial) => onChange({ ...o, ...patch }); + const onOff = (b: boolean) => (b ? 'on' : 'off'); + const known = TIME_PRESETS.some((p) => p[0] === timeKey(o.timeControl)); + return ( +
+ + [k, l] as [string, string]), ...(known ? [] : [[timeKey(o.timeControl), `${timeLabel(o.timeControl)}(관리자 설정)`] as [string, string]])]} + onChange={(k) => { + const preset = TIME_PRESETS.find((p) => p[0] === k); + if (preset) set({ timeControl: { ...o.timeControl, ...preset[2] } }); + }} + /> + + + set({ twoPlayerMode })} /> + + + set({ threePlayerMode })} /> + + + set({ fivePlayerObstacles })} /> + + + set({ allowFlip: k === 'on' })} /> + + + set({ showHints: k === 'on' })} /> + + + {more && ( + <> + + set({ bridgeRule })} /> + + + set({ scoring })} /> + + + set({ teams })} /> + + + set({ neutralBlocks })} /> + + {o.timeControl.kind !== 'fischer' && ( + + set({ timeoutPolicy })} /> + + )} + + [n, `${n}번`] as [number, string])} onChange={(autoMoveLimit) => set({ autoMoveLimit })} /> + + + set({ undo })} /> + + + set({ seatOrder })} /> + + + )} +
+ ); +} + +function optionsSummary(o: GembloOptions): string { + return [ + timeLabel(o.timeControl), + ...(o.allowFlip ? [] : ['뒤집기 금지']), + ...(o.bridgeRule === 'free' ? ['이음선 안 막힘'] : []), + ...(o.scoring === 'blokusBonus' ? ['블로커스 점수'] : []), + ...(o.teams !== 'off' ? ['팀전'] : []), + ...(o.neutralBlocks ? [`금색 블록 ${o.neutralBlocks}개`] : []), + ...(o.twoPlayerMode !== 'twoColors' ? [o.twoPlayerMode === 'duo' ? '2명 듀오' : '2명 3색씩'] : []), + ...(o.undo !== 'off' ? [`무르기 ${o.undo}번`] : []), + ].join(' · '); +} + +// ---------------------------------------------------------------- rules + +function Figure({ children, caption }: { children: React.ReactNode; caption: string }) { + return ( +
+ {children} +
+ {caption} +
+
+ ); +} + +function Rules({ options }: { options?: GembloOptions }) { + const free = options?.bridgeRule === 'free'; + return ( +
+

+ 육각형 칸 1~5개로 된 보석 블록 18개(72칸)를 차례로 판에 하나씩 놓아요. 더 놓을 수 없으면 끝나고, 못 놓은 블록의 칸 수가 가장 적은 사람이 이겨요. +

+
+
+ +
+
+ +
+
+ +
+
+

+ 놓는 규칙: 블록의 모든 칸이 빈칸이어야 하고(겹치기 금지), 같은 색 블록과는 변이 닿으면 안 돼요. 다른 색 블록과는 마음대로 닿아도 돼요. 두 번째 블록부터는 이미 놓은 내 블록의 꼭짓점에서 판의 선을 따라 한 칸 나간 곳(이음점, 판에 내 색 점으로 보여요)을 하나 이상 덮어야 해요. +

+
+
+ +
+
+ +
+
+

+ 막힘: {free ? '이 방은 "이음선 안 막힘" 규칙이라, 사이에 무엇이 있어도 이을 수 있어요.' : '내 칸과 이음점 사이에 낀 두 칸을 다른 블록 하나가 함께 덮고 있으면 그 선은 막혀서 못 지나가요. 서로 다른 블록 두 개가 한 칸씩 덮은 틈은 지나갈 수 있어요.'} +

+

+ 끝과 점수: 차례가 왔는데 그 색이 놓을 곳이 하나도 없으면 그 색은 끝나요(다시 생기지 않아요). 모든 색이 끝나면 남은 블록 칸 수를 세어 적은 사람이 이겨요.{options?.scoring === 'blokusBonus' ? ' 이 방은 블로커스 점수: 남은 칸마다 −1점, 18개를 다 놓으면 +15점, 마지막이 한 칸 블록이면 +20점이에요.' : ''} 2명은 기본으로 2색씩, 3명·4명은 판의 일부만 써요. +

+

+ 놓는 방법: PC는 아래에서 블록을 누르고 판 위로 마우스를 옮기면 반투명하게 미리 보여요. 휠이나 R로 돌리고 F로 뒤집고, 눌러서 놓아요. 휴대폰은 블록을 누르고 칸을 누르면 미리 보이고, 끌어서 옮긴 뒤 [놓기]를 눌러요. 내 색 점(이음점)을 누르면 그 점을 덮는 놓을 수 있는 방법이 바로 나오고, 다시 누르면 다음 방법으로 바뀌어요. 두 손가락으로 확대·이동할 수 있어요. 키보드: 방향키 이동, N 이음점에서 방법 보기, [ ] 블록 바꾸기, Enter 놓기. +

+

팁: 처음엔 5칸 블록으로 판 가운데 쪽으로 자리를 넓히고, 작은 블록은 끝에 틈을 메울 때 써요. 상대의 이음점을 덮으면 길을 막을 수 있어요.

+
+ ); +} + +const ui: GameUI = { + Board: GembloBoard, + Side: GembloSide, + statusText, + isMyTurn: (v, me) => v.phase !== 'finished' && !!me && v.turnPlayer === me, + Options, + optionsSummary, + Rules, + quickStart, + helpNow, +}; + +export default ui; diff --git a/apps/web/src/games/gemblo/quick.tsx b/apps/web/src/games/gemblo/quick.tsx new file mode 100644 index 0000000..bcddc8d --- /dev/null +++ b/apps/web/src/games/gemblo/quick.tsx @@ -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: , + alt: '빨간 블록의 꼭짓점에서 선을 따라 한 칸 떨어진 곳에 빨간 점이 찍혀 있어요', + title: '선으로 한 칸 떨어져 이어요', + text: '첫 블록은 내 시작점을 덮고, 그다음부터는 내 블록 꼭짓점에서 선을 따라 한 칸 떨어진 곳(내 색 점)에 이어 놓아요.', + }, + { + pic: , + alt: '빨간 블록 바로 옆 칸은 빨갛게 막혀 있고, 파란 블록은 빨간 블록 옆에 붙어 있어요', + title: '같은 색끼리는 닿으면 안 돼요', + text: '같은 색 블록끼리는 변이 닿으면 안 돼요. 다른 색과는 붙어도 괜찮아요. 서로 다른 두 블록 사이의 틈은 지나갈 수 있어요.', + }, + { + pic: , + alt: '여러 색 보석 블록이 판을 채우고 있어요', + title: '남은 칸이 적으면 승리', + text: '놓을 곳이 없으면 그 색은 끝나요. 모두 끝나면 못 놓은 블록의 칸 수가 가장 적은 사람이 이겨요. 큰 블록부터 쓰세요!', + }, +]; diff --git a/apps/web/src/games/gemblo/sound.ts b/apps/web/src/games/gemblo/sound.ts new file mode 100644 index 0000000..44da3b7 --- /dev/null +++ b/apps/web/src/games/gemblo/sound.ts @@ -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 }), +}; diff --git a/apps/web/src/games/help.test.ts b/apps/web/src/games/help.test.ts index 29e2479..2f275af 100644 --- a/apps/web/src/games/help.test.ts +++ b/apps/web/src/games/help.test.ts @@ -9,7 +9,7 @@ import { assertCleanText, eachView, seatIds, usersOf } from './help-kit.test-uti const IDS = Object.keys(GAME_UI); test('모든 게임에 도움말이 있어요', () => { - expect(IDS).toHaveLength(34); + expect(IDS).toHaveLength(35); for (const id of IDS) { const src = readFileSync(join(import.meta.dir, id, 'index.tsx'), 'utf8'); expect(src, id).toMatch(/\bquickStart,/); diff --git a/apps/web/src/games/registry.ts b/apps/web/src/games/registry.ts index 36dbfa7..527a734 100644 --- a/apps/web/src/games/registry.ts +++ b/apps/web/src/games/registry.ts @@ -36,6 +36,7 @@ export const GAME_UI: Record Promise<{ default: GameUI }>> = { liar: () => import('./liar'), 'magical-athlete': () => import('./magical-athlete'), blackjack: () => import('./blackjack'), + gemblo: () => import('./gemblo'), }; const cache = new Map(); diff --git a/apps/web/src/lib/catalog-ui.ts b/apps/web/src/lib/catalog-ui.ts index 13dc3e4..ce33475 100644 --- a/apps/web/src/lib/catalog-ui.ts +++ b/apps/web/src/lib/catalog-ui.ts @@ -33,6 +33,7 @@ export const GAME_ICON: Record = { liar: '🤥', 'magical-athlete': '🏃', blackjack: '🂡', + gemblo: '💠', }; /** Shown on the home screen so users know what's coming (docs/12-roadmap.md). */ @@ -40,7 +41,7 @@ export const UPCOMING: string[] = []; /** Tabs on the game picker (docs/07 §3.3). Games not listed here only show under 전체. */ export const GAME_GROUPS: { key: string; label: string; ids: string[] }[] = [ - { key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue'] }, + { key: 'board', label: '판·주사위', ids: ['omok', 'connect-four', 'othello', 'chess', 'janggi', 'baduk', 'quoridor', 'yut', 'marble', 'yacht', 'las-vegas', 'magical-athlete', 'clue', 'gemblo'] }, { key: 'cards', label: '카드·패', ids: ['seotda', 'poker', 'blackjack', 'one-card', 'uno', 'gostop', 'dalmuti', 'splendor', 'cockroach-poker', 'ninety-nine', 'old-maid', 'mahjong', 'rummikub', 'davinci-code'] }, { key: 'party', label: '여럿이 파티', ids: ['bang', 'halli-galli', 'dobble', 'catchmind', 'mafia', 'liar', 'apple'] }, ]; diff --git a/docs/games/README.md b/docs/games/README.md index 9862aaf..8a88391 100644 --- a/docs/games/README.md +++ b/docs/games/README.md @@ -47,6 +47,7 @@ | `liar` | 라이어 게임 | 3~10 | 2026-10 새 게임 | | `magical-athlete` | 야단법석 달리기 | 2~6 | 2026-10 새 게임 | | `blackjack` | 블랙잭 | 1~7 | 2026-10 새 게임 | +| `gemblo` | 젬블로 | 2~6 | 2026-10 새 게임 | 인원은 각 게임 문서에서 원작 기준으로 최종 확정한다(이 표와 다르면 게임 문서가 우선). diff --git a/docs/games/gemblo.md b/docs/games/gemblo.md index ab21317..412d733 100644 --- a/docs/games/gemblo.md +++ b/docs/games/gemblo.md @@ -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`). diff --git a/e2e/games.e2e.ts b/e2e/games.e2e.ts index b7ceb39..7540eb8 100644 --- a/e2e/games.e2e.ts +++ b/e2e/games.e2e.ts @@ -3190,6 +3190,136 @@ const PLANS: Record = { console.log(` magical-athlete: ${st.picks} picks, ${st.selects} race picks, ${st.acts} turn choices (${st.second} second options), powers + wild track seen`); }, }, + 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('승리'))}`); + }, + }, }; const games = process.argv.slice(2).length ? process.argv.slice(2) : Object.keys(PLANS); diff --git a/packages/games/package.json b/packages/games/package.json index 62f16f9..70bea40 100644 --- a/packages/games/package.json +++ b/packages/games/package.json @@ -12,6 +12,7 @@ "./liar/topics": "./src/liar/topics.ts", "./magical-athlete/racers": "./src/magical-athlete/racers.ts", "./seotda/money": "./src/seotda/money.ts", + "./gemblo/board": "./src/gemblo/board.ts", "./*": "./src/*/index.ts" }, "dependencies": { diff --git a/packages/games/src/bots/index.ts b/packages/games/src/bots/index.ts index 14d5844..b2c30c3 100644 --- a/packages/games/src/bots/index.ts +++ b/packages/games/src/bots/index.ts @@ -38,6 +38,7 @@ import { unoBot } from '../uno/bot'; import { liarBot } from '../liar/bot'; import { magicalAthleteBot } from '../magical-athlete/bot'; import { blackjackBot } from '../blackjack/bot'; +import { 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'; @@ -73,6 +74,7 @@ export const BOT_STRATEGIES: Record = { uno: unoBot, 'magical-athlete': magicalAthleteBot, blackjack: blackjackBot, + gemblo: gembloBot, }; /** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */ diff --git a/packages/games/src/bots/luck.test.ts b/packages/games/src/bots/luck.test.ts index 370eb27..23c50f3 100644 --- a/packages/games/src/bots/luck.test.ts +++ b/packages/games/src/bots/luck.test.ts @@ -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); } }); diff --git a/packages/games/src/bots/luck.ts b/packages/games/src/bots/luck.ts index 8d6d52a..fa6bcba 100644 --- a/packages/games/src/bots/luck.ts +++ b/packages/games/src/bots/luck.ts @@ -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); diff --git a/packages/games/src/gemblo/board.ts b/packages/games/src/gemblo/board.ts new file mode 100644 index 0000000..0556f2f --- /dev/null +++ b/packages/games/src/gemblo/board.ts @@ -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 = { 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 = Object.fromEntries(PIECES.map((p) => [p.id, p])) as Record; +export const PIECE_SIZE: Record = Object.fromEntries(PIECES.map((p) => [p.id, p.cells.length])) as Record; +const PIECE_INDEX: Record = Object.fromEntries(PIECES.map((p, i) => [p.id, i])) as Record; +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 = {} as Record; +export const NO_FLIP_COUNT: Record = {} as Record; +for (const p of PIECES) { + const seen = new Set(); + 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 = { + 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; +} diff --git a/packages/games/src/gemblo/bot.test.ts b/packages/games/src/gemblo/bot.test.ts new file mode 100644 index 0000000..82ff2e1 --- /dev/null +++ b/packages/games/src/gemblo/bot.test.ts @@ -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; + 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 }); + }); +}); diff --git a/packages/games/src/gemblo/bot.ts b/packages/games/src/gemblo/bot.ts new file mode 100644 index 0000000..159f990 --- /dev/null +++ b/packages/games/src/gemblo/bot.ts @@ -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 = ({ 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([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(); + 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 }, + ); +}; diff --git a/packages/games/src/gemblo/gemblo.test.ts b/packages/games/src/gemblo/gemblo.test.ts new file mode 100644 index 0000000..b8882c5 --- /dev/null +++ b/packages/games/src/gemblo/gemblo.test.ts @@ -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 = {}, 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 = { + 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 = {}) => { + 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; + 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(); + 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][]) { + 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][] = [ + [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); +}); diff --git a/packages/games/src/gemblo/index.ts b/packages/games/src/gemblo/index.ts new file mode 100644 index 0000000..8d3acb8 --- /dev/null +++ b/packages/games/src/gemblo/index.ts @@ -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 = {}; + 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 = { + id: 'gemblo', + nameKo: '젬블로', + minPlayers: 2, + maxPlayers: 6, + stateVersion: 1, + defaultOptions: gembloOptionsSchema.parse({}), + optionsSchema: gembloOptionsSchema as unknown as z.ZodType, + actionSchema: gembloActionSchema as z.ZodType, + 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 []; + }, +}; diff --git a/packages/games/src/gemblo/options.ts b/packages/games/src/gemblo/options.ts new file mode 100644 index 0000000..16d09f3 --- /dev/null +++ b/packages/games/src/gemblo/options.ts @@ -0,0 +1,65 @@ +/** 젬블로 room options (docs/games/gemblo.md §2). */ +import { z } from 'zod'; + +const lit = (...vals: T[]) => + z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral, z.ZodLiteral, ...z.ZodLiteral[]]); + +export const 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; diff --git a/packages/games/src/gemblo/types.ts b/packages/games/src/gemblo/types.ts new file mode 100644 index 0000000..53791ed --- /dev/null +++ b/packages/games/src/gemblo/types.ts @@ -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 | { 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; + /** 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; + scoreText: Record; + 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 }; + /** Consecutive automatic turns (timeouts) per person. */ + streak: Record; + history: GembloMove[]; + undo: { + usedBy: Record; + 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; pending: { by: PlayerId; accepted: PlayerId[] } | null; responders: PlayerId[]; canRequest: boolean }; + result: GembloResult | null; +} diff --git a/packages/games/src/index.ts b/packages/games/src/index.ts index e40af82..10c3da9 100644 --- a/packages/games/src/index.ts +++ b/packages/games/src/index.ts @@ -33,6 +33,7 @@ import { uno } from './uno'; import { liar } from './liar'; import { magicalAthlete } from './magical-athlete'; import { blackjack } from './blackjack'; +import { gemblo } from './gemblo'; export const GAMES: Record = { [omok.id]: omok, @@ -69,4 +70,5 @@ export const GAMES: Record = { [liar.id]: liar, [magicalAthlete.id]: magicalAthlete, [blackjack.id]: blackjack, + [gemblo.id]: gemblo, }; diff --git a/packages/shared/src/bots.ts b/packages/shared/src/bots.ts index 134d6f7..ed78f59 100644 --- a/packages/shared/src/bots.ts +++ b/packages/shared/src/bots.ts @@ -59,6 +59,7 @@ export const BOT_GAMES: readonly string[] = [ 'liar', 'magical-athlete', 'blackjack', + 'gemblo', ]; /** Players a practice room starts with when the minimum makes a thin game (마피아 4명 = 마피아 1, 경찰, 의사, 시민 1; 라이어 게임 3명). */ diff --git a/packages/shared/src/catalog.ts b/packages/shared/src/catalog.ts index b95f2ac..b475243 100644 --- a/packages/shared/src/catalog.ts +++ b/packages/shared/src/catalog.ts @@ -45,6 +45,7 @@ export const CATALOG: CatalogEntry[] = [ { id: 'uno', nameKo: '우노', minPlayers: 2, maxPlayers: 10, minutes: '10~20', level: '쉬움', blurb: '같은 색·숫자를 내고, 한 장 남으면 "우노!" 외치기 · 와일드 드로우4 도전', available: true }, { id: 'liar', nameKo: '라이어 게임', minPlayers: 3, maxPlayers: 10, minutes: '5~15', level: '쉬움', blurb: '모두 같은 제시어를 받았는데 한 명만 몰라요! 한 문장씩 설명하며 라이어를 찾아요 · 채팅 추리', available: true }, { id: 'blackjack', nameKo: '블랙잭', minPlayers: 1, maxPlayers: 7, minutes: '10~20', level: '쉬움', blurb: '딜러를 상대로 21에 가깝게! 공식 규칙 + 5카드 찰리·7트리플 하우스 룰 · 놀이용 칩 · 혼자서도 OK', available: true }, + { id: '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);