From 28590df4290ec7d2df329294ef60abd8a63aaf05 Mon Sep 17 00:00:00 2001 From: EJClaw Date: Tue, 13 Oct 2026 13:15:18 +0900 Subject: [PATCH] =?UTF-8?q?=EC=9B=90=EC=B9=B4=EB=93=9C:=20=EC=B9=B4?= =?UTF-8?q?=EB=93=9C=20=EB=82=B4=EA=B8=B0=EC=99=80=20=EC=9B=90=EC=B9=B4?= =?UTF-8?q?=EB=93=9C=20=EC=99=B8=EC=B9=98=EA=B8=B0=20=EB=B6=84=EB=A6=AC(?= =?UTF-8?q?=EB=82=B4=EB=A9=B4=EC=84=9C=20=EC=99=B8=EC=B9=98=EA=B8=B0=20?= =?UTF-8?q?=EC=97=86=EC=95=B0),=20=EC=9E=A1=EA=B8=B0=20=EC=A0=84=20?= =?UTF-8?q?=EB=B3=B4=ED=98=B8=20=EC=8B=9C=EA=B0=84(1~3=EC=B4=88,=20?= =?UTF-8?q?=EA=B8=B0=EB=B3=B8=202=EC=B4=88),=20=EC=BB=B4=ED=93=A8=ED=84=B0?= =?UTF-8?q?=EB=8F=84=20=EC=82=AC=EB=9E=8C=EC=B2=98=EB=9F=BC=20=EB=8A=A6?= =?UTF-8?q?=EA=B2=8C=20=EC=99=B8=EC=B9=98=EA=B3=A0=20=EC=9E=A1=EA=B8=B0,?= =?UTF-8?q?=20=ED=95=9C=20=ED=84=B4=20=EC=8B=9C=EA=B0=84=20=EB=AC=B4?= =?UTF-8?q?=EC=A0=9C=ED=95=9C,=20=EC=9B=90=EC=B9=B4=EB=93=9C=20=EB=B3=B4?= =?UTF-8?q?=EB=84=88=EC=8A=A4=20=EC=98=B5=EC=85=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/server/src/rooms/bots.room.test.ts | 60 ++++++++++++++- apps/server/src/rooms/bots.ts | 79 ++++++++++++++++---- packages/games/src/bots/index.ts | 22 +++++- packages/games/src/bots/types.ts | 7 ++ packages/games/src/one-card/bot.test.ts | 55 ++++++++++++-- packages/games/src/one-card/bot.ts | 76 +++++++++++++++++-- packages/games/src/one-card/index.ts | 49 +++++++++--- packages/games/src/one-card/one-card.test.ts | 63 ++++++++++++++-- packages/games/src/one-card/types.ts | 24 ++++-- 9 files changed, 378 insertions(+), 57 deletions(-) diff --git a/apps/server/src/rooms/bots.room.test.ts b/apps/server/src/rooms/bots.room.test.ts index f2a5eeb..ff64173 100644 --- a/apps/server/src/rooms/bots.room.test.ts +++ b/apps/server/src/rooms/bots.room.test.ts @@ -1,7 +1,8 @@ /** Computer players in rooms (docs/06-lobby-rooms.md §12): seating rules, practice rooms, driving, records, restore. */ import { afterEach, describe, expect, test } from 'bun:test'; import { GAMES } from '@bg/games'; -import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES } from '@bg/games/bots'; +import { BOT_STRATEGIES, LIVE_BOT_STRATEGIES, botReactionAt } from '@bg/games/bots'; +import { classicDeck, type OneCardState } from '@bg/games/one-card'; import { BOT_GAMES, ClientMessage, botProfile, isBotId, type ServerMessage } from '@bg/shared'; import { openDb } from '../db'; import { botPace, defaultBotDelay, type BotDelayInput } from './bots'; @@ -338,6 +339,63 @@ describe('playing with bots', () => { }); }); +describe('원카드: computers call and catch on their own reaction clock', () => { + test('a computer that played down to one card calls at its reaction time; a person can catch only after 2 s', () => { + const h = harness(undefined, undefined, (input) => defaultBotDelay(input, () => 0.5)); + const room = h.manager.createPractice('A', 'one-card') as Room; + rooms.push(room); + const a = h.conn('A'); + room.join(a, 'player'); + expect(room.start('A')).toBeNull(); + const bot = bots(room)[0]!; + // Rig: the computer's turn with [♥9, ♣3] on ♥5; the person is next. + const s = room.game!.state as OneCardState; + const deck = classicDeck(1); + const take = (ids: string[]) => ids.map((id) => deck.find((c) => c.id === id)!); + s.hands = { A: take(['S4', 'S6', 'D8']), [bot]: take(['H9', 'C3']) }; + s.discard = take(['H5']); + s.drawPile = deck.filter((c) => !['S4', 'S6', 'D8', 'H9', 'C3', 'H5'].includes(c.id)); + s.current = bot; + s.phase = { kind: 'turn' }; + s.pendingAttack = 0; + s.declaredSuit = null; + s.oneCardWindow = null; + room.bots.cancel(); + room.scheduleTimer(); + for (let k = 0; k < 5 && !(room.game!.state as OneCardState).oneCardWindow; k++) { + h.clock.advance(Math.max(0, (room.bots.dueAt ?? h.clock.now()) - h.clock.now())); + room.bots.fire(); + } + let st = room.game!.state as OneCardState; + expect(st.oneCardWindow).toMatchObject({ player: bot, declared: false }); + expect(st.current).toBe('A'); + const opened = st.oneCardWindow!.openedAt!; + // Planned exactly at its reaction time (not squeezed by the turn clock, no thinking chat). + const at = botReactionAt(room.def, st, bot, room.profile(bot).level) as number; + expect(at).toBeGreaterThanOrEqual(opened + 500); + expect(room.bots.dueAt).toBe(at); + const rejects = () => a.msgs.filter((m) => m.t === 'reject').length; + const before = rejects(); + room.act('A', 101, { type: 'declareOneCard' }); + expect(rejects()).toBe(before + 1); + if (at > opened + 2000) { + // Slow this time: the person catches it first and the planned call is dropped. + h.clock.advance(opened + 2000 - h.clock.now()); + room.act('A', 102, { type: 'declareOneCard' }); + st = room.game!.state as OneCardState; + expect(st.oneCardWindow).toBeNull(); + expect(st.hands[bot]).toHaveLength(2); + expect(room.bots.dueAt).toBeNull(); + } else { + h.clock.advance(at - h.clock.now()); + room.bots.fire(); + st = room.game!.state as OneCardState; + expect(st.oneCardWindow).toMatchObject({ player: bot, declared: true }); + expect(st.hands[bot]).toHaveLength(1); + } + }); +}); + describe('practice rooms close once nobody is there', () => { function finishedPractice() { const h = harness(); diff --git a/apps/server/src/rooms/bots.ts b/apps/server/src/rooms/bots.ts index 1a60c07..dbb8a1a 100644 --- a/apps/server/src/rooms/bots.ts +++ b/apps/server/src/rooms/bots.ts @@ -5,7 +5,7 @@ */ import { secureRandom, type AnyGameDefinition } from '@bg/engine'; import { isBotId } from '@bg/shared'; -import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots'; +import { LIVE_BOT_STRATEGIES, botCandidates, botPace, botPersona, botReactionAt, decideBotAction, idLevel, type LiveBotStrategy } from '@bg/games/bots'; import type { BotBrain } from '../ai/brain'; @@ -39,6 +39,8 @@ export interface BotDelayInput { bot: string; /** The same bot just acted and is still on (e.g. yacht keep → roll): it already knows what it wants. */ followUp: boolean; + /** An out-of-turn reaction the game timed itself (원카드 외치기·잡기, `botReactionAt`): wait exactly this long. */ + reactMs?: number; } /** @@ -49,6 +51,7 @@ export interface BotDelayInput { */ export function defaultBotDelay(input: BotDelayInput, random: () => number = secureRandom): number { const { choices, withPeople, bot, followUp } = input; + if (input.reactMs !== undefined) return Math.max(0, Math.round(input.reactMs)); let ms = choices <= 1 ? 700 + random() * 600 : 1300 + 300 * Math.min(Math.log2(choices), 4) + random() * 1400; if (choices > 1 && !followUp && random() < 0.12) ms += 1000 + random() * 2000; ms *= botPace(bot); @@ -68,6 +71,8 @@ export class BotDriver { dueAt: number | null = null; /** Bot the planned action is for. */ private planned: string | null = null; + /** The planned action is that bot's out-of-turn reaction due at this time (not its normal move). */ + private plannedReact: number | null = null; /** Bot whose action is being played right now: if it is still on afterwards, its next move is a follow-up. */ private acting: string | null = null; /** Live games (마피아): when each computer looks at the game again, and its notes for the current game. */ @@ -87,26 +92,65 @@ export class BotDriver { /** Plans the next bot action if the game is waiting on a bot. Keeps an already planned one (the bot is "thinking"). */ schedule(): void { if (this.liveStrategy()) return this.scheduleLive(); - if (this.dueAt !== null || this.busy) return; + if (this.busy) return; + if (this.dueAt !== null) { + // A planned reaction the moment has passed for (someone called first): plan again; anything else stays planned. + if (this.plannedReact === null || this.reactionDue()?.bot === this.planned) return; + if (this.timer) clearTimeout(this.timer); + this.timer = null; + this.dueAt = null; + this.planned = null; + this.plannedReact = null; + } const next = this.next(); - if (!next) return; - // People can see it think: "생각 중…" until it moves. - if (this.room.brain?.enabled()) this.room.brain.thinking(next.bot, true); + const react = this.reactionDue(); + if (!next && !react) return; const now = this.room.now(); - let ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting }); - const deadline = this.room.deadline?.() ?? null; - if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE)); + let ms = Infinity; + if (next) { + ms = this.delay({ choices: next.choices, withPeople: next.withPeople, bot: next.bot, followUp: next.bot === this.acting }); + const deadline = this.room.deadline?.() ?? null; + if (deadline !== null) ms = Math.min(ms, Math.max(0, (deadline - now) * BOT_DEADLINE_SHARE)); + } + // An out-of-turn reaction (원카드!) comes first when it is due earlier; it is not squeezed by the turn clock, so a + // slow computer can really be late. + if (react) { + const rms = this.delay({ choices: 1, withPeople: true, bot: react.bot, followUp: false, reactMs: react.at - now }); + if (rms <= ms) { + this.dueAt = now + rms; + this.planned = react.bot; + this.plannedReact = react.at; + return this.arm(); + } + } + // People can see it think: "생각 중…" until it moves. + if (this.room.brain?.enabled()) this.room.brain.thinking(next!.bot, true); this.dueAt = now + ms; - this.planned = next.bot; + this.planned = next!.bot; + this.plannedReact = null; this.arm(); } + /** The earliest out-of-turn reaction of a computer that may act now (games with `BOT_REACTIONS`). */ + private reactionDue(): { bot: string; at: number } | null { + const g = this.room.game; + if (!g || g.finished || this.room.status !== 'playing') return null; + let best: { bot: string; at: number } | null = null; + for (const p of g.players) { + if (!isBotId(p)) continue; + const at = botReactionAt(this.room.def, g.state, p, this.room.profile?.(p).level ?? idLevel(p)); + if (typeof at === 'number' && (!best || at < best.at)) best = { bot: p, at }; + } + return best; + } + cancel(): void { if (this.timer) clearTimeout(this.timer); this.timer = null; if (this.planned) this.room.brain?.thinking(this.planned, false); this.dueAt = null; this.planned = null; + this.plannedReact = null; this.liveDue.clear(); } @@ -219,8 +263,11 @@ export class BotDriver { const active = def.activePlayers(g.state); const waiting = new Set([...active, ...(def.timeoutPlayers?.(g.state) ?? [])]); const withPeople = active.some((p) => !isBotId(p)); + const timed = new Set(def.timeoutPlayers?.(g.state) ?? active); for (const p of g.players) { if (!isBotId(p) || !waiting.has(p)) continue; + // Only there to react out of turn (원카드!): `reactionDue` times that, not the thinking time. + if (!timed.has(p) && botReactionAt(def, g.state, p, this.room.profile?.(p).level ?? idLevel(p)) !== null) continue; const choices = botCandidates(def, g.state, p).length; if (choices > 0) return { bot: p, choices, withPeople }; } @@ -239,13 +286,16 @@ export class BotDriver { return this.fireLive(live); } const planned = this.planned; + const wasReact = this.plannedReact !== null; this.dueAt = null; this.planned = null; - const next = this.next(); + this.plannedReact = null; + const react = wasReact ? this.reactionDue() : null; + const next = wasReact ? (react && react.bot === planned ? { bot: react.bot } : null) : this.next(); const g = this.room.game; - if (!next || !g) return; - // Another bot's turn came up meanwhile: give it its own thinking time. - if (next.bot !== planned) return this.schedule(); + if (!g) return; + // Another bot's turn came up meanwhile (or the reaction is moot): give it its own thinking time. + if (!next || next.bot !== planned) return this.schedule(); const def = this.room.def; const t0 = performance.now(); let action: unknown; @@ -258,7 +308,8 @@ export class BotDriver { const ms = performance.now() - t0; if (ms > BOT_SLOW_MS) this.room.log?.('warn', 'slow bot move', { game: def.id, ms: Math.round(ms) }); const brain = this.room.brain; - if (brain && action != null && brain.enabled()) { + // A reaction (원카드!) is a reflex: no chat before it. + if (brain && action != null && brain.enabled() && !wasReact) { // Like a person: maybe type something first (the model writes it; "입력 중…" while typing), then move. const bot = next.bot; this.busy = bot; diff --git a/packages/games/src/bots/index.ts b/packages/games/src/bots/index.ts index 5a04b50..3b8cae8 100644 --- a/packages/games/src/bots/index.ts +++ b/packages/games/src/bots/index.ts @@ -5,7 +5,7 @@ */ import { secureRandom, type AnyGameDefinition, type PlayerId } from '@bg/engine'; import type { BotLevel } from './persona'; -import type { BotStrategy, LiveBotStrategy } from './types'; +import type { BotReaction, BotStrategy, LiveBotStrategy } from './types'; import { pick, playable, randomPolicy } from './policy'; import { omokBot } from '../omok/bot'; import { othelloBot } from '../othello/bot'; @@ -16,7 +16,7 @@ import { seotdaBot } from '../seotda/bot'; import { pokerBot } from '../poker/bot'; import { yachtBot } from '../yacht/bot'; import { yutBot } from '../yut/bot'; -import { oneCardBot } from '../one-card/bot'; +import { oneCardBot, oneCardReaction } from '../one-card/bot'; import { rummikubBot } from '../rummikub/bot'; import { gostopBot } from '../gostop/bot'; import { bangBot } from '../bang/bot'; @@ -38,7 +38,7 @@ import { unoBot } from '../uno/bot'; import { liarBot } from '../liar/bot'; import { magicalAthleteBot } from '../magical-athlete/bot'; -export type { BotInput, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types'; +export type { BotInput, BotReaction, BotStrategy, LiveBotDecision, LiveBotInput, LiveBotStrategy } from './types'; export { botDraw, botPace, botPersona, hash01, idLevel, type BotLevel, type BotPersona } from './persona'; export { botPlay } from './policy'; @@ -73,6 +73,22 @@ export const BOT_STRATEGIES: Record = { 'magical-athlete': magicalAthleteBot, }; +/** Games whose computers also react out of turn on their own clock (원카드 외치기·잡기). */ +export const BOT_REACTIONS: Record = { + 'one-card': oneCardReaction, +}; + +/** When `me` reacts out of turn (server time), 'ignore', or null (nothing to react to / the game has no reactions). */ +export function botReactionAt(def: AnyGameDefinition, state: unknown, me: PlayerId, level?: BotLevel): number | 'ignore' | null { + const react = BOT_REACTIONS[def.id]; + if (!react) return null; + try { + return react({ me, view: def.view(state, me), level }); + } catch { + return null; + } +} + /** The bot's legal actions as the game lists them (validated lazily: only the chosen one, see below). */ export function botCandidates(def: AnyGameDefinition, state: unknown, me: PlayerId): unknown[] { return def.legalActions ? def.legalActions(state, me) : []; diff --git a/packages/games/src/bots/types.ts b/packages/games/src/bots/types.ts index 36ea238..aa73684 100644 --- a/packages/games/src/bots/types.ts +++ b/packages/games/src/bots/types.ts @@ -56,3 +56,10 @@ export interface LiveBotDecision { } export type LiveBotStrategy = (input: LiveBotInput) => LiveBotDecision; + +/** + * Out-of-turn reactions (원카드 외치기·잡기): when (server time, ms) this computer reacts to what is on its screen now, + * 'ignore' when it doesn't notice (left alone unless the game waits on it), or null when there is nothing to react to + * (normal thinking time). Must give the same answer every time it is asked about the same moment. + */ +export type BotReaction = (input: { me: PlayerId; view: V; level?: import('./persona').BotLevel }) => number | 'ignore' | null; diff --git a/packages/games/src/one-card/bot.test.ts b/packages/games/src/one-card/bot.test.ts index f7e5ed2..25d540e 100644 --- a/packages/games/src/one-card/bot.test.ts +++ b/packages/games/src/one-card/bot.test.ts @@ -2,6 +2,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 { callDelayMs, catchDelayMs, noticesMissedCall, oneCardReaction } from './bot'; import { classicDeck, oneCard, unoDeck, type Card, type OneCardOptions, type OneCardState } from './index'; const ALL: Card[] = [...classicDeck(2), ...unoDeck()]; @@ -25,7 +26,7 @@ function rig(s: OneCardState, hands: Record, discard: string[] return s; } -const decide = (s: OneCardState, p = 'A') => decideBotAction(oneCard, s, p, { now: 0, random: () => 0.5 }) as Record; +const decide = (s: OneCardState, p = 'A', now = 0, level?: number) => decideBotAction(oneCard, s, p, { now, random: () => 0.5, level }) as Record; describe('one-card bot', () => { test('counters an attack instead of drawing', () => { @@ -38,9 +39,12 @@ describe('one-card bot', () => { expect(decide(s)).toEqual({ type: 'play', cardIds: ['H9'] }); }); - test('declares one-card, getting rid of a joker that may not be the last card', () => { - const s = rig(make(), { A: ['H9', 'JB'], B: ['C4', 'C5'], C: ['D9', 'D10'] }, ['H5']); - expect(decide(s)).toEqual({ type: 'play', cardIds: ['JB'], declareOneCard: true }); + test('plays the joker that may not be the last card, then calls "원카드!" as its own action', () => { + let s = rig(make(), { A: ['H9', 'JB'], B: ['C4', 'C5'], C: ['D9', 'D10'] }, ['H5']); + expect(decide(s)).toEqual({ type: 'play', cardIds: ['JB'] }); + s = oneCard.apply(s, 'A', { type: 'play', cardIds: ['JB'] }, { rng: SeededRng.fromSeed(seedN(2)), now: 10 }).state; + expect(oneCard.activePlayers(s)).toContain('A'); + expect(decide(s, 'A', 10)).toEqual({ type: 'declareOneCard' }); }); test('a 7 changes to the suit it holds most of', () => { @@ -49,11 +53,50 @@ describe('one-card bot', () => { expect(decide(s)).toMatchObject({ type: 'play', cardIds: ['H7'], chooseSuit: 'C' }); }); - test("catches another player's missed one-card call", () => { + test("catches another player's missed call once the protection time is over (only if it noticed)", () => { let s = rig(make(), { A: ['H9', 'C3'], B: ['C4', 'C5', 'S6'], C: ['D9', 'D10'] }, ['H5']); s = oneCard.apply(s, 'A', { type: 'play', cardIds: ['H9'] }, { rng: SeededRng.fromSeed(seedN(2)), now: 1 }).state; expect(s.oneCardWindow).toMatchObject({ player: 'A', declared: false }); - expect(decide(s, 'C')).toEqual({ type: 'declareOneCard' }); + // A window seq this computer notices (and one it misses) at level 30 (보통). + const seqs = Array.from({ length: 60 }, (_, i) => i + 1); + const seen = seqs.find((q) => noticesMissedCall('B', { seq: q }, 30))!; + const missed = seqs.find((q) => !noticesMissedCall('B', { seq: q }, 30))!; + s.oneCardWindow!.openedSeq = seen; + // B's own turn: before 2 s it can't catch yet and just draws; after, it catches first. + expect(decide(s, 'B', 500, 30)).toEqual({ type: 'draw' }); + expect(decide(s, 'B', 2001, 30)).toEqual({ type: 'declareOneCard' }); + s.oneCardWindow!.openedSeq = missed; + expect(decide(s, 'B', 2001, 30)).toEqual({ type: 'draw' }); + }); + + test('reaction clock: own call by level (sometimes late), catches only after the protection time, misses by level', () => { + let s = rig(make(), { A: ['H9', 'C3'], B: ['C4', 'C5', 'S6'], C: ['D9', 'D10'] }, ['H5']); + s = oneCard.apply(s, 'A', { type: 'play', cardIds: ['H9'] }, { rng: SeededRng.fromSeed(seedN(2)), now: 1000 }).state; + const react = (p: string, level?: number) => oneCardReaction({ me: p, view: oneCard.view(s, p), level }); + const w = { seq: s.oneCardWindow!.openedSeq }; + expect(react('A', 50)).toBe(Math.round(1000 + callDelayMs('A', w, 50))); + const c = react('C', 50); + expect(c === 'ignore' || (typeof c === 'number' && c >= 3000)).toBe(true); + if (typeof c === 'number') expect(c).toBe(Math.round(3000 + catchDelayMs('C', w, 50))); + // Same answer every time (the driver asks again when it fires). + expect(react('C', 50)).toBe(c); + // Statistics over many windows. + const N = 2000; + const avg = (f: (q: number) => number) => Array.from({ length: N }, (_, q) => f(q)).reduce((a, b) => a + b, 0) / N; + const late = (level: number) => avg((q) => (callDelayMs('bot:1:x', { seq: q }, level) > 2000 ? 1 : 0)); + expect(late(55)).toBeGreaterThan(0.03); + expect(late(55)).toBeLessThan(0.15); + expect(late(30)).toBeGreaterThan(0.25); + expect(late(10)).toBeGreaterThan(0.6); + const notice = (level: number) => avg((q) => (noticesMissedCall('bot:2:y', { seq: q }, level) ? 1 : 0)); + expect(notice(55)).toBeGreaterThan(0.85); + expect(notice(30)).toBeGreaterThan(0.6); + expect(notice(30)).toBeLessThan(0.8); + expect(notice(10)).toBeLessThan(0.55); + // Nothing to react to once A has called. + s = oneCard.apply(s, 'A', { type: 'declareOneCard' }, { rng: SeededRng.fromSeed(seedN(3)), now: 1500 }).state; + expect(react('A')).toBeNull(); + expect(react('C')).toBeNull(); }); test('colour cards: a wild picks the colour it holds most of', () => { diff --git a/packages/games/src/one-card/bot.ts b/packages/games/src/one-card/bot.ts index bf2161c..119d73d 100644 --- a/packages/games/src/one-card/bot.ts +++ b/packages/games/src/one-card/bot.ts @@ -1,9 +1,12 @@ /** - * 원카드 / 색깔 카드 computer player: always declare (and catch others' missed) one-card, counter attacks when it - * can, otherwise play a matching card while keeping jokers / 7s / wilds for later; attack when the next player is - * close to going out; a changed suit or colour is the one it holds most of. + * 원카드 / 색깔 카드 computer player: calls its own "원카드!" and catches others' missed calls (how fast, and whether it + * notices at all, depends on its level: `oneCardReaction`), counters attacks when it can, otherwise plays a matching + * card while keeping jokers / 7s / wilds for later; attacks when the next player is close to going out; a changed + * suit or colour is the one it holds most of. */ -import type { BotStrategy } from '../bots/types'; +import type { BotReaction, BotStrategy } from '../bots/types'; +import type { BotLevel } from '../bots/persona'; +import { hash01 } from '../bots/persona'; import { best, pick, playable, typeOf } from '../bots/policy'; import { COLORS, SUITS, colorOf, isStd, type Card, type Color, type Suit } from './cards'; import { attackOf, forbiddenAsLast } from './rules'; @@ -27,15 +30,72 @@ function majority(keys: K[], all: K[], random: () => number): return best(all, (k) => count.get(k) ?? 0, random); } -export const oneCardBot: BotStrategy = ({ view, legal, random }) => { +// ---------------------------------------------------------------- 원카드! reaction (docs/games/one-card.md §5.3) + +type Window = NonNullable; +const band = (level: BotLevel | undefined): 'hard' | 'normal' | 'easy' => (level === undefined || level > 40 ? 'hard' : level > 20 ? 'normal' : 'easy'); + +/** + * How long after the window opened this computer calls its own "원카드!" (ms). Mostly quick, but like a person it is + * sometimes slow: 쉬움 1.4~4 s (one in four times 5~9 s: forgot), 보통 0.9~2.8 s (sometimes 3~5 s), 어려움 0.5~1.5 s + * (now and then 1.8~3.2 s). Fixed per window (same answer every time it is asked). + */ +export function callDelayMs(me: string, w: Pick, level: BotLevel | undefined): number { + const r = hash01(me, w.seq, 'call'); + const slip = hash01(me, w.seq, 'slip'); + switch (band(level)) { + case 'hard': + return slip < 0.08 ? 1800 + r * 1400 : 500 + r * 1000; + case 'normal': + return slip < 0.12 ? 3000 + r * 2000 : 900 + r * 1900; + case 'easy': + return slip < 0.25 ? 5000 + r * 4000 : 1400 + r * 2600; + } +} + +/** Does this computer notice that someone forgot to call (어려움 90%, 보통 70%, 쉬움 45%)? Fixed per window. */ +export function noticesMissedCall(me: string, w: Pick, level: BotLevel | undefined): boolean { + const chance = { hard: 0.9, normal: 0.7, easy: 0.45 }[band(level)]; + return hash01(me, w.seq, 'notice') < chance; +} + +/** How long after the protection time it presses to catch (어려움 0.2~1.2 s, 보통 0.5~2.5 s, 쉬움 1~4 s). */ +export function catchDelayMs(me: string, w: Pick, level: BotLevel | undefined): number { + const r = hash01(me, w.seq, 'catch'); + switch (band(level)) { + case 'hard': + return 200 + r * 1000; + case 'normal': + return 500 + r * 2000; + case 'easy': + return 1000 + r * 3000; + } +} + +/** + * The bot driver asks this for every computer: when (server time) it reacts to an open "원카드!" window, 'ignore' when + * it doesn't notice a missed call, null when there is nothing to react to. + */ +export const oneCardReaction: BotReaction = ({ me, view, level }) => { + const w = view.oneCardWindow; + if (!w || w.declared || !view.my?.canDeclare) return null; + if (w.player === me) return Math.round(w.openedAt + callDelayMs(me, w, level)); + if (!noticesMissedCall(me, w, level)) return 'ignore'; + return Math.round(Math.max(w.catchFrom, w.openedAt) + catchDelayMs(me, w, level)); +}; + +export const oneCardBot: BotStrategy = ({ me, view, legal, random, level }) => { const types = new Set(legal.map(typeOf)); if (types.has('ready')) return { type: 'ready' }; - // My own one-card call, or catching someone who forgot to call it. - if (types.has('declareOneCard')) return { type: 'declareOneCard' }; + // My own call first; a catch only when it noticed (before the protection time ends the server refuses it and the + // bot just plays on). Returned as the listed action so a refused one is dropped from the retry. + const call = legal.find((a) => a.type === 'declareOneCard'); + const w = view.oneCardWindow; + if (call && w && (w.player === me || noticesMissedCall(me, w, level))) return call; const hand = view.my?.hand ?? []; const byId = new Map(hand.map((c) => [c.id, c])); - const plays = (legal.filter((a) => a.type === 'play') as PlayAction[]).filter((a) => a.declareOneCard || hand.length - a.cardIds.length !== 1); + const plays = legal.filter((a) => a.type === 'play') as PlayAction[]; const o = view.options; const uno = view.mode === 'uno-style'; diff --git a/packages/games/src/one-card/index.ts b/packages/games/src/one-card/index.ts index bd49d84..c5d40db 100644 --- a/packages/games/src/one-card/index.ts +++ b/packages/games/src/one-card/index.ts @@ -501,8 +501,9 @@ function playCards(s: OneCardState, p: PlayerId, a: PlayAction, ctx: Ctx): void } if (handLeft === 1) { - const declared = o.autoDeclare || !!a.declareOneCard; - s.oneCardWindow = { player: p, declared, openedSeq: s.seq }; + // Calling is its own action now (§5.3): only the autoDeclare option calls together with the play. + const declared = o.autoDeclare; + s.oneCardWindow = { player: p, declared, openedSeq: s.seq, openedAt: ctx.now }; ctx.events.push({ type: 'oneCardOpen', player: p, declared }); if (declared) log(s, { t: 'declare', p }); } @@ -594,6 +595,7 @@ function declareOneCard(s: OneCardState, actor: PlayerId, ctx: Ctx): void { w.declared = true; ctx.events.push({ type: 'oneCardDeclared', player: actor }); log(s, { t: 'declare', p: actor }); + if (s.options.oneCardBonus) bonusDraws(s, actor, ctx); return; } const target = w.player; @@ -605,6 +607,24 @@ function declareOneCard(s: OneCardState, actor: PlayerId, ctx: Ctx): void { if (s.status[target] !== 'playing') repairAfterRemoval(s, target, ctx); } +/** oneCardBonus: everyone else still in the round takes 1 card, in turn order from the caller. */ +function bonusDraws(s: OneCardState, caller: PlayerId, ctx: Ctx): void { + const order: PlayerId[] = []; + for (let k = 1, i = s.seats.indexOf(caller); k < s.seats.length; k++) { + const p = s.seats[(((i + k * s.direction) % s.seats.length) + s.seats.length) % s.seats.length]!; + if (s.status[p] === 'playing') order.push(p); + } + for (const p of order) { + if (s.phase.kind === 'finished' || s.phase.kind === 'roundEnd') return; + if (s.status[p] !== 'playing') continue; + drawCards(s, p, 1, 'bonus', ctx); + if (s.status[p] !== 'playing') repairAfterRemoval(s, p, ctx); + } +} + +/** When others may catch the window's owner (server time). */ +export const catchFrom = (s: OneCardState): number => (s.oneCardWindow?.openedAt ?? 0) + s.options.oneCardGrace * 1000; + function leave(s: OneCardState, p: PlayerId, ctx: Ctx): void { s.leftOrder.push(p); ctx.events.push({ type: 'left', player: p }); @@ -721,9 +741,11 @@ function deadlineMs(s: OneCardState): number | null { switch (s.phase.kind) { case 'turn': case 'afterDraw': - return s.away[s.current] ? AWAY_MS : s.options.turnSeconds * 1000; + if (s.away[s.current]) return AWAY_MS; + return s.options.turnSeconds === null ? null : s.options.turnSeconds * 1000; case 'wild4Response': - return s.away[s.phase.target] ? AWAY_MS : WILD4_MS; + if (s.away[s.phase.target]) return AWAY_MS; + return s.options.turnSeconds === null ? null : WILD4_MS; case 'roundEnd': return ROUND_END_MS; case 'finished': @@ -731,14 +753,13 @@ function deadlineMs(s: OneCardState): number | null { } } -/** All play actions for `p` built from a set of card ids (suits / colours / declare variants). */ +/** All play actions for `p` built from a set of card ids (suit / colour variants). */ function playVariants(s: OneCardState, p: PlayerId, ids: string[]): PlayAction[] { const hand = s.hands[p]!; const first = hand.find((c) => c.id === ids[0])!; let out: PlayAction[] = [{ type: 'play', cardIds: ids }]; if (isStd(first) && first.rank === 7) out = SUITS.map((chooseSuit: Suit) => ({ type: 'play', cardIds: ids, chooseSuit })); if (isWildKind(first)) out = COLORS.map((chooseColor: Color) => ({ type: 'play', cardIds: ids, chooseColor })); - if (hand.length - ids.length === 1) out = out.flatMap((x) => [x, { ...x, declareOneCard: true }]); return out; } @@ -805,7 +826,7 @@ export const oneCard: GameDefinition { test('lastCardRule = joker: [조커, ♥5] → ♥5 leaves the joker, which may not be played as the last card', () => { let s = rig(make({}, ['A', 'B']), { hands: { A: ['JB', 'H5'], B: ['H9', 'S9', 'C9'] }, discard: ['H8'] }); - s = play(s, 'A', ['H5'], { declareOneCard: true }); + s = play(s, 'A', ['H5']); + s = act(s, 'A', { type: 'declareOneCard' }); s = play(s, 'B', ['H9']); expect(reject(s, 'A', { type: 'play', cardIds: ['JB'] })).toBe('마지막 카드로 조커는 낼 수 없어요.'); expect(oneCard.view(s, 'A').my!.legalCardIds).toEqual([]); @@ -317,7 +318,9 @@ describe('원카드 선언 (§5.3)', () => { test('caught: B presses first → A takes the penalty (1장) and the window closes', () => { let s = play(setupOne(), 'A', ['H5']); expect(s.oneCardWindow).toMatchObject({ player: 'A', declared: false }); - expect(oneCard.activePlayers(s).sort()).toEqual(['A', 'B', 'C']); + // The game waits on A's call (and B's turn); catching is open to anyone but never awaited. + expect(oneCard.activePlayers(s).sort()).toEqual(['A', 'B']); + expect(oneCard.legalActions!(s, 'C')).toEqual([{ type: 'declareOneCard' }]); const out = actE(s, 'B', { type: 'declareOneCard' }); s = out.state; expect(s.hands.A).toHaveLength(2); @@ -335,13 +338,48 @@ describe('원카드 선언 (§5.3)', () => { expect(JSON.stringify(s)).toBe(before); }); - test('play with declareOneCard: true cannot be caught; autoDeclare does it for everyone', () => { - const s = play(setupOne(), 'A', ['H5'], { declareOneCard: true }); - expect(reject(s, 'B', { type: 'declareOneCard' })).not.toBeNull(); + test('calling is its own action: a play never calls (an old client flag is dropped); only autoDeclare does', () => { + const parsed = oneCard.actionSchema.parse({ type: 'play', cardIds: ['H5'], declareOneCard: true }) as Record; + expect(parsed.declareOneCard).toBeUndefined(); + const s = act(setupOne(), 'A', parsed as OneCardAction); + expect(s.oneCardWindow).toMatchObject({ player: 'A', declared: false }); + expect(reject(s, 'B', { type: 'declareOneCard' })).toBeNull(); + // No "play and call" variants for the bots / the random playouts either. + const two = setupOne(); + expect(oneCard.legalActions!(two, 'A').some((a) => 'declareOneCard' in a)).toBe(false); + expect(reject(two, 'A', { type: 'declareOneCard' })).toBe('지금은 원카드를 외칠 때가 아니에요.'); const auto = play(setupOne({ autoDeclare: true }), 'A', ['H5']); expect(auto.oneCardWindow?.declared).toBe(true); }); + test('protection time: only the owner may call during the first oneCardGrace seconds, then anyone may catch', () => { + const s = play(setupOne(), 'A', ['H5']); + const opened = s.oneCardWindow!.openedAt!; + expect(opened).toBe(clock); + const at = (p: string, now: number) => { + const v = oneCard.validate(s, p, { type: 'declareOneCard' }, { now }); + return v.ok ? null : v.reason; + }; + expect(at('A', opened)).toBeNull(); + expect(at('B', opened + 1999)).toBe('아직 잡을 수 없어요. 1장 남은 사람이 먼저 외칠 시간이에요.'); + expect(at('B', opened + 2000)).toBeNull(); + expect(oneCard.view(s, 'B').oneCardWindow).toEqual({ player: 'A', declared: false, seq: s.seq, openedAt: opened, catchFrom: opened + 2000 }); + const quick = play(setupOne({ oneCardGrace: 1 }), 'A', ['H5']); + expect(oneCard.validate(quick, 'C', { type: 'declareOneCard' }, { now: quick.oneCardWindow!.openedAt! + 1000 }).ok).toBe(true); + }); + + test('oneCardBonus: calling first makes everyone else take 1 card', () => { + let s = play(setupOne({ oneCardBonus: true }), 'A', ['H5']); + const out = actE(s, 'A', { type: 'declareOneCard' }); + s = out.state; + expect([s.hands.A!.length, s.hands.B!.length, s.hands.C!.length]).toEqual([1, 3, 3]); + expect(s.log.filter((e) => e.t === 'draw' && e.why === 'bonus').map((e) => ('p' in e ? e.p : ''))).toEqual(['B', 'C']); + expect(s.current).toBe('B'); + // Off by default. + const plain = act(play(setupOne(), 'A', ['H5']), 'A', { type: 'declareOneCard' }); + expect(plain.hands.B).toHaveLength(2); + }); + test('classic window lifetime and the colour-card rule (closes on the next player’s first action)', () => { let s = rig(make({}, ['A', 'B', 'C']), { hands: { A: ['H5', 'C9'], B: ['H9', 'S10', 'S4'], C: ['H10', 'D10', 'S3'] }, discard: ['H8'] }); s = play(s, 'A', ['H5']); @@ -591,6 +629,17 @@ describe('색깔 카드 (§5.6)', () => { // ---------------------------------------------------------------- timers, leaving describe('시간 초과, 연결 끊김, 나가기 (§8.5)', () => { + test('turnSeconds null (무제한): no turn clock, no +4 clock; away players still get 5 s; the round pause stays', () => { + const s = rig(make({ turnSeconds: null }), { hands: { A: ['H9', 'C4'], B: ['S9'] }, discard: ['H5'] }); + expect(oneCard.deadline!(s)).toBeNull(); + expect(oneCard.view(s, 'A').deadlineTotalMs).toBe(0); + s.away.A = true; + expect(oneCard.deadline!(s)).toBe(s.turnStartedAt + 5000); + let u = rig(make({ mode: 'uno-style', unoWild4Rule: 'challenge', turnSeconds: null }), { hands: { A: ['F1', 'G1a'], B: ['Y1a'], C: ['Y3a'] }, discard: ['R5a'] }); + u = play(u, 'A', ['F1'], { chooseColor: 'G' }); + expect(oneCard.deadline!(u)).toBeNull(); + }); + test('timeout while attacked → takes the attack; afterDraw → pass; wild4Response → accept', () => { let s = rig(make(), { hands: { A: ['H2', 'C4'], B: ['S2', 'S9'], C: ['D9'] }, discard: ['H5'] }); s = play(s, 'A', ['H2']); @@ -807,7 +856,7 @@ function fastPlayout(players: PlayerId[], options: OneCardOptions, seed: RngStat const PRESETS: Record<'classic' | 'uno-style', Partial[]> = { classic: [ {}, - { voluntaryDraw: false, multiPlay: true }, + { voluntaryDraw: false, multiPlay: true, oneCardBonus: true, turnSeconds: null }, { kEffect: 'skip-two', qInTwoPlayer: 'as-skip', lastCardRule: 'special', afterJoker: 'any', threeDefense: 'off' }, { endCondition: 'last-standing', bankruptLimit: 15, handSize: 5, deckCount: 2, playAfterDraw: 'on' }, { multiPlay: true, lastCardRule: 'attack', bankruptLimit: 'none', autoDeclare: true, attackColorJoker: 13, attackSpadeA: 10 }, @@ -815,7 +864,7 @@ const PRESETS: Record<'classic' | 'uno-style', Partial[]> = { 'uno-style': [ {}, { voluntaryDraw: false, unoWild4Rule: 'challenge' }, - { unoStacking: true, unoWild4Rule: 'challenge', bankruptLimit: 25, voluntaryDraw: false }, + { unoStacking: true, unoWild4Rule: 'challenge', bankruptLimit: 25, voluntaryDraw: false, oneCardBonus: true, oneCardGrace: 1 }, { endCondition: 'last-standing', unoWild4Rule: 'free', bankruptLimit: 18, playAfterDraw: 'off', handSize: 5 }, { unoTargetScore: 200, voluntaryDraw: false, bankruptLimit: 20, autoDeclare: true }, ], diff --git a/packages/games/src/one-card/types.ts b/packages/games/src/one-card/types.ts index 31ad55f..480b1cd 100644 --- a/packages/games/src/one-card/types.ts +++ b/packages/games/src/one-card/types.ts @@ -3,7 +3,7 @@ import { z } from 'zod'; import type { PlayerId } from '@bg/engine'; import type { Card, Color, Suit } from './cards'; -const lit = (...vals: T[]) => +const lit = (...vals: T[]) => z.union(vals.map((v) => z.literal(v)) as unknown as [z.ZodLiteral, z.ZodLiteral, ...z.ZodLiteral[]]); export const oneCardOptionsSchema = z.object({ @@ -47,7 +47,11 @@ export const oneCardOptionsSchema = z.object({ oneCardPenalty: lit<'auto' | 1 | 2 | 3>('auto', 1, 2, 3) .default('auto') .meta({ title: '원카드를 못 외치고 잡히면 먹는 장수', labels: { auto: '모드 기본(원카드 1장, 색깔 카드 2장)', 1: '1장', 2: '2장', 3: '3장' } }), - autoDeclare: z.boolean().default(false).meta({ title: '1장 남으면 자동으로 원카드 외치기' }), + autoDeclare: z.boolean().default(false).meta({ title: '1장 남으면 자동으로 원카드 외치기(잡기 없음, 초보용)' }), + oneCardGrace: lit(1, 2, 3) + .default(2) + .meta({ title: '원카드 잡기 전 보호 시간(1장 남은 사람만 외칠 수 있는 시간)', labels: { 1: '1초', 2: '2초', 3: '3초' } }), + oneCardBonus: z.boolean().default(false).meta({ title: '원카드를 먼저 외치면 다른 사람이 1장씩 먹기' }), bankruptLimit: lit<'auto' | 15 | 18 | 20 | 25 | 'none'>('auto', 15, 18, 20, 25, 'none') .default('auto') .meta({ @@ -62,9 +66,9 @@ export const oneCardOptionsSchema = z.object({ .enum(['first-out', 'last-standing']) .default('first-out') .meta({ title: '끝나는 때', labels: { 'first-out': '1등이 나오면', 'last-standing': '꼴찌가 정해질 때까지' } }), - turnSeconds: lit(10, 15, 20, 30, 60) + turnSeconds: lit(10, 15, 20, 30, 60, null) .default(20) - .meta({ title: '한 턴 제한 시간', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초' } }), + .meta({ title: '한 턴 제한 시간', labels: { 10: '10초', 15: '15초', 20: '20초', 30: '30초', 60: '60초', null: '무제한' } }), unoStacking: z.boolean().default(false).meta({ title: '(색깔 카드) +2·+4 받아치기' }), unoWild4Rule: z .enum(['strict', 'challenge', 'free']) @@ -86,7 +90,6 @@ export const oneCardActionSchema = z.discriminatedUnion('type', [ cardIds: z.array(z.string().max(8)).min(1).max(8), chooseSuit: z.enum(['S', 'H', 'D', 'C']).optional(), chooseColor: z.enum(['R', 'Y', 'G', 'B']).optional(), - declareOneCard: z.boolean().optional(), }), z.object({ type: z.literal('draw') }), z.object({ type: z.literal('pass') }), @@ -113,7 +116,7 @@ export type Phase = export type LogEntry = /** Played cards without ids: ids are reused after a reshuffle and must not hint at hidden cards. */ | { seq: number; t: 'play'; p: PlayerId; cards: CardFace[]; suit?: Suit; color?: Color } - | { seq: number; t: 'draw'; p: PlayerId; n: number; why: 'normal' | 'attack' | 'penalty' | 'draw2' | 'wild4' | 'challenge' | 'start' } + | { seq: number; t: 'draw'; p: PlayerId; n: number; why: 'normal' | 'attack' | 'penalty' | 'bonus' | 'draw2' | 'wild4' | 'challenge' | 'start' } | { seq: number; t: 'pass'; p: PlayerId } | { seq: number; t: 'blocked'; p: PlayerId } | { seq: number; t: 'declare'; p: PlayerId } @@ -171,7 +174,11 @@ export interface OneCardState { phase: Phase; pendingAttack: number; extraTurn: boolean; - oneCardWindow: { player: PlayerId; declared: boolean; openedSeq: number } | null; + /** + * "원카드!" window (§5.3): opens when a play leaves exactly one card. `openedAt` = server time it opened; others may + * catch only after the protection time (`oneCardGrace`). Missing `openedAt` (older saves) = catchable at once. + */ + oneCardWindow: { player: PlayerId; declared: boolean; openedSeq: number; openedAt?: number } | null; status: Record; finishOrder: PlayerId[]; bankruptOrder: PlayerId[]; @@ -234,7 +241,8 @@ export interface OneCardView { pendingAttack: number; drawPileCount: number; discardCount: number; - oneCardWindow: { player: PlayerId; declared: boolean } | null; + /** `catchFrom`: server time from which other players may catch (the owner may call at once). `seq` names the window. */ + oneCardWindow: { player: PlayerId; declared: boolean; seq: number; openedAt: number; catchFrom: number } | null; wild4: { by: PlayerId; target: PlayerId } | null; my: { hand: Card[];