/** 할리갈리 (docs/games/halli-galli.md). Pure and deterministic; state is JSON; time only via ctx.now. */ import { fail, ok, type GameDefinition, type GameEvent, type GameResult, type PlayerId } from '@bg/engine'; import { CARDS, DECK_SIZE, FRUITS, cardOf, halliGalliActionSchema, halliGalliOptionsSchema, type EndReason, type Fruit, type HalliGalliAction, type HalliGalliFinal, type HalliGalliOptions, type HalliGalliState, type HalliGalliView, type LogEntry, type OutReason, type RankRow, } from './types'; export * from './types'; type S = HalliGalliState; type A = HalliGalliAction; export const COUNTDOWN_MS = 3000; /** `latencyComp: 'light'` bell window (§5.4). */ export const RING_WINDOW_MS = 50; /** Max credit `latencyComp: 'light'` gives for half the RTT (§5.4). */ export const MAX_LATENCY_CREDIT_MS = 80; /** Away players (room grace period over) flip after this much of their turn (§8.5 "1초로 줄여"). */ export const AWAY_FLIP_MS = 1000; const LOG_KEEP = 30; const POINTS = [3, 2, 1]; /** Flip time limit in ms; null = 무제한 (자동 뒤집기 still needs a pace: 3 s, 어린이 모드 8 s). */ export function flipMs(o: HalliGalliOptions): number | null { if (o.flipSeconds === null) return o.autoFlip ? (o.kidMode ? 8 : 3) * 1000 : null; return (o.kidMode ? 8 : o.flipSeconds) * 1000; } const deadlineFrom = (o: HalliGalliOptions, from: number): number | null => { const ms = flipMs(o); return ms === null ? null : from + ms; }; /** Public key of a visible card; secretsOf uses the same form so leak checks are meaningful. */ export const cardKey = (id: number): string => `hg${id}`; // ---------------------------------------------------------------- table math /** Sum of fruits over every face-up pile's top card (eliminated players' piles included, §5.2). */ export function fruitTotals(s: Pick): Record { const t: Record = { strawberry: 0, banana: 0, lime: 0, plum: 0 }; for (const p of s.order) { const pile = s.faceUp[p]!; if (pile.length === 0) continue; const c = cardOf(pile[pile.length - 1]!); t[c.fruit] += c.count; } return t; } /** A fruit totalling exactly five, if any (6+ and 4- do not count). */ export function fiveFruit(s: Pick): Fruit | null { const t = fruitTotals(s); for (const f of FRUITS) if (t[f] === 5) return f; return null; } export const cardsHeld = (s: S, p: PlayerId): number => (s.decks[p]?.length ?? 0) + (s.faceUp[p]?.length ?? 0); /** All 56 cards, wherever they are (test invariant). */ export function allCardIds(s: S): number[] { return [...s.order.flatMap((p) => [...s.decks[p]!, ...s.faceUp[p]!]), ...s.pot, ...s.removed]; } // ---------------------------------------------------------------- helpers function clone(s: S): S { return { ...s, order: [...s.order], decks: Object.fromEntries(Object.entries(s.decks).map(([k, v]) => [k, [...v]])), faceUp: Object.fromEntries(Object.entries(s.faceUp).map(([k, v]) => [k, [...v]])), pot: [...s.pot], removed: [...s.removed], active: [...s.active], eliminated: [...s.eliminated], outReason: { ...s.outReason }, lockedUntil: { ...s.lockedUntil }, wrongCount: { ...s.wrongCount }, correctCount: { ...s.correctCount }, ringWindow: s.ringWindow ? { ...s.ringWindow, rings: s.ringWindow.rings.map((r) => ({ ...r })) } : null, lastBell: s.lastBell ? { ...s.lastBell } : null, log: [...s.log], final: s.final, }; } interface Ctx { now: number; events: GameEvent[]; } type LogBody = LogEntry extends infer E ? (E extends LogEntry ? Omit : never) : never; function log(s: S, e: LogBody): void { s.logNo += 1; s.log.push({ n: s.logNo, ...e } as LogEntry); if (s.log.length > LOG_KEEP) s.log.splice(0, s.log.length - LOG_KEEP); } /** Other active players clockwise, starting after `p`. */ function othersClockwise(s: S, p: PlayerId): PlayerId[] { const i = s.order.indexOf(p); const out: PlayerId[] = []; for (let k = 1; k < s.order.length; k++) { const q = s.order[(i + k) % s.order.length]!; if (s.active.includes(q)) out.push(q); } return out; } function startTurn(s: S, p: PlayerId, now: number): void { s.turn = p; s.turnStartedAt = now; s.turnDeadline = deadlineFrom(s.options, now); s.pendingFlip = null; } /** Removes `p` from play; returns true if the game ended. */ function eliminate(s: S, p: PlayerId, why: OutReason, ctx: Ctx): boolean { if (!s.active.includes(p)) return s.phase === 'ended'; s.active = s.active.filter((q) => q !== p); s.eliminated.push(p); s.outReason[p] = why; if (s.ringWindow) s.ringWindow.rings = s.ringWindow.rings.filter((r) => r.player !== p); ctx.events.push({ type: 'out', player: p, why }); log(s, { t: 'out', p, why }); if (s.active.length <= 1) { finish(s, 'lastStanding', ctx); return true; } if (s.options.endMode === 'official' && s.order.length >= 3 && s.active.length === 2) s.officialDuel = true; return false; } /** Passes the turn clockwise from `from`; players whose turn comes with an empty deck are out (§5.3). */ function advanceTurn(s: S, from: PlayerId, ctx: Ctx): void { const n = s.order.length; const i = s.order.indexOf(from); for (let k = 1; k <= n; k++) { const q = s.order[(i + k) % n]!; if (!s.active.includes(q)) continue; if (s.decks[q]!.length > 0) { startTurn(s, q, ctx.now); return; } if (eliminate(s, q, 'empty', ctx)) return; } // Unreachable while ≥ 2 players are active (someone holds cards); keep the game well-formed anyway. finish(s, 'lastStanding', ctx); } function doFlip(s: S, p: PlayerId, ctx: Ctx): void { const id = s.decks[p]!.pop(); if (id === undefined) throw new Error(`halli-galli: ${p} has no card to flip`); s.faceUp[p]!.push(id); s.tableVersion += 1; s.lastChange = 'flip'; s.lastFlipBy = p; s.pendingFlip = null; s.flipAllowedAt = ctx.now + s.options.flipGuardMs; const c = cardOf(id); ctx.events.push({ type: 'flip', player: p, fruit: c.fruit, count: c.count, version: s.tableVersion }); advanceTurn(s, p, ctx); } /** Queues or performs the turn player's flip (guard / bell window aware). */ function flipOrQueue(s: S, p: PlayerId, ctx: Ctx): void { if (s.ringWindow || ctx.now < s.flipAllowedAt) { if (s.pendingFlip !== p) { s.pendingFlip = p; ctx.events.push({ type: 'flipQueued', player: p }); } return; } doFlip(s, p, ctx); } /** Takes every face-up pile (seat order, bottom first) and then the pot to the bottom of `p`'s deck. */ function sweepTable(s: S, p: PlayerId): number { const taken: number[] = []; for (const q of s.order) { taken.push(...s.faceUp[q]!); s.faceUp[q] = []; } taken.push(...s.pot); s.pot = []; s.decks[p] = [...taken, ...s.decks[p]!]; s.tableVersion += 1; s.lastChange = 'collect'; return taken.length; } function collect(s: S, p: PlayerId, fruit: Fruit, ctx: Ctx): void { const cards = sweepTable(s, p); s.correctCount[p] = (s.correctCount[p] ?? 0) + 1; s.bellSeq += 1; s.lastBell = { seq: s.bellSeq, player: p, correct: true, fruit, cards, at: ctx.now }; s.ringWindow = null; ctx.events.push({ type: 'ring', player: p, correct: true, fruit, cards }); log(s, { t: 'collect', p, fruit, cards }); if (s.officialDuel) { finish(s, 'official', ctx); return; } // The winner flips next; the table must stay still for the guard time first. startTurn(s, p, ctx.now); s.flipAllowedAt = ctx.now + s.options.flipGuardMs; } function wrongBell(s: S, p: PlayerId, ctx: Ctx): void { const o = s.options; s.wrongCount[p] = (s.wrongCount[p] ?? 0) + 1; s.lockedUntil[p] = ctx.now + o.wrongRingLockoutMs; s.bellSeq += 1; const bell = { seq: s.bellSeq, player: p, correct: false, cards: 0, at: ctx.now }; s.lastBell = bell; // Two left: official ending / 1-on-1 house rule (§6, §7). if (s.active.length === 2 && (s.officialDuel || o.duelWrongLoses)) { const opp = s.active.find((q) => q !== p)!; let cards: number; if (s.officialDuel) { cards = sweepTable(s, opp); } else { cards = s.decks[p]!.length; s.decks[opp] = [...s.decks[p]!, ...s.decks[opp]!]; s.decks[p] = []; } bell.cards = cards; ctx.events.push({ type: 'ring', player: p, correct: false, gave: 0, duel: true, by: opp }); log(s, { t: 'duelWrong', p, by: opp, cards }); if (s.officialDuel) finish(s, 'official', ctx); else eliminate(s, p, 'duel', ctx); return; } // Give one card (more with penaltyEscalation) to every other active player clockwise; short → out (§5.2). const per = o.penaltyEscalation ? s.wrongCount[p]! : 1; const to = othersClockwise(s, p); let gave = 0; let short = false; outer: for (let r = 0; r < per; r++) { for (const q of to) { const id = s.decks[p]!.pop(); if (id === undefined) { short = true; break outer; } if (o.wrongToPot) s.pot.push(id); else s.decks[q]!.unshift(id); gave++; } } bell.cards = gave; ctx.events.push({ type: 'ring', player: p, correct: false, gave, toPot: o.wrongToPot }); log(s, { t: 'wrong', p, gave, toPot: o.wrongToPot }); let out: OutReason | null = null; if (short) out = 'penalty'; else if (o.strikeOut && s.wrongCount[p]! >= 3) { s.pot.push(...s.decks[p]!); s.decks[p] = []; out = 'strikeOut'; } else if (s.decks[p]!.length === 0 && s.turn === p) out = 'empty'; // it is already their turn and nothing is left to flip if (!out) return; const wasTurn = s.turn === p; if (eliminate(s, p, out, ctx)) return; if (wasTurn) advanceTurn(s, p, ctx); } /** Closes the `latencyComp` bell window: earliest adjusted time wins, ties by arrival (§5.4). */ function resolveWindow(s: S, ctx: Ctx): void { const w = s.ringWindow!; s.ringWindow = null; const fruit = fiveFruit(s); if (!fruit || w.rings.length === 0) return; // everyone in the window left let best = w.rings[0]!; for (const r of w.rings) if (r.adjTs < best.adjTs) best = r; for (const r of w.rings) if (r !== best) ctx.events.push({ type: 'late', player: r.player }); collect(s, best.player, fruit, ctx); } function ring(s: S, p: PlayerId, version: number, rtt: number | undefined, ctx: Ctx): void { if (s.ringWindow && ctx.now >= s.ringWindow.openedAt + RING_WINDOW_MS) resolveWindow(s, ctx); if (s.phase !== 'playing') return; if (version !== s.tableVersion) { ctx.events.push({ type: 'late', player: p }); return; } if (ctx.now < (s.lockedUntil[p] ?? 0)) { ctx.events.push({ type: 'locked', player: p }); return; } const fruit = fiveFruit(s); if (!fruit) { wrongBell(s, p, ctx); return; } if (s.options.latencyComp === 'light') { const adjTs = ctx.now - Math.min((rtt ?? 0) / 2, MAX_LATENCY_CREDIT_MS); if (!s.ringWindow) s.ringWindow = { version, openedAt: ctx.now, rings: [] }; if (!s.ringWindow.rings.some((r) => r.player === p)) s.ringWindow.rings.push({ player: p, adjTs }); ctx.events.push({ type: 'ringWindow', player: p }); return; } collect(s, p, fruit, ctx); } /** * Server timer. Runs whatever is due; for the turn player (whose clock the room drives) a tick that finds * nothing else due means "time's up / away" → flip (queued behind the guard if needed). */ function tick(s: S, actor: PlayerId, ctx: Ctx): void { if (s.phase === 'countdown') { if (ctx.now < s.countdownEndsAt) return; s.phase = 'playing'; startTurn(s, s.turn, ctx.now); s.flipAllowedAt = ctx.now; ctx.events.push({ type: 'start' }); return; } if (s.ringWindow) { if (ctx.now >= s.ringWindow.openedAt + RING_WINDOW_MS) resolveWindow(s, ctx); return; } const due = (s.pendingFlip !== null && ctx.now >= s.flipAllowedAt) || (s.turnDeadline !== null && ctx.now >= Math.max(s.turnDeadline, s.flipAllowedAt)); if (actor === s.turn || due) flipOrQueue(s, s.turn, ctx); } function leave(s: S, p: PlayerId, ctx: Ctx): void { // The leaver's face-down deck goes under the bell; their face-up pile stays on the table. s.pot.push(...s.decks[p]!); s.decks[p] = []; const wasTurn = s.turn === p; if (eliminate(s, p, 'left', ctx)) return; if (wasTurn) advanceTurn(s, p, ctx); } // ---------------------------------------------------------------- ending function finish(s: S, reason: EndReason, ctx: Ctx): void { if (s.phase === 'ended') return; s.phase = 'ended'; s.pendingFlip = null; s.ringWindow = null; const row = (id: PlayerId, rank: number): RankRow => ({ rank, id, cards: cardsHeld(s, id), correct: s.correctCount[id] ?? 0, wrong: s.wrongCount[id] ?? 0 }); const ranking: RankRow[] = []; // Still-active players: by cards held, then correct bells; equal → shared rank (§6). const alive = [...s.active].sort((a, b) => cardsHeld(s, b) - cardsHeld(s, a) || (s.correctCount[b] ?? 0) - (s.correctCount[a] ?? 0)); alive.forEach((id, i) => { const prev = ranking[i - 1]; const tie = prev && cardsHeld(s, prev.id) === cardsHeld(s, id) && (s.correctCount[prev.id] ?? 0) === (s.correctCount[id] ?? 0); ranking.push(row(id, tie ? prev.rank : i + 1)); }); // Eliminated players: last out ranks highest. for (const id of [...s.eliminated].reverse()) ranking.push(row(id, ranking.length + 1)); const winners = ranking.filter((r) => r.rank === 1).length; let summary: string; if (reason === 'lastStanding') { const allLeft = s.eliminated.every((p) => s.outReason[p] === 'left'); summary = allLeft ? '다른 사람이 모두 나가서 남은 사람이 이겼어요' : '끝까지 남아 카드를 지킨 사람이 이겼어요'; } else if (reason === 'official') { summary = '두 사람이 남은 뒤 종으로 승부가 났어요. 카드가 가장 많은 사람이 이겼어요'; } else { summary = '시간이 다 됐어요. 카드가 가장 많은 사람이 이겼어요'; } if (winners > 1) summary += ` (공동 1등 ${winners}명)`; s.final = { endReason: reason, ranking, summary } satisfies HalliGalliFinal; ctx.events.push({ type: 'gameEnd', reason }); } // ---------------------------------------------------------------- definition const LATE_COLLECT = '늦었어요! 다른 사람이 먼저 종을 쳤어요.'; const LATE_FLIP = '늦었어요! 그 사이에 카드가 바뀌었어요.'; export const halliGalli: GameDefinition = { id: 'halli-galli', nameKo: '할리갈리', realtime: true, minPlayers: 2, maxPlayers: 6, stateVersion: 1, defaultOptions: halliGalliOptionsSchema.parse({}), optionsSchema: halliGalliOptionsSchema as unknown as GameDefinition['optionsSchema'], actionSchema: halliGalliActionSchema as unknown as GameDefinition['actionSchema'], setup({ players, options, rng, now }) { if (players.length < 2 || players.length > 6) throw new Error(`halli-galli: ${players.length} players not allowed`); // §4 / §8.4: seats, first player and the deck all come from the seeded RNG. const order = rng.shuffle(players); const first = order[rng.int(order.length)]!; const deck = rng.shuffle(CARDS.map((c) => c.id)); const per = Math.floor(DECK_SIZE / order.length); const decks: Record = {}; order.forEach((p, i) => (decks[p] = deck.slice(i * per, (i + 1) * per))); const rest = deck.slice(order.length * per); const per0 = (v: T) => Object.fromEntries(order.map((p) => [p, v])) as Record; const countdownEndsAt = now + COUNTDOWN_MS; return { options, order, decks, faceUp: Object.fromEntries(order.map((p) => [p, [] as number[]])), pot: options.leftoverCards === 'pot' ? rest : [], removed: options.leftoverCards === 'remove' ? rest : [], active: [...order], eliminated: [], outReason: {}, officialDuel: false, turn: first, turnStartedAt: now, turnDeadline: deadlineFrom(options, countdownEndsAt), flipAllowedAt: countdownEndsAt, pendingFlip: null, tableVersion: 0, lastChange: null, lastFlipBy: null, lockedUntil: per0(0), wrongCount: per0(0), correctCount: per0(0), ringWindow: null, phase: 'countdown', countdownEndsAt, startedAt: now, endsAt: options.timeLimitMin === null ? null : countdownEndsAt + options.timeLimitMin * 60_000, lastBell: null, bellSeq: 0, logNo: 0, log: [], final: null, }; }, validate(s, actor, a) { if (!s.order.includes(actor)) return fail('이 게임의 플레이어가 아니에요.'); if (s.phase === 'ended') return fail('게임이 이미 끝났어요.'); switch (a.type) { case 'tick': return actor === s.turn || s.active.includes(actor) ? ok : fail('시간 초과 대상이 아니에요.'); case 'leave': return s.active.includes(actor) ? ok : fail('이미 게임에서 빠졌어요.'); case 'flip': if (s.phase !== 'playing') return fail('곧 시작해요. 잠시만 기다려 주세요.'); if (s.options.autoFlip) return fail('이 방은 카드가 자동으로 뒤집혀요.'); if (s.turn !== actor) return fail('지금은 내 차례가 아니에요.'); if (s.pendingFlip === actor) return fail('곧 뒤집혀요. 잠시만 기다려 주세요.'); if (s.decks[actor]!.length === 0) return fail('뒤집을 카드가 없어요.'); return ok; case 'ring': if (s.phase !== 'playing') return fail('곧 시작해요. 잠시만 기다려 주세요.'); if (!s.active.includes(actor)) return fail('게임에서 빠져서 종을 칠 수 없어요.'); // §5.2 늦은 종: the client saw an older table → ignored without penalty. if (a.version !== s.tableVersion) return fail(a.version < s.tableVersion && s.lastChange === 'collect' && a.version === s.tableVersion - 1 ? LATE_COLLECT : LATE_FLIP); if (s.ringWindow?.rings.some((r) => r.player === actor)) return fail('이미 종을 쳤어요.'); return ok; } }, apply(prev, actor, a, { now }) { const s = clone(prev); const ctx: Ctx = { now, events: [] }; // §2 timeLimitMin: once time is up nothing else happens. if (s.phase === 'playing' && s.endsAt !== null && now >= s.endsAt) { finish(s, 'timeLimit', ctx); return { state: s, events: ctx.events }; } switch (a.type) { case 'tick': tick(s, actor, ctx); break; case 'flip': flipOrQueue(s, actor, ctx); break; case 'ring': ring(s, actor, a.version, a.rtt, ctx); break; case 'leave': leave(s, actor, ctx); break; } 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, seats: s.order.map((p) => { const pile = s.faceUp[p]!; const topId = pile[pile.length - 1]; const c = topId === undefined ? null : cardOf(topId); const why = s.outReason[p]; return { id: p, deck: s.decks[p]!.length, pile: pile.length, top: c ? { key: cardKey(c.id), fruit: c.fruit, count: c.count } : null, cards: cardsHeld(s, p), status: s.active.includes(p) ? 'playing' : why === 'left' ? 'left' : 'out', isTurn: s.phase !== 'ended' && s.turn === p, lockedUntil: s.lockedUntil[p] ?? 0, correct: s.correctCount[p] ?? 0, wrong: s.wrongCount[p] ?? 0, }; }), turn: s.phase === 'ended' ? null : s.turn, tableVersion: s.tableVersion, pot: s.pot.length, removed: s.removed.length, countdownEndsAt: s.countdownEndsAt, turnStartedAt: s.turnStartedAt, turnDeadline: s.turnDeadline, flipTotalMs: flipMs(s.options), flipAllowedAt: s.flipAllowedAt, pendingFlip: s.pendingFlip !== null, endsAt: s.endsAt, windowOpen: s.ringWindow !== null, officialDuel: s.officialDuel, lastFlipBy: s.lastFlipBy, lastBell: s.lastBell, log: s.log.slice(-12), result: s.final, }; }, /** Everyone still in can ring at any time; the turn player also flips (§8.5). */ activePlayers(s) { if (s.phase === 'ended') return []; if (s.phase === 'countdown') return [s.turn]; return [...s.active]; }, deadline(s) { if (s.phase === 'ended') return null; if (s.phase === 'countdown') return s.countdownEndsAt; const c: number[] = []; if (s.endsAt !== null) c.push(s.endsAt); if (s.ringWindow) c.push(s.ringWindow.openedAt + RING_WINDOW_MS); else { if (s.pendingFlip) c.push(s.flipAllowedAt); if (s.turnDeadline !== null) c.push(Math.max(s.turnDeadline, s.flipAllowedAt)); } return c.length ? Math.min(...c) : null; }, /** Only the turn player's clock drives the server tick (flips, guard, bell window, time limit). */ timeoutPlayers(s) { return s.phase === 'ended' ? [] : [s.turn]; }, /** * Away players are timed out right after the room grace period; never earlier than the flip guard * (or 1s into their turn), so an away player's flips keep a steady pace instead of a busy loop. */ timeoutNotBefore(s) { if (s.phase === 'ended') return null; if (s.phase === 'countdown') return s.countdownEndsAt; if (s.ringWindow) return s.ringWindow.openedAt + RING_WINDOW_MS; const flipAt = s.pendingFlip ? s.flipAllowedAt : Math.max(s.flipAllowedAt, s.turnStartedAt + AWAY_FLIP_MS); return s.endsAt !== null ? Math.min(s.endsAt, flipAt) : flipAt; }, onTimeout() { return { type: 'tick' }; }, onLeave(s, player) { if (s.phase === 'ended' || !s.active.includes(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]); const scores: Record = {}; for (const r of f.ranking) scores[r.id] = POINTS[r.rank - 1] ?? 0; return { ranking: [...groups.entries()].sort((a, b) => a[0] - b[0]).map(([, ids]) => ids), scores, scoreText: Object.fromEntries(f.ranking.map((r) => [r.id, `카드 ${r.cards}장`])), summary: f.summary, reason: 'normal', }; }, legalActions(s, p) { if (s.phase === 'ended' || !s.order.includes(p)) return []; const out: A[] = []; if (p === s.turn) out.push({ type: 'tick' }); if (s.phase === 'playing' && s.active.includes(p)) { out.push({ type: 'ring', version: s.tableVersion }); if (p === s.turn) out.push({ type: 'flip' }); } return out.filter((a) => halliGalli.validate(s, p, a).ok); }, /** Every face-down or covered card (nobody may see them, including the owner — §8.3), as view keys. */ secretsOf(s, player) { const pile = s.faceUp[player] ?? []; return [...(s.decks[player] ?? []), ...pile.slice(0, -1), ...s.pot, ...s.removed].map(cardKey); }, };