/** * 사과 게임 (docs/games/apple.md). Pure and deterministic; state is JSON; time only via ctx.now. * Everyone solves the same board (one seeded deal) on their own copy at the same time; the server clock ends the game. */ import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId, type Rng } from '@bg/engine'; import { CELLS, COLS, ROWS, TARGET, appleActionSchema, appleOptionsSchema, type AppleAction, type AppleFinal, type AppleOptions, type AppleState, type AppleView, type EndReason, type RankRow, type SeatStatus, type SelectAction, } from './types'; export * from './types'; type S = AppleState; type A = AppleAction; export const COUNTDOWN_MS = 3000; /** Rate limit: at most this many selects per second per player (a person manages 2~3). */ export const SELECTS_PER_SEC = 5; export const MAX_PLAYERS = 8; // ---------------------------------------------------------------- board math export interface Rect { r0: number; c0: number; r1: number; c1: number; } /** Corners in any order → top-left / bottom-right. */ export function normRect(a: Rect): Rect { return { r0: Math.min(a.r0, a.r1), c0: Math.min(a.c0, a.c1), r1: Math.max(a.r0, a.r1), c1: Math.max(a.c0, a.c1) }; } /** Sum and apple count inside a rectangle (cleared cells count as nothing). */ export function rectSum(cells: string, rect: Rect): { sum: number; count: number } { const { r0, c0, r1, c1 } = normRect(rect); let sum = 0; let count = 0; for (let r = r0; r <= r1; r++) { for (let c = c0; c <= c1; c++) { const v = cells.charCodeAt(r * COLS + c) - 48; if (v > 0) { sum += v; count++; } } } return { sum, count }; } /** * Every rectangle whose apples add up to exactly 10, each once in its tightest form (its edges touch apples). * Prefix sums keep it to ~8k rectangle checks (well under a millisecond). `limit` stops early. */ export function findMoves(cells: string, limit = Infinity): Rect[] { const W = COLS + 1; const P = new Int32Array((ROWS + 1) * W); const N = new Int32Array((ROWS + 1) * W); for (let r = 0; r < ROWS; r++) { for (let c = 0; c < COLS; c++) { const v = cells.charCodeAt(r * COLS + c) - 48; const i = (r + 1) * W + c + 1; P[i] = v + P[i - 1]! + P[i - W]! - P[i - W - 1]!; N[i] = (v > 0 ? 1 : 0) + N[i - 1]! + N[i - W]! - N[i - W - 1]!; } } const box = (T: Int32Array, r0: number, c0: number, r1: number, c1: number) => T[(r1 + 1) * W + c1 + 1]! - T[r0 * W + c1 + 1]! - T[(r1 + 1) * W + c0]! + T[r0 * W + c0]!; const out: Rect[] = []; for (let r0 = 0; r0 < ROWS; r0++) { for (let r1 = r0; r1 < ROWS; r1++) { for (let c0 = 0; c0 < COLS; c0++) { for (let c1 = c0; c1 < COLS; c1++) { const sum = box(P, r0, c0, r1, c1); if (sum > TARGET) break; // only grows with c1 if (sum < TARGET) continue; // Tight: every edge row / column holds an apple. if (!box(N, r0, c0, r0, c1) || !box(N, r1, c0, r1, c1) || !box(N, r0, c0, r1, c0) || !box(N, r0, c1, r1, c1)) continue; out.push({ r0, c0, r1, c1 }); if (out.length >= limit) return out; } } } } return out; } export const hasMove = (cells: string): boolean => findMoves(cells, 1).length > 0; /** CELLS apples 1~9 from the seeded RNG; the total is a multiple of 10 (as in the original). */ export function makeBoard(rng: Rng): string { const v = Array.from({ length: CELLS }, () => 1 + rng.int(9)); let total = v.reduce((a, b) => a + b, 0); while (total % TARGET !== 0) { const i = rng.int(CELLS); total -= v[i]!; v[i] = 1 + rng.int(9); total += v[i]!; } return v.join(''); } // ---------------------------------------------------------------- helpers function clone(s: S): S { return { ...s, order: [...s.order], boards: { ...s.boards }, score: { ...s.score }, clears: { ...s.clears }, status: { ...s.status }, recent: Object.fromEntries(Object.entries(s.recent).map(([k, v]) => [k, [...v]])), }; } interface Ctx { now: number; events: GameEvent[]; } const inGame = (s: S, p: PlayerId) => s.status[p] === 'playing' || s.status[p] === 'stuck'; /** The countdown is over (the room timer may not have ticked yet). */ const started = (s: S, now: number | undefined) => s.phase === 'playing' || (s.phase === 'countdown' && now !== undefined && now >= s.countdownEndsAt); function rateOk(times: readonly number[] | undefined, now: number | undefined): boolean { if (now === undefined || !times || times.length < SELECTS_PER_SEC) return true; return now - times[times.length - SELECTS_PER_SEC]! >= 1000; } /** Brings the phase up to the clock: countdown → playing → ended (time). */ function catchUp(s: S, ctx: Ctx): void { if (s.phase === 'countdown' && ctx.now >= s.countdownEndsAt) { s.phase = 'playing'; ctx.events.push({ type: 'start' }); } if (s.phase === 'playing' && ctx.now >= s.endsAt) finish(s, 'time', ctx); } function select(s: S, p: PlayerId, a: SelectAction, ctx: Ctx): void { const { r0, c0, r1, c1 } = normRect(a); const b = s.boards[p]!.split(''); let count = 0; for (let r = r0; r <= r1; r++) { for (let c = c0; c <= c1; c++) { if (b[r * COLS + c] !== '0') { b[r * COLS + c] = '0'; count++; } } } s.boards[p] = b.join(''); s.score[p] = (s.score[p] ?? 0) + count; s.clears[p] = (s.clears[p] ?? 0) + 1; s.recent[p] = [...(s.recent[p] ?? []).slice(-(SELECTS_PER_SEC - 1)), ctx.now]; ctx.events.push({ type: 'clear', player: p, count, score: s.score[p] }); if (!hasMove(s.boards[p]!)) { s.status[p] = 'stuck'; ctx.events.push({ type: 'stuck', player: p }); if (s.order.every((q) => s.status[q] !== 'playing')) finish(s, 'cleared', ctx); } } function leave(s: S, p: PlayerId, ctx: Ctx): void { s.status[p] = 'left'; ctx.events.push({ type: 'left', player: p }); const still = s.order.filter((q) => inGame(s, q)); // Nobody left to race against (or nobody at all): the game is decided. if (still.length === 0 || (still.length === 1 && s.order.length > 1)) finish(s, 'left', ctx); else if (s.order.every((q) => s.status[q] !== 'playing')) finish(s, 'cleared', ctx); } // ---------------------------------------------------------------- ending /** Shared ranks by score (ties share a rank); players who left come after everyone who stayed. */ export function rankRows(s: Pick): RankRow[] { const rows: RankRow[] = []; for (const left of [false, true]) { const group = s.order.filter((p) => (s.status[p] === 'left') === left).sort((a, b) => (s.score[b] ?? 0) - (s.score[a] ?? 0)); group.forEach((id, i) => { const prev = rows.at(-1); const score = s.score[id] ?? 0; const tie = i > 0 && prev && prev.score === score; rows.push({ rank: tie ? prev.rank : rows.length + 1, id, score, clears: s.clears[id] ?? 0, left }); }); } return rows; } function finish(s: S, reason: EndReason, ctx: Ctx): void { if (s.phase === 'ended') return; s.phase = 'ended'; const ranking = rankRows(s); const top = ranking.filter((r) => r.rank === 1); let summary: string; if (s.order.length === 1) { const n = ranking[0]!.score; summary = reason === 'cleared' ? `더 지울 사과가 없어요. 사과 ${n}개를 지웠어요` : `시간이 다 됐어요. 사과 ${n}개를 지웠어요`; } else if (reason === 'left') summary = '다른 사람이 모두 나가서 남은 사람이 이겼어요'; else { summary = reason === 'cleared' ? '모두 더 지울 사과가 없어요. 가장 많이 지운 사람이 이겼어요' : '시간이 다 됐어요. 사과를 가장 많이 지운 사람이 이겼어요'; if (top.length > 1) summary += ` (공동 1등 ${top.length}명)`; } s.final = { endReason: reason, ranking, summary } satisfies AppleFinal; ctx.events.push({ type: 'gameEnd', reason }); } // ---------------------------------------------------------------- definition type Def = GameDefinition; export const apple: Def = { id: 'apple', nameKo: '사과 게임', minPlayers: 1, maxPlayers: MAX_PLAYERS, stateVersion: 1, defaultOptions: appleOptionsSchema.parse({}), optionsSchema: appleOptionsSchema as unknown as Def['optionsSchema'], actionSchema: appleActionSchema as unknown as Def['actionSchema'], setup({ players, options, rng, now }) { if (players.length < 1 || players.length > MAX_PLAYERS) throw new Error(`apple: ${players.length} players not allowed`); // One board for everybody, from the seeded RNG (§8.4). const initial = makeBoard(rng); const per0 = (v: () => T) => Object.fromEntries(players.map((p) => [p, v()])) as Record; const countdownEndsAt = now + COUNTDOWN_MS; return { options, order: [...players], initial, boards: per0(() => initial), score: per0(() => 0), clears: per0(() => 0), status: per0(() => 'playing'), recent: per0(() => []), phase: 'countdown', countdownEndsAt, endsAt: countdownEndsAt + options.timeLimitSec * 1000, final: null, }; }, validate(s, actor, a, vctx) { if (!s.order.includes(actor)) return fail('이 게임의 플레이어가 아니에요.'); if (s.phase === 'ended') return fail('게임이 이미 끝났어요.'); const now = vctx?.now; switch (a.type) { case 'tick': return ok; case 'leave': return inGame(s, actor) ? ok : fail('이미 게임에서 빠졌어요.'); case 'select': { if (s.status[actor] === 'left') return fail('게임에서 빠졌어요.'); if (!started(s, now)) return fail('곧 시작해요. 잠시만 기다려 주세요.'); if (now !== undefined && now >= s.endsAt) return fail('시간이 다 됐어요.'); if (s.status[actor] === 'stuck') return fail('더 지울 수 있는 사과가 없어요.'); if (!rateOk(s.recent[actor], now)) return fail('조금 천천히 해 주세요.'); const { sum, count } = rectSum(s.boards[actor]!, a); if (count === 0) return fail('고른 칸에 사과가 없어요.'); if (sum !== TARGET) return fail(`합이 ${sum}이에요. 딱 10이 되게 골라 주세요.`); return ok; } } }, apply(prev, actor, a, { now }) { const s = clone(prev); const ctx: Ctx = { now, events: [] }; catchUp(s, ctx); if (s.phase !== 'ended') { if (a.type === 'leave') leave(s, actor, ctx); else if (a.type === 'select' && s.phase === 'playing') select(s, actor, a, ctx); } return { state: s, events: ctx.events }; }, view(s, viewer) { const me = viewer && s.order.includes(viewer) ? viewer : null; return { options: s.options, me, phase: s.phase, rows: ROWS, cols: COLS, cells: me && s.phase !== 'countdown' ? s.boards[me]! : null, countdownEndsAt: s.countdownEndsAt, endsAt: s.endsAt, seats: s.order.map((id) => ({ id, score: s.score[id] ?? 0, clears: s.clears[id] ?? 0, status: s.status[id]! })), result: s.final, }; }, /** No turns: everyone still in may clear apples at any time. */ activePlayers(s) { if (s.phase === 'ended') return []; return s.order.filter((p) => s.status[p] === 'playing'); }, deadline(s) { if (s.phase === 'ended') return null; return s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt; }, /** Everyone still in drives the clock (a stuck player too: they wait for the end like everybody else). */ timeoutPlayers(s) { if (s.phase === 'ended') return []; return s.order.filter((p) => inGame(s, p)); }, /** A disconnected player is never timed out early: their score simply stays until the server clock ends the game. */ timeoutNotBefore(s) { if (s.phase === 'ended') return null; return s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt; }, onTimeout() { return { type: 'tick' }; }, onLeave(s, player) { if (s.phase === 'ended' || !inGame(s, player)) return null; return { type: 'leave' }; }, result(s): GameResult | null { const f = s.final; if (!f) return null; const groups = new Map(); for (const r of f.ranking) groups.set(r.rank, [...(groups.get(r.rank) ?? []), r.id]); return { ranking: [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ids]) => ids), scores: Object.fromEntries(f.ranking.map((r) => [r.id, r.score])), scoreText: Object.fromEntries(f.ranking.map((r) => [r.id, `사과 ${r.score}개`])), summary: f.summary, reason: 'normal', }; }, /** Test helper: the clock tick and the first few rectangles that add up to 10. */ legalActions(s, p) { if (s.phase === 'ended' || !s.order.includes(p)) return []; const out: A[] = [{ type: 'tick' }]; if (s.phase === 'playing' && s.status[p] === 'playing') { for (const m of findMoves(s.boards[p]!, 8)) out.push({ type: 'select', ...m }); } return out.filter((x) => apple.validate(s, p, x).ok); }, /** The board is the same for everyone; only the countdown hides it (so nobody gets a head start). */ secretsOf(s) { return s.phase === 'countdown' ? [s.initial] : []; }, };